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 @@ -3,8 +3,11 @@ package org.siloserver.silo.common.downloads
import android.content.Context
import android.util.Log
import androidx.work.WorkManager
import org.siloserver.silo.common.player.PlaybackCapabilityDetector
import org.siloserver.silo.common.settings.PlayerSettingsStore
import org.siloserver.silo.common.settings.dolbyVisionPolicySnapshot
import org.siloserver.silo.model.download.DownloadQuality
import org.siloserver.silo.model.download.effectiveDefault
import org.siloserver.silo.model.download.DownloadMediaType
import org.siloserver.silo.model.download.DownloadRequest
import org.siloserver.silo.model.download.DownloadSidecar
Expand Down Expand Up @@ -46,6 +49,8 @@ class DownloadEnqueuer(
private val authorities: org.siloserver.silo.network.DurableLoginAuthorityProvider? = null,
private val transitions: org.siloserver.silo.network.IdentityTransitionBarrier? = null,
private val devices: org.siloserver.silo.network.DeviceMetadataProvider? = null,
/** Supplies the decode caps sent with each create; null sends none. */
private val capabilityDetector: PlaybackCapabilityDetector? = null,
) {

/**
Expand Down Expand Up @@ -373,14 +378,26 @@ class DownloadEnqueuer(
series: Boolean = false,
downloadQualityOverride: DownloadQuality? = null,
): DownloadRequest {
val quality = downloadQualityOverride ?: DownloadQuality.fromWire(playerSettingsStore.defaultDownloadQualityFlow.first())
val quality = downloadQualityOverride
?: repository.capability.value.effectiveDefault(
DownloadQuality.fromWire(playerSettingsStore.defaultDownloadQualityFlow.first()),
)
return DownloadRequest(
contentId = contentId,
episodeId = episodeId,
fileId = fileId,
series = series,
quality = quality.wire,
targetBitrateKbps = quality.targetBitrateKbps,
// A failed probe must not block the download; the server then
// treats the device as able to play the original.
caps = capabilityDetector?.let { detector ->
withContext(Dispatchers.Default) {
runCatching { detector.downloadCaps(dolbyVision = playerSettingsStore.dolbyVisionPolicySnapshot()) }
.onFailure { Log.w(TAG, "download caps probe failed", it) }
.getOrNull()
}
},
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import androidx.media3.common.util.UnstableApi
import org.siloserver.silo.common.network.SiloClientBuildIdentity
import org.siloserver.silo.player.DolbyVisionPolicy
import org.siloserver.silo.common.player.video.media3OriginalPlaybackContainers
import org.siloserver.silo.model.download.DownloadCaps
import org.siloserver.silo.model.playback.ClientPlaybackContext
import org.siloserver.silo.model.playback.ClientCodecCapabilities
import org.siloserver.silo.model.playback.CAPABILITY_EVIDENCE_EXACT
Expand Down Expand Up @@ -404,6 +405,33 @@ class PlaybackCapabilityDetector(
return detected
}

/**
* Decode-only capability for `POST /api/v2/downloads`. A download plays
* later on whatever output is attached then, so this omits the display
* and audio-route facts [detect] intersects in: the codec, container and
* resolution facts come from the same probes, and HDR is the decoder's own
* support after the same Dolby Vision setting [detect] applies.
*/
fun downloadCaps(
ffmpegAvailable: Boolean = FfmpegAudioSupport.isAvailable(),
dolbyVision: DolbyVisionPolicy.Snapshot = DolbyVisionPolicy.Snapshot(),
): DownloadCaps {
val codecProbe = MediaCodecCapabilitiesProbe.probe()
val decoderHdr = codecProbe.hdr.withDolbyVisionPolicy(dolbyVision)
Comment thread
Quick104 marked this conversation as resolved.
Resolved
return DownloadCaps(
videoEvidence = CAPABILITY_EVIDENCE_EXACT,
codecsVideo = codecProbe.videoCodecs.toList(),
codecsAudio = advertisedAudioDecodeCodecs(
platformCodecs = detectPlatformSoftwareAudioCodecs().codecs,
Comment thread
Quick104 marked this conversation as resolved.
Resolved
ffmpegCodecs = if (ffmpegAvailable) FfmpegAudioSupport.supportedCodecShortCodes() else emptyList(),
),
containers = media3OriginalPlaybackContainers,
maxResolution = codecProbe.maxResolution,
hdr = decoderHdr.hdr10 || decoderHdr.hdr10Plus || decoderHdr.hlg || decoderHdr.dolbyVisionProfiles.isNotEmpty(),
videoDecode = codecProbe.videoDecodeCapabilities,
)
}

/**
* The form factor implied by the current UI mode, for callers that live in
* `android-shared` and so cannot see either app's `BuildConfig`. The app
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ val androidModule = module {
// One-time import of the legacy .record.json sidecar tree into Room.
single { org.siloserver.silo.common.downloads.LegacyDownloadImporter(androidContext().filesDir, get()) }
single { OfflineMediaResolver(get(), get(), get()) }
single { DownloadEnqueuer(androidContext(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) }
single { DownloadEnqueuer(androidContext(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) }
single { DownloadSubscriptionEvaluatorFactory(get(), get(), get()) }
// CoroutineWorker constructed by Koin's WorkerFactory — see
// SiloApplication.onCreate `workManagerFactory()` call.
Expand Down Expand Up @@ -453,7 +453,7 @@ val androidModule = module {
tmdbId = args.second,
)
}
viewModel { SettingsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) }
viewModel { SettingsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) }
viewModel { DiagnosticsViewModel(get()) }
viewModel { DownloadsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) }
viewModel { org.siloserver.silo.android.ui.screens.pairing.CompanionPairingViewModel(get(), get()) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ fun DownloadQualityPickerSheet(
// Presets to offer, already gated by server capability + media type (issue
// #20 GAP 4). Empty falls back to Original so the sheet is never blank.
allowedQualities: List<DownloadQuality> = DownloadQuality.entries,
// Row title per preset; the caller passes the server capability's label,
// which adds the preset's resolution ceiling ("10 Mbps · up to 1080p").
qualityLabel: (DownloadQuality) -> String = { it.label },
) {
val qualities = allowedQualities.ifEmpty { listOf(DownloadQuality.Original) }
ModalBottomSheet(
Expand Down Expand Up @@ -89,7 +92,7 @@ fun DownloadQualityPickerSheet(
ListItem(
headlineContent = {
Text(
text = quality.label,
text = qualityLabel(quality),
style = MaterialTheme.typography.bodyLarge,
)
},
Expand Down Expand Up @@ -165,6 +168,6 @@ internal fun downloadEstimateWarning(

private fun downloadQualityDescription(quality: DownloadQuality): String =
when (quality) {
DownloadQuality.Original -> "Original file, best quality, largest download."
else -> "Smaller copy capped around ${quality.label}."
DownloadQuality.Original -> "Source quality, with compatibility fallback if needed."
else -> "Prepared on the server when the original is larger."
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import org.siloserver.silo.model.ebook.chooseEbookVersion
import org.siloserver.silo.model.ebook.isInAppReadableEbookVersion
import org.siloserver.silo.model.ebook.isSupportedEbookVersion
import org.siloserver.silo.model.download.DownloadQuality
import org.siloserver.silo.model.download.labelFor
import org.siloserver.silo.model.feature.CLIENT_WATCH_TOGETHER_SURFACE_ENABLED
import org.siloserver.silo.common.settings.PlayerSettingsStore
import org.siloserver.silo.network.ServerRegistry
Expand Down Expand Up @@ -1002,6 +1003,7 @@ fun ItemDetailScreen(
estimate = pendingDownloadEstimate,
availableBytes = remember { downloadStorage.usableSpaceBytes() },
allowedQualities = pendingDownloadAllowedQualities,
qualityLabel = { quality -> downloadCapability.labelFor(quality) },
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ fun SettingsScreen(
label = "Download quality",
description = "Quality preset used for new downloads.",
value = state.defaultDownloadQuality,
options = DownloadQuality.entries.map { it.label },
options = state.downloadQualityOptions,
onOptionSelected = viewModel::setDefaultDownloadQuality,
)
SettingsSwitchRow(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import org.siloserver.silo.domain.player.IntroSkipMode
import org.siloserver.silo.domain.settings.ProfileSettingsController
import org.siloserver.silo.model.auth.User
import org.siloserver.silo.model.download.DownloadQuality
import org.siloserver.silo.model.download.effectiveDefault
import org.siloserver.silo.model.download.labelFor
import org.siloserver.silo.repository.DownloadsRepository
import org.siloserver.silo.model.notifications.NotificationPreferencesUpdate
import org.siloserver.silo.model.settings.CardCaption
import org.siloserver.silo.model.settings.CardPosterSize
Expand Down Expand Up @@ -94,6 +97,9 @@ data class SettingsUiState(
val downloadsWifiOnly: Boolean = true,
val keepWatchedDownloads: Boolean = false,
val defaultDownloadQuality: String = DownloadQuality.Original.label,
// The presets this account may request, labelled with the server's
// resolution ceiling once the download capability has loaded.
val downloadQualityOptions: List<String> = DownloadQuality.entries.map { it.label },

// Subtitles
// BCP 47 tag, "" = off. The picker converts to and from labels.
Expand Down Expand Up @@ -131,6 +137,7 @@ class SettingsViewModel(
private val cardPresentationStore: CardPresentationStore,
private val seekIntervalStore: SeekIntervalStore,
audiobookSettingsStore: AudiobookSettingsStore,
private val downloadsRepository: DownloadsRepository? = null,
) : ViewModel() {

private val _uiState = MutableStateFlow(SettingsUiState())
Expand Down Expand Up @@ -233,9 +240,20 @@ class SettingsViewModel(
playerSettingsStore.keepWatchedDownloadsFlow.onEach { keepWatched ->
_uiState.update { it.copy(keepWatchedDownloads = keepWatched) }
}.launchIn(viewModelScope)
playerSettingsStore.defaultDownloadQualityFlow.onEach { quality ->
_uiState.update { it.copy(defaultDownloadQuality = downloadQualityLabel(quality)) }
val downloadCapability = downloadsRepository?.capability ?: MutableStateFlow(null)
combine(playerSettingsStore.defaultDownloadQualityFlow, downloadCapability) { quality, capability ->
val offered = capability?.allowedQualities() ?: DownloadQuality.entries
_uiState.update {
it.copy(
// The preset new downloads will actually use.
defaultDownloadQuality = capability.labelFor(capability.effectiveDefault(DownloadQuality.fromWire(quality))),
downloadQualityOptions = offered.map { preset -> capability.labelFor(preset) },
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
}
}.launchIn(viewModelScope)
// Opening Settings refreshes the capability, as the detail screen does,
// so the labels reflect the server's current download settings.
downloadsRepository?.let { repository -> viewModelScope.launch { repository.refreshCapability() } }
playerSettingsStore.pictureInPictureEnabledFlow.onEach { enabled ->
_uiState.update { it.copy(pictureInPictureEnabled = enabled) }
}.launchIn(viewModelScope)
Expand Down Expand Up @@ -627,9 +645,10 @@ class SettingsViewModel(
}
}

private fun downloadQualityLabel(value: String): String =
DownloadQuality.fromWire(value).label

// A shown label is the preset's bitrate label plus an optional
// " · up to …" suffix, so the bitrate part alone identifies the preset
// even if the capability refreshed after the list was drawn.
private fun downloadQualityWireValue(value: String): String =
DownloadQuality.entries.firstOrNull { it.label == value }?.wire ?: DownloadQuality.Original.wire
DownloadQuality.entries.firstOrNull { it.label == value.substringBefore(" · ") }?.wire
?: DownloadQuality.Original.wire
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,53 @@ enum class DownloadQuality(
Mbps2("2mbps", "2 Mbps", 2_000),
Mbps1("1mbps", "1 Mbps", 1_000);

/**
* [label] plus the resolution ceiling the server reports for this preset,
* e.g. "20 Mbps · up to 4K". A missing ceiling (Original, or an older
* server) leaves the bitrate-only label.
*/
fun label(maxHeight: Int?): String {
if (maxHeight == null || maxHeight <= 0) return label
val resolution = if (maxHeight >= 2160) "4K" else "${maxHeight}p"
return "$label · up to $resolution"
}

companion object {
fun fromWire(value: String?): DownloadQuality =
entries.firstOrNull { it.wire == value?.lowercase()?.trim() } ?: Original
}
}

