mtrack 0.12.0

A multitrack audio and MIDI player for live performances.
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
// Copyright (C) 2026 Michael Wilson <mike@mdwn.dev>
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
//

use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use serde_json::json;
use tokio::sync::{broadcast, watch};
use tokio::time;
use tracing::{info, warn};

use rayon::prelude::*;

use crate::audio::sample_source::audio::AudioSampleSource;
use crate::audio::sample_source::traits::SampleSource;
use crate::player::Player;
use crate::tui::logging::get_log_buffer;

/// Per-track info needed for waveform computation: (track_name, file_path, file_channel).
pub type TrackInfo = (String, PathBuf, u16);

/// Per-track waveform peaks: (track_name, peak_values).
pub type TrackPeaks = (String, Vec<f32>);

/// Polls the player state at ~5Hz and broadcasts playback status messages.
#[tracing::instrument(skip_all, name = "playback_poller")]
pub async fn playback_poller(player: Arc<Player>, tx: broadcast::Sender<String>) {
    let mut interval = time::interval(Duration::from_millis(200));
    interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);

    loop {
        interval.tick().await;

        // Skip if no subscribers
        if tx.receiver_count() == 0 {
            continue;
        }

        let is_playing = player.is_playing().await;
        let playlist = player.get_playlist();

        let raw_elapsed_ms = player
            .elapsed()
            .await
            .ok()
            .flatten()
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);

        let playlist_name = playlist.name().to_string();
        let playlist_position = playlist.position();
        let playlist_songs: Vec<String> = playlist.songs().clone();

        let (song_name, song_duration_ms, tracks, beat_grid, looping, available_sections) =
            if let Some(current_song) = playlist.current() {
                let mappings = player.track_mappings();
                let tracks: Vec<serde_json::Value> = current_song
                    .tracks()
                    .iter()
                    .map(|t| {
                        let output_channels = mappings
                            .as_ref()
                            .and_then(|m| m.get(t.name()))
                            .cloned()
                            .unwrap_or_default();
                        json!({
                            "name": t.name(),
                            "output_channels": output_channels,
                        })
                    })
                    .collect();
                let beat_grid = current_song.beat_grid().map(|g| {
                    json!({
                        "beats": g.beats,
                        "measure_starts": g.measure_starts,
                    })
                });

                let available_sections: Vec<serde_json::Value> = current_song
                    .sections()
                    .iter()
                    .map(|s| {
                        json!({
                            "name": s.name,
                            "start_measure": s.start_measure,
                            "end_measure": s.end_measure,
                        })
                    })
                    .collect();

                (
                    current_song.name().to_string(),
                    current_song.duration().as_millis() as u64,
                    tracks,
                    beat_grid,
                    current_song.loop_playback(),
                    available_sections,
                )
            } else {
                (String::new(), 0, vec![], None, false, vec![])
            };

        let available_playlists = player.list_playlists();
        let persisted_playlist_name = player.persisted_playlist_name();

        // Get active section loop info.
        let active_section = player.active_section().map(|s| {
            json!({
                "name": s.name,
                "start_ms": s.start_time.as_millis() as u64,
                "end_ms": s.end_time.as_millis() as u64,
            })
        });

        // Get reactive loop state info.
        let reactive_loop_state = {
            use crate::player::ReactiveLoopState;
            let state = player.reactive_loop_state();
            match &state {
                ReactiveLoopState::Idle => json!({"state": "idle"}),
                ReactiveLoopState::SectionOffered(b) => json!({
                    "state": "section_offered",
                    "section_name": b.name,
                }),
                ReactiveLoopState::LoopArmed(b) => json!({
                    "state": "loop_armed",
                    "section_name": b.name,
                }),
                ReactiveLoopState::Looping(b) => json!({
                    "state": "looping",
                    "section_name": b.name,
                }),
                ReactiveLoopState::BreakRequested(b) => json!({
                    "state": "break_requested",
                    "section_name": b.name,
                }),
            }
        };
        // For looping, wrap elapsed time to show position within the current
        // loop/section iteration rather than total time since first play.
        let elapsed_ms = if let Some(ref section) = player.active_section() {
            let start_ms = section.start_time.as_millis() as u64;
            let end_ms = section.end_time.as_millis() as u64;
            let section_duration = end_ms.saturating_sub(start_ms);
            if section_duration > 0 && raw_elapsed_ms >= start_ms {
                (raw_elapsed_ms - start_ms) % section_duration + start_ms
            } else {
                raw_elapsed_ms
            }
        } else if looping && song_duration_ms > 0 {
            raw_elapsed_ms % song_duration_ms
        } else {
            raw_elapsed_ms
        };

        let msg = json!({
            "type": "playback",
            "is_playing": is_playing,
            "elapsed_ms": elapsed_ms,
            "song_name": song_name,
            "song_duration_ms": song_duration_ms,
            "playlist_name": playlist_name,
            "playlist_position": playlist_position,
            "playlist_songs": playlist_songs,
            "tracks": tracks,
            "available_playlists": available_playlists,
            "persisted_playlist_name": persisted_playlist_name,
            "locked": player.is_locked(),
            "beat_grid": beat_grid,
            "available_sections": available_sections,
            "active_section": active_section,
            "looping": looping,
            "reactive_loop_state": reactive_loop_state,
        });

        let _ = tx.send(msg.to_string());
    }
}

/// Watches the shared state snapshot (fixtures + active effects) and broadcasts changes.
#[tracing::instrument(skip_all, name = "state_poller")]
pub async fn state_poller(
    mut state_rx: watch::Receiver<Arc<crate::state::StateSnapshot>>,
    tx: broadcast::Sender<String>,
) {
    loop {
        // Wait for the state to change
        if state_rx.changed().await.is_err() {
            break; // Sender dropped
        }

        if tx.receiver_count() == 0 {
            continue;
        }

        let snapshot = state_rx.borrow_and_update().clone();

        let fixtures: serde_json::Map<String, serde_json::Value> = snapshot
            .fixtures
            .iter()
            .map(|f| {
                let channels: serde_json::Map<String, serde_json::Value> = f
                    .channels
                    .iter()
                    .map(|(k, v)| (k.clone(), json!(*v)))
                    .collect();
                (f.name.clone(), serde_json::Value::Object(channels))
            })
            .collect();

        let msg = json!({
            "type": "state",
            "fixtures": fixtures,
            "active_effects": snapshot.active_effects,
        });

        let _ = tx.send(msg.to_string());
    }
}

