Compare commits

..
  • fix(web): close leaked audio streams and ffmpeg jobs
    - File and ffmpeg streams cancel when the client aborts (seek, track change)
    - ffmpeg transcodes respect backpressure and are killed on cancel
    - HLS jobs dedupe in-flight creation; segments use -hls_flags temp_file
    - Evicted HLS jobs kill ffmpeg; concurrent ffmpeg is capped
    - Persistent, size-capped transcode cache (OTUNES_CACHE_DIR, OTUNES_CACHE_MAX_MB)
    - Codec info cached per file; drop per-chunk ffmpeg and codec logging
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
50 changed files with 3043 additions and 1682 deletions

No files matched your search

+6 -5
View File
@@ -54,11 +54,12 @@ playwright.config.*
*~
*.log
# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values
# into the bundle and the Convex CLI reads .env.local on deploy.
**/.env
**/.env.*
!**/.env.example
# Environment variables (only commit template files)
.env
.env*.local
.env.development
.env.test
.env.production.local
# Docker configuration files (not needed inside build context)
Dockerfile*
+1 -6
View File
@@ -195,12 +195,7 @@ RUN node --version \
&& ldd /convex/generate_key \
&& ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found'
# The backend gets its own user so the web server cannot read the database or
# instance secret. It joins the otunes group to clean up the web server's HLS
# cache in /tmp/otunes.
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes \
&& useradd --system --user-group --groups otunes --create-home --home-dir /home/convex \
--shell /usr/sbin/nologin convex
RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes
COPY --from=convex-functions /app /opt/otunes/convex
COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs
@@ -0,0 +1 @@
export { default } from "../library/queue"
@@ -35,7 +35,7 @@ import {
MediaActionMenu,
MediaContextMenu,
type MediaAction,
} from "@/components/media-context-menu"
} from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
@@ -488,7 +488,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
action: MediaAction
) => Promise<void>
}) {
const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable
const Row = Platform.OS === "ios" ? SongSwipeRow : Pressable
const { config } = useServerConfig()
return (
<MediaContextMenu
@@ -523,7 +523,6 @@ const AlbumTrackRow = memo(function AlbumTrackRow({
group={swipeGroup}
backgroundColor={palette.background}
onPlayNext={() => void onAction(track, album, "play-next")}
onAddToQueue={() => void onAction(track, album, "play-last")}
style={styles.trackRow}
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
>
@@ -6,7 +6,7 @@ import { Ionicons } from "@expo/vector-icons"
import { CoverImage } from "@/components/cover-image"
import { MediaGridList } from "@/components/media-cards"
import { MediaActionMenu } from "@/components/media-context-menu"
import { MediaActionMenu } from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset } from "@/components/player"
@@ -46,7 +46,7 @@ import {
import {
MediaActionMenu,
type MediaAction,
} from "@/components/media-context-menu"
} from "@/components/media-actions-sheet"
import { CollectionDetailSkeleton } from "@/components/skeletons"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongListRow } from "@/components/player"
@@ -314,6 +314,7 @@ function PlaylistContent({
deletePlaylist,
handlePlaylistDetailAction,
palette.foreground,
palette.background,
palette.isDark,
playlistId,
playlist?.title,
@@ -433,18 +434,11 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
palette={palette}
inset
swipe={
Platform.OS !== "web"
Platform.OS === "ios"
? {
group: swipeGroup,
backgroundColor: palette.background,
onPlayNext: () => onAction(song, "play-next"),
onAddToQueue: () => onAction(song, "play-last"),
onRemove:
Platform.OS === "android" && removable
? () => {
void onRemove(song.id)
}
: undefined,
}
: undefined
}
@@ -453,7 +447,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({
/>
)
if (Platform.OS !== "web" || !removable) {
if (Platform.OS === "ios" || !removable) {
return row
}
+186
View File
@@ -0,0 +1,186 @@
import { Stack, useRouter } from "expo-router"
import { memo, useCallback, useMemo } from "react"
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
import { Button } from "@/components/ui/primitives"
import { contentBottomInset, SongRow } from "@/components/player"
import { SongRowSkeleton } from "@/components/skeletons"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { longListProps } from "@/lib/list"
import { useSong, useSongs } from "@/lib/song-cache"
import { spacing, useThemeColors } from "@/lib/theme"
/** `key` stays stable when earlier songs leave the queue, so rows are not remounted on skip. */
type QueueItem = { songId: Id<"songs">; queueIndex: number; key: string }
function queueItemKey(item: QueueItem) {
return item.key
}
const QueueRow = memo(function QueueRow({
songId,
queueIndex,
isLast,
isCurrent,
onSkipTo,
onMove,
}: Omit<QueueItem, "key"> & {
isLast: boolean
isCurrent: boolean
onSkipTo: (index: number) => void
onMove: (index: number, direction: -1 | 1) => void
}) {
const colors = useThemeColors()
const song = useSong(songId)
return (
<View>
{song ? (
<SongRow song={song} onPress={() => onSkipTo(queueIndex)} />
) : (
<SongRowSkeleton />
)}
<View style={styles.queueActions}>
<Pressable
disabled={queueIndex === 0}
onPress={() => onMove(queueIndex, -1)}
>
<Text style={{ color: colors.foreground }}>Move up</Text>
</Pressable>
<Pressable disabled={isLast} onPress={() => onMove(queueIndex, 1)}>
<Text style={{ color: colors.foreground }}>Move down</Text>
</Pressable>
{isCurrent ? (
<Text style={{ color: colors.primary, fontWeight: "700" }}>
Now playing
</Text>
) : null}
</View>
</View>
)
})
export default function QueueScreen() {
const router = useRouter()
const colors = useThemeColors()
const { queueSongIds, queueHistorySongIds } = usePlaybackQueue()
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
const historySongs = useSongs(queueHistorySongIds)
const items = useMemo<QueueItem[]>(() => {
const occurrences = new Map<string, number>()
return queueSongIds.map((songId, queueIndex) => {
const occurrence = occurrences.get(songId) ?? 0
occurrences.set(songId, occurrence + 1)
return { songId, queueIndex, key: `${songId}:${occurrence}` }
})
}, [queueSongIds])
const moveSong = useCallback(
(fromIndex: number, direction: -1 | 1) => {
const toIndex = fromIndex + direction
if (toIndex < 0 || toIndex >= queueSongIds.length) return
const next = [...queueSongIds]
const [item] = next.splice(fromIndex, 1)
next.splice(toIndex, 0, item)
void reorderQueue(next)
},
[queueSongIds, reorderQueue]
)
function handleClearQueue() {
if (router.canGoBack()) {
router.back()
setTimeout(() => {
void clearQueue()
}, 0)
return
}
void clearQueue()
}
return (
<>
<Stack.Screen
options={{
headerRight: () =>
queueSongIds.length > 0 ? (
<Button
title="Clear"
variant="ghost"
onPress={handleClearQueue}
/>
) : null,
}}
/>
<FlatList
style={{ flex: 1, backgroundColor: colors.background }}
ListHeaderComponent={
<View>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
Up Next
</Text>
{queueSongIds.length === 0 ? (
<Text style={[styles.empty, { color: colors.mutedForeground }]}>
Queue is empty
</Text>
) : null}
</View>
}
{...longListProps}
data={items}
keyExtractor={queueItemKey}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
renderItem={({ item }) => (
<QueueRow
songId={item.songId}
queueIndex={item.queueIndex}
isLast={item.queueIndex === queueSongIds.length - 1}
isCurrent={item.queueIndex === 0}
onSkipTo={skipToQueueIndex}
onMove={moveSong}
/>
)}
ListFooterComponent={
queueHistorySongIds.length > 0 ? (
<View style={styles.history}>
<Text style={[styles.section, { color: colors.mutedForeground }]}>
History
</Text>
{historySongs.map((song, index) =>
song ? (
<SongRow key={`${song.id}-${index}`} song={song} />
) : (
<SongRowSkeleton
key={`${queueHistorySongIds[index]}-${index}`}
/>
)
)}
</View>
) : undefined
}
/>
</>
)
}
const styles = StyleSheet.create({
section: {
paddingHorizontal: spacing.lg,
paddingTop: spacing.md,
fontSize: 12,
fontWeight: "700",
textTransform: "uppercase",
},
empty: { padding: spacing.lg },
queueActions: {
flexDirection: "row",
gap: spacing.lg,
paddingHorizontal: spacing.lg,
paddingBottom: spacing.sm,
},
history: { marginTop: spacing.lg },
})
@@ -23,6 +23,7 @@ import { useServerConfig } from "@/contexts/server-config"
import {
setArtworkColorsEnabled,
useArtworkColorsEnabled,
useArtworkColorPreferenceLoaded,
} from "@/lib/artwork-color-preference"
import { initialsFromName } from "@/lib/format"
import { useCachedQuery } from "@/hooks/use-cached-query"
@@ -171,6 +172,7 @@ export default function SettingsScreen() {
function AppearanceSection() {
const enabled = useArtworkColorsEnabled()
const loaded = useArtworkColorPreferenceLoaded()
const [saving, setSaving] = useState(false)
return (
@@ -178,8 +180,8 @@ function AppearanceSection() {
<SwitchRow
title="New artwork colors"
subtitle="Use the new color algorithm on this device."
value={enabled ?? false}
disabled={enabled === undefined || saving}
value={enabled}
disabled={!loaded || saving}
onValueChange={async (checked) => {
setSaving(true)
try {
@@ -0,0 +1 @@
export { default } from "../home/queue"
@@ -0,0 +1 @@
export { default } from "../home/queue"
+1 -1
View File
@@ -39,7 +39,7 @@ import { MarqueeText } from "@/components/marquee-text"
import {
MediaActionMenu,
type MediaAction,
} from "@/components/media-context-menu"
} from "@/components/media-actions-sheet"
import {
NowPlayingQueue,
QUEUE_HORIZONTAL_INSET,
@@ -0,0 +1,7 @@
export type { MediaAction, MediaMenuConfig, MediaNavigation } from "@/components/media-context-menu"
export type { MediaShareContext } from "@/lib/media-links"
export {
buildMediaMenuActions,
MediaActionMenu,
MediaContextMenu,
} from "@/components/media-context-menu"
+1 -7
View File
@@ -45,8 +45,6 @@ export const SongRow = memo(function SongRow({
swipe?: {
group: SwipeRowGroup
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
backgroundColor: string
}
/** Album/playlist layout: the divider starts at the title, not the artwork. */
@@ -109,12 +107,10 @@ export const SongRow = memo(function SongRow({
? styles.insetRow
: [styles.row, { borderBottomColor: divider }]
const row =
swipe && Platform.OS !== "web" ? (
swipe && Platform.OS === "ios" ? (
<SongSwipeRow
group={swipe.group}
onPlayNext={swipe.onPlayNext}
onAddToQueue={swipe.onAddToQueue}
onRemove={swipe.onRemove}
backgroundColor={swipe.backgroundColor}
onPress={onPress}
style={rowStyle}
@@ -171,8 +167,6 @@ export const SongListRow = memo(function SongListRow({
swipe?: {
group: SwipeRowGroup
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
backgroundColor: string
}
onPlay: (song: BrowseSong) => void
+31 -160
View File
@@ -1,4 +1,3 @@
import { Ionicons } from "@expo/vector-icons"
import * as Haptics from "expo-haptics"
import { SymbolView } from "expo-symbols"
import {
@@ -9,7 +8,6 @@ import {
type ReactNode,
} from "react"
import {
Platform,
Pressable,
StyleSheet,
type StyleProp,
@@ -28,10 +26,7 @@ import Animated, {
import { scheduleOnRN } from "react-native-worklets"
import type { SwipeRowGroup } from "@/components/ios-swipe-to-remove-row"
const IS_ANDROID = Platform.OS === "android"
const ACTION_WIDTH = 82
const LEADING_ACTION_WIDTH = 72
const SPRING = { duration: 450, dampingRatio: 1 }
function impact() {
@@ -46,8 +41,6 @@ export function SongSwipeRow({
group,
onPress,
onPlayNext,
onAddToQueue,
onRemove,
}: {
children: ReactNode
style?: StyleProp<ViewStyle>
@@ -55,10 +48,7 @@ export function SongSwipeRow({
group: SwipeRowGroup
onPress?: () => void
onPlayNext: () => void
onAddToQueue: () => void
onRemove?: () => void
}) {
const hasRemove = IS_ANDROID && !!onRemove
const x = useSharedValue(0)
const startX = useSharedValue(0)
const width = useSharedValue(0)
@@ -88,10 +78,10 @@ export function SongSwipeRow({
const activate = useCallback(
(side: number) => {
close()
if (side > 0) onAddToQueue()
if (side > 0) onPlayNext()
// Download is intentionally a placeholder.
},
[close, onAddToQueue]
[close, onPlayNext]
)
const tapRow = useCallback(() => {
if (open) close()
@@ -115,13 +105,7 @@ export function SongSwipeRow({
Math.min(width.value, startX.value + event.translationX)
)
const commit =
Math.abs(x.value) >
Math.max(
x.value > 0
? LEADING_ACTION_WIDTH * 2
: ACTION_WIDTH * (hasRemove ? 2 : 1),
width.value * 0.55
)
Math.abs(x.value) > Math.max(ACTION_WIDTH, width.value * 0.55)
if (commit !== committed.value) {
committed.value = commit
commitProgress.value = withSpring(commit ? 1 : 0, SPRING)
@@ -140,16 +124,10 @@ export function SongSwipeRow({
Math.abs(x.value) > 10 && projected * side > ACTION_WIDTH / 2
? side
: 0
x.value = withSpring(
target *
(target > 0
? LEADING_ACTION_WIDTH * 2
: ACTION_WIDTH * (hasRemove ? 2 : 1)),
{
...SPRING,
velocity: event.velocityX,
}
)
x.value = withSpring(target * ACTION_WIDTH, {
...SPRING,
velocity: event.velocityX,
})
scheduleOnRN(settle, target)
})
.onFinalize((_event, success) => {
@@ -167,7 +145,6 @@ export function SongSwipeRow({
return Gesture.Exclusive(pan, tap)
}, [
activate,
hasRemove,
begin,
close,
commitProgress,
@@ -181,14 +158,12 @@ export function SongSwipeRow({
const rowStyle = useAnimatedStyle(() => ({
transform: [{ translateX: x.value }],
borderRadius: IS_ANDROID
? 0
: interpolate(
Math.abs(x.value),
[0, 40],
[0, height.value / 2],
Extrapolation.CLAMP
),
borderRadius: interpolate(
Math.abs(x.value),
[0, 40],
[0, height.value / 2],
Extrapolation.CLAMP
),
}))
const fillStyle = useAnimatedStyle(() => ({
opacity: interpolate(
@@ -215,37 +190,8 @@ export function SongSwipeRow({
open={open === 1}
onPress={() => activate(1)}
/>
<SwipeAction
side={1}
secondary
x={x}
height={height}
progress={commitProgress}
open={open === 1}
onPress={() => {
close()
onPlayNext()
}}
/>
{hasRemove && (
<SwipeAction
side={-1}
secondary
paired
remove
x={x}
height={height}
progress={commitProgress}
open={open === -1}
onPress={() => {
close()
onRemove?.()
}}
/>
)}
<SwipeAction
side={-1}
paired={hasRemove}
x={x}
height={height}
progress={commitProgress}
@@ -258,23 +204,11 @@ export function SongSwipeRow({
accessibilityRole="button"
onAccessibilityTap={tapRow}
accessibilityActions={[
{ name: "addToQueue", label: "Add to Queue" },
{ name: "playNext", label: "Play Next" },
{ name: "download", label: "Download" },
...(hasRemove
? [{ name: "remove", label: "Remove from Playlist" }]
: []),
]}
onAccessibilityAction={(event) => {
if (event.nativeEvent.actionName === "remove" && hasRemove) {
close()
onRemove?.()
}
if (event.nativeEvent.actionName === "addToQueue") activate(1)
if (event.nativeEvent.actionName === "playNext") {
close()
onPlayNext()
}
if (event.nativeEvent.actionName === "playNext") activate(1)
}}
style={[styles.row, { backgroundColor }, rowStyle]}
>
@@ -291,9 +225,6 @@ export function SongSwipeRow({
function SwipeAction({
side,
secondary = false,
paired = side > 0,
remove = false,
x,
height,
progress,
@@ -301,48 +232,22 @@ function SwipeAction({
onPress,
}: {
side: 1 | -1
secondary?: boolean
paired?: boolean
remove?: boolean
x: SharedValue<number>
height: SharedValue<number>
progress: SharedValue<number>
open: boolean
onPress: () => void
}) {
const actionStyle = useAnimatedStyle(() => {
const revealed = Math.max(0, x.value * side)
const primaryWidth = (revealed * (1 + progress.value)) / 2
return {
width: !paired
? revealed
: secondary
? revealed - primaryWidth
: primaryWidth,
...(secondary
? side > 0
? { left: primaryWidth }
: { right: primaryWidth }
: {}),
}
})
const actionStyle = useAnimatedStyle(() => ({
width: Math.max(0, x.value * side),
}))
const pillStyle = useAnimatedStyle(() => {
const total = Math.max(0, x.value * side)
const revealed = !paired
? total
: (total * (secondary ? 1 - progress.value : 1 + progress.value)) / 2
if (IS_ANDROID) {
return { width: revealed, height: height.value, borderRadius: 0 }
}
const revealed = Math.max(0, x.value * side)
const resting = Math.max(
0,
Math.min(
revealed - (side > 0 ? 10 : 20),
interpolate(
revealed,
[24, side > 0 ? LEADING_ACTION_WIDTH : ACTION_WIDTH, 220],
[0, 62, 200]
)
revealed - 20,
interpolate(revealed, [24, ACTION_WIDTH, 220], [0, 62, 200])
)
)
const pillWidth =
@@ -387,61 +292,27 @@ function SwipeAction({
>
<Pressable
accessibilityRole="button"
accessibilityLabel={
remove
? "Remove from Playlist"
: side > 0
? secondary
? "Play Next"
: "Add to Queue"
: "Download"
}
accessibilityLabel={side > 0 ? "Play Next" : "Download"}
onPress={onPress}
style={styles.actionButton}
>
<Animated.View
style={[
styles.pill,
{
backgroundColor: remove
? "#d32f2f"
: side > 0
? secondary
? "#6b5bff"
: "#f29943"
: "#008dff",
},
{ backgroundColor: side > 0 ? "#6b5bff" : "#008dff" },
pillStyle,
]}
>
<Animated.View style={iconStyle}>
{IS_ANDROID ? (
<Ionicons
name={
remove
? "trash-outline"
: side < 0
? "arrow-down"
: secondary
? "play-forward"
: "list"
}
size={22}
color="white"
/>
) : (
<SymbolView
name={
side > 0
? secondary
? "text.line.first.and.arrowtriangle.forward"
: "text.line.last.and.arrowtriangle.forward"
: "arrow.down"
}
size={22}
tintColor="white"
/>
)}
<SymbolView
name={
side > 0
? "text.line.first.and.arrowtriangle.forward"
: "arrow.down"
}
size={22}
tintColor="white"
/>
</Animated.View>
</Animated.View>
</Pressable>
@@ -18,7 +18,7 @@ import {
import { useTabletPlayerInsets } from "@/contexts/tablet-player-layout"
import { CoverImage } from "@/components/cover-image"
import { MediaActionMenu } from "@/components/media-context-menu"
import { MediaActionMenu } from "@/components/media-actions-sheet"
import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
+6 -8
View File
@@ -1,11 +1,12 @@
import { createContext, useContext, useMemo, type ReactNode } from "react"
import { createContext, useContext, type ReactNode } from "react"
type ConvexAuthSessionContextValue = {
invalidateSession: () => Promise<void>
}
const ConvexAuthSessionContext =
createContext<ConvexAuthSessionContextValue | null>(null)
const ConvexAuthSessionContext = createContext<ConvexAuthSessionContextValue | null>(
null
)
export function ConvexAuthSessionProvider({
children,
@@ -14,9 +15,8 @@ export function ConvexAuthSessionProvider({
children: ReactNode
invalidateSession: () => Promise<void>
}) {
const value = useMemo(() => ({ invalidateSession }), [invalidateSession])
return (
<ConvexAuthSessionContext.Provider value={value}>
<ConvexAuthSessionContext.Provider value={{ invalidateSession }}>
{children}
</ConvexAuthSessionContext.Provider>
)
@@ -25,9 +25,7 @@ export function ConvexAuthSessionProvider({
export function useInvalidateAuthSession() {
const context = useContext(ConvexAuthSessionContext)
if (!context) {
throw new Error(
"useInvalidateAuthSession must be used within ConvexAuthSessionProvider"
)
throw new Error("useInvalidateAuthSession must be used within ConvexAppProvider")
}
return context
}
File diff suppressed because it is too large. Load diff
-142
View File
@@ -1,142 +0,0 @@
import { useEffect, useMemo, useState } from "react"
import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
export const COVER_PALETTE_WAIT_MS = 400
export type CoverPaletteResult = { palette: CoverPalette; settled: boolean }
type CoverPaletteSourceOptions<Swatches> = {
/** Persistent cache key for a 64px cover URI. */
cacheKey: (colorSourceUri: string) => string
extract: (colorSourceUri: string) => Promise<Swatches | null>
derive: (swatches: Swatches, isDark: boolean) => CoverPalette | null
/** Reject persisted entries written in an older shape. */
isValidCache?: (swatches: Swatches) => boolean
}
/**
* One artwork color pipeline: an extractor and palette derivation with their
* own memory cache, persistent cache and in-flight requests.
*/
export function createCoverPaletteSource<Swatches>({
cacheKey,
extract,
derive,
isValidCache,
}: CoverPaletteSourceOptions<Swatches>) {
const swatchesByKey = new Map<string, Swatches | null>()
const pending = new Map<string, Promise<Swatches | null>>()
function cachedSwatches(key: string): Swatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
const cached = readCache<Swatches>(cacheKey(key))
return cached && isValidCache && !isValidCache(cached) ? undefined : cached
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = extract(key)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
function prefetch(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/**
* Colors for a screen tinted by `uri`'s cover art. Pass `uri` as "" to skip
* extraction. Pass `hasCover` as `undefined` while it isn't known yet so
* extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
function usePalette(
uri: string,
hasCover: boolean | undefined
): CoverPaletteResult {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: Swatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background
// in case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches ? derive(swatches, isDark) : null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key ||
hasCover === false ||
swatches !== undefined ||
waitedKey === key,
}
}
return { prefetch, usePalette }
}
function sameSwatches(a: unknown, b: unknown) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
+130 -30
View File
@@ -1,47 +1,147 @@
import { useEffect, useMemo, useState } from "react"
import {
createCoverPaletteSource,
type CoverPaletteResult,
} from "@/hooks/cover-palette-source"
import {
prefetchLegacyCoverPalette,
useLegacyCoverPalette,
} from "@/hooks/use-legacy-cover-palette"
import {
loadArtworkColorsEnabled,
artworkColorsEnabled,
useArtworkColorsEnabled,
} from "@/lib/artwork-color-preference"
import { prefetchLegacyCoverPalette, useLegacyCoverPalette } from "@/hooks/use-legacy-cover-palette"
import { extractCoverSwatches } from "@/lib/artwork-colors"
import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette"
export { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source"
import {
deriveCoverPalette,
themeCoverPalette,
type CoverPalette,
type CoverSwatches,
} from "@/lib/cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
const region = createCoverPaletteSource<CoverSwatches>({
cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`,
extract: extractCoverSwatches,
derive: (swatches) => deriveCoverPalette(swatches),
})
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
export const COVER_PALETTE_WAIT_MS = 400
const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:v2:${colorSourceUri}`
}
function sameSwatches(
a: CoverSwatches | null | undefined,
b: CoverSwatches | null | undefined
) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
function cachedSwatches(key: string): CoverSwatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
return readCache<CoverSwatches>(cacheKey(key))
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = extractCoverSwatches(key)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
/** Warm visible artwork colors before a detail page is pushed. */
export function prefetchCoverPalette(uri: string) {
void loadArtworkColorsEnabled().then((enabled) =>
enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri)
)
if (!artworkColorsEnabled()) {
prefetchLegacyCoverPalette(uri)
return
}
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/**
* Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the
* device preference selects. Nothing is extracted until the preference loads,
* and the screen stays unsettled meanwhile so it doesn't flash theme colors.
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
export function useCoverPalette(
function useRegionCoverPalette(
uri: string,
hasCover: boolean | undefined
): CoverPaletteResult {
const enabled = useArtworkColorsEnabled()
const current = region.usePalette(enabled === true ? uri : "", hasCover)
const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover)
if (enabled === undefined) {
return { palette: current.palette, settled: !uri || hasCover === false }
): { palette: CoverPalette; settled: boolean } {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches
? deriveCoverPalette(swatches)
: null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
return enabled ? current : legacy
}
/** Switch both extraction and palette derivation without mixing their caches. */
export function useCoverPalette(uri: string, hasCover: boolean | undefined) {
const enabled = useArtworkColorsEnabled()
const region = useRegionCoverPalette(enabled ? uri : "", hasCover)
const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover)
return enabled ? region : legacy
}
+132 -21
View File
@@ -1,14 +1,29 @@
import { useEffect, useMemo, useState } from "react"
import { getColors, type ImageColorsResult } from "react-native-image-colors"
import { createCoverPaletteSource } from "@/hooks/cover-palette-source"
import {
deriveCoverPalette,
type LegacyCoverSwatches as CoverSwatches,
} from "@/lib/legacy-cover-palette"
themeCoverPalette,
type CoverPalette,
} from "@/lib/cover-palette"
import { deriveCoverPalette, type LegacyCoverSwatches as CoverSwatches } from "@/lib/legacy-cover-palette"
import { readCache, writeCache } from "@/lib/persistent-cache"
import { useIsDark, useThemeColors } from "@/lib/theme"
import { withCoverImageSize } from "@/lib/urls"
// How long a screen holds its skeleton for the first extraction of a cover,
// so rows render once with final colors instead of flashing from the theme.
const COVER_PALETTE_WAIT_MS = 400
// image-colors substitutes this for swatches it couldn't find.
const MISSING = "#010203"
const swatchesByKey = new Map<string, CoverSwatches | null>()
const pending = new Map<string, Promise<CoverSwatches | null>>()
function cacheKey(colorSourceUri: string) {
return `palette:${colorSourceUri}`
}
function present(colors: (string | undefined)[]) {
return colors.filter(
(color): color is string => !!color && color.toLowerCase() !== MISSING
@@ -44,24 +59,120 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null {
}
}
const legacy = createCoverPaletteSource<CoverSwatches>({
cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`,
extract: (key) =>
getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
}).then(toSwatches),
derive: deriveCoverPalette,
function sameSwatches(
a: CoverSwatches | null | undefined,
b: CoverSwatches | null | undefined
) {
return a === b || JSON.stringify(a) === JSON.stringify(b)
}
function cachedSwatches(key: string): CoverSwatches | null | undefined {
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
const cached = readCache<CoverSwatches>(cacheKey(key))
// Discard the background-only entries written by the tablet palette experiment.
isValidCache: (cached) =>
Array.isArray(cached.text) && Array.isArray(cached.accent),
})
return cached && (!Array.isArray(cached.text) || !Array.isArray(cached.accent))
? undefined
: cached
}
function extractSwatches(key: string) {
const inFlight = pending.get(key)
if (inFlight) return inFlight
const request = getColors(key, {
fallback: MISSING,
cache: true,
key,
quality: "low",
pixelSpacing: 4,
})
.then(toSwatches)
.catch(() => null)
.then((swatches) => {
swatchesByKey.set(key, swatches)
if (swatches) writeCache(cacheKey(key), swatches)
pending.delete(key)
return swatches
})
pending.set(key, request)
return request
}
/** Warm visible artwork colors before a detail page is pushed. */
export const prefetchLegacyCoverPalette = legacy.prefetch
export function prefetchLegacyCoverPalette(uri: string) {
const key = withCoverImageSize(uri, 64)
if (cachedSwatches(key) !== undefined) return
void extractSwatches(key)
}
/** `react-native-image-colors` pipeline used when new artwork colors are off. */
export const useLegacyCoverPalette = legacy.usePalette
/**
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
* known yet so extraction can start early.
*
* `settled` turns true once the palette is final or after
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
*/
export function useLegacyCoverPalette(
uri: string,
hasCover: boolean | undefined
): { palette: CoverPalette; settled: boolean } {
const theme = useThemeColors()
const isDark = useIsDark()
const key = uri ? withCoverImageSize(uri, 64) : ""
const [resolved, setResolved] = useState(() => ({
key,
swatches: key ? cachedSwatches(key) : null,
}))
const [waitedKey, setWaitedKey] = useState<string | null>(null)
const swatches =
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
useEffect(() => {
if (!key || hasCover === false) return
let cancelled = false
const known = cachedSwatches(key)
const show = (next: CoverSwatches | null) =>
setResolved((prev) =>
prev.key === key && sameSwatches(prev.swatches, next)
? prev
: { key, swatches: next }
)
if (known !== undefined && swatchesByKey.has(key)) {
show(known)
return
}
// Persisted swatches render immediately; refresh them in the background in
// case the cover changed.
const timer =
known === undefined
? setTimeout(
() => !cancelled && setWaitedKey(key),
COVER_PALETTE_WAIT_MS
)
: null
void extractSwatches(key).then((next) => {
if (!cancelled) show(next ?? known ?? null)
})
return () => {
cancelled = true
if (timer) clearTimeout(timer)
}
}, [hasCover, key])
const palette = useMemo(() => {
const fromArt =
hasCover !== false && swatches
? deriveCoverPalette(swatches, isDark)
: null
return fromArt ?? themeCoverPalette(theme, isDark)
}, [hasCover, isDark, swatches, theme])
return {
palette,
settled:
!key || hasCover === false || swatches !== undefined || waitedKey === key,
}
}
@@ -1,728 +0,0 @@
import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import {
createAudioPlaylist,
setAudioModeAsync,
setIsAudioActiveAsync,
type AudioMetadata,
type AudioPlaylist,
type AudioPlaylistStatus,
type AudioSource,
} from "expo-audio"
import { useConvex } from "convex/react"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useCacheScope } from "@/contexts/persistent-cache"
import { useServerConfig } from "@/contexts/server-config"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import { playbackStreamPlan } from "@otunes/convex/playback-stream"
import * as playbackQueue from "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import type { PlaybackStore } from "@otunes/convex/client/playback-store"
import { getAuthCookieHeader } from "@/lib/auth-cookies"
import { loadPlaybackSongs } from "@/lib/playback-files"
import { showError } from "@/lib/toast"
import { albumCoverUrl, songAudioSource } from "@/lib/urls"
import {
activatePlaylistLockScreen,
releaseAudioPlaylist,
updatePlaylistLockScreenMetadata,
} from "@/lib/audio-playlist-lock-screen"
import {
nativePlaylistEdits,
nativePlaylistNeedsRebuild,
nativePlaylistSongIds,
repeatToPlaylistLoop,
} from "@/lib/native-playlist-window"
const PLAYBACK_READY_TIMEOUT_MS = 20_000
function lockScreenMetadata(
song: BrowseSong,
serverUrl: string
): AudioMetadata {
return {
title: song.title,
artist: song.artist.name,
albumTitle: song.album.title,
artworkUrl: albumCoverUrl(serverUrl, song.album.id, 512),
}
}
type PlaybackWaiter = { playing?: boolean; resolve: () => void }
/** Where the last sync left the native player, and the queue it reflects. */
type SyncedPosition = {
index: number
songId: Id<"songs"> | undefined
historyLength: number
}
/**
* Keeps the native `AudioPlaylist` in step with the playback queue, and
* feeds its status (position, playing, track changes) back into the queue.
*/
export function useNativePlaylistSync({
store,
queueSongIds,
queueHistorySongIds,
repeatEnabled,
currentSong,
queueStartVersion,
}: {
store: PlaybackStore
queueSongIds: Id<"songs">[]
queueHistorySongIds: Id<"songs">[]
repeatEnabled: RepeatMode
currentSong: BrowseSong | null
queueStartVersion: number
}) {
const convex = useConvex()
const { config } = useServerConfig()
const cacheScope = useCacheScope()
const user = useCachedQuery(api.auth.currentUser)
const storeRef = useRef(store)
storeRef.current = store
const playlistRef = useRef<AudioPlaylist | null>(null)
const statusSubscriptionRef = useRef<{ remove: () => void } | null>(null)
const trackChangedSubscriptionRef = useRef<{ remove: () => void } | null>(
null
)
const loadedSongIdsRef = useRef<Id<"songs">[]>([])
const loadedLoadKeyRef = useRef<string | null>(null)
const syncedPositionRef = useRef<SyncedPosition | null>(null)
const waitersRef = useRef(new Map<Id<"songs">, Set<PlaybackWaiter>>())
const autoPlayNextRef = useRef(false)
const isPlayingRef = useRef(false)
const currentTimeRef = useRef(0)
const pendingSeekRef = useRef<number | null>(null)
const seekInFlightRef = useRef(false)
// Set while `play()` waits for a pending seek to land.
const deferredPlayRef = useRef(false)
const loadRequestIdRef = useRef(0)
const [isPlaying, setIsPlayingState] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [measuredDuration, setDuration] = useState(0)
const currentSongId = queueSongIds[0] ?? null
const duration =
measuredDuration > 0
? measuredDuration
: (currentSong?.durationSeconds ?? 0)
const queueSyncKey = useMemo(
() => JSON.stringify(queueSongIds),
[queueSongIds]
)
const historySyncKey = useMemo(
() => JSON.stringify(queueHistorySongIds),
[queueHistorySongIds]
)
const currentSongSyncKey = currentSong
? JSON.stringify([
currentSong.id,
currentSong.title,
currentSong.artist.name,
currentSong.album.id,
currentSong.album.title,
currentSong.album.cover ?? "",
])
: ""
const userPlaybackKey = user
? JSON.stringify([
user._id,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false),
])
: ""
const settleWaiters = useCallback(() => {
const player = playlistRef.current
if (waitersRef.current.size === 0 || !player) return
const songId = loadedSongIdsRef.current[player.currentIndex]
const waiters = songId && waitersRef.current.get(songId)
if (!waiters || !player.isLoaded) return
for (const waiter of waiters) {
if (waiter.playing === undefined || player.playing === waiter.playing) {
waiter.resolve()
}
}
}, [])
const markSynced = useCallback(
(playlist: AudioPlaylist, songId: Id<"songs">, historyLength: number) => {
syncedPositionRef.current = {
index: playlist.currentIndex,
songId,
historyLength,
}
settleWaiters()
},
[settleWaiters]
)
const destroyPlaylist = useCallback(() => {
statusSubscriptionRef.current?.remove()
statusSubscriptionRef.current = null
trackChangedSubscriptionRef.current?.remove()
trackChangedSubscriptionRef.current = null
const playlist = playlistRef.current
if (playlist) {
playlist.pause()
releaseAudioPlaylist(playlist)
}
playlistRef.current = null
loadedSongIdsRef.current = []
loadedLoadKeyRef.current = null
syncedPositionRef.current = null
}, [])
const resetPosition = useCallback(() => {
pendingSeekRef.current = null
deferredPlayRef.current = false
currentTimeRef.current = 0
setCurrentTime(0)
setDuration(0)
}, [])
// A new queue must not inherit the native player's position or a pending seek.
const resetForNewQueue = useCallback(() => {
loadRequestIdRef.current += 1
destroyPlaylist()
seekInFlightRef.current = false
resetPosition()
}, [destroyPlaylist, resetPosition])
/**
* Starts the player, unless a seek (a restored position) is still pending.
* Then the status handler starts it once the seek lands, so playback never
* starts at 0:00 and jumps.
*/
const startPlayer = useCallback((playlist: AudioPlaylist) => {
if (pendingSeekRef.current !== null && pendingSeekRef.current > 0) {
deferredPlayRef.current = true
return
}
playlist.play()
}, [])
const handlePlaylistStatusUpdate = useCallback(
(status: AudioPlaylistStatus) => {
settleWaiters()
// iOS may remove the finished item before delivering its final status.
if (!status.isLoaded && !status.didJustFinish) return
const state = storeRef.current.getState()
if (loadedSongIdsRef.current[status.currentIndex] !== state.queue[0]) {
return
}
if (status.duration > 0) {
setDuration(status.duration)
}
if (pendingSeekRef.current !== null && pendingSeekRef.current > 0) {
const seekSeconds =
status.duration > 0
? Math.min(pendingSeekRef.current, status.duration)
: pendingSeekRef.current
pendingSeekRef.current = null
const playlist = playlistRef.current
if (playlist) {
// Statuses report the old position until the seek lands.
seekInFlightRef.current = true
void playlist.seekTo(seekSeconds).finally(() => {
seekInFlightRef.current = false
if (deferredPlayRef.current && playlistRef.current === playlist) {
deferredPlayRef.current = false
playlist.play()
}
})
}
currentTimeRef.current = seekSeconds
setCurrentTime(seekSeconds)
} else if (!seekInFlightRef.current) {
currentTimeRef.current = status.currentTime
setCurrentTime(status.currentTime)
}
if (status.playing) {
autoPlayNextRef.current = false
if (!isPlayingRef.current) {
isPlayingRef.current = true
setIsPlayingState(true)
}
} else if (
isPlayingRef.current &&
!status.didJustFinish &&
!deferredPlayRef.current
) {
autoPlayNextRef.current = false
isPlayingRef.current = false
setIsPlayingState(false)
}
if (!status.didJustFinish) return
if (state.repeatEnabled === "once") return
if (status.currentIndex < status.trackCount - 1) return
const shouldContinue =
state.repeatEnabled !== "none" || state.queue.length > 1
if (!shouldContinue) {
autoPlayNextRef.current = false
isPlayingRef.current = false
setIsPlayingState(false)
storeRef.current.update(playbackQueue.skipNext)
const playlist = playlistRef.current
if (playlist) {
playlist.pause()
// Reload the final item, which iOS removes when playback ends. The
// index doesn't move, so handleTrackChanged treats it as ours.
playlist.skipTo(status.currentIndex)
}
currentTimeRef.current = 0
setCurrentTime(0)
return
}
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
storeRef.current.update(playbackQueue.skipNext)
if (storeRef.current.getState().queue[0] === state.queue[0]) {
const playlist = playlistRef.current
void playlist?.seekTo(0)
playlist?.play()
}
},
[settleWaiters]
)
const handleTrackChanged = useCallback(() => {
const playlist = playlistRef.current
const synced = syncedPositionRef.current
if (!playlist || !synced) return
// Queue edits run synchronously, so an event can describe an index from
// before them (Android's `previousIndex` also goes stale). The player's
// live index is the one that matters; if it is where the last sync left
// it, this change was ours.
const index = playlist.currentIndex
if (index === synced.index) return
const state = storeRef.current.getState()
// A queue change is still being applied and will move the player itself.
if (
state.queue[0] !== synced.songId ||
state.history.length !== synced.historyLength
) {
return
}
// The window is history then queue, so the current track sits at
// `history.length`.
const steps = index - state.history.length
if (steps === 0) return
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
storeRef.current.update((state) => {
if (steps === 1) return playbackQueue.skipNext(state)
if (steps > 1) return playbackQueue.skipToQueueIndex(state, steps)
let next = state
for (let i = 0; i < -steps; i++) {
next = playbackQueue.skipPrevious(next)
}
return next
})
const next = storeRef.current.getState()
syncedPositionRef.current = {
index,
songId: next.queue[0],
historyLength: next.history.length,
}
settleWaiters()
}, [settleWaiters])
const ensurePlaylist = useCallback(
(sources: AudioSource[]) => {
if (playlistRef.current) {
return playlistRef.current
}
const playlist = createAudioPlaylist({
sources,
updateInterval: 500,
loop: repeatToPlaylistLoop(storeRef.current.getState().repeatEnabled),
})
// System volume controls loudness; keep the player gain at full scale.
playlist.volume = 1
statusSubscriptionRef.current = playlist.addListener(
"playlistStatusUpdate",
handlePlaylistStatusUpdate
)
trackChangedSubscriptionRef.current = playlist.addListener(
"trackChanged",
handleTrackChanged
)
playlistRef.current = playlist
return playlist
},
[handlePlaylistStatusUpdate, handleTrackChanged]
)
useEffect(() => {
let cancelled = false
void setAudioModeAsync({
playsInSilentMode: true,
shouldPlayInBackground: true,
interruptionMode: "doNotMix",
}).catch(() => {
if (!cancelled) {
showError("Audio playback could not be initialized.")
}
})
return () => {
cancelled = true
destroyPlaylist()
}
}, [destroyPlaylist])
useEffect(() => {
const playlist = playlistRef.current
if (playlist) {
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
}
}, [repeatEnabled])
const setIsPlaying = useCallback(
(playing: boolean) => {
isPlayingRef.current = playing
setIsPlayingState(playing)
const playlist = playlistRef.current
if (!playlist) return
if (playing) {
startPlayer(playlist)
} else {
deferredPlayRef.current = false
playlist.pause()
}
},
[startPlayer]
)
const seekTo = useCallback(
async (seconds: number) => {
const playlist = playlistRef.current
if (!playlist) return
const maxDuration = playlist.duration || duration || 0
const clamped = Math.max(0, Math.min(seconds, maxDuration))
await playlist.seekTo(clamped)
currentTimeRef.current = clamped
setCurrentTime(clamped)
},
[duration]
)
const handlePlaybackLoadFailure = useCallback(() => {
autoPlayNextRef.current = false
isPlayingRef.current = false
destroyPlaylist()
setIsPlayingState(false)
showError("Could not play this track. The queue has been cleared.")
storeRef.current.update(playbackQueue.clearQueue)
}, [destroyPlaylist])
useEffect(() => {
const loadRequestId = ++loadRequestIdRef.current
const isCurrentLoad = () => loadRequestIdRef.current === loadRequestId
async function syncPlaylist() {
if (!config || !currentSongId || !user) {
if (!currentSongId) {
destroyPlaylist()
}
return
}
const windowSongIds = nativePlaylistSongIds(
queueHistorySongIds,
queueSongIds
)
const currentIndex = queueHistorySongIds.length
const cookieHeader = await getAuthCookieHeader(
config.serverUrl,
config.convexUrl
)
if (!cookieHeader) {
showError("Your session has expired. Please sign in again.")
return
}
if (!isCurrentLoad()) return
const loadKey = `${user.playbackQuality}:${dolbyAtmosSupported && (user.preferAtmos ?? false)}:${cookieHeader}`
const needsRebuild =
loadedLoadKeyRef.current !== loadKey ||
nativePlaylistNeedsRebuild(
loadedSongIdsRef.current,
queueHistorySongIds,
queueSongIds
)
const metadata = currentSong
? lockScreenMetadata(currentSong, config.serverUrl)
: null
const shouldPlay = isPlayingRef.current || autoPlayNextRef.current
if (!needsRebuild) {
const playlist = playlistRef.current
if (!playlist) return
if (playlist.currentIndex !== currentIndex) {
playlist.skipTo(currentIndex)
}
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
if (metadata) {
updatePlaylistLockScreenMetadata(playlist, metadata)
}
markSynced(playlist, currentSongId, currentIndex)
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
startPlayer(playlist)
}
return
}
const buildSources = async (songIds: Id<"songs">[]) => {
const songs = await loadPlaybackSongs(convex, cacheScope, songIds)
const sources = new Map<Id<"songs">, AudioSource>()
for (const song of songs) {
if (!song) return null
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
dolbyAtmosSupported && (user.preferAtmos ?? false)
)
sources.set(
song.id,
songAudioSource(
config.serverUrl,
song.id,
plan.playbackQuality,
plan.preferAtmos,
plan.useHls,
{ cookieHeader, songTitle: song.title }
)
)
}
return sources
}
// Queue and history edits around the playing track are applied in place
// so playback isn't interrupted.
const loadedPlaylist = playlistRef.current
const edits =
loadedPlaylist && loadedLoadKeyRef.current === loadKey
? nativePlaylistEdits(
loadedSongIdsRef.current,
loadedPlaylist.currentIndex,
windowSongIds,
currentIndex
)
: null
if (loadedPlaylist && edits) {
const addedSongIds = edits.flatMap((edit) =>
edit.type === "remove" ? [] : [edit.songId]
)
const sources = await buildSources([...new Set(addedSongIds)])
if (!isCurrentLoad()) return
if (!sources) {
handlePlaybackLoadFailure()
return
}
for (const edit of edits) {
if (edit.type === "remove") {
loadedPlaylist.remove(edit.index)
} else if (edit.type === "insert") {
loadedPlaylist.insert(sources.get(edit.songId)!, edit.index)
} else {
loadedPlaylist.add(sources.get(edit.songId)!)
}
}
loadedSongIdsRef.current = windowSongIds
loadedPlaylist.loop = repeatToPlaylistLoop(repeatEnabled)
markSynced(loadedPlaylist, currentSongId, currentIndex)
if (shouldPlay && !loadedPlaylist.playing) {
isPlayingRef.current = true
setIsPlayingState(true)
startPlayer(loadedPlaylist)
}
return
}
const sourcesById = await buildSources(windowSongIds)
if (!isCurrentLoad()) return
if (!sourcesById) {
handlePlaybackLoadFailure()
return
}
const sources = windowSongIds.map((songId) => sourcesById.get(songId)!)
// Keep the position when only the stream settings changed.
const resumeSeconds =
loadedPlaylist &&
loadedSongIdsRef.current[loadedPlaylist.currentIndex] === currentSongId
? currentTimeRef.current
: null
destroyPlaylist()
if (resumeSeconds !== null && resumeSeconds > 0) {
pendingSeekRef.current = resumeSeconds
}
// Start at the current track and put history in front of it, so an
// earlier song is never loaded first.
const playlist = ensurePlaylist(sources.slice(currentIndex))
for (let index = 0; index < currentIndex; index++) {
playlist.insert(sources[index], index)
}
loadedSongIdsRef.current = windowSongIds
loadedLoadKeyRef.current = loadKey
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
activatePlaylistLockScreen(
playlist,
metadata ?? { title: currentSong?.title }
)
markSynced(playlist, currentSongId, currentIndex)
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
startPlayer(playlist)
} else {
playlist.pause()
// Enable audio for the restored queue without starting playback.
try {
await setIsAudioActiveAsync(true)
} catch {
if (isCurrentLoad()) {
showError("Audio playback could not be initialized.")
}
}
}
}
void syncPlaylist().catch(() => {
if (!isCurrentLoad()) return
handlePlaybackLoadFailure()
})
return () => {
if (loadRequestIdRef.current === loadRequestId) {
loadRequestIdRef.current += 1
}
}
}, [
cacheScope,
config,
convex,
currentSongId,
currentSongSyncKey,
destroyPlaylist,
ensurePlaylist,
handlePlaybackLoadFailure,
historySyncKey,
markSynced,
queueSyncKey,
queueStartVersion,
repeatEnabled,
startPlayer,
userPlaybackKey,
])
/**
* Resolves once the native player has `songId` loaded (and playing or
* paused, if given). Rejects if the queue moves to another song first.
*/
const waitForSong = useCallback(
(songId: Id<"songs">, playing?: boolean) =>
new Promise<void>((resolve, reject) => {
const store = storeRef.current
const waiters = waitersRef.current
let songWaiters = waiters.get(songId)
if (!songWaiters) {
songWaiters = new Set()
waiters.set(songId, songWaiters)
}
const finish = (error?: Error) => {
clearTimeout(timeout)
unsubscribe()
songWaiters.delete(waiter)
if (songWaiters.size === 0 && waiters.get(songId) === songWaiters) {
waiters.delete(songId)
}
if (error) reject(error)
else resolve()
}
const waiter: PlaybackWaiter = { playing, resolve: () => finish() }
const timeout = setTimeout(
() =>
finish(
new Error(
"The audio did not become ready. Check your connection and try again."
)
),
PLAYBACK_READY_TIMEOUT_MS
)
// Starting a queue clears it and fills it in one go; only the
// settled queue counts.
const unsubscribe = store.subscribe(() => {
queueMicrotask(() => {
if (store.getState().queue[0] !== songId) {
finish(
new Error(
"The playback queue changed before the request finished."
)
)
}
})
})
songWaiters.add(waiter)
settleWaiters()
}),
[settleWaiters]
)
/**
* Starts the current song at `seconds` once it loads, and shows that
* position right away. Playback waits for the seek (see `startPlayer`).
*/
const queueSeek = useCallback((seconds: number) => {
pendingSeekRef.current = seconds
currentTimeRef.current = seconds
setCurrentTime(seconds)
}, [])
const hasPlayer = useCallback(() => playlistRef.current !== null, [])
const requestAutoPlay = useCallback(() => {
autoPlayNextRef.current = true
}, [])
return {
isPlaying,
setIsPlaying,
currentTime,
currentTimeRef,
duration,
seekTo,
queueSeek,
hasPlayer,
requestAutoPlay,
resetPosition,
resetForNewQueue,
waitForSong,
}
}
@@ -1,110 +0,0 @@
import { useMutation } from "convex/react"
import { useCallback, useEffect, useRef, type RefObject } from "react"
import { AppState } from "react-native"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { PlaybackStore } from "@otunes/convex/client/playback-store"
import { flushPersistentCache } from "@/lib/persistent-cache"
const PROGRESS_SAVE_INTERVAL_MS = 5000
/**
* Restores the saved position when a song becomes current, and saves the
* position while it plays, on pause, and when the app leaves the foreground.
*/
export function useProgressPersistence({
store,
currentSongId,
isPlaying,
queueStartVersion,
currentTimeRef,
hasPlayer,
queueSeek,
resetPosition,
}: {
store: PlaybackStore
currentSongId: Id<"songs"> | null
isPlaying: boolean
queueStartVersion: number
currentTimeRef: RefObject<number>
hasPlayer: () => boolean
queueSeek: (seconds: number) => void
resetPosition: () => void
}) {
const updateSongProgressMutation = useMutation(
api.playback.updateSongProgress
)
const storeRef = useRef(store)
storeRef.current = store
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
const lastSavedProgressRef = useRef(-1)
const prevIsPlayingRef = useRef(false)
const saveProgress = useCallback(
(seconds: number) => {
const songId = storeRef.current.getState().queue[0]
if (!songId) return
const progressSeconds = Math.max(0, Math.floor(seconds))
if (progressSeconds === lastSavedProgressRef.current) return
lastSavedProgressRef.current = progressSeconds
storeRef.current.setProgress(songId, progressSeconds)
void updateSongProgressMutation({
songId,
progressSeconds,
}).catch(() => {})
},
[updateSongProgressMutation]
)
const resetProgress = useCallback(() => {
progressRestoredForSongRef.current = null
lastSavedProgressRef.current = -1
}, [])
useEffect(() => {
if (!currentSongId) {
progressRestoredForSongRef.current = null
return
}
if (progressRestoredForSongRef.current === currentSongId) return
progressRestoredForSongRef.current = currentSongId
lastSavedProgressRef.current = -1
resetPosition()
// Queue the seek before the song loads, so playback starts there.
const progressSeconds = store.getState().progressSeconds
if (progressSeconds > 0) {
queueSeek(progressSeconds)
}
}, [currentSongId, queueStartVersion, queueSeek, resetPosition, store])
useEffect(() => {
if (!currentSongId) return
if (prevIsPlayingRef.current === isPlaying) return
prevIsPlayingRef.current = isPlaying
saveProgress(currentTimeRef.current)
}, [isPlaying, currentSongId, currentTimeRef, saveProgress])
useEffect(() => {
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") return
if (currentSongId && hasPlayer()) {
saveProgress(currentTimeRef.current)
}
flushPersistentCache()
})
return () => subscription.remove()
}, [currentSongId, currentTimeRef, hasPlayer, saveProgress])
useEffect(() => {
if (!isPlaying || !currentSongId) return
const interval = setInterval(() => {
saveProgress(currentTimeRef.current)
}, PROGRESS_SAVE_INTERVAL_MS)
return () => clearInterval(interval)
}, [isPlaying, currentSongId, currentTimeRef, saveProgress])
return { resetProgress }
}
+18 -21
View File
@@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react"
const STORAGE_KEY = "otunes:artwork-colors"
const listeners = new Set<() => void>()
// Undefined until storage has been read, so callers never act on a guess.
let enabled: boolean | undefined
let enabled = true
let loaded = false
let loading: Promise<void> | undefined
function notify() {
@@ -13,40 +13,37 @@ function notify() {
function load() {
return (loading ??= AsyncStorage.getItem(STORAGE_KEY)
.then((value) => value !== "false")
// Keep the default when local storage is unavailable.
.catch(() => true)
.then((value) => {
enabled = value
enabled = value !== "false"
})
.catch(() => {
// Keep the default when local storage is unavailable.
})
.finally(() => {
loaded = true
notify()
}))
}
void load()
function subscribe(listener: () => void) {
listeners.add(listener)
void load()
return () => {
listeners.delete(listener)
}
}
/**
* Device preference, kept outside account data and the disposable query cache.
* `undefined` until it has loaded.
*/
/** Device preference, kept outside account data and the disposable query cache. */
export function useArtworkColorsEnabled() {
return useSyncExternalStore(
subscribe,
() => enabled,
() => undefined
)
return useSyncExternalStore(subscribe, () => loaded && enabled, () => false)
}
/** Resolves with the preference once it has loaded. */
export async function loadArtworkColorsEnabled() {
await load()
return enabled ?? true
export function useArtworkColorPreferenceLoaded() {
return useSyncExternalStore(subscribe, () => loaded, () => false)
}
export function artworkColorsEnabled() {
return loaded && enabled
}
export async function setArtworkColorsEnabled(value: boolean) {
+8 -13
View File
@@ -3,11 +3,11 @@ import type { Id } from "@otunes/convex/_generated/dataModel"
import { audioContentTypeForPath } from "@/lib/audio-content-type"
import { seekableLosslessFile } from "@/lib/server-lossless"
import { getConvexClient } from "@/lib/convex-server"
import { audioInfo } from "@/lib/server-audio-info"
import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream"
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
import { NextRequest, NextResponse, userAgent } from "next/server"
import { spawn } from "node:child_process"
import fs from "node:fs/promises"
import * as music from "music-metadata"
function parseByteRange(rangeHeader: string | null, fileSize: number) {
if (!rangeHeader) {
@@ -151,14 +151,15 @@ export async function GET(
transcodeNeeded = false
}
const metadata = await music.parseFile(song.files[originalCodec])
if (!transcodeNeeded && originalCodec === "lossless") {
// Native iOS playback does not identify itself as Safari.
const acceptsAlac =
browser.name === "Safari" ||
request.nextUrl.searchParams.get("losslessFormat") === "alac"
if (acceptsAlac && metadata.format.codec === "ALAC") {
if (
acceptsAlac &&
(await audioInfo(song.files[originalCodec])).codec === "ALAC"
) {
try {
return await streamFileResponse(
request,
@@ -183,11 +184,6 @@ export async function GET(
(originalCodec === "atmos" || originalCodec === "normal")
) {
// TODO: Dolby Atmos doesn't work on Google Chrome
console.log(
metadata.format.codec,
metadata.format.container,
metadata.format.codecProfile
)
try {
return await streamFileResponse(
request,
@@ -200,7 +196,6 @@ export async function GET(
}
const ffmpegArgs = [
"-nostdin",
"-i",
song.files[originalCodec],
"-c:a",
@@ -214,8 +209,8 @@ export async function GET(
try {
// TODO: Fix seeking for this
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
const stream = ffmpegToReadableStream(ffmpegProcess)
const ffmpeg = await spawnFfmpeg(ffmpegArgs, request.signal)
const stream = ffmpegToReadableStream(ffmpeg)
return new NextResponse(stream, {
status: 200,
+6 -1
View File
@@ -44,7 +44,12 @@ import {
import { albumCoverUrl } from "@/lib/cover-urls"
import { sumDurationSeconds } from "@/lib/media-summary"
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
import { formatDuration } from "@/lib/format-duration"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function formatMetadata(genre: string | null, year: number | null): string | null {
const parts: string[] = []
@@ -955,7 +955,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
if (!shouldContinuePlaying) {
autoPlayNextRef.current = false
isPlayingRef.current = false
audio.pause()
audio.currentTime = 0
currentTimeRef.current = 0
setCurrentTime(0)
+7 -1
View File
@@ -31,7 +31,13 @@ import { Slider } from "@/components/ui/slider"
import { useSidebar } from "@/components/ui/sidebar"
import { albumCoverUrl } from "@/lib/cover-urls"
import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
function formatDuration(seconds: number): string {
const total = Math.max(0, Math.floor(seconds))
const minutes = Math.floor(total / 60)
const remainingSeconds = total % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
export function PlayerBar() {
const {
+6 -1
View File
@@ -46,10 +46,15 @@ import {
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { formatDuration } from "@/lib/format-duration"
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function PlaylistSongCover({
song,
inRange,
+6 -1
View File
@@ -28,7 +28,6 @@ import {
} from "@/lib/selection-range-styles"
import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
const QUEUE_INITIAL_VISIBLE_COUNT = 100
const QUEUE_PAGE_SIZE = 50
@@ -41,6 +40,12 @@ type QueueItem = {
song: QueueSelectable | null
}
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function toSelectableQueue(
songIds: Id<"songs">[],
songs: (BrowseSong | undefined)[]
+6 -1
View File
@@ -52,7 +52,6 @@ import {
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { formatDuration } from "@/lib/format-duration"
type SortKey = "title" | "artist" | "album"
type SortDirection = "asc" | "desc"
@@ -65,6 +64,12 @@ const nameColumnLayout =
"grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2"
const songColumnClass = "w-36 shrink-0 truncate"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function SongCover({
song,
inRange,
+15
View File
@@ -0,0 +1,15 @@
import { exportJWK, exportPKCS8, generateKeyPair } from "jose";
const keys = await generateKeyPair("RS256", {
extractable: true,
});
const privateKey = await exportPKCS8(keys.privateKey);
const publicKey = await exportJWK(keys.publicKey);
const jwks = JSON.stringify({ keys: [{ use: "sig", ...publicKey }] });
process.stdout.write(
`JWT_PRIVATE_KEY="${privateKey.trimEnd().replace(/\n/g, " ")}"`,
);
process.stdout.write("\n");
process.stdout.write(`JWKS=${jwks}`);
process.stdout.write("\n");
+7 -1
View File
@@ -1,3 +1,9 @@
/** Shared layout for album grids. */
/** Shared layout for album grids and carousel slides (gap-x-6 = 1.5rem). */
export const albumGridClassName =
"grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"
/** Slide width matches one cell of `albumGridClassName` inside an `@container` ancestor. */
export const albumGridCarouselSlideClassName =
"w-[calc((100cqw-1.5rem)/2)] shrink-0 grow-0 basis-auto pl-6 sm:w-[calc((100cqw-3rem)/3)] md:w-[calc((100cqw-4.5rem)/4)] lg:w-[calc((100cqw-6rem)/5)] xl:w-[calc((100cqw-7.5rem)/6)]"
export const albumGridCarouselContentClassName = "-ml-6"
+19
View File
@@ -0,0 +1,19 @@
import type {
BrowseAlbum,
BrowseAlbumDetail,
BrowseAlbumTrack,
BrowseArtist,
BrowsePlaylistDetail,
BrowsePlaylistOwner,
BrowseSong,
PlaylistSummary,
} from "@otunes/convex/types"
export type Artist = BrowseArtist
export type Album = BrowseAlbum
export type Song = BrowseSong
export type Playlist = PlaylistSummary
export type PlaylistOwner = BrowsePlaylistOwner
export type PlaylistDetail = BrowsePlaylistDetail
export type AlbumTrack = BrowseAlbumTrack
export type AlbumDetail = BrowseAlbumDetail
-7
View File
@@ -1,7 +0,0 @@
/** Formats seconds as `m:ss`, flooring fractional and negative input. */
export function formatDuration(seconds: number): string {
const total = Math.max(0, Math.floor(seconds))
const minutes = Math.floor(total / 60)
const remainingSeconds = total % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
+14 -6
View File
@@ -13,15 +13,15 @@ function mediaOrigin() {
return window.location.origin
}
function albumShareUrl(albumId: string) {
export function albumShareUrl(albumId: string) {
return `${mediaOrigin()}/album/${albumId}`
}
function songShareUrl(albumId: string, songId: string) {
export function songShareUrl(albumId: string, songId: string) {
return `${mediaOrigin()}/album/${albumId}?s=${songId}`
}
function playlistShareUrl(
export function playlistShareUrl(
playlistId: string,
options?: { isFavorites?: boolean }
) {
@@ -31,11 +31,11 @@ function playlistShareUrl(
return `${mediaOrigin()}/playlist/${playlistId}`
}
function artistShareUrl(artistId: string) {
export function artistShareUrl(artistId: string) {
return `${mediaOrigin()}/artist/${artistId}`
}
function mediaShareUrl(share: MediaShareContext) {
export function mediaShareUrl(share: MediaShareContext) {
switch (share.type) {
case "album":
return albumShareUrl(share.albumId)
@@ -50,7 +50,7 @@ function mediaShareUrl(share: MediaShareContext) {
}
}
async function copyTextToClipboard(text: string) {
export async function copyTextToClipboard(text: string) {
await navigator.clipboard.writeText(text)
toast.success("Link Copied")
}
@@ -63,6 +63,10 @@ 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 }
@@ -73,3 +77,7 @@ export async function copyPlaylistLink(
isFavorites: options?.isFavorites,
})
}
export async function copyArtistLink(artistId: string) {
await copyMediaShareLink({ type: "artist", artistId })
}
+4 -4
View File
@@ -46,7 +46,7 @@ export function getSelectionRangePositions(
return positions
}
function selectionHighlightRadiusClass(
export function selectionHighlightRadiusClass(
position: SelectionRangePosition
) {
switch (position) {
@@ -61,7 +61,7 @@ function selectionHighlightRadiusClass(
}
}
const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2"
export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2"
export function SelectionRangeHighlight({
position,
@@ -117,7 +117,7 @@ export const TRACK_ROW_PADDING = "pl-8 pr-10"
export const TRACK_LIST_CONTAINER = "mx-auto w-full max-w-9/10"
/** Full-width highlight for library song rows (no horizontal inset). */
const SONGS_ROW_HIGHLIGHT_INSET = "absolute inset-0"
export const SONGS_ROW_HIGHLIGHT_INSET = "absolute inset-0"
export function SongsSelectionRangeHighlight({
position,
@@ -162,7 +162,7 @@ export function isInSelectionRange(position: SelectionRangePosition) {
}
/** Full-width, square-corner highlights for the queue sidebar. */
const QUEUE_ROW_HIGHLIGHT_INSET = "absolute inset-0"
export const QUEUE_ROW_HIGHLIGHT_INSET = "absolute inset-0"
export function QueueSelectionRangeHighlight({
position,
+41
View File
@@ -0,0 +1,41 @@
import fs from "node:fs/promises"
import * as music from "music-metadata"
const MAX_ENTRIES = 1000
export type AudioInfo = {
codec: string | undefined
duration: number | undefined
}
const cache = new Map<string, Promise<AudioInfo>>()
/** Codec info for a file, parsed once per file version. */
export async function audioInfo(file: string): Promise<AudioInfo> {
const stat = await fs.stat(file)
const key = `${file}\0${stat.size}\0${stat.mtimeMs}`
const cached = cache.get(key)
if (cached) {
cache.delete(key)
cache.set(key, cached)
return cached
}
const info = music.parseFile(file).then(({ format }) => ({
codec: format.codec,
duration: format.duration,
}))
cache.set(key, info)
info.catch(() => {
if (cache.get(key) === info) {
cache.delete(key)
}
})
if (cache.size > MAX_ENTRIES) {
cache.delete(cache.keys().next().value!)
}
return info
}
+79 -79
View File
@@ -1,96 +1,96 @@
import { type ChildProcessWithoutNullStreams } from "node:child_process"
import { createReadStream, ReadStream } from "node:fs"
import { createReadStream } from "node:fs"
import type { Readable } from "node:stream"
import type { FfmpegProcess } from "@/lib/server-ffmpeg"
const HIGH_WATER_MARK_BYTES = 256 * 1024
export type ByteRange = {
start: number
end: number
}
async function* nodeStreamToIterator(stream: ReadStream) {
for await (const chunk of stream) {
yield new Uint8Array(chunk)
}
}
/**
* Wraps a Node stream, pausing it while the consumer is behind. `cancel` runs
* when the consumer goes away (seek, track change, disconnect). `finish` runs
* when the source ends and may reject to error the stream.
*/
function toWebStream(
source: Readable,
{
cancel,
finish,
}: { cancel: () => void; finish?: () => Promise<void> }
): ReadableStream<Uint8Array> {
let done = false
// @ts-expect-error trust me bro
function iteratorToStream(iterator) {
return new ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next()
if (done) {
controller.close()
} else {
controller.enqueue(value)
}
},
})
}
export function streamFile(path: string, range?: ByteRange): ReadableStream {
const nodeStream = createReadStream(path, range)
return iteratorToStream(nodeStreamToIterator(nodeStream))
}
export function ffmpegToReadableStream(
ffmpegProcess: ChildProcessWithoutNullStreams
) {
let closed = false
return new ReadableStream({
start(controller) {
const finalize = (err?: Error) => {
if (closed) {
return
}
closed = true
try {
if (err) {
controller.error(err)
} else {
controller.close()
return new ReadableStream<Uint8Array>(
{
start(controller) {
const fail = (error: unknown) => {
if (done) {
return
}
} catch {
// Consumer may have already closed the stream (e.g. track change).
done = true
controller.error(error)
cancel()
}
}
ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
if (closed) {
source.on("data", (chunk: Buffer) => {
if (done) {
return
}
controller.enqueue(new Uint8Array(chunk))
if ((controller.desiredSize ?? 0) <= 0) {
source.pause()
}
})
source.once("error", fail)
source.once("end", () => {
if (done) {
return
}
void (finish?.() ?? Promise.resolve()).then(() => {
if (!done) {
done = true
controller.close()
}
}, fail)
})
},
pull() {
source.resume()
},
cancel() {
if (done) {
return
}
try {
controller.enqueue(new Uint8Array(chunk))
} catch {
closed = true
ffmpegProcess.kill("SIGKILL")
}
})
ffmpegProcess.stderr.on("data", (data) => {
console.error(`FFmpeg log: ${data.toString()}`)
})
ffmpegProcess.stdout.on("end", () => finalize())
ffmpegProcess.stdout.on("error", (err) => finalize(err))
ffmpegProcess.on("close", (code) => {
if (code !== 0 && !closed) {
finalize(new Error(`ffmpeg exited with code ${code}`))
} else {
finalize()
}
})
ffmpegProcess.on("error", (err) => finalize(err))
done = true
cancel()
},
},
cancel() {
if (closed) {
return
new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK_BYTES })
)
}
export function streamFile(path: string, range?: ByteRange) {
const file = createReadStream(path, range)
return toWebStream(file, { cancel: () => file.destroy() })
}
/** Streams ffmpeg stdout and kills ffmpeg when the consumer goes away. */
export function ffmpegToReadableStream({
child,
exited,
stderrTail,
}: FfmpegProcess) {
return toWebStream(child.stdout, {
cancel: () => child.kill("SIGKILL"),
finish: async () => {
const code = await exited
if (code !== 0) {
console.error(`ffmpeg transcode exited with code ${code}`, stderrTail())
throw new Error(`ffmpeg exited with code ${code}`)
}
closed = true
ffmpegProcess.kill("SIGKILL")
},
})
}
+132
View File
@@ -0,0 +1,132 @@
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
const DEFAULT_MAX_MB = 2048
const ORPHAN_MAX_AGE_MS = 60 * 60 * 1000
/** Prefix for in-progress entries. Pruning removes old unpinned ones as abandoned. */
export const CACHE_ORPHAN_PREFIX = "convert-"
type CacheState = {
pinned: Map<string, number>
pruning: Promise<void> | null
}
const globalState = globalThis as typeof globalThis & {
__otunesCache?: CacheState
}
const state = (globalState.__otunesCache ??= {
pinned: new Map(),
pruning: null,
})
/**
* Transcode cache root. Set OTUNES_CACHE_DIR to a persistent volume to keep
* transcodes across restarts.
*/
export function cacheRoot() {
return process.env.OTUNES_CACHE_DIR || path.join(os.tmpdir(), "otunes-cache")
}
export function cacheDir(kind: "hls" | "lossless") {
return path.join(cacheRoot(), kind)
}
function maxCacheBytes() {
const configured = Number(process.env.OTUNES_CACHE_MAX_MB)
const mb = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MAX_MB
return mb * 1024 * 1024
}
/** Pinned entries are never pruned. Pins are reference counted. */
export function pinCacheEntry(entry: string) {
state.pinned.set(entry, (state.pinned.get(entry) ?? 0) + 1)
}
export function unpinCacheEntry(entry: string) {
const count = state.pinned.get(entry) ?? 0
if (count <= 1) {
state.pinned.delete(entry)
} else {
state.pinned.set(entry, count - 1)
}
}
/** Marks an entry as recently used so pruning removes it last. */
export async function touchCacheEntry(entry: string) {
const now = new Date()
await fs.utimes(entry, now, now)
}
async function entrySize(entry: string): Promise<number> {
const stat = await fs.stat(entry).catch(() => null)
if (!stat) {
return 0
}
if (!stat.isDirectory()) {
return stat.size
}
const names = await fs.readdir(entry).catch(() => [])
const sizes = await Promise.all(
names.map((name) => entrySize(path.join(entry, name)))
)
return sizes.reduce((total, size) => total + size, 0)
}
async function prune() {
const entries: {
path: string
size: number
mtimeMs: number
orphan: boolean
}[] = []
for (const kind of ["hls", "lossless"] as const) {
const dir = cacheDir(kind)
const names = await fs.readdir(dir).catch(() => [])
for (const name of names) {
const entry = path.join(dir, name)
const stat = await fs.stat(entry).catch(() => null)
if (!stat) {
continue
}
entries.push({
path: entry,
size: await entrySize(entry),
mtimeMs: stat.mtimeMs,
orphan: name.startsWith(CACHE_ORPHAN_PREFIX),
})
}
}
const maxBytes = maxCacheBytes()
const now = Date.now()
let total = entries.reduce((sum, entry) => sum + entry.size, 0)
entries.sort((a, b) => a.mtimeMs - b.mtimeMs)
for (const entry of entries) {
if (state.pinned.has(entry.path)) {
continue
}
const remove = entry.orphan
? now - entry.mtimeMs > ORPHAN_MAX_AGE_MS
: total > maxBytes
if (remove) {
await fs.rm(entry.path, { recursive: true, force: true }).catch(() => {})
total -= entry.size
}
}
}
/**
* Removes least recently used entries until the cache fits under
* OTUNES_CACHE_MAX_MB, plus abandoned in-progress entries.
*/
export function pruneCache() {
state.pruning ??= prune()
.catch((error) => console.error("Transcode cache prune failed", error))
.finally(() => {
state.pruning = null
})
return state.pruning
}
+113
View File
@@ -0,0 +1,113 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
import os from "node:os"
const STDERR_TAIL_BYTES = 4096
export type FfmpegProcess = {
child: ChildProcessWithoutNullStreams
/** Resolves with the exit code, or null when killed by a signal. */
exited: Promise<number | null>
stderrTail: () => string
}
type Limiter = {
running: number
waiting: (() => void)[]
}
// Kept on globalThis so dev reloads share one limit with processes they spawned.
const globalState = globalThis as typeof globalThis & {
__otunesFfmpegLimiter?: Limiter
}
const limiter = (globalState.__otunesFfmpegLimiter ??= {
running: 0,
waiting: [],
})
function maxConcurrentFfmpeg() {
const configured = Number(process.env.OTUNES_MAX_FFMPEG)
if (Number.isInteger(configured) && configured > 0) {
return configured
}
return Math.max(2, os.availableParallelism())
}
async function acquireSlot(signal?: AbortSignal) {
signal?.throwIfAborted()
if (limiter.running < maxConcurrentFfmpeg()) {
limiter.running += 1
return
}
await new Promise<void>((resolve, reject) => {
const grant = () => {
signal?.removeEventListener("abort", onAbort)
resolve()
}
const onAbort = () => {
const index = limiter.waiting.indexOf(grant)
if (index !== -1) {
limiter.waiting.splice(index, 1)
}
reject(signal?.reason)
}
limiter.waiting.push(grant)
signal?.addEventListener("abort", onAbort, { once: true })
})
}
function releaseSlot() {
const next = limiter.waiting.shift()
if (next) {
// The slot passes straight to the next waiter.
next()
} else {
limiter.running -= 1
}
}
/**
* Spawns ffmpeg once a slot under the concurrency cap is free. The slot is
* held until the process exits. Rejects if `signal` aborts while queued.
*/
export async function spawnFfmpeg(
args: string[],
signal?: AbortSignal
): Promise<FfmpegProcess> {
await acquireSlot(signal)
let child: ChildProcessWithoutNullStreams
try {
child = spawn("ffmpeg", [
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
...args,
])
} catch (error) {
releaseSlot()
throw error
}
// stderr must be drained or ffmpeg blocks once the pipe buffer fills.
let stderr = ""
child.stderr.on("data", (data: Buffer) => {
stderr = (stderr + data.toString()).slice(-STDERR_TAIL_BYTES)
})
const exited = new Promise<number | null>((resolve) => {
let released = false
const finish = (code: number | null) => {
if (!released) {
released = true
releaseSlot()
}
resolve(code)
}
child.once("error", () => finish(1))
child.once("close", (code) => finish(code))
})
return { child, exited, stderrTail: () => stderr.trim() }
}
+183 -93
View File
@@ -2,8 +2,15 @@ import type { Doc } from "@otunes/convex/_generated/dataModel"
import crypto from "node:crypto"
import fs from "node:fs/promises"
import path from "node:path"
import { spawn } from "node:child_process"
import * as music from "music-metadata"
import { audioInfo } from "@/lib/server-audio-info"
import {
cacheDir,
pinCacheEntry,
pruneCache,
touchCacheEntry,
unpinCacheEntry,
} from "@/lib/server-cache"
import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg"
export const HLS_SEGMENT_SECONDS = 6
const HLS_MAX_IDLE_MS = 30 * 60 * 1000
@@ -17,11 +24,28 @@ type HlsJob = {
lastTouchedAt: number
processExited: boolean
processExitCode: number | null
process: FfmpegProcess | null
abort: AbortController
evicted: boolean
}
const jobs = new Map<string, HlsJob>()
const jobsByLookup = new Map<string, HlsJob>()
let lastCleanupAt = 0
type HlsState = {
/** In-flight and ready jobs by cache key, so overlapping requests share one ffmpeg. */
pending: Map<string, Promise<HlsJob>>
jobs: Map<string, HlsJob>
jobsByLookup: Map<string, HlsJob>
lastCleanupAt: number
}
const globalState = globalThis as typeof globalThis & {
__otunesHls?: HlsState
}
const state = (globalState.__otunesHls ??= {
pending: new Map(),
jobs: new Map(),
jobsByLookup: new Map(),
lastCleanupAt: 0,
})
export function qualityKbps(quality: string | null) {
if (quality === "low") {
@@ -50,10 +74,6 @@ export function selectHlsSourceCodec(
return sourceCodec
}
function hlsCacheRoot() {
return "/tmp/otunes"
}
function hlsLookupKey(
songId: string,
quality: string | null,
@@ -88,31 +108,38 @@ export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
async function touchHlsJob(job: HlsJob) {
job.lastTouchedAt = Date.now()
await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch(
() => {}
)
}
function forgetJob(job: HlsJob) {
jobs.delete(job.key)
if (jobsByLookup.get(job.lookupKey) === job) {
jobsByLookup.delete(job.lookupKey)
}
await touchCacheEntry(job.dir).catch(() => {})
}
async function evictJob(job: HlsJob) {
forgetJob(job)
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
if (job.evicted) {
return
}
job.evicted = true
state.pending.delete(job.key)
state.jobs.delete(job.key)
if (state.jobsByLookup.get(job.lookupKey) === job) {
state.jobsByLookup.delete(job.lookupKey)
}
job.abort.abort()
job.process?.child.kill("SIGKILL")
const complete = job.processExited && job.processExitCode === 0
if (!complete) {
await job.process?.exited
await fs.rm(job.dir, { recursive: true, force: true }).catch(() => {})
}
unpinCacheEntry(job.dir)
}
async function cleanupIdleHlsJobs() {
const now = Date.now()
if (now - lastCleanupAt < 60_000) {
if (now - state.lastCleanupAt < 60_000) {
return
}
lastCleanupAt = now
state.lastCleanupAt = now
for (const job of [...jobs.values()]) {
for (const job of [...state.jobs.values()]) {
if (now - job.lastTouchedAt > HLS_MAX_IDLE_MS) {
await evictJob(job)
}
@@ -124,7 +151,7 @@ export function getExistingHlsJob(
quality: string | null,
preferAtmos: boolean
) {
return jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
return state.jobsByLookup.get(hlsLookupKey(songId, quality, preferAtmos)) ?? null
}
export async function waitForHlsSegment(
@@ -137,18 +164,22 @@ export async function waitForHlsSegment(
const startedAt = Date.now()
while (Date.now() - startedAt < timeoutMs) {
// Read before checking the file so a segment renamed just before exit is found.
const exited = job.processExited
try {
const firstStat = await fs.stat(segmentPath)
if (firstStat.size > 0) {
await new Promise((resolve) => setTimeout(resolve, 100))
const secondStat = await fs.stat(segmentPath)
if (firstStat.size === secondStat.size) {
return segmentPath
}
}
// ffmpeg writes to a .tmp file and renames it when complete.
await fs.access(segmentPath)
return segmentPath
} catch {
if (job.processExited && job.processExitCode !== 0) {
throw new Error(`HLS transcode failed with code ${job.processExitCode}`)
if (job.evicted) {
throw new Error("HLS job was evicted")
}
if (exited) {
throw new Error(
job.processExitCode === 0
? "HLS segment does not exist"
: `HLS transcode failed with code ${job.processExitCode}`
)
}
}
await new Promise((resolve) => setTimeout(resolve, 100))
@@ -157,52 +188,15 @@ export async function waitForHlsSegment(
throw new Error("Timed out waiting for HLS segment")
}
export async function ensureHlsJob(
song: Doc<"songs">,
quality: string | null,
preferAtmos: boolean
) {
await cleanupIdleHlsJobs()
const kbps = qualityKbps(quality)
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
const sourcePath = song.files[sourceCodec]
const key = await hlsJobKey(song, sourcePath, kbps)
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
const existingJob = jobs.get(key)
if (existingJob) {
try {
await fs.access(existingJob.dir)
await touchHlsJob(existingJob)
return existingJob
} catch {
forgetJob(existingJob)
}
}
const metadata = await music.parseFile(sourcePath)
const duration = metadata.format.duration ?? song.length
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
const dir = path.join(hlsCacheRoot(), key)
await fs.mkdir(dir, { recursive: true })
const job: HlsJob = {
key,
lookupKey,
dir,
duration,
segmentCount,
lastTouchedAt: Date.now(),
processExited: false,
processExitCode: null,
}
jobs.set(key, job)
jobsByLookup.set(lookupKey, job)
await touchHlsJob(job)
async function hasCompletePlaylist(dir: string) {
const playlist = await fs
.readFile(path.join(dir, "index.m3u8"), "utf8")
.catch(() => "")
return playlist.includes("#EXT-X-ENDLIST")
}
function startTranscode(job: HlsJob, sourcePath: string, kbps: number) {
const ffmpegArgs = [
"-nostdin",
"-i",
sourcePath,
"-vn",
@@ -222,25 +216,121 @@ export async function ensureHlsJob(
"0",
"-hls_segment_type",
"mpegts",
"-hls_flags",
"temp_file",
"-hls_segment_filename",
path.join(dir, "segment_%05d.ts"),
path.join(dir, "index.m3u8"),
path.join(job.dir, "segment_%05d.ts"),
path.join(job.dir, "index.m3u8"),
]
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
ffmpegProcess.stderr.on("data", (data) => {
console.error(`FFmpeg HLS log: ${data.toString()}`)
})
spawnFfmpeg(ffmpegArgs, job.abort.signal).then(
async (ffmpeg) => {
job.process = ffmpeg
if (job.evicted) {
ffmpeg.child.kill("SIGKILL")
}
const code = await ffmpeg.exited
job.process = null
job.processExited = true
job.processExitCode = code
if (job.evicted) {
return
}
if (code === 0) {
void pruneCache()
} else {
console.error(`ffmpeg HLS exited with code ${code}`, ffmpeg.stderrTail())
}
},
() => {
job.processExited = true
job.processExitCode = 1
}
)
}
ffmpegProcess.on("close", (code) => {
job.processExited = true
job.processExitCode = code
})
async function createHlsJob(
song: Doc<"songs">,
sourcePath: string,
kbps: number,
key: string,
lookupKey: string
): Promise<HlsJob> {
const info = await audioInfo(sourcePath)
const duration = info.duration ?? song.length
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
const dir = path.join(cacheDir("hls"), key)
pinCacheEntry(dir)
ffmpegProcess.on("error", () => {
job.processExited = true
job.processExitCode = 1
})
try {
const complete = await hasCompletePlaylist(dir)
if (!complete) {
await fs.rm(dir, { recursive: true, force: true })
await fs.mkdir(dir, { recursive: true })
}
const job: HlsJob = {
key,
lookupKey,
dir,
duration,
segmentCount,
lastTouchedAt: Date.now(),
processExited: complete,
processExitCode: complete ? 0 : null,
process: null,
abort: new AbortController(),
evicted: false,
}
state.jobs.set(key, job)
await touchHlsJob(job)
if (!complete) {
startTranscode(job, sourcePath, kbps)
}
return job
} catch (error) {
unpinCacheEntry(dir)
throw error
}
}
export async function ensureHlsJob(
song: Doc<"songs">,
quality: string | null,
preferAtmos: boolean
): Promise<HlsJob> {
await cleanupIdleHlsJobs()
const kbps = qualityKbps(quality)
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
const sourcePath = song.files[sourceCodec]
const key = await hlsJobKey(song, sourcePath, kbps)
const lookupKey = hlsLookupKey(song._id, quality, preferAtmos)
let pending = state.pending.get(key)
if (!pending) {
pending = createHlsJob(song, sourcePath, kbps, key, lookupKey)
state.pending.set(key, pending)
const created = pending
created.catch(() => {
if (state.pending.get(key) === created) {
state.pending.delete(key)
}
})
}
const job = await pending
const exists = await fs.access(job.dir).then(
() => true,
() => false
)
if (job.evicted || !exists) {
await evictJob(job)
return ensureHlsJob(song, quality, preferAtmos)
}
state.jobsByLookup.set(lookupKey, job)
await touchHlsJob(job)
return job
}
+32 -43
View File
@@ -1,8 +1,15 @@
import { spawn } from "node:child_process"
import { createHash } from "node:crypto"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import {
CACHE_ORPHAN_PREFIX,
cacheDir,
pinCacheEntry,
pruneCache,
touchCacheEntry,
unpinCacheEntry,
} from "@/lib/server-cache"
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
const conversions = new Map<string, Promise<string>>()
@@ -27,56 +34,38 @@ export async function seekableLosslessFile(source: string): Promise<string> {
}
async function convert(source: string, key: string): Promise<string> {
const dir = path.join(os.tmpdir(), "otunes-lossless")
const dir = cacheDir("lossless")
await fs.mkdir(dir, { recursive: true })
const cutoff = Date.now() - 30 * 60 * 1000
await Promise.all(
(await fs.readdir(dir))
.filter((name) => name.endsWith(".flac"))
.map(async (name) => {
const file = path.join(dir, name)
const stat = await fs.stat(file).catch(() => null)
if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true })
})
)
const output = path.join(dir, `${key}.flac`)
try {
await fs.access(output)
// Every range request touches the file so it stays cached while playing.
await touchCacheEntry(output)
return output
} catch {
// Publish only completed conversions so range requests always see a complete file.
}
const temporary = path.join(
await fs.mkdtemp(path.join(dir, "convert-")),
"audio.flac"
)
const temporaryDir = await fs.mkdtemp(path.join(dir, CACHE_ORPHAN_PREFIX))
const temporary = path.join(temporaryDir, "audio.flac")
pinCacheEntry(temporaryDir)
try {
await new Promise<void>((resolve, reject) => {
const child = spawn(
"ffmpeg",
[
"-nostdin",
"-v",
"error",
"-i",
source,
"-map",
"0:a:0",
"-c:a",
"flac",
temporary,
],
{ stdio: "ignore" }
)
child.on("error", reject)
child.on("close", (code) => {
if (code === 0) resolve()
else reject(new Error(`Lossless conversion failed: ${code}`))
})
})
const ffmpeg = await spawnFfmpeg([
"-i",
source,
"-map",
"0:a:0",
"-c:a",
"flac",
temporary,
])
const code = await ffmpeg.exited
if (code !== 0) {
throw new Error(`Lossless conversion failed: ${code}: ${ffmpeg.stderrTail()}`)
}
await fs.rename(temporary, output)
return output
} finally {
await fs.rm(path.dirname(temporary), { recursive: true, force: true })
unpinCacheEntry(temporaryDir)
await fs.rm(temporaryDir, { recursive: true, force: true })
}
void pruneCache()
return output
}
+30
View File
@@ -0,0 +1,30 @@
import assert from "node:assert/strict"
import test from "node:test"
import { stationArtistId } from "./station-artist.ts"
const songs = [
{ id: "song-a", artist: { id: "artist-a" } },
{ id: "song-b", artist: { id: "artist-a" } },
{ id: "song-c", artist: { id: "artist-b" } },
]
test("a single song or a selection sharing one artist can create a station", () => {
assert.equal(stationArtistId(songs, new Set(["song-c"])), "artist-b")
assert.equal(
stationArtistId(songs, new Set(["song-a", "song-b"])),
"artist-a"
)
})
test("mixed artists cannot create a station", () => {
assert.equal(stationArtistId(songs, new Set(["song-a", "song-c"])), undefined)
})
test("empty or partially missing selections cannot create a station", () => {
assert.equal(stationArtistId(songs, new Set()), undefined)
assert.equal(
stationArtistId(songs, new Set(["song-a", "missing"])),
undefined
)
})
+6 -27
View File
@@ -46,34 +46,22 @@ stop() {
}
trap 'stop; exit 0' TERM INT
as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex)
convex_cli() {
(
cd "$FUNCTIONS_DIR"
unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY
CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \
CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \
"${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@"
"$NODE" node_modules/convex/bin/main.js "$@"
)
}
# Only the convex user may read the database and instance secret. Volumes from
# images that ran the backend as root are still owned by root, and
# read_credentials.sh generates a new instance secret if it cannot read the old one.
# Only root (the backend) may read the database and instance secret.
mkdir -p "$CONVEX_DATA_DIR"
find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \
-exec chown -h convex:convex {} +
chmod 700 "$CONVEX_DATA_DIR"
# The web server writes HLS streams here and a Convex cron deletes stale ones.
mkdir -p /tmp/otunes
chown otunes:otunes /tmp/otunes
chmod -R g+rwX /tmp/otunes
chmod g+s,o-rwx /tmp/otunes
log "Starting Convex backend"
(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) &
(cd /convex && umask 077 && exec ./run_backend.sh) &
backend_pid=$!
for _ in $(seq 1 120); do
@@ -92,24 +80,17 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then
exit 1
fi
admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh)
admin_key=$(cd /convex && ./generate_admin_key.sh)
log "Deploying Convex functions"
convex_cli deploy --typecheck disable --codegen disable
# `env get` exits 0 with no output when the variable is unset. Any other failure
# must not be read as "no keys": regenerating them signs every user out.
if ! jwks=$(convex_cli env get JWKS); then
log "Could not read Convex Auth signing keys"
stop
exit 1
fi
if [ -z "$jwks" ]; then
if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then
log "Generating Convex Auth signing keys"
"$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force
fi
unset admin_key jwks
unset admin_key
log "Starting web server"
(
@@ -119,8 +100,6 @@ log "Starting web server"
# Server-side Convex helpers fall back to this at runtime. The browser bundle
# is built without it, so browsers still derive their own URL.
export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL"
# Lets the convex group member delete stale HLS streams.
umask 0002
exec setpriv --reuid=otunes --regid=otunes --init-groups \
"$NODE" apps/web/server.js
) &
+7
View File
@@ -578,6 +578,13 @@ export const updateLibrary = action({
},
})
export const cleanupHlsStreams = internalAction({
args: {},
handler: async () => {
return await cleanHlsStreamsOlderThan(HLS_MAX_IDLE_MS)
},
})
export const adminCleanupHlsStreams = action({
args: {},
handler: async (ctx) => {
+25 -1
View File
@@ -1,10 +1,11 @@
import { getAuthUserId } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values"
import { paginationOptsValidator } from "convex/server"
import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx, QueryCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server"
import type { BrowsePlaylistDetail, BrowsePlaylistSummary } from "./library"
import { browseSongsFromIds } from "./library"
import { browseSongsFromIds, paginateSlice } from "./library"
function uniqueIds<T extends string>(ids: T[]): T[] {
return [...new Set(ids)]
@@ -180,6 +181,11 @@ async function browseFavoritesSummaryHandler(
}
}
export const browseFavoritesSummary = query({
args: {},
handler: async (ctx) => browseFavoritesSummaryHandler(ctx),
})
export const browseFavoritesPlaylistDetail = query({
args: {},
handler: async (ctx): Promise<BrowsePlaylistDetail | null> => {
@@ -203,6 +209,24 @@ export const browseFavoritesPlaylistDetail = query({
},
})
export const browseFavoritesSongsPaginated = query({
args: { paginationOpts: paginationOptsValidator },
handler: async (ctx, args) => {
const summary = await browseFavoritesSummaryHandler(ctx)
if (!summary) {
return { page: [], isDone: true, continueCursor: "" }
}
const slice = paginateSlice(summary.songIds, args.paginationOpts)
const page = await browseSongsFromIds(ctx, slice.page)
return {
...slice,
page,
}
},
})
export const favoriteSong = mutation({
args: { songId: v.id("songs") },
handler: async (ctx, { songId }) => {
+290 -1
View File
@@ -8,6 +8,7 @@ import type { PaginationOptions, PaginationResult } from "convex/server"
import type {
BrowseAlbum,
BrowseAlbumDetail,
BrowseAlbumSummary,
BrowseAlbumTrack,
BrowseArtist,
BrowseArtistDetail,
@@ -25,6 +26,7 @@ import type {
export type {
BrowseAlbum,
BrowseAlbumDetail,
BrowseAlbumSummary,
BrowseAlbumTrack,
BrowseArtist,
BrowseArtistDetail,
@@ -222,7 +224,7 @@ export const browseArtists = query({
},
})
function paginateSlice<T>(
export function paginateSlice<T>(
items: T[],
paginationOpts: PaginationOptions
): PaginationResult<T> {
@@ -278,6 +280,27 @@ export const browseAlbumsPaginated = query({
},
})
export const browseSongs = query({
args: {},
handler: async (ctx) => {
const artistMap = await loadArtistMap(ctx)
const albums = await ctx.db.query("albums").collect()
const albumMap = new Map(albums.map((album) => [album._id, album]))
const songs = await ctx.db.query("songs").collect()
return songs
.flatMap((song) => {
const album = albumMap.get(song.album)
const albumArtist = artistMap.get(song.albumArtist)
if (!album || !albumArtist) {
return []
}
return [toBrowseSong(song, album, albumArtist)]
})
.sort((a, b) => a.title.localeCompare(b.title))
},
})
export const songsSortKeyValidator = v.union(
v.literal("title"),
v.literal("artist"),
@@ -522,6 +545,72 @@ export const browseAlbumDetail = query({
},
})
async function browseAlbumSummaryHandler(
ctx: QueryCtx,
albumId: Id<"albums">
): Promise<BrowseAlbumSummary | null> {
const album = await ctx.db.get("albums", albumId)
if (!album) {
return null
}
const artist = await ctx.db.get("artists", album.artist)
if (!artist) {
return null
}
const songs = await ctx.db
.query("songs")
.withIndex("by_album", (q) => q.eq("album", albumId))
.collect()
songs.sort(compareAlbumSongs)
const primarySong = songs[0]
return {
...toBrowseAlbum(album, artist),
year: primarySong?.year ?? null,
genre: primarySong?.genres[0] ?? null,
releaseDate: album.date,
hasLossless: songs.some((song) => "lossless" in song.files),
hasAtmos: songs.some((song) => "atmos" in song.files),
trackCount: songs.length,
}
}
export const browseAlbumSummary = query({
args: { id: v.id("albums") },
handler: async (ctx, args) => browseAlbumSummaryHandler(ctx, args.id),
})
export const browseAlbumTracksPaginated = query({
args: {
albumId: v.id("albums"),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
const album = await ctx.db.get("albums", args.albumId)
if (!album) {
return { page: [], isDone: true, continueCursor: "" }
}
const artist = await ctx.db.get("artists", album.artist)
if (!artist) {
return { page: [], isDone: true, continueCursor: "" }
}
const songs = await ctx.db
.query("songs")
.withIndex("by_album", (q) => q.eq("album", args.albumId))
.collect()
songs.sort(compareAlbumSongs)
const tracks = songs.map((song) => toBrowseAlbumTrack(song, artist.name))
return paginateSlice(tracks, args.paginationOpts)
},
})
export const browseArtistDetail = query({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
@@ -819,6 +908,16 @@ export const getAlbums = internalQuery({
},
})
export const getAlbumsInArtist = internalQuery({
args: { artistID: v.id("artists") },
handler: async (ctx, args) => {
return await ctx.db
.query("albums")
.withIndex("by_artist", (q) => q.eq("artist", args.artistID))
.collect()
},
})
export const getSongs = internalQuery({
args: {},
handler: async (ctx) => {
@@ -826,6 +925,26 @@ export const getSongs = internalQuery({
},
})
export const getSongsInArtist = internalQuery({
args: { artistID: v.id("artists") },
handler: async (ctx, args) => {
return await ctx.db
.query("songs")
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistID))
.collect()
},
})
export const getSongsInAlbum = internalQuery({
args: { albumID: v.id("albums") },
handler: async (ctx, args) => {
return await ctx.db
.query("songs")
.withIndex("by_album", (q) => q.eq("album", args.albumID))
.collect()
},
})
export const getArtist = query({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
@@ -833,6 +952,16 @@ export const getArtist = query({
},
})
export const getArtistByName = internalQuery({
args: { name: v.string() },
handler: async (ctx, args) => {
return await ctx.db
.query("artists")
.withIndex("by_name", (q) => q.eq("name", args.name))
.first()
},
})
export const getAlbum = query({
args: { id: v.id("albums") },
handler: async (ctx, args) => {
@@ -840,6 +969,28 @@ export const getAlbum = query({
},
})
export const getAlbumByName = internalQuery({
args: { name: v.string() },
handler: async (ctx, args) => {
return await ctx.db
.query("albums")
.withIndex("by_name", (q) => q.eq("name", args.name))
.first()
},
})
export const getAlbumByAll = internalQuery({
args: { folder: v.string(), artist: v.id("artists") },
handler: async (ctx, args) => {
return await ctx.db
.query("albums")
.withIndex("by_all", (q) =>
q.eq("artist", args.artist).eq("folder", args.folder)
)
.first()
},
})
export const getPlaylist = query({
args: { id: v.id("playlists") },
handler: async (ctx, args) => {
@@ -1024,6 +1175,49 @@ export const intentCatalogPage = query({
},
})
export const getSongByName = internalQuery({
args: { name: v.string() },
handler: async (ctx, args) => {
return await ctx.db
.query("songs")
.withIndex("by_name", (q) => q.eq("name", args.name))
.first()
},
})
export const getSongByAll = internalQuery({
args: {
name: v.string(),
albumArtist: v.id("artists"),
album: v.id("albums"),
},
handler: async (ctx, args) => {
return await ctx.db
.query("songs")
.withIndex("by_all", (q) =>
q
.eq("name", args.name)
.eq("albumArtist", args.albumArtist)
.eq("album", args.album)
)
.first()
},
})
export const createArtist = internalMutation({
args: { name: v.string(), folder: v.string(), cover: v.nullable(v.string()) },
handler: async (ctx, args) => {
const existing = await ctx.db
.query("artists")
.withIndex("by_folder", (q) => q.eq("folder", args.folder))
.first()
if (existing) {
return existing._id
}
return await ctx.db.insert("artists", args)
},
})
export const createArtists = internalMutation({
args: {
artists: v.array(
@@ -1048,6 +1242,29 @@ export const createArtists = internalMutation({
},
})
export const createAlbum = internalMutation({
args: {
name: v.string(),
folder: v.string(),
cover: v.nullable(v.string()),
year: v.number(),
date: v.string(),
artist: v.id("artists"),
},
handler: async (ctx, args) => {
const existing = await ctx.db
.query("albums")
.withIndex("by_all", (q) =>
q.eq("artist", args.artist).eq("folder", args.folder)
)
.first()
if (existing) {
return existing._id
}
return await ctx.db.insert("albums", args)
},
})
export const createAlbums = internalMutation({
args: {
albums: v.array(
@@ -1077,6 +1294,50 @@ export const createAlbums = internalMutation({
},
})
export const updateAlbumName = internalMutation({
args: {
id: v.id("albums"),
newName: v.string(),
},
handler: async (ctx, args) => {
return await ctx.db.patch("albums", args.id, { name: args.newName })
},
})
export const createSong = internalMutation({
args: {
name: v.string(),
files: v.record(v.string(), v.string()),
album: v.id("albums"),
artist: v.union(v.string(), v.array(v.string())),
albumArtist: v.id("artists"),
length: v.number(),
diskNumber: v.nullable(v.number()),
track: v.number(),
year: v.number(),
date: v.string(),
genres: v.array(v.string()),
},
handler: async (ctx, args) => {
const existing = await ctx.db
.query("songs")
.withIndex("by_all", (q) =>
q
.eq("name", args.name)
.eq("albumArtist", args.albumArtist)
.eq("album", args.album)
)
.first()
if (existing) {
await ctx.db.patch(existing._id, {
files: { ...existing.files, ...args.files },
})
return existing._id
}
return await ctx.db.insert("songs", args)
},
})
export const createSongs = internalMutation({
args: {
songs: v.array(
@@ -1224,6 +1485,13 @@ export const purgeArtistsFromUsers = internalMutation({
},
})
export const removeArtist = internalMutation({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
return await ctx.db.delete("artists", args.id)
},
})
export const removeArtists = internalMutation({
args: { ids: v.array(v.id("artists")) },
handler: async (ctx, args) => {
@@ -1233,6 +1501,13 @@ export const removeArtists = internalMutation({
},
})
export const removeAlbum = internalMutation({
args: { id: v.id("albums") },
handler: async (ctx, args) => {
return await ctx.db.delete("albums", args.id)
},
})
export const removeAlbums = internalMutation({
args: { ids: v.array(v.id("albums")) },
handler: async (ctx, args) => {
@@ -1242,6 +1517,20 @@ export const removeAlbums = internalMutation({
},
})
export const removeSong = internalMutation({
args: { id: v.id("songs") },
handler: async (ctx, args) => {
return await ctx.db.delete("songs", args.id)
},
})
export const changeFilesForSong = internalMutation({
args: { id: v.id("songs"), files: v.record(v.string(), v.string()) },
handler: async (ctx, args) => {
return await ctx.db.patch("songs", args.id, { files: args.files })
},
})
export const changeFilesForSongs = internalMutation({
args: {
songs: v.array(
+654 -1
View File
@@ -1,9 +1,17 @@
import { getAuthUserId } from "@convex-dev/auth/server"
import { paginationOptsValidator } from "convex/server"
import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server"
import { browseSongsFromIds } from "./library"
import type { QueueSong } from "./types"
import {
browseSongsFromIds,
compareAlbumSongs,
getSortedLibrarySongIds,
songsSortDirectionValidator,
songsSortKeyValidator,
} from "./library"
export type { HistorySong, QueueSong } from "./types"
@@ -51,6 +59,35 @@ async function recordRecentlyPlayedFromSong(
await recordRecentlyPlayed(ctx, userId, song.album)
}
async function recordPlaybackStart(
ctx: MutationCtx,
userId: Id<"users">,
options: {
songIds: Id<"songs">[]
playlistId?: Id<"playlists">
}
) {
if (options.songIds.length === 0) {
return
}
if (options.playlistId) {
await recordRecentlyPlayed(ctx, userId, options.playlistId)
return
}
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) {
@@ -59,6 +96,54 @@ 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
}
const counts = new Map<Id<"songs">, number>()
for (const songId of first) {
counts.set(songId, (counts.get(songId) ?? 0) + 1)
}
for (const songId of second) {
const count = counts.get(songId)
if (!count) {
return false
}
if (count === 1) {
counts.delete(songId)
} else {
counts.set(songId, count - 1)
}
}
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">,
@@ -83,6 +168,26 @@ async function patchPlayback(
return playbackRevision
}
async function setQueueState(
ctx: MutationCtx,
userId: Id<"users">,
patch: {
songQueue: Id<"songs">[]
shuffleEnabled?: boolean
currentSongProgress?: number
resetHistory?: boolean
}
) {
await patchPlayback(ctx, userId, {
songQueue: patch.songQueue,
currentSongProgress: patch.currentSongProgress ?? 0,
...(patch.resetHistory ? { queueHistory: [] } : {}),
...(patch.shuffleEnabled !== undefined
? { shuffleEnabled: patch.shuffleEnabled }
: {}),
})
}
export const getPlaybackState = query({
args: {},
handler: async (ctx) => {
@@ -159,6 +264,554 @@ export const recordPlay = mutation({
},
})
export const getQueueHistory = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx)
if (userId === null) {
return []
}
const user = await ctx.db.get(userId)
if (!user) {
return []
}
const songIds = user.queueHistory ?? []
const songs = await browseSongsFromIds(ctx, songIds)
return songs.map((song, index) => ({
...song,
historyIndex: index,
}))
},
})
export const getQueuePaginated = query({
args: {
paginationOpts: paginationOptsValidator,
queueVersion: v.string(),
},
handler: async (ctx, args) => {
const userId = await getAuthUserId(ctx)
if (userId === null) {
return { page: [], isDone: true, continueCursor: "" }
}
const user = await ctx.db.get(userId)
if (!user) {
return { page: [], isDone: true, continueCursor: "" }
}
const songIds = user.songQueue ?? []
const startIndex = args.paginationOpts.cursor
? Number.parseInt(args.paginationOpts.cursor, 10)
: 0
const endIndex = Math.min(
startIndex + args.paginationOpts.numItems,
songIds.length
)
const pageIds = songIds.slice(startIndex, endIndex)
const songs = await browseSongsFromIds(ctx, pageIds)
const page: QueueSong[] = songs.map((song, index) => ({
...song,
queueIndex: startIndex + index,
}))
const isDone = endIndex >= songIds.length
return {
page,
isDone,
continueCursor: isDone ? "" : String(endIndex),
}
},
})
export const playInOrder = mutation({
args: {
songIds: v.array(v.id("songs")),
playlistId: v.optional(v.id("playlists")),
},
handler: async (ctx, { songIds, playlistId }) => {
const userId = await requireAuth(ctx)
const queue = uniqueSongIds(songIds)
await setQueueState(ctx, userId, {
songQueue: queue,
shuffleEnabled: false,
resetHistory: true,
})
await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
},
})
export const playShuffled = mutation({
args: {
songIds: v.array(v.id("songs")),
playlistId: v.optional(v.id("playlists")),
},
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,
})
await recordPlaybackStart(ctx, userId, { songIds: queue, playlistId })
},
})
function orderSongsForInsert(
songIds: Id<"songs">[],
shuffleEnabled: boolean
): Id<"songs">[] {
return shuffleEnabled ? shuffleArray(songIds) : songIds
}
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],
})
},
})
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],
})
},
})
export const playFromSong = mutation({
args: {
songId: v.id("songs"),
songIds: v.array(v.id("songs")),
},
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)
},
})
async function albumSongIds(ctx: MutationCtx, albumId: Id<"albums">) {
const songs = await ctx.db
.query("songs")
.withIndex("by_album", (q) => q.eq("album", albumId))
.collect()
songs.sort(compareAlbumSongs)
return songs.map((song) => song._id)
}
async function orderedArtistSongIds(
ctx: MutationCtx,
artistId: Id<"artists">
) {
const songs = await ctx.db
.query("songs")
.withIndex("by_artist", (q) => q.eq("albumArtist", artistId))
.collect()
const albums = await ctx.db
.query("albums")
.withIndex("by_artist", (q) => q.eq("artist", artistId))
.collect()
const albumMap = new Map(albums.map((album) => [album._id, album]))
songs.sort((a, b) => {
const albumA = albumMap.get(a.album)?.name ?? ""
const albumB = albumMap.get(b.album)?.name ?? ""
if (albumA !== albumB) {
return albumA.localeCompare(albumB)
}
if (a.track !== b.track) {
return a.track - b.track
}
return a.name.localeCompare(b.name)
})
return songs.map((song) => song._id)
}
async function playCollection(
ctx: MutationCtx,
options: {
songIds: Id<"songs">[]
shuffled: boolean
playlistId?: Id<"playlists">
}
) {
const userId = await requireAuth(ctx)
const unique = uniqueSongIds(options.songIds)
if (unique.length === 0) {
return
}
const queue = options.shuffled ? shuffleArray(unique) : unique
await setQueueState(ctx, userId, {
songQueue: queue,
shuffleEnabled: options.shuffled,
resetHistory: true,
})
await recordPlaybackStart(ctx, userId, {
songIds: queue,
playlistId: options.playlistId,
})
}
export const playAlbum = mutation({
args: { albumId: v.id("albums") },
handler: async (ctx, { albumId }) => {
await playCollection(ctx, {
songIds: await albumSongIds(ctx, albumId),
shuffled: false,
})
},
})
export const playAlbumShuffled = mutation({
args: { albumId: v.id("albums") },
handler: async (ctx, { albumId }) => {
await playCollection(ctx, {
songIds: await albumSongIds(ctx, albumId),
shuffled: true,
})
},
})
export const playArtist = mutation({
args: { artistId: v.id("artists") },
handler: async (ctx, { artistId }) => {
await playCollection(ctx, {
songIds: await orderedArtistSongIds(ctx, artistId),
shuffled: false,
})
},
})
export const playArtistShuffled = mutation({
args: { artistId: v.id("artists") },
handler: async (ctx, { artistId }) => {
await playCollection(ctx, {
songIds: await orderedArtistSongIds(ctx, artistId),
shuffled: true,
})
},
})
export const playPlaylist = mutation({
args: { playlistId: v.id("playlists") },
handler: async (ctx, { playlistId }) => {
const playlist = await ctx.db.get("playlists", playlistId)
await playCollection(ctx, {
songIds: playlist?.songs ?? [],
shuffled: false,
playlistId,
})
},
})
export const playPlaylistShuffled = mutation({
args: { playlistId: v.id("playlists") },
handler: async (ctx, { playlistId }) => {
const playlist = await ctx.db.get("playlists", playlistId)
await playCollection(ctx, {
songIds: playlist?.songs ?? [],
shuffled: true,
playlistId,
})
},
})
export const playFromLibrarySong = mutation({
args: {
songId: v.id("songs"),
sortKey: songsSortKeyValidator,
sortDirection: songsSortDirectionValidator,
},
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)
},
})
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 })
},
})
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 })
},
})
export const clearQueue = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
await patchPlayback(ctx, userId, {
songQueue: [],
queueHistory: [],
currentSongProgress: 0,
})
},
})
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 } : {}),
})
},
})
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,
})
},
})
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,
})
},
})
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,
})
},
})
export const getSongProgress = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx)
if (userId === null) {
throw new ConvexError("User not logged in")
}
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
return user.currentSongProgress ?? 0
},
})
export const updateSongProgress = mutation({
args: {
songId: v.id("songs"),
+33 -3
View File
@@ -1,3 +1,4 @@
import { paginationOptsValidator } from "convex/server"
import { getAuthUserId } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values"
import type { Doc, Id } from "./_generated/dataModel"
@@ -10,7 +11,7 @@ import type {
PlaylistSummary,
SidebarPlaylists,
} from "./library"
import { browseSongsFromIds, compareAlbumSongs } from "./library"
import { browseSongsFromIds, compareAlbumSongs, paginateSlice } from "./library"
function toPlaylistSummary(
playlist: Doc<"playlists">,
@@ -108,15 +109,23 @@ async function browsePlaylistSummaryHandler(
}
}
export const browsePlaylistDetail = query({
export const browsePlaylistSummary = query({
args: { id: v.id("playlists") },
handler: async (ctx, args) => browsePlaylistSummaryHandler(ctx, args.id),
})
export const browsePlaylistDetail = query({
args: { id: v.id("playlists"), includeSongs: v.optional(v.boolean()) },
handler: async (ctx, args): Promise<BrowsePlaylistDetail | null> => {
const summary = await browsePlaylistSummaryHandler(ctx, args.id)
if (!summary) {
return null
}
const songs = await browseSongsFromIds(ctx, summary.songIds)
const songs =
(args.includeSongs ?? true)
? await browseSongsFromIds(ctx, summary.songIds)
: []
return {
id: summary.id,
@@ -130,6 +139,27 @@ export const browsePlaylistDetail = query({
},
})
export const browsePlaylistSongsPaginated = query({
args: {
id: v.id("playlists"),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
const playlist = await ctx.db.get("playlists", args.id)
if (!playlist) {
return { page: [], isDone: true, continueCursor: "" }
}
const slice = paginateSlice(playlist.songs, args.paginationOpts)
const page = await browseSongsFromIds(ctx, slice.page)
return {
...slice,
page,
}
},
})
export const listOwnedPlaylists = query({
args: {},
handler: async (ctx) => {
+4
View File
@@ -41,6 +41,10 @@ export type BrowseAlbumDetail = BrowseAlbum & {
tracks: BrowseAlbumTrack[]
}
export type BrowseAlbumSummary = Omit<BrowseAlbumDetail, "tracks"> & {
trackCount: number
}
export type BrowseArtistDetail = {
artist: BrowseArtist
albums: BrowseAlbum[]