Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert [C-3561] Improve playback delay when playing track on mobile #7616

Merged
merged 1 commit into from
Feb 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 65 additions & 85 deletions packages/mobile/src/components/audio/AudioPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { useRef, useEffect, useCallback, useState } from 'react'

import { useAppContext } from '@audius/common/context'
import { SquareSizes } from '@audius/common/models'
import type { Track } from '@audius/common/models'
import type { ID, Track } from '@audius/common/models'
import { FeatureFlags } from '@audius/common/services'
import type { QueryParams } from '@audius/common/services'
import {
accountSelectors,
cacheTracksSelectors,
Expand Down Expand Up @@ -289,6 +290,38 @@ export const AudioPlayer = () => {
}
}, [reset])

// Map of user signature for gated tracks
const [gatedQueryParamsMap, setGatedQueryParamsMap] = useState<{
[trackId: ID]: QueryParams
}>({})

const handleGatedQueryParams = useCallback(
async (tracks: QueueableTrack[]) => {
const queryParamsMap: { [trackId: ID]: QueryParams } = {}

for (const { track } of tracks) {
if (!track) {
continue
}
const trackId = track.track_id

if (gatedQueryParamsMap[trackId]) {
queryParamsMap[trackId] = gatedQueryParamsMap[trackId]
} else {
const nftAccessSignature = nftAccessSignatureMap[trackId]?.mp3 ?? null
queryParamsMap[trackId] = await getQueryParams({
audiusBackendInstance,
nftAccessSignature
})
}
}

setGatedQueryParamsMap(queryParamsMap)
return queryParamsMap
},
[nftAccessSignatureMap, gatedQueryParamsMap, setGatedQueryParamsMap]
)

useTrackPlayerEvents(playerEvents, async (event) => {
const duration = (await TrackPlayer.getProgress()).duration
const position = (await TrackPlayer.getProgress()).position
Expand Down Expand Up @@ -491,13 +524,8 @@ export const AudioPlayer = () => {

// Ref to keep track of the queue in the track player vs the queue in state
const queueListRef = useRef<string[]>([])

// A ref to the enqueue task to await before either requeing or appending to queue
const enqueueTracksJobRef = useRef<Promise<void>>()
// A way to abort the enqeue tracks job if a new lineup is played
const abortEnqueueControllerRef = useRef(new AbortController())
// The ref of trackQueryParams to avoid re-generating query params for the same track
const trackQueryParams = useRef({})
// Ref to ensure that we do not try to update while we are already updating
const updatingQueueRef = useRef<boolean>(false)

const handleQueueChange = useCallback(async () => {
const refUids = queueListRef.current
Expand All @@ -508,6 +536,7 @@ export const AudioPlayer = () => {
return
}

updatingQueueRef.current = true
queueListRef.current = queueTrackUids

// Checks to allow for continuous playback while making queue updates
Expand All @@ -516,18 +545,6 @@ export const AudioPlayer = () => {
refUids.length > 0 &&
isEqual(queueTrackUids.slice(0, refUids.length), refUids)

// If not an append, cancel the enqueue task first
if (!isQueueAppend) {
abortEnqueueControllerRef.current.abort()
}
// wait for enqueue task to either shut down or finish
if (enqueueTracksJobRef.current) {
await enqueueTracksJobRef.current
}

// Re-init the abort controller now that the enqueue job is done
abortEnqueueControllerRef.current = new AbortController()

// TODO: Queue removal logic was firing too often previously and causing playback issues when at the end of queues. Need to fix
// Check if we are removing from the end of the queue
// const isQueueRemoval =
Expand All @@ -551,7 +568,11 @@ export const AudioPlayer = () => {
? queueTracks.slice(refUids.length)
: queueTracks

const makeTrackData = async ({ track, isPreview }: QueueableTrack) => {
const queryParamsMap = isReachable
? await handleGatedQueryParams(newQueueTracks)
: null

const newTrackData = newQueueTracks.map(({ track, isPreview }) => {
if (!track) {
return unlistedTrackFallbackTrackData
}
Expand All @@ -566,19 +587,10 @@ export const AudioPlayer = () => {
const audioFilePath = getLocalAudioPath(trackId)
url = `file://${audioFilePath}`
} else {
let queryParams = trackQueryParams.current[trackId]

if (!queryParams) {
const nftAccessSignature = nftAccessSignatureMap[trackId]?.mp3 ?? null
queryParams = await getQueryParams({
audiusBackendInstance,
nftAccessSignature
})
trackQueryParams.current[trackId] = queryParams
const queryParams = {
...queryParamsMap?.[track.track_id],
preview: isPreview
}

queryParams = { ...queryParams, preview: isPreview }

url = apiClient.makeUrl(
`/tracks/${encodeHashId(track.track_id)}/stream`,
queryParams
Expand Down Expand Up @@ -612,76 +624,44 @@ export const AudioPlayer = () => {
artwork: imageUrl,
duration: isPreview ? getTrackPreviewDuration(track) : track.duration
}
}

// Enqueue tracks using 'middle-out' to ensure user can ready skip forward or backwards
const enqueueTracks = async (
queuableTracks: QueueableTrack[],
queueIndex = 0
) => {
let currentPivot = 1
while (
queueIndex - currentPivot > 0 ||
queueIndex + currentPivot < queueTracks.length
) {
if (abortEnqueueControllerRef.current.signal.aborted) {
return
}

const nextTrack = queuableTracks[queueIndex + currentPivot]
if (nextTrack) {
await TrackPlayer.add(await makeTrackData(nextTrack))
}

const previousTrack = queuableTracks[queueIndex - currentPivot]
if (previousTrack) {
await TrackPlayer.add(await makeTrackData(previousTrack), 0)
}
currentPivot++
}
}
})

if (isQueueAppend) {
enqueueTracksJobRef.current = enqueueTracks(newQueueTracks)
await enqueueTracksJobRef.current
enqueueTracksJobRef.current = undefined
await TrackPlayer.add(newTrackData)
} else {
// New queue, reset before adding new tracks
// NOTE: Should only happen when the user selects a new lineup so reset should never be called in the background and cause an error
await TrackPlayer.reset()

const firstTrack = newQueueTracks[queueIndex]
if (!firstTrack) return
await TrackPlayer.add(await makeTrackData(firstTrack))

if (playing) {
await TrackPlayer.play()
await TrackPlayer.add(newTrackData)
if (queueIndex < newQueueTracks.length) {
await TrackPlayer.skip(queueIndex)
}

enqueueTracksJobRef.current = enqueueTracks(newQueueTracks, queueIndex)
await enqueueTracksJobRef.current
enqueueTracksJobRef.current = undefined
}

if (playing) await TrackPlayer.play()
updatingQueueRef.current = false
}, [
isNotReachable,
isOfflineModeEnabled,
offlineAvailabilityByTrackId,
playing,
queueIndex,
queueTrackOwnersMap,
queueTrackUids,
didOfflineToggleChange,
queueTracks,
queueTrackOwnersMap,
isOfflineModeEnabled,
offlineAvailabilityByTrackId,
didOfflineToggleChange,
isCollectionMarkedForDownload,
isNotReachable,
storageNodeSelector,
nftAccessSignatureMap,
playing
handleGatedQueryParams,
isReachable,
storageNodeSelector
])

const handleQueueIdxChange = useCallback(async () => {
const playerIdx = await TrackPlayer.getActiveTrackIndex()
const queue = await TrackPlayer.getQueue()

await enqueueTracksJobRef.current

if (
!updatingQueueRef.current &&
queueIndex !== -1 &&
queueIndex !== playerIdx &&
queueIndex < queue.length
Expand Down