From e11606890f3306183fd80af4495bd6f0349dabc2 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 07:55:52 +0200 Subject: [PATCH 01/11] docs: playback buffer architecture design Co-Authored-By: Claude Fable 5 --- ...-30-playback-buffer-architecture-design.md | 147 ++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md diff --git a/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md b/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md new file mode 100644 index 0000000000..2b93b4d5e0 --- /dev/null +++ b/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md @@ -0,0 +1,147 @@ +# Playback Buffer Architecture — Design + +**Date:** 2026-07-30 +**Status:** Approved in design conversation; this document is its record +**Scope:** `android-shared` playback buffering (phone + TV share it) + +## Why + +Two problems, one of which masks the other. + +**1. The buffer fills, the socket idles, the proxy kills the connection.** +`DefaultLoadControl` loads until `maxBufferMs`, then stops reading the socket +until the buffer drains below `minBufferMs`. The connection therefore sits idle +for roughly `max − min` of playback time. Today's hardcoded policy is +`min 50s / max 120s` — a **70-second idle window** against a proxy +`send_timeout` that defaults to 60s. The connection is dropped whenever the +buffer fills on a long direct-play file, and the client only discovers it when +it comes back for more data. This is arithmetic, not a race. + +**2. The byte cap silently overrides the time target.** +`prioritizeTimeOverSizeThresholds` is `false`, so whichever limit binds first +wins. With device-class caps of 48/96/160 MiB, a 40–80 Mbps remux gets roughly +10–34 seconds of buffer while the configuration claims 50. Nothing surfaces the +discrepancy. + +These interact: the premature byte cap has been *shortening the idle window*, +partly hiding problem 1. Raising the caps without fixing the window would make +dropped connections dramatically more common. + +Additionally, the three-mode `PlaybackBufferMode` enum is dead code — +`SiloPlayerFactory` hardcodes `Balanced`, so `QuickStart`, `SmoothPlayback` and +the `fromWire` parsing are unreachable. + +## Decisions + +Taken in conversation with Jim: + +- **Automatic, from measured conditions.** No user setting, no server-driven + wire value. The player derives the policy from what it can observe. +- **Start fast, then deepen.** Begin on a small cushion and fill in the + background; users judge a player on time-to-first-frame. +- **Depth and idle window are independent.** Extend the buffer as far as memory + and throughput allow, while holding the idle window fixed. + +## Architecture + +### The invariant + +`maxBufferMs` stops being a free parameter: + +``` +maxBufferMs = minBufferMs + MAX_LOAD_IDLE_MS +``` + +`MAX_LOAD_IDLE_MS = 30_000`, chosen to sit well under the assumed 60s upstream +proxy `send_timeout`. The assumed timeout is a named constant with its +reasoning beside it, so a deployment behind a 30s proxy has an obvious dial +rather than a mystery. + +This makes the failure structurally unrepresentable: no matter how deep the +buffer grows, the socket cannot idle long enough to be dropped. Depth is +`minBufferMs`; the window is the gap. + +### Depth is governed by memory and throughput + +Depth grows toward a ceiling, bounded by: + +- **Memory budget** — bytes needed = target seconds × observed bitrate, + clamped to a fraction of the app heap. When the budget cannot fund the target + seconds, the *target seconds are reduced explicitly* to what fits, never + below a **20s floor**. `maxBufferMs` follows `min` down, so the idle window + only ever shrinks. +- **Delivery throughput** — the bandwidth meter already reports delivery rate. + Delivery ≫ media bitrate means the source can outrun playback (direct file, + or a fast/GPU transcode) and depth may extend. Delivery ≈ bitrate means the + producer is realtime-bound and the buffer cannot grow regardless of target. +- **Ceiling: 180s.** Beyond this we are mostly pre-fetching content the user may + seek away from — wasted bandwidth, and wasted allowance on mobile data. + +### Transcode needs no special case + +Investigated and deliberately dropped. Two findings: + +1. A deep target does **not** make the client wait on the encoder — ExoPlayer + simply receives more slowly. If the encoder is realtime-bound the buffer + never reaches `max`, so the socket never idles and problem 1 cannot occur on + transcoded streams at all. A deep target on a slow encoder is inert. +2. The **server already bounds it**. `TranscodeThrottler` + (`internal/playback/throttle.go` in silo-server) pauses ffmpeg once it is + `transcode_throttle_seconds` ahead of the client's fetch position — default + **300s**, clamped to a 60s minimum, gated by `enable_transcode_throttle`. + That is the real ceiling for transcoded content, and it is the server's to + enforce. + +So throughput-driven depth handles transcode without the client knowing what it +is talking to: a GPU-transcoding server behaves like direct play, a CPU-bound +one degrades gracefully, and nothing breaks when stream nodes are enabled later. + +Note that HLS delivery (remux or transcode) fetches discrete segments, so each +request is short-lived and the idle-window problem does not arise there. The +invariant is harmless in that case and load-bearing for `ORIGINAL_HTTP` +progressive direct play — which is exactly where the reported drops occur. + +### Numbers + +| | Start | After stall | Depth (min) | Idle window | +|---|---|---|---|---| +| All delivery | 2s | 5s | 20s floor → 180s ceiling, memory/throughput governed | 30s | + +Start drops 3s → 2s. Stall recovery drops 10s → 5s: after a stall the user is +watching a spinner, and ten seconds is a long time to withhold the picture for +insurance. + +## Components + +Three units, each independently testable: + +- **`PlaybackBufferPolicy`** — the value type, plus a pure + `forConditions(deviceProfile, ...)` replacing `forMode(...)`. Where the + numbers live. `PlaybackBufferMode` and its `fromWire` parsing are deleted. +- **`SiloLoadControl`** — keeps bitrate-aware byte sizing; gains the + seconds-fit-to-budget reduction and enforces the idle-window invariant when + constructing its `DefaultLoadControl` parameters. +- **`SiloPlayerFactory`** — stops naming a mode; passes observed conditions. + +## Testing + +Pure functions, following the existing `PlaybackBufferPolicyTest` / +`SiloLoadControlTest` pattern. Per this repo's guidelines, focused tests on +high-risk behaviour only: + +- The idle-window invariant holds for every reachable policy — including after + the memory budget has forced depth down. +- Seconds-fit-to-budget reduction, and the 20s floor holding on a low-RAM device + with a 60 Mbps stream. +- The 180s ceiling holding when memory would allow more. +- A regression pinning `max − min ≤ 30s`, since that is the property that + prevents the dropped connections. + +## Out of scope + +- Any user-facing or server-driven buffer setting. +- LAN-vs-remote branching: no such signal exists in the player today. +- HLS-vs-progressive policy split: the throughput signal covers what matters. +- Changing `proxy_send_timeout` on openresty. That would help only servers Jim + controls; the client-side invariant holds against any proxy, including + users' own reverse proxies and CDNs. From c0bda8f845fb0c1a62f71205aa15cc88b10c4e62 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 08:00:20 +0200 Subject: [PATCH 02/11] docs: playback buffer architecture implementation plan Co-Authored-By: Claude Fable 5 --- ...2026-07-30-playback-buffer-architecture.md | 495 ++++++++++++++++++ 1 file changed, 495 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md diff --git a/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md b/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md new file mode 100644 index 0000000000..7a93e5b89e --- /dev/null +++ b/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md @@ -0,0 +1,495 @@ +# Playback Buffer Architecture Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Stop the buffer from idling the socket long enough for an upstream proxy to drop the connection, while letting buffer depth grow as far as memory and throughput allow. + +**Architecture:** `maxBufferMs` becomes derived (`min + MAX_LOAD_IDLE_MS`) rather than hand-written, which makes the dropped-connection failure unrepresentable. Depth is governed by a memory budget and observed throughput, with an explicit floor and ceiling. The dead three-mode enum is deleted. + +**Tech Stack:** Kotlin 2.1, Java 21, AndroidX Media3 (ExoPlayer), kotlin.test/JUnit4 unit tests in `android-shared/src/androidUnitTest`. + +**Spec:** `docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md` — read it first; it is the authority on behaviour and carries the reasoning behind every number. + +## Global Constraints + +- **The invariant is the point of this work:** `maxBufferMs == minBufferMs + MAX_LOAD_IDLE_MS`, always, for every reachable policy including after the memory budget reduces depth. `MAX_LOAD_IDLE_MS = 30_000`. +- **Depth bounds:** floor `20_000` ms, ceiling `180_000` ms. +- **Startup:** `bufferForPlaybackMs = 2_000`, `bufferForPlaybackAfterRebufferMs = 5_000`. +- **No user setting, no server-driven wire value.** `PlaybackBufferMode` and its `fromWire` are deleted, not repurposed. +- **No transcode/HLS special case.** One policy; throughput governs. The server's `TranscodeThrottler` owns the transcode-ahead ceiling. +- Package root is `org.siloserver.silo`; buffer code lives in `org.siloserver.silo.common.player`. +- Build/test: `./gradlew :android-shared:testDebugUnitTest` for these tests; `./gradlew :androidApp:assembleDebug` and `./gradlew :androidTvApp:assembleDebug` must both still build (the module is shared). +- Per repo guidelines, add focused tests for the high-risk behaviour only — do not blanket-test UI or trivial changes. +- Commit per task. Push to `origin` (the RXWatcher fork), never a PR against Silo-Server without being asked. + +--- + +### Task 1: Derive `maxBufferMs` and delete the dead mode enum + +This task alone fixes the reported dropped connections. + +**Files:** +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt` +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt:318-323` +- Test: `android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt` + +**Interfaces:** +- Produces: `PlaybackBufferPolicy.forConditions(deviceProfile: PlaybackBufferDeviceProfile): PlaybackBufferPolicy`, plus companion constants `MAX_LOAD_IDLE_MS = 30_000`, `MIN_DEPTH_MS = 20_000`, `MAX_DEPTH_MS = 180_000`, `ASSUMED_PROXY_SEND_TIMEOUT_MS = 60_000`. The `PlaybackBufferPolicy` data class keeps its existing six fields unchanged. +- Removes: `PlaybackBufferMode` (whole enum, including `fromWire`) and `PlaybackBufferPolicy.forMode(...)`. `PlaybackBufferDeviceProfile` stays exactly as it is. + +- [ ] **Step 1: Write the failing tests** + +Replace the whole body of `PlaybackBufferPolicyTest` (its existing tests reference `forMode`/`PlaybackBufferMode`, which this task deletes): + +```kotlin +package org.siloserver.silo.common.player + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class PlaybackBufferPolicyTest { + + private val roomy = PlaybackBufferDeviceProfile(memoryClassMb = 512, isLowRamDevice = false) + private val lowRam = PlaybackBufferDeviceProfile(memoryClassMb = 96, isLowRamDevice = true) + + // The load control stops reading the socket once the buffer reaches + // maxBufferMs and does not resume until it drains below minBufferMs, so + // this gap IS how long the connection sits idle. An upstream proxy with a + // 60s send timeout drops it if the gap approaches that. This is the + // property the whole design exists to guarantee. + @Test + fun `idle window is bounded for every device profile`() { + listOf(roomy, lowRam, PlaybackBufferDeviceProfile.Unknown).forEach { profile -> + val policy = PlaybackBufferPolicy.forConditions(profile) + assertEquals( + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS, + policy.maxBufferMs - policy.minBufferMs, + "idle window for $profile", + ) + } + } + + @Test + fun `idle window stays well under the proxy send timeout it guards against`() { + assertTrue( + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS * 2 <= + PlaybackBufferPolicy.ASSUMED_PROXY_SEND_TIMEOUT_MS, + "idle window should keep a wide margin below the assumed timeout", + ) + } + + @Test + fun `playback starts on a small cushion and recovers quickly after a stall`() { + val policy = PlaybackBufferPolicy.forConditions(roomy) + assertEquals(2_000, policy.bufferForPlaybackMs) + assertEquals(5_000, policy.bufferForPlaybackAfterRebufferMs) + } + + @Test + fun `depth stays within the declared floor and ceiling`() { + listOf(roomy, lowRam, PlaybackBufferDeviceProfile.Unknown).forEach { profile -> + val policy = PlaybackBufferPolicy.forConditions(profile) + assertTrue(policy.minBufferMs >= PlaybackBufferPolicy.MIN_DEPTH_MS, "floor for $profile") + assertTrue(policy.minBufferMs <= PlaybackBufferPolicy.MAX_DEPTH_MS, "ceiling for $profile") + } + } + + @Test + fun `startup thresholds never exceed the depth the policy asks for`() { + listOf(roomy, lowRam, PlaybackBufferDeviceProfile.Unknown).forEach { profile -> + val policy = PlaybackBufferPolicy.forConditions(profile) + assertTrue(policy.bufferForPlaybackMs <= policy.minBufferMs, "start for $profile") + assertTrue( + policy.bufferForPlaybackAfterRebufferMs <= policy.minBufferMs, + "rebuffer for $profile", + ) + } + } +} +``` + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `./gradlew :android-shared:testDebugUnitTest --tests '*PlaybackBufferPolicyTest*'` +Expected: FAIL — `forConditions` and the constants are unresolved references. + +- [ ] **Step 3: Implement** + +Replace the contents of `PlaybackBufferPolicy.kt` with: + +```kotlin +package org.siloserver.silo.common.player + +/** + * 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, + val bufferForPlaybackMs: Int, + val bufferForPlaybackAfterRebufferMs: Int, + val targetBufferBytes: Int, + val prioritizeTimeOverSizeThresholds: Boolean, +) { + companion object { + /** + * How long the load control may stop reading the socket. + * + * 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. Upstream proxies close + * an idle response body: 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. + * + * 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 = 30_000 + + /** 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 { + 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, + ) + } + + /** + * The byte ceiling this device can afford. SiloLoadControl sizes the + * real target from the stream's bitrate and clamps it to this. + */ + internal fun memoryBudgetBytes(deviceProfile: PlaybackBufferDeviceProfile): Int = when { + deviceProfile.isLowRamDevice -> 48 * MIB + deviceProfile.memoryClassMb <= 0 -> 48 * MIB + deviceProfile.memoryClassMb < 192 -> 48 * MIB + deviceProfile.memoryClassMb < 384 -> 96 * MIB + else -> 160 * MIB + } + + private const val MIB = 1024 * 1024 + } +} + +data class PlaybackBufferDeviceProfile( + val memoryClassMb: Int, + val isLowRamDevice: Boolean, +) { + companion object { + val Unknown = PlaybackBufferDeviceProfile(memoryClassMb = 0, isLowRamDevice = false) + } +} +``` + +Then update the call site in `SiloPlayerFactory.kt` (around line 318). Replace the `PlaybackBufferPolicy.forMode(PlaybackBufferMode.Balanced, playbackBufferDeviceProfile())` call and its preceding comment with: + +```kotlin + // 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()) +``` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `./gradlew :android-shared:testDebugUnitTest --tests '*PlaybackBufferPolicyTest*'` +Expected: PASS, 5 tests. + +- [ ] **Step 5: Confirm both apps still build** + +Run: `./gradlew :androidApp:assembleDebug :androidTvApp:assembleDebug` +Expected: BUILD SUCCESSFUL. If either fails on an unresolved `PlaybackBufferMode`, there is a second reference to the deleted enum — find it with `grep -rn "PlaybackBufferMode" --include="*.kt" .` and remove it. + +- [ ] **Step 6: Commit** + +```bash +git add android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt \ + android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt \ + android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt +git commit -m "fix(playback): bound the load-idle window so proxies stop dropping the connection" +``` + +--- + +### Task 2: Fit depth to the memory budget instead of letting bytes silently truncate it + +**Files:** +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt` +- Test: `android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt` + +**Interfaces:** +- Consumes: `PlaybackBufferPolicy.MIN_DEPTH_MS`, `PlaybackBufferPolicy.MAX_LOAD_IDLE_MS` (Task 1); the existing internal helpers `selectBufferSizingBitrateBps(...)` and `calculateBitrateTargetBufferBytes(...)`, both unchanged. +- Produces: `internal fun affordableDepthMs(desiredDepthMs: Int, selectedBitrateBps: Long?, budgetBytes: Int, minimumDepthMs: Int): Int` — the depth the budget can actually fund, never below `minimumDepthMs`, never above `desiredDepthMs`. + +**Context an implementer needs:** today `calculateTargetBufferBytes` clamps bytes to the budget and stops there, so on a 60 Mbps remux the loader quietly stops at whatever the cap affords (about 5s on a low-RAM device) while the policy still claims a much larger depth. The fix is not to raise the cap — memory is genuinely finite — but to make the reduction explicit, so the resulting depth is a number the code chose rather than an accident. + +- [ ] **Step 1: Write the failing tests** + +Append to `SiloLoadControlTest`: + +```kotlin + @Test + fun `depth shrinks to what the memory budget can fund`() { + // 60 Mbps against a 48 MiB budget: 48 MiB * 8 / 60 Mbps ~= 6.7s, so the + // requested 180s cannot be held and the depth must come down to fit. + val depth = + affordableDepthMs( + desiredDepthMs = 180_000, + selectedBitrateBps = 60_000_000L, + budgetBytes = 48 * 1024 * 1024, + minimumDepthMs = 20_000, + ) + + assertTrue(depth < 180_000, "expected reduction, got $depth") + assertEquals(20_000, depth, "should clamp to the floor, not below it") + } + + @Test + fun `depth is left alone when the budget can fund it`() { + // 5 Mbps against 160 MiB: ~268s available, more than the 180s asked for. + val depth = + affordableDepthMs( + desiredDepthMs = 180_000, + selectedBitrateBps = 5_000_000L, + budgetBytes = 160 * 1024 * 1024, + minimumDepthMs = 20_000, + ) + + assertEquals(180_000, depth) + } + + @Test + fun `depth falls back to the request when the bitrate is unknown`() { + val depth = + affordableDepthMs( + desiredDepthMs = 120_000, + selectedBitrateBps = null, + budgetBytes = 96 * 1024 * 1024, + minimumDepthMs = 20_000, + ) + + assertEquals(120_000, depth) + } + + @Test + fun `reducing depth never widens the idle window`() { + // The invariant has to survive the reduction: whatever depth the budget + // affords, max is still exactly one idle window above it. + val depth = + affordableDepthMs( + desiredDepthMs = 180_000, + selectedBitrateBps = 80_000_000L, + budgetBytes = 48 * 1024 * 1024, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + ) + val max = depth + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS + + assertEquals(PlaybackBufferPolicy.MAX_LOAD_IDLE_MS, max - depth) + } +``` + +Add `import org.junit.Assert.assertTrue` to the file's imports. + +- [ ] **Step 2: Run the tests and watch them fail** + +Run: `./gradlew :android-shared:testDebugUnitTest --tests '*SiloLoadControlTest*'` +Expected: FAIL — `affordableDepthMs` is an unresolved reference. + +- [ ] **Step 3: Implement** + +Add to `SiloLoadControl.kt`, beside the other internal helpers: + +```kotlin +/** + * 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. + * + * An unknown bitrate leaves the request untouched; the byte clamp still + * applies downstream. + */ +internal fun affordableDepthMs( + desiredDepthMs: Int, + selectedBitrateBps: Long?, + budgetBytes: Int, + minimumDepthMs: Int, +): Int { + val bitrate = selectedBitrateBps?.takeIf { it > 0L } ?: return desiredDepthMs + val affordableMs = budgetBytes.toLong() * 8L * 1_000L / bitrate + return affordableMs + .coerceIn(minimumDepthMs.toLong(), desiredDepthMs.toLong()) + .toInt() +} +``` + +- [ ] **Step 4: Run the tests and watch them pass** + +Run: `./gradlew :android-shared:testDebugUnitTest --tests '*SiloLoadControlTest*'` +Expected: PASS — the four new tests plus the existing bitrate-selection ones. + +- [ ] **Step 5: Commit** + +```bash +git add android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt \ + android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +git commit -m "feat(playback): fit buffer depth to the device memory budget" +``` + +--- + +### Task 3: Apply the affordable depth to the live load control + +**Files:** +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt` +- Test: `android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt` + +**Interfaces:** +- Consumes: `affordableDepthMs(...)` (Task 2), `PlaybackBufferPolicy` (Task 1). +- Produces: `SiloLoadControl.currentDepthMs(): Int` — the depth most recently computed from observed bitrate, for tests and diagnostics. Defaults to the policy's `minBufferMs` before any track selection has happened. + +**Context an implementer needs:** `DefaultLoadControl` reads its min/max durations from constructor arguments and does not re-read them, so the depth reduction cannot change the running loader's time thresholds. It can and must still change the *byte* target, which is what actually stops the loader. `currentDepthMs()` exists so the reduction is observable rather than implicit — do not attempt to mutate the superclass's durations. + +- [ ] **Step 1: Write the failing test** + +Append to `SiloLoadControlTest`: + +```kotlin + @Test + fun `byte target follows the affordable depth rather than the requested one`() { + // A 40 Mbps stream on a 48 MiB budget can hold ~10s, not the 180s the + // policy asks for. The byte target must reflect the affordable depth, + // and must never exceed the budget. + val budgetBytes = 48 * 1024 * 1024 + val depth = + affordableDepthMs( + desiredDepthMs = PlaybackBufferPolicy.MAX_DEPTH_MS, + selectedBitrateBps = 40_000_000L, + budgetBytes = budgetBytes, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + ) + + val bytes = + calculateBitrateTargetBufferBytes( + selectedBitrateBps = 40_000_000L, + desiredForwardBufferMs = depth, + minimumBytes = SiloLoadControl.MIN_TARGET_BUFFER_BYTES, + maximumBytes = budgetBytes, + unknownBitrateFallbackBytes = budgetBytes, + ) + + assertTrue(bytes <= budgetBytes, "byte target $bytes exceeded budget $budgetBytes") + assertTrue(bytes >= SiloLoadControl.MIN_TARGET_BUFFER_BYTES, "byte target below floor") + } +``` + +- [ ] **Step 2: Run the test and watch it fail** + +Run: `./gradlew :android-shared:testDebugUnitTest --tests '*SiloLoadControlTest*'` +Expected: FAIL — `MIN_TARGET_BUFFER_BYTES` is `internal` inside a companion that the test can reach, but `calculateTargetBufferBytes` does not yet size from an affordable depth. If it compiles and passes immediately, the sizing path was already correct; still complete step 3 so the running loader uses it. + +- [ ] **Step 3: Implement** + +Replace `SiloLoadControl`'s `calculateTargetBufferBytes` override and add the depth field: + +```kotlin + @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, + ): Int { + val selectedBitrateBps = + selectBufferSizingBitrateBps( + trackSelections.mapNotNull { selection -> + selection?.let { + BufferSizingTrackBitrates( + averageBitrateBps = it.selectedFormat.averageBitrate, + peakBitrateBps = it.selectedFormat.peakBitrate, + latestNetworkEstimateBps = it.latestBitrateEstimate, + ) + } + }, + ) + val fallback = super.calculateTargetBufferBytes(parameters, trackSelections) + val affordableMs = + affordableDepthMs( + desiredDepthMs = policy.minBufferMs, + selectedBitrateBps = selectedBitrateBps, + budgetBytes = policy.targetBufferBytes, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + ) + depthMs = affordableMs + return calculateBitrateTargetBufferBytes( + selectedBitrateBps = selectedBitrateBps, + desiredForwardBufferMs = affordableMs, + minimumBytes = MIN_TARGET_BUFFER_BYTES, + maximumBytes = policy.targetBufferBytes, + unknownBitrateFallbackBytes = fallback, + ) + } +``` + +- [ ] **Step 4: Run the full module test suite** + +Run: `./gradlew :android-shared:testDebugUnitTest` +Expected: PASS, no regressions in the existing player tests. + +- [ ] **Step 5: Confirm both apps build** + +Run: `./gradlew :androidApp:assembleDebug :androidTvApp:assembleDebug` +Expected: BUILD SUCCESSFUL. + +- [ ] **Step 6: Commit** + +```bash +git add android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt \ + android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +git commit -m "feat(playback): size the byte target from the affordable buffer depth" +``` + +--- + +## Self-review notes (already applied) + +- Spec coverage: the invariant and enum deletion → Task 1; memory-governed depth with floor/ceiling → Tasks 2 and 3; startup/rebuffer numbers → Task 1; no-transcode-special-case and no-user-setting are satisfied by never introducing them. +- Throughput-driven depth is represented by the existing `latestBitrateEstimate` fallback inside `selectBufferSizingBitrateBps`, which already prefers measured network throughput when the container declares no bitrate. No separate task: adding a second throughput mechanism would duplicate it. +- Type consistency: `affordableDepthMs` has one signature, used identically in Tasks 2 and 3; `PlaybackBufferPolicy.forConditions` takes only a device profile in both Task 1 and its call site. +- `MIN_TARGET_BUFFER_BYTES` stays `internal const` on `SiloLoadControl`'s companion, unchanged from today, so the Task 3 test can reference it. From bf1225cf01539ec863465f60e4418469f39d09cf Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 08:03:58 +0200 Subject: [PATCH 03/11] fix(playback): bound the load-idle window so proxies stop dropping the connection DefaultLoadControl stops reading the socket once the buffer hits maxBufferMs and does not resume until it drains below minBufferMs, so max - min is literally how long the connection sits idle. The old hardcoded 50s/120s pair left a 70s gap, well past a typical upstream proxy's 60s send_timeout, so long direct-play files got dropped every time the buffer filled. PlaybackBufferPolicy.forConditions() now derives maxBufferMs as minBufferMs + a fixed MAX_LOAD_IDLE_MS (30s), so depth can grow without ever widening the idle window. Depth is pinned to MAX_DEPTH_MS for now; a later task will shrink it per device memory budget without touching the idle-window guarantee. Deletes the unused PlaybackBufferMode enum (QuickStart/Balanced/ SmoothPlayback) and forMode(), which were never wired to any user or server setting. --- .../common/player/PlaybackBufferPolicy.kt | 107 ++++++----- .../silo/common/player/SiloPlayerFactory.kt | 14 +- .../common/player/PlaybackBufferPolicyTest.kt | 168 ++++-------------- 3 files changed, 104 insertions(+), 185 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt index d349df1c1e..7fc0afff29 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt @@ -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, @@ -21,46 +14,66 @@ data class PlaybackBufferPolicy( val prioritizeTimeOverSizeThresholds: Boolean, ) { companion object { - fun forMode( - mode: PlaybackBufferMode, + /** + * How long the load control may stop reading the socket. + * + * 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. Upstream proxies close + * an idle response body: 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. + * + * 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 = 30_000 + + /** 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. + */ + internal fun memoryBudgetBytes(deviceProfile: PlaybackBufferDeviceProfile): Int = when { + deviceProfile.isLowRamDevice -> 48 * MIB + deviceProfile.memoryClassMb <= 0 -> 48 * MIB + deviceProfile.memoryClassMb < 192 -> 48 * MIB + deviceProfile.memoryClassMb < 384 -> 96 * MIB + else -> 160 * MIB } private const val MIB = 1024 * 1024 diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt index bfd292c6c3..fa437683a3 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt @@ -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) diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt index 26459c7649..b3474a0691 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt @@ -2,154 +2,64 @@ package org.siloserver.silo.common.player import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertFalse import kotlin.test.assertTrue class PlaybackBufferPolicyTest { - @Test - fun profilesExposeExpectedStartupAndRebufferTargets() { - val quick = PlaybackBufferPolicy.forMode(PlaybackBufferMode.QuickStart) - val balanced = PlaybackBufferPolicy.forMode(PlaybackBufferMode.Balanced) - val smooth = PlaybackBufferPolicy.forMode(PlaybackBufferMode.SmoothPlayback) - - assertEquals(2_000, quick.bufferForPlaybackMs) - assertEquals(6_000, quick.bufferForPlaybackAfterRebufferMs) - assertEquals(3_000, balanced.bufferForPlaybackMs) - assertEquals(10_000, balanced.bufferForPlaybackAfterRebufferMs) - assertEquals(5_000, smooth.bufferForPlaybackMs) - assertEquals(15_000, smooth.bufferForPlaybackAfterRebufferMs) - } + private val roomy = PlaybackBufferDeviceProfile(memoryClassMb = 512, isLowRamDevice = false) + private val lowRam = PlaybackBufferDeviceProfile(memoryClassMb = 96, isLowRamDevice = true) + // The load control stops reading the socket once the buffer reaches + // maxBufferMs and does not resume until it drains below minBufferMs, so + // this gap IS how long the connection sits idle. An upstream proxy with a + // 60s send timeout drops it if the gap approaches that. This is the + // property the whole design exists to guarantee. @Test - fun profilesKeepBufferDurationsInValidOrder() { - PlaybackBufferMode.entries.forEach { mode -> - val policy = PlaybackBufferPolicy.forMode(mode) - assertTrue(policy.bufferForPlaybackMs <= policy.minBufferMs, mode.name) - assertTrue(policy.bufferForPlaybackAfterRebufferMs <= policy.minBufferMs, mode.name) - assertTrue(policy.minBufferMs <= policy.maxBufferMs, mode.name) + fun `idle window is bounded for every device profile`() { + listOf(roomy, lowRam, PlaybackBufferDeviceProfile.Unknown).forEach { profile -> + val policy = PlaybackBufferPolicy.forConditions(profile) + assertEquals( + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS, + policy.maxBufferMs - policy.minBufferMs, + "idle window for $profile", + ) } } @Test - fun quickStartUsesHeapBoundedByteCapForHighBitrate4kDirectPlay() { - val policy = PlaybackBufferPolicy.forMode(PlaybackBufferMode.QuickStart, roomyDevice) - - assertEquals(128 * 1024 * 1024, policy.targetBufferBytes) - assertFalse(policy.prioritizeTimeOverSizeThresholds) - assertTrue(policy.maxBufferMs <= 60_000) - } - - @Test - fun smoothPlaybackUsesHeapBoundedByteCapForHighBitrateRemuxes() { - val policy = PlaybackBufferPolicy.forMode(PlaybackBufferMode.SmoothPlayback, roomyDevice) - - assertEquals(192 * 1024 * 1024, policy.targetBufferBytes) - assertFalse(policy.prioritizeTimeOverSizeThresholds) - assertTrue(policy.maxBufferMs <= 180_000) - } - - @Test - fun smoothPlaybackPrioritizesDeepForwardBufferingOverQuickStartup() { - val policy = PlaybackBufferPolicy.forMode(PlaybackBufferMode.SmoothPlayback) - - assertTrue(policy.bufferForPlaybackMs >= PlaybackBufferPolicy.forMode(PlaybackBufferMode.Balanced).bufferForPlaybackMs) - assertTrue(policy.bufferForPlaybackAfterRebufferMs >= policy.bufferForPlaybackMs * 3) - assertTrue(policy.minBufferMs >= policy.bufferForPlaybackAfterRebufferMs * 3) - assertTrue(policy.maxBufferMs >= policy.minBufferMs * 2) - } - - @Test - fun allProfilesHaveFiniteTargetByteCaps() { - assertEquals(128 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.QuickStart, roomyDevice).targetBufferBytes) - assertEquals(160 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.Balanced, roomyDevice).targetBufferBytes) - assertEquals(192 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.SmoothPlayback, roomyDevice).targetBufferBytes) - } - - @Test - fun lowMemoryDevicesUseSmallerByteCaps() { - val lowMemory = PlaybackBufferDeviceProfile(memoryClassMb = 128, isLowRamDevice = true) - - assertEquals(32 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.QuickStart, lowMemory).targetBufferBytes) - assertEquals(48 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.Balanced, lowMemory).targetBufferBytes) - assertEquals(64 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.SmoothPlayback, lowMemory).targetBufferBytes) - } - - @Test - fun unknownDevicesUseConstrainedByteCapsUntilMemoryClassIsKnown() { - assertEquals( - 32 * 1024 * 1024, - PlaybackBufferPolicy.forMode( - PlaybackBufferMode.QuickStart, - PlaybackBufferDeviceProfile.Unknown, - ).targetBufferBytes, - ) - assertEquals( - 48 * 1024 * 1024, - PlaybackBufferPolicy.forMode( - PlaybackBufferMode.Balanced, - PlaybackBufferDeviceProfile.Unknown, - ).targetBufferBytes, - ) - assertEquals( - 64 * 1024 * 1024, - PlaybackBufferPolicy.forMode( - PlaybackBufferMode.SmoothPlayback, - PlaybackBufferDeviceProfile.Unknown, - ).targetBufferBytes, + fun `idle window stays well under the proxy send timeout it guards against`() { + assertTrue( + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS * 2 <= + PlaybackBufferPolicy.ASSUMED_PROXY_SEND_TIMEOUT_MS, + "idle window should keep a wide margin below the assumed timeout", ) } @Test - fun roomyDevicesKeepLargeByteCaps() { - assertEquals(128 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.QuickStart, roomyDevice).targetBufferBytes) - assertEquals(160 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.Balanced, roomyDevice).targetBufferBytes) - assertEquals(192 * 1024 * 1024, PlaybackBufferPolicy.forMode(PlaybackBufferMode.SmoothPlayback, roomyDevice).targetBufferBytes) + fun `playback starts on a small cushion and recovers quickly after a stall`() { + val policy = PlaybackBufferPolicy.forConditions(roomy) + assertEquals(2_000, policy.bufferForPlaybackMs) + assertEquals(5_000, policy.bufferForPlaybackAfterRebufferMs) } @Test - fun bitrateAwareTargetScalesLowBitrateStreamsBelowDeviceCap() { - assertEquals( - 35_937_500, - calculateBitrateTargetBufferBytes( - selectedBitrateBps = 5_000_000, - desiredForwardBufferMs = 50_000, - minimumBytes = 16 * 1024 * 1024, - maximumBytes = 160 * 1024 * 1024, - unknownBitrateFallbackBytes = 96 * 1024 * 1024, - ), - ) - } - - @Test - fun bitrateAwareTargetClampsHighBitrateRemuxesToDeviceCap() { - assertEquals( - 160 * 1024 * 1024, - calculateBitrateTargetBufferBytes( - selectedBitrateBps = 100_000_000, - desiredForwardBufferMs = 50_000, - minimumBytes = 16 * 1024 * 1024, - maximumBytes = 160 * 1024 * 1024, - unknownBitrateFallbackBytes = 96 * 1024 * 1024, - ), - ) + fun `depth stays within the declared floor and ceiling`() { + listOf(roomy, lowRam, PlaybackBufferDeviceProfile.Unknown).forEach { profile -> + val policy = PlaybackBufferPolicy.forConditions(profile) + assertTrue(policy.minBufferMs >= PlaybackBufferPolicy.MIN_DEPTH_MS, "floor for $profile") + assertTrue(policy.minBufferMs <= PlaybackBufferPolicy.MAX_DEPTH_MS, "ceiling for $profile") + } } @Test - fun bitrateAwareTargetClampsOverflowingBitrateEstimateToDeviceCap() { - assertEquals( - 160 * 1024 * 1024, - calculateBitrateTargetBufferBytes( - selectedBitrateBps = Long.MAX_VALUE, - desiredForwardBufferMs = 50_000, - minimumBytes = 16 * 1024 * 1024, - maximumBytes = 160 * 1024 * 1024, - unknownBitrateFallbackBytes = 96 * 1024 * 1024, - ), - ) - } - - private companion object { - val roomyDevice = PlaybackBufferDeviceProfile(memoryClassMb = 384, isLowRamDevice = false) + fun `startup thresholds never exceed the depth the policy asks for`() { + listOf(roomy, lowRam, PlaybackBufferDeviceProfile.Unknown).forEach { profile -> + val policy = PlaybackBufferPolicy.forConditions(profile) + assertTrue(policy.bufferForPlaybackMs <= policy.minBufferMs, "start for $profile") + assertTrue( + policy.bufferForPlaybackAfterRebufferMs <= policy.minBufferMs, + "rebuffer for $profile", + ) + } } } From 9851af5863bda2b3692565b5e0d271725807d737 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 08:09:30 +0200 Subject: [PATCH 04/11] feat(playback): fit buffer depth to the device memory budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add affordableDepthMs, a pure helper beside the existing bitrate-selection and byte-target helpers in SiloLoadControl.kt. It computes the forward buffer depth a device's memory budget can actually fund at the selected bitrate, clamped between minimumDepthMs and the desired depth, so a high-bitrate stream's reduced depth is a number the code chose rather than wherever the byte clamp happens to truncate it. Not yet wired into calculateTargetBufferBytes — that's Task 3. --- .../silo/common/player/SiloLoadControl.kt | 25 ++++++++ .../silo/common/player/SiloLoadControlTest.kt | 60 +++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt index 392c697e63..1190ae5b62 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt @@ -89,6 +89,31 @@ 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. + * + * An unknown bitrate leaves the request untouched; the byte clamp still + * applies downstream. + */ +internal fun affordableDepthMs( + desiredDepthMs: Int, + selectedBitrateBps: Long?, + budgetBytes: Int, + minimumDepthMs: Int, +): Int { + val bitrate = selectedBitrateBps?.takeIf { it > 0L } ?: return desiredDepthMs + val affordableMs = budgetBytes.toLong() * 8L * 1_000L / bitrate + return affordableMs + .coerceIn(minimumDepthMs.toLong(), desiredDepthMs.toLong()) + .toInt() +} + internal fun calculateBitrateTargetBufferBytes( selectedBitrateBps: Long?, desiredForwardBufferMs: Int, diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt index 14db83db8f..be0854766a 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt @@ -2,6 +2,7 @@ package org.siloserver.silo.common.player import org.junit.Assert.assertEquals import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Test class SiloLoadControlTest { @@ -92,4 +93,63 @@ class SiloLoadControlTest { fun `empty track selection remains unknown`() { assertNull(selectBufferSizingBitrateBps(emptyList())) } + + @Test + fun `depth shrinks to what the memory budget can fund`() { + // 60 Mbps against a 48 MiB budget: 48 MiB * 8 / 60 Mbps ~= 6.7s, so the + // requested 180s cannot be held and the depth must come down to fit. + val depth = + affordableDepthMs( + desiredDepthMs = 180_000, + selectedBitrateBps = 60_000_000L, + budgetBytes = 48 * 1024 * 1024, + minimumDepthMs = 20_000, + ) + + assertTrue("expected reduction, got $depth", depth < 180_000) + assertEquals("should clamp to the floor, not below it", 20_000, depth) + } + + @Test + fun `depth is left alone when the budget can fund it`() { + // 5 Mbps against 160 MiB: ~268s available, more than the 180s asked for. + val depth = + affordableDepthMs( + desiredDepthMs = 180_000, + selectedBitrateBps = 5_000_000L, + budgetBytes = 160 * 1024 * 1024, + minimumDepthMs = 20_000, + ) + + assertEquals(180_000, depth) + } + + @Test + fun `depth falls back to the request when the bitrate is unknown`() { + val depth = + affordableDepthMs( + desiredDepthMs = 120_000, + selectedBitrateBps = null, + budgetBytes = 96 * 1024 * 1024, + minimumDepthMs = 20_000, + ) + + assertEquals(120_000, depth) + } + + @Test + fun `reducing depth never widens the idle window`() { + // The invariant has to survive the reduction: whatever depth the budget + // affords, max is still exactly one idle window above it. + val depth = + affordableDepthMs( + desiredDepthMs = 180_000, + selectedBitrateBps = 80_000_000L, + budgetBytes = 48 * 1024 * 1024, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + ) + val max = depth + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS + + assertEquals(PlaybackBufferPolicy.MAX_LOAD_IDLE_MS, max - depth) + } } From 79d690d72f33ba5e7527f6547be478438a8d915b Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 08:13:32 +0200 Subject: [PATCH 05/11] feat(playback): size the byte target from the affordable buffer depth Co-Authored-By: Claude Opus 5 (1M context) --- .../silo/common/player/SiloLoadControl.kt | 15 ++++++++++- .../silo/common/player/SiloLoadControlTest.kt | 27 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt index 1190ae5b62..5e388567c3 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt @@ -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, @@ -51,9 +56,17 @@ class SiloLoadControl( }, ) val fallback = super.calculateTargetBufferBytes(parameters, trackSelections) + val affordableMs = + affordableDepthMs( + desiredDepthMs = policy.minBufferMs, + selectedBitrateBps = selectedBitrateBps, + budgetBytes = policy.targetBufferBytes, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + ) + depthMs = affordableMs return calculateBitrateTargetBufferBytes( selectedBitrateBps = selectedBitrateBps, - desiredForwardBufferMs = policy.minBufferMs, + desiredForwardBufferMs = affordableMs, minimumBytes = MIN_TARGET_BUFFER_BYTES, maximumBytes = policy.targetBufferBytes, unknownBitrateFallbackBytes = fallback, diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt index be0854766a..b58e9a9304 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt @@ -152,4 +152,31 @@ class SiloLoadControlTest { assertEquals(PlaybackBufferPolicy.MAX_LOAD_IDLE_MS, max - depth) } + + @Test + fun `byte target follows the affordable depth rather than the requested one`() { + // A 40 Mbps stream on a 48 MiB budget can hold ~10s, not the 180s the + // policy asks for. The byte target must reflect the affordable depth, + // and must never exceed the budget. + val budgetBytes = 48 * 1024 * 1024 + val depth = + affordableDepthMs( + desiredDepthMs = PlaybackBufferPolicy.MAX_DEPTH_MS, + selectedBitrateBps = 40_000_000L, + budgetBytes = budgetBytes, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + ) + + val bytes = + calculateBitrateTargetBufferBytes( + selectedBitrateBps = 40_000_000L, + desiredForwardBufferMs = depth, + minimumBytes = SiloLoadControl.MIN_TARGET_BUFFER_BYTES, + maximumBytes = budgetBytes, + unknownBitrateFallbackBytes = budgetBytes, + ) + + assertTrue("byte target $bytes exceeded budget $budgetBytes", bytes <= budgetBytes) + assertTrue("byte target below floor", bytes >= SiloLoadControl.MIN_TARGET_BUFFER_BYTES) + } } From 4996d26d90368aca2655208a264fe0666be1840e Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 08:24:25 +0200 Subject: [PATCH 06/11] refactor(playback): split buffer-sizing policy from the Media3 adapter Task review found the Task 3 test exercised affordableDepthMs and calculateBitrateTargetBufferBytes directly (already covered by Task 2) rather than the calculateTargetBufferBytes wiring it claimed to test, so a wiring bug (wrong value into depthMs, fallback swapped for the budget as maximumBytes, or depth not routed into desiredForwardBufferMs) would still pass. Extract the composition into a pure computeBufferSizing helper beside the other internal helpers, reduce the override to a thin Media3-type adapter over it, and replace the test with cases against computeBufferSizing that pin the wiring itself. Co-Authored-By: Claude Opus 5 (1M context) --- .../silo/common/player/SiloLoadControl.kt | 57 +++++++++++---- .../silo/common/player/SiloLoadControlTest.kt | 69 +++++++++++++++---- 2 files changed, 99 insertions(+), 27 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt index 5e388567c3..500448f142 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt @@ -56,21 +56,17 @@ class SiloLoadControl( }, ) val fallback = super.calculateTargetBufferBytes(parameters, trackSelections) - val affordableMs = - affordableDepthMs( - desiredDepthMs = policy.minBufferMs, + val result = + computeBufferSizing( selectedBitrateBps = selectedBitrateBps, - budgetBytes = policy.targetBufferBytes, + desiredDepthMs = policy.minBufferMs, minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + budgetBytes = policy.targetBufferBytes, + minimumBytes = MIN_TARGET_BUFFER_BYTES, + unknownBitrateFallbackBytes = fallback, ) - depthMs = affordableMs - return calculateBitrateTargetBufferBytes( - selectedBitrateBps = selectedBitrateBps, - desiredForwardBufferMs = affordableMs, - minimumBytes = MIN_TARGET_BUFFER_BYTES, - maximumBytes = policy.targetBufferBytes, - unknownBitrateFallbackBytes = fallback, - ) + depthMs = result.depthMs + return result.targetBytes } companion object { @@ -127,6 +123,43 @@ internal fun affordableDepthMs( .toInt() } +/** The composed result of sizing the buffer: the depth chosen and the bytes it maps to. */ +internal data class BufferSizingResult(val depthMs: Int, val targetBytes: Int) + +/** + * 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, + minimumBytes = minimumBytes, + maximumBytes = budgetBytes, + unknownBitrateFallbackBytes = unknownBitrateFallbackBytes, + ) + return BufferSizingResult(depthMs = depthMs, targetBytes = targetBytes) +} + internal fun calculateBitrateTargetBufferBytes( selectedBitrateBps: Long?, desiredForwardBufferMs: Int, diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt index b58e9a9304..a00d473db6 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt @@ -154,29 +154,68 @@ class SiloLoadControlTest { } @Test - fun `byte target follows the affordable depth rather than the requested one`() { - // A 40 Mbps stream on a 48 MiB budget can hold ~10s, not the 180s the - // policy asks for. The byte target must reflect the affordable depth, - // and must never exceed the budget. + fun `composed sizing clamps depth to the floor and bytes to the budget ceiling`() { + // A 40 Mbps stream on a 48 MiB budget cannot hold the 180s the policy + // asks for, nor even the 20s floor (affordable is ~10s), so depth + // clamps to the floor. The resulting byte target is then sized from + // that clamped depth and clamps to the budget, not the (distinct) + // fallback — this exercises the exact composition + // calculateTargetBufferBytes wires together, unlike the free-standing + // affordableDepthMs/calculateBitrateTargetBufferBytes tests above. val budgetBytes = 48 * 1024 * 1024 - val depth = - affordableDepthMs( - desiredDepthMs = PlaybackBufferPolicy.MAX_DEPTH_MS, + val fallbackBytes = 30 * 1024 * 1024 // distinct from budgetBytes: catches a maximumBytes mix-up + val result = + computeBufferSizing( selectedBitrateBps = 40_000_000L, + desiredDepthMs = PlaybackBufferPolicy.MAX_DEPTH_MS, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, budgetBytes = budgetBytes, + minimumBytes = SiloLoadControl.MIN_TARGET_BUFFER_BYTES, + unknownBitrateFallbackBytes = fallbackBytes, + ) + + assertEquals("depth should clamp to the floor", PlaybackBufferPolicy.MIN_DEPTH_MS, result.depthMs) + assertEquals("byte target should clamp to the budget ceiling, not the fallback", budgetBytes, result.targetBytes) + } + + @Test + fun `composed sizing routes the fallback bytes when the bitrate is unknown`() { + // With no bitrate to size from, the requested depth passes through + // untouched and the byte target must come from the caller-supplied + // fallback (what the superclass computed) rather than the budget. + val fallbackBytes = 40 * 1024 * 1024 + val result = + computeBufferSizing( + selectedBitrateBps = null, + desiredDepthMs = 120_000, minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + budgetBytes = 160 * 1024 * 1024, + minimumBytes = SiloLoadControl.MIN_TARGET_BUFFER_BYTES, + unknownBitrateFallbackBytes = fallbackBytes, ) - val bytes = - calculateBitrateTargetBufferBytes( - selectedBitrateBps = 40_000_000L, - desiredForwardBufferMs = depth, + assertEquals("depth should pass through unchanged", 120_000, result.depthMs) + assertEquals("byte target should route the fallback", fallbackBytes, result.targetBytes) + } + + @Test + fun `composed sizing never asks for a deeper buffer than the policy requested`() { + // A reduction must only ever shrink the depth, never grow it — + // growing it would widen the fixed idle window between min and max. + val desiredDepthMs = PlaybackBufferPolicy.MAX_DEPTH_MS + val result = + computeBufferSizing( + selectedBitrateBps = 80_000_000L, + desiredDepthMs = desiredDepthMs, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + budgetBytes = 48 * 1024 * 1024, minimumBytes = SiloLoadControl.MIN_TARGET_BUFFER_BYTES, - maximumBytes = budgetBytes, - unknownBitrateFallbackBytes = budgetBytes, + unknownBitrateFallbackBytes = 48 * 1024 * 1024, ) - assertTrue("byte target $bytes exceeded budget $budgetBytes", bytes <= budgetBytes) - assertTrue("byte target below floor", bytes >= SiloLoadControl.MIN_TARGET_BUFFER_BYTES) + assertTrue( + "depth ${result.depthMs} exceeded requested $desiredDepthMs", + result.depthMs <= desiredDepthMs, + ) } } From 87111610562402cb0461e7095f30717845e9b2d2 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 08:37:52 +0200 Subject: [PATCH 07/11] fix(playback): heap-proportional budget, honest depth, and a compile-time depth/bytes guard Scoped re-review injected each wiring bug from the last fix and found "depth not routed into desiredForwardBufferMs" undetected: the 15% overhead margin calculateBitrateTargetBufferBytes applies makes a correct depth and an un-routed 180s depth overshoot the same budget and clamp to the identical byte ceiling, erasing the depth's effect from the only value a test could observe. Same root cause as two product gaps: the fixed 48/96/160 MiB budget tiers can hand a 96 MB-heap device half its heap as a buffer (OOM risk) while capping a 512 MB device's headroom unused, and the 20s floor silently overrides a smaller budget so currentDepthMs() could report 20s on a device the loader could actually only hold 6-7s on. - PlaybackBufferPolicy.memoryBudgetBytes is now 1/4 of the device's own heap (memoryClassMb), bounded to [16, 192] MiB, with a conservative fixed 24 MiB fallback for low-RAM or unknown-heap devices, replacing the fixed 48/96/160 MiB tiers. - affordableDepthMs now lets the budget win over minimumDepthMs when a known bitrate affords less than the floor (the floor remains a lower bound only for the unknown-bitrate branch, where there's no bitrate to derive a number from), and divides by the same 115/100 margin calculateBitrateTargetBufferBytes multiplies back in, so a budget-limited depth lands its byte target at or just under the budget instead of overshooting and clamping. - BufferSizingResult now wraps depth and bytes in BufferDepthMs/ BufferTargetBytes inline value classes so transposing them at the override's two-line handoff is a compile error, not a silent bug no test without Media3 scaffolding could catch. - Tests updated/added throughout: heap-proportional budget cases at both ends, the honest sub-floor depth value, and a computeBufferSizing case asserting the depth itself (not just the clamped byte target) for a budget-limited stream. Co-Authored-By: Claude Opus 5 (1M context) --- .../common/player/PlaybackBufferPolicy.kt | 40 +++++++++-- .../silo/common/player/SiloLoadControl.kt | 48 +++++++++---- .../common/player/PlaybackBufferPolicyTest.kt | 39 +++++++++++ .../silo/common/player/SiloLoadControlTest.kt | 70 ++++++++++++++----- 4 files changed, 161 insertions(+), 36 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt index 7fc0afff29..0f8df2fa96 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt @@ -67,16 +67,44 @@ data class PlaybackBufferPolicy( /** * 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. */ - internal fun memoryBudgetBytes(deviceProfile: PlaybackBufferDeviceProfile): Int = when { - deviceProfile.isLowRamDevice -> 48 * MIB - deviceProfile.memoryClassMb <= 0 -> 48 * MIB - deviceProfile.memoryClassMb < 192 -> 48 * MIB - deviceProfile.memoryClassMb < 384 -> 96 * MIB - else -> 160 * MIB + internal fun memoryBudgetBytes(deviceProfile: PlaybackBufferDeviceProfile): Int { + if (deviceProfile.isLowRamDevice || deviceProfile.memoryClassMb <= 0) { + return LOW_RAM_MEMORY_BUDGET_BYTES + } + val proportionalBytes = + deviceProfile.memoryClassMb.toLong() * MIB / MEMORY_BUDGET_HEAP_DIVISOR + return 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/4) of the app heap — see [memoryBudgetBytes]. */ + private const val MEMORY_BUDGET_HEAP_DIVISOR = 4L + + /** 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 a quarter of an unknown or explicitly + * constrained heap is not a number worth trusting. + */ + private const val LOW_RAM_MEMORY_BUDGET_BYTES = 24 * MIB } } diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt index 500448f142..03ecb91527 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt @@ -65,8 +65,8 @@ class SiloLoadControl( minimumBytes = MIN_TARGET_BUFFER_BYTES, unknownBitrateFallbackBytes = fallback, ) - depthMs = result.depthMs - return result.targetBytes + depthMs = result.depth.ms + return result.target.bytes } companion object { @@ -107,8 +107,19 @@ internal fun selectBufferSizingBitrateBps( * 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. * - * An unknown bitrate leaves the request untouched; the byte clamp still - * applies downstream. + * 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, @@ -116,15 +127,28 @@ internal fun affordableDepthMs( budgetBytes: Int, minimumDepthMs: Int, ): Int { - val bitrate = selectedBitrateBps?.takeIf { it > 0L } ?: return desiredDepthMs - val affordableMs = budgetBytes.toLong() * 8L * 1_000L / bitrate - return affordableMs - .coerceIn(minimumDepthMs.toLong(), desiredDepthMs.toLong()) - .toInt() + 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() } -/** The composed result of sizing the buffer: the depth chosen and the bytes it maps to. */ -internal data class BufferSizingResult(val depthMs: Int, val targetBytes: Int) +/** 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 @@ -157,7 +181,7 @@ internal fun computeBufferSizing( maximumBytes = budgetBytes, unknownBitrateFallbackBytes = unknownBitrateFallbackBytes, ) - return BufferSizingResult(depthMs = depthMs, targetBytes = targetBytes) + return BufferSizingResult(depth = BufferDepthMs(depthMs), target = BufferTargetBytes(targetBytes)) } internal fun calculateBitrateTargetBufferBytes( diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt index b3474a0691..0e7e09e4af 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt @@ -62,4 +62,43 @@ class PlaybackBufferPolicyTest { ) } } + + @Test + fun `a small heap gets well under half its heap as a buffer budget`() { + // A fixed tier this small would starve the device (48 MiB was half of + // a 96 MB heap before this became proportional). 1/4 of the heap must + // land far short of half of it. + val smallHeap = PlaybackBufferDeviceProfile(memoryClassMb = 96, isLowRamDevice = false) + val budgetBytes = PlaybackBufferPolicy.memoryBudgetBytes(smallHeap) + val halfHeapBytes = (smallHeap.memoryClassMb * 1024 * 1024) / 2 + + assertTrue( + budgetBytes <= halfHeapBytes / 2, + "budget $budgetBytes should be well under half the heap ($halfHeapBytes)", + ) + } + + @Test + fun `a bigger heap gets a bigger budget than a smaller one`() { + // Proportional scaling means the ceiling grows with the device + // instead of two devices past the old 384 MB tier boundary sharing + // the same flat 160 MiB cap. + val midHeap = PlaybackBufferDeviceProfile(memoryClassMb = 256, isLowRamDevice = false) + val bigHeap = PlaybackBufferDeviceProfile(memoryClassMb = 512, isLowRamDevice = false) + + val midBudget = PlaybackBufferPolicy.memoryBudgetBytes(midHeap) + val bigBudget = PlaybackBufferPolicy.memoryBudgetBytes(bigHeap) + + assertTrue( + bigBudget > midBudget, + "a 512 MB heap ($bigBudget) should get more budget than a 256 MB heap ($midBudget)", + ) + } + + @Test + fun `a low-RAM device gets the conservative fixed fallback, not a proportional share`() { + val budgetBytes = PlaybackBufferPolicy.memoryBudgetBytes(lowRam) + + assertEquals(24 * 1024 * 1024, budgetBytes) + } } diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt index a00d473db6..e963f71e25 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt @@ -95,9 +95,13 @@ class SiloLoadControlTest { } @Test - fun `depth shrinks to what the memory budget can fund`() { - // 60 Mbps against a 48 MiB budget: 48 MiB * 8 / 60 Mbps ~= 6.7s, so the - // requested 180s cannot be held and the depth must come down to fit. + fun `depth follows the budget honestly, even below the floor`() { + // 60 Mbps against a 48 MiB budget: accounting for the same 15% + // overhead margin calculateBitrateTargetBufferBytes applies when it + // turns this depth back into bytes, the budget only really affords + // ~5.8s. The requested 180s cannot be held, and neither can the 20s + // floor — the budget wins over the floor because a false, rounded-up + // report would be worse than an honest shortfall. val depth = affordableDepthMs( desiredDepthMs = 180_000, @@ -106,8 +110,8 @@ class SiloLoadControlTest { minimumDepthMs = 20_000, ) - assertTrue("expected reduction, got $depth", depth < 180_000) - assertEquals("should clamp to the floor, not below it", 20_000, depth) + assertTrue("expected reduction below the floor, got $depth", depth < 20_000) + assertEquals("should report the honest budget-derived value", 5_835, depth) } @Test @@ -154,14 +158,15 @@ class SiloLoadControlTest { } @Test - fun `composed sizing clamps depth to the floor and bytes to the budget ceiling`() { + fun `composed sizing derives depth from the budget and sizes bytes just under the ceiling`() { // A 40 Mbps stream on a 48 MiB budget cannot hold the 180s the policy - // asks for, nor even the 20s floor (affordable is ~10s), so depth - // clamps to the floor. The resulting byte target is then sized from - // that clamped depth and clamps to the budget, not the (distinct) - // fallback — this exercises the exact composition - // calculateTargetBufferBytes wires together, unlike the free-standing - // affordableDepthMs/calculateBitrateTargetBufferBytes tests above. + // asks for; the budget-derived depth (~8.75s, once the overhead + // margin is accounted for) is neither the request nor the 20s floor. + // The resulting byte target is sized from that depth and lands at or + // just under the budget — not the (distinct) fallback — which is + // exactly what proves the depth actually determines the bytes, + // rather than both overshooting and clamping to the same ceiling + // regardless of which depth was used. val budgetBytes = 48 * 1024 * 1024 val fallbackBytes = 30 * 1024 * 1024 // distinct from budgetBytes: catches a maximumBytes mix-up val result = @@ -174,8 +179,37 @@ class SiloLoadControlTest { unknownBitrateFallbackBytes = fallbackBytes, ) - assertEquals("depth should clamp to the floor", PlaybackBufferPolicy.MIN_DEPTH_MS, result.depthMs) - assertEquals("byte target should clamp to the budget ceiling, not the fallback", budgetBytes, result.targetBytes) + assertEquals("depth should be the honest budget-derived value", 8_753, result.depth.ms) + assertTrue( + "byte target ${result.target.bytes} should not exceed the budget $budgetBytes", + result.target.bytes <= budgetBytes, + ) + assertTrue( + "byte target ${result.target.bytes} should land just under the budget, not clamp to it", + result.target.bytes > budgetBytes - (budgetBytes / 50), + ) + } + + @Test + fun `composed sizing reports the true budget-limited depth, not just a clamped byte target`() { + // Both a correctly-routed depth and an un-routed, un-reduced one can + // produce the same clamped byte target once the byte clamp is hit — + // that erasure is exactly how a wiring bug that never routes the + // affordable depth into the byte calculation went undetected. This + // asserts the depth itself, which is the only place such a bug is + // visible: 60 Mbps against a 48 MiB budget affords ~5.8s once the + // overhead margin is accounted for. + val result = + computeBufferSizing( + selectedBitrateBps = 60_000_000L, + desiredDepthMs = PlaybackBufferPolicy.MAX_DEPTH_MS, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + budgetBytes = 48 * 1024 * 1024, + minimumBytes = SiloLoadControl.MIN_TARGET_BUFFER_BYTES, + unknownBitrateFallbackBytes = 48 * 1024 * 1024, + ) + + assertEquals("depth should be the true budget-limited value", 5_835, result.depth.ms) } @Test @@ -194,8 +228,8 @@ class SiloLoadControlTest { unknownBitrateFallbackBytes = fallbackBytes, ) - assertEquals("depth should pass through unchanged", 120_000, result.depthMs) - assertEquals("byte target should route the fallback", fallbackBytes, result.targetBytes) + assertEquals("depth should pass through unchanged", 120_000, result.depth.ms) + assertEquals("byte target should route the fallback", fallbackBytes, result.target.bytes) } @Test @@ -214,8 +248,8 @@ class SiloLoadControlTest { ) assertTrue( - "depth ${result.depthMs} exceeded requested $desiredDepthMs", - result.depthMs <= desiredDepthMs, + "depth ${result.depth.ms} exceeded requested $desiredDepthMs", + result.depth.ms <= desiredDepthMs, ) } } From 6000128ee26cea97da03193cd67bbcef310fd7eb Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 09:01:58 +0200 Subject: [PATCH 08/11] fix(playback): half-heap memory budget, low-RAM proportional floor, speed-derived idle window, structural invariant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final fix wave from whole-branch review ("No — with fixes"): 1. memoryBudgetBytes now takes half the heap, not a quarter. Measured via adb: Shield memoryClass=192MB, Google TV Streamer memoryClass=384MB, neither low-RAM. The old 25% rule gave both LESS buffer than they shipped with before this branch existed; half gives Shield 96 MiB and Streamer 192 MiB (at the cap), both at or above prior fixed values. 2. The low-RAM branch no longer ignores a known small memoryClass: it now takes the smaller of the flat 24 MiB fallback and the proportional share, falling back to the flat value only when memoryClassMb is genuinely unknown (<= 0). 3. MAX_LOAD_IDLE_MS is now derived from the slowest selectable playback rate (0.5x, shared by audiobooks): 15_000ms media time so the window still fits the assumed 60s proxy send_timeout once stretched to wall clock at 0.5x, where DefaultLoadControl does not scale minBufferUs. 4. PlaybackBufferPolicy's init now requires maxBufferMs - minBufferMs == MAX_LOAD_IDLE_MS, so the invariant can't be reintroduced by hand via the public constructor or copy(). 5. Removed a vacuous SiloLoadControlTest case that was algebraically true regardless of what affordableDepthMs returned. 6. computeBufferSizing now coerces maximumBytes to be at least minimumBytes before calling calculateBitrateTargetBufferBytes, so a future change to either MIN_MEMORY_BUDGET_BYTES or MIN_TARGET_BUFFER_BYTES can't trigger an IllegalArgumentException on the playback thread. Verified: ./gradlew :android-shared:testDebugUnitTest (1,005 tests, 0 failures) and :androidApp:assembleDebug :androidTvApp:assembleDebug both green. Co-Authored-By: Claude Opus 5 (1M context) --- .../common/player/PlaybackBufferPolicy.kt | 85 ++++++++++++-- .../silo/common/player/SiloLoadControl.kt | 10 +- .../common/player/PlaybackBufferPolicyTest.kt | 110 ++++++++++++++++-- .../silo/common/player/SiloLoadControlTest.kt | 16 --- 4 files changed, 181 insertions(+), 40 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt index 0f8df2fa96..bdfb792e88 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt @@ -13,21 +13,53 @@ 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 { /** - * How long the load control may stop reading the socket. + * 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. Upstream proxies close - * an idle response body: nginx's send_timeout defaults to 60s. The old + * 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 = 30_000 + 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 @@ -75,22 +107,49 @@ data class PlaybackBufferPolicy( * 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) { - return LOW_RAM_MEMORY_BUDGET_BYTES + // 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 } - val proportionalBytes = - deviceProfile.memoryClassMb.toLong() * MIB / MEMORY_BUDGET_HEAP_DIVISOR - return proportionalBytes + 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/4) of the app heap — see [memoryBudgetBytes]. */ - private const val MEMORY_BUDGET_HEAP_DIVISOR = 4L + /** 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 @@ -101,8 +160,10 @@ data class PlaybackBufferPolicy( /** * Fixed fallback for devices that report no usable heap size, or that * flag themselves as low-RAM outright — conservative rather than - * proportional, since a quarter of an unknown or explicitly - * constrained heap is not a number worth trusting. + * 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 } diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt index 03ecb91527..7fb47c0976 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt @@ -178,7 +178,15 @@ internal fun computeBufferSizing( selectedBitrateBps = selectedBitrateBps, desiredForwardBufferMs = depthMs, minimumBytes = minimumBytes, - maximumBytes = budgetBytes, + // 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. Coercing here means + // this call can never violate the relation regardless of how + // budgetBytes and minimumBytes drift relative to each other. + maximumBytes = budgetBytes.coerceAtLeast(minimumBytes), unknownBitrateFallbackBytes = unknownBitrateFallbackBytes, ) return BufferSizingResult(depth = BufferDepthMs(depthMs), target = BufferTargetBytes(targetBytes)) diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt index 0e7e09e4af..4c5808ac8d 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt @@ -2,6 +2,7 @@ package org.siloserver.silo.common.player import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertTrue class PlaybackBufferPolicyTest { @@ -35,6 +36,27 @@ class PlaybackBufferPolicyTest { ) } + // The idle window is expressed in MEDIA time, but a proxy's send_timeout + // measures WALL CLOCK time, and DefaultLoadControl only scales + // minBufferUs for speeds ABOVE 1.0 — not below it. Audiobooks share this + // load control and the UI offers rates down to + // PlaybackBufferPolicy.SLOWEST_PLAYBACK_SPEED (0.5x), where one + // media-time second of idle window takes two wall-clock seconds. This + // asserts the window still fits inside the assumed proxy timeout once + // stretched by that slowest rate, not just at 1.0x. + @Test + fun `idle window still fits the proxy timeout once stretched by the slowest playback speed`() { + val stretchedWallClockMs = + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS / PlaybackBufferPolicy.SLOWEST_PLAYBACK_SPEED + + assertTrue( + stretchedWallClockMs <= PlaybackBufferPolicy.ASSUMED_PROXY_SEND_TIMEOUT_MS, + "idle window ($stretchedWallClockMs ms wall clock at " + + "${PlaybackBufferPolicy.SLOWEST_PLAYBACK_SPEED}x) should still fit inside the " + + "assumed proxy timeout (${PlaybackBufferPolicy.ASSUMED_PROXY_SEND_TIMEOUT_MS} ms)", + ) + } + @Test fun `playback starts on a small cushion and recovers quickly after a stall`() { val policy = PlaybackBufferPolicy.forConditions(roomy) @@ -64,18 +86,34 @@ class PlaybackBufferPolicyTest { } @Test - fun `a small heap gets well under half its heap as a buffer budget`() { - // A fixed tier this small would starve the device (48 MiB was half of - // a 96 MB heap before this became proportional). 1/4 of the heap must - // land far short of half of it. + fun `a small heap gets exactly half its heap as a buffer budget`() { + // Product ruling: half the heap, not a quarter. A quarter-heap rule + // gives a 96 MB heap only 24 MiB — the exact fixed floor this policy + // replaced, not an improvement on it. val smallHeap = PlaybackBufferDeviceProfile(memoryClassMb = 96, isLowRamDevice = false) val budgetBytes = PlaybackBufferPolicy.memoryBudgetBytes(smallHeap) val halfHeapBytes = (smallHeap.memoryClassMb * 1024 * 1024) / 2 - assertTrue( - budgetBytes <= halfHeapBytes / 2, - "budget $budgetBytes should be well under half the heap ($halfHeapBytes)", - ) + assertEquals(halfHeapBytes, budgetBytes) + } + + @Test + fun `NVIDIA Shield measured memoryClass gets half its heap, not a quarter`() { + // Measured via adb: the Shield reports memoryClass=192MB and is not + // flagged low-RAM. Under a quarter-heap rule it would get 48 MiB — + // LESS than the 96 MiB it shipped with before this policy existed. + val shield = PlaybackBufferDeviceProfile(memoryClassMb = 192, isLowRamDevice = false) + + assertEquals(96 * 1024 * 1024, PlaybackBufferPolicy.memoryBudgetBytes(shield)) + } + + @Test + fun `Google TV Streamer measured memoryClass hits the ceiling at half its heap`() { + // Measured via adb: the Streamer reports memoryClass=384MB and is + // not flagged low-RAM. Half of that is exactly the 192 MiB ceiling. + val streamer = PlaybackBufferDeviceProfile(memoryClassMb = 384, isLowRamDevice = false) + + assertEquals(192 * 1024 * 1024, PlaybackBufferPolicy.memoryBudgetBytes(streamer)) } @Test @@ -96,9 +134,59 @@ class PlaybackBufferPolicyTest { } @Test - fun `a low-RAM device gets the conservative fixed fallback, not a proportional share`() { - val budgetBytes = PlaybackBufferPolicy.memoryBudgetBytes(lowRam) + fun `a low-RAM device with an unknown heap gets the conservative fixed fallback`() { + val unknownHeapLowRam = PlaybackBufferDeviceProfile(memoryClassMb = 0, isLowRamDevice = true) - assertEquals(24 * 1024 * 1024, budgetBytes) + assertEquals(24 * 1024 * 1024, PlaybackBufferPolicy.memoryBudgetBytes(unknownHeapLowRam)) + } + + @Test + fun `a low-RAM device with a small known heap gets the smaller of the flat fallback and its proportional share`() { + // A low-RAM stick reporting a small but genuinely known memoryClass + // must not have that number thrown away in favor of the flat 24 MiB + // fallback — that would be the exact flaw (a fixed value ignoring + // what the device actually reports) the proportional rule exists to + // remove. 48MB is a real memoryClass a low-RAM device could report; + // half of it (24 MiB) ties the flat fallback, so use a heap small + // enough that the proportional share is strictly smaller. + val smallKnownHeapLowRam = + PlaybackBufferDeviceProfile(memoryClassMb = 32, isLowRamDevice = true) + val proportionalBytes = (32 * 1024 * 1024) / 2 + + assertTrue(proportionalBytes < 24 * 1024 * 1024, "test heap must undercut the flat fallback") + assertEquals( + proportionalBytes, + PlaybackBufferPolicy.memoryBudgetBytes(smallKnownHeapLowRam), + ) + } + + @Test + fun `a low-RAM device with a larger known heap is still capped at the flat fallback`() { + // The flat 24 MiB fallback must still act as a ceiling on the + // low-RAM path: a low-RAM device reporting a heap large enough that + // half of it exceeds 24 MiB must not get more than the conservative + // fallback just because isLowRamDevice happened to be paired with a + // roomier-looking memoryClass. + val largerKnownHeapLowRam = + PlaybackBufferDeviceProfile(memoryClassMb = 96, isLowRamDevice = true) + + assertEquals( + 24 * 1024 * 1024, + PlaybackBufferPolicy.memoryBudgetBytes(largerKnownHeapLowRam), + ) + } + + @Test + fun `constructing a policy with a wider idle window than MAX_LOAD_IDLE_MS throws`() { + assertFailsWith { + PlaybackBufferPolicy( + minBufferMs = 50_000, + maxBufferMs = 120_000, + bufferForPlaybackMs = 2_000, + bufferForPlaybackAfterRebufferMs = 5_000, + targetBufferBytes = 16 * 1024 * 1024, + prioritizeTimeOverSizeThresholds = false, + ) + } } } diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt index e963f71e25..a3a884de24 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt @@ -141,22 +141,6 @@ class SiloLoadControlTest { assertEquals(120_000, depth) } - @Test - fun `reducing depth never widens the idle window`() { - // The invariant has to survive the reduction: whatever depth the budget - // affords, max is still exactly one idle window above it. - val depth = - affordableDepthMs( - desiredDepthMs = 180_000, - selectedBitrateBps = 80_000_000L, - budgetBytes = 48 * 1024 * 1024, - minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, - ) - val max = depth + PlaybackBufferPolicy.MAX_LOAD_IDLE_MS - - assertEquals(PlaybackBufferPolicy.MAX_LOAD_IDLE_MS, max - depth) - } - @Test fun `composed sizing derives depth from the budget and sizes bytes just under the ceiling`() { // A 40 Mbps stream on a 48 MiB budget cannot hold the 180s the policy From cab938fa5cd7ef99973c5a8cbaefd721add91d48 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 10:08:46 +0200 Subject: [PATCH 09/11] fix(player): keep the memory budget authoritative when it is below the byte floor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit calculateBitrateTargetBufferBytes requires maximumBytes >= minimumBytes. That relation was being restored by raising the ceiling to meet the floor, which inverts the intent: a device whose budget is under the nominal 16 MiB floor would be handed a byte target larger than the heap it was allowed. Restore it by lowering the floor instead, so the budget stays the binding limit on every path including the unknown-bitrate fallback. Unreachable on shipping hardware today — MIN_MEMORY_BUDGET_BYTES and MIN_TARGET_BUFFER_BYTES are both exactly 16 MiB — which is precisely why it needs a regression test rather than a comment. Also corrects doc drift: the spec and plan still described MAX_LOAD_IDLE_MS as 30_000 and the 20s depth floor as a guarantee. The constant became 15_000 (the 30s wall-clock budget divided by the 0.5x audiobook rate), and the floor is deliberately not a guarantee — a known bitrate whose budget funds less than 20s yields the honest smaller number, which is the whole point of making the reduction explicit. Co-Authored-By: Claude Opus 5 (1M context) --- .../silo/common/player/SiloLoadControl.kt | 12 ++++--- .../silo/common/player/SiloLoadControlTest.kt | 30 ++++++++++++++++ ...2026-07-30-playback-buffer-architecture.md | 18 ++++++---- ...-30-playback-buffer-architecture-design.md | 34 ++++++++++++------- 4 files changed, 70 insertions(+), 24 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt index 7fb47c0976..a8f028360e 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt @@ -177,16 +177,18 @@ internal fun computeBufferSizing( calculateBitrateTargetBufferBytes( selectedBitrateBps = selectedBitrateBps, desiredForwardBufferMs = depthMs, - minimumBytes = minimumBytes, // 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. Coercing here means - // this call can never violate the relation regardless of how - // budgetBytes and minimumBytes drift relative to each other. - maximumBytes = budgetBytes.coerceAtLeast(minimumBytes), + // 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, ) return BufferSizingResult(depth = BufferDepthMs(depthMs), target = BufferTargetBytes(targetBytes)) diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt index a3a884de24..730fdc7fc8 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt @@ -236,4 +236,34 @@ class SiloLoadControlTest { result.depth.ms <= desiredDepthMs, ) } + + @Test + fun `composed sizing keeps the budget authoritative when it is below the nominal byte floor`() { + // MIN_TARGET_BUFFER_BYTES and the policy's memory floor are both + // 16 MiB today, so nothing on shipping hardware reaches this case. + // A future change to either constant could separate them, and the + // relation must then be restored by lowering the floor, not raising + // the ceiling: a device allowed 8 MiB must get 8 MiB, not the 16 MiB + // floor its heap cannot hold. Both a known and an unknown bitrate are + // exercised, since the unknown path routes a caller-supplied fallback + // that is itself larger than the budget here. + val budgetBytes = 8 * 1024 * 1024 + + for (bitrate in listOf(6_000_000L, null)) { + val result = + computeBufferSizing( + selectedBitrateBps = bitrate, + desiredDepthMs = PlaybackBufferPolicy.MAX_DEPTH_MS, + minimumDepthMs = PlaybackBufferPolicy.MIN_DEPTH_MS, + budgetBytes = budgetBytes, + minimumBytes = SiloLoadControl.MIN_TARGET_BUFFER_BYTES, + unknownBitrateFallbackBytes = 40 * 1024 * 1024, + ) + + assertTrue( + "byte target ${result.target.bytes} exceeded the budget $budgetBytes at bitrate $bitrate", + result.target.bytes <= budgetBytes, + ) + } + } } diff --git a/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md b/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md index 7a93e5b89e..301e3ad708 100644 --- a/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md +++ b/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md @@ -12,8 +12,8 @@ ## Global Constraints -- **The invariant is the point of this work:** `maxBufferMs == minBufferMs + MAX_LOAD_IDLE_MS`, always, for every reachable policy including after the memory budget reduces depth. `MAX_LOAD_IDLE_MS = 30_000`. -- **Depth bounds:** floor `20_000` ms, ceiling `180_000` ms. +- **The invariant is the point of this work:** `maxBufferMs == minBufferMs + MAX_LOAD_IDLE_MS`, always, for every reachable policy including after the memory budget reduces depth. `MAX_LOAD_IDLE_MS = 15_000` — a 30s wall-clock budget divided by the slowest selectable playback rate (0.5x, offered for audiobooks, which share this load control and which `DefaultLoadControl` does not scale for). +- **Depth bounds:** requested floor `20_000` ms, ceiling `180_000` ms. The floor is where depth starts, not a guarantee: a known bitrate whose budget funds less than 20s yields the smaller number rather than a claimed depth memory cannot hold. - **Startup:** `bufferForPlaybackMs = 2_000`, `bufferForPlaybackAfterRebufferMs = 5_000`. - **No user setting, no server-driven wire value.** `PlaybackBufferMode` and its `fromWire` are deleted, not repurposed. - **No transcode/HLS special case.** One policy; throughput governs. The server's `TranscodeThrottler` owns the transcode-ahead ceiling. @@ -34,7 +34,7 @@ This task alone fixes the reported dropped connections. - Test: `android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt` **Interfaces:** -- Produces: `PlaybackBufferPolicy.forConditions(deviceProfile: PlaybackBufferDeviceProfile): PlaybackBufferPolicy`, plus companion constants `MAX_LOAD_IDLE_MS = 30_000`, `MIN_DEPTH_MS = 20_000`, `MAX_DEPTH_MS = 180_000`, `ASSUMED_PROXY_SEND_TIMEOUT_MS = 60_000`. The `PlaybackBufferPolicy` data class keeps its existing six fields unchanged. +- Produces: `PlaybackBufferPolicy.forConditions(deviceProfile: PlaybackBufferDeviceProfile): PlaybackBufferPolicy`, plus companion constants `MAX_LOAD_IDLE_MS = 15_000`, `MIN_DEPTH_MS = 20_000`, `MAX_DEPTH_MS = 180_000`, `ASSUMED_PROXY_SEND_TIMEOUT_MS = 60_000`. The `PlaybackBufferPolicy` data class keeps its existing six fields unchanged. - Removes: `PlaybackBufferMode` (whole enum, including `fromWire`) and `PlaybackBufferPolicy.forMode(...)`. `PlaybackBufferDeviceProfile` stays exactly as it is. - [ ] **Step 1: Write the failing tests** @@ -148,12 +148,16 @@ data class PlaybackBufferPolicy( * 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 = 30_000 + const val MAX_LOAD_IDLE_MS = 15_000 - /** The timeout MAX_LOAD_IDLE_MS is chosen to stay clear of. */ + /** + * The timeout MAX_LOAD_IDLE_MS is chosen to stay clear of. The window is + * this budgeted down to 30s and then divided by SLOWEST_PLAYBACK_SPEED, + * because the invariant is in media time and a proxy measures wall clock. + */ const val ASSUMED_PROXY_SEND_TIMEOUT_MS = 60_000 - /** Never buffer less than this, however constrained the device. */ + /** The depth the policy asks for before the memory budget has its say. */ const val MIN_DEPTH_MS = 20_000 /** @@ -250,7 +254,7 @@ git commit -m "fix(playback): bound the load-idle window so proxies stop droppin **Interfaces:** - Consumes: `PlaybackBufferPolicy.MIN_DEPTH_MS`, `PlaybackBufferPolicy.MAX_LOAD_IDLE_MS` (Task 1); the existing internal helpers `selectBufferSizingBitrateBps(...)` and `calculateBitrateTargetBufferBytes(...)`, both unchanged. -- Produces: `internal fun affordableDepthMs(desiredDepthMs: Int, selectedBitrateBps: Long?, budgetBytes: Int, minimumDepthMs: Int): Int` — the depth the budget can actually fund, never below `minimumDepthMs`, never above `desiredDepthMs`. +- Produces: `internal fun affordableDepthMs(desiredDepthMs: Int, selectedBitrateBps: Long?, budgetBytes: Int, minimumDepthMs: Int): Int` — the depth the budget can actually fund, never above `desiredDepthMs`. `minimumDepthMs` is the floor only on the unknown-bitrate path, where there is nothing to size from; with a known bitrate the helper returns the true affordable depth even when that is below `minimumDepthMs`, since claiming the floor would reinstate exactly the silent overrun this task removes. **Context an implementer needs:** today `calculateTargetBufferBytes` clamps bytes to the budget and stops there, so on a 60 Mbps remux the loader quietly stops at whatever the cap affords (about 5s on a low-RAM device) while the policy still claims a much larger depth. The fix is not to raise the cap — memory is genuinely finite — but to make the reduction explicit, so the resulting depth is a number the code chose rather than an accident. diff --git a/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md b/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md index 2b93b4d5e0..603701c316 100644 --- a/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md +++ b/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md @@ -48,14 +48,19 @@ Taken in conversation with Jim: `maxBufferMs` stops being a free parameter: -``` +```text maxBufferMs = minBufferMs + MAX_LOAD_IDLE_MS ``` -`MAX_LOAD_IDLE_MS = 30_000`, chosen to sit well under the assumed 60s upstream -proxy `send_timeout`. The assumed timeout is a named constant with its -reasoning beside it, so a deployment behind a 30s proxy has an obvious dial -rather than a mystery. +`MAX_LOAD_IDLE_MS = 15_000`, which is a 30s wall-clock budget divided by the +slowest selectable playback rate. The 30s budget sits well under the assumed +60s upstream proxy `send_timeout`, but the invariant is expressed in *media* +time while a proxy measures *wall clock*, and `DefaultLoadControl` scales +`minBufferUs` only for speeds above 1.0. Audiobooks offer 0.5x and share this +load control, so a 30s media window would stretch to 60s of wall clock — +exactly the timeout. The assumed timeout and the slowest rate are both named +constants with their reasoning beside them, so a deployment behind a 30s proxy +has an obvious dial rather than a mystery. This makes the failure structurally unrepresentable: no matter how deep the buffer grows, the socket cannot idle long enough to be dropped. Depth is @@ -67,9 +72,13 @@ Depth grows toward a ceiling, bounded by: - **Memory budget** — bytes needed = target seconds × observed bitrate, clamped to a fraction of the app heap. When the budget cannot fund the target - seconds, the *target seconds are reduced explicitly* to what fits, never - below a **20s floor**. `maxBufferMs` follows `min` down, so the idle window - only ever shrinks. + seconds, the *target seconds are reduced explicitly* to what fits. + **20s is the policy's requested floor, not a guarantee:** it is where depth + starts when nothing constrains it, but a known bitrate high enough that the + budget funds less than 20s yields the smaller, honest number. Raising it back + to 20s would only mean claiming a depth the memory cannot hold — which is the + silent overrun this work exists to remove. `maxBufferMs` follows `min` down, + so the idle window only ever shrinks. - **Delivery throughput** — the bandwidth meter already reports delivery rate. Delivery ≫ media bitrate means the source can outrun playback (direct file, or a fast/GPU transcode) and depth may extend. Delivery ≈ bitrate means the @@ -105,7 +114,7 @@ progressive direct play — which is exactly where the reported drops occur. | | Start | After stall | Depth (min) | Idle window | |---|---|---|---|---| -| All delivery | 2s | 5s | 20s floor → 180s ceiling, memory/throughput governed | 30s | +| All delivery | 2s | 5s | 20s requested floor → 180s ceiling, memory/throughput governed | 15s media (30s wall clock at 0.5x) | Start drops 3s → 2s. Stall recovery drops 10s → 5s: after a stall the user is watching a spinner, and ten seconds is a long time to withhold the picture for @@ -131,10 +140,11 @@ high-risk behaviour only: - The idle-window invariant holds for every reachable policy — including after the memory budget has forced depth down. -- Seconds-fit-to-budget reduction, and the 20s floor holding on a low-RAM device - with a 60 Mbps stream. +- Seconds-fit-to-budget reduction on a low-RAM device with a 60 Mbps stream: + the reported depth is the honest sub-floor number the budget funds, not the + 20s the policy asked for. - The 180s ceiling holding when memory would allow more. -- A regression pinning `max − min ≤ 30s`, since that is the property that +- A regression pinning `max − min == MAX_LOAD_IDLE_MS`, since that is the property that prevents the dropped connections. ## Out of scope From 4bb5b2a5c143d8a762771de84bcb5192eecd17fc Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 10:10:22 +0200 Subject: [PATCH 10/11] test(player): make the idle-window guard strict so it fails on a revert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The assertion was `stretchedWallClockMs <= ASSUMED_PROXY_SEND_TIMEOUT_MS`. Reverting MAX_LOAD_IDLE_MS to the pre-fix 30_000 yields 60_000 <= 60_000, so the one test whose job is to catch that revert passed through it — a guard that cannot fail is not a guard. Strict is also the correct statement of the property: a socket idle for exactly the timeout is a race, not a fit. Verified by temporarily setting the constant back to 30_000, where the test now fails. Co-Authored-By: Claude Opus 5 (1M context) --- .../silo/common/player/PlaybackBufferPolicyTest.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt index 4c5808ac8d..1146a4d8d9 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt @@ -44,13 +44,20 @@ class PlaybackBufferPolicyTest { // media-time second of idle window takes two wall-clock seconds. This // asserts the window still fits inside the assumed proxy timeout once // stretched by that slowest rate, not just at 1.0x. + // + // The comparison is strict on purpose. Equality is not "fits" — a socket + // that goes quiet for exactly the timeout is a race the proxy wins about + // as often as we do. It also matters for what this test is FOR: with a + // non-strict comparison, reverting MAX_LOAD_IDLE_MS to the pre-fix 30_000 + // gives 60_000 <= 60_000 and the guard passes, silently readmitting the + // exact bug this work removed. @Test fun `idle window still fits the proxy timeout once stretched by the slowest playback speed`() { val stretchedWallClockMs = PlaybackBufferPolicy.MAX_LOAD_IDLE_MS / PlaybackBufferPolicy.SLOWEST_PLAYBACK_SPEED assertTrue( - stretchedWallClockMs <= PlaybackBufferPolicy.ASSUMED_PROXY_SEND_TIMEOUT_MS, + stretchedWallClockMs < PlaybackBufferPolicy.ASSUMED_PROXY_SEND_TIMEOUT_MS, "idle window ($stretchedWallClockMs ms wall clock at " + "${PlaybackBufferPolicy.SLOWEST_PLAYBACK_SPEED}x) should still fit inside the " + "assumed proxy timeout (${PlaybackBufferPolicy.ASSUMED_PROXY_SEND_TIMEOUT_MS} ms)", From 3404f0fa09ddcd6d7a9042fefd739ff31842fbd5 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Thu, 30 Jul 2026 12:48:40 +0200 Subject: [PATCH 11/11] docs(player): correct the MAX_LOAD_IDLE_MS derivation and the stale plan snippets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two things CodeRabbit caught on the re-review, both mine. The derivation was written backwards in prose: "a 30s wall-clock budget divided by the slowest playback rate" computes 60_000, not 15_000. The window is in media time and converts TO wall clock by dividing, so deriving the constant multiplies: 30_000 * 0.5 = 15_000. The shipped source comment had it right (30_000 * SLOWEST_PLAYBACK_SPEED); the spec, the plan, and the plan's own code comment did not. The plan also still carried the pre-fix affordableDepthMs: a test asserting `assertEquals(20_000, depth, "should clamp to the floor, not below it")` and an implementation using coerceIn(minimumDepthMs, ...) with no overhead margin. That is exactly the behaviour the review loop removed — anyone re-running the plan would have reimplemented the silent overrun. Both snippets now match the shipped code, including why the known-bitrate path is deliberately not floored. Docs only; no source change. Suite green. Co-Authored-By: Claude Opus 5 (1M context) --- ...2026-07-30-playback-buffer-architecture.md | 37 +++++++++++++------ ...-30-playback-buffer-architecture-design.md | 4 +- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md b/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md index 301e3ad708..167e6d2dcd 100644 --- a/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md +++ b/docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md @@ -12,7 +12,7 @@ ## Global Constraints -- **The invariant is the point of this work:** `maxBufferMs == minBufferMs + MAX_LOAD_IDLE_MS`, always, for every reachable policy including after the memory budget reduces depth. `MAX_LOAD_IDLE_MS = 15_000` — a 30s wall-clock budget divided by the slowest selectable playback rate (0.5x, offered for audiobooks, which share this load control and which `DefaultLoadControl` does not scale for). +- **The invariant is the point of this work:** `maxBufferMs == minBufferMs + MAX_LOAD_IDLE_MS`, always, for every reachable policy including after the memory budget reduces depth. `MAX_LOAD_IDLE_MS = 15_000` — a 30s wall-clock budget scaled *down* by the slowest selectable playback rate: `30_000 * 0.5`. (0.5x is offered for audiobooks, which share this load control and which `DefaultLoadControl` does not scale for. Media time converts back to wall clock by dividing: `15_000 / 0.5 = 30_000`.) - **Depth bounds:** requested floor `20_000` ms, ceiling `180_000` ms. The floor is where depth starts, not a guarantee: a known bitrate whose budget funds less than 20s yields the smaller number rather than a claimed depth memory cannot hold. - **Startup:** `bufferForPlaybackMs = 2_000`, `bufferForPlaybackAfterRebufferMs = 5_000`. - **No user setting, no server-driven wire value.** `PlaybackBufferMode` and its `fromWire` are deleted, not repurposed. @@ -152,7 +152,8 @@ data class PlaybackBufferPolicy( /** * The timeout MAX_LOAD_IDLE_MS is chosen to stay clear of. The window is - * this budgeted down to 30s and then divided by SLOWEST_PLAYBACK_SPEED, + * this budgeted down to 30s of wall clock and then multiplied by + * SLOWEST_PLAYBACK_SPEED to express it in media time, * because the invariant is in media time and a proxy measures wall clock. */ const val ASSUMED_PROXY_SEND_TIMEOUT_MS = 60_000 @@ -264,9 +265,13 @@ Append to `SiloLoadControlTest`: ```kotlin @Test - fun `depth shrinks to what the memory budget can fund`() { - // 60 Mbps against a 48 MiB budget: 48 MiB * 8 / 60 Mbps ~= 6.7s, so the - // requested 180s cannot be held and the depth must come down to fit. + fun `depth follows the budget honestly, even below the floor`() { + // 60 Mbps against a 48 MiB budget: accounting for the same 15% + // overhead margin calculateBitrateTargetBufferBytes applies when it + // turns this depth back into bytes, the budget only really affords + // ~5.8s. The requested 180s cannot be held, and neither can the 20s + // floor — the budget wins over the floor because a false, rounded-up + // report would be worse than an honest shortfall. val depth = affordableDepthMs( desiredDepthMs = 180_000, @@ -275,8 +280,8 @@ Append to `SiloLoadControlTest`: minimumDepthMs = 20_000, ) - assertTrue(depth < 180_000, "expected reduction, got $depth") - assertEquals(20_000, depth, "should clamp to the floor, not below it") + assertTrue(depth < 20_000, "expected reduction below the floor, got $depth") + assertEquals(5_835, depth, "should report the honest budget-derived value") } @Test @@ -353,11 +358,19 @@ internal fun affordableDepthMs( budgetBytes: Int, minimumDepthMs: Int, ): Int { - val bitrate = selectedBitrateBps?.takeIf { it > 0L } ?: return desiredDepthMs - val affordableMs = budgetBytes.toLong() * 8L * 1_000L / bitrate - return affordableMs - .coerceIn(minimumDepthMs.toLong(), desiredDepthMs.toLong()) - .toInt() + val bitrate = selectedBitrateBps?.takeIf { it > 0L } + ?: return desiredDepthMs.coerceAtLeast(minimumDepthMs) + // The 115/100 mirrors the 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 and clamps back to the ceiling, + // erasing the depth's effect on the byte target entirely. + val affordableMs = budgetBytes.toLong() * 8L * 1_000L * 100L / (bitrate * 115L) + // Deliberately NOT coerced up to minimumDepthMs: with a known bitrate the + // honest budget-derived depth wins over the floor, since claiming a depth + // the loader cannot hold is the exact silent overrun this task removes. + // minimumDepthMs bounds only the unknown-bitrate branch above. + return affordableMs.coerceAtMost(desiredDepthMs.toLong()).toInt() } ``` diff --git a/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md b/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md index 603701c316..7f5d2e3b15 100644 --- a/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md +++ b/docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md @@ -52,8 +52,8 @@ Taken in conversation with Jim: maxBufferMs = minBufferMs + MAX_LOAD_IDLE_MS ``` -`MAX_LOAD_IDLE_MS = 15_000`, which is a 30s wall-clock budget divided by the -slowest selectable playback rate. The 30s budget sits well under the assumed +`MAX_LOAD_IDLE_MS = 15_000`, which is a 30s wall-clock budget scaled *down* by +the slowest selectable playback rate (`30_000 * 0.5`). The 30s budget sits well under the assumed 60s upstream proxy `send_timeout`, but the invariant is expressed in *media* time while a proxy measures *wall clock*, and `DefaultLoadControl` scales `minBufferUs` only for speeds above 1.0. Audiobooks offer 0.5x and share this