Files
otunes/packages/convex/download-quality.ts
T
2026-11-20 15:00:19 -05:00

186 lines
5.2 KiB
TypeScript

import type { PlaybackSource, PlaybackStreamPlan } from "./playback-stream"
/** Qualities a listener can pick when downloading, lowest first. */
export const DOWNLOAD_QUALITIES = [
"low",
"medium",
"high",
"lossless",
"atmos",
] as const
export type DownloadQuality = (typeof DOWNLOAD_QUALITIES)[number]
export const DOWNLOAD_QUALITY_LABELS: Record<DownloadQuality, string> = {
low: "Low",
medium: "Medium",
high: "High",
lossless: "Lossless",
atmos: "Dolby Atmos",
}
export const DOWNLOAD_QUALITY_DETAILS: Record<DownloadQuality, string> = {
low: "AAC 64 kbps",
medium: "AAC 128 kbps",
high: "AAC 256 kbps",
lossless: "ALAC or FLAC",
atmos: "Spatial audio",
}
const LOW_KBPS = 64
const MEDIUM_KBPS = 128
const HIGH_KBPS = 256
export function parseDownloadQuality(
value: string | null | undefined
): DownloadQuality | undefined {
return DOWNLOAD_QUALITIES.find((quality) => quality === value)
}
export type DownloadPlan = {
/** What the song actually downloads as after falling back. */
quality: DownloadQuality
source: PlaybackSource
/** AAC bitrate to transcode to; 0 sends the source file as-is. */
kbps: number
}
function highPlan(files: Record<string, unknown>): DownloadPlan {
if ("normal" in files) {
return { quality: "high", source: "normal", kbps: 0 }
}
return {
quality: "high",
source: "lossless" in files ? "lossless" : "atmos",
kbps: HIGH_KBPS,
}
}
/**
* Picks the file for one song. Lossless and Dolby Atmos fall back to High when
* the song lacks them, and Low and Medium are always transcoded.
*/
export function downloadPlan(
files: Record<string, unknown>,
quality: DownloadQuality
): DownloadPlan {
switch (quality) {
case "low":
case "medium":
return {
quality,
source:
"lossless" in files
? "lossless"
: "normal" in files
? "normal"
: "atmos",
kbps: quality === "low" ? LOW_KBPS : MEDIUM_KBPS,
}
case "high":
return highPlan(files)
case "lossless":
case "atmos": {
const source = quality === "lossless" ? "lossless" : "atmos"
return source in files ? { quality, source, kbps: 0 } : highPlan(files)
}
}
}
/**
* The download quality holding the same audio a stream plan plays, so a
* download can stand in for streaming.
*/
export function streamDownloadQuality(
plan: PlaybackStreamPlan
): DownloadQuality | undefined {
if (plan.preferAtmos) return "atmos"
if (!plan.transcodeNeeded) {
return plan.source === "lossless" ? "lossless" : "high"
}
if (plan.kbps === HIGH_KBPS) return "high"
if (plan.kbps === MEDIUM_KBPS) return "medium"
if (plan.kbps === LOW_KBPS) return "low"
return undefined
}
/**
* Queue origin for playback started from the Downloads page, where downloads
* play whatever their quality. `list` keeps origins of different lists apart.
*/
export function downloadsQueueOrigin(list: string) {
return `downloads:${list}`
}
export function isDownloadsQueueOrigin(origin: string | undefined) {
return origin?.startsWith("downloads:") ?? false
}
export type DownloadOption = {
quality: DownloadQuality
/** How many of the songs fall back to High for this quality. */
fallbackCount: number
}
/**
* The qualities to offer for a set of songs. Lossless and Dolby Atmos only
* appear when at least one song has them.
*/
export function downloadOptions(
songs: readonly Record<string, unknown>[]
): DownloadOption[] {
return DOWNLOAD_QUALITIES.flatMap((quality) => {
const fallbackCount = songs.filter(
(files) => downloadPlan(files, quality).quality !== quality
).length
if (
fallbackCount === songs.length &&
quality !== "low" &&
quality !== "medium" &&
quality !== "high"
) {
return []
}
return [{ quality, fallbackCount }]
})
}
export type SizedDownloadOption = DownloadOption & {
bytes: number
/** True when part of the size is a guess because the server re-encodes. */
estimated: boolean
}
/** Server answer for a set of songs about to be downloaded. */
export type DownloadOptionsResponse = {
songs: { id: string; albumId: string; files: Record<string, true> }[]
options: SizedDownloadOption[]
}
/** POST `{ songIds, losslessFormat? }` here for `DownloadOptionsResponse`. */
export const DOWNLOAD_OPTIONS_PATH = "/api/download/options"
/** Rough size of an AAC encode, including container overhead. */
export function estimatedAacBytes(seconds: number, kbps: number) {
return Math.round(((seconds * kbps * 1000) / 8) * 1.02)
}
export function formatBytes(bytes: number) {
if (bytes < 1000 * 1000) return `${Math.max(1, Math.round(bytes / 1000))} KB`
if (bytes < 1000 * 1000 * 1000) return `${Math.round(bytes / 1000 / 1000)} MB`
return `${(bytes / 1000 / 1000 / 1000).toFixed(1)} GB`
}
/** Download route for one song. iOS asks for ALAC so it skips FLAC conversion. */
export function songDownloadPath(
songId: string,
quality: DownloadQuality,
options?: { losslessFormat?: "alac" }
) {
const params = new URLSearchParams({ quality })
if (options?.losslessFormat) {
params.set("losslessFormat", options.losslessFormat)
}
return `/api/song/${songId}/download?${params}`
}