Files
otunes/apps/mobile/contexts/playback.tsx
T

733 lines
20 KiB
TypeScript

import { useConvex, useMutation, useQuery } from "convex/react"
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type ReactNode,
} from "react"
import {
ANONYMOUS_CACHE_SCOPE,
useCacheScope,
} from "@/contexts/persistent-cache"
import { useNativePlaylistSync } from "@/hooks/use-native-playlist-sync"
import { useProgressPersistence } from "@/hooks/use-progress-persistence"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import * as playbackQueue from "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
import { getPlaybackStore } from "@otunes/convex/client/playback-store"
import { rememberSongs, useSong, useSongs } from "@/lib/song-cache"
import { donateMusicPlay, type MusicEntityKind } from "@/lib/app-intents"
import { showError } from "@/lib/toast"
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
const PREFETCH_UPCOMING_SONGS = 5
type PlaybackContextValue = {
queueSongIds: Id<"songs">[]
queueHistorySongIds: Id<"songs">[]
currentSong: BrowseSong | null
shuffleEnabled: boolean
repeatEnabled: RepeatMode
isPlaying: boolean
currentTime: number
duration: number
seekTo: (seconds: number) => void
waitForPlaybackReady: (playing?: boolean) => Promise<void>
setIsPlaying: (playing: boolean) => void
playInOrder: (songIds: Id<"songs">[]) => Promise<void>
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
playFromSong: (
songId: Id<"songs">,
songIds: Id<"songs">[],
origin?: string
) => Promise<void>
playFromLibrarySong: (
songId: Id<"songs">,
sort: {
sortKey: "title" | "artist" | "album"
sortDirection: "asc" | "desc"
}
) => Promise<void>
playAlbum: (albumId: Id<"albums">, songIds?: Id<"songs">[]) => Promise<void>
playAlbumShuffled: (
albumId: Id<"albums">,
songIds?: Id<"songs">[]
) => Promise<void>
playArtist: (artistId: Id<"artists">) => Promise<void>
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
playPlaylist: (
playlistId: Id<"playlists">,
songIds?: Id<"songs">[]
) => Promise<void>
playPlaylistShuffled: (
playlistId: Id<"playlists">,
songIds?: Id<"songs">[]
) => Promise<void>
toggleShuffle: () => Promise<void>
setShuffleEnabled: (enabled: boolean) => Promise<void>
cycleRepeat: () => Promise<void>
setRepeatMode: (mode: RepeatMode) => Promise<void>
prepareQueue: (songIds: Id<"songs">[], shuffled: boolean) => Promise<void>
startFromSong: (
songId: Id<"songs">,
songIds: Id<"songs">[],
shuffled: boolean,
play: boolean
) => Promise<void>
clearQueue: () => Promise<void>
clearUpNext: () => Promise<void>
clearHistory: () => Promise<void>
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
skipToQueueIndex: (index: number) => Promise<void>
skipToHistoryIndex: (index: number) => Promise<void>
skipNext: () => Promise<void>
skipPrevious: () => Promise<void>
}
type PlaybackActionsValue = Pick<
PlaybackContextValue,
| "seekTo"
| "waitForPlaybackReady"
| "setIsPlaying"
| "playInOrder"
| "playShuffled"
| "addToQueueNext"
| "addToQueueLast"
| "playFromSong"
| "playFromLibrarySong"
| "playAlbum"
| "playAlbumShuffled"
| "playArtist"
| "playArtistShuffled"
| "playPlaylist"
| "playPlaylistShuffled"
| "toggleShuffle"
| "setShuffleEnabled"
| "cycleRepeat"
| "setRepeatMode"
| "prepareQueue"
| "startFromSong"
| "clearQueue"
| "clearUpNext"
| "clearHistory"
| "reorderQueue"
| "skipToQueueIndex"
| "skipToHistoryIndex"
| "skipNext"
| "skipPrevious"
>
type PlaybackQueueValue = Pick<
PlaybackContextValue,
| "queueSongIds"
| "queueHistorySongIds"
| "currentSong"
| "isPlaying"
| "shuffleEnabled"
| "repeatEnabled"
>
type PlaybackProgressValue = Pick<
PlaybackContextValue,
"currentTime" | "duration"
>
type CollectionPlayers = Pick<
PlaybackActionsValue,
| "playAlbum"
| "playAlbumShuffled"
| "playArtist"
| "playArtistShuffled"
| "playPlaylist"
| "playPlaylistShuffled"
>
type RecordedPlay = {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
}
type CollectionPlay = {
songIds: Id<"songs">[] | Promise<Id<"songs">[]>
recorded: RecordedPlay
}
const PlaybackActionsContext = createContext<PlaybackActionsValue | null>(null)
const PlaybackQueueContext = createContext<PlaybackQueueValue | null>(null)
const PlaybackProgressContext = createContext<PlaybackProgressValue | null>(
null
)
/** Ticks while audio plays. Keep consumers small (slider and time labels). */
export function usePlaybackProgress() {
const context = useContext(PlaybackProgressContext)
if (!context) {
throw new Error("usePlaybackProgress must be used within PlaybackProvider")
}
return context
}
export function usePlaybackActions() {
const context = useContext(PlaybackActionsContext)
if (!context) {
throw new Error("usePlaybackActions must be used within PlaybackProvider")
}
return context
}
export function usePlaybackQueue() {
const context = useContext(PlaybackQueueContext)
if (!context) {
throw new Error("usePlaybackQueue must be used within PlaybackProvider")
}
return context
}
export function PlaybackProvider({ children }: { children: ReactNode }) {
const convex = useConvex()
const cacheScope = useCacheScope()
const isSignedIn = cacheScope !== ANONYMOUS_CACHE_SCOPE
const store = useMemo(
() => getPlaybackStore(isSignedIn ? cacheScope : null),
[cacheScope, isSignedIn]
)
const playback = useSyncExternalStore(store.subscribe, store.getSnapshot)
const serverPlayback = useQuery(
api.playback.getPlaybackState,
isSignedIn ? {} : "skip"
)
const syncPlaybackStateMutation = useMutation(api.playback.syncPlaybackState)
const recordPlayMutation = useMutation(api.playback.recordPlay)
useEffect(() => {
if (!isSignedIn) return
store.setTransport({
sync: (state) =>
syncPlaybackStateMutation({
songQueue: state.queue,
queueHistory: state.history,
shuffleEnabled: state.shuffleEnabled,
repeatEnabled: state.repeatEnabled,
currentSongProgress: state.progressSeconds,
}),
loadProgress: () => convex.query(api.playback.getSongProgress, {}),
})
return () => store.setTransport(null)
}, [store, isSignedIn, syncPlaybackStateMutation, convex])
useEffect(() => {
if (!serverPlayback) return
if (serverPlayback.currentSong) {
rememberSongs([serverPlayback.currentSong])
}
store.receiveServerState(serverPlayback)
}, [store, serverPlayback])
const recordPlay = useCallback(
(args: { songId?: Id<"songs">; playlistId?: Id<"playlists"> }) => {
void recordPlayMutation(args).catch(() => {})
},
[recordPlayMutation]
)
const queueOriginRef = useRef<string | undefined>(undefined)
const playRequestRef = useRef(0)
const [queueStartVersion, setQueueStartVersion] = useState(0)
const queueSongIds = playback.queue
const queueHistorySongIds = playback.history
const repeatEnabled = playback.repeatEnabled
const currentSongId = queueSongIds[0] ?? null
const currentSong = useSong(currentSongId)
const adjacentSongIds = useMemo(
() => [
...queueHistorySongIds.slice(-1),
...queueSongIds.slice(1, 1 + PREFETCH_UPCOMING_SONGS),
],
[queueHistorySongIds, queueSongIds]
)
useSongs(adjacentSongIds)
const {
isPlaying,
setIsPlaying,
currentTime,
currentTimeRef,
duration,
seekTo,
queueSeek,
hasPlayer,
requestAutoPlay,
resetPosition,
resetForNewQueue,
waitForSong,
} = useNativePlaylistSync({
store,
queueSongIds,
queueHistorySongIds,
repeatEnabled,
currentSong,
queueStartVersion,
})
const { resetProgress } = useProgressPersistence({
store,
currentSongId,
isPlaying,
queueStartVersion,
currentTimeRef,
hasPlayer,
queueSeek,
resetPosition,
})
const resetQueuePlayback = useCallback(() => {
resetForNewQueue()
resetProgress()
setQueueStartVersion((version) => version + 1)
}, [resetForNewQueue, resetProgress])
const startPlayback = useCallback(
(
recipe: (
state: playbackQueue.PlaybackQueueState
) => playbackQueue.PlaybackQueueState,
recorded: RecordedPlay = {}
) => {
playRequestRef.current += 1
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
resetQueuePlayback()
store.update(playbackQueue.clearQueue)
store.update(recipe)
const firstSongId = store.getState().queue[0]
if (!firstSongId) return
setIsPlaying(true)
void waitForSong(firstSongId, true).then(
() =>
donateMusicPlay(
recorded.entity?.kind ??
(recorded.playlistId ? "playlist" : "song"),
recorded.entity?.id ?? recorded.playlistId ?? firstSongId,
store.getState().shuffleEnabled
),
() => {}
)
recordPlay(
recorded.playlistId
? { playlistId: recorded.playlistId }
: { songId: firstSongId }
)
},
[store, resetQueuePlayback, setIsPlaying, waitForSong, recordPlay]
)
const playCollection = useCallback(
async (
songIds: Id<"songs">[] | Promise<Id<"songs">[]>,
shuffled: boolean,
recorded: RecordedPlay = {}
) => {
const request = ++playRequestRef.current
let resolvedSongIds: Id<"songs">[]
try {
resolvedSongIds = await songIds
} catch {
showError("Could not load songs to play")
return
}
if (request !== playRequestRef.current || resolvedSongIds.length === 0) {
return
}
startPlayback(
(state) => playbackQueue.startQueue(state, resolvedSongIds, shuffled),
recorded
)
},
[startPlayback]
)
const playSongs = useCallback(
(shuffled: boolean) => async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) return
startPlayback((state) =>
playbackQueue.startQueue(state, songIds, shuffled)
)
},
[startPlayback]
)
const playInOrder = useMemo(() => playSongs(false), [playSongs])
const playShuffled = useMemo(() => playSongs(true), [playSongs])
const collectionPlayers = useMemo<CollectionPlayers>(() => {
const collection =
<Args extends unknown[]>(resolve: (...args: Args) => CollectionPlay) =>
(shuffled: boolean) =>
(...args: Args) => {
const { songIds, recorded } = resolve(...args)
return playCollection(songIds, shuffled, recorded)
}
const album = collection(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) => ({
songIds:
songIds ??
fetchCachedQuery(convex, cacheScope, api.playlists.getAlbumSongIds, {
albumId,
}),
recorded: {
entity: { kind: "album", id: albumId },
origin: `album:${albumId}`,
},
})
)
const artist = collection((artistId: Id<"artists">) => ({
songIds: fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId }
),
recorded: { entity: { kind: "artist", id: artistId } },
}))
const playlist = collection(
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) => ({
songIds:
songIds ??
fetchCachedQuery(
convex,
cacheScope,
api.playlists.getPlaylistSongIds,
{ playlistId }
),
recorded: { playlistId },
})
)
return {
playAlbum: album(false),
playAlbumShuffled: album(true),
playArtist: artist(false),
playArtistShuffled: artist(true),
playPlaylist: playlist(false),
playPlaylistShuffled: playlist(true),
}
}, [convex, cacheScope, playCollection])
const addToQueue = useCallback(
(songIds: Id<"songs">[], position: "next" | "last") => {
if (songIds.length === 0) return
const shouldStartPlayback = store.getState().queue.length === 0
store.update((state) =>
playbackQueue.addToQueue(state, songIds, position)
)
if (shouldStartPlayback) {
setIsPlaying(true)
}
},
[store, setIsPlaying]
)
const addToQueueNext = useCallback(
async (songIds: Id<"songs">[]) => addToQueue(songIds, "next"),
[addToQueue]
)
const addToQueueLast = useCallback(
async (songIds: Id<"songs">[]) => addToQueue(songIds, "last"),
[addToQueue]
)
const playFromSong = useCallback(
async (songId: Id<"songs">, songIds: Id<"songs">[], origin?: string) => {
if (
origin &&
queueOriginRef.current === origin &&
store.getState().queue[0] === songId
)
return
startPlayback(
(state) => playbackQueue.startQueueFromSong(state, songId, songIds),
{ origin }
)
},
[startPlayback, store]
)
const playFromLibrarySong = useCallback(
async (
songId: Id<"songs">,
sort: {
sortKey: "title" | "artist" | "album"
sortDirection: "asc" | "desc"
}
) => {
startPlayback((state) =>
playbackQueue.startQueueFromSong(state, songId, [songId])
)
const request = playRequestRef.current
let songIds: Id<"songs">[]
try {
songIds = await fetchCachedQuery(
convex,
cacheScope,
api.library.browseSortedSongIds,
sort
)
} catch {
return
}
if (request === playRequestRef.current) {
store.update((state) =>
playbackQueue.extendQueueFromSong(state, songId, songIds)
)
}
},
[convex, cacheScope, store, startPlayback]
)
const toggleShuffle = useCallback(async () => {
store.update(playbackQueue.toggleShuffle)
}, [store])
const setShuffleEnabled = useCallback(
async (enabled: boolean) => {
store.update((state) => playbackQueue.setShuffleEnabled(state, enabled))
},
[store]
)
const cycleRepeat = useCallback(async () => {
store.update(playbackQueue.cycleRepeat)
}, [store])
const setRepeatMode = useCallback(
async (mode: RepeatMode) => {
store.update((state) => playbackQueue.setRepeatMode(state, mode))
},
[store]
)
const prepareQueue = useCallback(
async (songIds: Id<"songs">[], shuffled: boolean) => {
if (songIds.length === 0) return
playRequestRef.current += 1
queueOriginRef.current = undefined
resetQueuePlayback()
store.update((state) =>
playbackQueue.startQueue(state, songIds, shuffled)
)
setIsPlaying(false)
},
[store, resetQueuePlayback, setIsPlaying]
)
const startFromSong = useCallback(
async (
songId: Id<"songs">,
songIds: Id<"songs">[],
shuffled: boolean,
play: boolean
) => {
playRequestRef.current += 1
queueOriginRef.current = undefined
resetQueuePlayback()
store.update((state) => playbackQueue.setShuffleEnabled(state, shuffled))
store.update((state) =>
playbackQueue.startQueueFromSong(state, songId, songIds)
)
setIsPlaying(play)
},
[store, resetQueuePlayback, setIsPlaying]
)
const clearQueue = useCallback(async () => {
playRequestRef.current += 1
queueOriginRef.current = undefined
store.update(playbackQueue.clearQueue)
setIsPlaying(false)
}, [store, setIsPlaying])
const clearUpNext = useCallback(async () => {
store.update(playbackQueue.clearUpNext)
}, [store])
const clearHistory = useCallback(async () => {
store.update(playbackQueue.clearHistory)
}, [store])
const reorderQueue = useCallback(
async (songIds: Id<"songs">[]) => {
store.update((state) => playbackQueue.reorderQueue(state, songIds))
},
[store]
)
const skipToQueueIndex = useCallback(
async (index: number) => {
if (index <= 0) return
requestAutoPlay()
store.update((state) => playbackQueue.skipToQueueIndex(state, index))
},
[store, requestAutoPlay]
)
const skipToHistoryIndex = useCallback(
async (index: number) => {
if (index < 0 || index >= store.getState().history.length) return
requestAutoPlay()
store.update((state) => playbackQueue.skipToHistoryIndex(state, index))
},
[store, requestAutoPlay]
)
const skipNext = useCallback(async () => {
const before = store.getState()
if (before.repeatEnabled === "none" && before.queue.length <= 1) {
setIsPlaying(false)
store.update(playbackQueue.skipNext)
await seekTo(0)
return
}
if (before.repeatEnabled === "once" || before.queue.length <= 1) {
store.update(playbackQueue.skipNext)
await seekTo(0)
setIsPlaying(true)
return
}
requestAutoPlay()
store.update(playbackQueue.skipNext)
}, [store, seekTo, setIsPlaying, requestAutoPlay])
const skipPrevious = useCallback(async () => {
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
await seekTo(0)
return
}
if (store.getState().history.length === 0) {
store.update(playbackQueue.skipPrevious)
await seekTo(0)
return
}
requestAutoPlay()
store.update(playbackQueue.skipPrevious)
}, [store, seekTo, currentTimeRef, requestAutoPlay])
// Queue changes return before React has loaded the native audio source. Siri
// must observe the native player, rather than treating a state update as success.
const waitForPlaybackReady = useCallback(
async (playing?: boolean) => {
const expectedId = store.getState().queue[0]
if (!expectedId) throw new Error("Nothing is queued to play.")
await waitForSong(expectedId, playing)
},
[store, waitForSong]
)
const actionsValue = useMemo<PlaybackActionsValue>(
() => ({
seekTo,
waitForPlaybackReady,
...collectionPlayers,
setIsPlaying,
playInOrder,
playShuffled,
addToQueueNext,
addToQueueLast,
playFromSong,
playFromLibrarySong,
toggleShuffle,
setShuffleEnabled,
cycleRepeat,
setRepeatMode,
prepareQueue,
startFromSong,
clearQueue,
clearUpNext,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
skipNext,
skipPrevious,
}),
[
addToQueueNext,
addToQueueLast,
clearHistory,
clearQueue,
clearUpNext,
collectionPlayers,
cycleRepeat,
prepareQueue,
startFromSong,
setRepeatMode,
setShuffleEnabled,
playFromLibrarySong,
playFromSong,
playInOrder,
playShuffled,
reorderQueue,
seekTo,
setIsPlaying,
skipNext,
skipPrevious,
skipToHistoryIndex,
skipToQueueIndex,
toggleShuffle,
waitForPlaybackReady,
]
)
const isPlaybackActive = Boolean(currentSongId && isPlaying)
const queueValue = useMemo<PlaybackQueueValue>(
() => ({
shuffleEnabled: playback.shuffleEnabled,
repeatEnabled,
queueSongIds,
queueHistorySongIds,
currentSong,
isPlaying: isPlaybackActive,
}),
[
currentSong,
isPlaybackActive,
queueHistorySongIds,
queueSongIds,
playback.shuffleEnabled,
repeatEnabled,
]
)
const progressValue = useMemo<PlaybackProgressValue>(
() => ({ currentTime, duration }),
[currentTime, duration]
)
return (
<PlaybackActionsContext.Provider value={actionsValue}>
<PlaybackQueueContext.Provider value={queueValue}>
<PlaybackProgressContext.Provider value={progressValue}>
{children}
</PlaybackProgressContext.Provider>
</PlaybackQueueContext.Provider>
</PlaybackActionsContext.Provider>
)
}