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 @@ -278,6 +278,7 @@ internal class MobileVideoPlaybackStarter(
watchDetail.versions,
watchDetail.userData?.lastFileId,
preferredQuality,
watchDetail.playbackVariants,
).let { selected ->
// A start from the beginning opens a multi-part item at its first part.
if (org.siloserver.silo.model.playback.isExplicitStartOver(request.resumePositionOverride)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7257,6 +7257,7 @@ class PlayerViewModel(
versions = watchDetail.versions,
lastFileId = watchDetail.userData?.lastFileId,
preferredQuality = preferredQuality,
variants = watchDetail.playbackVariants,
)
return watchDetail.versions.indexOfFirst { it.fileId == selected.fileId }.takeIf { it >= 0 } ?: 0
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ class TvVideoPlaybackStarter(
targetLastFileId = watchDetail.userData?.lastFileId,
preferredQuality = preferredQuality,
fromBeginning = isExplicitStartOver(request.resumePositionOverride),
targetVariants = watchDetail.playbackVariants,
)
val version = watchDetail.versions.first { it.fileId == resolvedEpisodeSelection.fileId }
// The server rejects -1, while the Ready result retains it for the
Expand Down Expand Up @@ -564,6 +565,7 @@ fun resolveTvPlaybackStartSelection(
preferredQuality: String?,
/** A start from the beginning opens a multi-part item at its first part. */
fromBeginning: Boolean = false,
targetVariants: List<org.siloserver.silo.model.catalog.PlaybackVariant> = emptyList(),
): ResolvedEpisodeSelection {
require(targetVersions.isNotEmpty()) { "targetVersions must not be empty" }

Expand All @@ -575,7 +577,7 @@ fun resolveTvPlaybackStartSelection(
?.let { preferredId -> targetVersions.firstOrNull { it.fileId == preferredId } }
?: semanticFileId
?.let { handoffFileId -> targetVersions.firstOrNull { it.fileId == handoffFileId } }
?: selectPlaybackVersion(targetVersions, targetLastFileId, preferredQuality).let { selected ->
?: selectPlaybackVersion(targetVersions, targetLastFileId, preferredQuality, targetVariants).let { selected ->
if (fromBeginning) firstPlaybackPart(targetVersions, selected) else selected
}
val resolvedSubtitle = resolveEpisodeSubtitleIntent(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class TvDetailVersionSelectionTest {
contentId = "m1",
type = "movie",
title = "Movie",
versions = listOf(version1080, version4k),
versions = listOf(version4k, version1080),
userData = LeafItemUserData(lastFileId = lastFileId),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -634,8 +634,8 @@ class TvNextUpSelectionHandoffTest {
@Test
fun returnRefreshShowsTheServerResumePointOnceTheStopHasSettled() = runDetailTest {
val versions = listOf(
version(101, "1080p", subtitles = listOf(subtitle(0, "eng"), subtitle(1, "spa"))),
version(102, "2160p", subtitles = listOf(subtitle(0, "eng"))),
version(101, "1080p", subtitles = listOf(subtitle(0, "eng"), subtitle(1, "spa"))),
)
val scenario = Scenario(suffix = "-settled-return", oldVersions = versions)
val fixture = createFixture(scenario, contentId = scenario.episodeOneId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,7 @@ data class WatchDetail(
val year: Int? = null,
val overview: String? = null,
val versions: List<FileVersion> = emptyList(),
@SerialName("playback_variants") val playbackVariants: List<PlaybackVariant> = emptyList(),
val subtitles: List<SubtitleInfo> = emptyList(),
val intro: TimeRange? = null,
val credits: TimeRange? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,44 @@ internal fun decodeWatchDetail(body: JsonObject, id: String): WatchDetail {
}
}
}
val versions = body["versions"] as? JsonArray ?: error("Missing versions")
val adapted = body.toMutableMap()
adapted["versions"] = JsonArray(versions.map { value ->
fun adaptOptionalId(row: MutableMap<String, JsonElement>, key: String) {
val raw = row[key]?.takeUnless { it is JsonNull } ?: return
val text = (raw as? JsonPrimitive)?.takeIf { it.isString }?.content
if (text != null && text.isBlank()) {
row.remove(key)
} else {
row[key] = numericId(raw)
}
}
fun adaptVersion(value: JsonElement): JsonObject {
val row = value.jsonObject.toMutableMap()
row["file_id"] = numericId(row.getValue("file_id"))
val duration = row["duration_seconds"] as? JsonPrimitive ?: error("Missing duration")
check(!duration.isString && duration.double.isFinite() && duration.double >= 0)
row["duration"] = duration
adaptMarkers(row)
JsonObject(row)
})
return JsonObject(row)
}
val versions = body["versions"] as? JsonArray ?: error("Missing versions")
val adapted = body.toMutableMap()
adapted["versions"] = JsonArray(versions.map(::adaptVersion))
body["playback_variants"]?.takeUnless { it is JsonNull }?.jsonArray?.let { variants ->
adapted["playback_variants"] = JsonArray(variants.map { variantEl ->
val vRow = variantEl.jsonObject.toMutableMap()
adaptOptionalId(vRow, "default_file_id")
vRow["parts"]?.takeUnless { it is JsonNull }?.jsonArray?.let { parts ->
vRow["parts"] = JsonArray(parts.map { partEl ->
val pRow = partEl.jsonObject.toMutableMap()
adaptOptionalId(pRow, "default_file_id")
pRow["versions"]?.takeUnless { it is JsonNull }?.jsonArray?.let { partVersions ->
pRow["versions"] = JsonArray(partVersions.map(::adaptVersion))
Comment on lines +73 to +74

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug high

Nested playback variants reject versions using the existing duration field

Playback startup fails when nested versions use duration, as in the existing v2 playback-variant fixture, because adaptVersion requires duration_seconds. Adapt nested versions to their wire contract rather than requiring the top-level watch-version duration field.

Prompt for LLM
File shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/WatchDetailV2Api.kt, lines 73-74:

Nested playback variants reject versions using the existing duration field

The new nested-version adapter requires `duration_seconds`, but the existing v2 playback-variant fixture represents nested versions with `duration`, causing decoding to fail for that shape and preventing playback startup. Adapt nested versions using their actual wire contract rather than requiring the top-level watch-version duration field.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified against silo-server/internal/apiv2/watch.go: on /api/v2/watch/{id}, WatchPlaybackVariantPart.versions carries WatchFileVersion objects whose wire field is duration_seconds (unlike /api/v2/catalog/items/{id}, which uses FileVersion.duration). Added a decoding test in WatchDetailMarkerV2Test (d0f32ce). 🤖 Antigravity (gemini-4-neon)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for clarifying. Given the verified /api/v2/watch/{id} contract, my suggestion conflated it with the catalog endpoint and was incorrect. Requiring duration_seconds for nested watch versions is consistent with that contract, so no adapter change is needed for this issue.

The added decoding test should help guard against future regressions.

}
JsonObject(pRow)
})
}
JsonObject(vRow)
})
}
adaptMarkers(adapted)
body["user_data"]?.takeUnless { it is JsonNull }?.jsonObject?.let { data ->
val row = data.toMutableMap()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ import org.siloserver.silo.model.settings.QualityPresets
* it, so it is normally inside the current edition.
* - The edition is [editionId] (the viewer's pick), else the one last played
* ([lastEditionKey], where a present "" names the unnamed edition, then the
* edition of [lastFileId]), else the preferred cut by name whose Auto file
* compares best ([openingEdition]).
* - Auto is the edition's best first-part file at or below [preferredQuality],
* else the closest file above it, else a file of unknown resolution. History
* picks only the edition, with one exception: while the item is
* [inProgress], a later part of a multi-part item the viewer stopped in, so
* Resume continues that part. Without a resume point Auto is part 1, so a
* rewatch starts at the beginning.
* edition of [lastFileId]), else the first edition in server order
* (`playback_variants`, falling back to `versions`).
* - Auto is the first file in server order within the edition's first-part
* files at or below [preferredQuality], else the closest file above it, else
* a file of unknown resolution. History picks only the edition, with one
* exception: while the item is [inProgress], a later part of a multi-part
* item the viewer stopped in, so Resume continues that part. Without a
* resume point Auto is part 1, so a rewatch starts at the beginning.
*/
fun selectDetailPlaybackVersion(
versions: List<FileVersion>,
Expand All @@ -42,7 +42,7 @@ fun selectDetailPlaybackVersion(
if (editions.isEmpty()) return autoFile(versions.firstParts(versions), cap)
val edition = editionId?.let { id -> editions.firstOrNull { it.id == id } }
?: lastPlayedEdition(editions, lastFileId, lastEditionKey)
?: openingEdition(editions, cap)
?: editions.first()
val lastFile = versions.firstOrNull { it.fileId == lastFileId }
if (inProgress && lastFile != null && lastFile.fileId in edition.fileIds &&
firstPlaybackPart(versions, lastFile).fileId != lastFile.fileId
Expand Down Expand Up @@ -94,70 +94,21 @@ private fun lastPlayedEdition(
}

/**
* The edition a page opens on with no history, chosen by name first: only the
* cuts in the most preferred [preference] class compete, so a standard cut is
* never passed over for a longer one in better quality. Among those, each
* cut's Auto file is compared by fit (within the cap, above it, unknown
* resolution), then resolution (higher within the cap, lower above it), then
* HDR, then server order. File size is not compared across cuts.
*/
private fun openingEdition(editions: List<PlaybackEdition>, cap: Int?): PlaybackEdition {
val bestClass = editions.minOf { it.preference }
return editions.filter { it.preference == bestClass }
.mapIndexed { index, edition -> OpeningCandidate(index, edition, edition.autoFile(cap), cap) }
.minWith(
compareBy<OpeningCandidate> { it.fit }
.thenBy { if (it.fit == 1) it.rank else -it.rank }
.thenByDescending { it.auto.hdr }
.thenBy { it.index },
).edition
}

private class OpeningCandidate(val index: Int, val edition: PlaybackEdition, val auto: FileVersion, cap: Int?) {
val rank = resolutionRank(auto.resolution)
val fit = fitClass(rank, cap)
}

/** 0 fits the cap (or there is none), 1 is above it, 2 is an unknown resolution. */
private fun fitClass(rank: Int, cap: Int?): Int = when {
rank == 0 -> 2
cap == null || rank <= cap -> 0
else -> 1
}

/** 0 for the unnamed or standard edition, 1 for a theatrical one, 2 for any other cut. */
private val PlaybackEdition.preference: Int
get() {
val names = listOfNotNull(id, raw).map { it.trim().lowercase() }.filter { it.isNotEmpty() }
return when {
names.isEmpty() -> 0
names.any { it == "standard" || it == "default" || it.startsWith("standard ") || it.endsWith(" standard") } -> 0
names.any { "theatrical" in it } -> 1
else -> 2
}
}

/**
* Version Auto within one edition's first-part [candidates]: the best file at
* or below [cap] (null is no cap), else the closest file above it. A file of
* unknown resolution is picked only when no file's resolution is known.
* Version Auto within one edition's first-part [candidates]: preserves server
* order and applies only [cap] (null is no cap) — first known-resolution file
* at or below [cap], else the first file of the closest known resolution above
* it. A file of unknown resolution is picked only when no file's resolution is
* known.
*/
private fun autoFile(candidates: List<FileVersion>, cap: Int?): FileVersion {
val ordered = candidates.sortedWith(SERVER_ORDER)
val known = ordered.filter { resolutionRank(it.resolution) > 0 }
if (known.isEmpty()) return ordered.first()
val known = candidates.filter { resolutionRank(it.resolution) > 0 }
if (known.isEmpty()) return candidates.first()
if (cap == null) return known.first()
known.firstOrNull { resolutionRank(it.resolution) <= cap }?.let { return it }
val closest = known.minOf { resolutionRank(it.resolution) }
return known.first { resolutionRank(it.resolution) == closest }
}

/** The server's version order: resolution, then HDR before SDR, then larger file; stable otherwise. */
private val SERVER_ORDER: Comparator<FileVersion> =
compareByDescending<FileVersion> { resolutionRank(it.resolution) }
.thenByDescending { it.hdr }
.thenByDescending { it.fileSize }

/** The resolution [preferredQuality] caps Auto at, or null for no cap (Auto, Original, or no resolution). */
private fun qualityCap(preferredQuality: String?): Int? =
resolutionRank(QualityPresets.normalizeResolution(preferredQuality)).takeIf { it > 0 }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,49 @@
package org.siloserver.silo.playback

import org.siloserver.silo.model.catalog.FileVersion
import org.siloserver.silo.model.catalog.PlaybackVariant
import org.siloserver.silo.model.catalog.playbackEditions
import org.siloserver.silo.model.playback.PLAYBACK_QUALITY_AUTO
import org.siloserver.silo.model.playback.videoQualityPreference

/**
* Selects the file for a direct playback start (Continue Watching, Up Next, or
* a start without a detail-page pin): [lastFileId] when still listed, else the
* first file in server order (the server's recommended edition in [variants]
* when present, otherwise [versions]) that satisfies the local
* [preferredQuality] cap.
*/
fun selectPlaybackVersion(
versions: List<FileVersion>,
lastFileId: Int?,
preferredQuality: String?,
variants: List<PlaybackVariant> = emptyList(),
): FileVersion {
require(versions.isNotEmpty()) { "versions must not be empty" }

if (lastFileId != null) {
versions.firstOrNull { it.fileId == lastFileId }?.let { return it }
}

val candidates = playbackEditions(versions, variants)
.firstOrNull()?.versions?.takeIf { it.isNotEmpty() }
?: versions

val known = candidates.filter { playbackResolutionRank(it.resolution) > 0 }
if (known.isEmpty()) return candidates.first()

val target = videoQualityPreference(preferredQuality) ?: PLAYBACK_QUALITY_AUTO
if (target == PLAYBACK_QUALITY_AUTO) {
return versions.bestAvailable()
return known.first()
}

val preferredRank = playbackResolutionRank(target)
return versions
.sortedWith(
compareByDescending<FileVersion> { playbackResolutionRank(it.resolution) }
.thenByDescending { it.bitrate }
.thenByDescending { it.fileSize },
)
.firstOrNull { playbackResolutionRank(it.resolution) <= preferredRank }
?: versions.bestAvailable()
if (preferredRank <= 0) {
return known.first()
}
known.firstOrNull { playbackResolutionRank(it.resolution) <= preferredRank }?.let { return it }
val closest = known.minOf { playbackResolutionRank(it.resolution) }
return known.first { playbackResolutionRank(it.resolution) == closest }
}

fun playbackResolutionRank(value: String?): Int {
Expand All @@ -51,12 +66,4 @@ fun playbackResolutionRank(value: String?): Int {
}
}

private fun List<FileVersion>.bestAvailable(): FileVersion {
return maxWithOrNull(
compareBy<FileVersion> { playbackResolutionRank(it.resolution) }
.thenBy { it.bitrate }
.thenBy { it.fileSize },
) ?: first()
}

private val RESOLUTION_HEIGHT_REGEX = Regex("""\b(\d{3,4})(?:p|i)?\b""")
Loading
Loading