/// Polls the log ring buffer at ~2Hz and broadcasts log lines.
#[tracing::instrument(skip_all, name = "log_poller")]
pub async fn log_poller(tx: broadcast::Sender<String>) {
    let mut interval = time::interval(Duration::from_millis(500));
    interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);

    // Track how many log lines we've already sent
    let mut last_sent_count: usize = 0;

    loop {
        interval.tick().await;

        if tx.receiver_count() == 0 {
            continue;
        }

        let buffer = match get_log_buffer() {
            Some(buf) => buf,
            None => continue,
        };

        // Acquire the log buffer lock on the blocking thread pool so we never
        // block a tokio worker thread.  The TuiLogLayer acquires this same
        // parking_lot::Mutex on every log event from any thread.
        let skip_from = last_sent_count;
        let (new_lines, new_count) = match tokio::task::spawn_blocking(move || {
            let buf = buffer.lock();

            let current_len = buf.len();
            let mut adjusted_skip = skip_from;
            if current_len < adjusted_skip {
                adjusted_skip = 0;
            }
            if current_len == adjusted_skip {
                return (Vec::new(), adjusted_skip);
            }

            let lines: Vec<serde_json::Value> = buf
                .iter()
                .skip(adjusted_skip)
                .map(|line| {
                    // Parse "LEVEL target: message" format from TuiLogLayer
                    let (level, rest) = line.split_once(' ').unwrap_or(("INFO", line));
                    let (target, message) = rest.split_once(": ").unwrap_or(("", rest));
                    json!({
                        "level": level,
                        "target": target,
                        "message": message,
                    })
                })
                .collect();

            (lines, current_len)
        })
        .await
        {
            Ok(result) => result,
            Err(_) => continue,
        };

        last_sent_count = new_count;

        if new_lines.is_empty() {
            continue;
        }

        let msg = json!({
            "type": "logs",
            "lines": new_lines,
        });

        let _ = tx.send(msg.to_string());
    }
}

/// Shared waveform cache: song name → [(track_name, peaks)].
/// ~2 KB per track in memory; safe to cache entire setlists.
pub type WaveformCache = Arc<parking_lot::Mutex<HashMap<String, Vec<(String, Vec<f32>)>>>>;

/// Creates a new empty waveform cache.
pub fn new_waveform_cache() -> WaveformCache {
    Arc::new(parking_lot::Mutex::new(HashMap::new()))
}

/// Polls for song changes and sends waveform peaks to WebSocket clients.
///
/// Checks the shared cache first; on a miss, computes peaks on demand via
/// `spawn_blocking` and inserts the result into the cache.
#[tracing::instrument(skip_all, name = "waveform_poller")]
pub async fn waveform_poller(
    player: Arc<Player>,
    tx: broadcast::Sender<String>,
    cache: WaveformCache,
) {
    let mut interval = time::interval(Duration::from_millis(500));
    interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);

    let mut last_song_name = String::new();

    loop {
        interval.tick().await;

        if tx.receiver_count() == 0 {
            continue;
        }

        let playlist = player.get_playlist();
        let current_song = match playlist.current() {
            Some(song) => song,
            None => continue,
        };
        let song_name = current_song.name().to_string();

        if song_name == last_song_name {
            continue;
        }
        last_song_name = song_name.clone();

        // Check cache first
        let cached = cache.lock().get(&song_name).cloned();
        let track_peaks = if let Some(cached) = cached {
            cached
        } else {
            // Collect track info (owned data) for the blocking task
            let track_infos: Vec<TrackInfo> = current_song
                .tracks()
                .iter()
                .map(|t| {
                    (
                        t.name().to_string(),
                        t.file().to_path_buf(),
                        t.file_channel(),
                    )
                })
                .collect();
            let song_dir = current_song.base_path().to_path_buf();

            let song_name_for_task = song_name.clone();
            info!("Computing waveform for '{}'", song_name_for_task);
            let start = std::time::Instant::now();
            let peaks_result = tokio::task::spawn_blocking(move || {
                compute_waveform_peaks(&song_dir, &track_infos)
            })
            .await;
            info!(
                "Waveform for '{}' computed in {:.1?}",
                song_name,
                start.elapsed()
            );

            // Song changed while we were computing — discard stale result
            let current_now = player
                .get_playlist()
                .current()
                .map(|s| s.name().to_string())
                .unwrap_or_default();
            if current_now != song_name_for_task {
                last_song_name = String::new(); // Force recompute on next tick
                continue;
            }

            match peaks_result {
                Ok(peaks) => {
                    cache.lock().insert(song_name.clone(), peaks.clone());
                    peaks
                }
                Err(e) => {
                    warn!("Waveform computation task failed: {}", e);
                    continue;
                }
            }
        };

        let tracks_json: Vec<serde_json::Value> = track_peaks
            .into_iter()
            .map(|(name, peaks)| {
                json!({
                    "name": name,
                    "peaks": peaks,
                })
            })
            .collect();

        let msg = json!({
            "type": "waveform",
            "song_name": song_name,
            "tracks": tracks_json,
        });

        let _ = tx.send(msg.to_string());
    }
}

/// Watches the ConfigStore for mutations and broadcasts a signal to WebSocket clients.
///
/// This is event-driven (not polling): it waits on the ConfigStore's broadcast channel
/// and sends a lightweight notification so clients know to re-fetch config.
#[tracing::instrument(skip_all, name = "config_watcher")]
pub async fn config_watcher(player: Arc<Player>, tx: broadcast::Sender<String>) {
    let store = match player.config_store() {
        Some(s) => s,
        None => return, // No config store — nothing to watch.
    };

    let mut rx = store.subscribe();

    loop {
        match rx.recv().await {
            Ok(()) => {
                if tx.receiver_count() == 0 {
                    continue;
                }
                let msg = json!({ "type": "config_changed" });
                let _ = tx.send(msg.to_string());
            }
            Err(broadcast::error::RecvError::Lagged(n)) => {
                warn!("config_watcher missed {} change notifications", n);
                // Still send one notification so clients know to re-fetch.
                if tx.receiver_count() > 0 {
                    let msg = json!({ "type": "config_changed" });
                    let _ = tx.send(msg.to_string());
                }
            }
            Err(broadcast::error::RecvError::Closed) => break,
        }
    }
}

