- Virtualize mobile lists and defer queue loading - Split playback state from actions to reduce rerenders - Skip invalid or unnecessary Convex queries Reviewed-on: #18
1243 lines
33 KiB
TypeScript
1243 lines
33 KiB
TypeScript
"use client"
|
|
|
|
import {
|
|
useState,
|
|
useEffect,
|
|
useCallback,
|
|
useRef,
|
|
RefObject,
|
|
createContext,
|
|
useContext,
|
|
ReactNode,
|
|
useSyncExternalStore,
|
|
useMemo,
|
|
} from "react"
|
|
import { useMutation, useQuery } from "convex/react"
|
|
import type Hls from "hls.js"
|
|
import { toast } from "sonner"
|
|
|
|
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 { useMediaSession } from "@/hooks/use-media-session"
|
|
import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support"
|
|
import { songHlsPlaylistUrl, songPlayUrl } from "@/lib/song-play-url"
|
|
|
|
type RepeatMode = "none" | "once" | "always"
|
|
|
|
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
|
|
|
|
type PlaybackContextValue = {
|
|
queueSongIds: Id<"songs">[]
|
|
queueHistorySongIds: Id<"songs">[]
|
|
currentSong: BrowseSong | null
|
|
shuffleEnabled: boolean
|
|
repeatEnabled: RepeatMode
|
|
queueOpen: boolean
|
|
isPlaying: boolean
|
|
volume: number
|
|
setQueueOpen: (open: boolean) => void
|
|
toggleQueueOpen: () => void
|
|
setIsPlaying: (playing: boolean) => void
|
|
setVolume: (volume: number) => 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">[]) => Promise<void>
|
|
playFromLibrarySong: (
|
|
songId: Id<"songs">,
|
|
sort: {
|
|
sortKey: "title" | "artist" | "album"
|
|
sortDirection: "asc" | "desc"
|
|
}
|
|
) => Promise<void>
|
|
playAlbum: (albumId: Id<"albums">) => Promise<void>
|
|
playAlbumShuffled: (albumId: Id<"albums">) => Promise<void>
|
|
playArtist: (artistId: Id<"artists">) => Promise<void>
|
|
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
|
|
playPlaylist: (playlistId: Id<"playlists">) => Promise<void>
|
|
playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise<void>
|
|
toggleShuffle: () => Promise<void>
|
|
cycleRepeat: () => Promise<void>
|
|
clearQueue: () => Promise<void>
|
|
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
|
|
skipToQueueIndex: (index: number) => Promise<void>
|
|
skipNext: () => Promise<void>
|
|
skipPrevious: () => Promise<void>
|
|
dolbyAtmosSupported: boolean | null
|
|
}
|
|
|
|
const PlaybackContext = createContext<PlaybackContextValue | null>(null)
|
|
const PlaybackProgressContext = createContext<{
|
|
currentTime: number
|
|
duration: number
|
|
seekTo: (seconds: number) => void
|
|
} | null>(null)
|
|
|
|
const VOLUME_STORAGE_KEY = "otunes:volume"
|
|
const DEFAULT_VOLUME = 80
|
|
|
|
const volumeListeners = new Set<() => void>()
|
|
let dolbyAtmosSnapshot: boolean | undefined
|
|
|
|
function subscribePlaybackCapabilities() {
|
|
return () => {}
|
|
}
|
|
|
|
function getDolbyAtmosSnapshot() {
|
|
dolbyAtmosSnapshot ??= supportsDolbyAtmosPlayback(new Audio())
|
|
return dolbyAtmosSnapshot
|
|
}
|
|
|
|
function subscribeVolume(listener: () => void) {
|
|
volumeListeners.add(listener)
|
|
const onStorage = (event: StorageEvent) => {
|
|
if (event.key === null || event.key === VOLUME_STORAGE_KEY) {
|
|
listener()
|
|
}
|
|
}
|
|
window.addEventListener("storage", onStorage)
|
|
return () => {
|
|
volumeListeners.delete(listener)
|
|
window.removeEventListener("storage", onStorage)
|
|
}
|
|
}
|
|
|
|
function notifyVolumeChange() {
|
|
for (const listener of volumeListeners) {
|
|
listener()
|
|
}
|
|
}
|
|
|
|
function readStoredVolume(): number {
|
|
try {
|
|
const stored = localStorage.getItem(VOLUME_STORAGE_KEY)
|
|
if (stored === null) {
|
|
return DEFAULT_VOLUME
|
|
}
|
|
|
|
const parsed = Number(stored)
|
|
if (!Number.isFinite(parsed)) {
|
|
return DEFAULT_VOLUME
|
|
}
|
|
|
|
return Math.min(100, Math.max(0, Math.round(parsed)))
|
|
} catch {
|
|
return DEFAULT_VOLUME
|
|
}
|
|
}
|
|
|
|
type PlaybackLoadSettings = {
|
|
preferAtmos: boolean
|
|
playbackQuality: "low" | "medium" | "high" | "lossless"
|
|
useHls: boolean
|
|
}
|
|
|
|
function playbackLoadSettings(
|
|
user: {
|
|
preferAtmos?: boolean
|
|
playbackQuality?: "low" | "medium" | "high" | "lossless"
|
|
},
|
|
dolbyAtmosSupported: boolean | null,
|
|
files: Record<string, unknown>
|
|
): PlaybackLoadSettings {
|
|
const preferAtmos =
|
|
dolbyAtmosSupported === true && (user.preferAtmos ?? false)
|
|
const plan = playbackStreamPlan(files, user.playbackQuality, preferAtmos)
|
|
return {
|
|
preferAtmos: plan.preferAtmos,
|
|
playbackQuality: plan.playbackQuality,
|
|
useHls: plan.useHls,
|
|
}
|
|
}
|
|
|
|
function songLoadKey(songId: string, settings: PlaybackLoadSettings) {
|
|
return `${songId}:${settings.preferAtmos}:${settings.playbackQuality}:${settings.useHls ? "hls" : "file"}`
|
|
}
|
|
|
|
function destroyHlsInstance(hlsRef: RefObject<Hls | null>) {
|
|
hlsRef.current?.destroy()
|
|
hlsRef.current = null
|
|
}
|
|
|
|
function adoptPreloadedPlayback(
|
|
mainAudio: HTMLAudioElement,
|
|
mainHlsRef: RefObject<Hls | null>,
|
|
preloadAudio: HTMLAudioElement,
|
|
preloadHlsRef: RefObject<Hls | null>
|
|
) {
|
|
const preloadHls = preloadHlsRef.current
|
|
if (preloadHls) {
|
|
preloadHls.detachMedia()
|
|
preloadHlsRef.current = null
|
|
mainHlsRef.current = preloadHls
|
|
preloadHls.attachMedia(mainAudio)
|
|
} else {
|
|
mainAudio.src = preloadAudio.src
|
|
}
|
|
|
|
preloadAudio.pause()
|
|
preloadAudio.removeAttribute("src")
|
|
}
|
|
|
|
type AudioSourceCleanup = () => void
|
|
|
|
function loadAudioSource(
|
|
audio: HTMLAudioElement,
|
|
hlsRef: RefObject<Hls | null>,
|
|
songId: string,
|
|
settings: PlaybackLoadSettings,
|
|
onReady: () => void
|
|
): AudioSourceCleanup {
|
|
let disposed = false
|
|
let hlsInstance: Hls | null = null
|
|
const directUrl = songPlayUrl(
|
|
songId,
|
|
settings.playbackQuality,
|
|
settings.preferAtmos
|
|
)
|
|
const hlsUrl = songHlsPlaylistUrl(
|
|
songId,
|
|
settings.playbackQuality,
|
|
settings.preferAtmos
|
|
)
|
|
|
|
const onReadyToPlay = () => {
|
|
audio.removeEventListener("loadedmetadata", onReadyToPlay)
|
|
audio.removeEventListener("loadeddata", onReadyToPlay)
|
|
audio.removeEventListener("canplay", onReadyToPlay)
|
|
onReady()
|
|
}
|
|
|
|
audio.addEventListener("loadedmetadata", onReadyToPlay)
|
|
audio.addEventListener("loadeddata", onReadyToPlay)
|
|
audio.addEventListener("canplay", onReadyToPlay)
|
|
|
|
const loadDirectSource = () => {
|
|
if (disposed) {
|
|
return
|
|
}
|
|
audio.src = directUrl
|
|
audio.load()
|
|
}
|
|
|
|
if (settings.useHls && audio.canPlayType("application/vnd.apple.mpegurl")) {
|
|
audio.src = hlsUrl
|
|
audio.load()
|
|
} else if (settings.useHls) {
|
|
void import("hls.js")
|
|
.then(({ default: HlsConstructor }) => {
|
|
if (disposed) {
|
|
return
|
|
}
|
|
if (!HlsConstructor.isSupported()) {
|
|
loadDirectSource()
|
|
return
|
|
}
|
|
const hls = new HlsConstructor()
|
|
hlsInstance = hls
|
|
hlsRef.current = hls
|
|
hls.on(HlsConstructor.Events.MANIFEST_PARSED, onReady)
|
|
hls.loadSource(hlsUrl)
|
|
hls.attachMedia(audio)
|
|
})
|
|
.catch(loadDirectSource)
|
|
} else {
|
|
loadDirectSource()
|
|
}
|
|
|
|
return () => {
|
|
disposed = true
|
|
audio.removeEventListener("loadedmetadata", onReadyToPlay)
|
|
audio.removeEventListener("loadeddata", onReadyToPlay)
|
|
audio.removeEventListener("canplay", onReadyToPlay)
|
|
if (hlsInstance && hlsRef.current === hlsInstance) {
|
|
hlsInstance.destroy()
|
|
hlsRef.current = null
|
|
}
|
|
}
|
|
}
|
|
|
|
export function usePlayback() {
|
|
const context = useContext(PlaybackContext)
|
|
if (!context) {
|
|
throw new Error("usePlayback must be used within PlaybackProvider")
|
|
}
|
|
return context
|
|
}
|
|
|
|
export function usePlaybackProgress() {
|
|
const context = useContext(PlaybackProgressContext)
|
|
if (!context) {
|
|
throw new Error(
|
|
"usePlaybackProgress must be used within PlaybackProvider"
|
|
)
|
|
}
|
|
return context
|
|
}
|
|
|
|
export function PlaybackProvider({ children }: { children: ReactNode }) {
|
|
const user = useQuery(api.auth.currentUser)
|
|
const playback = useQuery(api.playback.getPlaybackState)
|
|
const audioRef = useRef<HTMLAudioElement | null>(null)
|
|
const hlsRef = useRef<Hls | null>(null)
|
|
const preloadAudioRef = useRef<HTMLAudioElement | null>(null)
|
|
const preloadHlsRef = useRef<Hls | null>(null)
|
|
const loadedSongKeyRef = useRef<string | null>(null)
|
|
const preloadedSongKeyRef = useRef<string | null>(null)
|
|
const playbackErrorHandledRef = useRef(false)
|
|
const isPlayingRef = useRef(false)
|
|
const autoPlayNextRef = useRef(false)
|
|
const intentionalLoadRef = useRef(false)
|
|
const ignoreAudioSyncRef = useRef(false)
|
|
const playInOrderMutation = useMutation(api.playback.playInOrder)
|
|
const playShuffledMutation = useMutation(api.playback.playShuffled)
|
|
const addToQueueNextMutation = useMutation(api.playback.addToQueueNext)
|
|
const addToQueueLastMutation = useMutation(api.playback.addToQueueLast)
|
|
const playFromSongMutation = useMutation(api.playback.playFromSong)
|
|
const playFromLibrarySongMutation = useMutation(
|
|
api.playback.playFromLibrarySong
|
|
)
|
|
const playAlbumMutation = useMutation(api.playback.playAlbum)
|
|
const playAlbumShuffledMutation = useMutation(api.playback.playAlbumShuffled)
|
|
const playArtistMutation = useMutation(api.playback.playArtist)
|
|
const playArtistShuffledMutation = useMutation(
|
|
api.playback.playArtistShuffled
|
|
)
|
|
const playPlaylistMutation = useMutation(api.playback.playPlaylist)
|
|
const playPlaylistShuffledMutation = useMutation(
|
|
api.playback.playPlaylistShuffled
|
|
)
|
|
const toggleShuffleMutation = useMutation(
|
|
api.playback.toggleShuffle
|
|
).withOptimisticUpdate((store) => {
|
|
const current = store.getQuery(api.playback.getPlaybackState, {})
|
|
if (!current) return
|
|
store.setQuery(api.playback.getPlaybackState, {}, {
|
|
...current,
|
|
shuffleEnabled: !current.shuffleEnabled,
|
|
})
|
|
})
|
|
const cycleRepeatMutation = useMutation(
|
|
api.playback.cycleRepeat
|
|
).withOptimisticUpdate((store) => {
|
|
const current = store.getQuery(api.playback.getPlaybackState, {})
|
|
if (!current) return
|
|
const next =
|
|
current.repeatEnabled === "none"
|
|
? "once"
|
|
: current.repeatEnabled === "once"
|
|
? "always"
|
|
: "none"
|
|
store.setQuery(api.playback.getPlaybackState, {}, {
|
|
...current,
|
|
repeatEnabled: next,
|
|
})
|
|
})
|
|
const clearQueueMutation = useMutation(api.playback.clearQueue)
|
|
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
|
|
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
|
|
const skipNextMutation = useMutation(api.playback.skipNext)
|
|
const skipPreviousMutation = useMutation(api.playback.skipPrevious)
|
|
const updateSongProgressMutation = useMutation(api.playback.updateSongProgress)
|
|
|
|
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
|
|
const lastSavedProgressRef = useRef(-1)
|
|
const prevIsPlayingRef = useRef(false)
|
|
const currentTimeRef = useRef(0)
|
|
const durationRef = useRef(0)
|
|
|
|
const [queueOpen, setQueueOpen] = useState(false)
|
|
const [isPlaying, setIsPlaying] = useState(false)
|
|
const [currentTime, setCurrentTime] = useState(0)
|
|
const [measuredDuration, setMeasuredDuration] = useState<{
|
|
songId: string
|
|
seconds: number
|
|
} | null>(null)
|
|
const [progressToRestore, setProgressToRestore] = useState<number | null>(
|
|
null
|
|
)
|
|
const dolbyAtmosSupported = useSyncExternalStore(
|
|
subscribePlaybackCapabilities,
|
|
getDolbyAtmosSnapshot,
|
|
() => null
|
|
)
|
|
const volume = useSyncExternalStore(
|
|
subscribeVolume,
|
|
readStoredVolume,
|
|
() => DEFAULT_VOLUME
|
|
)
|
|
|
|
const setVolume = useCallback((nextVolume: number) => {
|
|
const clamped = Math.min(100, Math.max(0, Math.round(nextVolume)))
|
|
|
|
try {
|
|
localStorage.setItem(VOLUME_STORAGE_KEY, String(clamped))
|
|
notifyVolumeChange()
|
|
} catch {
|
|
// Ignore storage failures (private browsing, quota, etc.)
|
|
}
|
|
}, [])
|
|
|
|
const currentSong = playback?.currentSong ?? null
|
|
const currentSongId = currentSong?.id ?? null
|
|
const playbackQuality = user?.playbackQuality
|
|
const preferAtmos = user?.preferAtmos
|
|
const duration =
|
|
currentSong && measuredDuration?.songId === currentSong.id
|
|
? measuredDuration.seconds
|
|
: (currentSong?.durationSeconds ?? 0)
|
|
|
|
useEffect(() => {
|
|
durationRef.current = duration
|
|
}, [duration])
|
|
const currentSongDoc = useQuery(
|
|
api.library.getSongPlaybackInfo,
|
|
currentSong ? { id: currentSong.id } : "skip"
|
|
)
|
|
const isPlaybackActive = Boolean(currentSong && isPlaying)
|
|
const repeatEnabled = playback?.repeatEnabled ?? "none"
|
|
const queueLength = playback?.queueSongIds.length ?? 0
|
|
const queueSongIds = playback?.queueSongIds ?? []
|
|
const nextQueueSongId =
|
|
queueSongIds.length > 1 ? queueSongIds[1] : null
|
|
const nextQueueSongDoc = useQuery(
|
|
api.library.getSongPlaybackInfo,
|
|
nextQueueSongId ? { id: nextQueueSongId } : "skip"
|
|
)
|
|
|
|
const seekTo = useCallback(
|
|
(seconds: number) => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
const maxDuration =
|
|
Number.isFinite(audio.duration) && audio.duration > 0
|
|
? audio.duration
|
|
: durationRef.current
|
|
const clamped = Math.max(0, Math.min(seconds, maxDuration || 0))
|
|
audio.currentTime = clamped
|
|
currentTimeRef.current = clamped
|
|
setCurrentTime(clamped)
|
|
},
|
|
[]
|
|
)
|
|
|
|
const saveProgress = useCallback(
|
|
(seconds: number) => {
|
|
if (!currentSongId) {
|
|
return
|
|
}
|
|
|
|
const progressSeconds = Math.max(0, Math.floor(seconds))
|
|
if (progressSeconds === lastSavedProgressRef.current) {
|
|
return
|
|
}
|
|
|
|
lastSavedProgressRef.current = progressSeconds
|
|
void updateSongProgressMutation({
|
|
songId: currentSongId,
|
|
progressSeconds,
|
|
})
|
|
},
|
|
[currentSongId, updateSongProgressMutation]
|
|
)
|
|
|
|
useEffect(() => {
|
|
if (!currentSongId || !playback) {
|
|
return
|
|
}
|
|
|
|
if (progressRestoredForSongRef.current === currentSongId) {
|
|
return
|
|
}
|
|
|
|
progressRestoredForSongRef.current = currentSongId
|
|
lastSavedProgressRef.current = -1
|
|
setProgressToRestore(playback.currentSongProgress ?? 0)
|
|
}, [currentSongId, playback])
|
|
|
|
useEffect(() => {
|
|
if (progressToRestore === null || progressToRestore <= 0) {
|
|
return
|
|
}
|
|
|
|
const audio = audioRef.current
|
|
if (!audio || !currentSongId) {
|
|
return
|
|
}
|
|
|
|
const applyProgress = () => {
|
|
const maxDuration =
|
|
Number.isFinite(audio.duration) && audio.duration > 0
|
|
? audio.duration
|
|
: progressToRestore
|
|
const clamped = Math.min(progressToRestore, maxDuration)
|
|
audio.currentTime = clamped
|
|
currentTimeRef.current = clamped
|
|
setCurrentTime(clamped)
|
|
setProgressToRestore(null)
|
|
}
|
|
|
|
if (audio.readyState >= HTMLMediaElement.HAVE_METADATA) {
|
|
applyProgress()
|
|
return
|
|
}
|
|
|
|
audio.addEventListener("loadedmetadata", applyProgress, { once: true })
|
|
return () => {
|
|
audio.removeEventListener("loadedmetadata", applyProgress)
|
|
}
|
|
}, [progressToRestore, currentSongId])
|
|
|
|
useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio || !currentSongId) {
|
|
return
|
|
}
|
|
|
|
if (prevIsPlayingRef.current === isPlaying) {
|
|
return
|
|
}
|
|
|
|
prevIsPlayingRef.current = isPlaying
|
|
saveProgress(audio.currentTime)
|
|
}, [isPlaying, currentSongId, saveProgress])
|
|
|
|
useEffect(() => {
|
|
if (!isPlaying || !currentSongId) {
|
|
return
|
|
}
|
|
|
|
const interval = window.setInterval(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
saveProgress(audio.currentTime)
|
|
}, 5000)
|
|
|
|
return () => {
|
|
window.clearInterval(interval)
|
|
}
|
|
}, [isPlaying, currentSongId, saveProgress])
|
|
|
|
useEffect(() => {
|
|
isPlayingRef.current = isPlaying
|
|
}, [isPlaying])
|
|
|
|
const runWithoutAudioSync = useCallback((fn: () => void) => {
|
|
ignoreAudioSyncRef.current = true
|
|
try {
|
|
fn()
|
|
} finally {
|
|
ignoreAudioSyncRef.current = false
|
|
}
|
|
}, [])
|
|
|
|
const destroyHls = useCallback(() => {
|
|
destroyHlsInstance(hlsRef)
|
|
}, [])
|
|
|
|
const destroyPreloadHls = useCallback(() => {
|
|
destroyHlsInstance(preloadHlsRef)
|
|
}, [])
|
|
|
|
const clearPreload = useCallback(() => {
|
|
const preloadAudio = preloadAudioRef.current
|
|
destroyPreloadHls()
|
|
preloadedSongKeyRef.current = null
|
|
if (preloadAudio) {
|
|
preloadAudio.pause()
|
|
preloadAudio.removeAttribute("src")
|
|
}
|
|
}, [destroyPreloadHls])
|
|
|
|
useEffect(() => {
|
|
const audio = new Audio()
|
|
const preloadAudio = new Audio()
|
|
preloadAudio.preload = "auto"
|
|
audioRef.current = audio
|
|
preloadAudioRef.current = preloadAudio
|
|
|
|
const syncPlayingFromAudio = () => {
|
|
if (ignoreAudioSyncRef.current) {
|
|
return
|
|
}
|
|
if (autoPlayNextRef.current && audio.paused) {
|
|
return
|
|
}
|
|
setIsPlaying(!audio.paused)
|
|
}
|
|
|
|
audio.addEventListener("play", syncPlayingFromAudio)
|
|
audio.addEventListener("pause", syncPlayingFromAudio)
|
|
|
|
return () => {
|
|
audio.removeEventListener("play", syncPlayingFromAudio)
|
|
audio.removeEventListener("pause", syncPlayingFromAudio)
|
|
destroyHls()
|
|
destroyPreloadHls()
|
|
audio.pause()
|
|
audio.removeAttribute("src")
|
|
preloadAudio.pause()
|
|
preloadAudio.removeAttribute("src")
|
|
audioRef.current = null
|
|
preloadAudioRef.current = null
|
|
loadedSongKeyRef.current = null
|
|
preloadedSongKeyRef.current = null
|
|
}
|
|
}, [destroyHls, destroyPreloadHls])
|
|
|
|
useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
audio.volume = volume / 100
|
|
}, [volume])
|
|
|
|
const attemptPlayback = useCallback(
|
|
(
|
|
audio: HTMLAudioElement,
|
|
expectedLoadKey: string,
|
|
playState: { playPending: boolean; playSucceeded: boolean }
|
|
) => {
|
|
if (
|
|
!(isPlayingRef.current || autoPlayNextRef.current) ||
|
|
playState.playPending ||
|
|
playState.playSucceeded
|
|
) {
|
|
return
|
|
}
|
|
|
|
playState.playPending = true
|
|
void audio
|
|
.play()
|
|
.then(() => {
|
|
playState.playPending = false
|
|
playState.playSucceeded = true
|
|
intentionalLoadRef.current = false
|
|
autoPlayNextRef.current = false
|
|
isPlayingRef.current = true
|
|
setIsPlaying(true)
|
|
})
|
|
.catch((error: unknown) => {
|
|
playState.playPending = false
|
|
if (loadedSongKeyRef.current !== expectedLoadKey) {
|
|
return
|
|
}
|
|
if (error instanceof DOMException && error.name === "AbortError") {
|
|
return
|
|
}
|
|
intentionalLoadRef.current = false
|
|
autoPlayNextRef.current = false
|
|
isPlayingRef.current = false
|
|
setIsPlaying(false)
|
|
})
|
|
},
|
|
[]
|
|
)
|
|
|
|
useEffect(() => {
|
|
const audio = audioRef.current
|
|
const preloadAudio = preloadAudioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
if (!currentSongId) {
|
|
autoPlayNextRef.current = false
|
|
intentionalLoadRef.current = false
|
|
destroyHls()
|
|
clearPreload()
|
|
audio.pause()
|
|
audio.removeAttribute("src")
|
|
loadedSongKeyRef.current = null
|
|
return
|
|
}
|
|
|
|
if (!user || !currentSongDoc) {
|
|
return
|
|
}
|
|
|
|
const settings = playbackLoadSettings(
|
|
{ playbackQuality, preferAtmos },
|
|
dolbyAtmosSupported,
|
|
currentSongDoc.files
|
|
)
|
|
const loadKey = songLoadKey(currentSongId, settings)
|
|
|
|
if (loadedSongKeyRef.current === loadKey) {
|
|
return
|
|
}
|
|
|
|
playbackErrorHandledRef.current = false
|
|
intentionalLoadRef.current = true
|
|
runWithoutAudioSync(() => {
|
|
audio.pause()
|
|
})
|
|
|
|
const playState = { playPending: false, playSucceeded: false }
|
|
const requestPlay = () => {
|
|
if (!(isPlayingRef.current || autoPlayNextRef.current)) {
|
|
intentionalLoadRef.current = false
|
|
return
|
|
}
|
|
attemptPlayback(audio, loadKey, playState)
|
|
}
|
|
|
|
if (
|
|
preloadAudio &&
|
|
preloadedSongKeyRef.current === loadKey &&
|
|
(preloadHlsRef.current !== null || preloadAudio.src !== "")
|
|
) {
|
|
destroyHls()
|
|
adoptPreloadedPlayback(audio, hlsRef, preloadAudio, preloadHlsRef)
|
|
loadedSongKeyRef.current = loadKey
|
|
preloadedSongKeyRef.current = null
|
|
requestPlay()
|
|
return () => {
|
|
intentionalLoadRef.current = false
|
|
}
|
|
}
|
|
|
|
destroyHls()
|
|
loadedSongKeyRef.current = loadKey
|
|
|
|
const cleanupSource = loadAudioSource(
|
|
audio,
|
|
hlsRef,
|
|
currentSongId,
|
|
settings,
|
|
requestPlay
|
|
)
|
|
|
|
return () => {
|
|
intentionalLoadRef.current = false
|
|
cleanupSource()
|
|
}
|
|
}, [
|
|
currentSongId,
|
|
currentSongDoc,
|
|
user,
|
|
playbackQuality,
|
|
preferAtmos,
|
|
dolbyAtmosSupported,
|
|
runWithoutAudioSync,
|
|
destroyHls,
|
|
clearPreload,
|
|
attemptPlayback,
|
|
])
|
|
|
|
useEffect(() => {
|
|
const preloadAudio = preloadAudioRef.current
|
|
if (!preloadAudio || !nextQueueSongId || !currentSongId) {
|
|
clearPreload()
|
|
return
|
|
}
|
|
|
|
if (!user || !nextQueueSongDoc) {
|
|
return
|
|
}
|
|
|
|
const settings = playbackLoadSettings(
|
|
{ playbackQuality, preferAtmos },
|
|
dolbyAtmosSupported,
|
|
nextQueueSongDoc.files
|
|
)
|
|
const loadKey = songLoadKey(nextQueueSongId, settings)
|
|
|
|
if (preloadedSongKeyRef.current === loadKey) {
|
|
return
|
|
}
|
|
|
|
clearPreload()
|
|
|
|
const onPreloadReady = () => {
|
|
if (preloadedSongKeyRef.current !== null) {
|
|
return
|
|
}
|
|
preloadedSongKeyRef.current = loadKey
|
|
}
|
|
|
|
const cleanupSource = loadAudioSource(
|
|
preloadAudio,
|
|
preloadHlsRef,
|
|
nextQueueSongId,
|
|
settings,
|
|
onPreloadReady
|
|
)
|
|
|
|
return () => {
|
|
cleanupSource()
|
|
if (preloadedSongKeyRef.current === loadKey) {
|
|
preloadedSongKeyRef.current = null
|
|
}
|
|
destroyPreloadHls()
|
|
preloadAudio.pause()
|
|
preloadAudio.removeAttribute("src")
|
|
}
|
|
}, [
|
|
currentSongId,
|
|
nextQueueSongId,
|
|
nextQueueSongDoc,
|
|
user,
|
|
playbackQuality,
|
|
preferAtmos,
|
|
dolbyAtmosSupported,
|
|
clearPreload,
|
|
destroyPreloadHls,
|
|
])
|
|
|
|
useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio || !currentSong) {
|
|
return
|
|
}
|
|
|
|
if (!isPlaying && !autoPlayNextRef.current) {
|
|
audio.pause()
|
|
return
|
|
}
|
|
|
|
const expectedLoadKey = loadedSongKeyRef.current
|
|
if (!expectedLoadKey) {
|
|
return
|
|
}
|
|
|
|
const playState = { playPending: false, playSucceeded: false }
|
|
|
|
if (audio.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) {
|
|
attemptPlayback(audio, expectedLoadKey, playState)
|
|
return
|
|
}
|
|
|
|
const onCanPlay = () => {
|
|
audio.removeEventListener("canplay", onCanPlay)
|
|
attemptPlayback(audio, expectedLoadKey, playState)
|
|
}
|
|
|
|
audio.addEventListener("canplay", onCanPlay)
|
|
return () => {
|
|
audio.removeEventListener("canplay", onCanPlay)
|
|
}
|
|
}, [isPlaying, currentSong, attemptPlayback])
|
|
|
|
useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
const handleEnded = () => {
|
|
if (repeatEnabled === "once") {
|
|
audio.currentTime = 0
|
|
void audio.play()
|
|
return
|
|
}
|
|
|
|
const shouldContinuePlaying = repeatEnabled !== "none" || queueLength > 1
|
|
|
|
if (shouldContinuePlaying) {
|
|
autoPlayNextRef.current = true
|
|
isPlayingRef.current = true
|
|
setIsPlaying(true)
|
|
}
|
|
|
|
const preloadAudio = preloadAudioRef.current
|
|
if (shouldContinuePlaying && preloadAudio && nextQueueSongId && user && nextQueueSongDoc) {
|
|
const settings = playbackLoadSettings(
|
|
user,
|
|
dolbyAtmosSupported,
|
|
nextQueueSongDoc.files
|
|
)
|
|
const nextLoadKey = songLoadKey(nextQueueSongId, settings)
|
|
|
|
if (
|
|
preloadedSongKeyRef.current === nextLoadKey &&
|
|
(preloadHlsRef.current !== null || preloadAudio.src !== "")
|
|
) {
|
|
intentionalLoadRef.current = true
|
|
runWithoutAudioSync(() => {
|
|
audio.pause()
|
|
})
|
|
destroyHls()
|
|
adoptPreloadedPlayback(audio, hlsRef, preloadAudio, preloadHlsRef)
|
|
loadedSongKeyRef.current = nextLoadKey
|
|
preloadedSongKeyRef.current = null
|
|
|
|
const playState = { playPending: false, playSucceeded: false }
|
|
if (audio.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) {
|
|
attemptPlayback(audio, nextLoadKey, playState)
|
|
} else {
|
|
const onCanPlay = () => {
|
|
audio.removeEventListener("canplay", onCanPlay)
|
|
attemptPlayback(audio, nextLoadKey, playState)
|
|
}
|
|
audio.addEventListener("canplay", onCanPlay)
|
|
}
|
|
}
|
|
}
|
|
|
|
void skipNextMutation()
|
|
.then(() => {
|
|
if (shouldContinuePlaying) {
|
|
autoPlayNextRef.current = true
|
|
isPlayingRef.current = true
|
|
setIsPlaying(true)
|
|
return
|
|
}
|
|
|
|
autoPlayNextRef.current = false
|
|
isPlayingRef.current = false
|
|
audio.currentTime = 0
|
|
currentTimeRef.current = 0
|
|
setCurrentTime(0)
|
|
setIsPlaying(false)
|
|
})
|
|
.catch(() => {
|
|
autoPlayNextRef.current = false
|
|
isPlayingRef.current = false
|
|
setIsPlaying(false)
|
|
})
|
|
}
|
|
|
|
const handleError = () => {
|
|
if (intentionalLoadRef.current) {
|
|
return
|
|
}
|
|
if (!currentSong || playbackErrorHandledRef.current) {
|
|
return
|
|
}
|
|
playbackErrorHandledRef.current = true
|
|
|
|
const { error } = audio
|
|
if (error) {
|
|
console.error("Audio playback error:", {
|
|
code: error.code,
|
|
message: error.message,
|
|
src: audio.src,
|
|
})
|
|
}
|
|
|
|
audio.pause()
|
|
autoPlayNextRef.current = false
|
|
destroyHls()
|
|
audio.removeAttribute("src")
|
|
loadedSongKeyRef.current = null
|
|
setIsPlaying(false)
|
|
|
|
toast.error("Playback error", {
|
|
description: "Could not play this track. The queue has been cleared.",
|
|
})
|
|
void clearQueueMutation()
|
|
}
|
|
|
|
audio.addEventListener("ended", handleEnded)
|
|
audio.addEventListener("error", handleError)
|
|
|
|
return () => {
|
|
audio.removeEventListener("ended", handleEnded)
|
|
audio.removeEventListener("error", handleError)
|
|
}
|
|
}, [
|
|
repeatEnabled,
|
|
currentSong,
|
|
queueLength,
|
|
nextQueueSongId,
|
|
nextQueueSongDoc,
|
|
user,
|
|
dolbyAtmosSupported,
|
|
skipNextMutation,
|
|
clearQueueMutation,
|
|
destroyHls,
|
|
runWithoutAudioSync,
|
|
attemptPlayback,
|
|
])
|
|
|
|
useEffect(() => {
|
|
const audio = audioRef.current
|
|
if (!audio) {
|
|
return
|
|
}
|
|
|
|
const syncDuration = () => {
|
|
if (Number.isFinite(audio.duration) && audio.duration > 0) {
|
|
if (currentSong) {
|
|
setMeasuredDuration({
|
|
songId: currentSong.id,
|
|
seconds: audio.duration,
|
|
})
|
|
}
|
|
} else if (currentSong) {
|
|
setMeasuredDuration({
|
|
songId: currentSong.id,
|
|
seconds: currentSong.durationSeconds,
|
|
})
|
|
}
|
|
}
|
|
|
|
const syncTime = () => {
|
|
currentTimeRef.current = audio.currentTime
|
|
setCurrentTime(audio.currentTime)
|
|
}
|
|
|
|
audio.addEventListener("timeupdate", syncTime)
|
|
audio.addEventListener("durationchange", syncDuration)
|
|
audio.addEventListener("loadedmetadata", syncDuration)
|
|
audio.addEventListener("seeked", syncTime)
|
|
|
|
return () => {
|
|
audio.removeEventListener("timeupdate", syncTime)
|
|
audio.removeEventListener("durationchange", syncDuration)
|
|
audio.removeEventListener("loadedmetadata", syncDuration)
|
|
audio.removeEventListener("seeked", syncTime)
|
|
}
|
|
}, [currentSong])
|
|
|
|
const playInOrder = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await playInOrderMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playInOrderMutation]
|
|
)
|
|
|
|
const playShuffled = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await playShuffledMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playShuffledMutation]
|
|
)
|
|
|
|
const addToQueueNext = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await addToQueueNextMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[addToQueueNextMutation]
|
|
)
|
|
|
|
const addToQueueLast = useCallback(
|
|
async (songIds: Id<"songs">[]) => {
|
|
if (songIds.length === 0) {
|
|
return
|
|
}
|
|
await addToQueueLastMutation({ songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[addToQueueLastMutation]
|
|
)
|
|
|
|
const playFromSong = useCallback(
|
|
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
|
|
await playFromSongMutation({ songId, songIds })
|
|
setIsPlaying(true)
|
|
},
|
|
[playFromSongMutation]
|
|
)
|
|
|
|
const playFromLibrarySong = useCallback(
|
|
async (
|
|
songId: Id<"songs">,
|
|
sort: {
|
|
sortKey: "title" | "artist" | "album"
|
|
sortDirection: "asc" | "desc"
|
|
}
|
|
) => {
|
|
await playFromLibrarySongMutation({ songId, ...sort })
|
|
setIsPlaying(true)
|
|
},
|
|
[playFromLibrarySongMutation]
|
|
)
|
|
|
|
const playAlbum = useCallback(
|
|
async (albumId: Id<"albums">) => {
|
|
await playAlbumMutation({ albumId })
|
|
setIsPlaying(true)
|
|
},
|
|
[playAlbumMutation]
|
|
)
|
|
|
|
const playAlbumShuffled = useCallback(
|
|
async (albumId: Id<"albums">) => {
|
|
await playAlbumShuffledMutation({ albumId })
|
|
setIsPlaying(true)
|
|
},
|
|
[playAlbumShuffledMutation]
|
|
)
|
|
|
|
const playArtist = useCallback(
|
|
async (artistId: Id<"artists">) => {
|
|
await playArtistMutation({ artistId })
|
|
setIsPlaying(true)
|
|
},
|
|
[playArtistMutation]
|
|
)
|
|
|
|
const playArtistShuffled = useCallback(
|
|
async (artistId: Id<"artists">) => {
|
|
await playArtistShuffledMutation({ artistId })
|
|
setIsPlaying(true)
|
|
},
|
|
[playArtistShuffledMutation]
|
|
)
|
|
|
|
const playPlaylist = useCallback(
|
|
async (playlistId: Id<"playlists">) => {
|
|
await playPlaylistMutation({ playlistId })
|
|
setIsPlaying(true)
|
|
},
|
|
[playPlaylistMutation]
|
|
)
|
|
|
|
const playPlaylistShuffled = useCallback(
|
|
async (playlistId: Id<"playlists">) => {
|
|
await playPlaylistShuffledMutation({ playlistId })
|
|
setIsPlaying(true)
|
|
},
|
|
[playPlaylistShuffledMutation]
|
|
)
|
|
|
|
const toggleQueueOpen = useCallback(() => {
|
|
setQueueOpen((open) => !open)
|
|
}, [])
|
|
|
|
const skipNext = useCallback(async () => {
|
|
const isFinishingQueue =
|
|
repeatEnabled === "none" && queueSongIds.length <= 1
|
|
if (isFinishingQueue) {
|
|
setIsPlaying(false)
|
|
seekTo(0)
|
|
}
|
|
await skipNextMutation()
|
|
if (isFinishingQueue) {
|
|
seekTo(0)
|
|
}
|
|
}, [repeatEnabled, queueSongIds.length, seekTo, skipNextMutation])
|
|
|
|
const skipPrevious = useCallback(async () => {
|
|
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
|
|
seekTo(0)
|
|
return
|
|
}
|
|
await skipPreviousMutation()
|
|
}, [seekTo, skipPreviousMutation])
|
|
|
|
useMediaSession({
|
|
song: currentSong,
|
|
isPlaying: isPlaybackActive,
|
|
duration,
|
|
currentTime,
|
|
seekTo,
|
|
setIsPlaying,
|
|
skipNext,
|
|
skipPrevious,
|
|
})
|
|
|
|
const value = useMemo<PlaybackContextValue>(
|
|
() => ({
|
|
queueSongIds: playback?.queueSongIds ?? [],
|
|
queueHistorySongIds: playback?.queueHistorySongIds ?? [],
|
|
currentSong: playback?.currentSong ?? null,
|
|
shuffleEnabled: playback?.shuffleEnabled ?? false,
|
|
repeatEnabled: playback?.repeatEnabled ?? "none",
|
|
queueOpen,
|
|
isPlaying: isPlaybackActive,
|
|
volume,
|
|
setQueueOpen,
|
|
toggleQueueOpen,
|
|
setIsPlaying,
|
|
setVolume,
|
|
playInOrder,
|
|
playShuffled,
|
|
addToQueueNext,
|
|
addToQueueLast,
|
|
playFromSong,
|
|
playFromLibrarySong,
|
|
playAlbum,
|
|
playAlbumShuffled,
|
|
playArtist,
|
|
playArtistShuffled,
|
|
playPlaylist,
|
|
playPlaylistShuffled,
|
|
toggleShuffle: async () => {
|
|
await toggleShuffleMutation()
|
|
},
|
|
cycleRepeat: async () => {
|
|
await cycleRepeatMutation()
|
|
},
|
|
clearQueue: async () => {
|
|
await clearQueueMutation()
|
|
setIsPlaying(false)
|
|
},
|
|
reorderQueue: async (songIds) => {
|
|
await reorderQueueMutation({ songIds })
|
|
},
|
|
skipToQueueIndex: async (index) => {
|
|
await skipToQueueIndexMutation({ index })
|
|
},
|
|
skipNext,
|
|
skipPrevious,
|
|
dolbyAtmosSupported,
|
|
}),
|
|
[
|
|
playback,
|
|
queueOpen,
|
|
isPlaybackActive,
|
|
volume,
|
|
toggleQueueOpen,
|
|
setVolume,
|
|
playInOrder,
|
|
playShuffled,
|
|
addToQueueNext,
|
|
addToQueueLast,
|
|
playFromSong,
|
|
playFromLibrarySong,
|
|
playAlbum,
|
|
playAlbumShuffled,
|
|
playArtist,
|
|
playArtistShuffled,
|
|
playPlaylist,
|
|
playPlaylistShuffled,
|
|
toggleShuffleMutation,
|
|
cycleRepeatMutation,
|
|
clearQueueMutation,
|
|
reorderQueueMutation,
|
|
skipToQueueIndexMutation,
|
|
skipNext,
|
|
skipPrevious,
|
|
dolbyAtmosSupported,
|
|
]
|
|
)
|
|
|
|
const progressValue = useMemo(
|
|
() => ({ currentTime, duration, seekTo }),
|
|
[currentTime, duration, seekTo]
|
|
)
|
|
|
|
return (
|
|
<PlaybackContext.Provider value={value}>
|
|
<PlaybackProgressContext.Provider value={progressValue}>
|
|
{children}
|
|
</PlaybackProgressContext.Provider>
|
|
</PlaybackContext.Provider>
|
|
)
|
|
}
|