-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMusicPlayerFunctions.js
More file actions
1637 lines (1492 loc) · 56.6 KB
/
MusicPlayerFunctions.js
File metadata and controls
1637 lines (1492 loc) · 56.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import TrackPlayer from 'react-native-track-player';
import { setRepeatMode } from 'react-native-track-player/lib/trackPlayer';
import { GetPlaybackQuality } from './LocalStorage/AppSettings';
import NetInfo from '@react-native-community/netinfo';
import {
ToastAndroid,
DeviceEventEmitter,
InteractionManager,
} from 'react-native';
import historyManager from './Utils/HistoryManager';
import dabMusicService from './Utils/DabMusicService';
import youtubeStreamingService from './Utils/YouTubeStreamingService';
import queueManager from './Utils/QueueManager';
import {
enhanceYTMusicArtwork,
getPrimaryArtworkUrl,
} from './Utils/ArtworkEnhancer';
import autoRecommendations from './Utils/AutoRecommendations';
import skipOperationManager from './Utils/SkipOperationManager';
import streamFetchManager from './Utils/StreamFetchManager';
import smartPrefetchManager from './Utils/SmartPrefetchManager';
import FormatArtist from './Utils/FormatArtists';
import dabRecommendationService from './Utils/DABRecommendationService';
import lastFMService from './Utils/LastFMService';
import progressiveQueueLoader from './Utils/ProgressiveQueueLoader';
let isPlayerInitialized = false;
// PERFORMANCE: Cache quality index to avoid repeated AsyncStorage calls
let cachedQualityIndex = null;
let qualityCacheTimestamp = 0;
const QUALITY_CACHE_TTL = 60000; // 1 minute cache TTL
// Helper to extract artwork URL from various formats
const extractArtwork = (song) => {
let artworkUrl = '';
// Direct artwork/image string
if (
song.artwork &&
typeof song.artwork === 'string' &&
song.artwork.length > 0
) {
artworkUrl = song.artwork;
} else if (
song.image &&
typeof song.image === 'string' &&
song.image.length > 0
) {
artworkUrl = song.image;
}
// Object format with url/uri
else if (song.artwork && typeof song.artwork === 'object') {
artworkUrl = song.artwork.url || song.artwork.uri || '';
}
// Array format (Saavn/OuterTune)
else if (song.image && Array.isArray(song.image)) {
const bestImage =
song.image[2] ||
song.image[song.image.length - 1] ||
song.image[0];
artworkUrl =
bestImage?.url ||
bestImage?.link ||
bestImage?.uri ||
(typeof bestImage === 'string' ? bestImage : '');
}
// Single Image Object format
else if (song.image && typeof song.image === 'object') {
artworkUrl = song.image.url || song.image.link || song.image.uri || '';
}
// Thumbnail format (YTMusic)
else if (song.thumbnail) {
artworkUrl =
typeof song.thumbnail === 'string'
? song.thumbnail
: song.thumbnail.url || '';
} else if (song.thumbnails && Array.isArray(song.thumbnails)) {
const bestThumb =
song.thumbnails[song.thumbnails.length - 1] || song.thumbnails[0];
artworkUrl = bestThumb?.url || '';
}
// Final enhancement pass
if (artworkUrl && typeof artworkUrl === 'string') {
const enhanced = enhanceYTMusicArtwork(artworkUrl, 'card');
return getPrimaryArtworkUrl(enhanced) || artworkUrl;
}
return artworkUrl || song.artwork?.uri || song.image?.uri || '';
};
export const setupPlayer = async () => {
try {
if (!isPlayerInitialized) {
try {
await TrackPlayer.setupPlayer({
android: {
appKilledPlaybackBehavior: 'ContinuePlayback',
alwaysPauseOnInterruption: false,
},
autoUpdateMetadata: true,
});
// NOTE: Remote control listeners (play, pause, next, previous) are registered in service.js
// to avoid duplicate event listeners. DO NOT add them here.
await TrackPlayer.updateOptions({
android: {
appKilledPlaybackBehavior: 'ContinuePlayback',
alwaysPauseOnInterruption: false,
},
capabilities: [
'play',
'pause',
'stop',
'seekTo',
'skip',
'skipToNext',
'skipToPrevious',
],
compactCapabilities: [
'play',
'pause',
'stop',
'seekTo',
'skip',
'skipToNext',
'skipToPrevious',
],
notificationCapabilities: [
'play',
'pause',
'stop',
'seekTo',
'skip',
'skipToNext',
'skipToPrevious',
],
});
isPlayerInitialized = true;
// Initialize SmartPrefetchManager for background prefetching
smartPrefetchManager.initialize();
} catch (setupError) {
// Check if the error is about player already being initialized
if (
setupError.message &&
setupError.message.includes('player has already been initialized')
) {
isPlayerInitialized = true;
smartPrefetchManager.initialize();
} else {
console.error(
'Error setting up player in MusicPlayerFunctions:',
setupError
);
throw setupError;
}
}
} else {
}
} catch (error) {
console.error('Error in setupPlayer function:', error);
}
};
async function PlayOneSong(song) {
try {
// Validate song object
if (!song) {
console.error('PlayOneSong: No song provided');
return;
}
// Ensure player is initialized
if (!isPlayerInitialized) {
await setupPlayer();
}
// Get the appropriate URL based on playback quality setting
let playbackUrl = song.url;
let updatedSong = { ...song };
// Check if this is a podcast episode - skip all stream processing
const isPodcast = song.isPodcast || song.type === 'podcast';
// Check if this is a YouTube song (has videoId/id that looks like YouTube video ID)
// Podcasts should NOT be treated as YouTube songs even if ID length matches
const isYouTubeSong =
!isPodcast &&
song.id &&
typeof song.id === 'string' &&
song.id.length === 11 &&
!song.isLocalMusic;
if (isYouTubeSong) {
try {
// OPTIMISTIC UI: Emit early metadata event so mini player shows immediately
// This provides instant feedback while the 2-3 second stream fetch happens
const earlyArtwork =
extractArtwork(song) || song.artwork || song.image || '';
DeviceEventEmitter.emit('song-loading-started', {
id: song.id,
title: song.title || song.name || 'Loading...',
artist: song.artist || 'Loading...',
artwork: earlyArtwork,
image: earlyArtwork,
duration: song.duration,
isLoading: true,
});
// Use StreamFetchManager for deduplication and abort support
const streamData = await streamFetchManager.fetchStream(
song.id,
async (videoId, signal) => {
return await youtubeStreamingService.getStreamUrl(videoId, false);
}
);
if (streamData && streamData.url) {
// Verbose logging removed for cleaner console
playbackUrl = streamData.url;
// Update song with stream data and headers
// IMPORTANT: Preserve artist from original song data
// Determine quality label from actual bitrate and mimeType
// Estimate bitrate based on codec if not available
const isOpus = streamData.mimeType?.includes('webm');
const estimatedBitrate =
streamData.bitrate || (isOpus ? 148000 : 256000);
const bitrateKbps = Math.round(estimatedBitrate / 1000);
const codec = isOpus ? 'Opus' : 'AAC';
const ytQuality = `${codec} ${bitrateKbps}kbps`;
updatedSong = {
...updatedSong,
url: streamData.url,
headers: streamData.headers,
userAgent: streamData.headers?.['User-Agent'],
artwork: streamData.thumbnail || updatedSong.artwork,
duration: streamData.duration || updatedSong.duration,
currentPlayingQuality: ytQuality, // Store actual stream quality
title: updatedSong.title || streamData.title,
artist: updatedSong.artist || 'Unknown Artist',
};
// Reset error counter on successful fetch
skipOperationManager.resetErrorCounter();
} else {
console.error('Failed to get YouTube stream URL');
ToastAndroid.show(
'Failed to load YouTube stream',
ToastAndroid.SHORT
);
return;
}
} catch (error) {
console.error('Error fetching YouTube stream:', error);
// Don't show toast if operation was cancelled
if (error.name !== 'AbortError') {
ToastAndroid.show('Error loading YouTube stream', ToastAndroid.SHORT);
}
return;
}
}
// Check if this is a SPOTIFY track - needs to be mapped to YTMusic
else if (song.source === 'spotify' || song.spotifyId) {
try {
// OPTIMISTIC UI: Emit early metadata so mini player shows immediately
// Uses Spotify artwork while we search for YTMusic match
const earlyArtwork =
extractArtwork(song) || song.artwork || song.image || '';
DeviceEventEmitter.emit('song-loading-started', {
id: song.id,
title: song.title || song.name || 'Loading...',
artist: song.artist || 'Finding on YTMusic...',
artwork: earlyArtwork,
image: earlyArtwork,
duration: song.duration,
isLoading: true,
isSpotifyMapping: true, // Flag for UI to show mapping indicator
});
// Use YouTubeMusicService.searchAndStream to find and get stream URL
const YouTubeMusicService =
require('./Utils/YouTubeMusicService').default;
const searchQuery = `${song.title || song.name} ${
song.artist || ''
}`.trim();
const ytMusicResult = await YouTubeMusicService.searchAndStream(
song.title || song.name,
song.artist || ''
);
if (ytMusicResult && ytMusicResult.url && !ytMusicResult.error) {
playbackUrl = ytMusicResult.url;
// Update song with YTMusic stream data while strictly PRESERVING Spotify metadata
// Determine quality label from actual bitrate and mimeType
// Estimate bitrate based on codec if not available
const isOpus = ytMusicResult.mimeType?.includes('webm');
const estimatedBitrate =
ytMusicResult.bitrate || (isOpus ? 148000 : 256000);
const bitrateKbps = Math.round(estimatedBitrate / 1000);
const codec = isOpus ? 'Opus' : 'AAC';
const ytQuality = `${codec} ${bitrateKbps}kbps`;
updatedSong = {
...updatedSong,
url: ytMusicResult.url,
headers: ytMusicResult.headers,
userAgent: ytMusicResult.headers?.['User-Agent'],
// Add technical YTMusic data but keep Spotify metadata for UI
ytMusicVideoId: ytMusicResult.videoId,
mappedFromSpotify: true,
currentPlayingQuality: ytQuality,
};
skipOperationManager.resetErrorCounter();
} else {
console.error('❌ Failed to find YTMusic match for Spotify track');
ToastAndroid.show(
'Could not find song on YTMusic',
ToastAndroid.SHORT
);
return;
}
} catch (error) {
console.error('❌ Error mapping Spotify to YTMusic:', error);
ToastAndroid.show('Error finding song on YTMusic', ToastAndroid.SHORT);
return;
}
}
// Check if this is a DAB Music track
else if (
song.isDabTrack ||
song.source === 'dab' ||
(!isNaN(song.url) && String(song.url).length > 5)
) {
try {
// OPTIMISTIC UI: Emit early metadata so mini player shows immediately
const earlyArtwork =
extractArtwork(song) || song.artwork || song.image || '';
DeviceEventEmitter.emit('song-loading-started', {
id: song.id,
title: song.title || song.name || 'Loading...',
artist: song.artist || 'Loading...',
artwork: earlyArtwork,
image: earlyArtwork,
duration: song.duration,
isLoading: true,
isDabTrack: true, // Flag for UI to show DAB indicator
});
await dabMusicService.initialize();
const streamUrl = await dabMusicService.getStreamUrl(song.id);
if (streamUrl) {
playbackUrl = streamUrl;
// Parse format from URL to determine quality
const fmtMatch = streamUrl.match(/[?&]fmt=(\d+)/);
const fmt = fmtMatch ? fmtMatch[1] : null;
const formatMap = {
5: 'MP3 320kbps',
6: 'FLAC 16-bit/44.1kHz',
7: 'FLAC 24-bit/96kHz',
27: 'FLAC 24-bit/192kHz',
};
const dabQuality = formatMap[fmt] || 'FLAC';
updatedSong = {
...updatedSong,
url: streamUrl,
source: 'dab',
isDabTrack: true,
currentPlayingQuality: dabQuality, // Set actual FLAC quality
};
} else {
console.error('Failed to get DAB stream URL');
ToastAndroid.show('Failed to load DAB stream', ToastAndroid.SHORT);
return;
}
} catch (error) {
console.error('❌ Error fetching DAB stream:', error);
ToastAndroid.show('Error loading DAB stream', ToastAndroid.SHORT);
return;
}
} else {
// If song has multiple quality URLs, select based on setting
const resolveTrackUrl = (entries) => {
if (!Array.isArray(entries)) {
return '';
}
const preferred =
entries[qualityIndex] || entries[entries.length - 1] || entries[0];
if (!preferred || typeof preferred !== 'object') {
return '';
}
return preferred.url || preferred.link || preferred.uri || '';
};
if (song.downloadUrl && Array.isArray(song.downloadUrl)) {
const qualityIndex = await getIndexQuality();
playbackUrl = resolveTrackUrl(song.downloadUrl);
} else if (song.download_url && Array.isArray(song.download_url)) {
// Alternative format
const qualityIndex = await getIndexQuality();
playbackUrl = resolveTrackUrl(song.download_url);
}
}
// Validate song URL
if (!playbackUrl || typeof playbackUrl !== 'string') {
console.error('PlayOneSong: Invalid or missing song URL', song);
ToastAndroid.show('Cannot play song - invalid URL', ToastAndroid.SHORT);
return;
}
// Check if the song is a local file (has a path or isLocalMusic property)
const isLocalFile =
song.isLocalMusic || song.path || playbackUrl.startsWith('file://');
// If it's a local file, make sure the URL starts with file://
if (isLocalFile && !playbackUrl.startsWith('file://') && song.path) {
playbackUrl = `file://${song.path}`;
}
// Check network availability for non-local files - NON-BLOCKING
// Instead of blocking here, we let playback fail gracefully if offline
if (!isLocalFile) {
NetInfo.fetch()
.then((netInfo) => {
if (!netInfo.isConnected) {
}
})
.catch(() => {
/* ignore */
});
}
// NOTE: History tracking moved to AFTER TrackPlayer.play() to avoid blocking playback
// See below after TrackPlayer.play() call
// Create a copy of the song with the selected playback URL and quality info
// PERFORMANCE: Use cached quality index if available
let qualityIndex = cachedQualityIndex;
if (
qualityIndex === null ||
Date.now() - qualityCacheTimestamp > QUALITY_CACHE_TTL
) {
qualityIndex = await getIndexQuality();
cachedQualityIndex = qualityIndex;
qualityCacheTimestamp = Date.now();
}
const qualityNames = ['12kbps', '48kbps', '96kbps', '160kbps', '320kbps'];
const currentQuality = qualityNames[qualityIndex] || 'Unknown';
// Enhance artwork to highest quality for playing song (w500)
const enhancedArtwork = enhanceYTMusicArtwork(
updatedSong.artwork || updatedSong.image,
'playing'
);
const playingArtwork =
getPrimaryArtworkUrl(enhancedArtwork) ||
updatedSong.artwork ||
updatedSong.image;
// NORMALIZE METADATA (Critical for Saavn/Standard tracks)
// 1. Ensure Title
if (!updatedSong.title && updatedSong.name) {
updatedSong.title = String(updatedSong.name)
.replace(/"/g, '"')
.replace(/&/g, '&')
.replace(/'/g, "'");
}
if (!updatedSong.title) {
updatedSong.title = 'Unknown Title';
}
// 2. Ensure Artist
if (!updatedSong.artist) {
if (updatedSong.artists && updatedSong.artists.primary) {
updatedSong.artist = FormatArtist(updatedSong.artists.primary);
} else if (song.artists && song.artists.primary) {
updatedSong.artist = FormatArtist(song.artists.primary);
} else {
updatedSong.artist = 'Unknown Artist';
}
}
const songForPlayback = {
...updatedSong,
url: playbackUrl,
// CRITICAL: Preserve existing quality for YTMusic/Spotify/DAB tracks
// Only use Saavn quality setting if no quality was already set by stream handler
currentPlayingQuality:
updatedSong.currentPlayingQuality || currentQuality,
artwork: playingArtwork, // Use enhanced w500 quality
// Store original full name for lyrics search (not truncated for display)
originalTitle:
song.name || song.title || updatedSong.name || updatedSong.title,
};
await TrackPlayer.reset();
await TrackPlayer.add([songForPlayback]);
await TrackPlayer.play();
// NON-BLOCKING: Start history tracking AFTER playback begins
// Uses InteractionManager to run after all UI interactions complete,
// preventing any lag, hangs, or unresponsive UI from file I/O operations
InteractionManager.runAfterInteractions(() => {
historyManager
.startTracking(song)
.catch((err) =>
console.error('HistoryManager: Background tracking error:', err)
);
});
// Signal that this is a single song playback (enable auto-recommendations)
DeviceEventEmitter.emit('playback-mode-changed', { isPlaylist: false });
// CORRECT FLOW: Load initial recommendations immediately after playback starts
// 1. Song plays -> 2. Recommendations API called -> 3. Songs added to queue
// 4. Monitor set up for refill when 5 songs left
// NON-BLOCKING: Use InteractionManager for proper deferral (better than setTimeout)
// This waits for animations to complete before starting background work
InteractionManager.runAfterInteractions(async () => {
try {
// Determine source based on song type
// SPOTIFY SUPPORT: If this is a Spotify song mapped to YTMusic, use the YTMusic videoId
const isSpotifyMapped =
updatedSong.mappedFromSpotify && updatedSong.ytMusicVideoId;
const isYTId =
song.id &&
typeof song.id === 'string' &&
song.id.length === 11 &&
!song.isLocalMusic;
const isDABSong =
updatedSong.isDabTrack || updatedSong.source === 'dab';
// For DAB songs, use Last.fm-powered recommendations
if (isDABSong && lastFMService.isAuthenticated()) {
// Register the song as a seed for vibe tracking
dabRecommendationService.registerSongPlayed({
title: song.title || song.name,
artist: song.artist,
id: song.id,
});
// Fetch recommendations from Last.fm via DABRecommendationService
const dabRecommendations =
await dabRecommendationService.getRecommendations(20);
if (dabRecommendations && dabRecommendations.length > 0) {
// Filter out the currently playing song
const filteredRecs = dabRecommendations.filter(
(rec) => rec.id !== song.id
);
if (filteredRecs.length > 0) {
await AddSongsToQueue(filteredRecs);
// Trigger prefetch for N+1
setImmediate(() => {
const smartPrefetchManager =
require('./Utils/SmartPrefetchManager').default;
smartPrefetchManager._prefetchTrackAtIndex(1).catch((err) => {
if (!err.message?.includes("doesn't exist")) {
}
});
});
}
} else {
// Fall back to YTMusic recommendations using song title/artist search
}
// Start the continuous monitor for DAB to enable infinite playback
queueManager.startContinuousQueueMonitor(song.id);
return;
}
// For Spotify-mapped songs, use YTMusic recommendations via the mapped videoId
const source = isSpotifyMapped || isYTId ? 'ytmusic' : 'saavn';
const recommendationSongId = isSpotifyMapped
? updatedSong.ytMusicVideoId
: song.id;
// Load initial recommendations
const recommendations =
await queueManager.buildQueueFromRecommendations(
recommendationSongId,
source,
20
);
if (recommendations && recommendations.length > 0) {
// SAFETY: Filter out the currently playing song to prevent duplicates
// For Spotify-mapped songs, also check against the YTMusic videoId
const filteredRecs = recommendations.filter(
(rec) => rec.id !== song.id && rec.id !== recommendationSongId
);
if (filteredRecs.length > 0) {
await AddSongsToQueue(filteredRecs);
// 🎵 PREMIUM UX: Trigger initial prefetch for N+1 immediately after queue loads
// This ensures the next song is ready even faster
setImmediate(() => {
const smartPrefetchManager =
require('./Utils/SmartPrefetchManager').default;
smartPrefetchManager._prefetchTrackAtIndex(1).catch((err) => {
// Silence expected errors when queue isn't ready
if (!err.message?.includes("doesn't exist")) {
}
});
});
}
}
// Now start the monitor (it will only trigger refill when 5 songs remain)
queueManager.startContinuousQueueMonitor(recommendationSongId);
} catch (err) {
console.error('Error loading initial recommendations:', err);
// Still start monitor even if initial load fails
// Use ytMusicVideoId for Spotify-mapped songs
const fallbackSongId =
updatedSong.mappedFromSpotify && updatedSong.ytMusicVideoId
? updatedSong.ytMusicVideoId
: song.id;
queueManager.startContinuousQueueMonitor(fallbackSongId);
}
});
} catch (error) {
console.error('Error playing song:', error);
}
}
async function AddPlaylist(songs, startSongId = null) {
try {
// Validate songs array
if (!Array.isArray(songs) || songs.length === 0) {
console.error('Invalid songs array provided to AddPlaylist');
return;
}
// Filter/Slice if startSongId is provided
let tracksToAdd = [...songs];
if (startSongId) {
const startIndex = songs.findIndex(
(s) => s.id === startSongId || s.videoId === startSongId
);
if (startIndex !== -1) {
tracksToAdd = songs.slice(startIndex);
} else {
console.warn(
`⚠️ Start song ID ${startSongId} not found in playlist, playing all`
);
}
}
// OPTIMISTIC UI: Emit early metadata for first song so mini player shows immediately
// This provides instant feedback while stream URL is being fetched
const firstSong = tracksToAdd[0];
if (firstSong) {
const earlyArtwork =
extractArtwork(firstSong) || firstSong.artwork || firstSong.image || '';
// Format artist properly - handle various data structures
let artistDisplay = firstSong.artist || 'Loading...';
if (!artistDisplay || artistDisplay === 'Loading...') {
if (
firstSong.artists?.primary &&
Array.isArray(firstSong.artists.primary)
) {
artistDisplay = FormatArtist(firstSong.artists.primary);
} else if (typeof firstSong.artists === 'string') {
artistDisplay = firstSong.artists;
} else if (firstSong.primaryArtists) {
artistDisplay = firstSong.primaryArtists;
}
}
DeviceEventEmitter.emit('song-loading-started', {
id: firstSong.id || firstSong.videoId,
title:
firstSong.title || firstSong.name || firstSong.song || 'Loading...',
artist: artistDisplay,
artwork: earlyArtwork,
image: earlyArtwork,
duration: firstSong.duration,
isLoading: true,
isPlaylist: true, // Flag to indicate playlist/album playback
});
}
// Get quality setting ONCE
const qualityIndex = await getIndexQuality();
const qualityNames = ['12kbps', '48kbps', '96kbps', '160kbps', '320kbps'];
const currentQuality = qualityNames[qualityIndex] || 'Unknown';
const albumId = tracksToAdd[0]?.albumId;
// Helper function to process single song (extracted to avoid code duplication)
const processSingleSong = async (song, index, isFirstSong = false) => {
let playbackUrl = song.url;
let updatedSong = { ...song, albumId: albumId || song.albumId };
// Check if this is a podcast episode - skip all stream processing
const isPodcast = song.isPodcast || song.type === 'podcast';
const isYouTubeSong =
!isPodcast &&
song.id &&
typeof song.id === 'string' &&
song.id.length === 11 &&
!song.isLocalMusic;
if (isYouTubeSong) {
if (isFirstSong) {
try {
const streamData = await youtubeStreamingService.getStreamUrl(
song.id
);
if (streamData && streamData.url) {
playbackUrl = streamData.url;
updatedSong = {
...updatedSong,
url: streamData.url,
headers: streamData.headers,
userAgent: streamData.headers?.['User-Agent'],
artwork: streamData.thumbnail || updatedSong.artwork,
duration: streamData.duration || updatedSong.duration,
title: streamData.title || updatedSong.title,
currentPlayingQuality: currentQuality,
};
}
} catch (error) {
console.error('Error fetching YouTube stream:', error.message);
}
} else {
// LAZY LOAD: Set placeholder URL
playbackUrl = `ytmusic://${song.id || song.videoId}`;
updatedSong._needsStream = true;
updatedSong.isYTMusic = true;
updatedSong.source = 'ytmusic';
updatedSong.sourceType = 'online';
updatedSong.url = playbackUrl;
updatedSong.currentPlayingQuality = currentQuality;
}
}
// Spotify tracks
else if (song.source === 'spotify' || song.spotifyId) {
if (isFirstSong) {
try {
const earlyArtwork =
extractArtwork(song) || song.artwork || song.image || '';
DeviceEventEmitter.emit('song-loading-started', {
id: song.id,
title: song.title || song.name || 'Loading...',
artist: song.artist || 'Finding on YTMusic...',
artwork: earlyArtwork,
image: earlyArtwork,
duration: song.duration,
isLoading: true,
isSpotifyMapping: true,
});
const YouTubeMusicService =
require('./Utils/YouTubeMusicService').default;
const ytMusicResult = await YouTubeMusicService.searchAndStream(
song.title || song.name,
song.artist || ''
);
if (ytMusicResult && ytMusicResult.url && !ytMusicResult.error) {
playbackUrl = ytMusicResult.url;
const isOpus = ytMusicResult.mimeType?.includes('webm');
const estimatedBitrate =
ytMusicResult.bitrate || (isOpus ? 148000 : 256000);
const bitrateKbps = Math.round(estimatedBitrate / 1000);
const codec = isOpus ? 'Opus' : 'AAC';
updatedSong = {
...updatedSong,
url: ytMusicResult.url,
headers: ytMusicResult.headers,
userAgent: ytMusicResult.headers?.['User-Agent'],
ytMusicVideoId: ytMusicResult.videoId,
mappedFromSpotify: true,
currentPlayingQuality: `${codec} ${bitrateKbps}kbps`,
};
} else {
console.error('❌ Failed to map first Spotify song to YTMusic');
}
} catch (error) {
console.error(
'Error mapping first Spotify playlist song:',
error.message
);
}
} else {
// LAZY LOAD: Set placeholder
playbackUrl = `spotify://${song.id || song.spotifyId}`;
updatedSong._needsStream = true;
updatedSong._needsSpotifyMapping = true;
updatedSong.source = 'spotify';
updatedSong.spotifyId = song.id || song.spotifyId;
updatedSong.sourceType = 'online';
updatedSong.url = playbackUrl;
updatedSong.currentPlayingQuality = currentQuality;
}
}
// DAB tracks
else if (
song.isDabTrack ||
song.source === 'dab' ||
(!isNaN(song.url) && String(song.url).length > 5)
) {
if (isFirstSong) {
try {
await dabMusicService.initialize();
const streamUrl = await dabMusicService.getStreamUrl(song.id);
if (streamUrl) {
playbackUrl = streamUrl;
const fmtMatch = streamUrl.match(/[?&]fmt=(\d+)/);
const fmt = fmtMatch ? fmtMatch[1] : null;
const formatMap = {
5: 'MP3 320kbps',
6: 'FLAC 16-bit/44.1kHz',
7: 'FLAC 24-bit/96kHz',
27: 'FLAC 24-bit/192kHz',
};
updatedSong = {
...updatedSong,
url: streamUrl,
source: 'dab',
isDabTrack: true,
currentPlayingQuality: formatMap[fmt] || 'FLAC',
};
}
} catch (error) {
console.error(
'Error fetching DAB stream for first song:',
error.message
);
}
} else {
playbackUrl = `dab://${song.id}`;
updatedSong._needsStream = true;
updatedSong._needsDabStream = true;
updatedSong.source = 'dab';
updatedSong.isDabTrack = true;
updatedSong.sourceType = 'online';
updatedSong.url = playbackUrl;
updatedSong.currentPlayingQuality = currentQuality;
}
} else {
// Standard file/download URL logic (Saavn, etc.)
if (song.downloadUrl && Array.isArray(song.downloadUrl)) {
const entry =
song.downloadUrl[qualityIndex] ||
song.downloadUrl[song.downloadUrl.length - 1] ||
song.downloadUrl[0];
updatedSong.url = entry?.url || entry?.link || song.url;
} else if (song.download_url && Array.isArray(song.download_url)) {
const entry =
song.download_url[qualityIndex] ||
song.download_url[song.download_url.length - 1] ||
song.download_url[0];
updatedSong.url = entry?.url || entry?.link || song.url;
}
playbackUrl = updatedSong.url;
}
const artworkUrl = extractArtwork(song) || extractArtwork(updatedSong);
let extractedArtist =
updatedSong.artist ||
song.artist ||
(typeof song.artists === 'string' ? song.artists : null) ||
song.primaryArtists ||
(song.artists?.primary ? FormatArtist(song.artists.primary) : null) ||
'Unknown Artist';
const normalizedSong = {
...updatedSong,
url: playbackUrl || updatedSong.url,
title: updatedSong.title || updatedSong.name || song.name || 'Unknown',
artist: extractedArtist,
artwork: artworkUrl,
image: artworkUrl,
currentPlayingQuality:
updatedSong.currentPlayingQuality || currentQuality,
// Store original full name for lyrics search (not truncated for display)
originalTitle:
song.name || song.title || updatedSong.name || updatedSong.title,
};
// SAFETY: Ensure URL exists
if (!normalizedSong.url) {
if (
song.source === 'spotify' ||
song.spotifyId ||
updatedSong._needsSpotifyMapping
) {
normalizedSong.url = `spotify://${
song.id || song.spotifyId || 'unknown'
}`;
normalizedSong._needsStream = true;
normalizedSong._needsSpotifyMapping = true;
normalizedSong.source = 'spotify';
} else if (
song.source === 'dab' ||
song.isDabTrack ||
updatedSong._needsDabStream
) {
normalizedSong.url = `dab://${song.id || 'unknown'}`;
normalizedSong._needsStream = true;
normalizedSong._needsDabStream = true;
normalizedSong.source = 'dab';
} else if (isYouTubeSong) {
normalizedSong.url = `ytmusic://${
song.id || song.videoId || 'unknown'
}`;
normalizedSong._needsStream = true;
} else {
return null; // Skip songs with no URL
}
}
return normalizedSong;
};
// ============================================================
// PHASE 1: Process only INITIAL BATCH for instant playback
// This prevents UI blocking by NOT processing all 89+ songs upfront
// ============================================================
const INITIAL_BATCH_SIZE = 20;
const initialTracks = tracksToAdd.slice(0, INITIAL_BATCH_SIZE);
const remainingTracks = tracksToAdd.slice(INITIAL_BATCH_SIZE);
// Process initial batch - only first song gets stream fetch
const initialProcessed = await Promise.all(
initialTracks.map((song, index) =>
processSingleSong(song, index, index === 0)
)
);
const validInitialSongs = initialProcessed.filter((song) => song !== null);
// Cleanup any previous progressive loading session
progressiveQueueLoader.cleanup();
// Start playback IMMEDIATELY with initial batch
await TrackPlayer.reset();
await TrackPlayer.add(validInitialSongs);
await TrackPlayer.play();
// CRITICAL: Emit queue-updated immediately so Context.Queue syncs
// This ensures queue panel shows songs even before progressive loading completes
DeviceEventEmitter.emit('queue-updated', {
count: validInitialSongs.length,
});
DeviceEventEmitter.emit('playback-mode-changed', { isPlaylist: true });
// ============================================================
// PROGRESSIVE LOADING: Use ProgressiveQueueLoader for remaining songs
// This uses threshold-based loading - adds batches when user approaches
// end of loaded songs, keeping UI responsive throughout playback
// ============================================================
if (remainingTracks.length > 0) {
// Initialize progressive loader with remaining tracks
// The loader will monitor track position and add batches as needed
progressiveQueueLoader
.initialize(
remainingTracks,
processSingleSong,
0 // Start from beginning of remainingTracks
)
.then((result) => {
if (result.success && result.initialBatch.length > 0) {
// Add the first batch from progressive loader immediately in background
InteractionManager.runAfterInteractions(async () => {
try {
await TrackPlayer.add(result.initialBatch);
DeviceEventEmitter.emit('queue-updated', {
count: validInitialSongs.length + result.initialBatch.length,
isProgressiveBatch: true,
});
} catch (err) {
console.error(
'❌ Error adding progressive batch:',
err.message
);
}
});
}
})
.catch((err) => {
console.error('❌ ProgressiveQueueLoader init error:', err.message);
// Fallback: Load all remaining in old way if progressive loader fails
InteractionManager.runAfterInteractions(async () => {
try {
const BATCH_SIZE = 25;
for (let i = 0; i < remainingTracks.length; i += BATCH_SIZE) {
const batch = remainingTracks.slice(i, i + BATCH_SIZE);