/// Background pre-warms the waveform cache for all songs.
///
/// Collects all uncached songs and computes their waveform peaks in parallel
/// using rayon. Waits for playback to stop before starting computation to
/// avoid competing with audio playback for CPU and I/O.
#[tracing::instrument(skip_all, name = "waveform_prewarmer")]
pub async fn waveform_prewarmer(player: Arc<Player>, cache: WaveformCache) {
    // Small delay before starting so the server can finish initializing
    time::sleep(Duration::from_secs(1)).await;

    // Wait until playback stops before computing
    while player.is_playing().await {
        time::sleep(Duration::from_secs(1)).await;
    }

    let all_songs = match player.get_all_songs_playlist() {
        Some(playlist) => playlist,
        None => return,
    };
    let song_names: Vec<String> = all_songs.songs().clone();
    let total_songs = song_names.len();

    // Collect track info for all uncached songs up front
    let uncached_songs: Vec<(String, PathBuf, Vec<TrackInfo>)> = song_names
        .iter()
        .filter(|name| !cache.lock().contains_key(*name))
        .filter_map(|name| {
            let song = all_songs.get_song(name)?;
            let song_dir = song.base_path().to_path_buf();
            let track_infos: Vec<TrackInfo> = song
                .tracks()
                .iter()
                .map(|t| {
                    (
                        t.name().to_string(),
                        t.file().to_path_buf(),
                        t.file_channel(),
                    )
                })
                .collect();
            Some((name.clone(), song_dir, track_infos))
        })
        .collect();

    let uncached_count = uncached_songs.len();
    if uncached_count == 0 {
        info!("Waveform prewarm: all {} songs already cached", total_songs);
        return;
    }

    info!(
        "Waveform prewarm starting for {} uncached songs ({} total)",
        uncached_count, total_songs
    );
    let total_start = std::time::Instant::now();

    // Compute all songs in parallel using rayon
    let results: Vec<(String, Vec<TrackPeaks>)> = tokio::task::spawn_blocking(move || {
        uncached_songs
            .into_par_iter()
            .map(|(name, song_dir, track_infos)| {
                let start = std::time::Instant::now();
                let peaks = compute_waveform_peaks(&song_dir, &track_infos);
                info!(
                    "Prewarmed waveform for '{}' in {:.1?}",
                    name,
                    start.elapsed()
                );
                (name, peaks)
            })
            .collect()
    })
    .await
    .unwrap_or_default();

    // Insert all results into cache
    let mut cache_guard = cache.lock();
    for (name, peaks) in results {
        cache_guard.insert(name, peaks);
    }
    drop(cache_guard);

    info!(
        "Waveform prewarm complete for {} songs in {:.1?}",
        uncached_count,
        total_start.elapsed()
    );
}

/// Computes waveform peaks for all tracks in parallel, using the disk cache
/// when available. Returns (track_name, peaks) pairs.
///
/// Loads valid cached peaks first, computes only uncached tracks, then saves
/// newly computed peaks back to disk.
pub fn compute_waveform_peaks(song_dir: &std::path::Path, tracks: &[TrackInfo]) -> Vec<TrackPeaks> {
    const NUM_BUCKETS: usize = 500;

    let cached = crate::song_cache::load_cached_peaks(song_dir, tracks);

    // Split tracks into cached and uncached.
    let mut results: Vec<TrackPeaks> = Vec::with_capacity(tracks.len());
    let uncached: Vec<&TrackInfo> = tracks
        .iter()
        .filter(|(name, _, _)| !cached.contains_key(name))
        .collect();

    // Compute uncached tracks in parallel.
    let newly_computed: Vec<TrackPeaks> = uncached
        .par_iter()
        .map(|(name, file, file_channel)| {
            let peaks = compute_track_peaks(file, *file_channel, NUM_BUCKETS);
            (name.clone(), peaks)
        })
        .collect();

    // Save newly computed peaks to disk.
    if !newly_computed.is_empty() {
        let save_data: Vec<(String, PathBuf, u16, Vec<f32>)> = newly_computed
            .iter()
            .filter_map(|(name, peaks)| {
                let (_, file, channel) = tracks.iter().find(|(n, _, _)| n == name)?;
                Some((name.clone(), file.clone(), *channel, peaks.clone()))
            })
            .collect();

        if let Err(e) = crate::song_cache::save_peaks(song_dir, &save_data) {
            warn!("Failed to save waveform cache: {}", e);
        }
    }

    // Merge: preserve original track order.
    for (name, _file, _channel) in tracks {
        if let Some(peaks) = cached.get(name) {
            results.push((name.clone(), peaks.clone()));
        } else if let Some(peaks) = newly_computed.iter().find(|(n, _)| n == name) {
            results.push(peaks.clone());
        } else {
            results.push((name.clone(), vec![]));
        }
    }

    results
}

