refactor: share logic duplicated across web, mobile, and Convex #103
No files matched your search
@@ -89,20 +89,6 @@ export default function AlbumScreen() {
|
||||
[album]
|
||||
)
|
||||
|
||||
// Older servers do not include album format availability yet.
|
||||
const formatTracks = useCachedQuery(
|
||||
api.library.getSongsForPlayback,
|
||||
album && (album.hasLossless === undefined || album.hasAtmos === undefined)
|
||||
? { ids: songIds }
|
||||
: "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)
|
||||
|
||||
useEffect(() => {
|
||||
if (album) {
|
||||
rememberSongs(albumDetailSongs(album))
|
||||
@@ -374,7 +360,7 @@ export default function AlbumScreen() {
|
||||
{metadata}
|
||||
</PaletteText>
|
||||
) : null}
|
||||
{hasLossless ? (
|
||||
{album.hasLossless ? (
|
||||
<>
|
||||
{metadata ? (
|
||||
<PaletteText
|
||||
@@ -392,9 +378,9 @@ export default function AlbumScreen() {
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
{hasAtmos ? (
|
||||
{album.hasAtmos ? (
|
||||
<>
|
||||
{metadata || hasLossless ? (
|
||||
{metadata || album.hasLossless ? (
|
||||
<PaletteText
|
||||
tone="secondaryForeground"
|
||||
style={{ color: palette.secondaryForeground }}
|
||||
|
||||
@@ -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 { useProfileImageUrl } from "@/hooks/use-profile-image-url"
|
||||
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"
|
||||
|
||||
@@ -418,7 +418,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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 FavoriteTables = { song: "songs"; album: "albums"; artist: "artists" }
|
||||
@@ -69,110 +72,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,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,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
|
||||
import { atmosEnabled } from "@/lib/playback-capabilities"
|
||||
import {
|
||||
createAudioPlaylist,
|
||||
setAudioModeAsync,
|
||||
@@ -132,11 +132,7 @@ export function useNativePlaylistSync({
|
||||
])
|
||||
: ""
|
||||
const userPlaybackKey = user
|
||||
? JSON.stringify([
|
||||
user._id,
|
||||
user.playbackQuality,
|
||||
dolbyAtmosSupported && (user.preferAtmos ?? false),
|
||||
])
|
||||
? JSON.stringify([user._id, user.playbackQuality, atmosEnabled(user)])
|
||||
: ""
|
||||
|
||||
const settleWaiters = useCallback(() => {
|
||||
@@ -462,7 +458,7 @@ export function useNativePlaylistSync({
|
||||
}
|
||||
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(
|
||||
@@ -503,7 +499,7 @@ export function useNativePlaylistSync({
|
||||
const plan = playbackStreamPlan(
|
||||
song.files,
|
||||
user.playbackQuality,
|
||||
dolbyAtmosSupported && (user.preferAtmos ?? false)
|
||||
atmosEnabled(user)
|
||||
)
|
||||
sources.set(
|
||||
song.id,
|
||||
|
||||
@@ -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 }
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
@@ -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 }
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
parsePlaybackQuality,
|
||||
playbackStreamPlan,
|
||||
} from "@otunes/convex/playback-stream"
|
||||
import { audioContentTypeForPath } from "@/lib/audio-content-type"
|
||||
import { seekableLosslessFile } from "@/lib/server-lossless"
|
||||
import { getSongSource } from "@/lib/server-song"
|
||||
@@ -118,34 +122,17 @@ export async function GET(
|
||||
try {
|
||||
const song = await getSongSource(id)
|
||||
|
||||
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
|
||||
}
|
||||
)
|
||||
|
||||
if (!transcodeNeeded && originalCodec === "lossless") {
|
||||
// Native iOS playback does not identify itself as Safari.
|
||||
|
||||
@@ -24,8 +24,6 @@ import {
|
||||
import { TrackRow } from "@/components/track-row"
|
||||
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 {
|
||||
useMediaActions,
|
||||
useTrackListMediaAction,
|
||||
@@ -116,20 +114,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])
|
||||
@@ -260,15 +244,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" />
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -30,6 +30,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 =
|
||||
@@ -47,19 +48,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
|
||||
}
|
||||
|
||||
// Lets the same items render inside a dropdown or a right-click menu.
|
||||
const MenuKindContext = React.createContext<"dropdown" | "context">("dropdown")
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
@@ -183,14 +185,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>
|
||||
@@ -245,12 +247,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
|
||||
|
||||
@@ -40,6 +40,7 @@ import { playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import { copyPlaylistLink } from "@/lib/media-links"
|
||||
import { sumDurationSeconds } from "@/lib/media-summary"
|
||||
import { rememberSongs } from "@/lib/song-cache"
|
||||
import { filterSongs } from "@otunes/convex/client/song-search"
|
||||
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
|
||||
|
||||
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
|
||||
@@ -79,17 +80,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">),
|
||||
@@ -156,7 +150,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
runSongsAction(action, playlistSongIds)
|
||||
}
|
||||
|
||||
const canReorder = isOwner && !isFavorites && !normalizedQuery
|
||||
const canReorder = isOwner && !isFavorites && !isSearching
|
||||
|
||||
function handleRowSelect(index: number, event: React.MouseEvent) {
|
||||
const songId = filteredSongs[index].id
|
||||
@@ -470,7 +464,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>
|
||||
|
||||
@@ -1,62 +1,16 @@
|
||||
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
|
||||
}
|
||||
|
||||
function albumShareUrl(albumId: string) {
|
||||
return `${mediaOrigin()}/album/${albumId}`
|
||||
}
|
||||
|
||||
function songShareUrl(albumId: string, songId: string) {
|
||||
return `${mediaOrigin()}/album/${albumId}?s=${songId}`
|
||||
}
|
||||
|
||||
function playlistShareUrl(
|
||||
playlistId: string,
|
||||
options?: { isFavorites?: boolean }
|
||||
) {
|
||||
if (options?.isFavorites) {
|
||||
return `${mediaOrigin()}/playlist/favorites`
|
||||
}
|
||||
return `${mediaOrigin()}/playlist/${playlistId}`
|
||||
}
|
||||
|
||||
function artistShareUrl(artistId: string) {
|
||||
return `${mediaOrigin()}/artist/${artistId}`
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
+13
-30
@@ -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"
|
||||
@@ -50,33 +55,6 @@ const state = (globalState.__otunesHls ??= {
|
||||
lastCleanupAt: 0,
|
||||
})
|
||||
|
||||
export function qualityKbps(quality: string | null) {
|
||||
if (quality === "low") {
|
||||
return 64
|
||||
}
|
||||
|
||||
if (quality === "high") {
|
||||
return 256
|
||||
}
|
||||
|
||||
return 128
|
||||
}
|
||||
|
||||
export function selectHlsSourceCodec(
|
||||
song: SongSource,
|
||||
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 hlsLookupKey(
|
||||
songId: string,
|
||||
quality: string | null,
|
||||
@@ -305,9 +283,14 @@ export async function ensureHlsJob(
|
||||
): Promise<HlsJob> {
|
||||
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)
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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]>
|
||||
>
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { ConvexError } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { MAX_QUEUE_HISTORY } from "../client/playback-queue"
|
||||
import { MAX_QUEUE_LENGTH } from "./limits"
|
||||
|
||||
const MAX_QUEUE_HISTORY = 30
|
||||
|
||||
export type RepeatMode = Doc<"playbackStates">["repeatEnabled"]
|
||||
|
||||
export type PlaybackState = Pick<
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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. */
|
||||
|
||||
Reference in new issue
Block a user