/**
* One entry of the capability's `quality_options`: a preset's video bitrate
* cap and the tallest output it can produce on this server. Both are absent
* for `original`.
*/
@Serializable
data class DownloadQualityOption(
val preset: String,
@SerialName("bitrate_kbps") val bitrateKbps: Int? = null,
@SerialName("max_height") val maxHeight: Int? = null,
)

/**
* Decode-only device facts sent as `caps` on `POST /api/v2/downloads`. The
* server uses them to serve `original` as-is only when this device plays it,
* and to keep a bitrate preset's resolution within what the decoder takes.
* A download plays later on whatever output is attached then, so nothing here
* describes the current display or audio route.
*/
@Serializable
data class DownloadCaps(
@SerialName("video_evidence") val videoEvidence: String,
@SerialName("codecs_video") val codecsVideo: List<String>,
@SerialName("codecs_audio") val codecsAudio: List<String>,
val containers: List<String>,
@SerialName("max_resolution") val maxResolution: String? = null,
val hdr: Boolean = false,
@SerialName("video_decode") val videoDecode: List<org.siloserver.silo.model.playback.VideoDecodeCapability> = emptyList(),
)

/**
* POST /api/v2/downloads body. Either `episodeId` or `fileId` is set on
* top of the always-required `contentId`. `series = true` requests batch
Expand All @@ -96,6 +137,7 @@ data class DownloadRequest(
@SerialName("device_id") val deviceId: String? = null,
val revision: Int? = null,
@SerialName("status_event_at") val statusEventAt: String? = null,
val caps: DownloadCaps? = null,
)

/**
Expand Down Expand Up @@ -158,12 +200,18 @@ data class DownloadCapability(
val enabled: Boolean = false,
@SerialName("download_allowed") val downloadAllowed: Boolean = false,
@SerialName("quality_presets") val qualityPresets: List<String> = emptyList(),
/** One entry per [qualityPresets] value: its bitrate cap and resolution ceiling. */
@SerialName("quality_options") val qualityOptions: List<DownloadQualityOption> = emptyList(),
@SerialName("transcode_enabled") val transcodeEnabled: Boolean = false,
@SerialName("transcode_user_allowed") val transcodeUserAllowed: Boolean = false,
@SerialName("season_download") val seasonDownload: Boolean = false,
@SerialName("series_monitoring") val seriesMonitoring: Boolean = false,
@SerialName("monitoring_modes") val monitoringModes: List<String> = emptyList(),
) {
/** The label for [quality], with the server's resolution ceiling: "10 Mbps · up to 1080p". */
fun label(quality: DownloadQuality): String =
quality.label(qualityOptions.firstOrNull { it.preset == quality.wire }?.maxHeight)

/** Downloads are usable only when the feature is on AND this user may download. */
val isUsable: Boolean get() = enabled && downloadAllowed && (revision == null || (revision.isNotBlank() && state == "available"))

Expand All @@ -186,6 +234,26 @@ data class DownloadCapability(
}
}