/// Computes peak values for a single track using bulk buffer reads.
///
/// Uses `AudioSampleSource::read_samples` to read large chunks at a time,
/// avoiding per-sample virtual dispatch overhead.
fn compute_track_peaks(file: &std::path::Path, file_channel: u16, num_buckets: usize) -> Vec<f32> {
    let mut source = match AudioSampleSource::from_file(file, None, 4096) {
        Ok(s) => s,
        Err(e) => {
            warn!("Failed to open audio file {}: {}", file.display(), e);
            return vec![];
        }
    };

    let channel_count = source.channel_count() as usize;
    if channel_count == 0 {
        return vec![];
    }

    // file_channel is 1-indexed
    let target_channel = (file_channel as usize).saturating_sub(1);
    if target_channel >= channel_count {
        warn!(
            "file_channel {} exceeds channel count {} for {}",
            file_channel,
            channel_count,
            file.display()
        );
        return vec![];
    }

    // Estimate total mono samples from duration to size buckets up front
    let estimated_samples = source
        .duration()
        .map(|d| (d.as_secs_f64() * source.sample_rate() as f64) as usize)
        .unwrap_or(0);

    let samples_per_bucket = if estimated_samples > 0 {
        estimated_samples.div_ceil(num_buckets)
    } else {
        // Unknown duration: use a reasonable default, resize at end
        4096
    };

    let mut peaks = vec![0.0_f32; num_buckets];
    let mut mono_sample_idx: usize = 0;
    let mut interleaved_idx: usize = 0;

    // Read in chunks of ~16K interleaved samples at a time
    let mut buf = vec![0.0_f32; 16384];
    loop {
        let n = match source.read_samples(&mut buf) {
            Ok(0) => break,
            Ok(n) => n,
            Err(_) => break,
        };

        for &sample in &buf[..n] {
            let ch = interleaved_idx % channel_count;
            interleaved_idx += 1;

            if ch == target_channel {
                let bucket = (mono_sample_idx / samples_per_bucket).min(num_buckets - 1);
                let abs = sample.abs();
                if abs > peaks[bucket] {
                    peaks[bucket] = abs;
                }
                mono_sample_idx += 1;
            }
        }
    }

    // If we had no samples, return empty
    if mono_sample_idx == 0 {
        return vec![];
    }

    // Trim trailing empty buckets (if file was shorter than estimated)
    let used_buckets = (mono_sample_idx / samples_per_bucket + 1).min(num_buckets);
    peaks.truncate(used_buckets);

    // Normalize to 0.0 - 1.0
    let max_peak = peaks.iter().cloned().fold(0.0_f32, f32::max);
    if max_peak > 0.0 {
        for p in &mut peaks {
            *p /= max_peak;
        }
    }

    peaks
}

/// Builds the initial metadata JSON from the lighting system.
///
/// Sent to each WebSocket client on connect so the stage view knows fixture
/// names, types, and spatial tags.
pub fn build_metadata_json(
    lighting_system: Option<&Arc<Mutex<crate::lighting::system::LightingSystem>>>,
) -> String {
    let mut fixtures = serde_json::Map::new();

    if let Some(ls) = lighting_system {
        let system = ls.lock();
        if let Ok(fixture_infos) = system.get_current_venue_fixtures() {
            let venue_fixtures = get_venue_fixture_tags(&system);

            for fi in &fixture_infos {
                let tags = venue_fixtures.get(&fi.name).cloned().unwrap_or_default();

                let fixture_meta = json!({
                    "tags": tags,
                    "type": fi.fixture_type,
                });
                fixtures.insert(fi.name.clone(), fixture_meta);
            }
        }
    }

    let msg = json!({
        "type": "metadata",
        "fixtures": fixtures,
    });
    msg.to_string()
}

