koan-core 0.19.0

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
Documentation
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
pub mod commands;
pub mod state;
pub mod undo;

use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;

use thiserror::Error;

use crate::audio::{
    analyzer::VizAnalyzer,
    backend::{self, AudioBackend, AudioEngineHandle, BackendError},
    buffer, streaming,
    viz::{VizBuffer, VizSnapshot},
};
use buffer::PlaybackTimeline;
use commands::{CommandChannel, PlayerCommand};
use state::{LoadState, PlaybackSource, PlaybackState, QueueItemId, SharedPlayerState, TrackInfo};
use undo::{UndoEntry, UndoStack};

/// Ring buffer size in samples. ~1s at 192kHz stereo.
const RING_BUFFER_SIZE: usize = 192_000 * 2;

#[derive(Debug, Error)]
pub enum PlayerError {
    #[error("backend error: {0}")]
    Backend(#[from] BackendError),
    #[error("decode error: {0}")]
    Decode(#[from] buffer::DecodeError),
}

/// The player controller. Owns the audio pipeline and processes commands.
pub struct Player {
    shared_state: Arc<SharedPlayerState>,
    commands: CommandChannel,
    active_playback: Option<ActivePlayback>,
    timeline: Arc<PlaybackTimeline>,
    viz_buffer: Arc<VizBuffer>,
    viz_snapshot: Arc<VizSnapshot>,
    /// Background FFT analysis thread. Held for its lifetime; dropped on Player drop.
    _viz_analyzer: VizAnalyzer,
    undo_stack: UndoStack,
    /// When Some, undo entries are collected into this buffer instead of pushed
    /// directly onto the undo stack. Flushed on EndUndoBatch.
    batch_buffer: Option<Vec<UndoEntry>>,
    /// Configured output device name. None = system default.
    output_device_name: Option<String>,
    /// Platform audio backend (CoreAudio on macOS, cpal on Linux).
    backend: Box<dyn AudioBackend>,
    /// Debounce: timestamp of last NextTrack/PrevTrack to suppress key repeat.
    last_skip: std::time::Instant,
}

/// Holds the resources for an active playback session.
struct ActivePlayback {
    engine: Box<dyn AudioEngineHandle>,
    decode_handle: buffer::DecodeHandle,
}

impl Default for Player {
    fn default() -> Self {
        Self::new()
    }
}

impl Player {
    pub fn new() -> Self {
        let viz_buffer = VizBuffer::new();
        let viz_snapshot = VizSnapshot::new();
        let cfg = crate::config::Config::load_or_default();
        let viz_analyzer = VizAnalyzer::spawn_with_snapshot(
            Arc::clone(&viz_buffer),
            &cfg.visualizer,
            Arc::clone(&viz_snapshot),
        );

        Self {
            shared_state: SharedPlayerState::new(),
            commands: CommandChannel::new(),
            active_playback: None,
            timeline: PlaybackTimeline::new(),
            viz_buffer,
            viz_snapshot,
            _viz_analyzer: viz_analyzer,
            undo_stack: UndoStack::new(),
            batch_buffer: None,
            output_device_name: cfg.playback.output_device.clone(),
            backend: crate::audio::platform_backend(),
            last_skip: std::time::Instant::now(),
        }
    }

    /// Get a clone of the shared state for UI reads.
    pub fn shared_state(&self) -> Arc<SharedPlayerState> {
        self.shared_state.clone()
    }

    /// Get the playback timeline for UI reads.
    pub fn timeline(&self) -> Arc<PlaybackTimeline> {
        self.timeline.clone()
    }

    /// Get the visualization buffer for the TUI.
    pub fn viz_buffer(&self) -> Arc<VizBuffer> {
        self.viz_buffer.clone()
    }

    /// Get the shared analysis snapshot for the TUI.
    /// The analysis thread writes here; the UI thread reads a clone each frame.
    pub fn viz_snapshot(&self) -> Arc<VizSnapshot> {
        self.viz_snapshot.clone()
    }

    /// Access undo stack (for tests and UI state queries).
    pub fn undo_stack(&self) -> &UndoStack {
        &self.undo_stack
    }

    /// Resolve the output device: use configured device name if set,
    /// falling back to system default if not set or if the named device is unavailable.
    fn resolve_device(&self) -> Result<backend::DeviceInfo, PlayerError> {
        if let Some(ref name) = self.output_device_name {
            match self.backend.list_devices() {
                Ok(devices) => {
                    if let Some(dev) = devices.into_iter().find(|d| d.name == *name) {
                        return Ok(dev);
                    }
                    log::warn!(
                        "configured output device '{}' not found, falling back to default",
                        name,
                    );
                }
                Err(e) => {
                    log::warn!("failed to list devices while resolving '{}': {}", name, e);
                }
            }
        }
        Ok(self.backend.default_device()?)
    }

    /// Switch the output device. Persists to config and restarts the engine
    /// on the current track if playing.
    pub fn set_output_device(&mut self, name: String) {
        log::info!("switching output device to: {}", name);
        self.output_device_name = Some(name.clone());

        // Persist to config.toml (not the merged config — avoids leaking secrets).
        if let Err(e) = crate::config::Config::update_base(|cfg| {
            cfg.playback.output_device = Some(name);
        }) {
            log::error!("failed to save output device config: {}", e);
        }

        self.restart_on_current_track();
    }

    /// Clear the configured output device, reverting to system default.
    pub fn clear_output_device(&mut self) {
        log::info!("reverting to system default output device");
        self.output_device_name = None;

        if let Err(e) = crate::config::Config::update_base(|cfg| {
            cfg.playback.output_device = None;
        }) {
            log::error!("failed to save output device config: {}", e);
        }

        self.restart_on_current_track();
    }

    /// If a track is currently playing or paused, restart playback at the
    /// current position (e.g. after switching output devices). Preserves pause state.
    fn restart_on_current_track(&mut self) {
        if let Some(info) = self.shared_state.track_info() {
            let was_paused = self.shared_state.playback_state() == PlaybackState::Paused;
            let position_ms = self.shared_state.position_ms();
            if let Err(e) = self.start_playback(info.id, &info.path, position_ms) {
                log::error!("failed to restart playback on device switch: {}", e);
                return;
            }
            if was_paused {
                self.pause();
            }
        }
    }

    /// Get the current output device name (if configured).
    pub fn output_device_name(&self) -> Option<&str> {
        self.output_device_name.as_deref()
    }

    /// Get a command sender for the UI layer.
    pub fn command_sender(&self) -> crossbeam_channel::Sender<PlayerCommand> {
        self.commands.tx.clone()
    }

    /// Play a specific item in the playlist by ID.
    /// Sets cursor, starts playback if Ready or streaming-ready, otherwise waits for TrackReady.
    pub fn play(&mut self, id: QueueItemId) {
        self.shared_state.set_cursor(Some(id));

        match self.shared_state.item_playback_source(id) {
            Some(PlaybackSource::Ready(path)) => {
                if let Err(e) = self.start_playback(id, &path, 0) {
                    log::error!("play failed: {}", e);
                }
            }
            Some(PlaybackSource::Streaming {
                path,
                bytes_written,
                total,
            }) => {
                if let Err(e) = self.start_streaming_playback(id, &path, bytes_written, total) {
                    log::error!("streaming play failed, waiting for full download: {}", e);
                    // Fall back to waiting for TrackReady.
                    self.stop_engine();
                    self.shared_state.set_playback_state(PlaybackState::Stopped);
                }
            }
            None => {
                // Item not ready — stop current playback, wait for TrackReady.
                self.stop_engine();
                self.shared_state.set_playback_state(PlaybackState::Stopped);
                log::info!("play: item {:?} not ready, waiting for TrackReady", id);
            }
        }
    }

    /// Internal: start playback of a file.
    fn start_playback(
        &mut self,
        id: QueueItemId,
        path: &Path,
        seek_ms: u64,
    ) -> Result<(), PlayerError> {
        self.stop_engine();

        let info = buffer::probe_file(path)?;

        // Set track_info + position immediately so the UI never sees a gap.
        // For seeks, this keeps the bar at the target position instead of
        // flashing to 0 while the new timeline spins up.
        self.shared_state.set_track_info(Some(TrackInfo {
            id,
            path: path.to_path_buf(),
            codec: info.codec.clone(),
            sample_rate: info.sample_rate,
            bit_depth: info.bit_depth,
            channels: info.channels,
            duration_ms: info.duration_ms,
        }));
        self.shared_state.set_position_ms(seek_ms);
        log::info!(
            "playing: {} ({:?}) — {} {}Hz/{}bit/{}ch, {}ms{}",
            path.display(),
            id,
            info.codec,
            info.sample_rate,
            info.bit_depth,
            info.channels,
            info.duration_ms,
            if seek_ms > 0 {
                format!(" @{}ms", seek_ms)
            } else {
                String::new()
            }
        );

        let device = self.resolve_device()?;
        let device_rate = self.backend.get_device_sample_rate(&device)?;
        let source_rate = info.sample_rate as f64;

        let actual_rate = if (device_rate - source_rate).abs() > 0.1 {
            log::info!(
                "switching device sample rate: {}Hz → {}Hz",
                device_rate,
                source_rate
            );
            match self.backend.set_device_sample_rate(&device, source_rate) {
                Ok(confirmed_rate) => {
                    if (confirmed_rate - source_rate).abs() > 0.1 {
                        log::warn!(
                            "device stayed at {}Hz (wanted {}Hz) — playback will use device rate",
                            confirmed_rate,
                            source_rate
                        );
                    }
                    confirmed_rate
                }
                Err(e) => {
                    log::warn!(
                        "failed to set sample rate (continuing at device rate): {}",
                        e
                    );
                    device_rate
                }
            }
        } else {
            device_rate
        };

        let (producer, consumer) = rtrb::RingBuffer::new(RING_BUFFER_SIZE);

        let _generation = self.shared_state.bump_generation();

        // Reset timeline for new playback session and start decode.
        self.timeline.reset();

        // Gapless lookahead: the decode thread maintains its own cursor
        // (separate from the UI cursor) so it can look ahead through the
        // playlist without affecting what the UI shows as "now playing".
        let advance_state = self.shared_state.clone();
        let decode_cursor = std::sync::Mutex::new(Some(id));
        let next_track = move || {
            let current = decode_cursor.lock().ok()?.take()?;
            let next = advance_state.peek_next_ready_after(current);
            if let Some((next_id, _)) = &next
                && let Ok(mut guard) = decode_cursor.lock()
            {
                *guard = Some(*next_id);
            }
            next
        };

        // Load ReplayGain config for this playback session.
        let cfg = crate::config::Config::load_or_default();
        let rg_mode = cfg.playback.replaygain;
        let pre_amp_db = cfg.playback.pre_amp_db;

        let finish_tx = self.commands.tx.clone();
        let (_stream_info, decode_handle) = buffer::start_decode_file(
            id,
            path,
            producer,
            seek_ms,
            next_track,
            self.timeline.clone(),
            Some(self.viz_buffer.clone()),
            rg_mode,
            pre_amp_db,
            move || {
                finish_tx.send(PlayerCommand::DecodeFinished).ok();
            },
        )?;

        // Create and start audio engine with the confirmed device rate.
        let engine = self.backend.create_engine(
            &device,
            actual_rate,
            info.channels as u32,
            consumer,
            self.timeline.samples_played_counter(),
        )?;
        engine.start()?;

        self.shared_state.set_playback_state(PlaybackState::Playing);

        self.active_playback = Some(ActivePlayback {
            engine,
            decode_handle,
        });

        Ok(())
    }

    /// Internal: start streaming playback from a partially-downloaded file.
    ///
    /// Creates a StreamBuffer and a pump thread that reads from the on-disk partial
    /// file as bytes become available (tracked via `bytes_written`). The decode thread
    /// reads from a StreamingSource backed by that buffer, blocking briefly when it
    /// catches up to the write head.
    fn start_streaming_playback(
        &mut self,
        id: QueueItemId,
        path: &Path,
        bytes_written: Arc<AtomicU64>,
        total: u64,
    ) -> Result<(), PlayerError> {
        self.stop_engine();

        // Create a StreamBuffer with known total length.
        let stream_buf = streaming::StreamBuffer::new(if total > 0 { Some(total) } else { None });

        // Spawn a pump thread: reads bytes from the on-disk partial file as they
        // become available (per bytes_written) and pushes them into StreamBuffer.
        // This bridges the disk-based download with StreamingSource's in-memory design.
        let pump_path = path.to_path_buf();
        let pump_buf = stream_buf.clone();
        let pump_written = bytes_written.clone();
        thread::Builder::new()
            .name("koan-stream-pump".into())
            .spawn(move || {
                use std::fs::File;
                use std::io::Read;
                let mut file = match File::open(&pump_path) {
                    Ok(f) => f,
                    Err(e) => {
                        log::error!("stream pump: failed to open {}: {}", pump_path.display(), e);
                        pump_buf.finish();
                        return;
                    }
                };
                let mut buf = vec![0u8; 65536];
                let mut offset: u64 = 0;
                loop {
                    let available = pump_written.load(Ordering::Acquire);
                    if offset >= available {
                        if total > 0 && available >= total {
                            break; // Download complete.
                        }
                        thread::sleep(std::time::Duration::from_millis(10));
                        continue;
                    }
                    let to_read = ((available - offset) as usize).min(buf.len());
                    match file.read(&mut buf[..to_read]) {
                        Ok(0) => {
                            // File data may lag behind bytes_written (OS buffer flush timing).
                            // Only treat as true EOF if we've pumped all expected data.
                            if total > 0 && offset >= total {
                                break;
                            }
                            let latest = pump_written.load(Ordering::Acquire);
                            if total > 0 && latest >= total && offset >= latest {
                                break;
                            }
                            // Data not yet visible on disk — back off and retry.
                            thread::sleep(std::time::Duration::from_millis(1));
                            continue;
                        }
                        Ok(n) => {
                            pump_buf.push(&buf[..n]);
                            offset += n as u64;
                        }
                        Err(e) => {
                            log::warn!("stream pump read error: {}", e);
                            break;
                        }
                    }
                }
                pump_buf.finish();
            })
            .map_err(|e| PlayerError::Decode(buffer::DecodeError::Io(e)))?;

        // Probe via a streaming reader — blocks (via condvar) until enough header data arrives.
        let probe_reader = stream_buf.reader();
        let probe_hint = {
            let mut h = symphonia::core::probe::Hint::new();
            if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                h.with_extension(ext);
            }
            h
        };
        let probe_mss =
            symphonia::core::io::MediaSourceStream::new(Box::new(probe_reader), Default::default());
        let info = buffer::probe_source(probe_mss, &probe_hint)?;

        self.shared_state.set_track_info(Some(TrackInfo {
            id,
            path: path.to_path_buf(),
            codec: info.codec.clone(),
            sample_rate: info.sample_rate,
            bit_depth: info.bit_depth,
            channels: info.channels,
            duration_ms: info.duration_ms,
        }));
        self.shared_state.set_position_ms(0);
        log::info!(
            "streaming: {} ({:?}) — {} {}Hz/{}bit/{}ch, {}ms",
            path.display(),
            id,
            info.codec,
            info.sample_rate,
            info.bit_depth,
            info.channels,
            info.duration_ms,
        );

        let device = self.resolve_device()?;
        let device_rate = self.backend.get_device_sample_rate(&device)?;
        let source_rate = info.sample_rate as f64;

        let actual_rate = if (device_rate - source_rate).abs() > 0.1 {
            log::info!(
                "switching device sample rate: {}Hz → {}Hz",
                device_rate,
                source_rate
            );
            match self.backend.set_device_sample_rate(&device, source_rate) {
                Ok(confirmed_rate) => {
                    if (confirmed_rate - source_rate).abs() > 0.1 {
                        log::warn!(
                            "device stayed at {}Hz (wanted {}Hz) — playback will use device rate",
                            confirmed_rate,
                            source_rate
                        );
                    }
                    confirmed_rate
                }
                Err(e) => {
                    log::warn!(
                        "failed to set sample rate (continuing at device rate): {}",
                        e
                    );
                    device_rate
                }
            }
        } else {
            device_rate
        };

        let (producer, consumer) = rtrb::RingBuffer::new(RING_BUFFER_SIZE);

        let _generation = self.shared_state.bump_generation();
        self.timeline.reset();

        // Gapless lookahead after streaming: next track uses normal file path.
        let advance_state = self.shared_state.clone();
        let decode_cursor = std::sync::Mutex::new(Some(id));
        let next_track = move || {
            let current = decode_cursor.lock().ok()?.take()?;
            let next = advance_state.peek_next_ready_after(current);
            if let Some((next_id, _)) = &next
                && let Ok(mut guard) = decode_cursor.lock()
            {
                *guard = Some(*next_id);
            }
            next
        };

        // Decode using a fresh StreamingSource reader — reads from the StreamBuffer
        // that the pump thread feeds. The decode thread blocks when it catches up to
        // the write head, resuming as more data arrives.
        // Build a SourceEntry using a fresh StreamingSource reader for the decode thread.
        let decode_reader = stream_buf.reader();
        let path_buf = path.to_path_buf();
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_string();
        let mut decode_hint = symphonia::core::probe::Hint::new();
        if !ext.is_empty() {
            decode_hint.with_extension(&ext);
        }
        let first = buffer::SourceEntry {
            id,
            path: path_buf,
            hint: decode_hint,
            make_mss: Box::new(move || {
                Ok(symphonia::core::io::MediaSourceStream::new(
                    Box::new(decode_reader),
                    Default::default(),
                ))
            }),
        };

        // Load ReplayGain config for this streaming session.
        let cfg = crate::config::Config::load_or_default();
        let rg_mode = cfg.playback.replaygain;
        let pre_amp_db = cfg.playback.pre_amp_db;

        let finish_tx = self.commands.tx.clone();
        let (_stream_info, decode_handle) = buffer::start_decode(
            first,
            producer,
            0,
            move || {
                let (next_id, next_path) = next_track()?;
                Some(buffer::SourceEntry::from_file(next_id, next_path))
            },
            self.timeline.clone(),
            Some(self.viz_buffer.clone()),
            rg_mode,
            pre_amp_db,
            move || {
                finish_tx.send(PlayerCommand::DecodeFinished).ok();
            },
        )?;

        // Create and start audio engine with the confirmed device rate.
        let engine = self.backend.create_engine(
            &device,
            actual_rate,
            info.channels as u32,
            consumer,
            self.timeline.samples_played_counter(),
        )?;
        engine.start()?;

        self.shared_state.set_playback_state(PlaybackState::Playing);

        self.active_playback = Some(ActivePlayback {
            engine,
            decode_handle,
        });

        Ok(())
    }

    /// Seek within the current track. Clamps to just before the end to avoid
    /// accidentally skipping. Preserves pause state.
    pub fn seek(&mut self, position_ms: u64) {
        let info = match self.shared_state.track_info() {
            Some(info) => info,
            None => return,
        };
        let id = info.id;
        let path = info.path.clone();
        let duration = info.duration_ms;

        // Clamp to just before the end so we don't skip to the next track.
        let mut clamped = if duration > 0 {
            position_ms.min(duration.saturating_sub(500))
        } else {
            position_ms
        };

        // Clamp to downloaded portion if streaming to prevent seeking into
        // data that hasn't arrived yet.
        if let Some(dl_frac) = self.shared_state.current_download_fraction() {
            let max_ms = (dl_frac * duration as f64) as u64;
            if max_ms > 5_000 {
                clamped = clamped.min(max_ms - 5_000);
            }
        }

        let was_paused = self.shared_state.playback_state() == PlaybackState::Paused;

        if let Err(e) = self.start_playback(id, &path, clamped) {
            log::error!("seek failed: {}", e);
            return;
        }

        if was_paused {
            self.pause();
        }
    }

    /// Skip to next track in playlist.
    pub fn next_track(&mut self) {
        // advance_cursor finds the next Ready item after cursor.
        match self.shared_state.advance_cursor() {
            Some((id, path)) => {
                if let Err(e) = self.start_playback(id, &path, 0) {
                    log::error!("next track failed: {}", e);
                }
            }
            None => {
                log::info!("no more tracks in playlist");
                self.stop_playback_and_clear_state();
            }
        }
    }

    /// Go back to previous track.
    pub fn prev_track(&mut self) {
        match self.shared_state.retreat_cursor() {
            Some((id, path)) => {
                if matches!(path.try_exists(), Ok(true)) {
                    if let Err(e) = self.start_playback(id, &path, 0) {
                        log::error!("prev track failed: {}", e);
                    }
                } else {
                    log::warn!("prev track path doesn't exist: {}", path.display());
                }
            }
            None => {
                // No previous track — restart current from the beginning.
                if let Some(info) = self.shared_state.track_info()
                    && let Err(e) = self.start_playback(info.id, &info.path, 0)
                {
                    log::error!("restart failed: {}", e);
                }
            }
        }
    }

    /// Pause playback.
    pub fn pause(&mut self) {
        if let Some(ref playback) = self.active_playback {
            let _ = playback.engine.stop();
            self.shared_state.set_playback_state(PlaybackState::Paused);
        }
    }

    /// Resume playback.
    pub fn resume(&mut self) {
        if let Some(ref playback) = self.active_playback {
            let _ = playback.engine.start();
            self.shared_state.set_playback_state(PlaybackState::Playing);
        }
    }

    /// Stop playback and clear playlist.
    pub fn stop(&mut self) {
        self.shared_state.clear_playlist();
        self.stop_playback_and_clear_state();
    }

    /// Stop the audio engine and decode thread without touching shared state.
    ///
    /// The engine is stopped synchronously (silence begins immediately), but
    /// the heavy teardown (decode thread join + AudioUnit dispose) is moved to
    /// a background thread so the player command loop never blocks — preventing
    /// UI freezes when CoreAudio or the decode thread is slow to shut down.
    fn stop_engine(&mut self) {
        if let Some(playback) = self.active_playback.take() {
            // Stop audio output immediately.
            let _ = playback.engine.stop();
            // Signal decode thread to exit (non-blocking).
            playback.decode_handle.signal_stop();

            // Drop the audio engine synchronously. AudioUnitUninitialize must
            // complete before any device sample rate change, otherwise CoreAudio's
            // internal ExtendedAudioBufferList can be freed mid-teardown (crash
            // in caulk::alloc::tiered_allocator::deallocate — GitHub #89).
            let ActivePlayback {
                engine,
                decode_handle,
            } = playback;
            drop(engine);

            // The decode handle join is the heavy part (waits for the decode
            // thread to exit) — run it on a background thread so we don't block
            // the player command loop.
            thread::Builder::new()
                .name("koan-cleanup".into())
                .spawn(move || drop(decode_handle))
                .ok();
        }
    }

    /// Full stop: tear down engine + clear all display state.
    fn stop_playback_and_clear_state(&mut self) {
        self.stop_engine();
        self.timeline.reset();
        self.shared_state.set_playback_state(PlaybackState::Stopped);
        self.shared_state.set_position_ms(0);
        self.shared_state.set_track_info(None);
    }

    /// Remove a track from the playlist. If it was the cursor, skip to next.
    pub fn remove_from_playlist(&mut self, id: QueueItemId) {
        let was_cursor = self.shared_state.is_cursor(id);
        self.shared_state.remove_item(id);
        if was_cursor {
            self.next_track();
        }
    }

    /// A download finished — if cursor is waiting on this item, start playback.
    /// If already streaming this item, trigger progressive metadata enhancement.
    pub fn track_ready(&mut self, id: QueueItemId) {
        // Mark as Ready (download thread already did this, but be safe).
        self.shared_state.update_load_state(id, LoadState::Ready);

        if !self.shared_state.is_cursor(id) {
            return;
        }

        let is_playing = self.shared_state.playback_state() == PlaybackState::Playing;
        let current_track_id = self.shared_state.track_info().map(|t| t.id);

        if is_playing && current_track_id == Some(id) {
            // Already streaming this track — download just finished.
            // Trigger progressive enhancement: re-read full lofty metadata and update state.
            log::info!(
                "track_ready: download complete while streaming {:?}, refreshing metadata",
                id
            );
            self.refresh_track_metadata(id);
            return;
        }

        // Cursor is on this item but not yet playing — start playback now.
        if !is_playing && let Some(path) = self.shared_state.item_path_if_ready(id) {
            log::info!("track_ready: starting playback for {:?}", id);
            if let Err(e) = self.start_playback(id, &path, 0) {
                log::error!("track_ready playback failed: {}", e);
            }
        }
    }

    /// Called when enough data has been buffered for streaming playback.
    /// If the cursor is waiting on this track and nothing is playing, start streaming.
    pub fn track_stream_ready(&mut self, id: QueueItemId) {
        if !self.shared_state.is_cursor(id) {
            return;
        }

        let is_playing = self.shared_state.playback_state() == PlaybackState::Playing;
        if is_playing {
            return; // Already playing something — don't interrupt.
        }

        match self.shared_state.item_playback_source(id) {
            Some(PlaybackSource::Streaming {
                path,
                bytes_written,
                total,
            }) => {
                log::info!(
                    "track_stream_ready: starting streaming playback for {:?}",
                    id
                );
                if let Err(e) = self.start_streaming_playback(id, &path, bytes_written, total) {
                    log::error!("track_stream_ready streaming failed: {}", e);
                }
            }
            Some(PlaybackSource::Ready(path)) => {
                // Download finished between threshold and now — just play normally.
                log::info!(
                    "track_stream_ready: track already ready, starting normal playback for {:?}",
                    id
                );
                if let Err(e) = self.start_playback(id, &path, 0) {
                    log::error!("track_stream_ready playback failed: {}", e);
                }
            }
            None => {} // Not enough data yet — wait.
        }
    }

    /// Re-read full lofty metadata for a track after its download completes.
    /// Updates the playlist item's tags and track_info with complete metadata.
    /// Called from track_ready() when a streaming track finishes downloading.
    fn refresh_track_metadata(&mut self, id: QueueItemId) {
        use crate::index::metadata;

        let path = match self.shared_state.item_path_if_ready(id) {
            Some(p) => p,
            None => return,
        };

        match metadata::read_metadata(&path) {
            Ok(meta) => {
                // Update playlist item with full lofty tags (title, artist, album, duration).
                self.shared_state.update_item_metadata(
                    id,
                    meta.title,
                    meta.artist,
                    meta.album_artist.unwrap_or_default(),
                    meta.album,
                    meta.duration_ms.map(|d| d as u64),
                );

                // Re-probe the complete file for accurate duration + stream info.
                // The initial probe was done on partial streaming data and may have
                // underestimated duration, causing premature seek clamping or wrong
                // progress bar display.
                if let Ok(stream_info) = buffer::probe_file(&path)
                    && let Some(current) = self.shared_state.track_info()
                    && current.id == id
                    && stream_info.duration_ms > current.duration_ms
                {
                    log::info!(
                        "track_ready: duration corrected {}ms → {}ms",
                        current.duration_ms,
                        stream_info.duration_ms
                    );
                    self.shared_state.set_track_info(Some(TrackInfo {
                        duration_ms: stream_info.duration_ms,
                        ..current
                    }));
                }

                // Signal UI to re-read cover art and update souvlaki media controls.
                self.shared_state.signal_metadata_refresh();
                log::info!("track_ready: metadata refreshed for {:?}", id);
            }
            Err(e) => {
                log::warn!("track_ready: metadata refresh failed for {:?}: {}", id, e);
            }
        }
    }

    /// Poll the timeline and update shared state with current track/position.
    /// Called from the command loop on each tick.
    pub fn update_playback_state(&self) {
        if self.active_playback.is_none() {
            return;
        }

        if let Some((id, path, info, position_ms)) = self.timeline.current_playback() {
            self.shared_state.set_position_ms(position_ms);

            // Update track_info + cursor if the timeline shows a different track
            // (gapless transition happened).
            let current_id = self.shared_state.track_info().map(|t| t.id);
            if current_id != Some(id) {
                log::info!("timeline: now playing {:?}", id);
                self.shared_state.set_track_info(Some(TrackInfo {
                    id,
                    path,
                    codec: info.codec,
                    sample_rate: info.sample_rate,
                    bit_depth: info.bit_depth,
                    channels: info.channels,
                    duration_ms: info.duration_ms,
                }));
                self.shared_state.set_cursor(Some(id));
            }
        }
    }

    /// Decode thread naturally finished (playlist exhausted or error).
    /// Try to advance to the next Ready track; otherwise stop cleanly.
    fn on_decode_finished(&mut self) {
        log::info!("decode finished, checking for next track");
        match self.shared_state.advance_cursor() {
            Some((id, path)) => {
                if let Err(e) = self.start_playback(id, &path, 0) {
                    log::error!("auto-advance after decode finished failed: {}", e);
                    self.stop_playback_and_clear_state();
                }
            }
            None => {
                log::info!("no more tracks — stopping");
                self.stop_playback_and_clear_state();
            }
        }
    }

    /// Route an undo entry to the batch buffer (if batching) or the undo stack.
    fn push_undo(&mut self, entry: UndoEntry) {
        if let Some(ref mut batch) = self.batch_buffer {
            batch.push(entry);
        } else {
            self.undo_stack.push(entry);
        }
    }

    /// Process a single command.
    pub fn process_command(&mut self, cmd: PlayerCommand) {
        match cmd {
            PlayerCommand::Play(id) => self.play(id),
            PlayerCommand::Pause => self.pause(),
            PlayerCommand::Resume => self.resume(),
            PlayerCommand::Stop => self.stop(),
            PlayerCommand::Seek(pos) => self.seek(pos),
            PlayerCommand::NextTrack => {
                // Debounce: suppress key repeat from terminal (150ms window).
                let now = std::time::Instant::now();
                if now.duration_since(self.last_skip).as_millis() >= 150 {
                    self.last_skip = now;
                    self.next_track();
                }
            }
            PlayerCommand::PrevTrack => {
                let now = std::time::Instant::now();
                if now.duration_since(self.last_skip).as_millis() >= 150 {
                    self.last_skip = now;
                    self.prev_track();
                }
            }
            PlayerCommand::AddToPlaylist(items) => {
                let ids: Vec<QueueItemId> = items.iter().map(|i| i.id).collect();
                self.shared_state.add_items(items);
                self.push_undo(UndoEntry::Added { ids });
            }
            PlayerCommand::UpdatePaths(updates) => {
                self.shared_state.update_paths(&updates);
                if let Some(info) = self.shared_state.track_info()
                    && let Some((_, new_path)) = updates.iter().find(|(id, _)| *id == info.id)
                {
                    self.shared_state.set_track_info(Some(TrackInfo {
                        path: new_path.clone(),
                        ..info
                    }));
                }
            }
            PlayerCommand::InsertInPlaylist { items, after } => {
                let ids: Vec<QueueItemId> = items.iter().map(|i| i.id).collect();
                self.shared_state.insert_items_after(items, after);
                self.push_undo(UndoEntry::Inserted { ids });
            }
            PlayerCommand::ClearPlaylist => {
                // Stop engine + clear display state WITHOUT touching the playlist,
                // then snapshot, then clear. This avoids the race where stop()
                // would clear the playlist before we capture it for undo.
                self.stop_playback_and_clear_state();
                let (items, cursor) = self.shared_state.snapshot_playlist();
                self.shared_state.clear_playlist();
                self.push_undo(UndoEntry::Replaced { items, cursor });
            }
            PlayerCommand::RemoveFromPlaylist(id) => {
                let item = self.shared_state.get_item(id);
                let after = self.shared_state.item_before(id);
                self.remove_from_playlist(id);
                if let Some(item) = item {
                    self.push_undo(UndoEntry::Removed {
                        items: vec![(Box::new(item), after)],
                    });
                }
            }
            PlayerCommand::RemoveFromPlaylistBatch(ids) => {
                // Snapshot all items with their predecessors before removing any.
                let items_with_pos: Vec<_> = ids
                    .iter()
                    .filter_map(|&id| {
                        let item = self.shared_state.get_item(id)?;
                        let after = self.shared_state.item_before(id);
                        Some((Box::new(item), after))
                    })
                    .collect();
                for &id in &ids {
                    self.remove_from_playlist(id);
                }
                if !items_with_pos.is_empty() {
                    self.push_undo(UndoEntry::Removed {
                        items: items_with_pos,
                    });
                }
            }
            PlayerCommand::MoveInPlaylist { id, target, after } => {
                let was_after = self.shared_state.item_before(id);
                self.shared_state.move_item(id, target, after);
                self.push_undo(UndoEntry::Moved { id, was_after });
            }
            PlayerCommand::MoveItemsInPlaylist { ids, target, after } => {
                let entries = self.shared_state.items_before(&ids);
                self.shared_state.move_items(&ids, target, after);
                self.push_undo(UndoEntry::MovedBatch { entries });
            }
            PlayerCommand::TrackReady(id) => self.track_ready(id),
            PlayerCommand::DecodeFinished => self.on_decode_finished(),
            PlayerCommand::TrackStreamReady(id) => self.track_stream_ready(id),
            PlayerCommand::Undo => self.execute_undo(),
            PlayerCommand::Redo => self.execute_redo(),
            PlayerCommand::BeginUndoBatch => {
                self.batch_buffer = Some(Vec::new());
            }
            PlayerCommand::EndUndoBatch => {
                if let Some(entries) = self.batch_buffer.take() {
                    if entries.len() == 1 {
                        // Single entry — push directly, no wrapping.
                        self.undo_stack.push(entries.into_iter().next().unwrap());
                    } else if !entries.is_empty() {
                        self.undo_stack.push(UndoEntry::Batch(entries));
                    }
                }
            }
            PlayerCommand::SetOutputDevice(name) => self.set_output_device(name),
            PlayerCommand::ClearOutputDevice => self.clear_output_device(),
        }
    }

    /// Apply an undo/redo entry: mutate the playlist and return the inverse entry.
    fn apply_entry(&mut self, entry: UndoEntry) -> Option<UndoEntry> {
        match entry {
            UndoEntry::Added { ids } => {
                // Undo of "items were added": snapshot them with positions, then remove.
                let items_with_pos: Vec<_> = ids
                    .iter()
                    .filter_map(|&id| {
                        let item = self.shared_state.get_item(id)?;
                        let after = self.shared_state.item_before(id);
                        Some((Box::new(item), after))
                    })
                    .collect();
                self.shared_state.remove_items(&ids);
                Some(UndoEntry::Removed {
                    items: items_with_pos,
                })
            }
            UndoEntry::Removed { items } => {
                // Undo of "items were removed": re-insert each at its position.
                let mut ids = Vec::with_capacity(items.len());
                for (item, after) in items {
                    ids.push(item.id);
                    self.shared_state.insert_item_at(*item, after);
                }
                Some(UndoEntry::Added { ids })
            }
            UndoEntry::Inserted { ids } => {
                // Same as Added — snapshot positions, remove items.
                let items_with_pos: Vec<_> = ids
                    .iter()
                    .filter_map(|&id| {
                        let item = self.shared_state.get_item(id)?;
                        let after = self.shared_state.item_before(id);
                        Some((Box::new(item), after))
                    })
                    .collect();
                self.shared_state.remove_items(&ids);
                Some(UndoEntry::Removed {
                    items: items_with_pos,
                })
            }
            UndoEntry::Moved { id, was_after } => {
                let current_after = self.shared_state.item_before(id);
                self.shared_state.move_item_to(id, was_after);
                Some(UndoEntry::Moved {
                    id,
                    was_after: current_after,
                })
            }
            UndoEntry::MovedBatch { entries } => {
                let ids: Vec<QueueItemId> = entries.iter().map(|(id, _)| *id).collect();
                let current_positions = self.shared_state.items_before(&ids);
                self.shared_state.move_items_to(&entries);
                Some(UndoEntry::MovedBatch {
                    entries: current_positions,
                })
            }
            UndoEntry::Replaced { items, cursor } => {
                let (current_items, current_cursor) = self.shared_state.snapshot_playlist();
                self.shared_state.restore_playlist(items, cursor);
                Some(UndoEntry::Replaced {
                    items: current_items,
                    cursor: current_cursor,
                })
            }
            UndoEntry::Batch(entries) => {
                // Apply entries in reverse order, collect inverses.
                let mut inverses = Vec::with_capacity(entries.len());
                for entry in entries.into_iter().rev() {
                    if let Some(inverse) = self.apply_entry(entry) {
                        inverses.push(inverse);
                    }
                }
                inverses.reverse();
                Some(UndoEntry::Batch(inverses))
            }
        }
    }

    /// Execute an undo operation, pushing the inverse onto the redo stack.
    fn execute_undo(&mut self) {
        let Some(entry) = self.undo_stack.pop_undo() else {
            return;
        };
        if let Some(inverse) = self.apply_entry(entry) {
            self.undo_stack.push_redo(inverse);
        }
    }

    /// Execute a redo operation, pushing the inverse onto the undo stack.
    fn execute_redo(&mut self) {
        let Some(entry) = self.undo_stack.pop_redo() else {
            return;
        };
        if let Some(inverse) = self.apply_entry(entry) {
            self.undo_stack.push_undo_keep_redo(inverse);
        }
    }

    /// Run the command loop. Blocks until the sender is dropped.
    pub fn run(&mut self) {
        use std::time::Duration;

        let rx = self.commands.rx.clone();
        loop {
            // Poll with timeout so we update position even without commands.
            match rx.recv_timeout(Duration::from_millis(50)) {
                Ok(cmd) => self.process_command(cmd),
                Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => break,
            }
            self.update_playback_state();
        }
        self.stop();
    }

    /// Spawn the player on a background thread, returning the shared state,
    /// timeline, visualization snapshot, and command sender.
    pub fn spawn() -> (
        Arc<SharedPlayerState>,
        Arc<PlaybackTimeline>,
        Arc<VizSnapshot>,
        crossbeam_channel::Sender<PlayerCommand>,
    ) {
        let mut player = Self::new();
        let state = player.shared_state();
        let timeline = player.timeline();
        let viz_snapshot = player.viz_snapshot();
        let tx = player.command_sender();

        thread::Builder::new()
            .name("koan-player".into())
            .spawn(move || player.run())
            .expect("failed to spawn player thread");

        (state, timeline, viz_snapshot, tx)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use state::PlaylistItem;
    use std::path::PathBuf;

    fn make_item(title: &str) -> PlaylistItem {
        PlaylistItem {
            id: QueueItemId::new(),
            db_id: None,
            path: PathBuf::from(format!("/music/{title}.flac")),
            title: title.to_string(),
            artist: String::new(),
            album_artist: String::new(),
            album: String::new(),
            year: None,
            codec: None,
            track_number: None,
            disc: None,
            duration_ms: None,
            load_state: LoadState::Ready,
        }
    }

    fn playlist_ids(player: &Player) -> Vec<QueueItemId> {
        let (items, _) = player.shared_state.snapshot_playlist();
        items.iter().map(|i| i.id).collect()
    }

    fn playlist_titles(player: &Player) -> Vec<String> {
        let (items, _) = player.shared_state.snapshot_playlist();
        items.iter().map(|i| i.title.clone()).collect()
    }

    // --- AddToPlaylist undo/redo ---

    #[test]
    fn undo_add_removes_items() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B")];
        let ids: Vec<_> = items.iter().map(|i| i.id).collect();

        player.process_command(PlayerCommand::AddToPlaylist(items));
        assert_eq!(playlist_ids(&player), ids);
        assert!(player.undo_stack().can_undo());

        player.process_command(PlayerCommand::Undo);
        assert!(playlist_ids(&player).is_empty());
        assert!(player.undo_stack().can_redo());
    }

    #[test]
    fn redo_add_restores_items() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B")];

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::Undo);
        assert!(playlist_ids(&player).is_empty());

