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

1368 lines
40 KiB
TypeScript

import { dolbyAtmosSupported } from "@/lib/playback-capabilities"
import {
createAudioPlaylist,
setAudioModeAsync,
setIsAudioActiveAsync,
type AudioMetadata,
type AudioPlaylist,
type AudioPlaylistStatus,
type AudioSource,
} from "expo-audio"
import { useConvex, useMutation, useQuery } from "convex/react"
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type ReactNode,
} from "react"
import { AppState } from "react-native"
import {
ANONYMOUS_CACHE_SCOPE,
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 { 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 { getAuthCookieHeader } from "@/lib/auth-cookies"
import { flushPersistentCache } from "@/lib/persistent-cache"
import { loadPlaybackSongs } from "@/lib/playback-files"
import { rememberSongs, useSong, useSongs } from "@/lib/song-cache"
import { donateMusicPlay, type MusicEntityKind } from "@/lib/app-intents"
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 PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
const PROGRESS_SAVE_INTERVAL_MS = 5000
const PREFETCH_UPCOMING_SONGS = 5
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 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,
| "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"
>
const PlaybackContext = createContext<PlaybackContextValue | null>(null)
const PlaybackActionsContext = createContext<PlaybackActionsValue | null>(null)
const PlaybackQueueContext = createContext<PlaybackQueueValue | null>(null)
export function usePlayback() {
const context = useContext(PlaybackContext)
if (!context) {
throw new Error("usePlayback 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 { config } = useServerConfig()
const cacheScope = useCacheScope()
const isSignedIn = cacheScope !== ANONYMOUS_CACHE_SCOPE
const store = useMemo(
() => getPlaybackStore(isSignedIn ? cacheScope : null),
[cacheScope, isSignedIn]
)
const storeRef = useRef(store)
storeRef.current = store
const playback = useSyncExternalStore(store.subscribe, store.getSnapshot)
const user = useCachedQuery(api.auth.currentUser)
const serverPlayback = useQuery(
api.playback.getPlaybackState,
isSignedIn ? {} : "skip"
)
const syncPlaybackStateMutation = useMutation(api.playback.syncPlaybackState)
const recordPlayMutation = useMutation(api.playback.recordPlay)
const updateSongProgressMutation = useMutation(
api.playback.updateSongProgress
)
useEffect(() => {
if (!isSignedIn) return
store.setTransport((state) =>
syncPlaybackStateMutation({
songQueue: state.queue,
queueHistory: state.history,
shuffleEnabled: state.shuffleEnabled,
repeatEnabled: state.repeatEnabled,
currentSongProgress: state.progressSeconds,
})
)
return () => store.setTransport(null)
}, [store, isSignedIn, syncPlaybackStateMutation])
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 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 ignoreTrackChangeRef = useRef(false)
const autoPlayNextRef = useRef(false)
const isPlayingRef = useRef(false)
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
const lastSavedProgressRef = useRef(-1)
const prevIsPlayingRef = useRef(false)
const currentTimeRef = useRef(0)
const pendingSeekRef = useRef<number | null>(null)
const seekInFlightRef = useRef(false)
const loadRequestIdRef = useRef(0)
const queueOriginRef = useRef<string | undefined>(undefined)
const playRequestRef = useRef(0)
const ignoreTrackChangeTimerRef = useRef<ReturnType<
typeof setTimeout
> | null>(null)
const [queueStartVersion, setQueueStartVersion] = useState(0)
const [isPlaying, setIsPlayingState] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [measuredDuration, setDuration] = useState(0)
const [progressToRestore, setProgressToRestore] = useState<number | null>(
null
)
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 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 scheduleTrackChangeHandling = useCallback(() => {
if (ignoreTrackChangeTimerRef.current) {
clearTimeout(ignoreTrackChangeTimerRef.current)
}
ignoreTrackChangeTimerRef.current = setTimeout(() => {
ignoreTrackChangeTimerRef.current = null
ignoreTrackChangeRef.current = false
}, 150)
}, [])
const destroyPlaylist = useCallback(() => {
if (ignoreTrackChangeTimerRef.current) {
clearTimeout(ignoreTrackChangeTimerRef.current)
ignoreTrackChangeTimerRef.current = null
}
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
}, [])
// A new queue must not inherit the native player's position or a pending seek.
const resetQueuePlayback = useCallback(() => {
loadRequestIdRef.current += 1
destroyPlaylist()
pendingSeekRef.current = null
seekInFlightRef.current = false
progressRestoredForSongRef.current = null
lastSavedProgressRef.current = -1
currentTimeRef.current = 0
setCurrentTime(0)
setDuration(0)
setProgressToRestore(null)
setQueueStartVersion((version) => version + 1)
}, [destroyPlaylist])
const handlePlaylistStatusUpdate = useCallback(
(status: AudioPlaylistStatus) => {
if (!status.isLoaded) 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 = 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
})
}
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) {
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)
void playlistRef.current?.seekTo(0)
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()
}
},
[]
)
const handleTrackChanged = useCallback(
(data: { currentIndex: number; previousIndex: number }) => {
if (ignoreTrackChangeRef.current) return
// The window is history then queue, so the current track sits at
// `history.length`. Android's `previousIndex` goes stale when tracks
// are inserted or removed before it.
const steps =
data.currentIndex - storeRef.current.getState().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 ensurePlaylist = useCallback(
(sources: AudioSource[]) => {
if (playlistRef.current) {
return playlistRef.current
}
ignoreTrackChangeRef.current = true
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
scheduleTrackChangeHandling()
return playlist
},
[
handlePlaylistStatusUpdate,
handleTrackChanged,
scheduleTrackChangeHandling,
]
)
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) {
playlist.play()
} else {
playlist.pause()
}
}, [])
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 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 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(() => {
if (!currentSongId) {
progressRestoredForSongRef.current = null
destroyPlaylist()
return
}
if (progressRestoredForSongRef.current === currentSongId) return
progressRestoredForSongRef.current = currentSongId
lastSavedProgressRef.current = -1
pendingSeekRef.current = null
currentTimeRef.current = 0
setCurrentTime(0)
setDuration(0)
setProgressToRestore(store.getState().progressSeconds)
}, [currentSongId, destroyPlaylist, queueStartVersion, store])
useEffect(() => {
if (progressToRestore === null || progressToRestore <= 0) return
if (!currentSongId || !playlistRef.current) return
const maxDuration = duration > 0 ? duration : progressToRestore
const clamped = Math.min(progressToRestore, maxDuration)
pendingSeekRef.current = clamped
setProgressToRestore(null)
}, [progressToRestore, currentSongId, duration])
useEffect(() => {
if (!currentSongId) return
if (prevIsPlayingRef.current === isPlaying) return
prevIsPlayingRef.current = isPlaying
saveProgress(currentTimeRef.current)
}, [isPlaying, currentSongId, saveProgress])
useEffect(() => {
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") return
const restorePending = progressToRestore !== null && progressToRestore > 0
if (currentSongId && playlistRef.current && !restorePending) {
saveProgress(currentTimeRef.current)
}
flushPersistentCache()
})
return () => subscription.remove()
}, [currentSongId, progressToRestore, saveProgress])
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
ignoreTrackChangeRef.current = true
if (playlist.currentIndex !== currentIndex) {
playlist.skipTo(currentIndex)
}
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
if (metadata) {
updatePlaylistLockScreenMetadata(playlist, metadata)
}
scheduleTrackChangeHandling()
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
playlist.play()
}
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
}
ignoreTrackChangeRef.current = true
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)
scheduleTrackChangeHandling()
if (shouldPlay && !loadedPlaylist.playing) {
isPlayingRef.current = true
setIsPlayingState(true)
loadedPlaylist.play()
}
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
ignoreTrackChangeRef.current = true
destroyPlaylist()
if (!isCurrentLoad()) {
ignoreTrackChangeRef.current = false
return
}
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 }
)
scheduleTrackChangeHandling()
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
playlist.play()
} 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,
queueSyncKey,
queueStartVersion,
repeatEnabled,
scheduleTrackChangeHandling,
userPlaybackKey,
])
useEffect(() => {
if (!isPlaying || !currentSongId) return
const interval = setInterval(() => {
saveProgress(currentTimeRef.current)
}, PROGRESS_SAVE_INTERVAL_MS)
return () => clearInterval(interval)
}, [isPlaying, currentSongId, saveProgress])
const startPlayback = useCallback(
(
recipe: (
state: playbackQueue.PlaybackQueueState
) => playbackQueue.PlaybackQueueState,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
) => {
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 (async () => {
const deadline = Date.now() + 20_000
while (
Date.now() < deadline &&
store.getState().queue[0] === firstSongId
) {
const player = playlistRef.current
if (
player?.isLoaded &&
player.playing &&
loadedSongIdsRef.current[player.currentIndex] === firstSongId
) {
await donateMusicPlay(
recorded.entity?.kind ??
(recorded.playlistId ? "playlist" : "song"),
recorded.entity?.id ?? recorded.playlistId ?? firstSongId,
store.getState().shuffleEnabled
)
return
}
await new Promise((resolve) => setTimeout(resolve, 250))
}
})()
recordPlay(
recorded.playlistId
? { playlistId: recorded.playlistId }
: { songId: firstSongId }
)
},
[store, resetQueuePlayback, setIsPlaying, recordPlay]
)
const playCollection = useCallback(
async (
songIds: Id<"songs">[] | Promise<Id<"songs">[]>,
shuffled: boolean,
recorded: {
playlistId?: Id<"playlists">
origin?: string
entity?: { kind: MusicEntityKind; id: string }
} = {}
) => {
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 playInOrder = useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) return
startPlayback((state) => playbackQueue.startQueue(state, songIds, false))
},
[startPlayback]
)
const playShuffled = useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) return
startPlayback((state) => playbackQueue.startQueue(state, songIds, true))
},
[startPlayback]
)
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 loadAlbumSongIds = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
songIds ??
fetchCachedQuery(convex, cacheScope, api.playlists.getAlbumSongIds, {
albumId,
}),
[convex, cacheScope]
)
const loadArtistSongIds = useCallback(
(artistId: Id<"artists">) =>
fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId }
),
[convex, cacheScope]
)
const loadPlaylistSongIds = useCallback(
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
songIds ??
fetchCachedQuery(convex, cacheScope, api.playlists.getPlaylistSongIds, {
playlistId,
}),
[convex, cacheScope]
)
const playAlbum = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), false, {
entity: { kind: "album", id: albumId },
origin: `album:${albumId}`,
}),
[playCollection, loadAlbumSongIds]
)
const playAlbumShuffled = useCallback(
(albumId: Id<"albums">, songIds?: Id<"songs">[]) =>
playCollection(loadAlbumSongIds(albumId, songIds), true, {
entity: { kind: "album", id: albumId },
origin: `album:${albumId}`,
}),
[playCollection, loadAlbumSongIds]
)
const playArtist = useCallback(
(artistId: Id<"artists">) =>
playCollection(loadArtistSongIds(artistId), false, {
entity: { kind: "artist", id: artistId },
}),
[playCollection, loadArtistSongIds]
)
const playArtistShuffled = useCallback(
(artistId: Id<"artists">) =>
playCollection(loadArtistSongIds(artistId), true, {
entity: { kind: "artist", id: artistId },
}),
[playCollection, loadArtistSongIds]
)
const playPlaylist = useCallback(
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
playCollection(loadPlaylistSongIds(playlistId, songIds), false, {
playlistId,
}),
[playCollection, loadPlaylistSongIds]
)
const playPlaylistShuffled = useCallback(
(playlistId: Id<"playlists">, songIds?: Id<"songs">[]) =>
playCollection(loadPlaylistSongIds(playlistId, songIds), true, {
playlistId,
}),
[playCollection, loadPlaylistSongIds]
)
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
autoPlayNextRef.current = true
store.update((state) => playbackQueue.skipToQueueIndex(state, index))
},
[store]
)
const skipToHistoryIndex = useCallback(
async (index: number) => {
if (index < 0 || index >= store.getState().history.length) return
autoPlayNextRef.current = true
store.update((state) => playbackQueue.skipToHistoryIndex(state, index))
},
[store]
)
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
}
autoPlayNextRef.current = true
store.update(playbackQueue.skipNext)
}, [store, seekTo, setIsPlaying])
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
}
autoPlayNextRef.current = true
store.update(playbackQueue.skipPrevious)
}, [store, seekTo])
// 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.")
const deadline = Date.now() + 20_000
while (Date.now() < deadline) {
if (store.getState().queue[0] !== expectedId) {
throw new Error(
"The playback queue changed before the request finished."
)
}
const player = playlistRef.current
if (
player &&
loadedSongIdsRef.current[player.currentIndex] === expectedId &&
player.isLoaded &&
(playing === undefined || player.playing === playing)
)
return
await new Promise((resolve) => setTimeout(resolve, 100))
}
throw new Error(
"The audio did not become ready. Check your connection and try again."
)
},
[store]
)
const actionsValue = useMemo<PlaybackActionsValue>(
() => ({
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,
}),
[
addToQueueNext,
addToQueueLast,
clearHistory,
clearQueue,
clearUpNext,
cycleRepeat,
prepareQueue,
startFromSong,
setRepeatMode,
setShuffleEnabled,
playAlbum,
playAlbumShuffled,
playArtist,
playArtistShuffled,
playFromLibrarySong,
playFromSong,
playInOrder,
playPlaylist,
playPlaylistShuffled,
playShuffled,
reorderQueue,
setIsPlaying,
skipNext,
skipPrevious,
skipToHistoryIndex,
skipToQueueIndex,
toggleShuffle,
]
)
const isPlaybackActive = Boolean(currentSongId && isPlaying)
const queueValue = useMemo<PlaybackQueueValue>(
() => ({
queueSongIds,
queueHistorySongIds,
currentSong,
isPlaying: isPlaybackActive,
}),
[currentSong, isPlaybackActive, queueHistorySongIds, queueSongIds]
)
const value = useMemo<PlaybackContextValue>(
() => ({
...actionsValue,
waitForPlaybackReady,
queueSongIds,
queueHistorySongIds,
currentSong,
shuffleEnabled: playback.shuffleEnabled,
repeatEnabled,
isPlaying: isPlaybackActive,
currentTime,
duration,
seekTo,
}),
[
actionsValue,
waitForPlaybackReady,
currentSong,
currentTime,
duration,
isPlaybackActive,
playback.shuffleEnabled,
queueHistorySongIds,
queueSongIds,
repeatEnabled,
seekTo,
]
)
return (
<PlaybackActionsContext.Provider value={actionsValue}>
<PlaybackQueueContext.Provider value={queueValue}>
<PlaybackContext.Provider value={value}>
{children}
</PlaybackContext.Provider>
</PlaybackQueueContext.Provider>
</PlaybackActionsContext.Provider>
)
}