/// Extracts fixture names -> tags from the lighting system's current venue.
fn get_venue_fixture_tags(
    system: &crate::lighting::system::LightingSystem,
) -> HashMap<String, Vec<String>> {
    let mut result = HashMap::new();
    if let Some(venue) = system.get_current_venue() {
        for (name, fixture) in venue.fixtures() {
            result.insert(name.clone(), fixture.tags().to_vec());
        }
    }
    result
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn new_waveform_cache_is_empty() {
        let cache = new_waveform_cache();
        assert!(cache.lock().is_empty());
    }

    #[test]
    fn waveform_cache_insert_and_retrieve() {
        let cache = new_waveform_cache();
        let peaks = vec![("track1".to_string(), vec![0.5, 1.0, 0.3])];
        cache.lock().insert("Song 1".to_string(), peaks.clone());

        let retrieved = cache.lock().get("Song 1").cloned();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap(), peaks);
    }

    #[test]
    fn build_metadata_json_no_lighting() {
        let json_str = build_metadata_json(None);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");
        assert_eq!(parsed["type"], "metadata");
        assert!(parsed["fixtures"].is_object());
        assert!(parsed["fixtures"].as_object().unwrap().is_empty());
    }

    #[test]
    fn compute_track_peaks_with_test_wav() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("test.wav");

        // Create a simple WAV with known samples
        let samples: Vec<i32> = (0..4410).map(|i| (i * 100) % 32768).collect();
        crate::testutil::write_wav(wav_path.clone(), vec![samples], 44100).expect("write test wav");

        let peaks = compute_track_peaks(&wav_path, 1, 10);
        assert!(!peaks.is_empty());
        // Peaks should be normalized to 0.0-1.0
        for &p in &peaks {
            assert!((0.0..=1.0).contains(&p), "peak {} out of range", p);
        }
        // At least one peak should be 1.0 (the max)
        assert!(
            peaks.iter().any(|&p| (p - 1.0).abs() < f32::EPSILON),
            "expected at least one normalized peak at 1.0"
        );
    }

    #[test]
    fn compute_track_peaks_invalid_channel() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("mono.wav");

        crate::testutil::write_wav(wav_path.clone(), vec![vec![1_i32, 2, 3]], 44100)
            .expect("write wav");

        // file_channel 5 on a mono file — should return empty
        let peaks = compute_track_peaks(&wav_path, 5, 10);
        assert!(peaks.is_empty());
    }

    #[test]
    fn compute_track_peaks_missing_file() {
        let peaks = compute_track_peaks(std::path::Path::new("/nonexistent/file.wav"), 1, 10);
        assert!(peaks.is_empty());
    }

    #[test]
    fn compute_track_peaks_zero_buckets_edge() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("test.wav");
        let samples: Vec<i32> = (0..4410).map(|i| (i * 100) % 32768).collect();
        crate::testutil::write_wav(wav_path.clone(), vec![samples], 44100).expect("write test wav");

        // Even with 1 bucket, should work
        let peaks = compute_track_peaks(&wav_path, 1, 1);
        assert!(!peaks.is_empty());
        assert!(peaks.len() <= 1);
    }

    #[test]
    fn compute_track_peaks_stereo_extracts_correct_channel() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("stereo.wav");

        // Write a properly interleaved stereo WAV: ch1=loud, ch2=silence
        let spec = hound::WavSpec {
            channels: 2,
            sample_rate: 44100,
            bits_per_sample: 32,
            sample_format: hound::SampleFormat::Float,
        };
        let mut writer = hound::WavWriter::create(&wav_path, spec).expect("create wav");
        for _ in 0..44100 {
            writer.write_sample(0.9_f32).unwrap(); // ch1: loud
            writer.write_sample(0.0_f32).unwrap(); // ch2: silence
        }
        writer.finalize().unwrap();

        // file_channel 1 should see the loud signal
        let ch1_peaks = compute_track_peaks(&wav_path, 1, 10);
        assert!(!ch1_peaks.is_empty());
        assert!(
            ch1_peaks.iter().all(|&p| p > 0.5),
            "channel 1 should have loud peaks: {:?}",
            ch1_peaks
        );

        // file_channel 2 should see silence (all zeros)
        let ch2_peaks = compute_track_peaks(&wav_path, 2, 10);
        assert!(!ch2_peaks.is_empty());
        assert!(
            ch2_peaks.iter().all(|&p| p == 0.0),
            "channel 2 should be all zeros: {:?}",
            ch2_peaks
        );
    }

    #[test]
    fn waveform_cache_overwrite() {
        let cache = new_waveform_cache();
        let peaks1 = vec![("t1".to_string(), vec![0.5])];
        let peaks2 = vec![("t2".to_string(), vec![1.0])];
        cache.lock().insert("Song".to_string(), peaks1);
        cache.lock().insert("Song".to_string(), peaks2.clone());

        let retrieved = cache.lock().get("Song").cloned().unwrap();
        assert_eq!(retrieved, peaks2);
    }

    #[test]
    fn waveform_cache_multiple_songs() {
        let cache = new_waveform_cache();
        cache
            .lock()
            .insert("Song A".to_string(), vec![("t".to_string(), vec![0.1])]);
        cache
            .lock()
            .insert("Song B".to_string(), vec![("t".to_string(), vec![0.9])]);

        assert_eq!(cache.lock().len(), 2);
        assert!(cache.lock().contains_key("Song A"));
        assert!(cache.lock().contains_key("Song B"));
    }

    use crate::player::PlayerDevices;
    use crate::playlist;
    use crate::songs::{Song, Songs};

    /// Creates a test Player with no hardware devices.
    fn test_player(song_names: &[&str]) -> Arc<crate::player::Player> {
        let mut map = std::collections::HashMap::new();
        for name in song_names {
            map.insert(
                name.to_string(),
                Arc::new(Song::new_for_test(name, &["track1"])),
            );
        }
        let songs = Arc::new(Songs::new(map));
        let playlist_config = crate::config::Playlist::new(
            &song_names.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
        );
        let pl = playlist::Playlist::new("test", &playlist_config, songs.clone()).unwrap();
        let devices = PlayerDevices {
            audio: None,
            mappings: None,
            midi: None,
            dmx_engine: None,
            sample_engine: None,
            trigger_engine: None,
        };
        let mut playlists = HashMap::new();
        playlists.insert(
            "all_songs".to_string(),
            playlist::from_songs(songs.clone()).unwrap(),
        );
        playlists.insert(pl.name().to_string(), pl);
        Arc::new(
            crate::player::Player::new_with_devices(devices, playlists, "test".to_string(), None)
                .unwrap(),
        )
    }

    #[test]
    fn get_venue_fixture_tags_no_venue() {
        let system = crate::lighting::system::LightingSystem::new();
        let tags = get_venue_fixture_tags(&system);
        assert!(tags.is_empty());
    }

    #[tokio::test]
    async fn playback_poller_sends_message() {
        let player = test_player(&["Song A"]);
        let (tx, mut rx) = broadcast::channel(16);

        let handle = tokio::spawn(playback_poller(player, tx));

        let msg = tokio::time::timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out waiting for playback message")
            .expect("recv error");

        let parsed: serde_json::Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(parsed["type"], "playback");
        assert_eq!(parsed["song_name"], "Song A");
        assert_eq!(parsed["is_playing"], false);
        assert!(parsed["playlist_songs"].is_array());
        assert!(parsed["tracks"].is_array());

        handle.abort();
    }

    #[tokio::test]
    async fn state_poller_sends_on_change() {
        let initial = Arc::new(crate::state::StateSnapshot::default());
        let (state_tx, state_rx) = watch::channel(initial);
        let (tx, mut rx) = broadcast::channel(16);

        let handle = tokio::spawn(state_poller(state_rx, tx));

        // Send a state update with fixtures
        let snapshot = Arc::new(crate::state::StateSnapshot {
            fixtures: vec![crate::state::FixtureSnapshot {
                name: "wash1".to_string(),
                channels: {
                    let mut m = std::collections::HashMap::new();
                    m.insert("red".to_string(), 255);
                    m
                },
            }],
            active_effects: vec!["chase".to_string()],
        });
        state_tx.send(snapshot).unwrap();

        let msg = tokio::time::timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out waiting for state message")
            .expect("recv error");

        let parsed: serde_json::Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(parsed["type"], "state");
        assert!(parsed["fixtures"].is_object());
        assert_eq!(parsed["fixtures"]["wash1"]["red"], 255);
        assert_eq!(parsed["active_effects"][0], "chase");

        handle.abort();
    }

    #[tokio::test]
    async fn state_poller_exits_when_sender_dropped() {
        let initial = Arc::new(crate::state::StateSnapshot::default());
        let (state_tx, state_rx) = watch::channel(initial);
        let (tx, _rx) = broadcast::channel::<String>(16);

        let handle = tokio::spawn(state_poller(state_rx, tx));

        // Drop the sender — poller should exit
        drop(state_tx);

        let result = tokio::time::timeout(Duration::from_secs(2), handle).await;
        assert!(result.is_ok(), "poller should have exited");
    }

    #[tokio::test]
    async fn waveform_poller_sends_waveform_on_song() {
        let player = test_player(&["Song A"]);
        let (tx, mut rx) = broadcast::channel(16);
        let cache = new_waveform_cache();

        // Pre-populate cache so the poller doesn't need real audio files
        cache.lock().insert(
            "Song A".to_string(),
            vec![("track1".to_string(), vec![0.5, 1.0])],
        );

        let handle = tokio::spawn(waveform_poller(player, tx, cache));

        let msg = tokio::time::timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out waiting for waveform message")
            .expect("recv error");

        let parsed: serde_json::Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(parsed["type"], "waveform");
        assert_eq!(parsed["song_name"], "Song A");
        assert!(parsed["tracks"].is_array());

        handle.abort();
    }

    #[tokio::test]
    async fn waveform_poller_computes_on_cache_miss() {
        let player = test_player(&["Song A"]);
        let (tx, mut rx) = broadcast::channel(16);
        let cache = new_waveform_cache();
        // Don't pre-populate cache — force computation

        let handle = tokio::spawn(waveform_poller(player, tx, cache.clone()));

        let msg = tokio::time::timeout(Duration::from_secs(3), rx.recv())
            .await
            .expect("timed out waiting for waveform message")
            .expect("recv error");

        let parsed: serde_json::Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(parsed["type"], "waveform");
        assert_eq!(parsed["song_name"], "Song A");

        // Should have been cached after computation
        assert!(cache.lock().contains_key("Song A"));

        handle.abort();
    }

    #[tokio::test]
    async fn playback_poller_skips_no_subscribers() {
        let player = test_player(&["Song A"]);
        let (tx, _) = broadcast::channel::<String>(16);

        // Drop the only receiver — poller should not panic
        let handle = tokio::spawn(playback_poller(player, tx));

        // Let it tick a few times with no subscribers
        tokio::time::sleep(Duration::from_millis(500)).await;

        // Now subscribe and verify it sends when we have a subscriber
        // (can't easily test from here since tx was moved, but at least
        // we verified it doesn't panic)
        handle.abort();
    }

    #[tokio::test]
    async fn log_poller_sends_when_buffer_has_lines() {
        // Initialize the global log buffer if not already initialized.
        // init_tui_logging panics on double-init, so ignore errors.
        let _ = std::panic::catch_unwind(|| {
            crate::tui::logging::init_tui_logging(100);
        });

        let buffer =
            crate::tui::logging::get_log_buffer().expect("log buffer should be initialized");

        // Push some test lines
        {
            let mut buf = buffer.lock();
            buf.push_back("INFO test: hello from log_poller test".to_string());
        }

        let (tx, mut rx) = broadcast::channel(16);
        let handle = tokio::spawn(log_poller(tx));

        let msg = tokio::time::timeout(Duration::from_secs(3), rx.recv())
            .await
            .expect("timed out waiting for log message")
            .expect("recv error");

        let parsed: serde_json::Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(parsed["type"], "logs");
        assert!(parsed["lines"].is_array());
        assert!(!parsed["lines"].as_array().unwrap().is_empty());

        handle.abort();
    }

    #[tokio::test]
    async fn log_poller_skips_when_no_new_lines() {
        // Initialize the global log buffer
        let _ = std::panic::catch_unwind(|| {
            crate::tui::logging::init_tui_logging(100);
        });

        let buffer = match crate::tui::logging::get_log_buffer() {
            Some(b) => b,
            None => return,
        };

        let (tx, mut rx) = broadcast::channel(16);
        let handle = tokio::spawn(log_poller(tx));

        // Push a line and wait for it to be sent
        {
            let mut buf = buffer.lock();
            buf.push_back("INFO test: first line".to_string());
        }
        let _ = tokio::time::timeout(Duration::from_secs(2), rx.recv()).await;

        // Don't push any new lines — next tick should skip (line 167)
        // Wait for another tick — it should produce no message
        let result = tokio::time::timeout(Duration::from_millis(800), rx.recv()).await;
        // Either timeout (no message sent) or lagged — both are fine
        if let Ok(Ok(msg)) = result {
            // If we got a message, it might be from accumulated lines;
            // the important thing is the poller doesn't panic
            let _: serde_json::Value = serde_json::from_str(&msg).unwrap();
        }

        handle.abort();
    }

    #[tokio::test]
    async fn waveform_prewarmer_caches_songs() {
        use tokio::time::timeout;

        let player = test_player(&["Song A"]);
        let cache = new_waveform_cache();

        // Pre-populate the cache so prewarmer skips computation
        cache.lock().insert(
            "Song A".to_string(),
            vec![("track1".to_string(), vec![0.5])],
        );

        // Run prewarmer with a timeout — it should skip Song A (already cached)
        // and finish quickly after the 1s initial delay
        let result = timeout(
            Duration::from_secs(3),
            waveform_prewarmer(player, cache.clone()),
        )
        .await;

        // Prewarmer should have completed (all songs already cached)
        assert!(result.is_ok(), "prewarmer should complete within timeout");
        assert!(cache.lock().contains_key("Song A"));
    }

    #[tokio::test]
    async fn waveform_prewarmer_computes_for_uncached() {
        use tokio::time::timeout;

        let player = test_player(&["Song A"]);
        let cache = new_waveform_cache();

        // Don't pre-populate — prewarmer will try to compute peaks.
        // With test songs using /dev/null, peaks will be empty but it
        // should still complete without panicking.
        let result = timeout(
            Duration::from_secs(5),
            waveform_prewarmer(player, cache.clone()),
        )
        .await;

        assert!(result.is_ok(), "prewarmer should complete within timeout");
        // Should have attempted to cache Song A (even if peaks are empty)
        assert!(cache.lock().contains_key("Song A"));
    }

    #[test]
    fn compute_track_peaks_stereo_selects_correct_channel() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("stereo.wav");

        // Create a stereo WAV with different amplitudes per channel
        let ch1: Vec<i32> = (0..4410).map(|i| (i * 10) % 32768).collect();
        let ch2: Vec<i32> = (0..4410).map(|i| (i * 100) % 32768).collect();
        crate::testutil::write_wav(wav_path.clone(), vec![ch1, ch2], 44100)
            .expect("write stereo wav");

        // Both channels should produce peaks
        let peaks_ch1 = compute_track_peaks(&wav_path, 1, 10);
        let peaks_ch2 = compute_track_peaks(&wav_path, 2, 10);

        assert!(!peaks_ch1.is_empty());
        assert!(!peaks_ch2.is_empty());
        // Both should be normalized (max = 1.0)
        assert!(peaks_ch1.iter().any(|&p| (p - 1.0).abs() < f32::EPSILON));
        assert!(peaks_ch2.iter().any(|&p| (p - 1.0).abs() < f32::EPSILON));
    }

    #[test]
    fn compute_track_peaks_large_bucket_count() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("test.wav");
        let samples: Vec<i32> = (0..4410).map(|i| (i * 100) % 32768).collect();
        crate::testutil::write_wav(wav_path.clone(), vec![samples], 44100).expect("write wav");

        // More buckets than samples — should still work
        let peaks = compute_track_peaks(&wav_path, 1, 10000);
        assert!(!peaks.is_empty());
    }

    #[test]
    fn compute_waveform_peaks_missing_file() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let tracks = vec![(
            "missing".to_string(),
            std::path::PathBuf::from("/nonexistent/file.wav"),
            1_u16,
        )];
        let results = compute_waveform_peaks(temp_dir.path(), &tracks);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, "missing");
        assert!(results[0].1.is_empty());
    }

    #[test]
    fn compute_waveform_peaks_multiple_tracks() {
        let temp_dir = tempfile::tempdir().expect("tempdir");

        let wav1 = temp_dir.path().join("track1.wav");
        let wav2 = temp_dir.path().join("track2.wav");

        let samples: Vec<i32> = (0..4410).map(|i| (i * 50) % 32768).collect();
        crate::testutil::write_wav(wav1.clone(), vec![samples.clone()], 44100).expect("write wav1");
        crate::testutil::write_wav(wav2.clone(), vec![samples], 44100).expect("write wav2");

        let tracks = vec![
            ("Track 1".to_string(), wav1, 1_u16),
            ("Track 2".to_string(), wav2, 1_u16),
        ];

        let results = compute_waveform_peaks(temp_dir.path(), &tracks);
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].0, "Track 1");
        assert_eq!(results[1].0, "Track 2");
        assert!(!results[0].1.is_empty());
        assert!(!results[1].1.is_empty());
    }

    #[test]
    fn compute_track_peaks_file_channel_zero_returns_empty() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("test.wav");
        let samples: Vec<i32> = (0..4410).map(|i| (i * 100) % 32768).collect();
        crate::testutil::write_wav(wav_path.clone(), vec![samples], 44100).expect("write wav");

        // file_channel 0 uses saturating_sub to get target_channel 0, which should work
        // (it matches the first channel of a mono file)
        let peaks = compute_track_peaks(&wav_path, 0, 10);
        // With file_channel 0, target_channel = 0 which is valid for a mono file
        assert!(!peaks.is_empty());
    }

    #[test]
    fn compute_track_peaks_all_zeros_returns_empty() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let wav_path = temp_dir.path().join("silence.wav");
        // All-zero samples should produce peaks of 0.0 but still have buckets
        let samples: Vec<i32> = vec![0_i32; 4410];
        crate::testutil::write_wav(wav_path.clone(), vec![samples], 44100).expect("write wav");

        let peaks = compute_track_peaks(&wav_path, 1, 10);
        // All zero peaks, so normalization divides by 0.0 which is skipped,
        // all values should remain 0.0
        assert!(!peaks.is_empty());
        for &p in &peaks {
            assert!((p - 0.0).abs() < f32::EPSILON, "expected 0.0, got {}", p);
        }
    }

    #[test]
    fn compute_waveform_peaks_empty_tracks() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let tracks: Vec<(String, PathBuf, u16)> = vec![];
        let results = compute_waveform_peaks(temp_dir.path(), &tracks);
        assert!(results.is_empty());
    }

    #[tokio::test]
    async fn playback_poller_no_subscribers_does_not_panic() {
        let player = test_player(&["Song A"]);
        let (tx, _rx) = broadcast::channel::<String>(16);

        // Drop the receiver immediately so receiver_count() == 0
        drop(_rx);

        let handle = tokio::spawn(playback_poller(player, tx));

        // Let it tick several times with zero subscribers
        tokio::time::sleep(Duration::from_millis(600)).await;

        // It should still be running without panicking
        assert!(!handle.is_finished());
        handle.abort();
    }

    #[tokio::test]
    async fn state_poller_no_subscribers_skips_send() {
        let initial = Arc::new(crate::state::StateSnapshot::default());
        let (state_tx, state_rx) = watch::channel(initial);
        let (tx, _rx) = broadcast::channel::<String>(16);

        // Drop receiver so receiver_count() == 0
        drop(_rx);

        let handle = tokio::spawn(state_poller(state_rx, tx));

        // Send a state update with no subscribers
        let snapshot = Arc::new(crate::state::StateSnapshot {
            fixtures: vec![crate::state::FixtureSnapshot {
                name: "light1".to_string(),
                channels: std::collections::HashMap::new(),
            }],
            active_effects: vec![],
        });
        state_tx.send(snapshot).unwrap();

        // Let it process with no subscribers
        tokio::time::sleep(Duration::from_millis(200)).await;

        // Should still be running
        assert!(!handle.is_finished());
        handle.abort();
    }

    #[tokio::test]
    async fn waveform_poller_no_subscribers_skips() {
        let player = test_player(&["Song A"]);
        let (tx, _rx) = broadcast::channel::<String>(16);
        let cache = new_waveform_cache();

        // Drop the receiver
        drop(_rx);

        let handle = tokio::spawn(waveform_poller(player, tx, cache));

        // Let it tick with no subscribers
        tokio::time::sleep(Duration::from_millis(600)).await;

        // Should still be running
        assert!(!handle.is_finished());
        handle.abort();
    }

    #[tokio::test]
    async fn log_poller_no_subscribers_skips() {
        let (tx, _rx) = broadcast::channel::<String>(16);

        // Drop the receiver
        drop(_rx);

        let handle = tokio::spawn(log_poller(tx));

        // Let it tick with no subscribers
        tokio::time::sleep(Duration::from_millis(600)).await;

        assert!(!handle.is_finished());
        handle.abort();
    }

    /// Creates a LightingSystem loaded with fixture types and venues from DSL files.
    fn create_test_lighting_system(
        fixture_type_dsl: &str,
        venue_dsl: &str,
        venue_name: &str,
    ) -> (crate::lighting::system::LightingSystem, tempfile::TempDir) {
        use crate::config::lighting::{Directories, Lighting};

        let dir = tempfile::tempdir().expect("tempdir");
        let ft_dir = dir.path().join("fixture_types");
        let venues_dir = dir.path().join("venues");
        std::fs::create_dir(&ft_dir).unwrap();
        std::fs::create_dir(&venues_dir).unwrap();

        std::fs::write(ft_dir.join("types.light"), fixture_type_dsl).unwrap();
        std::fs::write(venues_dir.join("venues.light"), venue_dsl).unwrap();

        let config = Lighting::new(
            Some(venue_name.to_string()),
            None,
            None,
            Some(Directories::new(
                Some("fixture_types".to_string()),
                Some("venues".to_string()),
            )),
        );

        let mut system = crate::lighting::system::LightingSystem::new();
        system.load(&config, dir.path()).unwrap();

        (system, dir)
    }

    #[test]
    fn build_metadata_json_with_lighting_system() {
        let fixture_dsl = r#"fixture_type "wash" {
            channels: 3
            channel_map: {
                "red": 1,
                "green": 2,
                "blue": 3
            }
        }"#;
        let venue_dsl = r#"venue "Test Venue" {
            fixture "front_wash_1" wash @ 1:1 tags ["front", "wash"]
        }"#;

        let (system, _dir) = create_test_lighting_system(fixture_dsl, venue_dsl, "Test Venue");

        let ls = Arc::new(parking_lot::Mutex::new(system));
        let json_str = build_metadata_json(Some(&ls));
        let parsed: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

        assert_eq!(parsed["type"], "metadata");
        assert!(parsed["fixtures"].is_object());

        let fixture_meta = &parsed["fixtures"]["front_wash_1"];
        assert!(fixture_meta.is_object());
        assert_eq!(fixture_meta["type"], "wash");

        let tags = fixture_meta["tags"].as_array().unwrap();
        assert!(tags.contains(&serde_json::json!("front")));
        assert!(tags.contains(&serde_json::json!("wash")));
    }

    #[test]
    fn build_metadata_json_with_fixture_no_tags() {
        let fixture_dsl = r#"fixture_type "par" {
            channels: 1
            channel_map: {
                "dimmer": 1
            }
        }"#;
        let venue_dsl = r#"venue "Test Venue" {
            fixture "par_1" par @ 1:1
        }"#;

        let (system, _dir) = create_test_lighting_system(fixture_dsl, venue_dsl, "Test Venue");

        let ls = Arc::new(parking_lot::Mutex::new(system));
        let json_str = build_metadata_json(Some(&ls));
        let parsed: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

        assert_eq!(parsed["type"], "metadata");
        let fixture_meta = &parsed["fixtures"]["par_1"];
        assert_eq!(fixture_meta["type"], "par");
        let tags = fixture_meta["tags"].as_array().unwrap();
        assert!(tags.is_empty());
    }

    #[test]
    fn get_venue_fixture_tags_with_venue() {
        let fixture_dsl = r#"fixture_type "spot" {
            channels: 1
            channel_map: {
                "dimmer": 1
            }
        }"#;
        let venue_dsl = r#"venue "Live Venue" {
            fixture "spot_1" spot @ 1:1 tags ["overhead", "spot"]
        }"#;

        let (system, _dir) = create_test_lighting_system(fixture_dsl, venue_dsl, "Live Venue");

        let tags = get_venue_fixture_tags(&system);
        assert_eq!(tags.len(), 1);
        let spot_tags = tags.get("spot_1").unwrap();
        assert!(spot_tags.contains(&"overhead".to_string()));
        assert!(spot_tags.contains(&"spot".to_string()));
    }

    #[test]
    fn build_metadata_json_with_multiple_fixtures() {
        let fixture_dsl = r#"fixture_type "generic" {
            channels: 1
            channel_map: {
                "dimmer": 1
            }
        }"#;
        let venue_dsl = r#"venue "Multi" {
            fixture "fixture_1" generic @ 1:1 tags ["group_1"]
            fixture "fixture_2" generic @ 1:2 tags ["group_2"]
            fixture "fixture_3" generic @ 1:3 tags ["group_3"]
        }"#;

        let (system, _dir) = create_test_lighting_system(fixture_dsl, venue_dsl, "Multi");

        let ls = Arc::new(parking_lot::Mutex::new(system));
        let json_str = build_metadata_json(Some(&ls));
        let parsed: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

        let fixtures_obj = parsed["fixtures"].as_object().unwrap();
        assert_eq!(fixtures_obj.len(), 3);
        for i in 1..=3 {
            let key = format!("fixture_{}", i);
            assert!(fixtures_obj.contains_key(&key));
            assert_eq!(fixtures_obj[&key]["type"], "generic");
        }
    }

    #[tokio::test]
    async fn config_watcher_sends_on_mutation() {
        let player = test_player(&["Song A"]);

        // Set up a config store on the player.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.yaml");
        std::fs::write(&path, "songs: songs\n").unwrap();
        let cfg = crate::config::Player::deserialize(&path).unwrap();
        let store = Arc::new(crate::config::ConfigStore::new(cfg, path));
        player.set_config_store(store.clone());

        let (tx, mut rx) = broadcast::channel(16);
        let handle = tokio::spawn(config_watcher(player, tx));

        // Yield to let the watcher subscribe before we mutate.
        tokio::task::yield_now().await;

        // Trigger a mutation so the watcher broadcasts.
        let snap = store.read().await.unwrap();
        store
            .update_midi(
                Some(crate::config::Midi::new("test-midi", None)),
                &snap.checksum,
            )
            .await
            .unwrap();

        let msg = tokio::time::timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timed out waiting for config_changed message")
            .expect("recv error");

        let parsed: serde_json::Value = serde_json::from_str(&msg).unwrap();
        assert_eq!(parsed["type"], "config_changed");

        handle.abort();
    }

    #[tokio::test]
    async fn config_watcher_no_store_exits_immediately() {
        let player = test_player(&["Song A"]);
        // No config store set — watcher should return immediately.
        let (tx, _rx) = broadcast::channel(16);
        let handle = tokio::spawn(config_watcher(player, tx));

        // Should complete quickly since there's no store.
        let result = tokio::time::timeout(Duration::from_secs(2), handle).await;
        assert!(result.is_ok(), "config_watcher should exit when no store");
    }
}