/** [DownloadCapability.label], or the bitrate-only label before a capability has loaded. */
fun DownloadCapability?.labelFor(quality: DownloadQuality): String = this?.label(quality) ?: quality.label

/**
* The preset new downloads use for a saved default: the saved one when this
* capability offers it, since the server refuses a preset the account can no
* longer request (transcoding turned off, say); else Original, or the first
* offered preset if the server does not list Original. An unloaded capability
* keeps the saved value.
*/
fun DownloadCapability?.effectiveDefault(saved: DownloadQuality): DownloadQuality {
if (this == null) return saved
val offered = allowedQualities()
return when {
saved in offered -> saved
DownloadQuality.Original in offered -> DownloadQuality.Original
else -> offered.first()
}
}

/** Convenience: type-safe accessor. */
fun DownloadRecord.statusEnum(): DownloadStatus = DownloadStatus.fromWire(status)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class DownloadCreationV2Api(
request.episodeId?.let { put("episode_id",it) }
request.fileId?.let { put("media_file_id",it.toString()) }
put("quality", request.quality ?: "original")
request.caps?.let { put("caps", SiloJson.encodeToJsonElement(DownloadCaps.serializer(), it)) }
Comment thread
Quick104 marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}.toMutableMap()

private suspend fun send(scope: AuthScopeSnapshot, device: String, body: JsonObject, cursor: String? = null): ApiResult<CreatedDownloadsV2> {
Expand All @@ -56,8 +57,12 @@ class DownloadCreationV2Api(
val device = devices.current()?.id?.takeIf { it.isNotBlank() } ?: return identityChanged()
if (!current(scope,device)) return identityChanged()
if (request.series || request.fileId == null || request.fileId <= 0) return invalid()
// Reconcile first. A confirmed usable entry with the requested quality
// can be downloaded without resetting its bytes/status/batch on the server.
// Reconcile first. A usable entry with the requested quality whose
// bytes are already on or coming to this device is downloaded without
// resetting its bytes/status/batch on the server. One no bytes have
// reached yet is posted again with the current caps, so an entry an
// earlier build created without them is decided for this device; the
// server keeps the entry unchanged when the decision is the same.
val listed = registry.list(scope)
if (listed !is ApiResult.Success) return when(listed) {
is ApiResult.Error -> listed
Expand All @@ -74,7 +79,8 @@ class DownloadCreationV2Api(
if (matches.size > 1) return invalid()
val existing = matches.singleOrNull()
if (existing != null && existing.mediaFileId == request.fileId && existing.quality == (request.quality ?: "original") &&
existing.status in setOf("ready","preparing","queued","downloading","completed")) return ApiResult.Success(existing)
existing.status in setOf("ready","preparing","queued","downloading","completed") &&
(request.caps == null || existing.status in setOf("downloading","completed") || existing.bytesSent > 0)) return ApiResult.Success(existing)
val fields = body(request)
fields["expected_revision"] = JsonPrimitive(existing?.revision ?: 0)
existing?.let { fields["expected_download_id"] = JsonPrimitive(it.id) }
Expand Down
Loading
Loading