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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -725,11 +725,29 @@ class SiloPlayerFactory(
// A sidecar must not decide when playback starts or what loads
// next — left as a plain merged child it starves the video until
// its own download reaches the resume point. See the wrapper.
return SidecarSubtitleMediaSource(progressive, playbackFloor)
// A PGS sidecar also reads only a bounded stretch ahead: each of
// its cues carries a caption image, and a whole film of them does
// not fit in a phone's heap.
return SidecarSubtitleMediaSource(
progressive,
playbackFloor,
maxLookaheadUs = if (configuration.mimeType == MimeTypes.APPLICATION_PGS) {
PGS_SIDECAR_LOOKAHEAD_US
} else {
C.TIME_UNSET
},
)
}
}

private companion object {
/**
* Two minutes of captions ahead of the playhead. The loader can read
* one check interval (1 MiB of the file) past that before it parks,
* so a PGS sidecar holds a few MB instead of the whole film.
*/
const val PGS_SIDECAR_LOOKAHEAD_US = 120_000_000L

val replayableTextSubtitleMimeTypes = setOf(
MimeTypes.TEXT_SSA,
MimeTypes.APPLICATION_SUBRIP,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,19 @@ class SidecarPlaybackFloor {
* Captions that arrive after the playhead has passed them are the extractor's
* problem, not this class's: it publishes the live position through
* [SidecarPlaybackFloor] so a REPLACE-behaviour extractor can drop them.
*
* [maxLookaheadUs] bounds how far past the playhead the sidecar may read.
* Without it the whole file is read up front, and everything read stays in the
* sample queue until playback reaches it. That is nothing for a text sidecar,
* but a feature-length `.sup` holds tens of MB of caption images, enough to
* run a phone with a 192 MB heap out of memory. [C.TIME_UNSET] keeps the
* unbounded read.
*/
@UnstableApi
class SidecarSubtitleMediaSource(
child: MediaSource,
private val floor: SidecarPlaybackFloor,
private val maxLookaheadUs: Long = C.TIME_UNSET,
) : WrappingMediaSource(child) {

override fun createPeriod(
Expand All @@ -70,6 +78,7 @@ class SidecarSubtitleMediaSource(
): MediaPeriod = NonGatingSidecarPeriod(
mediaSource.createPeriod(id, allocator, startPositionUs),
floor,
maxLookaheadUs,
)

override fun releasePeriod(mediaPeriod: MediaPeriod) {
Expand All @@ -81,28 +90,68 @@ class SidecarSubtitleMediaSource(
internal class NonGatingSidecarPeriod(
val delegate: MediaPeriod,
private val floor: SidecarPlaybackFloor,
private val maxLookaheadUs: Long = C.TIME_UNSET,
) : MediaPeriod, MediaPeriod.Callback {

private var callback: MediaPeriod.Callback? = null

/** The delegate parked far enough ahead that it was left parked; see [continueUnlessAhead]. */
private var heldAhead = false

/** A delegate's buffered position is only defined once it has prepared. */
private var prepared = false

override fun prepare(callback: MediaPeriod.Callback, positionUs: Long) {
this.callback = callback
floor.set(positionUs)
delegate.prepare(this, positionUs)
}

override fun onPrepared(mediaPeriod: MediaPeriod) {
prepared = true
callback?.onPrepared(this)
}

override fun onContinueLoadingRequested(source: MediaPeriod) {
// The delegate parked its loader (interval reached, or a cancelled load
// finished unwinding). Nobody upstream will continue a child that
// reports nothing to load, so do it here.
kickDelegate("requested")
continueUnlessAhead("requested")
callback?.onContinueLoadingRequested(this)
}

/**
* Continues the delegate unless its queued cues already reach more than
* [maxLookaheadUs] past the playhead. A held delegate stays parked, and
* [resumeIfCaughtUp] continues it from the playback ticks once the
* playhead closes the gap.
*/
private fun continueUnlessAhead(reason: String) {
if (isAheadOfPlayhead()) {
if (!heldAhead) {
org.siloserver.silo.common.player.SubDiag.log(
"sidecar held($reason) buffered=${delegate.bufferedPositionUs / 1000}ms " +
"floor=${floor.get() / 1000}ms",
)
}
heldAhead = true
return
}
heldAhead = false
kickDelegate(reason)
}

private fun resumeIfCaughtUp() {
if (heldAhead && !isAheadOfPlayhead()) continueUnlessAhead("caught-up")
}

private fun isAheadOfPlayhead(): Boolean {
if (maxLookaheadUs == C.TIME_UNSET || !prepared) return false
val bufferedUs = delegate.bufferedPositionUs
if (bufferedUs == C.TIME_END_OF_SOURCE || bufferedUs == C.TIME_UNSET) return false
return bufferedUs - floor.get() > maxLookaheadUs
}

/**
* `ProgressiveMediaPeriod` never restarts itself: after `prepare()` it
* reads until its check interval and parks; `selectTracks` that enables a
Expand Down Expand Up @@ -153,17 +202,26 @@ internal class NonGatingSidecarPeriod(
val result = delegate.selectTracks(selections, mayRetainStreamFlags, streams, streamResetFlags, positionUs)
// Enabling the text track (a subtitle pick after start, or the first
// selection once prepared) is what makes the delegate willing to load.
if (selections.any { it != null }) kickDelegate("select")
if (selections.any { it != null }) continueUnlessAhead("select")
return result
}

override fun discardBuffer(positionUs: Long, toKeyframe: Boolean) =
/**
* Called on the playing period every playback tick, unlike
* [reevaluateBuffer], which stops once the next item starts loading. So
* this is what keeps a held sidecar reading through the end of an item.
*/
override fun discardBuffer(positionUs: Long, toKeyframe: Boolean) {
delegate.discardBuffer(positionUs, toKeyframe)
floor.set(maxOf(floor.get(), positionUs))
resumeIfCaughtUp()
}

override fun readDiscontinuity(): Long = delegate.readDiscontinuity()

override fun seekToUs(positionUs: Long): Long {
floor.set(positionUs)
heldAhead = false
val result = delegate.seekToUs(positionUs)
// An idle delegate is left reset-but-parked by a seek; a loading one is
// cancelled and comes back through onContinueLoadingRequested.
Expand Down Expand Up @@ -192,5 +250,6 @@ internal class NonGatingSidecarPeriod(
// period position — the live floor for "this cue is already history".
floor.set(positionUs)
delegate.reevaluateBuffer(positionUs)
resumeIfCaughtUp()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,106 @@ class SidecarSubtitleMediaSourceTest {
assertEquals(1_000_000L, delegate.lastSeekUs)
}

/**
* A feature-length `.sup` read in one go kept every caption image in the
* sample queue and ran a phone with a 192 MB heap out of memory. With a
* lookahead, a delegate that parks far enough ahead stays parked until
* the playback ticks show the playhead has closed the gap.
*/
@Test
fun leavesADelegateParkedWhileItIsFurtherAheadThanTheLookahead() {
val delegate = FakePeriod().apply { bufferedUs = 300_000_000L }
val floor = SidecarPlaybackFloor()
val period = NonGatingSidecarPeriod(delegate, floor, maxLookaheadUs = 120_000_000L)
val upstream = RecordingCallback()
period.prepare(upstream, 0L)
delegate.callback!!.onPrepared(delegate)

delegate.callback!!.onContinueLoadingRequested(delegate)
assertTrue(delegate.continueLoadingCalls.isEmpty())
// The merge is still told, as before.
assertSame(period, upstream.continueLoadingRequestedFrom.single())

period.discardBuffer(150_000_000L, false) // 150 s still ahead: keep holding
assertTrue(delegate.continueLoadingCalls.isEmpty())

period.discardBuffer(190_000_000L, false) // 110 s ahead: read on
assertEquals(1, delegate.continueLoadingCalls.size)
assertEquals(190_000_000L, delegate.continueLoadingCalls.single().playbackPositionUs)

period.discardBuffer(191_000_000L, false) // no longer held: no second kick
assertEquals(1, delegate.continueLoadingCalls.size)
}

@Test
fun reevaluateBufferAlsoResumesAHeldDelegate() {
val delegate = FakePeriod().apply { bufferedUs = 300_000_000L }
val period = NonGatingSidecarPeriod(delegate, SidecarPlaybackFloor(), maxLookaheadUs = 120_000_000L)
period.prepare(RecordingCallback(), 0L)
delegate.callback!!.onPrepared(delegate)
delegate.callback!!.onContinueLoadingRequested(delegate)

period.reevaluateBuffer(200_000_000L)

assertEquals(1, delegate.continueLoadingCalls.size)
}

@Test
fun aSeekAlwaysRestartsAHeldDelegateAndTheHoldStartsOver() {
val delegate = FakePeriod().apply { bufferedUs = 300_000_000L }
val period = NonGatingSidecarPeriod(delegate, SidecarPlaybackFloor(), maxLookaheadUs = 120_000_000L)
period.prepare(RecordingCallback(), 0L)
delegate.callback!!.onPrepared(delegate)
delegate.callback!!.onContinueLoadingRequested(delegate)
assertTrue(delegate.continueLoadingCalls.isEmpty())

period.seekToUs(10_000_000L)
assertEquals(1, delegate.continueLoadingCalls.size)

// The restarted read parks again within the lookahead of the new
// position: read on. Once it is too far ahead again, it holds again.
delegate.bufferedUs = 60_000_000L
delegate.callback!!.onContinueLoadingRequested(delegate)
assertEquals(2, delegate.continueLoadingCalls.size)
delegate.bufferedUs = 200_000_000L
delegate.callback!!.onContinueLoadingRequested(delegate)
assertEquals(2, delegate.continueLoadingCalls.size)
}

@Test
fun aDelegateThatHasNotPreparedIsNeverHeld() {
val delegate = FakePeriod().apply { bufferedUs = 300_000_000L }
val period = NonGatingSidecarPeriod(delegate, SidecarPlaybackFloor(), maxLookaheadUs = 120_000_000L)
period.prepare(RecordingCallback(), 0L)

delegate.callback!!.onContinueLoadingRequested(delegate)

assertEquals(1, delegate.continueLoadingCalls.size)
}

@Test
fun aFinishedDelegateIsNeverHeld() {
val delegate = FakePeriod().apply { bufferedUs = C.TIME_END_OF_SOURCE }
val period = NonGatingSidecarPeriod(delegate, SidecarPlaybackFloor(), maxLookaheadUs = 120_000_000L)
period.prepare(RecordingCallback(), 0L)
delegate.callback!!.onPrepared(delegate)

delegate.callback!!.onContinueLoadingRequested(delegate)

assertEquals(1, delegate.continueLoadingCalls.size)
}

@Test
fun withoutALookaheadTheDelegateReadsTheWholeFile() {
val delegate = FakePeriod().apply { bufferedUs = 3_000_000_000L }
val period = NonGatingSidecarPeriod(delegate, SidecarPlaybackFloor())
period.prepare(RecordingCallback(), 0L)

delegate.callback!!.onContinueLoadingRequested(delegate)

assertEquals(1, delegate.continueLoadingCalls.size)
}

@Test
fun forwardsPreparedAsItself() {
val delegate = FakePeriod()
Expand Down Expand Up @@ -167,6 +267,7 @@ class SidecarSubtitleMediaSourceTest {
var callback: MediaPeriod.Callback? = null
var loading = false
var lastSeekUs = C.TIME_UNSET
var bufferedUs = 0L
val continueLoadingCalls = mutableListOf<LoadingInfo>()
/** Models a prepared ProgressiveMediaPeriod: a new load needs a pending reset. */
var requirePendingReset = false
Expand Down Expand Up @@ -197,7 +298,7 @@ class SidecarSubtitleMediaSourceTest {
override fun getAdjustedSeekPositionUs(positionUs: Long, seekParameters: SeekParameters): Long =
positionUs

override fun getBufferedPositionUs(): Long = 0L
override fun getBufferedPositionUs(): Long = bufferedUs
override fun getNextLoadPositionUs(): Long = 0L
override fun continueLoading(loadingInfo: LoadingInfo): Boolean {
continueLoadingCalls += loadingInfo
Expand Down
Loading