        player.process_command(PlayerCommand::Redo);
        assert_eq!(playlist_titles(&player), vec!["A", "B"]);
    }

    // --- RemoveFromPlaylist undo/redo ---

    #[test]
    fn undo_remove_restores_item_at_position() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];
        let b_id = items[1].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::RemoveFromPlaylist(b_id));
        assert_eq!(playlist_titles(&player), vec!["A", "C"]);

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);
    }

    #[test]
    fn undo_remove_first_item() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B")];
        let a_id = items[0].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::RemoveFromPlaylist(a_id));
        assert_eq!(playlist_titles(&player), vec!["B"]);

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B"]);
    }

    #[test]
    fn undo_batch_remove_restores_all() {
        let mut player = Player::new();
        let items = vec![
            make_item("A"),
            make_item("B"),
            make_item("C"),
            make_item("D"),
        ];
        let b_id = items[1].id;
        let c_id = items[2].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::RemoveFromPlaylistBatch(vec![b_id, c_id]));
        assert_eq!(playlist_titles(&player), vec!["A", "D"]);

        // Single undo restores both
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C", "D"]);
    }

    #[test]
    fn redo_batch_remove() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];
        let a_id = items[0].id;
        let b_id = items[1].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::RemoveFromPlaylistBatch(vec![a_id, b_id]));
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);

        player.process_command(PlayerCommand::Redo);
        assert_eq!(playlist_titles(&player), vec!["C"]);
    }

    #[test]
    fn redo_remove() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];
        let b_id = items[1].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::RemoveFromPlaylist(b_id));
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);

        player.process_command(PlayerCommand::Redo);
        assert_eq!(playlist_titles(&player), vec!["A", "C"]);
    }

    // --- InsertInPlaylist undo/redo ---

    #[test]
    fn undo_insert_removes_inserted_items() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("C")];
        let a_id = items[0].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));

        let inserted = vec![make_item("B")];
        player.process_command(PlayerCommand::InsertInPlaylist {
            items: inserted,
            after: a_id,
        });
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "C"]);
    }

    // --- MoveInPlaylist undo/redo ---

    #[test]
    fn undo_move_restores_position() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];
        let a_id = items[0].id;
        let c_id = items[2].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));

        // Move A after C: [B, C, A]
        player.process_command(PlayerCommand::MoveInPlaylist {
            id: a_id,
            target: c_id,
            after: true,
        });
        assert_eq!(playlist_titles(&player), vec!["B", "C", "A"]);

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);
    }

    #[test]
    fn redo_move() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];
        let a_id = items[0].id;
        let c_id = items[2].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::MoveInPlaylist {
            id: a_id,
            target: c_id,
            after: true,
        });
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);

        player.process_command(PlayerCommand::Redo);
        assert_eq!(playlist_titles(&player), vec!["B", "C", "A"]);
    }

    // --- MoveItemsInPlaylist (batch) undo/redo ---

    #[test]
    fn undo_batch_move() {
        let mut player = Player::new();
        let items = vec![
            make_item("A"),
            make_item("B"),
            make_item("C"),
            make_item("D"),
        ];
        let a_id = items[0].id;
        let b_id = items[1].id;
        let d_id = items[3].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));

        // Move A,B after D: [C, D, A, B]
        player.process_command(PlayerCommand::MoveItemsInPlaylist {
            ids: vec![a_id, b_id],
            target: d_id,
            after: true,
        });
        assert_eq!(playlist_titles(&player), vec!["C", "D", "A", "B"]);

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C", "D"]);
    }

    // --- ClearPlaylist undo/redo ---

    #[test]
    fn undo_clear_restores_playlist() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::ClearPlaylist);
        assert!(playlist_ids(&player).is_empty());

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);
    }

    #[test]
    fn redo_clear() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B")];

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::ClearPlaylist);
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B"]);

        player.process_command(PlayerCommand::Redo);
        assert!(playlist_ids(&player).is_empty());
    }

    // --- Multi-step undo/redo ---

    #[test]
    fn multiple_undos_in_sequence() {
        let mut player = Player::new();

        player.process_command(PlayerCommand::AddToPlaylist(vec![make_item("A")]));
        player.process_command(PlayerCommand::AddToPlaylist(vec![make_item("B")]));
        player.process_command(PlayerCommand::AddToPlaylist(vec![make_item("C")]));
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B"]);

        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A"]);

        player.process_command(PlayerCommand::Undo);
        assert!(playlist_ids(&player).is_empty());
    }

    #[test]
    fn undo_redo_undo_cycle() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B")];

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::Undo);
        assert!(playlist_ids(&player).is_empty());

        player.process_command(PlayerCommand::Redo);
        assert_eq!(playlist_titles(&player), vec!["A", "B"]);

        player.process_command(PlayerCommand::Undo);
        assert!(playlist_ids(&player).is_empty());
    }

    #[test]
    fn new_action_clears_redo_stack() {
        let mut player = Player::new();
        let items = vec![make_item("A")];

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::Undo);
        assert!(player.undo_stack().can_redo());

        // New action should clear redo
        player.process_command(PlayerCommand::AddToPlaylist(vec![make_item("B")]));
        assert!(!player.undo_stack().can_redo());
    }

    #[test]
    fn undo_on_empty_stack_is_noop() {
        let mut player = Player::new();
        player.process_command(PlayerCommand::Undo);
        assert!(playlist_ids(&player).is_empty());
    }

    #[test]
    fn redo_on_empty_stack_is_noop() {
        let mut player = Player::new();
        player.process_command(PlayerCommand::Redo);
        assert!(playlist_ids(&player).is_empty());
    }

    // --- Non-undoable commands don't push entries ---

    #[test]
    fn playback_commands_not_undoable() {
        let mut player = Player::new();
        player.process_command(PlayerCommand::Pause);
        player.process_command(PlayerCommand::Resume);
        player.process_command(PlayerCommand::NextTrack);
        player.process_command(PlayerCommand::PrevTrack);
        assert!(!player.undo_stack().can_undo());
    }

    #[test]
    fn update_paths_not_undoable() {
        let mut player = Player::new();
        let items = vec![make_item("A")];
        let id = items[0].id;
        player.process_command(PlayerCommand::AddToPlaylist(items));

        let undo_count = player.undo_stack().undo_len();
        player.process_command(PlayerCommand::UpdatePaths(vec![(
            id,
            PathBuf::from("/new/path.flac"),
        )]));
        assert_eq!(player.undo_stack().undo_len(), undo_count);
    }

    // --- Complex scenarios ---

    #[test]
    fn add_remove_undo_undo_produces_original() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];
        let b_id = items[1].id;
        let original_titles = vec!["A", "B", "C"];

        player.process_command(PlayerCommand::AddToPlaylist(items));
        player.process_command(PlayerCommand::RemoveFromPlaylist(b_id));
        assert_eq!(playlist_titles(&player), vec!["A", "C"]);

        // Undo remove → back to A, B, C
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), original_titles);

        // Undo add → empty
        player.process_command(PlayerCommand::Undo);
        assert!(playlist_ids(&player).is_empty());
    }

    #[test]
    fn interleaved_adds_and_moves_undo() {
        let mut player = Player::new();
        let items = vec![make_item("A"), make_item("B"), make_item("C")];
        let a_id = items[0].id;
        let c_id = items[2].id;

        player.process_command(PlayerCommand::AddToPlaylist(items));

        // Move A after C: [B, C, A]
        player.process_command(PlayerCommand::MoveInPlaylist {
            id: a_id,
            target: c_id,
            after: true,
        });
        assert_eq!(playlist_titles(&player), vec!["B", "C", "A"]);

        // Add D: [B, C, A, D]
        player.process_command(PlayerCommand::AddToPlaylist(vec![make_item("D")]));
        assert_eq!(playlist_titles(&player), vec!["B", "C", "A", "D"]);

        // Undo add D: [B, C, A]
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["B", "C", "A"]);

        // Undo move: [A, B, C]
        player.process_command(PlayerCommand::Undo);
        assert_eq!(playlist_titles(&player), vec!["A", "B", "C"]);
    }

    /// Regression test for GitHub #89: AudioEngine must be dropped synchronously
    /// in stop_engine() before the caller changes sample rates. If the engine is
    /// dropped on a background thread, CoreAudio's internal buffer list can be
    /// freed while AudioUnitUninitialize is still tearing it down → crash.
    #[test]
    fn stop_engine_drops_engine_synchronously() {
        use std::sync::atomic::AtomicBool;

        struct MockEngine {
            dropped: Arc<AtomicBool>,
        }
        impl AudioEngineHandle for MockEngine {
            fn start(&self) -> Result<(), BackendError> {
                Ok(())
            }
            fn stop(&self) -> Result<(), BackendError> {
                Ok(())
            }
            fn is_running(&self) -> bool {
                false
            }
        }
        impl Drop for MockEngine {
            fn drop(&mut self) {
                self.dropped.store(true, Ordering::SeqCst);
            }
        }

        let dropped = Arc::new(AtomicBool::new(false));

        // Build a minimal decode handle that won't block.
        let stop_flag = Arc::new(AtomicBool::new(false));
        let decode_handle = buffer::DecodeHandle::new_for_test(stop_flag);

        let mut player = Player::new();
        player.active_playback = Some(ActivePlayback {
            engine: Box::new(MockEngine {
                dropped: dropped.clone(),
            }),
            decode_handle,
        });

        player.stop_engine();

        // The engine must already be dropped when stop_engine returns.
        // If this fails, the engine was moved to a background thread — the
        // exact race condition that causes the #89 crash.
        assert!(
            dropped.load(Ordering::SeqCst),
            "AudioEngine must be dropped synchronously in stop_engine (GitHub #89)"
        );
    }
}