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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
use config::{AppConfig, MusicService};
use dioxus::logger::tracing::Instrument;
use dioxus::{logger::tracing, prelude::*};
use player::engine::{SourceFactory, Transition};
use player::player::{LoadArgs, NowPlayingMeta, Player};
use reader::Track;
use std::sync::Arc;
use std::time::Duration;
use utils;
use crate::playback_ref::{PlaybackItemRef, ResolvedStreamRef};
use crate::scrobble_scheduler::{self, ScrobbleOptions};
use player::decoder;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum LoopMode {
None,
Queue,
Track,
}
/// What the UI intends to be playing. The `token` is the engine session token;
/// event consumers filter by it, which is what lets one signal replace the old
/// three-way cancellation (task cancel + engine cancel + generation bump).
#[derive(Clone, Copy, PartialEq, Debug)]
pub(crate) enum PlaybackIntent {
Stopped,
/// `from_token`: the session still playing during a crossfade resolve — a
/// failed or reverted crossfade falls back to it.
Loading {
token: u64,
idx: usize,
crossfade: bool,
from_token: u64,
},
Committed {
token: u64,
},
}
impl PlaybackIntent {
pub(crate) fn token(self) -> u64 {
match self {
Self::Stopped => 0,
Self::Loading { token, .. } | Self::Committed { token } => token,
}
}
pub(crate) fn is_loading(self) -> bool {
matches!(self, Self::Loading { .. })
}
}
impl LoopMode {
pub fn next(&self) -> Self {
match self {
LoopMode::None => LoopMode::Queue,
LoopMode::Queue => LoopMode::Track,
LoopMode::Track => LoopMode::None,
}
}
}
#[derive(Clone, Copy)]
pub struct PlayerController {
pub player: Signal<Player>,
pub is_playing: Signal<bool>,
/// Derived from the intent (plus the browse spinner) — read-only, so it
/// can't be left stuck by a cancel path that forgets to clear it.
pub is_loading: Memo<bool>,
pub history: Signal<Vec<usize>>,
pub queue: Signal<Vec<Track>>,
pub shuffle: Signal<bool>,
pub shuffle_order: Signal<Vec<usize>>,
pub loop_mode: Signal<LoopMode>,
pub current_queue_index: Signal<usize>,
pub current_song_title: Signal<String>,
pub current_song_artist: Signal<String>,
pub current_song_album: Signal<String>,
pub current_song_khz: Signal<u32>,
pub current_song_bitrate: Signal<u16>,
pub current_song_duration: Signal<u64>,
pub current_song_progress: Signal<u64>,
/// Byte ranges already fetched for the active network track. The UI draws
/// these behind playback position, like a browser media seek bar.
pub buffered_ranges: Signal<Vec<BufferedRange>>,
buffer_progress_tx: Signal<tokio::sync::mpsc::UnboundedSender<BufferProgressEvent>>,
pub current_song_cover_url: Signal<String>,
pub current_track_snapshot: Signal<Option<Track>>,
pub volume: Signal<f32>,
pub config: Signal<AppConfig>,
/// Storage handle (in a `Signal` so the controller stays `Copy`) — used by
/// the still-`Db`-taking factories (`local`/`for_track`) the player calls.
pub db: Signal<db::Db>,
/// The cached active [`MediaSource`](::server::source::ActiveSource) — the
/// player reads this shared handle to resolve streams instead of rebuilding
/// the source (and its HTTP client) on every play/skip.
pub active_source: Signal<::server::source::ActiveSource>,
pub(crate) intent: Signal<PlaybackIntent>,
/// Monotonic session-token allocator (0 = none).
pub(crate) next_token: Signal<u64>,
/// The current token as a plain `Signal` (not a memo) so the scrobble
/// scheduler can `origin_scope` off it.
pub(crate) current_token: Signal<u64>,
/// The token a crossfade last armed for; cleared on seek so a fresh fade
/// can arm at the outgoing track's real end.
pub(crate) armed_transition: Signal<Option<u64>>,
/// Discover tiles want the spinner shown synchronously on click, before any
/// load intent exists; folded into `is_loading`, cleared by `set_intent`.
pub browse_loading: Signal<bool>,
pub(crate) pending_resume: Signal<Option<PendingResumeState>>,
pub pending_crossfade_ui: Signal<Option<PendingCrossfadeUiState>>,
pub radio_task: Signal<Option<dioxus_core::Task>>,
/// The in-flight load pipeline (resolve → source factory → engine Load).
/// Starting a new transition cancels the previous one, so a superseded
/// load can never write back stale state.
pub(crate) load_task: Signal<Option<dioxus_core::Task>>,
pub station_registry: Signal<radio::registry::StationRegistry>,
/// User-visible playback error. Set when something needs the user's
/// attention (expired YT cookies, a failed stream resolve, …).
/// Rendered as a banner by whoever subscribes — currently the
/// settings popup error sink mirrors it on next open.
pub playback_error: Signal<Option<String>>,
/// The Spotify playback host (a browser tab running the Web Playback SDK),
/// lazily started on the first Spotify play. `None` until then. Spotify audio
/// plays in the browser, not the Symphonia engine, so its transport is routed
/// here instead of to `player`.
pub spotify_host: Signal<Option<::server::spotify::host::SpotifyHost>>,
/// The SDK's Connect device id, set once the host reports `Ready`. Playback is
/// started against it via the Web API; the device picker hides it from the
/// remote-device list (it renders as the in-app entry).
pub spotify_device: Signal<Option<String>>,
/// A Spotify track URI waiting for the device to become ready (first play).
pub(crate) spotify_pending_uri: Signal<Option<String>>,
/// Whether the browser tab reported playback is allowed (autoplay probe or
/// the enable-playback click). Plays issued before this just storm autoplay
/// errors and can wedge the SDK, so the first play waits on it.
pub(crate) spotify_activated: Signal<bool>,
/// Spotify Connect device playback is routed to instead of the in-app SDK
/// device (`None`). While set, transport goes through the Web API and a
/// poll loop owns progress/auto-advance.
pub spotify_device_override: Signal<Option<String>>,
/// Millisecond-precision progress anchor for external playback: the last
/// reported position and when it arrived. Reads interpolate elapsed time on
/// top, so second-granular state ticks don't lag the lyric clock.
pub(crate) spotify_progress_anchor: Signal<Option<(u64, std::time::Instant)>>,
/// Whether a host launch is in flight — serializes rapid first plays so
/// they can't spawn multiple hosts (and browser tabs).
pub(crate) spotify_host_starting: Signal<bool>,
/// Latest Spotify start request, canceled when superseded.
pub(crate) spotify_start_task: Signal<Option<dioxus_core::Task>>,
/// Track id kopuz last asked Spotify to play, and when.
pub(crate) spotify_commanded: Signal<Option<(String, std::time::Instant)>>,
/// Whether the current track is playing through the Spotify host rather than
/// the engine — transport methods and the progress pump branch on this.
pub(crate) external_active: Signal<bool>,
/// Set once the user explicitly picks a playback target from the device
/// panel (including "this app"). Suppresses automatic adoption of an
/// externally active Connect device so it can't override a deliberate choice.
pub(crate) spotify_device_chosen: Signal<bool>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PendingResumeState {
track_path: String,
progress_secs: u64,
}
/// A crossfade whose UI hasn't committed to the incoming track yet — held until
/// the engine's `TrackSwitched`; a seek/prev before then reverts to `from_token`.
#[derive(Clone, Copy, Debug)]
pub struct PendingCrossfadeUiState {
pub next_idx: usize,
pub to_token: u64,
pub from_token: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BufferedRange {
pub start: u64,
pub end: u64,
pub total: u64,
}
#[derive(Clone, Copy, Debug)]
struct BufferProgressEvent {
token: u64,
start: u64,
end: u64,
total: Option<u64>,
}
fn merge_buffered_range(ranges: &mut Vec<BufferedRange>, incoming: BufferedRange) {
if incoming.total == 0 || incoming.start >= incoming.end {
return;
}
if ranges
.first()
.is_some_and(|range| range.total != incoming.total)
{
ranges.clear();
}
ranges.push(BufferedRange {
end: incoming.end.min(incoming.total),
..incoming
});
ranges.sort_unstable_by_key(|range| range.start);
let mut merged: Vec<BufferedRange> = Vec::with_capacity(ranges.len());
for range in ranges.drain(..) {
if let Some(previous) = merged.last_mut()
&& range.start <= previous.end
{
previous.end = previous.end.max(range.end);
continue;
}
merged.push(range);
}
*ranges = merged;
}
impl PlayerController {
fn buffer_progress_callback(&self, token: u64) -> utils::stream_buffer::BufferProgressCallback {
let progress_tx = self.buffer_progress_tx.peek().clone();
Arc::new(move |start, end, total| {
let _ = progress_tx.send(BufferProgressEvent {
token,
start,
end,
total,
});
})
}
fn track_key(track: &Track) -> String {
track.id.uid().to_string()
}
pub(crate) fn shift_indices_at_or_after(indices: &mut [usize], at: usize, by: usize) {
for idx in indices {
if *idx >= at {
*idx += by;
}
}
}
/// Retrieves the queue index for a given index, taking into account the shuffle state.
pub fn get_queue_index(&self, idx: usize) -> Option<usize> {
if *self.shuffle.peek() {
self.shuffle_order.peek().get(idx).cloned()
} else {
Some(idx)
}
}
/// Retrieves the current track index in the queue, taking into account the shuffle state.
/// Useful when it is not required to be a reactive value
pub fn get_current_track_index(&self) -> Option<usize> {
self.get_queue_index(*self.current_queue_index.peek())
}
/// Retrieves the track at a given index in the queue, taking into account the shuffle state.
pub fn get_track_at(&self, idx: usize) -> Option<Track> {
let idx = self.get_queue_index(idx)?;
self.queue.peek().get(idx).cloned()
}
/// Retrieves the current track
pub fn current_track(&self) -> Option<Track> {
self.get_track_at(*self.current_queue_index.peek())
}
/// Stamp a resolved stream's probed duration/bitrate (YT ships them late)
/// onto the queue Track and, if it's still the shown track, the live
/// signals — in a single `queue.write()`.
fn stamp_probed_stream_info(
&mut self,
phys_idx: Option<usize>,
idx: usize,
duration_secs: Option<u64>,
bitrate: Option<u32>,
) {
let duration = duration_secs.filter(|s| *s > 0);
let kbps = bitrate.map(|bps| (bps / 1000) as u16);
if let Some(p) = phys_idx
&& let Some(track) = self.queue.write().get_mut(p)
{
if let Some(secs) = duration {
track.duration = secs;
}
if let Some(k) = kbps {
track.bitrate = k;
}
}
if *self.current_queue_index.peek() == idx {
if let Some(secs) = duration {
self.current_song_duration.set(secs);
}
if let Some(k) = kbps {
self.current_song_bitrate.set(k);
}
}
}
/// Follow a radio station's live now-playing metadata into the UI signals
/// for as long as it plays.
///
/// `icy_rx` carries `StreamTitle` updates from the audio connection. Only
/// wired up for stations without a live (REST/WebSocket) provider, so the
/// two sources never fight.
fn start_radio_metadata(
&mut self,
station_id: String,
stream_id: String,
icy_rx: Option<tokio::sync::watch::Receiver<utils::icy::IcyMeta>>,
) {
let Some(provider) = self.station_registry.read().create_provider(&station_id) else {
tracing::warn!("[radio] no metadata provider for station: {station_id}");
return;
};
// Station artwork / name fallbacks for song updates without their own.
let station_cover: Option<String> =
self.station_registry
.read()
.get(&station_id)
.and_then(|m| match &m.metadata {
Some(radio::manifest::MetadataSourceDef::Static(s)) => s.cover_url.clone(),
_ => None,
});
let station_name: Option<String> = self
.station_registry
.read()
.get(&station_id)
.map(|m| m.name.clone())
.filter(|n| !n.trim().is_empty());
let mut current_song_title = self.current_song_title;
let mut current_song_artist = self.current_song_artist;
let mut current_song_album = self.current_song_album;
let mut current_song_cover_url = self.current_song_cover_url;
let task = spawn(async move {
use radio::provider::RadioMetadataProvider;
let mut rx = provider.start(&stream_id);
// Signals are Copy: each loop gets its own mutable handle.
let mut icy_song_title = current_song_title;
let mut icy_song_artist = current_song_artist;
let mut icy_song_cover = current_song_cover_url;
let provider_loop = async {
while let Some(meta) = rx.recv().await {
current_song_title.set(meta.title.clone());
current_song_artist.set(meta.artist.clone());
current_song_album.set(meta.station.clone());
current_song_cover_url.set(meta.cover_url.unwrap_or_default());
}
};
let icy_loop = async {
let Some(mut icy_rx) = icy_rx else { return };
while icy_rx.changed().await.is_ok() {
let meta = icy_rx.borrow_and_update().clone();
if meta.title.trim().is_empty() {
continue;
}
let (artist, title) = utils::icy::split_artist_title(&meta.title);
icy_song_title.set(title);
// No artist in title: show station.
if let Some(artist) = artist.or_else(|| station_name.clone()) {
icy_song_artist.set(artist);
}
let cover = meta
.cover_url
.or_else(|| station_cover.clone())
.unwrap_or_default();
icy_song_cover.set(cover);
}
};
tokio::join!(provider_loop, icy_loop);
});
self.radio_task.set(Some(task));
}
/// Download a server track's cover to a temp file and hand the OS media
/// controls its local path (they need a path, not a URL). No-ops if `token`
/// is superseded before the download finishes.
fn spawn_server_artwork_fetch(&self, cover_url: String, track: Track, token: u64) {
let mut player = self.player;
let current_token = self.current_token;
spawn(
async move {
if let Ok(response) = reqwest::get(&cover_url).await
&& let Ok(bytes) = response.bytes().await
{
let file_path = std::env::temp_dir()
.join(format!("kopuz_cover_{}.jpg", rand::random::<u64>()));
if tokio::fs::write(&file_path, bytes).await.is_ok()
&& *current_token.read() == token
{
player.write().update_metadata(NowPlayingMeta {
title: track.title,
artist: track.artist,
album: track.album,
duration: std::time::Duration::from_secs(track.duration),
artwork: Some(file_path.to_string_lossy().to_string()),
});
}
}
}
.instrument(tracing::info_span!("player.cover_fetch")),
);
}
fn cover_url_for_track(&self, track: &Track) -> String {
// Dispatch on the track's own source through the cover seam. Every track
// self-describes its cover (a local row's path is projected from its album
// by the DB read layer), so this sync path needs no album lookup.
::server::cover::track(&self.config.read(), track, 800)
.map(|cover| cover.as_ref().to_string())
.unwrap_or_else(|| utils::default_cover_url().as_ref().to_string())
}
pub(crate) fn clear_current_track_metadata(&mut self) {
self.current_song_title.set(String::new());
self.current_song_artist.set(String::new());
self.current_song_album.set(String::new());
self.current_song_khz.set(0);
self.current_song_bitrate.set(0);
self.current_song_duration.set(0);
self.current_song_progress.set(0);
self.buffered_ranges.set(Vec::new());
self.current_song_cover_url.set(String::new());
self.current_track_snapshot.set(None);
}
pub(crate) fn hydrate_current_track_metadata(&mut self, idx: usize, progress_secs: u64) {
if let Some(track) = self.get_track_at(idx) {
let progress_secs = progress_secs.min(track.duration);
self.current_queue_index.set(idx);
self.current_song_title.set(track.title.clone());
self.current_song_artist.set(track.artist.clone());
self.current_song_album.set(track.album.clone());
self.current_song_khz.set(track.khz);
self.current_song_bitrate.set(track.bitrate);
self.current_song_duration.set(track.duration);
self.current_song_progress.set(progress_secs);
self.current_song_cover_url
.set(self.cover_url_for_track(&track));
self.current_track_snapshot.set(Some(track));
} else {
self.current_queue_index.set(0);
self.clear_current_track_metadata();
}
}
/// Adopt a Spotify Connect track started elsewhere. Upsert it into the
/// queue and select its logical position so the normal queue-state save can
/// restore it after restart instead of falling back to the last track
/// clicked in kopuz.
///
/// Under shuffle, Spotify reports every track change — including the ones
/// kopuz itself commanded — so reshuffling on all of them tears up the run
/// mid-listen. A track the queue already held keeps its permutation
/// position; only a track the queue has never seen is a genuine pick from
/// another client, and that one starts a new run, because leaving a
/// just-appended index in the old permutation puts it at the end and makes
/// Next stop immediately.
pub(crate) fn hydrate_external_track_metadata(&mut self, track: Track, progress_secs: u64) {
let queued_idx = self
.queue
.peek()
.iter()
.position(|queued| queued.id == track.id);
let physical_idx = match queued_idx {
Some(idx) => {
self.queue.write()[idx] = track;
idx
}
None => {
let idx = self.queue.peek().len();
self.queue.write().push(track);
idx
}
};
let logical_idx = if *self.shuffle.peek() {
match queued_idx.and_then(|_| self.shuffle_position_of(physical_idx)) {
Some(position) => position,
None => {
self.current_queue_index.set(physical_idx);
self.rebuild_shuffle_order();
0
}
}
} else {
physical_idx
};
self.hydrate_current_track_metadata(logical_idx, progress_secs);
}
/// Replace the provisional one-track external queue with the complete
/// Spotify playlist/album once its context finishes loading.
pub(crate) fn hydrate_external_context(
&mut self,
tracks: Vec<Track>,
current_track_id: &str,
progress_secs: u64,
) {
let Some(physical_idx) = tracks
.iter()
.position(|track| track.id.key() == current_track_id)
else {
return;
};
self.queue.set(tracks);
self.history.write().clear();
self.current_queue_index.set(physical_idx);
let logical_idx = if *self.shuffle.peek() {
self.rebuild_shuffle_order();
0
} else {
physical_idx
};
self.hydrate_current_track_metadata(logical_idx, progress_secs);
}
fn pending_resume_seek(&self, track: &Track) -> (Option<u64>, bool) {
let pending = self.pending_resume.read().clone();
let restore_seek_secs = pending.as_ref().and_then(|pending| {
if pending.track_path == Self::track_key(track) {
Some(pending.progress_secs.min(track.duration))
} else {
None
}
});
(restore_seek_secs, pending.is_some())
}
pub(crate) fn clear_pending_crossfade_ui(&mut self) {
self.pending_crossfade_ui.set(None);
}
pub(crate) fn schedule_pending_crossfade_ui(
&mut self,
next_idx: usize,
to_token: u64,
from_token: u64,
) {
self.pending_crossfade_ui.set(Some(PendingCrossfadeUiState {
next_idx,
to_token,
from_token,
}));
}
/// Commit the deferred crossfade UI to the incoming track, on the engine's
/// `TrackSwitched` for the switch we armed.
pub(crate) fn commit_transition(&mut self, token: u64) {
let Some(pending) = *self.pending_crossfade_ui.peek() else {
return;
};
if pending.to_token != token {
return;
}
self.pending_crossfade_ui.set(None);
let pos = self.player.peek().get_position().as_secs();
self.hydrate_current_track_metadata(pending.next_idx, pos);
// Push the incoming track's now-playing metadata, deferred from load.
self.player.peek().commit_now_playing();
}
/// Undo an armed crossfade at either stage — load still resolving (cancel
/// it) or fade running (drop the deferred UI; the caller's tokened seek
/// revives the outgoing session engine-side). Pops the history entry the arm
/// pushed and reverts the intent to the outgoing token, returned on success.
pub(crate) fn revert_transition(&mut self) -> Option<u64> {
// Read both stage markers out before any signal write below.
let fading = (*self.pending_crossfade_ui.peek()).map(|p| p.from_token);
let resolving = match *self.intent.peek() {
PlaybackIntent::Loading {
crossfade: true,
from_token,
..
} => Some(from_token),
_ => None,
};
let from_token = if let Some(from_token) = fading {
self.clear_pending_crossfade_ui();
from_token
} else if let Some(from_token) = resolving {
self.cancel_load_task();
from_token
} else {
return None;
};
self.armed_transition.set(None);
let idx = *self.current_queue_index.peek();
self.history.with_mut(|h| {
if h.last() == Some(&idx) {
h.pop();
}
});
self.set_intent(PlaybackIntent::Committed { token: from_token });
Some(from_token)
}
pub(crate) fn set_pending_resume_for_track(&mut self, track: &Track, progress_secs: u64) {
self.pending_resume.set(Some(PendingResumeState {
track_path: Self::track_key(track),
progress_secs: progress_secs.min(track.duration),
}));
}
pub(crate) fn cancel_load_task(&mut self) {
if let Some(task) = self.load_task.take() {
task.cancel();
}
self.player.peek().cancel_pending_load();
}
pub(crate) fn allocate_token(&mut self) -> u64 {
let token = self.next_token.peek().wrapping_add(1);
self.next_token.set(token);
token
}
/// The one writer of playback intent — keeps the `current_token` mirror and
/// the browse spinner in step so no cancel path leaves them stale.
pub(crate) fn set_intent(&mut self, next: PlaybackIntent) {
self.browse_loading.set(false);
self.current_token.set(next.token());
self.intent.set(next);
}
/// Banner + stay on the visible track (never auto-advance): a failed
/// crossfade reverts to the still-playing outgoing session; a failed
/// immediate load leaves its already-hydrated track shown, paused. Ignored
/// if a newer load already superseded `token`.
pub(crate) fn fail_load(&mut self, token: u64, error: impl std::fmt::Display) {
let intent = *self.intent.peek();
if intent.token() != token {
return;
}
self.playback_error
.set(Some(format!("Couldn't load this track:\n{error}")));
self.buffered_ranges.set(Vec::new());
match intent {
PlaybackIntent::Loading {
crossfade: true,
from_token,
..
} => {
self.set_intent(PlaybackIntent::Committed { token: from_token });
}
_ => {
self.set_intent(PlaybackIntent::Stopped);
self.is_playing.set(false);
}
}
}
/// The current Spotify OAuth access token, if Spotify is the active server.
pub(crate) fn spotify_access(&self) -> Option<String> {
let cfg = self.config.peek();
let server = cfg.server.as_ref()?;
if server.service != MusicService::Spotify {
return None;
}
let packed = server.access_token.clone()?;
let access = ::server::spotify::auth::unpack_token(&packed).0;
(!access.is_empty()).then_some(access)
}
/// Start the browser playback host if it isn't running yet (first Spotify play).
fn ensure_spotify_host(&mut self) {
if self.spotify_host.peek().is_some() || *self.spotify_host_starting.peek() {
return;
}
let Some(access) = self.spotify_access() else {
return;
};
let browser = self.config.peek().spotify_browser.clone();
self.spotify_host_starting.set(true);
let mut host_sig = self.spotify_host;
let mut starting = self.spotify_host_starting;
let mut error = self.playback_error;
let mut external = self.external_active;
let mut playing = self.is_playing;
let mut pending = self.spotify_pending_uri;
spawn(async move {
match ::server::spotify::host::SpotifyHost::start(access, browser).await {
Ok(host) => host_sig.set(Some(host)),
Err(e) => {
tracing::warn!(error = %e, "spotify host failed to start");
error.set(Some(e));
if *external.peek() {
external.set(false);
playing.set(false);
pending.set(None);
}
}
}
starting.set(false);
});
}
/// Forget a closed Spotify browser host. The next explicit play reads the
/// current browser setting and starts a fresh host; closing a background
/// tab must not immediately reopen a browser the user no longer wants.
pub(crate) fn spotify_browser_disconnected(&mut self) {
self.spotify_host.set(None);
self.spotify_device.set(None);
self.spotify_activated.set(false);
if self.spotify_device_override.peek().is_some() {
return;
}
self.spotify_pending_uri.set(None);
self.spotify_commanded.set(None);
if let Some(task) = self.spotify_start_task.take() {
task.cancel();
}
self.spotify_progress_anchor.set(None);
self.external_active.set(false);
self.is_playing.set(false);
}
/// The Spotify access token for UI data fetches (Connect device list).
pub fn spotify_access_token(&self) -> Option<String> {
self.spotify_access()
}
/// Route Spotify playback to a Connect device (`None` = the in-app SDK
/// device), transferring the live session over when one is active.
pub fn spotify_select_device(&mut self, device_id: Option<String>) {
self.spotify_device_chosen.set(true);
self.spotify_device_override.set(device_id.clone());
if !*self.external_active.peek() {
return;
}
let Some(access) = self.spotify_access() else {
return;
};
let Some(target) = device_id.or_else(|| self.spotify_device.peek().clone()) else {
return;
};
let play = *self.is_playing.peek();
spawn(async move {
if let Err(e) = ::server::spotify::api::transfer_playback(&access, &target, play).await
{
tracing::warn!(error = %e, "spotify device transfer failed");
}
});
}
/// Adopt a Connect device that is already playing on its own — e.g. the user
/// started it from the Spotify app, possibly before this app launched.
/// Routes transport to it and flips `external_active` so the player-state
/// poller begins syncing progress and play/pause state, without transferring
/// or restarting the live session. No-op when the feature is disabled, a
/// target is already active, or the user has made an explicit choice.
pub fn spotify_adopt_external(&mut self, device_id: String) {
if *self.spotify_device_chosen.peek()
|| self.spotify_device_override.peek().is_some()
|| !self.config.peek().spotify_prefer_active_device
{
return;
}
self.spotify_device_override.set(Some(device_id));
self.external_active.set(true);
}
pub(crate) fn spotify_transport_pause(&mut self) {
if self.spotify_device_override.peek().is_some() {
if let Some(access) = self.spotify_access() {
spawn(async move {
let _ = ::server::spotify::api::player_pause(&access).await;
});
}
} else if let Some(host) = self.spotify_host.peek().clone() {
host.pause();
}
}
pub(crate) fn spotify_transport_resume(&mut self) {
if self.spotify_device_override.peek().is_some() {
if let Some(access) = self.spotify_access() {
spawn(async move {
let _ = ::server::spotify::api::player_resume(&access).await;
});
}
} else if let Some(host) = self.spotify_host.peek().clone() {
host.resume();
}
}
/// Begin playing a Spotify track id. A chosen Connect device gets the URI
/// directly; otherwise ensure the host and start it on the SDK device — or
/// stash it as pending until the device is ready AND the tab has confirmed
/// playback is allowed. The pump fires the pending URI on those events.
pub(crate) fn start_spotify_uri(&mut self, access: String, device: String, uri: String) {
if let Some(task) = self.spotify_start_task.take() {
task.cancel();
}
let mut error = self.playback_error;
let task = spawn(async move {
tokio::time::sleep(Duration::from_millis(125)).await;
if let Err(e) = ::server::spotify::api::start_playback(&access, &device, &[uri]).await {
tracing::warn!(error = %e, "spotify start_playback failed");
error.set(Some(e));
}
});
self.spotify_start_task.set(Some(task));
}
/// True while Spotify is still reporting a track other than the one kopuz
/// last commanded. The SDK keeps emitting state for the outgoing track for
/// a beat after a skip, and applying it flashes the previous song back over
/// the one kopuz already showed. Self-clearing: the first report that
/// matches, or the window lapsing, drops the guard so a track genuinely
/// started from another client is never held back for long.
pub(crate) fn spotify_report_is_stale(&mut self, reported: Option<&str>) -> bool {
let Some((commanded, at)) = self.spotify_commanded.peek().clone() else {
return false;
};
if at.elapsed() > Duration::from_secs(3) || reported == Some(commanded.as_str()) {
self.spotify_commanded.set(None);
return false;
}
true
}
fn spotify_play(&mut self, item_id: &str, track: &Track) {
let uri = format!("spotify:track:{item_id}");
self.spotify_commanded
.set(Some((item_id.to_string(), std::time::Instant::now())));
let override_device = self.spotify_device_override.peek().clone();
if let Some(device) = override_device {
if let Some(access) = self.spotify_access() {
self.spotify_pending_uri.set(None);
self.start_spotify_uri(access, device, uri);
}
return;
}
self.ensure_spotify_host();
if let Some(host) = self.spotify_host.peek().clone() {
let artwork = self.current_song_cover_url.peek().clone();
host.set_now_playing(track, &artwork);
}
if !*self.spotify_activated.peek() {
self.spotify_pending_uri.set(Some(uri));
return;
}
let sdk_device = self.spotify_device.peek().clone();
match (self.spotify_access(), sdk_device) {
(Some(access), Some(device)) => {
self.spotify_pending_uri.set(None);
self.start_spotify_uri(access, device, uri);
}
_ => self.spotify_pending_uri.set(Some(uri)),
}
}
/// Stop external (Spotify) playback and hand control back to the engine.
/// Also drops any deferred play so a later `Ready`/`Activated` event can't
/// start an obsolete track over whatever plays next.
pub(crate) fn stop_external_playback(&mut self) {
if !*self.external_active.peek() {
return;
}
self.spotify_pending_uri.set(None);
self.spotify_commanded.set(None);
if let Some(task) = self.spotify_start_task.take() {
task.cancel();
}
self.spotify_transport_pause();
self.external_active.set(false);
}
/// Seek the current track. All progress-bar / lyric scrubbers route here.
pub fn seek(&mut self, time: Duration) {
if *self.external_active.peek() {
if self.spotify_device_override.peek().is_some() {
if let Some(access) = self.spotify_access() {
let ms = time.as_millis() as u64;
spawn(async move {
let _ = ::server::spotify::api::player_seek(&access, ms).await;
});
}
} else if let Some(host) = self.spotify_host.peek().clone() {
host.seek(time.as_millis() as u64);
}
self.spotify_progress_anchor
.set(Some((time.as_millis() as u64, std::time::Instant::now())));
self.current_song_progress.set(time.as_secs());
return;
}
// The scrub targets the visible track. During a crossfade that's the
// outgoing session: revert the armed transition and seek it by its own
// token, so a fade that just completed can't misdirect the seek.
if let Some(from_token) = self.revert_transition() {
self.player.peek().seek_for_session(time, from_token);
} else {
self.player.peek().seek(time);
}
self.current_song_progress.set(time.as_secs());
}
pub fn displayed_progress_secs_f64(&self) -> f64 {
if *self.external_active.peek() {
if let Some((ms, at)) = *self.spotify_progress_anchor.peek() {
let mut pos = ms as f64 / 1000.0;
if *self.is_playing.peek() {
pos += at.elapsed().as_secs_f64();
}
let dur = *self.current_song_duration.peek();
if dur > 0 {
pos = pos.min(dur as f64);
}
return pos;
}
return *self.current_song_progress.peek() as f64;
}
// Mid-crossfade the bar shows the outgoing (fading) track's live position.
if self.pending_crossfade_ui.peek().is_some()
&& let Some(fading) = self.player.peek().fading_position()
{
return fading.as_secs_f64();
}
self.player.peek().get_position().as_secs_f64()
}
/// Remap a queue index after moving one item within the queue.
///
/// `index` is the position to remap, `from` is the original position of the moved item,
/// and `to` is its destination after the move.
///
/// Returns the new position for `index` after applying the move:
/// - if `index == from`, this is the moved item itself, so it now lives at `to`
/// - if the item moved forward (`from < to`), every item that was between `from + 1`
/// and `to` shifts left by one slot
/// - if the item moved backward (`to < from`), every item that was between `to`
/// and `from - 1` shifts right by one slot
/// - all other indices are unaffected
pub(crate) fn remap_queue_index(index: usize, from: usize, to: usize) -> usize {
if index == from {
to
} else if from < to && index > from && index <= to {
index - 1
} else if to < from && index >= to && index < from {
index + 1
} else {
index
}
}
pub fn should_crossfade(&self) -> bool {
self.config.peek().crossfade_seconds > 0
&& *self.is_playing.peek()
&& self.player.peek().can_resume()
}
pub fn has_next_track(&self) -> bool {
// Delegates to the same predicate the advance uses, so the crossfade
// arm can't fire when the advance would instead end the queue.
Self::has_following_track(
*self.current_queue_index.peek(),
self.queue.peek().len(),
*self.loop_mode.peek(),
)
}
pub fn play_track(&mut self, idx: usize) {
let current_idx = *self.current_queue_index.peek();
self.history.with_mut(|h| {
if h.last() != Some(¤t_idx) {
h.push(current_idx);
}
});
if *self.shuffle.peek() {
// workaround: shuffle enable/disable needed to play the selected track when shuffle is enabled
self.shuffle.set(false);
self.play_track_no_history_without_crossfade(idx);
self.shuffle.set(true);
self.rebuild_shuffle_order();
} else {
self.play_track_no_history_without_crossfade(idx);
}
}
pub fn play_track_no_history(&mut self, idx: usize) {
self.play_track_no_history_with_transition(idx, false);
}
pub fn play_track_no_history_without_crossfade(&mut self, idx: usize) {
self.play_track_no_history_with_transition(idx, false);
}
#[tracing::instrument(name = "player.transition", skip(self), fields(idx, crossfade = allow_crossfade))]
pub(crate) fn play_track_no_history_with_transition(
&mut self,
idx: usize,
allow_crossfade: bool,
) {
// ── Phase 1: classify — no mutation (bar stale-cache eviction), so
// every early bail below leaves no half-set loading state behind. ──
let Some(track) = self.get_track_at(idx) else {
return;
};
let path_str = track.id.uid().to_string();
let (restore_seek_secs, clear_pending_resume_on_success) = self.pending_resume_seek(&track);
let use_crossfade = allow_crossfade
&& self.should_crossfade()
&& restore_seek_secs.is_none_or(|secs| secs == 0);
let crossfade_duration = Duration::from_secs(self.config.peek().crossfade_seconds as u64);
let item_ref = PlaybackItemRef::parse(&path_str);
let is_radio_item = item_ref.is_radio();
let is_server_item = item_ref.is_server();
let id = item_ref.primary_id().unwrap_or_default().to_string();
let stream_id = item_ref.stream_id().unwrap_or_default().to_string();
let is_spotify_item = track.id.service() == Some(MusicService::Spotify);
if !is_spotify_item {
self.stop_external_playback();
} else if self.spotify_access().is_some() {
self.playback_error.set(None);
self.cancel_radio_task();
self.cancel_load_task();
self.clear_pending_crossfade_ui();
self.player.peek().stop_for_transition();
let token = self.allocate_token();
self.set_intent(PlaybackIntent::Committed { token });
self.external_active.set(true);
self.spotify_progress_anchor
.set(Some((0, std::time::Instant::now())));
self.hydrate_current_track_metadata(idx, 0);
self.is_playing.set(true);
self.spotify_play(&id, &track);
scrobble_scheduler::schedule(
track.clone(),
Some(id.clone()),
self.config,
self.current_token,
token,
self.is_playing,
Some(self.active_source),
ScrobbleOptions::REMOTE_NATIVE,
self.db.peek().clone(),
);
return;
}
// ── classify the source ─────────────────────────────────────────
// Offline cache first (server items only).
let offline_path: Option<std::path::PathBuf> = if is_server_item {
let raw = self
.config
.read()
.offline_tracks
.get(&id)
.map(std::path::PathBuf::from)
.filter(|p| p.exists());
// Evict stale entries saved with the wrong ".audio"/".bin" fallback
if let Some(ref p) = raw {
let bad_ext = matches!(
p.extension().and_then(|e| e.to_str()),
Some("audio") | Some("bin")
);
if bad_ext {
let _ = std::fs::remove_file(p);
self.config.write().offline_tracks.remove(&id);
None
} else {
raw
}
} else {
raw
}
} else {
None
};
// Remote stream reference + synchronous cover URL for server/radio
// items that aren't cached offline. Streams resolve in the load task;
// only the cover is built here so artwork shows immediately on click.
// ICY titles only for stations without a live metadata provider.
let mut use_icy = false;
let remote_ref: Option<(String, String)> = if offline_path.is_some() {
None
} else if is_radio_item {
let registry = self.station_registry.read();
let station = registry.get(&id);
use_icy = station.is_some_and(|s| !s.has_live_metadata());
// Static cover/favicon so artwork shows from the first frame.
let cover = station
.and_then(|s| match &s.metadata {
Some(radio::manifest::MetadataSourceDef::Static(st)) => {
st.resolve(&stream_id).2.map(str::to_string)
}
_ => None,
})
.unwrap_or_default();
station
.and_then(|s| s.streams.iter().find(|str| str.id == stream_id))
.map(|s| s.url.clone())
.map(|stream_url| (stream_url, cover))
} else if is_server_item {
// Every server source resolves its stream async in the load task, so
// the ref is a pending marker; only the cover is built now, through
// the cover seam. No creds no longer bails silently — resolve_stream
// surfaces a real error instead.
if self.config.read().server.is_some() {
let cover_url = ::server::cover::track(&self.config.read(), &track, 800)
.map(|cover| cover.as_ref().to_string())
.unwrap_or_default();
Some((ResolvedStreamRef::pending_marker(&id), cover_url))
} else {
None
}
} else {
None
};
let local_path: Option<std::path::PathBuf> = if is_server_item || is_radio_item {
None
} else {
track.id.local_path().map(|p| p.to_path_buf())
};
// A server item with no server configured has nothing to resolve — stop
// silently, as the old sync path did.
if offline_path.is_none() && local_path.is_none() && remote_ref.is_none() {
return;
}
// ── Phase 2: commit — mutates state, so only past every bail above ──
// (Cancelling the prior load is just a resource optimization; the token
// is what guards correctness.)
self.playback_error.set(None);
self.cancel_radio_task();
self.cancel_load_task();
if !use_crossfade {
self.clear_pending_crossfade_ui();
}
let from_token = self.intent.peek().token();
let token = self.allocate_token();
self.set_intent(PlaybackIntent::Loading {
token,
idx,
crossfade: use_crossfade,
from_token,
});
self.buffered_ranges.set(Vec::new());
let cover_url: String = if offline_path.is_some() {
self.cover_url_for_track(&track)
} else if let Some((_, cover)) = &remote_ref {
cover.clone()
} else {
String::new()
};
let artwork = if is_server_item || is_radio_item {
Some(cover_url.clone())
} else {
// For a local track `track.cover` is its album-art file path
// (projected from the album by the DB read layer).
track.cover.clone()
};
// ── UI transition ───────────────────────────────────────────────
if !use_crossfade {
if is_server_item || is_radio_item {
// Deliberate UX: silence while a (possibly slow) load resolves.
// Pure local files switch seamlessly inside the engine instead.
self.player.peek().stop_for_transition();
self.is_playing.set(false);
}
self.hydrate_current_track_metadata(idx, restore_seek_secs.unwrap_or(0));
if is_server_item || is_radio_item {
self.current_song_cover_url.set(cover_url.clone());
}
}
// ── the load pipeline ───────────────────────────────────────────
// One cancellable task for every source kind: resolve the stream URL
// if needed, hand the engine a source factory (executed on its decode
// worker thread, so network buffering never blocks the UI), then apply
// the post-load bookkeeping once the engine confirms playback.
let mut ctrl = *self;
let phys_idx = self.get_queue_index(idx);
let station_id = id.clone();
let cached_item_id = id;
let task = spawn(
async move {
// ICY channel: tx goes to the stream download, rx to the
// metadata follower after load commits.
let (icy_tx, icy_rx) = if is_radio_item && use_icy {
let (tx, rx) = tokio::sync::watch::channel(utils::icy::IcyMeta::default());
(Some(tx), Some(rx))
} else {
(None, None)
};
let buffer_progress = (!is_radio_item)
.then(|| ctrl.buffer_progress_callback(token));
let factory: SourceFactory = if let Some(path) = local_path {
Box::new(move || decoder::open_file(&path).map_err(|e| e.to_string()))
} else if let Some(path) = offline_path {
// Cached server file: on open failure fall back to the live
// stream instead of failing. The resolve blocks on this
// task's runtime handle — legal on the decode worker.
let source = ctrl.active_source.peek().clone();
let rt_handle = tokio::runtime::Handle::current();
Box::new(move || match decoder::open_file(&path) {
Ok(parts) => Ok(parts),
Err(e) => {
tracing::warn!(error = %e, "cached file failed to open; falling back to the server stream");
let info = rt_handle
.block_on(source.resolve_stream(&cached_item_id))
.map_err(|e| e.to_string())?;
network_factory(
info.url,
info.format,
info.user_agent,
false,
None,
rt_handle.clone(),
buffer_progress.clone(),
)()
}
})
} else {
let (stream_ref, _) = remote_ref.expect("classified as remote above");
let (stream_url, yt_format, yt_user_agent) =
match ResolvedStreamRef::parse(&stream_ref) {
ResolvedStreamRef::Pending(item_id) => {
// The one genuinely per-source op: resolve the
// playable stream through the active source
// (a URL for Jellyfin/Subsonic, a deciphered
// stream for YT).
let source = ctrl.active_source.peek().clone();
match source.resolve_stream(item_id).await {
Ok(info) => {
ctrl.stamp_probed_stream_info(
phys_idx,
idx,
info.duration_secs,
info.bitrate,
);
(info.url, info.format, info.user_agent)
}
Err(e) => {
tracing::error!(error = %e, "stream URL resolve failed");
ctrl.fail_load(token, &e);
return;
}
}
}
ResolvedStreamRef::SoundCloudHls(_) | ResolvedStreamRef::Direct(_) => {
(stream_ref, None, None)
}
};
// The factory runs on the decode worker (no runtime), so
// hand StreamBuffer's download a handle from this task.
let rt_handle = tokio::runtime::Handle::current();
network_factory(
stream_url,
yt_format,
yt_user_agent,
is_radio_item,
icy_tx,
rt_handle,
buffer_progress,
)
};
let meta = NowPlayingMeta {
title: track.title.clone(),
artist: track.artist.clone(),
album: track.album.clone(),
duration: std::time::Duration::from_secs(track.duration),
artwork,
};
let transition = if use_crossfade {
Transition::Crossfade(crossfade_duration)
} else {
Transition::Immediate
};
let start_at = restore_seek_secs
.filter(|secs| *secs > 0)
.map(Duration::from_secs);
let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
ctrl.player.write().load(LoadArgs {
token,
factory,
meta,
transition,
start_at,
reply: Some(reply_tx),
});
match reply_rx.await {
Ok(Ok(outcome)) => {
ctrl.set_intent(PlaybackIntent::Committed { token });
if clear_pending_resume_on_success {
ctrl.pending_resume.set(None);
}
if use_crossfade {
if outcome.crossfaded {
// Defer the UI until TrackSwitched confirms the fade.
ctrl.schedule_pending_crossfade_ui(idx, token, from_token);
} else {
// Crossfade fell back to an immediate switch —
// commit now; no fade midpoint is coming.
ctrl.hydrate_current_track_metadata(idx, 0);
}
}
if is_radio_item {
ctrl.start_radio_metadata(station_id, stream_id, icy_rx);
} else {
let (item_id, source, options) = if is_server_item {
(
Some(station_id.clone()),
Some(ctrl.active_source),
ScrobbleOptions::REMOTE_NATIVE,
)
} else {
(None, None, ScrobbleOptions::LOCAL)
};
scrobble_scheduler::schedule(
track.clone(),
item_id,
ctrl.config,
ctrl.current_token,
token,
ctrl.is_playing,
source,
options,
ctrl.db.peek().clone(),
);
if is_server_item && !cover_url.is_empty() {
ctrl.spawn_server_artwork_fetch(
cover_url.clone(),
track.clone(),
token,
);
}
}
}
Ok(Err(e)) => {
tracing::error!(error = %e, "playback failed");
ctrl.fail_load(token, &e);
}
Err(_) => {
// Cancelled engine-side (superseded or stopped) — the
// token no longer matches, so any stray write-back is
// ignored; whichever flow cancelled owns the intent.
}
}
}
.instrument(tracing::info_span!("player.load_pipeline", idx)),
);
self.load_task.set(Some(task));
}
}
/// Factory for a resolved network stream (radio, YT range/sequential,
/// SoundCloud HLS, or a plain buffered stream). Returns a `SourceFactory` so the
/// symphonia types stay inferred inside the closure — hooks can't name them.
fn network_factory(
stream_url: String,
yt_format: Option<(::server::ytmusic::player::AudioFormat, bool)>,
yt_user_agent: Option<String>,
is_radio: bool,
icy_tx: Option<tokio::sync::watch::Sender<utils::icy::IcyMeta>>,
rt_handle: tokio::runtime::Handle,
buffer_progress: Option<utils::stream_buffer::BufferProgressCallback>,
) -> SourceFactory {
Box::new(move || {
let build = || -> std::io::Result<_> {
if is_radio {
let stream = utils::stream_buffer::StreamBuffer::with_user_agent(
stream_url,
true,
yt_user_agent,
icy_tx,
rt_handle,
);
Ok(decoder::from_stream_with_hint(stream, "ogg"))
} else if let Some((fmt, range_safe)) = yt_format {
if range_safe {
// YT: HTTP Range-backed source. Symphonia can seek freely
// (Matroska Cues at the end, scrub anywhere) and startup
// probes only fetch the ~512 KiB they need.
let range = utils::range_source::RangeStreamSource::new_with_progress(
stream_url,
yt_user_agent,
buffer_progress,
)?;
let len = Some(range.total_size());
let (source, mut hint) = decoder::from_stream_with_len(range, len);
hint.with_extension(fmt.extension());
Ok((source, hint))
} else {
// No-pot fallback: googlevideo 403s deep ranges, and the
// probe reads the webm tail — stream sequentially instead of
// failing outright (issue #386). No scrubbing.
let stream = utils::stream_buffer::StreamBuffer::with_user_agent_and_progress(
stream_url,
false,
yt_user_agent,
None,
rt_handle,
buffer_progress,
);
stream.wait_for_response_headers();
let len = stream.known_total_size();
let (source, mut hint) = decoder::from_stream_with_len(stream, len);
hint.with_extension(fmt.extension());
Ok((source, hint))
}
} else if let ResolvedStreamRef::SoundCloudHls(hls_url) =
ResolvedStreamRef::parse(&stream_url)
{
// SoundCloud Go+ AAC: assemble the HLS playlist's fMP4 segments
// into one in-memory buffer Symphonia can decode (no HLS demuxer).
let bytes = utils::hls_source::assemble(hls_url, yt_user_agent.as_deref())?;
let len = Some(bytes.len() as u64);
let cursor = std::io::Cursor::new(bytes);
let (source, mut hint) = decoder::from_stream_with_len(cursor, len);
hint.with_extension("m4a");
Ok((source, hint))
} else {
// Jellyfin and Subsonic/Navidrome normally support HTTP
// ranges. Let format probes jump straight to tail metadata
// instead of making a sequential buffer download everything
// between the start and end of the file.
match utils::range_source::RangeStreamSource::new_with_progress(
stream_url.clone(),
yt_user_agent.clone(),
buffer_progress.clone(),
) {
Ok(range) => {
let len = Some(range.total_size());
Ok(decoder::from_stream_with_len(range, len))
}
Err(error) => {
tracing::debug!(%error, "HTTP ranges unavailable; using progressive stream");
let stream =
utils::stream_buffer::StreamBuffer::with_user_agent_and_progress(
stream_url,
false,
yt_user_agent,
None,
rt_handle,
buffer_progress,
);
stream.wait_for_response_headers();
let len = stream.known_total_size();
Ok(decoder::from_stream_with_len(stream, len))
}
}
}
};
build().map_err(|e| e.to_string())
})
}
#[allow(clippy::too_many_arguments)]
pub fn use_player_controller(
player: Signal<Player>,
is_playing: Signal<bool>,
queue: Signal<Vec<Track>>,
current_queue_index: Signal<usize>,
current_song_title: Signal<String>,
current_song_artist: Signal<String>,
current_song_album: Signal<String>,
current_song_khz: Signal<u32>,
current_song_bitrate: Signal<u16>,
current_song_duration: Signal<u64>,
current_song_progress: Signal<u64>,
current_song_cover_url: Signal<String>,
current_track_snapshot: Signal<Option<Track>>,
volume: Signal<f32>,
config: Signal<AppConfig>,
config_loaded_ok: Signal<bool>,
db_handle: db::Db,
) -> PlayerController {
let intent = use_signal(|| PlaybackIntent::Stopped);
let next_token = use_signal(|| 0u64);
let current_token = use_signal(|| 0u64);
let buffered_ranges = use_signal(Vec::<BufferedRange>::new);
let (progress_tx, progress_rx) = use_hook(|| {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<BufferProgressEvent>();
(tx, std::rc::Rc::new(std::cell::RefCell::new(Some(rx))))
});
let buffer_progress_tx = use_signal(move || progress_tx);
let progress_rx_slot = progress_rx.clone();
let mut buffered_ranges_sink = buffered_ranges;
use_effect(move || {
let Some(mut progress_rx) = progress_rx_slot.borrow_mut().take() else {
return;
};
spawn(async move {
while let Some(event) = progress_rx.recv().await {
if *current_token.peek() != event.token {
continue;
}
let Some(total) = event.total.filter(|total| *total > 0) else {
continue;
};
buffered_ranges_sink.with_mut(|ranges| {
merge_buffered_range(
ranges,
BufferedRange {
start: event.start,
end: event.end,
total,
},
);
});
}
});
});
let armed_transition = use_signal(|| None);
let browse_loading = use_signal(|| false);
let is_loading = use_memo(move || intent.read().is_loading() || *browse_loading.read());
let history = use_signal(Vec::new);
let shuffle = use_signal(|| false);
let shuffle_order = use_signal(Vec::<usize>::new);
let loop_mode = use_signal(|| LoopMode::None);
let pending_resume = use_signal(|| None::<PendingResumeState>);
let pending_crossfade_ui = use_signal(|| None::<PendingCrossfadeUiState>);
let radio_task = use_signal(|| None::<dioxus_core::Task>);
let load_task = use_signal(|| None::<dioxus_core::Task>);
let station_registry = use_context::<Signal<radio::registry::StationRegistry>>();
let playback_error = use_signal(|| None::<String>);
let spotify_host = use_signal(|| None::<::server::spotify::host::SpotifyHost>);
let spotify_device = use_signal(|| None::<String>);
let spotify_pending_uri = use_signal(|| None::<String>);
let spotify_activated = use_signal(|| false);
let spotify_device_override = use_signal(|| None::<String>);
let spotify_progress_anchor = use_signal(|| None::<(u64, std::time::Instant)>);
let spotify_host_starting = use_signal(|| false);
let spotify_start_task = use_signal(|| None::<dioxus_core::Task>);
let spotify_commanded = use_signal(|| None::<(String, std::time::Instant)>);
let external_active = use_signal(|| false);
let spotify_device_chosen = use_signal(|| false);
let db = use_signal(move || db_handle);
let active_source = use_context::<Signal<::server::source::ActiveSource>>();
// Scrobbles queued while offline (issue #335): retry once on startup, in
// case connectivity came back between sessions.
let mut drained = use_signal(|| false);
use_effect(move || {
if !*config_loaded_ok.read() || *drained.peek() {
return;
}
drained.set(true);
let creds = {
let cfg = config.peek();
scrobble::queue::Credentials {
lastfm: (!cfg.lastfm_api_key.is_empty() && !cfg.lastfm_api_secret.is_empty()).then(
|| {
(
cfg.lastfm_api_key.clone(),
cfg.lastfm_api_secret.clone(),
cfg.lastfm_session_key.clone(),
)
},
),
librefm_session_key: (!cfg.librefm_session_key.is_empty())
.then(|| cfg.librefm_session_key.clone()),
listenbrainz_token: (!cfg.musicbrainz_token.trim().is_empty())
.then(|| cfg.musicbrainz_token.clone()),
}
};
let db_handle = db.peek().clone();
spawn(async move {
scrobble::queue::drain(&db_handle, &creds).await;
});
});
PlayerController {
player,
is_playing,
is_loading,
history,
queue,
shuffle,
shuffle_order,
loop_mode,
current_queue_index,
current_song_title,
current_song_artist,
current_song_album,
current_song_khz,
current_song_bitrate,
current_song_duration,
current_song_progress,
buffered_ranges,
buffer_progress_tx,
current_song_cover_url,
current_track_snapshot,
volume,
config,
db,
active_source,
intent,
next_token,
current_token,
armed_transition,
browse_loading,
pending_resume,
pending_crossfade_ui,
radio_task,
load_task,
station_registry,
playback_error,
spotify_host,
spotify_device,
spotify_pending_uri,
spotify_activated,
spotify_device_override,
spotify_progress_anchor,
spotify_host_starting,
spotify_start_task,
spotify_commanded,
external_active,
spotify_device_chosen,
}
}
#[cfg(test)]
mod tests {
use super::{BufferedRange, merge_buffered_range};
#[test]
fn buffered_ranges_merge_adjacent_and_overlapping_chunks() {
let mut ranges = Vec::new();
for (start, end) in [(500, 750), (0, 250), (200, 500)] {
merge_buffered_range(
&mut ranges,
BufferedRange {
start,
end,
total: 1_000,
},
);
}
assert_eq!(
ranges,
vec![BufferedRange {
start: 0,
end: 750,
total: 1_000,
}]
);
}
#[test]
fn buffered_ranges_preserve_gaps_and_reset_for_a_new_total() {
let mut ranges = Vec::new();
merge_buffered_range(
&mut ranges,
BufferedRange {
start: 0,
end: 100,
total: 1_000,
},
);
merge_buffered_range(
&mut ranges,
BufferedRange {
start: 900,
end: 1_000,
total: 1_000,
},
);
assert_eq!(ranges.len(), 2);
merge_buffered_range(
&mut ranges,
BufferedRange {
start: 0,
end: 50,
total: 500,
},
);
assert_eq!(
ranges,
vec![BufferedRange {
start: 0,
end: 50,
total: 500,
}]
);
}
}