fix: music downloading not playing + queue drag and drop
Some checks failed
🔒 Lockfile Consistency Check / 🔍 Check bun.lock and package.json consistency (push) Has been cancelled
🛡️ CodeQL Analysis / 🔎 Analyze with CodeQL (actions) (push) Has been cancelled
🛡️ CodeQL Analysis / 🔎 Analyze with CodeQL (javascript-typescript) (push) Has been cancelled
🏷️🔀Merge Conflict Labeler / 🏷️ Labeling Merge Conflicts (push) Has been cancelled
🏗️ Build Apps / 🤖 Build Android APK (Phone) (push) Has been cancelled
🏗️ Build Apps / 🤖 Build Android APK (TV) (push) Has been cancelled
🏗️ Build Apps / 🍎 Build iOS IPA (Phone) (push) Has been cancelled
🌐 Translation Sync / sync-translations (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (lint) (push) Has been cancelled
🚦 Security & Quality Gate / 📝 Validate PR Title (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Vulnerable Dependencies (push) Has been cancelled
🚦 Security & Quality Gate / 🚑 Expo Doctor Check (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (check) (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (format) (push) Has been cancelled
🚦 Security & Quality Gate / 🔍 Lint & Test (typecheck) (push) Has been cancelled
🕒 Handle Stale Issues / 🗑️ Cleanup Stale Issues (push) Has been cancelled

This commit is contained in:
Fredrik Burmester
2026-01-04 16:28:35 +01:00
parent d22827bc9b
commit a2058a8009
17 changed files with 375 additions and 92 deletions

View File

@@ -1,3 +1,5 @@
import { Ionicons } from "@expo/vector-icons";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Platform, ScrollView, View } from "react-native";
import { Switch } from "react-native-gesture-handler";
@@ -5,13 +7,68 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Text } from "@/components/common/Text";
import { ListGroup } from "@/components/list/ListGroup";
import { ListItem } from "@/components/list/ListItem";
import { PlatformDropdown } from "@/components/PlatformDropdown";
import { useSettings } from "@/utils/atoms/settings";
const CACHE_SIZE_OPTIONS = [
{ label: "100 MB", value: 100 },
{ label: "250 MB", value: 250 },
{ label: "500 MB", value: 500 },
{ label: "1 GB", value: 1024 },
{ label: "2 GB", value: 2048 },
];
const LOOKAHEAD_COUNT_OPTIONS = [
{ label: "1 song", value: 1 },
{ label: "2 songs", value: 2 },
{ label: "3 songs", value: 3 },
{ label: "5 songs", value: 5 },
];
export default function MusicSettingsPage() {
const insets = useSafeAreaInsets();
const { settings, updateSettings, pluginSettings } = useSettings();
const { t } = useTranslation();
const cacheSizeOptions = useMemo(
() => [
{
options: CACHE_SIZE_OPTIONS.map((option) => ({
type: "radio" as const,
label: option.label,
value: String(option.value),
selected: option.value === settings?.audioMaxCacheSizeMB,
onPress: () => updateSettings({ audioMaxCacheSizeMB: option.value }),
})),
},
],
[settings?.audioMaxCacheSizeMB, updateSettings],
);
const currentCacheSizeLabel =
CACHE_SIZE_OPTIONS.find((o) => o.value === settings?.audioMaxCacheSizeMB)
?.label ?? `${settings?.audioMaxCacheSizeMB} MB`;
const lookaheadCountOptions = useMemo(
() => [
{
options: LOOKAHEAD_COUNT_OPTIONS.map((option) => ({
type: "radio" as const,
label: option.label,
value: String(option.value),
selected: option.value === settings?.audioLookaheadCount,
onPress: () => updateSettings({ audioLookaheadCount: option.value }),
})),
},
],
[settings?.audioLookaheadCount, updateSettings],
);
const currentLookaheadLabel =
LOOKAHEAD_COUNT_OPTIONS.find(
(o) => o.value === settings?.audioLookaheadCount,
)?.label ?? `${settings?.audioLookaheadCount} songs`;
return (
<ScrollView
contentInsetAdjustmentBehavior='automatic'
@@ -67,6 +124,51 @@ export default function MusicSettingsPage() {
}
/>
</ListItem>
<ListItem
title={t("home.settings.music.lookahead_count")}
disabled={
pluginSettings?.audioLookaheadCount?.locked ||
!settings.audioLookaheadEnabled
}
>
<PlatformDropdown
groups={lookaheadCountOptions}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>
{currentLookaheadLabel}
</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t("home.settings.music.lookahead_count")}
/>
</ListItem>
<ListItem
title={t("home.settings.music.max_cache_size")}
disabled={pluginSettings?.audioMaxCacheSizeMB?.locked}
>
<PlatformDropdown
groups={cacheSizeOptions}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>
{currentCacheSizeLabel}
</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t("home.settings.music.max_cache_size")}
/>
</ListItem>
</ListGroup>
</View>
</View>

View File

@@ -139,7 +139,10 @@ export default function AlbumDetailScreen() {
if (!track.Id || isPermanentlyDownloaded(track.Id)) continue;
const result = await getAudioStreamUrl(api, user.Id, track.Id);
if (result?.url && !result.isTranscoding) {
await downloadTrack(track.Id, result.url, { permanent: true });
await downloadTrack(track.Id, result.url, {
permanent: true,
container: result.mediaSource?.Container || undefined,
});
}
}
} catch {
@@ -150,7 +153,8 @@ export default function AlbumDetailScreen() {
const isLoading = loadingAlbum || loadingTracks;
if (isLoading) {
// Only show loading if we have no cached data to display
if (isLoading && !album) {
return (
<View className='flex-1 justify-center items-center bg-black'>
<Loader />

View File

@@ -120,7 +120,8 @@ export default function ArtistDetailScreen() {
const isLoading = loadingArtist || loadingAlbums || loadingTracks;
if (isLoading) {
// Only show loading if we have no cached data to display
if (isLoading && !artist) {
return (
<View className='flex-1 justify-center items-center bg-black'>
<Loader />

View File

@@ -146,7 +146,10 @@ export default function PlaylistDetailScreen() {
if (!track.Id || getLocalPath(track.Id)) continue;
const result = await getAudioStreamUrl(api, user.Id, track.Id);
if (result?.url && !result.isTranscoding) {
await downloadTrack(track.Id, result.url, { permanent: true });
await downloadTrack(track.Id, result.url, {
permanent: true,
container: result.mediaSource?.Container || undefined,
});
}
}
} catch {
@@ -157,7 +160,8 @@ export default function PlaylistDetailScreen() {
const isLoading = loadingPlaylist || loadingTracks;
if (isLoading) {
// Only show loading if we have no cached data to display
if (isLoading && !playlist) {
return (
<View className='flex-1 justify-center items-center bg-black'>
<Loader />

View File

@@ -102,7 +102,8 @@ export default function ArtistsScreen() {
);
}
if (isLoading) {
// Only show loading if we have no cached data to display
if (isLoading && artists.length === 0) {
return (
<View className='flex-1 justify-center items-center bg-black'>
<Loader />
@@ -110,7 +111,9 @@ export default function ArtistsScreen() {
);
}
if (isError) {
// Only show error if we have no cached data to display
// This allows offline access to previously cached artists
if (isError && artists.length === 0) {
return (
<View className='flex-1 justify-center items-center bg-black px-6'>
<Text className='text-neutral-500 text-center'>

View File

@@ -124,7 +124,8 @@ export default function PlaylistsScreen() {
);
}
if (isLoading) {
// Only show loading if we have no cached data to display
if (isLoading && playlists.length === 0) {
return (
<View className='flex-1 justify-center items-center bg-black'>
<Loader />
@@ -132,7 +133,9 @@ export default function PlaylistsScreen() {
);
}
if (isError) {
// Only show error if we have no cached data to display
// This allows offline access to previously cached playlists
if (isError && playlists.length === 0) {
return (
<View className='flex-1 justify-center items-center bg-black px-6'>
<Text className='text-neutral-500 text-center'>

View File

@@ -232,7 +232,8 @@ export default function SuggestionsScreen() {
);
}
if (isLoading) {
// Only show loading if we have no cached data to display
if (isLoading && sections.length === 0) {
return (
<View className='flex-1 justify-center items-center bg-black'>
<Loader />
@@ -240,7 +241,12 @@ export default function SuggestionsScreen() {
);
}
if (isLatestError || isRecentlyPlayedError || isFrequentError) {
// Only show error if we have no cached data to display
// This allows offline access to previously cached suggestions
if (
(isLatestError || isRecentlyPlayedError || isFrequentError) &&
sections.length === 0
) {
const msg =
(latestError as Error | undefined)?.message ||
(recentlyPlayedError as Error | undefined)?.message ||

View File

@@ -10,13 +10,16 @@ import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
ActivityIndicator,
Dimensions,
FlatList,
Platform,
ScrollView,
TouchableOpacity,
View,
} from "react-native";
import { Slider } from "react-native-awesome-slider";
import DraggableFlatList, {
type RenderItemParams,
ScaleDecorator,
} from "react-native-draggable-flatlist";
import { useSharedValue } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Badge } from "@/components/Badge";
@@ -73,6 +76,7 @@ export default function NowPlayingScreen() {
toggleShuffle,
jumpToIndex,
removeFromQueue,
reorderQueue,
stop,
} = useMusicPlayer();
@@ -244,6 +248,7 @@ export default function NowPlayingScreen() {
queueIndex={queueIndex}
onJumpToIndex={jumpToIndex}
onRemoveFromQueue={removeFromQueue}
onReorderQueue={reorderQueue}
/>
)}
</View>
@@ -490,6 +495,7 @@ interface QueueViewProps {
queueIndex: number;
onJumpToIndex: (index: number) => void;
onRemoveFromQueue: (index: number) => void;
onReorderQueue: (newQueue: BaseItemDto[]) => void;
}
const QueueView: React.FC<QueueViewProps> = ({
@@ -498,9 +504,11 @@ const QueueView: React.FC<QueueViewProps> = ({
queueIndex,
onJumpToIndex,
onRemoveFromQueue,
onReorderQueue,
}) => {
const renderQueueItem = useCallback(
({ item, index }: { item: BaseItemDto; index: number }) => {
({ item, drag, isActive, getIndex }: RenderItemParams<BaseItemDto>) => {
const index = getIndex() ?? 0;
const isCurrentTrack = index === queueIndex;
const isPast = index < queueIndex;
@@ -512,80 +520,102 @@ const QueueView: React.FC<QueueViewProps> = ({
: null;
return (
<TouchableOpacity
onPress={() => onJumpToIndex(index)}
className={`flex-row items-center px-4 py-3 ${isCurrentTrack ? "bg-purple-900/30" : ""}`}
style={{ opacity: isPast ? 0.5 : 1 }}
>
{/* Track number / Now playing indicator */}
<View className='w-8 items-center'>
{isCurrentTrack ? (
<Ionicons name='musical-note' size={16} color='#9334E9' />
) : (
<Text className='text-neutral-500 text-sm'>{index + 1}</Text>
)}
</View>
{/* Album art */}
<View className='w-12 h-12 rounded overflow-hidden bg-neutral-800 mr-3'>
{imageUrl ? (
<Image
source={{ uri: imageUrl }}
style={{ width: "100%", height: "100%" }}
contentFit='cover'
cachePolicy='memory-disk'
/>
) : (
<View className='flex-1 items-center justify-center'>
<Ionicons name='musical-note' size={16} color='#666' />
</View>
)}
</View>
{/* Track info */}
<View className='flex-1 mr-2'>
<Text
numberOfLines={1}
className={`text-base ${isCurrentTrack ? "text-purple-400 font-semibold" : "text-white"}`}
>
{item.Name}
</Text>
<Text numberOfLines={1} className='text-neutral-500 text-sm'>
{item.Artists?.join(", ") || item.AlbumArtist}
</Text>
</View>
{/* Remove button (not for current track) */}
{!isCurrentTrack && (
<ScaleDecorator>
<TouchableOpacity
onPress={() => onJumpToIndex(index)}
onLongPress={drag}
disabled={isActive}
className='flex-row items-center px-4 py-3'
style={{
opacity: isPast && !isActive ? 0.5 : 1,
backgroundColor: isActive
? "#2a2a2a"
: isCurrentTrack
? "rgba(147, 52, 233, 0.3)"
: "#121212",
}}
>
{/* Drag handle */}
<TouchableOpacity
onPress={() => onRemoveFromQueue(index)}
onPressIn={drag}
disabled={isActive}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
className='p-2'
className='pr-2'
>
<Ionicons name='close' size={20} color='#666' />
<Ionicons
name='reorder-three'
size={20}
color={isActive ? "#9334E9" : "#666"}
/>
</TouchableOpacity>
)}
</TouchableOpacity>
{/* Album art */}
<View className='w-12 h-12 rounded overflow-hidden bg-neutral-800 mr-3'>
{imageUrl ? (
<Image
source={{ uri: imageUrl }}
style={{ width: "100%", height: "100%" }}
contentFit='cover'
cachePolicy='memory-disk'
/>
) : (
<View className='flex-1 items-center justify-center'>
<Ionicons name='musical-note' size={16} color='#666' />
</View>
)}
</View>
{/* Track info */}
<View className='flex-1 mr-2'>
<Text
numberOfLines={1}
className={`text-base ${isCurrentTrack ? "text-purple-400 font-semibold" : "text-white"}`}
>
{item.Name}
</Text>
<Text numberOfLines={1} className='text-neutral-500 text-sm'>
{item.Artists?.join(", ") || item.AlbumArtist}
</Text>
</View>
{/* Now playing indicator */}
{isCurrentTrack && (
<Ionicons name='musical-note' size={16} color='#9334E9' />
)}
{/* Remove button (not for current track) */}
{!isCurrentTrack && (
<TouchableOpacity
onPress={() => onRemoveFromQueue(index)}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
className='p-2'
>
<Ionicons name='close' size={20} color='#666' />
</TouchableOpacity>
)}
</TouchableOpacity>
</ScaleDecorator>
);
},
[api, queueIndex, onJumpToIndex, onRemoveFromQueue],
);
const _upNext = queue.slice(queueIndex + 1);
const handleDragEnd = useCallback(
({ data }: { data: BaseItemDto[] }) => {
onReorderQueue(data);
},
[onReorderQueue],
);
const history = queue.slice(0, queueIndex);
return (
<FlatList
<DraggableFlatList
data={queue}
keyExtractor={(item, index) => `${item.Id}-${index}`}
renderItem={renderQueueItem}
onDragEnd={handleDragEnd}
showsVerticalScrollIndicator={false}
initialScrollIndex={queueIndex > 2 ? queueIndex - 2 : 0}
getItemLayout={(_, index) => ({
length: 72,
offset: 72 * index,
index,
})}
ListHeaderComponent={
<View className='px-4 py-2'>
<Text className='text-neutral-400 text-xs uppercase tracking-wider'>

View File

@@ -61,6 +61,7 @@
"react-native-collapsible": "^1.6.2",
"react-native-country-flag": "^2.0.2",
"react-native-device-info": "^15.0.0",
"react-native-draggable-flatlist": "^4.0.3",
"react-native-edge-to-edge": "^1.7.0",
"react-native-gesture-handler": "~2.28.0",
"react-native-glass-effect-view": "^1.0.0",
@@ -1637,6 +1638,8 @@
"react-native-device-info": ["react-native-device-info@15.0.1", "", { "peerDependencies": { "react-native": "*" } }, "sha512-U5waZRXtT3l1SgZpZMlIvMKPTkFZPH8W7Ks6GrJhdH723aUIPxjVer7cRSij1mvQdOAAYFJV/9BDzlC8apG89A=="],
"react-native-draggable-flatlist": ["react-native-draggable-flatlist@4.0.3", "", { "dependencies": { "@babel/preset-typescript": "^7.17.12" }, "peerDependencies": { "react-native": ">=0.64.0", "react-native-gesture-handler": ">=2.0.0", "react-native-reanimated": ">=2.8.0" } }, "sha512-2F4x5BFieWdGq9SetD2nSAR7s7oQCSgNllYgERRXXtNfSOuAGAVbDb/3H3lP0y5f7rEyNwabKorZAD/SyyNbDw=="],
"react-native-edge-to-edge": ["react-native-edge-to-edge@1.7.0", "", { "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-ERegbsq28yoMndn/Uq49i4h6aAhMvTEjOfkFh50yX9H/dMjjCr/Tix/es/9JcPRvC+q7VzCMWfxWDUb6Jrq1OQ=="],
"react-native-gesture-handler": ["react-native-gesture-handler@2.28.0", "", { "dependencies": { "@egjs/hammerjs": "^2.0.17", "hoist-non-react-statics": "^3.3.0", "invariant": "^2.2.4" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-0msfJ1vRxXKVgTgvL+1ZOoYw3/0z1R+Ked0+udoJhyplC2jbVKIJ8Z1bzWdpQRCV3QcQ87Op0zJVE5DhKK2A0A=="],

View File

@@ -99,6 +99,7 @@ export const MusicPlaybackEngine: React.FC = () => {
currentIndex,
);
await TrackPlayer.skip(currentIndex);
await TrackPlayer.play();
}
} catch (error) {
console.warn(

View File

@@ -27,6 +27,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Text } from "@/components/common/Text";
import { useFavorite } from "@/hooks/useFavorite";
import {
audioStorageEvents,
downloadTrack,
isCached,
isPermanentDownloading,
@@ -62,6 +63,22 @@ export const TrackOptionsSheet: React.FC<Props> = ({
const insets = useSafeAreaInsets();
const { t } = useTranslation();
const [isDownloadingTrack, setIsDownloadingTrack] = useState(false);
// Counter to trigger re-evaluation of download status when storage changes
const [storageUpdateCounter, setStorageUpdateCounter] = useState(0);
// Listen for storage events to update download status
useEffect(() => {
const handleComplete = (event: { itemId: string }) => {
if (event.itemId === track?.Id) {
setStorageUpdateCounter((c) => c + 1);
}
};
audioStorageEvents.on("complete", handleComplete);
return () => {
audioStorageEvents.off("complete", handleComplete);
};
}, [track?.Id]);
// Use a placeholder item for useFavorite when track is null
const { isFavorite, toggleFavorite } = useFavorite(
@@ -70,15 +87,18 @@ export const TrackOptionsSheet: React.FC<Props> = ({
const snapPoints = useMemo(() => ["65%"], []);
// Check download status
// Check download status (storageUpdateCounter triggers re-evaluation when download completes)
const isAlreadyDownloaded = useMemo(
() => isPermanentlyDownloaded(track?.Id),
[track?.Id],
[track?.Id, storageUpdateCounter],
);
const isOnlyCached = useMemo(
() => isCached(track?.Id),
[track?.Id, storageUpdateCounter],
);
const isOnlyCached = useMemo(() => isCached(track?.Id), [track?.Id]);
const isCurrentlyDownloading = useMemo(
() => isPermanentDownloading(track?.Id),
[track?.Id],
[track?.Id, storageUpdateCounter],
);
const imageUrl = useMemo(() => {
@@ -150,7 +170,10 @@ export const TrackOptionsSheet: React.FC<Props> = ({
try {
const result = await getAudioStreamUrl(api, user.Id, track.Id);
if (result?.url && !result.isTranscoding) {
await downloadTrack(track.Id, result.url, { permanent: true });
await downloadTrack(track.Id, result.url, {
permanent: true,
container: result.mediaSource?.Container || undefined,
});
}
} catch {
// Silent fail

View File

@@ -80,6 +80,7 @@
"react-native-collapsible": "^1.6.2",
"react-native-country-flag": "^2.0.2",
"react-native-device-info": "^15.0.0",
"react-native-draggable-flatlist": "^4.0.3",
"react-native-edge-to-edge": "^1.7.0",
"react-native-gesture-handler": "~2.28.0",
"react-native-glass-effect-view": "^1.0.0",

View File

@@ -34,7 +34,10 @@ const AUDIO_PERMANENT_DIR = "streamyfin-audio";
// Default limits
const DEFAULT_MAX_CACHE_TRACKS = 10;
const DEFAULT_MAX_CACHE_SIZE_BYTES = 100 * 1024 * 1024; // 100MB
const DEFAULT_MAX_CACHE_SIZE_BYTES = 500 * 1024 * 1024; // 500MB
// Configurable limits (can be updated at runtime)
let configuredMaxCacheSizeBytes = DEFAULT_MAX_CACHE_SIZE_BYTES;
// Event emitter for notifying about download completion
class AudioStorageEventEmitter extends EventEmitter<{
@@ -130,6 +133,17 @@ async function ensureDirectories(): Promise<void> {
}
}
/**
* Set the maximum cache size in megabytes
* Call this when settings change
*/
export function setMaxCacheSizeMB(sizeMB: number): void {
configuredMaxCacheSizeBytes = sizeMB * 1024 * 1024;
console.log(
`[AudioStorage] Max cache size set to ${sizeMB}MB (${configuredMaxCacheSizeBytes} bytes)`,
);
}
/**
* Initialize audio storage - call this on app startup
*/
@@ -447,9 +461,11 @@ export async function downloadTrack(
return;
}
// Use .m4a extension - compatible with iOS/Android and most audio formats
const filename = `${itemId}.m4a`;
const destinationPath = `${targetDir.uri}/${filename}`.replace("file://", "");
// Use the actual container format as extension, fallback to m4a
const extension = options.container?.toLowerCase() || "m4a";
const filename = `${itemId}.${extension}`;
const destinationPath =
`${targetDir.uri.replace(/\/$/, "")}/${filename}`.replace("file://", "");
console.log(
`[AudioStorage] Starting download: ${itemId} (permanent=${permanent})`,
@@ -529,7 +545,7 @@ export async function deleteTrack(itemId: string): Promise<void> {
*/
async function evictCacheIfNeeded(
maxTracks: number = DEFAULT_MAX_CACHE_TRACKS,
maxSizeBytes: number = DEFAULT_MAX_CACHE_SIZE_BYTES,
maxSizeBytes: number = configuredMaxCacheSizeBytes,
): Promise<void> {
const index = getStorageIndex();

View File

@@ -22,6 +22,7 @@ export interface AudioStorageIndex {
export interface DownloadOptions {
permanent: boolean;
container?: string; // File extension/format (e.g., "mp3", "flac", "m4a")
}
export interface DownloadCompleteEvent {

View File

@@ -26,6 +26,7 @@ import {
getLocalPath,
initAudioStorage,
isDownloading,
setMaxCacheSizeMB,
} from "@/providers/AudioStorage";
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
import { settingsAtom } from "@/utils/atoms/settings";
@@ -86,6 +87,7 @@ interface MusicPlayerContextType extends MusicPlayerState {
playNext: (tracks: BaseItemDto | BaseItemDto[]) => void;
removeFromQueue: (index: number) => void;
moveInQueue: (fromIndex: number, toIndex: number) => void;
reorderQueue: (newQueue: BaseItemDto[]) => void;
clearQueue: () => void;
jumpToIndex: (index: number) => void;
@@ -286,7 +288,12 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
// Initialize audio storage for caching
await initAudioStorage();
await TrackPlayer.setupPlayer();
await TrackPlayer.setupPlayer({
minBuffer: 120, // Minimum 2 minutes buffer for network resilience
maxBuffer: 240, // Maximum 4 minutes buffer
playBuffer: 5, // Start playback after 5 seconds buffered
backBuffer: 30, // Keep 30 seconds behind for seeking
});
await TrackPlayer.updateOptions({
capabilities: [
Capability.Play,
@@ -313,6 +320,13 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
setupPlayer();
}, []);
// Update audio cache size when settings change
useEffect(() => {
if (settings?.audioMaxCacheSizeMB) {
setMaxCacheSizeMB(settings.audioMaxCacheSizeMB);
}
}, [settings?.audioMaxCacheSizeMB]);
// Sync repeat mode to TrackPlayer
useEffect(() => {
const syncRepeatMode = async () => {
@@ -476,9 +490,15 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
const item = queue[i];
if (!item.Id) continue;
// First check for cached version (for offline fallback)
// Check for cached/downloaded version
const cachedUrl = getLocalPath(item.Id);
// If preferLocal and we have a local file, use it directly without server request
if (preferLocal && cachedUrl) {
tracks.push(itemToTrack(item, cachedUrl, api, true));
continue;
}
// Try to get stream URL from server
const result = await getAudioStreamUrl(api, user.Id, item.Id);
@@ -545,7 +565,8 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
}));
reportPlaybackStart(currentTrack, state.playSessionId);
} catch (_error) {
} catch (error) {
console.error("[MusicPlayer] Error loading queue:", error);
setState((prev) => ({
...prev,
isLoading: false,
@@ -1043,6 +1064,63 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
[],
);
// Reorder queue with a new array (used by drag-to-reorder UI)
const reorderQueue = useCallback(
async (newQueue: BaseItemDto[]) => {
// Find where the current track ended up in the new order
const currentTrackId = state.currentTrack?.Id;
const newIndex = currentTrackId
? newQueue.findIndex((t) => t.Id === currentTrackId)
: 0;
// Build the reordering operations for TrackPlayer
// We need to match TrackPlayer's queue to the new order
const tpQueue = await TrackPlayer.getQueue();
// Create a map of trackId -> current TrackPlayer index
const currentPositions = new Map<string, number>();
tpQueue.forEach((track, idx) => {
currentPositions.set(track.id, idx);
});
// Move tracks one by one to match the new order
// Work backwards to avoid index shifting issues
for (let targetIdx = newQueue.length - 1; targetIdx >= 0; targetIdx--) {
const trackId = newQueue[targetIdx].Id;
if (!trackId) continue;
const currentIdx = currentPositions.get(trackId);
if (currentIdx !== undefined && currentIdx !== targetIdx) {
await TrackPlayer.move(currentIdx, targetIdx);
// Update positions map after move
currentPositions.forEach((pos, id) => {
if (currentIdx < targetIdx) {
// Moving down: items between shift up
if (pos > currentIdx && pos <= targetIdx) {
currentPositions.set(id, pos - 1);
}
} else {
// Moving up: items between shift down
if (pos >= targetIdx && pos < currentIdx) {
currentPositions.set(id, pos + 1);
}
}
});
currentPositions.set(trackId, targetIdx);
}
}
setState((prev) => ({
...prev,
queue: newQueue,
queueIndex: newIndex >= 0 ? newIndex : 0,
currentTrack: newIndex >= 0 ? newQueue[newIndex] : prev.currentTrack,
}));
},
[state.currentTrack?.Id],
);
const clearQueue = useCallback(async () => {
const currentIndex = await TrackPlayer.getActiveTrackIndex();
const queue = await TrackPlayer.getQueue();
@@ -1181,7 +1259,7 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
// For other modes, TrackPlayer handles it via repeat mode setting
}, [state.repeatMode]);
// Cache current track + look-ahead: pre-cache current and next N tracks
// Look-ahead cache: pre-cache upcoming N tracks (excludes current track to avoid bandwidth competition)
const triggerLookahead = useCallback(async () => {
// Check if caching is enabled in settings
if (settings?.audioLookaheadEnabled === false) return;
@@ -1192,10 +1270,10 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
const currentIdx = await TrackPlayer.getActiveTrackIndex();
if (currentIdx === undefined || currentIdx < 0) return;
// Cache current track + next N tracks (from settings, default 2)
const lookaheadCount = settings?.audioLookaheadCount ?? 2;
// Cache next N tracks (from settings, default 1) - excludes current to avoid bandwidth competition
const lookaheadCount = settings?.audioLookaheadCount ?? 1;
const tracksToCache = tpQueue.slice(
currentIdx,
currentIdx + 1,
currentIdx + 1 + lookaheadCount,
);
@@ -1209,7 +1287,10 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
// Only cache direct streams (not transcoding - can't cache dynamic content)
if (result?.url && !result.isTranscoding) {
downloadTrack(itemId, result.url, { permanent: false }).catch(() => {
downloadTrack(itemId, result.url, {
permanent: false,
container: result.mediaSource?.Container || undefined,
}).catch(() => {
// Silent fail - caching is best-effort
});
}
@@ -1242,6 +1323,7 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
playNext,
removeFromQueue,
moveInQueue,
reorderQueue,
clearQueue,
jumpToIndex,
setRepeatMode,
@@ -1271,6 +1353,7 @@ export const MusicPlayerProvider: React.FC<MusicPlayerProviderProps> = ({
playNext,
removeFromQueue,
moveInQueue,
reorderQueue,
clearQueue,
jumpToIndex,
setRepeatMode,

View File

@@ -232,7 +232,9 @@
"prefer_downloaded": "Prefer Downloaded Songs",
"caching_title": "Caching",
"caching_description": "Automatically cache upcoming tracks for smoother playback.",
"lookahead_enabled": "Enable Look-Ahead Caching"
"lookahead_enabled": "Enable Look-Ahead Caching",
"lookahead_count": "Tracks to Pre-cache",
"max_cache_size": "Max Cache Size"
},
"plugins": {
"plugins_title": "Plugins",

View File

@@ -294,8 +294,8 @@ export const defaultValues: Settings = {
hideWatchlistsTab: false,
// Audio look-ahead caching defaults
audioLookaheadEnabled: true,
audioLookaheadCount: 2,
audioMaxCacheSizeMB: 100,
audioLookaheadCount: 1,
audioMaxCacheSizeMB: 500,
// Music playback
preferLocalAudio: true,
};