refactor: share logic duplicated across web, mobile, and Convex

Move queue rules, stream planning, stream URLs, share links, song search,
favorites optimistic updates, token parsing, and format badge marks into
@otunes/convex so each rule has one implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
joshuafhigginsandClaude Opus 5.5 committed 2026-11-16 14:22:19 -05:00 Verified
1 parent dce66b7697
commit 22cb6b6ccc
35 files changed
+612 -861

No files matched your search

@@ -89,7 +89,8 @@ export default function AlbumScreen() {
[album]
)
// Older servers do not include album format availability yet.
// Servers from before the album format fields (#61, 2026-11-03) omit them,
// so derive them from the tracks there. Current servers skip this query.
const formatTracks = useCachedQuery(
api.library.getSongsForPlayback,
album && (album.hasLossless === undefined || album.hasAtmos === undefined)
@@ -1,4 +1,4 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { atmosEnabled, dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
@@ -30,7 +30,7 @@ import { useCachedQuery } from "@/hooks/use-cached-query"
import { changeServer, signOut } from "@/lib/session"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError } from "@/lib/toast"
import type { PlaybackQuality } from "@/lib/urls"
import type { PlaybackQuality } from "@otunes/convex/playback-stream"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
@@ -419,7 +419,7 @@ function QualitySection({ user }: { user: CurrentUser }) {
: "This device does not support Dolby Atmos playback."
}
disabled={!dolbyAtmosSupported}
value={dolbyAtmosSupported && (user.preferAtmos ?? false)}
value={atmosEnabled(user)}
onValueChange={(checked) =>
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
showError(error.message)
+2 -2
View File
@@ -1,6 +1,6 @@
import { useTabletLayout } from "@/hooks/use-tablet-layout"
import { TabletNowPlaying } from "@/components/tablet-now-playing"
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { atmosEnabled } from "@/lib/playback-capabilities"
import { NavigationBar } from "expo-navigation-bar"
import { MusicEntityView } from "@/components/music-entity-view"
import { Stack, useRouter, useLocalSearchParams } from "expo-router"
@@ -114,7 +114,7 @@ export default function PlayerScreen() {
? playbackFormat(
playbackInfo.files,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false)
atmosEnabled(user)
)
: null
+19 -25
View File
@@ -2,39 +2,33 @@ import { PaletteText } from "@/components/palette-text"
import { StyleSheet, View } from "react-native"
import Svg, { G, Path } from "react-native-svg"
import {
DOLBY_PATHS,
DOLBY_VIEW_BOX,
DOLBY_WIDTH,
LOSSLESS_FALL,
LOSSLESS_FALL_GAP,
LOSSLESS_PEAKS,
LOSSLESS_STROKES,
LOSSLESS_THIN_WIDTH,
LOSSLESS_VIEW_BOX,
LOSSLESS_WIDTH,
MARK_HEIGHT,
} from "@otunes/convex/client/audio-format-marks"
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
const LABEL_SIZE = 13
const MARK_HEIGHT = 11
function DolbyMark({ color }: { color: string }) {
return (
<Svg
width={(MARK_HEIGHT * 23) / 16}
height={MARK_HEIGHT}
viewBox="0 0 23 16"
>
<Path d="M0 0H2.5A8 8 0 0 1 2.5 16H0Z" fill={color} />
<Path d="M23 0H20.5A8 8 0 0 0 20.5 16H23Z" fill={color} />
<Svg width={DOLBY_WIDTH} height={MARK_HEIGHT} viewBox={DOLBY_VIEW_BOX}>
{DOLBY_PATHS.map((d) => (
<Path key={d} d={d} fill={color} />
))}
</Svg>
)
}
const LOSSLESS_PEAKS = [110, 215, 320]
const LOSSLESS_THIN_WIDTH = 24
const LOSSLESS_STROKES: [peak: number, d: string][] = [
[110, "M-70 320C-62 245 -38 166 0 166"],
[215, "M-70 320C-62 245 -38 166 0 166"],
[320, "M-30 185C-22 173 -11 166 0 166"],
[110, "M166 413C176 413 186 406 194 395"],
[215, "M166 413C200 413 226 340 240 275"],
[320, "M166 413C200 413 226 340 240 275"],
]
const LOSSLESS_FALL =
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
const LOSSLESS_FALL_GAP =
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
/**
* Three overlapping waves. Each thick downstroke is outlined in the
* background color so it reads as passing over the strokes behind it.
@@ -48,9 +42,9 @@ function LosslessMark({
}) {
return (
<Svg
width={(MARK_HEIGHT * 544) / 271}
width={LOSSLESS_WIDTH}
height={MARK_HEIGHT}
viewBox="28 154 544 271"
viewBox={LOSSLESS_VIEW_BOX}
>
{LOSSLESS_STROKES.map(([peak, d], index) => (
<Path
@@ -4,19 +4,15 @@ import { Stack } from "expo-router"
import { useDebouncedSearch } from "@/hooks/use-debounced-search"
import { useThemeColors } from "@/lib/theme"
import { filterSongs } from "@otunes/convex/client/song-search"
import type { BrowseSong } from "@otunes/convex/types"
export function usePlaylistSearch(songs: BrowseSong[]) {
const search = useDebouncedSearch()
const filteredSongs = useMemo(() => {
const query = search.searchQuery.toLowerCase()
if (!query) return songs
return songs.filter((song) =>
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(query)
)
)
}, [songs, search.searchQuery])
const filteredSongs = useMemo(
() => filterSongs(songs, search.searchQuery),
[songs, search.searchQuery]
)
return { ...search, filteredSongs }
}
+14 -90
View File
@@ -12,20 +12,23 @@ import {
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
import { favoriteOptimisticUpdates } from "@otunes/convex/client/favorites"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError } from "@/lib/toast"
/**
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. The
* update is captured on first render, so it must not close over render state.
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. Pass a
* module-level update so it does not change between renders.
*/
function useOptimisticMutation<Mutation extends FunctionReference<"mutation">>(
mutation: Mutation,
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>
): ReactMutation<Mutation> {
const base = useMutation(mutation)
const updateRef = useRef(optimisticUpdate)
return useMemo(() => base.withOptimisticUpdate(updateRef.current), [base])
return useMemo(
() => base.withOptimisticUpdate(optimisticUpdate),
[base, optimisticUpdate]
)
}
type FavoritesContextValue = {
@@ -52,110 +55,31 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
const favorites = useCachedQuery(api.favorites.getUserFavorites)
const favoriteSong = useOptimisticMutation(
api.favorites.favoriteSong,
(store, { songId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current || current.favoriteSongs.includes(songId)) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteSongs: [...current.favoriteSongs, songId],
}
)
}
favoriteOptimisticUpdates.favoriteSong
)
const unfavoriteSong = useOptimisticMutation(
api.favorites.unfavoriteSong,
(store, { songId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
}
)
}
favoriteOptimisticUpdates.unfavoriteSong
)
const favoriteAlbum = useOptimisticMutation(
api.favorites.favoriteAlbum,
(store, { albumId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current || current.favoriteAlbums.includes(albumId)) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteAlbums: [...current.favoriteAlbums, albumId],
}
)
}
favoriteOptimisticUpdates.favoriteAlbum
)
const unfavoriteAlbum = useOptimisticMutation(
api.favorites.unfavoriteAlbum,
(store, { albumId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
}
)
}
favoriteOptimisticUpdates.unfavoriteAlbum
)
const favoriteArtist = useOptimisticMutation(
api.favorites.favoriteArtist,
(store, { artistId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current || current.favoriteArtists.includes(artistId)) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteArtists: [...current.favoriteArtists, artistId],
}
)
}
favoriteOptimisticUpdates.favoriteArtist
)
const unfavoriteArtist = useOptimisticMutation(
api.favorites.unfavoriteArtist,
(store, { artistId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteArtists: current.favoriteArtists.filter(
(id) => id !== artistId
),
}
)
}
favoriteOptimisticUpdates.unfavoriteArtist
)
const favoriteSongsMutation = useOptimisticMutation(
api.favorites.favoriteSongs,
(store, { songIds }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
}
)
}
favoriteOptimisticUpdates.favoriteSongs
)
const songIds = useMemo(
+1 -15
View File
@@ -1,4 +1,5 @@
import { useAuthToken } from "@convex-dev/auth/react"
import { userIdFromToken } from "@otunes/convex/client/auth-token"
import { createContext, useContext, useMemo, type ReactNode } from "react"
import { loadPersistentCache } from "@/lib/persistent-cache"
@@ -9,21 +10,6 @@ const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
void loadPersistentCache()
function userIdFromToken(token: string | null) {
const payload = token?.split(".")[1]
if (!payload) {
return null
}
try {
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
const subject = (JSON.parse(json) as { sub?: unknown }).sub
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
} catch {
return null
}
}
/** Namespaces persisted client data by server and signed-in user. */
export function PersistentCacheProvider({
serverUrl,
+4 -8
View File
@@ -1,4 +1,4 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import { atmosEnabled } from "@/lib/playback-capabilities"
import {
createAudioPlaylist,
setAudioModeAsync,
@@ -323,11 +323,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
])
: ""
const userPlaybackKey = user
? JSON.stringify([
user._id,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false),
])
? JSON.stringify([user._id, user.playbackQuality, atmosEnabled(user)])
: ""
const scheduleTrackChangeHandling = useCallback(() => {
@@ -654,7 +650,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
if (!isCurrentLoad()) return
const loadKey = `${user.playbackQuality}:${dolbyAtmosSupported && (user.preferAtmos ?? false)}:${cookieHeader}`
const loadKey = `${user.playbackQuality}:${atmosEnabled(user)}:${cookieHeader}`
const needsRebuild =
loadedLoadKeyRef.current !== loadKey ||
nativePlaylistNeedsRebuild(
@@ -696,7 +692,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false)
atmosEnabled(user)
)
sources.set(
song.id,
+7 -38
View File
@@ -1,40 +1,9 @@
export type MediaShareContext = (
| { type: "album"; albumId: string }
| { type: "song"; albumId: string; songId: string }
| { type: "playlist"; playlistId: string; isFavorites?: boolean }
| { type: "artist"; artistId: string }
) & { title: string }
import type { MediaShareTarget } from "@otunes/convex/client/media-links"
export function shouldShowShare(
share: MediaShareContext | undefined,
selectedCount: number
) {
if (!share) {
return false
}
if (share.type === "song") {
return selectedCount === 1
}
return true
}
export {
mediaShareUrl,
shouldShowShare,
} from "@otunes/convex/client/media-links"
export function mediaShareUrl(
serverUrl: string,
share: MediaShareContext
): string {
const origin = serverUrl.replace(/\/+$/, "")
switch (share.type) {
case "album":
return `${origin}/album/${share.albumId}`
case "song":
return `${origin}/album/${share.albumId}?s=${share.songId}`
case "playlist":
if (share.isFavorites) {
return `${origin}/playlist/favorites`
}
return `${origin}/playlist/${share.playlistId}`
case "artist":
return `${origin}/artist/${share.artistId}`
}
}
/** A share target plus the title shown in the native share sheet. */
export type MediaShareContext = MediaShareTarget & { title: string }
+5
View File
@@ -2,3 +2,8 @@ import { Platform } from "react-native"
// Android Dolby decoder reports do not reliably indicate working Atmos playback.
export const dolbyAtmosSupported = Platform.OS === "ios"
/** Whether to stream Atmos for this user: they opted in and the device can play it. */
export function atmosEnabled(user: { preferAtmos?: boolean }) {
return dolbyAtmosSupported && (user.preferAtmos ?? false)
}
+4 -4
View File
@@ -5,8 +5,10 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import {
getCachedSong,
getSongSnapshot,
getSongsVersion,
requestSongs,
songFromSnapshot,
subscribeSongs,
} from "@otunes/convex/client/song-cache"
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
@@ -50,12 +52,10 @@ export function useSongs(songIds: readonly Id<"songs">[]) {
*/
export function useSong(songId: Id<"songs"> | null): BrowseSong | null {
const convex = useConvex()
// While the song is missing the snapshot is the cache version, so every
// cache change re-renders and retries the fetch below.
const snapshot = useSyncExternalStore(subscribeSongs, () =>
songId ? (getCachedSong(songId) ?? getSongsVersion()) : null
getSongSnapshot(songId)
)
const song = typeof snapshot === "object" ? snapshot : null
const song = songFromSnapshot(snapshot)
useEffect(() => {
if (songId && !song && isPersistentCacheLoaded()) {
+11 -33
View File
@@ -1,9 +1,11 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import {
type PlaybackQuality,
songHlsPlaylistPath,
songPlayPath,
} from "@otunes/convex/playback-stream"
import { Platform } from "react-native"
import type { AudioSource } from "expo-audio"
export type PlaybackQuality = "low" | "medium" | "high" | "lossless"
export const coverImageSizes = [64, 128, 192, 256, 384, 512, 768, 1024] as const
export type CoverImageSize = (typeof coverImageSizes)[number]
@@ -45,33 +47,6 @@ export function playlistCoverUrl(
return sizedCoverUrl(`${serverUrl}/api/playlist/${playlistId}/cover`, size)
}
export function songPlayUrl(
serverUrl: string,
songId: string,
quality: PlaybackQuality | undefined,
preferAtmos: boolean | undefined
) {
const params = new URLSearchParams()
if (Platform.OS === "ios") params.set("losslessFormat", "alac")
if (quality) params.set("quality", quality)
if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true")
const query = params.toString()
return `${serverUrl}/api/song/${songId}/play${query ? `?${query}` : ""}`
}
export function songHlsPlaylistUrl(
serverUrl: string,
songId: string,
quality: PlaybackQuality | undefined,
preferAtmos: boolean | undefined
) {
const params = new URLSearchParams()
if (quality) params.set("quality", quality)
if (dolbyAtmosSupported && preferAtmos) params.set("preferAtmos", "true")
const query = params.toString()
return `${serverUrl}/api/song/${songId}/play/hls${query ? `?${query}` : ""}`
}
export function songAudioSource(
serverUrl: string,
songId: string,
@@ -80,9 +55,12 @@ export function songAudioSource(
useHls: boolean,
options?: { cookieHeader?: string | null; songTitle?: string }
): AudioSource {
const uri = useHls
? songHlsPlaylistUrl(serverUrl, songId, quality, preferAtmos)
: songPlayUrl(serverUrl, songId, quality, preferAtmos)
const path = useHls
? songHlsPlaylistPath(songId, quality, preferAtmos)
: songPlayPath(songId, quality, preferAtmos, {
losslessFormat: Platform.OS === "ios" ? "alac" : undefined,
})
const uri = `${serverUrl}${path}`
const headers = options?.cookieHeader
? { Cookie: options.cookieHeader }
+14 -27
View File
@@ -1,5 +1,9 @@
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import {
parsePlaybackQuality,
playbackStreamPlan,
} from "@otunes/convex/playback-stream"
import { audioContentTypeForPath } from "@/lib/audio-content-type"
import { seekableLosslessFile } from "@/lib/server-lossless"
import { getConvexClient } from "@/lib/convex-server"
@@ -122,34 +126,17 @@ export async function GET(
id: id as Id<"songs">,
}))!
const quality = request.nextUrl.searchParams.get("quality") as
"low" | "medium" | "high" | "lossless" | null
const preferAtmos =
const {
source: originalCodec,
kbps,
transcodeNeeded,
} = playbackStreamPlan(
song.files,
// Without a quality, serve the original file as this route always has.
parsePlaybackQuality(request.nextUrl.searchParams.get("quality")) ??
"lossless",
request.nextUrl.searchParams.get("preferAtmos") === "true"
let kbps = 0
if (quality === "low") {
kbps = 64
} else if (quality === "medium") {
kbps = 128
} else if (quality === "high") {
kbps = 256
}
let originalCodec = "lossless" in song.files ? "lossless" : "normal"
let transcodeNeeded = true
if (preferAtmos && "atmos" in song.files) {
originalCodec = "atmos"
transcodeNeeded = false
} else if (kbps === 0 && "lossless" in song.files) {
originalCodec = "lossless"
transcodeNeeded = false
} else if (kbps === 0 || (kbps === 256 && "normal" in song.files)) {
originalCodec = "normal"
transcodeNeeded = false
}
)
const metadata = await music.parseFile(song.files[originalCodec])
+3 -19
View File
@@ -22,8 +22,6 @@ import {
} from "@/components/media-context-menu"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { cn } from "@/lib/utils"
@@ -276,20 +274,6 @@ export function AlbumView({
[album.tracks]
)
// Older servers do not include album format availability yet.
const formatTracks = useCachedQuery(
api.library.getSongsForPlayback,
album.hasLossless === undefined || album.hasAtmos === undefined
? { ids: albumSongIds }
: "skip"
)
const hasLossless =
album.hasLossless ??
formatTracks?.some((track) => track && "lossless" in track.files)
const hasAtmos =
album.hasAtmos ??
formatTracks?.some((track) => track && "atmos" in track.files)
React.useEffect(() => {
rememberSongs(albumDetailSongs(album))
}, [album])
@@ -421,15 +405,15 @@ export function AlbumView({
</Link>
<div className="flex flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground sm:justify-start">
{metadata ? <span>{metadata}</span> : null}
{hasLossless ? (
{album.hasLossless ? (
<>
{metadata ? <span aria-hidden>·</span> : null}
<AudioFormatBadge format="lossless" />
</>
) : null}
{hasAtmos ? (
{album.hasAtmos ? (
<>
{metadata || hasLossless ? (
{metadata || album.hasLossless ? (
<span aria-hidden>·</span>
) : null}
<AudioFormatBadge format="atmos" />
+19 -26
View File
@@ -1,35 +1,28 @@
import {
DOLBY_PATHS,
DOLBY_VIEW_BOX,
DOLBY_WIDTH,
LOSSLESS_FALL,
LOSSLESS_FALL_GAP,
LOSSLESS_PEAKS,
LOSSLESS_STROKES,
LOSSLESS_THIN_WIDTH,
LOSSLESS_VIEW_BOX,
LOSSLESS_WIDTH,
MARK_HEIGHT,
} from "@otunes/convex/client/audio-format-marks"
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
const MARK_HEIGHT = 11
function DolbyMark({ color }: { color: string }) {
return (
<svg
width={(MARK_HEIGHT * 23) / 16}
height={MARK_HEIGHT}
viewBox="0 0 23 16"
>
<path d="M0 0H2.5A8 8 0 0 1 2.5 16H0Z" fill={color} />
<path d="M23 0H20.5A8 8 0 0 0 20.5 16H23Z" fill={color} />
<svg width={DOLBY_WIDTH} height={MARK_HEIGHT} viewBox={DOLBY_VIEW_BOX}>
{DOLBY_PATHS.map((d) => (
<path key={d} d={d} fill={color} />
))}
</svg>
)
}
const LOSSLESS_PEAKS = [110, 215, 320]
const LOSSLESS_THIN_WIDTH = 24
const LOSSLESS_STROKES: [peak: number, d: string][] = [
[110, "M-70 320C-62 245 -38 166 0 166"],
[215, "M-70 320C-62 245 -38 166 0 166"],
[320, "M-30 185C-22 173 -11 166 0 166"],
[110, "M166 413C176 413 186 406 194 395"],
[215, "M166 413C200 413 226 340 240 275"],
[320, "M166 413C200 413 226 340 240 275"],
]
const LOSSLESS_FALL =
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
const LOSSLESS_FALL_GAP =
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
/**
* Three overlapping waves. Each thick downstroke is outlined in the
* background color so it reads as passing over the strokes behind it.
@@ -43,9 +36,9 @@ function LosslessMark({
}) {
return (
<svg
width={(MARK_HEIGHT * 544) / 271}
width={LOSSLESS_WIDTH}
height={MARK_HEIGHT}
viewBox="28 154 544 271"
viewBox={LOSSLESS_VIEW_BOX}
>
{LOSSLESS_STROKES.map(([peak, d], index) => (
<path
+53 -92
View File
@@ -1,13 +1,31 @@
"use client"
import * as React from "react"
import { useMutation } from "convex/react"
import type { OptimisticUpdate } from "convex/browser"
import { useMutation, type ReactMutation } from "convex/react"
import type { FunctionArgs, FunctionReference } from "convex/server"
import { toast } from "sonner"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
import { favoriteOptimisticUpdates } from "@otunes/convex/client/favorites"
import type { Id } from "@otunes/convex/_generated/dataModel"
/**
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. Pass a
* module-level update so it does not change between renders.
*/
function useOptimisticMutation<Mutation extends FunctionReference<"mutation">>(
mutation: Mutation,
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>
): ReactMutation<Mutation> {
const base = useMutation(mutation)
return React.useMemo(
() => base.withOptimisticUpdate(optimisticUpdate),
[base, optimisticUpdate]
)
}
type FavoritesContextValue = {
isSongFavorite: (songId: string) => boolean
isAlbumFavorite: (albumId: string) => boolean
@@ -34,97 +52,38 @@ export function useFavorites() {
export function FavoritesProvider({ children }: { children: React.ReactNode }) {
const favorites = useCachedQuery(api.favorites.getUserFavorites)
const favoriteSong = useMutation(api.favorites.favoriteSong).withOptimisticUpdate(
(store, { songId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current && !current.favoriteSongs.includes(songId)) {
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteSongs: [...current.favoriteSongs, songId],
})
}
}
const favoriteSong = useOptimisticMutation(
api.favorites.favoriteSong,
favoriteOptimisticUpdates.favoriteSong
)
const favoriteSongsMutation = useOptimisticMutation(
api.favorites.favoriteSongs,
favoriteOptimisticUpdates.favoriteSongs
)
const unfavoriteSong = useOptimisticMutation(
api.favorites.unfavoriteSong,
favoriteOptimisticUpdates.unfavoriteSong
)
const unfavoriteSongs = useOptimisticMutation(
api.favorites.unfavoriteSongs,
favoriteOptimisticUpdates.unfavoriteSongs
)
const favoriteAlbum = useOptimisticMutation(
api.favorites.favoriteAlbum,
favoriteOptimisticUpdates.favoriteAlbum
)
const unfavoriteAlbum = useOptimisticMutation(
api.favorites.unfavoriteAlbum,
favoriteOptimisticUpdates.unfavoriteAlbum
)
const favoriteArtist = useOptimisticMutation(
api.favorites.favoriteArtist,
favoriteOptimisticUpdates.favoriteArtist
)
const unfavoriteArtist = useOptimisticMutation(
api.favorites.unfavoriteArtist,
favoriteOptimisticUpdates.unfavoriteArtist
)
const favoriteSongsMutation = useMutation(
api.favorites.favoriteSongs
).withOptimisticUpdate((store, { songIds }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current) {
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
})
}
})
const unfavoriteSong = useMutation(
api.favorites.unfavoriteSong
).withOptimisticUpdate((store, { songId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current) {
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
})
}
})
const unfavoriteSongs = useMutation(
api.favorites.unfavoriteSongs
).withOptimisticUpdate((store, { songIds }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current) {
const removed = new Set(songIds)
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteSongs: current.favoriteSongs.filter((id) => !removed.has(id)),
})
}
})
const favoriteAlbum = useMutation(
api.favorites.favoriteAlbum
).withOptimisticUpdate((store, { albumId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current && !current.favoriteAlbums.includes(albumId)) {
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteAlbums: [...current.favoriteAlbums, albumId],
})
}
})
const unfavoriteAlbum = useMutation(
api.favorites.unfavoriteAlbum
).withOptimisticUpdate((store, { albumId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current) {
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
})
}
})
const favoriteArtist = useMutation(
api.favorites.favoriteArtist
).withOptimisticUpdate((store, { artistId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current && !current.favoriteArtists.includes(artistId)) {
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteArtists: [...current.favoriteArtists, artistId],
})
}
})
const unfavoriteArtist = useMutation(
api.favorites.unfavoriteArtist
).withOptimisticUpdate((store, { artistId }) => {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (current) {
store.setQuery(api.favorites.getUserFavorites, {}, {
...current,
favoriteArtists: current.favoriteArtists.filter(
(id) => id !== artistId
),
})
}
})
const songIds = React.useMemo(
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
@@ -288,6 +247,8 @@ export function FavoritesProvider({ children }: { children: React.ReactNode }) {
)
return (
<FavoritesContext.Provider value={value}>{children}</FavoritesContext.Provider>
<FavoritesContext.Provider value={value}>
{children}
</FavoritesContext.Provider>
)
}
+1 -13
View File
@@ -23,6 +23,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { copyMediaShareLink, type MediaShareContext } from "@/lib/media-links"
import { shouldShowShare } from "@otunes/convex/client/media-links"
import { cn } from "@/lib/utils"
export type MediaContextAction =
@@ -40,19 +41,6 @@ export type MediaContextNavigation = {
export type { MediaShareContext } from "@/lib/media-links"
function shouldShowShare(
share: MediaShareContext | undefined,
selectedCount: number
) {
if (!share) {
return false
}
if (share.type === "song") {
return selectedCount === 1
}
return true
}
function actionLabel(base: string, selectedCount: number) {
return selectedCount > 1 ? `${base} (${selectedCount})` : base
}
+1 -2
View File
@@ -47,13 +47,12 @@ import {
import { usePlayback } from "@/components/playback-provider"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { PlaybackQuality } from "@otunes/convex/playback-stream"
import { resizeProfileImageToDataUrl } from "@/lib/resize-profile-image"
import { cn } from "@/lib/utils"
type Section = "profile" | "quality" | "users" | "library"
type PlaybackQuality = "low" | "medium" | "high" | "lossless"
type CurrentUser = {
_id: Id<"users">
name: string
@@ -1,6 +1,7 @@
"use client"
import { useAuthToken } from "@convex-dev/auth/react"
import { userIdFromToken } from "@otunes/convex/client/auth-token"
import { createContext, ReactNode, useContext, useEffect, useMemo } from "react"
import { loadPersistentCache } from "@/lib/persistent-cache"
@@ -13,21 +14,6 @@ if (typeof window !== "undefined") {
void loadPersistentCache()
}
function userIdFromToken(token: string | null) {
const payload = token?.split(".")[1]
if (!payload) {
return null
}
try {
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
const subject = (JSON.parse(json) as { sub?: unknown }).sub
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
} catch {
return null
}
}
/** Namespaces persisted client data by the signed-in user. */
export function PersistentCacheProvider({ children }: { children: ReactNode }) {
const token = useAuthToken()
+7 -5
View File
@@ -22,7 +22,10 @@ import type { BrowseSong } from "@otunes/convex/types"
import {
playbackFormat,
type PlaybackFormat,
type PlaybackQuality,
playbackStreamPlan,
songHlsPlaylistPath,
songPlayPath,
} from "@otunes/convex/playback-stream"
import {
ANONYMOUS_CACHE_SCOPE,
@@ -40,7 +43,6 @@ import {
getServerPlaybackSnapshot,
} from "@otunes/convex/client/playback-store"
import { rememberSongs, useSong } from "@/lib/song-cache"
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
const PROGRESS_SAVE_INTERVAL_MS = 5000
@@ -164,14 +166,14 @@ function readStoredVolume(): number {
type PlaybackLoadSettings = {
preferAtmos: boolean
playbackQuality: "low" | "medium" | "high" | "lossless"
playbackQuality: PlaybackQuality
useHls: boolean
}
function playbackLoadSettings(
user: {
preferAtmos?: boolean
playbackQuality?: "low" | "medium" | "high" | "lossless"
playbackQuality?: PlaybackQuality
},
dolbyAtmosSupported: boolean | null,
files: Record<string, unknown>
@@ -226,12 +228,12 @@ function loadAudioSource(
): AudioSourceCleanup {
let disposed = false
let hlsInstance: Hls | null = null
const directUrl = songPlayUrl(
const directUrl = songPlayPath(
songId,
settings.playbackQuality,
settings.preferAtmos
)
const hlsUrl = songHlsPlaylistUrl(
const hlsUrl = songHlsPlaylistPath(
songId,
settings.playbackQuality,
settings.preferAtmos
+9 -15
View File
@@ -35,6 +35,7 @@ import { copyPlaylistLink } from "@/lib/media-links"
import { sumDurationSeconds } from "@/lib/media-summary"
import { rememberSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils"
import { filterSongs } from "@otunes/convex/client/song-search"
import {
getSelectionRangePositions,
isInSelectionRange,
@@ -306,17 +307,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id))
: playlistSongs
const [searchQuery, setSearchQuery] = React.useState("")
const normalizedQuery = searchQuery.trim().toLowerCase()
const isSearching = searchQuery.trim() !== ""
const filteredSongs = React.useMemo(
() =>
normalizedQuery
? songs.filter((song) =>
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(normalizedQuery)
)
)
: songs,
[songs, normalizedQuery]
() => filterSongs(songs, searchQuery),
[songs, searchQuery]
)
const playlistSongIds = React.useMemo(
() => songs.map((song) => song.id as Id<"songs">),
@@ -480,7 +474,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
function handleDrop(targetIndex: number) {
if (
normalizedQuery ||
isSearching ||
isFavorites ||
!isOwner ||
dragIndex === null ||
@@ -681,7 +675,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
key={song.id}
song={song}
index={index}
isOwner={isOwner && !isFavorites && !normalizedQuery}
isOwner={isOwner && !isFavorites && !isSearching}
canRemove={isFavorites || isOwner}
showFavoriteInMenu={!isFavorites}
removeLabel={
@@ -721,14 +715,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
onMediaAction={handleMediaAction}
onRemove={() => handleRemoveSong(song.id)}
onDragStart={(event) => {
if (normalizedQuery || isFavorites || !isOwner) {
if (isSearching || isFavorites || !isOwner) {
return
}
setDragIndex(index)
event.dataTransfer.effectAllowed = "move"
}}
onDragOver={(event) => {
if (normalizedQuery || isFavorites || !isOwner) {
if (isSearching || isFavorites || !isOwner) {
return
}
event.preventDefault()
@@ -749,7 +743,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
))
) : (
<p className="px-6 py-8 text-sm text-muted-foreground">
{normalizedQuery
{isSearching
? "No songs found."
: "This playlist has no songs yet."}
</p>
+9 -63
View File
@@ -1,72 +1,22 @@
import { toast } from "sonner"
import {
mediaShareUrl,
type MediaShareTarget,
} from "@otunes/convex/client/media-links"
export type MediaShareContext =
| { type: "album"; albumId: string }
| { type: "song"; albumId: string; songId: string }
| { type: "playlist"; playlistId: string; isFavorites?: boolean }
| { type: "artist"; artistId: string }
function mediaOrigin() {
if (typeof window === "undefined") {
return ""
}
return window.location.origin
}
export function albumShareUrl(albumId: string) {
return `${mediaOrigin()}/album/${albumId}`
}
export function songShareUrl(albumId: string, songId: string) {
return `${mediaOrigin()}/album/${albumId}?s=${songId}`
}
export function playlistShareUrl(
playlistId: string,
options?: { isFavorites?: boolean }
) {
if (options?.isFavorites) {
return `${mediaOrigin()}/playlist/favorites`
}
return `${mediaOrigin()}/playlist/${playlistId}`
}
export function artistShareUrl(artistId: string) {
return `${mediaOrigin()}/artist/${artistId}`
}
export function mediaShareUrl(share: MediaShareContext) {
switch (share.type) {
case "album":
return albumShareUrl(share.albumId)
case "song":
return songShareUrl(share.albumId, share.songId)
case "playlist":
return playlistShareUrl(share.playlistId, {
isFavorites: share.isFavorites,
})
case "artist":
return artistShareUrl(share.artistId)
}
}
export async function copyTextToClipboard(text: string) {
await navigator.clipboard.writeText(text)
toast.success("Link Copied")
}
export type MediaShareContext = MediaShareTarget
export async function copyMediaShareLink(share: MediaShareContext) {
await copyTextToClipboard(mediaShareUrl(share))
await navigator.clipboard.writeText(
mediaShareUrl(window.location.origin, share)
)
toast.success("Link Copied")
}
export async function copyAlbumLink(albumId: string) {
await copyMediaShareLink({ type: "album", albumId })
}
export async function copySongLink(albumId: string, songId: string) {
await copyMediaShareLink({ type: "song", albumId, songId })
}
export async function copyPlaylistLink(
playlistId: string,
options?: { isFavorites?: boolean }
@@ -77,7 +27,3 @@ export async function copyPlaylistLink(
isFavorites: options?.isFavorites,
})
}
export async function copyArtistLink(artistId: string) {
await copyMediaShareLink({ type: "artist", artistId })
}
+13 -30
View File
@@ -1,4 +1,9 @@
import type { Doc } from "@otunes/convex/_generated/dataModel"
import {
parsePlaybackQuality,
playbackStreamPlan,
qualityKbps,
} from "@otunes/convex/playback-stream"
import crypto from "node:crypto"
import fs from "node:fs/promises"
import path from "node:path"
@@ -23,33 +28,6 @@ const jobs = new Map<string, HlsJob>()
const jobsByLookup = new Map<string, HlsJob>()
let lastCleanupAt = 0
export function qualityKbps(quality: string | null) {
if (quality === "low") {
return 64
}
if (quality === "high") {
return 256
}
return 128
}
export function selectHlsSourceCodec(
song: Doc<"songs">,
quality: string | null,
preferAtmos: boolean
) {
let sourceCodec = "lossless" in song.files ? "lossless" : "normal"
if (preferAtmos && "atmos" in song.files) {
sourceCodec = "atmos"
} else if (quality === "high" && "normal" in song.files) {
sourceCodec = "normal"
}
return sourceCodec
}
function hlsCacheRoot() {
return "/tmp/otunes"
}
@@ -164,9 +142,14 @@ export async function ensureHlsJob(
) {
await cleanupIdleHlsJobs()
const kbps = qualityKbps(quality)
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
const sourcePath = song.files[sourceCodec]
const plan = playbackStreamPlan(
song.files,
parsePlaybackQuality(quality),
preferAtmos
)
// HLS always transcodes, and lossless quality has no target bitrate.
const kbps = plan.kbps || qualityKbps("medium")
const sourcePath = song.files[plan.source]
const key = await hlsJobKey(song, sourcePath, kbps)
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
const existingJob = jobs.get(key)
+23 -3
View File
@@ -2,10 +2,13 @@ import { useConvex } from "convex/react"
import { useEffect, useMemo, useSyncExternalStore } from "react"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import {
getCachedSong,
getSongSnapshot,
getSongsVersion,
requestSongs,
songFromSnapshot,
subscribeSongs,
} from "@otunes/convex/client/song-cache"
import { isPersistentCacheLoaded } from "@/lib/persistent-cache"
@@ -48,7 +51,24 @@ export function useSongs(songIds: readonly Id<"songs">[]) {
return songs
}
export function useSong(songId: Id<"songs"> | null) {
const songIds = useMemo(() => (songId ? [songId] : []), [songId])
return useSongs(songIds)[0] ?? null
/**
* Like `useSongs` for one song, but only re-renders when that song changes
* once it is cached.
*/
export function useSong(songId: Id<"songs"> | null): BrowseSong | null {
const convex = useConvex()
const snapshot = useSyncExternalStore(
subscribeSongs,
() => getSongSnapshot(songId),
() => null
)
const song = songFromSnapshot(snapshot)
useEffect(() => {
if (songId && !song && isPersistentCacheLoaded()) {
requestSongs(convex, [songId])
}
}, [convex, songId, song, snapshot])
return song
}
-33
View File
@@ -1,33 +0,0 @@
export type PlaybackQuality = "low" | "medium" | "high" | "lossless"
export function songPlayUrl(
songId: string,
quality: PlaybackQuality | undefined,
preferAtmos: boolean | undefined
) {
const params = new URLSearchParams()
if (quality) {
params.set("quality", quality)
}
if (preferAtmos) {
params.set("preferAtmos", "true")
}
const query = params.toString()
return `/api/song/${songId}/play${query ? `?${query}` : ""}`
}
export function songHlsPlaylistUrl(
songId: string,
quality: PlaybackQuality | undefined,
preferAtmos: boolean | undefined
) {
const params = new URLSearchParams()
if (quality) {
params.set("quality", quality)
}
if (preferAtmos) {
params.set("preferAtmos", "true")
}
const query = params.toString()
return `/api/song/${songId}/play/hls${query ? `?${query}` : ""}`
}
@@ -0,0 +1,30 @@
/**
* Path data for the Dolby Atmos and Lossless badge marks, drawn with each
* platform's own SVG primitives.
*/
export const MARK_HEIGHT = 11
export const DOLBY_VIEW_BOX = "0 0 23 16"
export const DOLBY_WIDTH = (MARK_HEIGHT * 23) / 16
export const DOLBY_PATHS = [
"M0 0H2.5A8 8 0 0 1 2.5 16H0Z",
"M23 0H20.5A8 8 0 0 0 20.5 16H23Z",
]
export const LOSSLESS_VIEW_BOX = "28 154 544 271"
export const LOSSLESS_WIDTH = (MARK_HEIGHT * 544) / 271
export const LOSSLESS_PEAKS = [110, 215, 320]
export const LOSSLESS_THIN_WIDTH = 24
export const LOSSLESS_STROKES: [peak: number, d: string][] = [
[110, "M-70 320C-62 245 -38 166 0 166"],
[215, "M-70 320C-62 245 -38 166 0 166"],
[320, "M-30 185C-22 173 -11 166 0 166"],
[110, "M166 413C176 413 186 406 194 395"],
[215, "M166 413C200 413 226 340 240 275"],
[320, "M166 413C200 413 226 340 240 275"],
]
export const LOSSLESS_FALL =
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
export const LOSSLESS_FALL_GAP =
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
+15
View File
@@ -0,0 +1,15 @@
/** Reads the user id from a Convex Auth JWT without verifying it, for scoping client caches. */
export function userIdFromToken(token: string | null | undefined) {
const payload = token?.split(".")[1]
if (!payload) {
return null
}
try {
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
const subject = (JSON.parse(json) as { sub?: unknown }).sub
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
} catch {
return null
}
}
+96
View File
@@ -0,0 +1,96 @@
import type { OptimisticLocalStore, OptimisticUpdate } from "convex/browser"
import type { FunctionArgs, FunctionReference } from "convex/server"
import { api } from "../convex/_generated/api"
import type { Id } from "../convex/_generated/dataModel"
type FavoriteIds = {
favoriteSongs: Id<"songs">[]
favoriteAlbums: Id<"albums">[]
favoriteArtists: Id<"artists">[]
}
type FavoriteList = keyof FavoriteIds
function patchFavorites<List extends FavoriteList>(
store: OptimisticLocalStore,
list: List,
update: (ids: FavoriteIds[List]) => FavoriteIds[List]
) {
const current = store.getQuery(api.favorites.getUserFavorites, {})
if (!current) return
const next = update(current[list])
if (next !== current[list]) {
store.setQuery(
api.favorites.getUserFavorites,
{},
{
...current,
[list]: next,
}
)
}
}
function addFavorites<List extends FavoriteList>(
store: OptimisticLocalStore,
list: List,
ids: FavoriteIds[List]
) {
patchFavorites(store, list, (current) => {
const added = ids.filter((id) => !(current as string[]).includes(id))
return added.length === 0
? current
: ([...new Set([...current, ...added])] as FavoriteIds[List])
})
}
function removeFavorites<List extends FavoriteList>(
store: OptimisticLocalStore,
list: List,
ids: FavoriteIds[List]
) {
const removed = new Set<string>(ids)
patchFavorites(
store,
list,
(current) =>
(current as string[]).filter(
(id) => !removed.has(id)
) as FavoriteIds[List]
)
}
type FavoritesApi = typeof api.favorites
type FavoriteMutation = {
[
Name in keyof FavoritesApi
]: FavoritesApi[Name] extends FunctionReference<"mutation"> ? Name : never
}[keyof FavoritesApi]
/**
* Optimistic updates for the favorites mutations, so toggles show instantly.
* Pass them to `useMutation(...).withOptimisticUpdate(...)`.
*/
export const favoriteOptimisticUpdates = {
favoriteSong: (store, { songId }) =>
addFavorites(store, "favoriteSongs", [songId]),
favoriteSongs: (store, { songIds }) =>
addFavorites(store, "favoriteSongs", songIds),
unfavoriteSong: (store, { songId }) =>
removeFavorites(store, "favoriteSongs", [songId]),
unfavoriteSongs: (store, { songIds }) =>
removeFavorites(store, "favoriteSongs", songIds),
favoriteAlbum: (store, { albumId }) =>
addFavorites(store, "favoriteAlbums", [albumId]),
unfavoriteAlbum: (store, { albumId }) =>
removeFavorites(store, "favoriteAlbums", [albumId]),
favoriteArtist: (store, { artistId }) =>
addFavorites(store, "favoriteArtists", [artistId]),
unfavoriteArtist: (store, { artistId }) =>
removeFavorites(store, "favoriteArtists", [artistId]),
} satisfies {
[Name in FavoriteMutation]?: OptimisticUpdate<
FunctionArgs<FavoritesApi[Name]>
>
}
+34
View File
@@ -0,0 +1,34 @@
/** A piece of media that has a shareable page on the web app. */
export type MediaShareTarget =
| { type: "album"; albumId: string }
| { type: "song"; albumId: string; songId: string }
| { type: "playlist"; playlistId: string; isFavorites?: boolean }
| { type: "artist"; artistId: string }
/** Builds the web app URL for `share`, relative to `origin` (no trailing slash needed). */
export function mediaShareUrl(origin: string, share: MediaShareTarget) {
const base = origin.replace(/\/+$/, "")
switch (share.type) {
case "album":
return `${base}/album/${share.albumId}`
case "song":
return `${base}/album/${share.albumId}?s=${share.songId}`
case "playlist":
return share.isFavorites
? `${base}/playlist/favorites`
: `${base}/playlist/${share.playlistId}`
case "artist":
return `${base}/artist/${share.artistId}`
}
}
/** Songs are shared one at a time; collections are shared whatever is selected. */
export function shouldShowShare(
share: MediaShareTarget | undefined,
selectedCount: number
) {
if (!share) {
return false
}
return share.type !== "song" || selectedCount === 1
}
+5 -2
View File
@@ -1,6 +1,9 @@
import type { Id } from "../convex/_generated/dataModel"
/** Mirrors the queue rules in `packages/convex/convex/playback.ts`. */
/**
* Queue rules shared by the clients, which apply them locally, and the Convex
* playback mutations.
*/
function shuffleArray<T>(items: T[]): T[] {
const next = [...items]
@@ -30,7 +33,7 @@ export const EMPTY_PLAYBACK_QUEUE: PlaybackQueueState = {
progressSeconds: 0,
}
const MAX_QUEUE_HISTORY = 30
export const MAX_QUEUE_HISTORY = 30
function uniqueSongIds(songIds: Id<"songs">[]) {
return [...new Set(songIds)]
+13
View File
@@ -59,6 +59,19 @@ export function getCachedSong(songId: string) {
return readCache<BrowseSong>(songKey(songId))
}
/**
* `useSyncExternalStore` snapshot for one song: the song once cached, else the
* cache version, so a missing song re-renders on every cache change (to retry
* the fetch) and a cached one only when it changes.
*/
export function getSongSnapshot(songId: string | null) {
return songId ? (getCachedSong(songId) ?? version) : null
}
export function songFromSnapshot(snapshot: ReturnType<typeof getSongSnapshot>) {
return typeof snapshot === "object" ? snapshot : null
}
/** Stores song metadata so the player and queue can render it offline. */
export function rememberSongs(songs: readonly BrowseSong[]) {
let changed = false
+21
View File
@@ -0,0 +1,21 @@
type SearchableSong = {
title: string
artist: { name: string }
album: { title: string }
}
/** Case-insensitive match on title, artist, or album. A blank query keeps every song. */
export function filterSongs<T extends SearchableSong>(
songs: T[],
query: string
) {
const normalized = query.trim().toLowerCase()
if (!normalized) {
return songs
}
return songs.filter((song) =>
[song.title, song.artist.name, song.album.title].some((value) =>
value.toLowerCase().includes(normalized)
)
)
}
+82 -287
View File
@@ -12,10 +12,11 @@ import {
songsSortDirectionValidator,
songsSortKeyValidator,
} from "./library"
import * as playbackQueue from "../client/playback-queue"
import type { PlaybackQueueState } from "../client/playback-queue"
export type { HistorySong, QueueSong } from "./types"
const MAX_QUEUE_HISTORY = 30
const MAX_RECENTLY_PLAYED = 30
type RecentlyPlayedItem = Id<"albums"> | Id<"playlists">
@@ -79,15 +80,6 @@ async function recordPlaybackStart(
await recordRecentlyPlayedFromSong(ctx, userId, options.songIds[0])
}
function shuffleArray<T>(items: T[]): T[] {
const next = [...items]
for (let i = next.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[next[i], next[j]] = [next[j], next[i]]
}
return next
}
async function requireAuth(ctx: MutationCtx) {
const userId = await getAuthUserId(ctx)
if (userId === null) {
@@ -96,10 +88,6 @@ async function requireAuth(ctx: MutationCtx) {
return userId
}
function uniqueSongIds(songIds: Id<"songs">[]) {
return [...new Set(songIds)]
}
function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) {
if (first.length !== second.length) {
return false
@@ -122,28 +110,6 @@ function haveSameSongCounts(first: Id<"songs">[], second: Id<"songs">[]) {
return counts.size === 0
}
function appendToQueueHistory(
history: Id<"songs">[],
songId: Id<"songs">
): Id<"songs">[] {
const next = [...history, songId]
if (next.length <= MAX_QUEUE_HISTORY) {
return next
}
return next.slice(next.length - MAX_QUEUE_HISTORY)
}
function appendManyToQueueHistory(
history: Id<"songs">[],
songIds: Id<"songs">[]
): Id<"songs">[] {
let next = history
for (const songId of songIds) {
next = appendToQueueHistory(next, songId)
}
return next
}
async function patchPlayback(
ctx: MutationCtx,
userId: Id<"users">,
@@ -168,24 +134,38 @@ async function patchPlayback(
return playbackRevision
}
async function setQueueState(
/** Applies a queue rule to the user's stored playback state. */
async function updateQueue(
ctx: MutationCtx,
userId: Id<"users">,
patch: {
songQueue: Id<"songs">[]
shuffleEnabled?: boolean
currentSongProgress?: number
resetHistory?: boolean
}
update: (state: PlaybackQueueState) => PlaybackQueueState
) {
await patchPlayback(ctx, userId, {
songQueue: patch.songQueue,
currentSongProgress: patch.currentSongProgress ?? 0,
...(patch.resetHistory ? { queueHistory: [] } : {}),
...(patch.shuffleEnabled !== undefined
? { shuffleEnabled: patch.shuffleEnabled }
: {}),
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const state: PlaybackQueueState = {
queue: user.songQueue ?? [],
history: user.queueHistory ?? [],
shuffleEnabled: user.shuffleEnabled ?? false,
repeatEnabled: user.repeatEnabled ?? "none",
progressSeconds: user.currentSongProgress ?? 0,
}
const next = update(state)
if (next === state) {
return next
}
await ctx.db.patch(userId, {
songQueue: next.queue,
queueHistory: next.history,
shuffleEnabled: next.shuffleEnabled,
repeatEnabled: next.repeatEnabled,
currentSongProgress: next.progressSeconds,
playbackRevision: (user.playbackRevision ?? 0) + 1,
})
return next
}
export const getPlaybackState = query({
@@ -241,7 +221,7 @@ export const syncPlaybackState = mutation({
const userId = await requireAuth(ctx)
return await patchPlayback(ctx, userId, {
songQueue: args.songQueue,
queueHistory: args.queueHistory.slice(-MAX_QUEUE_HISTORY),
queueHistory: args.queueHistory.slice(-playbackQueue.MAX_QUEUE_HISTORY),
shuffleEnabled: args.shuffleEnabled,
repeatEnabled: args.repeatEnabled,
currentSongProgress: Math.max(0, Math.floor(args.currentSongProgress)),
@@ -336,12 +316,9 @@ export const playInOrder = mutation({
},
handler: async (ctx, { songIds, playlistId }) => {
const userId = await requireAuth(ctx)
const queue = uniqueSongIds(songIds)
await setQueueState(ctx, userId, {
songQueue: queue,
shuffleEnabled: false,
resetHistory: true,
})
const { queue } = await updateQueue(ctx, userId, (state) =>
playbackQueue.startQueue(state, songIds, false)
)
await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
},
})
@@ -353,73 +330,54 @@ export const playShuffled = mutation({
},
handler: async (ctx, { songIds, playlistId }) => {
const userId = await requireAuth(ctx)
const queue = shuffleArray(uniqueSongIds(songIds))
await setQueueState(ctx, userId, {
songQueue: queue,
shuffleEnabled: true,
resetHistory: true,
})
const { queue } = await updateQueue(ctx, userId, (state) =>
playbackQueue.startQueue(state, songIds, true)
)
await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
},
})
function orderSongsForInsert(
async function addToQueue(
ctx: MutationCtx,
songIds: Id<"songs">[],
shuffleEnabled: boolean
): Id<"songs">[] {
return shuffleEnabled ? shuffleArray(songIds) : songIds
position: "next" | "last"
) {
if (songIds.length === 0) {
return
}
const userId = await requireAuth(ctx)
await updateQueue(ctx, userId, (state) =>
playbackQueue.addToQueue(state, songIds, position)
)
}
export const addToQueueNext = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
if (songIds.length === 0) {
return
}
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
const queue = user.songQueue ?? []
if (queue.length === 0) {
await setQueueState(ctx, userId, { songQueue: toAdd })
return
}
const [current, ...rest] = queue
await setQueueState(ctx, userId, {
songQueue: [current, ...toAdd, ...rest],
})
await addToQueue(ctx, songIds, "next")
},
})
export const addToQueueLast = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
if (songIds.length === 0) {
return
}
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
const queue = user.songQueue ?? []
await setQueueState(ctx, userId, {
songQueue: queue.length === 0 ? toAdd : [...queue, ...toAdd],
})
await addToQueue(ctx, songIds, "last")
},
})
async function playFromSongIn(
ctx: MutationCtx,
userId: Id<"users">,
songId: Id<"songs">,
songIds: Id<"songs">[]
) {
await updateQueue(ctx, userId, (state) =>
playbackQueue.startQueueFromSong(state, songId, songIds)
)
await recordRecentlyPlayedFromSong(ctx, userId, songId)
}
export const playFromSong = mutation({
args: {
songId: v.id("songs"),
@@ -427,24 +385,7 @@ export const playFromSong = mutation({
},
handler: async (ctx, { songId, songIds }) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const index = songIds.indexOf(songId)
const rest = user.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
await setQueueState(ctx, userId, {
songQueue: [songId, ...queueRest],
resetHistory: true,
})
await recordRecentlyPlayedFromSong(ctx, userId, songId)
await playFromSongIn(ctx, userId, songId, songIds)
},
})
@@ -496,17 +437,13 @@ async function playCollection(
}
) {
const userId = await requireAuth(ctx)
const unique = uniqueSongIds(options.songIds)
if (unique.length === 0) {
if (options.songIds.length === 0) {
return
}
const queue = options.shuffled ? shuffleArray(unique) : unique
await setQueueState(ctx, userId, {
songQueue: queue,
shuffleEnabled: options.shuffled,
resetHistory: true,
})
const { queue } = await updateQueue(ctx, userId, (state) =>
playbackQueue.startQueue(state, options.songIds, options.shuffled)
)
await recordPlaybackStart(ctx, userId, {
songIds: queue,
playlistId: options.playlistId,
@@ -585,25 +522,8 @@ export const playFromLibrarySong = mutation({
},
handler: async (ctx, { songId, sortKey, sortDirection }) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const songIds = await getSortedLibrarySongIds(ctx, sortKey, sortDirection)
const index = songIds.indexOf(songId)
const rest = user.shuffleEnabled
? uniqueSongIds(songIds).filter((id) => id !== songId)
: index === -1
? []
: songIds.slice(index + 1)
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
await setQueueState(ctx, userId, {
songQueue: [songId, ...queueRest],
resetHistory: true,
})
await recordRecentlyPlayedFromSong(ctx, userId, songId)
await playFromSongIn(ctx, userId, songId, songIds)
},
})
@@ -611,24 +531,7 @@ export const toggleShuffle = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const shuffleEnabled = !(user.shuffleEnabled ?? false)
const queue = user.songQueue ?? []
if (shuffleEnabled && queue.length > 1) {
const [current, ...upNext] = queue
await patchPlayback(ctx, userId, {
shuffleEnabled: true,
songQueue: [current, ...shuffleArray(upNext)],
})
return
}
await patchPlayback(ctx, userId, { shuffleEnabled })
await updateQueue(ctx, userId, playbackQueue.toggleShuffle)
},
})
@@ -636,16 +539,7 @@ export const cycleRepeat = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const current = user.repeatEnabled ?? "none"
const next =
current === "none" ? "once" : current === "once" ? "always" : "none"
await patchPlayback(ctx, userId, { repeatEnabled: next })
await updateQueue(ctx, userId, playbackQueue.cycleRepeat)
},
})
@@ -653,11 +547,7 @@ export const clearQueue = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
await patchPlayback(ctx, userId, {
songQueue: [],
queueHistory: [],
currentSongProgress: 0,
})
await updateQueue(ctx, userId, playbackQueue.clearQueue)
},
})
@@ -665,25 +555,11 @@ export const reorderQueue = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const queue = user.songQueue ?? []
if (!haveSameSongCounts(queue, songIds)) {
throw new ConvexError("Invalid queue order")
}
const currentSongChanged = songIds.length > 0 && songIds[0] !== queue[0]
const history =
currentSongChanged && queue.length > 0
? appendToQueueHistory(user.queueHistory ?? [], queue[0])
: (user.queueHistory ?? [])
await patchPlayback(ctx, userId, {
songQueue: songIds,
queueHistory: history,
...(currentSongChanged ? { currentSongProgress: 0 } : {}),
await updateQueue(ctx, userId, (state) => {
if (!haveSameSongCounts(state.queue, songIds)) {
throw new ConvexError("Invalid queue order")
}
return playbackQueue.reorderQueue(state, songIds)
})
},
})
@@ -692,24 +568,9 @@ export const skipToQueueIndex = mutation({
args: { index: v.number() },
handler: async (ctx, { index }) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const queue = user.songQueue ?? []
if (index < 0 || index >= queue.length || index === 0) {
return
}
const skipped = queue.slice(0, index)
const history = appendManyToQueueHistory(user.queueHistory ?? [], skipped)
await patchPlayback(ctx, userId, {
songQueue: queue.slice(index),
queueHistory: history,
currentSongProgress: 0,
})
await updateQueue(ctx, userId, (state) =>
playbackQueue.skipToQueueIndex(state, index)
)
},
})
@@ -717,48 +578,7 @@ export const skipNext = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const queue = user.songQueue ?? []
if (queue.length === 0) {
return
}
const repeat = user.repeatEnabled ?? "none"
if (repeat === "once") {
await patchPlayback(ctx, userId, { currentSongProgress: 0 })
return
}
const [current, ...rest] = queue
if (repeat === "always") {
await patchPlayback(ctx, userId, {
songQueue: [...rest, current],
currentSongProgress: 0,
})
return
}
if (rest.length === 0) {
await patchPlayback(ctx, userId, {
songQueue: [current],
currentSongProgress: 0,
})
return
}
const history = appendToQueueHistory(user.queueHistory ?? [], current)
await patchPlayback(ctx, userId, {
songQueue: rest,
queueHistory: history,
currentSongProgress: 0,
})
await updateQueue(ctx, userId, playbackQueue.skipNext)
},
})
@@ -766,32 +586,7 @@ export const skipPrevious = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const queue = user.songQueue ?? []
const history = user.queueHistory ?? []
if (queue.length === 0) {
return
}
if (history.length === 0) {
await patchPlayback(ctx, userId, { currentSongProgress: 0 })
return
}
const [current, ...rest] = queue
const previous = history[history.length - 1]
const newHistory = history.slice(0, -1)
await patchPlayback(ctx, userId, {
songQueue: [previous, current, ...rest],
queueHistory: newHistory,
currentSongProgress: 0,
})
await updateQueue(ctx, userId, playbackQueue.skipPrevious)
},
})
+20
View File
@@ -23,10 +23,26 @@
"types": "./server-url.ts",
"default": "./server-url.ts"
},
"./client/audio-format-marks": {
"types": "./client/audio-format-marks.ts",
"default": "./client/audio-format-marks.ts"
},
"./client/auth-token": {
"types": "./client/auth-token.ts",
"default": "./client/auth-token.ts"
},
"./client/cached-query": {
"types": "./client/cached-query.ts",
"default": "./client/cached-query.ts"
},
"./client/favorites": {
"types": "./client/favorites.ts",
"default": "./client/favorites.ts"
},
"./client/media-links": {
"types": "./client/media-links.ts",
"default": "./client/media-links.ts"
},
"./client/persistent-cache": {
"types": "./client/persistent-cache.ts",
"default": "./client/persistent-cache.ts"
@@ -42,6 +58,10 @@
"./client/song-cache": {
"types": "./client/song-cache.ts",
"default": "./client/song-cache.ts"
},
"./client/song-search": {
"types": "./client/song-search.ts",
"default": "./client/song-search.ts"
}
},
"scripts": {
+66 -1
View File
@@ -1,5 +1,21 @@
export type PlaybackQuality = "low" | "medium" | "high" | "lossless"
const PLAYBACK_QUALITIES: readonly string[] = [
"low",
"medium",
"high",
"lossless",
] satisfies PlaybackQuality[]
/** Reads a `quality` request parameter; anything unknown means the default. */
export function parsePlaybackQuality(
value: string | null | undefined
): PlaybackQuality | undefined {
return value && PLAYBACK_QUALITIES.includes(value)
? (value as PlaybackQuality)
: undefined
}
export function qualityKbps(quality: PlaybackQuality | null | undefined) {
if (quality === "low") {
return 64
@@ -16,9 +32,15 @@ export function qualityKbps(quality: PlaybackQuality | null | undefined) {
return 0
}
export type PlaybackSource = "atmos" | "lossless" | "normal"
export type PlaybackStreamPlan = {
playbackQuality: PlaybackQuality
preferAtmos: boolean
/** The file that is streamed as-is, or transcoded when `transcodeNeeded`. */
source: PlaybackSource
/** AAC bitrate to transcode to; 0 for lossless quality. */
kbps: number
transcodeNeeded: boolean
useHls: boolean
}
@@ -29,27 +51,70 @@ export function playbackStreamPlan(
preferAtmos: boolean
): PlaybackStreamPlan {
const playbackQuality = quality ?? "medium"
const kbps = playbackQuality === "lossless" ? 0 : qualityKbps(playbackQuality)
const kbps = qualityKbps(playbackQuality)
const effectivePreferAtmos = preferAtmos && "atmos" in files
let source: PlaybackSource = "lossless" in files ? "lossless" : "normal"
let transcodeNeeded = true
if (effectivePreferAtmos) {
source = "atmos"
transcodeNeeded = false
} else if (kbps === 0 && "lossless" in files) {
source = "lossless"
transcodeNeeded = false
} else if (kbps === 0 || (kbps === 256 && "normal" in files)) {
source = "normal"
transcodeNeeded = false
}
return {
playbackQuality,
preferAtmos: effectivePreferAtmos,
source,
kbps,
transcodeNeeded,
useHls: transcodeNeeded,
}
}
function songStreamQuery(
params: URLSearchParams,
quality: PlaybackQuality | undefined,
preferAtmos: boolean | undefined
) {
if (quality) {
params.set("quality", quality)
}
if (preferAtmos) {
params.set("preferAtmos", "true")
}
const query = params.toString()
return query ? `?${query}` : ""
}
export function songPlayPath(
songId: string,
quality: PlaybackQuality | undefined,
preferAtmos: boolean | undefined,
options?: { losslessFormat?: "alac" }
) {
const params = new URLSearchParams()
if (options?.losslessFormat) {
params.set("losslessFormat", options.losslessFormat)
}
return `/api/song/${songId}/play${songStreamQuery(params, quality, preferAtmos)}`
}
export function songHlsPlaylistPath(
songId: string,
quality: PlaybackQuality | undefined,
preferAtmos: boolean | undefined
) {
const query = songStreamQuery(new URLSearchParams(), quality, preferAtmos)
return `/api/song/${songId}/play/hls${query}`
}
export type PlaybackFormat = "atmos" | "lossless"
/** The labeled format a song streams in under the plan, if any. */