1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
//! Main application state and control flow for the audio player.
//!
//! This module serves as the central coordinator for the terminal-based audio player,
//! managing the interaction between the audio engine, user interface, file browser,
//! and save functionality. It handles the main event loop, keyboard input processing,
//! and state transitions between different modes (playback, browsing, saving).
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use log::info;
use ratatui::{Terminal, backend::CrosstermBackend};
use std::{error::Error, io, path::PathBuf, time::Duration};
use super::audio::AudioEngine;
use super::browser::Browser;
use super::save_dialog::SaveDialog;
use super::telemetry::{AudioTelemetry, TelemetryConfig};
use super::timeline_waveform::{TimelineWaveform, WaveformProgress};
use super::ui;
use super::waveform::WaveformBuffer;
use std::sync::mpsc;
use zim_studio::utils::sidecar::{SidecarCloneMode, clone_sidecar, get_sidecar_path};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ViewMode {
Player,
Browser,
}
/// Waveform visualization display mode
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum WaveformDisplayMode {
Line, // Braille markers with connected lines (smooth)
Scatter, // Dot markers as individual points (vintage)
#[default]
Vectorscope, // X/Y plot of left vs right channel (stereo phase)
}
impl WaveformDisplayMode {
/// Cycle to the next display mode
pub fn next(self) -> Self {
match self {
Self::Vectorscope => Self::Line,
Self::Line => Self::Scatter,
Self::Scatter => Self::Vectorscope,
}
}
/// Get display name for UI
pub fn label(&self) -> &'static str {
match self {
Self::Line => "line",
Self::Scatter => "scatter",
Self::Vectorscope => "vector",
}
}
}
pub struct App {
pub should_quit: bool,
pub current_file: Option<String>,
pub is_playing: bool,
pub audio_engine: Option<AudioEngine>,
pub waveform_buffer: WaveformBuffer,
pub timeline_waveform: Option<TimelineWaveform>, // Full-timeline waveform for long file navigation
waveform_progress_rx: Option<mpsc::Receiver<WaveformProgress>>, // Progress updates for async waveform calculation
waveform_result_rx: Option<mpsc::Receiver<Result<TimelineWaveform, String>>>, // Completed waveform from background thread
pub waveform_progress: Option<WaveformProgress>, // Current waveform calculation progress
samples_rx: Option<mpsc::Receiver<Vec<f32>>>,
pub left_level: f32,
pub right_level: f32,
pub is_stereo: bool,
pub browser: Browser,
pub playback_position: f32, // 0.0 to 1.0
pub duration: Option<std::time::Duration>,
pub mark_in: Option<f32>, // 0.0 to 1.0
pub mark_out: Option<f32>, // 0.0 to 1.0
edit_counter: u32, // Track number of edits this session
pub save_dialog: Option<SaveDialog>,
pub is_looping: bool, // Whether we're looping the selection
pub show_timeline_while_playing: bool, // Toggle timeline view during playback (default: oscilloscope)
pub waveform_display_mode: WaveformDisplayMode, // Line, Scatter, or Vectorscope
pub view_mode: ViewMode,
pub telemetry: AudioTelemetry,
previous_left_level: f32, // For slew gate rate calculation
previous_right_level: f32, // For slew gate rate calculation
pub editor_message: Option<String>, // Message to show when editor can't open
editor_message_timer: Option<std::time::Instant>, // When to clear the message
pub playlist: Option<Vec<String>>, // Playlist of files to play sequentially
pub playlist_index: usize, // Current position in playlist (0-based)
playlist_total_duration: Option<Duration>, // Cached total duration of all playlist tracks
is_loading_track: bool, // Guard against race conditions during track loading
}
impl App {
pub fn new() -> Self {
Self {
should_quit: false,
current_file: None,
is_playing: false,
audio_engine: None,
waveform_buffer: WaveformBuffer::new(4096),
timeline_waveform: None,
waveform_progress_rx: None,
waveform_result_rx: None,
waveform_progress: None,
samples_rx: None,
left_level: 0.0,
right_level: 0.0,
is_stereo: false,
browser: Browser::new(),
playback_position: 0.0,
duration: None,
mark_in: None,
mark_out: None,
edit_counter: 0,
save_dialog: None,
is_looping: false,
show_timeline_while_playing: false,
waveform_display_mode: WaveformDisplayMode::default(),
view_mode: ViewMode::Player,
telemetry: AudioTelemetry::new(),
previous_left_level: 0.0,
previous_right_level: 0.0,
editor_message: None,
editor_message_timer: None,
playlist: None,
playlist_index: 0,
playlist_total_duration: None,
is_loading_track: false,
}
}
pub fn load_file(&mut self, path: &str) -> Result<(), Box<dyn Error>> {
// Create audio engine if needed
if self.audio_engine.is_none() {
let (engine, samples_rx) = AudioEngine::new()?;
self.audio_engine = Some(engine);
self.samples_rx = Some(samples_rx);
}
// Determine if we need to spawn waveform calculation
let mut should_spawn_waveform = false;
let path_string = path.to_string();
// Load the file
if let Some(engine) = &mut self.audio_engine {
engine.load_file(std::path::Path::new(path))?;
// Update channel info and duration
if let Some(info) = &engine.info {
self.is_stereo = info.channels > 1;
}
self.duration = engine.duration;
self.current_file = Some(path.to_string());
// Calculate timeline waveform for WAV files (async, non-blocking)
let path_obj = std::path::Path::new(path);
let is_wav = path_obj
.extension()
.and_then(|s| s.to_str())
.map(|s| s.eq_ignore_ascii_case("wav"))
.unwrap_or(false);
if is_wav {
should_spawn_waveform = true;
} else {
// Non-WAV files don't get timeline waveforms
self.timeline_waveform = None;
self.waveform_progress = None;
}
// Start playback automatically when file is loaded
self.is_playing = true;
engine.play();
}
// Spawn waveform calculation if needed (outside the engine borrow)
if should_spawn_waveform {
self.spawn_waveform_calculation(path_string);
}
Ok(())
}
/// Spawn background thread to calculate timeline waveform
fn spawn_waveform_calculation(&mut self, path: String) {
let (progress_tx, progress_rx) = mpsc::channel();
let (result_tx, result_rx) = mpsc::channel();
self.waveform_progress_rx = Some(progress_rx);
self.waveform_result_rx = Some(result_rx);
self.waveform_progress = Some(WaveformProgress { percentage: 0.0 });
// Spawn calculation thread
std::thread::spawn(move || {
let path_obj = std::path::Path::new(&path);
let result =
TimelineWaveform::from_wav_file_with_progress(path_obj, 1500, Some(progress_tx));
// Send result (success or error) back to main thread
let _ = result_tx.send(result.map_err(|e| e.to_string()));
});
}
/// Poll for waveform calculation updates (call this in the main loop)
pub fn poll_waveform_updates(&mut self) {
// Check for progress updates
if let Some(ref rx) = self.waveform_progress_rx {
while let Ok(progress) = rx.try_recv() {
self.waveform_progress = Some(progress);
}
}
// Check for completed waveform (success or failure)
if let Some(ref rx) = self.waveform_result_rx
&& let Ok(result) = rx.try_recv()
{
match result {
Ok(waveform) => {
self.timeline_waveform = Some(waveform);
}
Err(e) => {
eprintln!("Warning: Could not calculate timeline waveform: {e}");
// Could optionally show error in UI here
}
}
// Always clear progress indicator and cleanup channels
self.waveform_progress = None;
self.waveform_progress_rx = None;
self.waveform_result_rx = None;
}
}
pub fn load_files(
&mut self,
paths: &[String],
gains: Option<Vec<f32>>,
) -> Result<(), Box<dyn Error>> {
// Create audio engine if needed
if self.audio_engine.is_none() {
let (engine, samples_rx) = AudioEngine::new()?;
self.audio_engine = Some(engine);
self.samples_rx = Some(samples_rx);
}
// Load the files for mixing
if let Some(engine) = &mut self.audio_engine {
engine.load_files(paths, gains)?;
// Update channel info and duration
if let Some(info) = &engine.info {
self.is_stereo = info.channels > 1;
}
self.duration = engine.duration;
// Store files info for display
let display_name = if paths.len() == 1 {
paths[0].clone()
} else {
format!("Mixing {} files", paths.len())
};
self.current_file = Some(display_name);
// Start playback automatically when files are loaded
self.is_playing = true;
engine.play();
}
Ok(())
}
/// Load the next track in the playlist.
///
/// Advances to the next track in the playlist and begins playback automatically.
/// Does nothing if already at the last track or no playlist is active.
/// Includes race condition protection to prevent concurrent loading.
///
/// # Errors
///
/// Returns an error if the audio file fails to load.
pub fn load_next_track(&mut self) -> Result<(), Box<dyn Error>> {
// Guard against concurrent loading
if self.is_loading_track {
return Ok(());
}
if let Some(playlist) = &self.playlist
&& self.playlist_index + 1 < playlist.len()
{
self.is_loading_track = true;
self.playlist_index += 1;
let next_file = playlist[self.playlist_index].clone();
info!(
"Loading next track ({}/{}): {}",
self.playlist_index + 1,
playlist.len(),
next_file
);
// Load file and ensure flag is cleared regardless of outcome
let result = self.load_file(&next_file);
self.is_loading_track = false;
result?;
}
Ok(())
}
/// Load the previous track in the playlist.
///
/// Goes back to the previous track in the playlist and begins playback automatically.
/// Does nothing if already at the first track or no playlist is active.
/// Includes race condition protection to prevent concurrent loading.
///
/// # Errors
///
/// Returns an error if the audio file fails to load.
pub fn load_previous_track(&mut self) -> Result<(), Box<dyn Error>> {
// Guard against concurrent loading
if self.is_loading_track {
return Ok(());
}
if let Some(playlist) = &self.playlist
&& self.playlist_index > 0
{
self.is_loading_track = true;
self.playlist_index -= 1;
let prev_file = playlist[self.playlist_index].clone();
info!(
"Loading previous track ({}/{}): {}",
self.playlist_index + 1,
playlist.len(),
prev_file
);
// Load file and ensure flag is cleared regardless of outcome
let result = self.load_file(&prev_file);
self.is_loading_track = false;
result?;
}
Ok(())
}
/// Check if there's a next track available in the playlist.
///
/// # Returns
///
/// `true` if there are more tracks after the current position, `false` otherwise.
pub fn has_next_track(&self) -> bool {
if let Some(playlist) = &self.playlist {
self.playlist_index + 1 < playlist.len()
} else {
false
}
}
/// Check if there's a previous track available in the playlist.
///
/// # Returns
///
/// `true` if there are tracks before the current position, `false` otherwise.
pub fn has_previous_track(&self) -> bool {
self.playlist_index > 0
}
/// Calculate total duration of all files in a playlist
///
/// # Arguments
///
/// * `playlist` - Slice of file paths to calculate duration for
///
/// # Returns
///
/// `Some(Duration)` with the sum of all track durations, or `None` if playlist is empty
/// or any file duration cannot be determined.
fn calculate_playlist_total_duration(playlist: &[String]) -> Option<Duration> {
if playlist.is_empty() {
return None;
}
let mut total_seconds = 0.0;
for file_path in playlist {
let path = std::path::Path::new(file_path);
if let Ok(metadata) = crate::media::metadata::read_audio_metadata(path) {
if let Some(duration) = metadata.duration_seconds {
total_seconds += duration;
} else {
return None; // Can't get duration for this file
}
} else {
return None; // Can't read metadata for this file
}
}
Some(Duration::from_secs_f64(total_seconds))
}
/// Get current playlist position as a formatted string with total duration.
///
/// # Returns
///
/// `Some("1/6 [35:42 total]")` if a playlist is active, `None` otherwise.
/// The format is `current_track/total_tracks [HH:MM:SS total]` (1-indexed).
/// If total duration is not cached, returns just the track position.
pub fn get_playlist_position(&self) -> Option<String> {
self.playlist.as_ref().map(|pl| {
let position = format!("{}/{}", self.playlist_index + 1, pl.len());
// Add cached total duration if available
if let Some(total_duration) = self.playlist_total_duration {
let total_secs = total_duration.as_secs();
let hours = total_secs / 3600;
let minutes = (total_secs % 3600) / 60;
let seconds = total_secs % 60;
if hours > 0 {
format!("{position} [{hours:02}:{minutes:02}:{seconds:02} total]")
} else {
format!("{position} [{minutes:02}:{seconds:02} total]")
}
} else {
position
}
})
}
/// Enable telemetry with default debugging configuration
pub fn enable_debug_telemetry(&mut self) {
let config = TelemetryConfig {
enabled: true,
debug_audio_levels: true,
debug_format_info: true,
capture_interval_ms: 100, // 10Hz for debugging
output_format: "log".to_string(),
..Default::default()
};
self.telemetry.update_config(config);
log::info!("Audio telemetry enabled for slew gate and VC control debugging");
}
/// Disable telemetry
pub fn disable_telemetry(&mut self) {
let mut config = self.telemetry.config().clone();
config.enabled = false;
self.telemetry.update_config(config);
}
pub fn toggle_playback(&mut self) {
if let Some(engine) = &mut self.audio_engine {
if self.is_playing {
engine.pause();
self.is_playing = false;
} else {
// If at 100%, restart from beginning
if self.playback_position >= 0.99 {
let _ = engine.seek_relative(-self.duration.unwrap_or_default().as_secs_f32());
}
engine.play();
self.is_playing = true;
}
}
}
pub fn update_waveform(&mut self) {
self.process_audio_samples();
self.update_playback_state();
self.apply_level_decay();
}
fn process_audio_samples(&mut self) {
let mut samples_to_process = Vec::new();
if let Some(rx) = &self.samples_rx {
while let Ok(samples) = rx.try_recv() {
// Use stereo push for vectorscope support when audio is stereo
if self.is_stereo {
self.waveform_buffer.push_stereo_samples(&samples);
} else {
self.waveform_buffer.push_samples(&samples);
}
if !samples.is_empty() {
samples_to_process.push(samples);
}
}
}
for samples in samples_to_process {
self.calculate_audio_levels(&samples);
}
}
fn calculate_audio_levels(&mut self, samples: &[f32]) {
// Store previous levels for slew gate calculation
self.previous_left_level = self.left_level;
self.previous_right_level = self.right_level;
if self.is_stereo {
self.calculate_stereo_levels(samples);
} else {
self.calculate_mono_levels(samples);
}
// Apply gentler decay for better visibility
self.left_level = (self.left_level * 0.98).max(self.left_level * 0.8);
self.right_level = (self.right_level * 0.98).max(self.right_level * 0.8);
// Capture telemetry data for observability
let playback_state = if self.is_playing {
"playing"
} else {
"stopped"
};
let audio_info = self.audio_engine.as_ref().and_then(|e| e.info.as_ref());
self.telemetry.maybe_capture(
self.left_level,
self.right_level,
self.previous_left_level,
self.previous_right_level,
playback_state,
self.playback_position,
Some(samples),
audio_info,
);
}
fn calculate_stereo_levels(&mut self, samples: &[f32]) {
let mut left_sum = 0.0;
let mut right_sum = 0.0;
let mut left_count = 0;
let mut right_count = 0;
for (i, &sample) in samples.iter().enumerate() {
if i % 2 == 0 {
left_sum += sample * sample;
left_count += 1;
} else {
right_sum += sample * sample;
right_count += 1;
}
}
// Amplify the RMS values to make LEDs more responsive
self.left_level = ((left_sum / left_count.max(1) as f32).sqrt() * 2.0).min(1.0);
self.right_level = ((right_sum / right_count.max(1) as f32).sqrt() * 2.0).min(1.0);
}
fn calculate_mono_levels(&mut self, samples: &[f32]) {
let sum: f32 = samples.iter().map(|s| s * s).sum();
// Mono - amplify for better visibility
let rms = ((sum / samples.len() as f32).sqrt() * 2.0).min(1.0);
self.left_level = rms;
self.right_level = rms;
}
fn update_playback_state(&mut self) {
let mut need_loop_seek = None;
let mut should_stop = false;
if let Some(engine) = &self.audio_engine {
self.playback_position = engine.get_progress();
// Check if we've reached the end (not looping)
if !self.is_looping && self.is_playing && self.playback_position >= 1.0 {
should_stop = true;
}
// Check if we need to loop
if self.is_looping && self.is_playing {
need_loop_seek = self.check_loop_boundaries();
}
}
// Handle end of track - either stop or advance to next in playlist
if should_stop {
// Don't auto-advance if loop mode is active (user wants to keep looping current track)
if self.is_looping {
// Loop mode is active - don't advance, just let loop logic handle it
return;
}
// Check if we have a playlist with more tracks
if self.has_next_track() {
// Auto-advance to next track in playlist
if let Err(e) = self.load_next_track() {
log::error!("Failed to load next track: {e}");
self.is_playing = false;
if let Some(engine) = &self.audio_engine {
engine.pause();
}
}
// Note: load_next_track() calls load_file() which starts playback automatically
} else {
// No more tracks, stop playback
self.is_playing = false;
if let Some(engine) = &self.audio_engine {
engine.pause();
}
}
}
// Apply loop seek if needed
if let (Some(offset), Some(engine)) = (need_loop_seek, &mut self.audio_engine) {
let _ = engine.seek_relative(offset);
}
}
fn check_loop_boundaries(&self) -> Option<f32> {
if let (Some(mark_in), Some(mark_out)) = (self.mark_in, self.mark_out) {
let loop_start = mark_in.min(mark_out);
let loop_end = mark_in.max(mark_out);
// Check if we've reached the end of the loop or are before the start
if (self.playback_position >= loop_end || self.playback_position < loop_start)
&& let Some(duration) = self.duration
{
let current_seconds = duration.as_secs_f32() * self.playback_position;
let start_seconds = duration.as_secs_f32() * loop_start;
return Some(start_seconds - current_seconds);
}
}
None
}
fn apply_level_decay(&mut self) {
// Store previous levels for slew gate calculation
self.previous_left_level = self.left_level;
self.previous_right_level = self.right_level;
if self.is_playing {
self.left_level *= 0.99; // Slower decay for better visibility
self.right_level *= 0.99;
} else {
self.left_level = 0.0;
self.right_level = 0.0;
}
// Capture telemetry for decay behavior (slew gate monitoring)
let playback_state = if self.is_playing {
"playing"
} else {
"stopped"
};
let audio_info = self.audio_engine.as_ref().and_then(|e| e.info.as_ref());
self.telemetry.maybe_capture(
self.left_level,
self.right_level,
self.previous_left_level,
self.previous_right_level,
playback_state,
self.playback_position,
None, // No sample data during decay
audio_info,
);
}
pub fn set_mark_in(&mut self) {
self.mark_in = Some(self.playback_position);
info!("Mark in set at {:.1}%", self.playback_position * 100.0);
}
pub fn set_mark_out(&mut self) {
self.mark_out = Some(self.playback_position);
info!("Mark out set at {:.1}%", self.playback_position * 100.0);
}
pub fn clear_marks(&mut self) {
self.mark_in = None;
self.mark_out = None;
self.is_looping = false; // Stop looping when marks are cleared
info!("Marks cleared");
}
pub fn toggle_loop(&mut self) {
if self.mark_in.is_some() && self.mark_out.is_some() {
self.is_looping = !self.is_looping;
info!(
"Loop {}",
if self.is_looping {
"enabled"
} else {
"disabled"
}
);
// If starting loop, jump to mark in position
if self.is_looping
&& let (Some(mark_in), Some(duration), Some(engine)) =
(self.mark_in, self.duration, &mut self.audio_engine)
{
let start_seconds = duration.as_secs_f32() * mark_in;
let current_seconds = duration.as_secs_f32() * self.playback_position;
let offset = start_seconds - current_seconds;
let _ = engine.seek_relative(offset);
}
} else {
info!("Cannot loop without both marks set");
}
}
pub fn get_selection_duration(&self) -> Option<std::time::Duration> {
if let (Some(mark_in), Some(mark_out), Some(duration)) =
(self.mark_in, self.mark_out, self.duration)
{
let start_secs = duration.as_secs_f32() * mark_in;
let end_secs = duration.as_secs_f32() * mark_out;
let selection_secs = (end_secs - start_secs).abs();
Some(std::time::Duration::from_secs_f32(selection_secs))
} else {
None
}
}
pub fn open_save_dialog(&mut self) {
if let Some(current_file) = &self.current_file {
let path = std::path::Path::new(current_file);
let parent = path.parent().unwrap_or(std::path::Path::new("."));
// Generate suggested filename
let base_name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("audio");
let source_extension = path.extension().and_then(|s| s.to_str()).unwrap_or("wav");
// Always suggest WAV for selections (since we convert FLAC to WAV)
// For full file saves, keep original extension
let has_selection = self.mark_in.is_some() && self.mark_out.is_some();
let extension = if has_selection {
"wav" // Always WAV for selections
} else {
source_extension // Keep original for full file copies
};
let suggested_name = if has_selection {
if self.edit_counter == 0 {
format!("{base_name}_edit.{extension}")
} else {
format!("{}_edit_{}.{}", base_name, self.edit_counter + 1, extension)
}
} else {
format!("{base_name}.{extension}")
};
self.save_dialog = Some(SaveDialog::new(
parent.to_path_buf(),
suggested_name,
has_selection,
));
info!(
"Opened save dialog with filename: {}",
self.save_dialog.as_ref().unwrap().filename
);
}
}
pub fn save_audio(
&self,
path: std::path::PathBuf,
save_selection: bool,
) -> Result<(), Box<dyn Error>> {
if let Some(current_file) = &self.current_file {
if save_selection && self.mark_in.is_some() && self.mark_out.is_some() {
// Save selection
self.save_selection(current_file, path)
} else {
// Save full file (copy audio + sidecar)
std::fs::copy(current_file, &path)?;
info!("Copied full file to: {path:?}");
// Also create sidecar file for the copy
if let Err(e) = clone_sidecar(
std::path::Path::new(current_file),
&path,
SidecarCloneMode::FullCopy,
None,
) {
log::warn!("Failed to create sidecar file: {e}");
// Don't fail the entire operation if sidecar creation fails
}
Ok(())
}
} else {
Err("No file loaded".into())
}
}
fn save_selection(
&self,
source_path: &str,
dest_path: std::path::PathBuf,
) -> Result<(), Box<dyn Error>> {
let (mark_in, mark_out) = match (self.mark_in, self.mark_out) {
(Some(a), Some(b)) => (a.min(b), a.max(b)),
_ => return Err("No selection marks set".into()),
};
// Determine SOURCE format from extension
let source_ext = std::path::Path::new(source_path)
.extension()
.and_then(|e| e.to_str())
.map(|e| e.to_lowercase())
.unwrap_or_default();
// Save the audio selection first
let audio_result = match source_ext.as_str() {
"wav" => self.save_wav_selection(source_path, dest_path.clone(), mark_in, mark_out),
"flac" => {
self.save_flac_to_wav_selection(source_path, dest_path.clone(), mark_in, mark_out)
}
_ => Err(format!("Unsupported source format: {source_ext}").into()),
};
// If audio save succeeded, try to clone and modify the sidecar file
if audio_result.is_ok() {
// Convert normalized positions to actual time in seconds
let duration_secs = self.duration.map(|d| d.as_secs_f32()).unwrap_or(0.0);
let start_time = mark_in * duration_secs;
let end_time = mark_out * duration_secs;
// Get tags from browser as fallback
let tags_fallback: Option<Vec<String>> =
if let Some((idx, _)) = self.browser.filtered_indices.get(self.browser.selected) {
self.browser
.items
.get(*idx)
.map(|audio_file| audio_file.metadata.tags.clone())
} else {
None
};
if let Err(e) = clone_sidecar(
std::path::Path::new(source_path),
&dest_path,
SidecarCloneMode::Selection {
start_time,
end_time,
duration: duration_secs,
},
tags_fallback.as_deref(),
) {
log::warn!("Failed to create sidecar file: {e}");
// Don't fail the entire operation if sidecar creation fails
}
}
audio_result
}
fn save_wav_selection(
&self,
source_path: &str,
dest_path: std::path::PathBuf,
start: f32,
end: f32,
) -> Result<(), Box<dyn Error>> {
use hound::{WavReader, WavWriter};
use std::fs::File;
use std::io::BufReader;
// Open source file
let reader = WavReader::new(BufReader::new(File::open(source_path)?))?;
let spec = reader.spec();
// Calculate sample range
let (start_sample, samples_to_write) = self.calculate_sample_range(&reader, start, end);
// Create output file
let mut writer = WavWriter::create(&dest_path, spec)?;
// Read and write samples based on bit depth
self.copy_wav_samples(
reader,
&mut writer,
spec.bits_per_sample,
start_sample,
samples_to_write,
)?;
writer.finalize()?;
info!("Saved WAV selection to: {dest_path:?}");
Ok(())
}
fn calculate_sample_range(
&self,
reader: &hound::WavReader<std::io::BufReader<std::fs::File>>,
start: f32,
end: f32,
) -> (usize, usize) {
let total_samples = reader.len() as usize;
let start_sample = (start * total_samples as f32) as usize;
let end_sample = (end * total_samples as f32) as usize;
let samples_to_write = end_sample - start_sample;
(start_sample, samples_to_write)
}
fn copy_wav_samples<W: std::io::Write + std::io::Seek>(
&self,
mut reader: hound::WavReader<std::io::BufReader<std::fs::File>>,
writer: &mut hound::WavWriter<W>,
bits_per_sample: u16,
start_sample: usize,
samples_to_write: usize,
) -> Result<(), Box<dyn Error>> {
match bits_per_sample {
16 => self.copy_samples::<i16, _>(&mut reader, writer, start_sample, samples_to_write),
24 | 32 => {
self.copy_samples::<i32, _>(&mut reader, writer, start_sample, samples_to_write)
}
8 => self.copy_samples::<i8, _>(&mut reader, writer, start_sample, samples_to_write),
_ => Err(format!("Unsupported bit depth: {bits_per_sample}").into()),
}
}
fn copy_samples<T, W>(
&self,
reader: &mut hound::WavReader<std::io::BufReader<std::fs::File>>,
writer: &mut hound::WavWriter<W>,
start_sample: usize,
samples_to_write: usize,
) -> Result<(), Box<dyn Error>>
where
T: hound::Sample + std::fmt::Debug,
W: std::io::Write + std::io::Seek,
{
let samples: Vec<T> = reader
.samples::<T>()
.skip(start_sample)
.take(samples_to_write)
.collect::<Result<Vec<_>, _>>()?;
for sample in samples {
writer.write_sample(sample)?;
}
Ok(())
}
fn save_flac_to_wav_selection(
&self,
source_path: &str,
dest_path: std::path::PathBuf,
start: f32,
end: f32,
) -> Result<(), Box<dyn Error>> {
use claxon::FlacReader;
use hound::{WavSpec, WavWriter};
// Open FLAC file
let reader = FlacReader::open(source_path)?;
let info = reader.streaminfo();
// Calculate sample range
let total_samples = info.samples.unwrap_or(0) as usize;
let start_sample = (start * total_samples as f32) as usize;
let end_sample = (end * total_samples as f32) as usize;
// Create WAV spec from FLAC info
let spec = WavSpec {
channels: info.channels as u16,
sample_rate: info.sample_rate,
bits_per_sample: 16, // Convert to 16-bit for compatibility
sample_format: hound::SampleFormat::Int,
};
// Create output WAV file
let mut writer = WavWriter::create(&dest_path, spec)?;
// Read and convert samples
self.convert_flac_samples(
reader,
&mut writer,
info.bits_per_sample,
start_sample,
end_sample,
)?;
writer.finalize()?;
info!("Saved FLAC selection as WAV to: {dest_path:?}");
Ok(())
}
fn convert_flac_samples<W: std::io::Write + std::io::Seek>(
&self,
mut reader: claxon::FlacReader<std::fs::File>,
writer: &mut hound::WavWriter<W>,
bits_per_sample: u32,
start_sample: usize,
end_sample: usize,
) -> Result<(), Box<dyn Error>> {
let mut sample_count = 0;
for sample in reader.samples() {
if sample_count >= start_sample && sample_count < end_sample {
let sample = sample?;
let sample_i16 = self.convert_sample_to_16bit(sample, bits_per_sample);
writer.write_sample(sample_i16)?;
}
sample_count += 1;
if sample_count >= end_sample {
break;
}
}
Ok(())
}
fn convert_sample_to_16bit(&self, sample: i32, bits_per_sample: u32) -> i16 {
match bits_per_sample {
16 => sample as i16,
24 => (sample >> 8) as i16,
32 => (sample >> 16) as i16,
_ => (sample >> (bits_per_sample - 16)) as i16,
}
}
pub fn open_sidecar_in_editor(&mut self) -> Result<Option<PathBuf>, Box<dyn Error>> {
// Get the current file path
let current_file = match &self.current_file {
Some(file) => file,
None => {
self.editor_message = Some("No audio file loaded".to_string());
self.editor_message_timer = Some(std::time::Instant::now());
return Ok(None);
}
};
// Construct sidecar path using utility function
let sidecar_path = get_sidecar_path(std::path::Path::new(current_file));
// Check if sidecar exists
if !sidecar_path.exists() {
self.editor_message =
Some("No sidecar file found - run 'zim update' first".to_string());
self.editor_message_timer = Some(std::time::Instant::now());
return Ok(None);
}
// Return the path to signal that we can open the editor
Ok(Some(sidecar_path))
}
pub fn launch_editor(&mut self, sidecar_path: PathBuf) -> Result<(), Box<dyn Error>> {
// Get editor from environment or use vim as fallback
let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
// Basic security validation - reject if editor contains shell metacharacters
// This helps prevent command injection attacks
if editor.contains('|')
|| editor.contains(';')
|| editor.contains('&')
|| editor.contains('`')
|| editor.contains('$')
|| editor.contains('\n')
|| editor.contains('\r')
|| editor.contains('<')
|| editor.contains('>')
{
self.editor_message =
Some("Invalid EDITOR value: contains shell metacharacters".to_string());
self.editor_message_timer = Some(std::time::Instant::now());
return Err("EDITOR environment variable contains invalid characters".into());
}
// Split editor command into program and args (handle cases like "vim -n")
let editor_parts: Vec<&str> = editor.split_whitespace().collect();
if editor_parts.is_empty() {
return Err("EDITOR environment variable is empty".into());
}
let editor_cmd = editor_parts[0];
let editor_args = &editor_parts[1..];
// Launch editor in a subprocess
let mut cmd = std::process::Command::new(editor_cmd);
for arg in editor_args {
cmd.arg(arg);
}
let status = cmd
.arg(&sidecar_path)
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.status();
match status {
Ok(exit_status) => {
if !exit_status.success() {
self.editor_message = Some(format!("Editor '{editor}' exited with error"));
self.editor_message_timer = Some(std::time::Instant::now());
}
}
Err(e) => {
self.editor_message = Some(format!("Failed to launch editor '{editor}': {e}"));
self.editor_message_timer = Some(std::time::Instant::now());
}
}
Ok(())
}
}
pub fn run_with_file(
file_path: Option<&str>,
_gains: Option<Vec<f32>>,
) -> Result<(), Box<dyn Error>> {
// Initialize logging
init_logging()?;
info!("Starting ZIM Audio Player");
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app and load file if provided
let mut app = App::new();
// Scan current directory for audio files
info!("Scanning directory for audio files...");
if let Err(e) = app.browser.scan_directory(std::path::Path::new(".")) {
log::error!("Could not scan directory: {e}");
}
if let Some(path) = file_path
&& let Err(e) = app.load_file(path)
{
// Clean up terminal before showing error
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
return Err(e);
}
loop {
let res = run_app(&mut terminal, &mut app);
match res {
Err(e) if e.to_string() == "EDITOR_REQUESTED" => {
// Check if we can open the editor and get the sidecar path
match app.open_sidecar_in_editor() {
Ok(Some(sidecar_path)) => {
// Store terminal state
let terminal_state_result = (|| -> Result<(), Box<dyn Error>> {
// Temporarily restore terminal for editor
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
})();
// Only proceed if terminal state was successfully changed
if let Err(term_err) = terminal_state_result {
log::error!("Failed to prepare terminal for editor: {term_err}");
app.editor_message = Some(format!("Terminal error: {term_err}"));
app.editor_message_timer = Some(std::time::Instant::now());
} else {
// Launch editor
if let Err(editor_err) = app.launch_editor(sidecar_path) {
log::error!("Editor launch failed: {editor_err}");
}
// Always attempt to restore terminal state, even if editor failed
let restore_result = (|| -> Result<(), Box<dyn Error>> {
enable_raw_mode()?;
execute!(
terminal.backend_mut(),
EnterAlternateScreen,
EnableMouseCapture
)?;
terminal.hide_cursor()?;
terminal.clear()?;
Ok(())
})();
if let Err(restore_err) = restore_result {
// Terminal restoration failed - this is critical
log::error!("Failed to restore terminal: {restore_err}");
return Err(
format!("Terminal restoration failed: {restore_err}").into()
);
}
}
}
Ok(None) => {
// Editor cannot be opened (message already set in open_sidecar_in_editor)
}
Err(err) => {
log::error!("Error checking sidecar: {err}");
app.editor_message = Some(format!("Error: {err}"));
app.editor_message_timer = Some(std::time::Instant::now());
}
}
// Continue the main loop
continue;
}
Err(e) => {
// Restore terminal before showing error
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
eprintln!("Error: {e}");
return Err(e);
}
Ok(_) => {
// Normal exit
break;
}
}
}
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
}
pub fn run_with_files(
file_paths: &[String],
gains: Option<Vec<f32>>,
) -> Result<(), Box<dyn Error>> {
// Initialize logging
init_logging()?;
info!("Starting ZIM Audio Player in mixing mode");
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app and load files for mixing
let mut app = App::new();
// Load multiple files
if let Err(e) = app.load_files(file_paths, gains) {
// Clean up terminal before showing error
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
return Err(e);
}
loop {
let res = run_app(&mut terminal, &mut app);
match res {
Err(e) if e.to_string() == "EDITOR_REQUESTED" => {
// Check if we can open the editor and get the sidecar path
match app.open_sidecar_in_editor() {
Ok(Some(sidecar_path)) => {
// Store terminal state
let terminal_state_result = (|| -> Result<(), Box<dyn Error>> {
// Temporarily restore terminal for editor
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
})();
// Only proceed if terminal state was successfully changed
if let Err(term_err) = terminal_state_result {
log::error!("Failed to prepare terminal for editor: {term_err}");
app.editor_message = Some(format!("Terminal error: {term_err}"));
app.editor_message_timer = Some(std::time::Instant::now());
} else {
// Launch editor
if let Err(editor_err) = app.launch_editor(sidecar_path) {
log::error!("Editor launch failed: {editor_err}");
}
// Always attempt to restore terminal state, even if editor failed
let restore_result = (|| -> Result<(), Box<dyn Error>> {
enable_raw_mode()?;
execute!(
terminal.backend_mut(),
EnterAlternateScreen,
EnableMouseCapture
)?;
terminal.hide_cursor()?;
terminal.clear()?;
Ok(())
})();
if let Err(restore_err) = restore_result {
// Terminal restoration failed - this is critical
log::error!("Failed to restore terminal: {restore_err}");
return Err(
format!("Terminal restoration failed: {restore_err}").into()
);
}
}
}
Ok(None) => {
// Editor cannot be opened (message already set in open_sidecar_in_editor)
}
Err(err) => {
log::error!("Error checking sidecar: {err}");
app.editor_message = Some(format!("Error: {err}"));
app.editor_message_timer = Some(std::time::Instant::now());
}
}
// Continue the main loop
continue;
}
Err(e) => {
// Restore terminal before showing error
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
eprintln!("Error: {e}");
return Err(e);
}
Ok(_) => {
// Normal exit
break;
}
}
}
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
}
pub fn run_with_playlist(file_paths: &[String]) -> Result<(), Box<dyn Error>> {
// Initialize logging
init_logging()?;
info!(
"Starting ZIM Audio Player in playlist mode with {} tracks",
file_paths.len()
);
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app and set up playlist
let mut app = App::new();
// Scan current directory for audio files (for browser functionality)
info!("Scanning directory for audio files...");
if let Err(e) = app.browser.scan_directory(std::path::Path::new(".")) {
log::error!("Could not scan directory: {e}");
}
// Set up playlist and calculate total duration once
app.playlist = Some(file_paths.to_vec());
app.playlist_index = 0;
app.playlist_total_duration = App::calculate_playlist_total_duration(file_paths);
// Load first track
if !file_paths.is_empty()
&& let Err(e) = app.load_file(&file_paths[0])
{
// Clean up terminal before showing error
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
return Err(e);
}
loop {
let res = run_app(&mut terminal, &mut app);
match res {
Err(e) if e.to_string() == "EDITOR_REQUESTED" => {
// Check if we can open the editor and get the sidecar path
match app.open_sidecar_in_editor() {
Ok(Some(sidecar_path)) => {
// Store terminal state
let terminal_state_result = (|| -> Result<(), Box<dyn Error>> {
// Temporarily restore terminal for editor
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
})();
// Only proceed if terminal state was successfully changed
if let Err(term_err) = terminal_state_result {
log::error!("Failed to prepare terminal for editor: {term_err}");
app.editor_message = Some(format!("Terminal error: {term_err}"));
app.editor_message_timer = Some(std::time::Instant::now());
} else {
// Launch editor
if let Err(editor_err) = app.launch_editor(sidecar_path) {
log::error!("Editor launch failed: {editor_err}");
}
// Always attempt to restore terminal state, even if editor failed
let restore_result = (|| -> Result<(), Box<dyn Error>> {
enable_raw_mode()?;
execute!(
terminal.backend_mut(),
EnterAlternateScreen,
EnableMouseCapture
)?;
terminal.hide_cursor()?;
terminal.clear()?;
Ok(())
})();
if let Err(restore_err) = restore_result {
// Terminal restoration failed - this is critical
log::error!("Failed to restore terminal: {restore_err}");
return Err(
format!("Terminal restoration failed: {restore_err}").into()
);
}
}
}
Ok(None) => {
// Editor cannot be opened (message already set in open_sidecar_in_editor)
}
Err(err) => {
log::error!("Error checking sidecar: {err}");
app.editor_message = Some(format!("Error: {err}"));
app.editor_message_timer = Some(std::time::Instant::now());
}
}
// Continue the main loop
continue;
}
Err(e) => {
// Restore terminal before showing error
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
eprintln!("Error: {e}");
return Err(e);
}
Ok(_) => {
// Normal exit
break;
}
}
}
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
}
fn run_app<B: ratatui::backend::Backend>(
terminal: &mut Terminal<B>,
app: &mut App,
) -> Result<(), Box<dyn Error>>
where
B::Error: 'static,
{
loop {
// Update waveform data
app.update_waveform();
// Poll for timeline waveform calculation updates
app.poll_waveform_updates();
// Clear editor message after 3 seconds
if let Some(timer) = app.editor_message_timer
&& timer.elapsed() > Duration::from_secs(3)
{
app.editor_message = None;
// Use take() to properly clear the Option and avoid resource leak
app.editor_message_timer.take();
}
terminal.draw(|f| ui::draw(f, app))?;
// Poll for events with a short timeout to allow continuous rendering
if event::poll(Duration::from_millis(50))?
&& let Event::Key(key) = event::read()?
{
handle_key_event(app, key)?;
}
if app.should_quit {
return Ok(());
}
}
}
fn handle_key_event(app: &mut App, key: event::KeyEvent) -> Result<(), Box<dyn Error>> {
if app.save_dialog.is_some() {
handle_save_dialog_keys(app, key)
} else {
match app.view_mode {
ViewMode::Player => handle_player_keys(app, key),
ViewMode::Browser => handle_integrated_browser_keys(app, key),
}
}
}
fn handle_save_dialog_keys(app: &mut App, key: event::KeyEvent) -> Result<(), Box<dyn Error>> {
use super::save_dialog::SaveDialogFocus;
let save_dialog = app.save_dialog.as_mut().unwrap();
match key.code {
KeyCode::Esc => {
app.save_dialog = None;
}
KeyCode::Tab => {
save_dialog.toggle_focus();
}
KeyCode::Up => {
if save_dialog.focus == SaveDialogFocus::DirectoryList {
save_dialog.navigate_up();
}
}
KeyCode::Down => {
if save_dialog.focus == SaveDialogFocus::DirectoryList {
save_dialog.navigate_down();
}
}
KeyCode::Enter => {
if save_dialog.focus == SaveDialogFocus::DirectoryList {
save_dialog.enter_directory();
} else {
execute_save(app)?;
}
}
KeyCode::Backspace => {
save_dialog.pop_char();
}
KeyCode::Char(c) => {
save_dialog.push_char(c);
}
_ => {}
}
Ok(())
}
fn execute_save(app: &mut App) -> Result<(), Box<dyn Error>> {
if let Some(save_dialog) = &app.save_dialog {
let save_path = save_dialog.get_full_path();
let has_selection = save_dialog.has_selection;
info!("Saving to: {save_path:?}");
// Perform the save
if let Err(e) = app.save_audio(save_path, has_selection) {
log::error!("Failed to save audio: {e}");
return Err(e);
} else {
app.edit_counter += 1;
}
}
app.save_dialog = None;
Ok(())
}
fn handle_integrated_browser_keys(
app: &mut App,
key: event::KeyEvent,
) -> Result<(), Box<dyn Error>> {
use super::browser::BrowserFocus;
// Universal keys that work regardless of focus
match key.code {
KeyCode::Esc => {
// If search is visible, hide it first. Otherwise exit browser
if app.browser.search_visible {
app.browser.hide_search();
} else {
app.view_mode = ViewMode::Player;
}
return Ok(());
}
KeyCode::Tab => {
// Only allow tab if search is visible
if app.browser.search_visible {
app.browser.toggle_focus();
}
return Ok(());
}
KeyCode::Left => {
// Seek backward (works regardless of focus)
if app.current_file.is_some() {
if key.modifiers.contains(event::KeyModifiers::SHIFT) {
seek_audio_percentage(app, -0.2); // Jump back 20%
} else {
seek_audio(app, -5.0); // Normal 5-second seek
}
}
return Ok(());
}
KeyCode::Right => {
// Seek forward (works regardless of focus)
if app.current_file.is_some() {
if key.modifiers.contains(event::KeyModifiers::SHIFT) {
seek_audio_percentage(app, 0.2); // Jump forward 20%
} else {
seek_audio(app, 5.0); // Normal 5-second seek
}
}
return Ok(());
}
_ => {}
}
// Focus-specific keys
match app.browser.focus {
BrowserFocus::Search => match key.code {
KeyCode::Enter => {
// Enter closes search and returns to file list
app.browser.hide_search();
}
KeyCode::Backspace => app.browser.pop_char(),
KeyCode::Char('c' | 'k') if key.modifiers.contains(event::KeyModifiers::CONTROL) => {
app.browser.clear_search(); // Ctrl+C or Ctrl+K to clear search
}
KeyCode::Char(c) => app.browser.push_char(c),
_ => {}
},
BrowserFocus::Files => {
match key.code {
KeyCode::Up | KeyCode::Char('k') => {
app.browser.select_previous();
// Auto-load the selected file for preview
preview_selected_file(app)?;
}
KeyCode::Down | KeyCode::Char('j') => {
app.browser.select_next();
// Auto-load the selected file for preview
preview_selected_file(app)?;
}
KeyCode::Char('/') => {
// Show search box when / is pressed in file list
app.browser.show_search();
}
KeyCode::Char('h') => {
// Seek backward
if app.current_file.is_some() {
if key.modifiers.contains(event::KeyModifiers::SHIFT) {
seek_audio_percentage(app, -0.2); // Jump back 20%
} else {
seek_audio(app, -5.0); // Normal 5-second seek
}
}
}
KeyCode::Char('l') => {
// Seek forward
if app.current_file.is_some() {
if key.modifiers.contains(event::KeyModifiers::SHIFT) {
seek_audio_percentage(app, 0.2); // Jump forward 20%
} else {
seek_audio(app, 5.0); // Normal 5-second seek
}
}
}
KeyCode::Char(' ') => {
// Toggle play/pause (only in Files focus)
// First ensure we have the selected file loaded
if let Some(path) = app.browser.get_selected_path() {
let path_str = path.to_string_lossy().to_string();
// If no file is loaded or it's different from the selected one, load it
if app.current_file.as_ref() != Some(&path_str) {
preview_selected_file(app)?;
}
// Now toggle playback
app.toggle_playback();
}
}
KeyCode::Enter => {
// Load file and return to player
if let Some(path) = app.browser.get_selected_path() {
let path_str = path.to_string_lossy().to_string();
// Check if we're already playing this file
let was_playing_this_file = app.current_file.as_ref() == Some(&path_str);
let current_position = if was_playing_this_file {
Some(app.playback_position)
} else {
None
};
let was_playing = app.is_playing;
// Load the file (this resets position to 0)
app.load_file(&path_str)?;
// If we were previewing this file, restore the position
if let Some(position) = current_position {
// Seek to the previous position
if let Some(duration) = app.duration
&& let Some(engine) = &mut app.audio_engine
{
// Since load_file resets to position 0, we need to seek forward
// by the absolute amount
let target_seconds = duration.as_secs_f32() * position;
engine.seek_relative(target_seconds)?;
// Note: playback_position will be updated by the next update_waveform call
}
// Restore play state if it was playing
if was_playing {
app.is_playing = true;
if let Some(engine) = &app.audio_engine {
engine.play();
}
}
}
app.view_mode = ViewMode::Player;
}
}
_ => {}
}
}
}
Ok(())
}
fn preview_selected_file(app: &mut App) -> Result<(), Box<dyn Error>> {
// Clone the path to avoid borrow issues
let selected_path = app
.browser
.get_selected_path()
.map(|p| p.to_string_lossy().to_string());
if let Some(path_str) = selected_path {
// Only load if it's an audio file and different from current
if (path_str.ends_with(".wav")
|| path_str.ends_with(".flac")
|| path_str.ends_with(".aiff")
|| path_str.ends_with(".aif"))
&& app.current_file.as_ref() != Some(&path_str)
{
app.load_file(&path_str)?;
// Don't auto-play, let user control with space
app.is_playing = false;
if let Some(engine) = &app.audio_engine {
engine.pause();
}
}
}
Ok(())
}
fn handle_player_keys(app: &mut App, key: event::KeyEvent) -> Result<(), Box<dyn Error>> {
match key.code {
KeyCode::Char('q') => app.should_quit = true,
KeyCode::Char(' ') => app.toggle_playback(),
KeyCode::Char('b') => {
app.view_mode = ViewMode::Browser;
app.browser.hide_search(); // Ensure search is hidden when opening browser
// Initialize browser with current directory
app.browser.scan_directory(std::path::Path::new("."))?;
}
KeyCode::Char('/') => {
app.view_mode = ViewMode::Browser;
app.browser.hide_search(); // Start with search hidden, user can press '/' again to search
// Initialize browser with current directory (preserves existing search)
app.browser.scan_directory(std::path::Path::new("."))?;
}
KeyCode::Left => {
if key.modifiers.contains(event::KeyModifiers::SHIFT) {
seek_audio_percentage(app, -0.2); // Jump back 20%
} else {
seek_audio(app, -5.0); // Normal 5-second seek
}
}
KeyCode::Right => {
if key.modifiers.contains(event::KeyModifiers::SHIFT) {
seek_audio_percentage(app, 0.2); // Jump forward 20%
} else {
seek_audio(app, 5.0); // Normal 5-second seek
}
}
KeyCode::Char('[') | KeyCode::Char('i') => app.set_mark_in(),
KeyCode::Char(']') | KeyCode::Char('o') => app.set_mark_out(),
KeyCode::Char('x') => app.clear_marks(),
KeyCode::Char('s') => app.open_save_dialog(),
KeyCode::Char('l') => app.toggle_loop(),
KeyCode::Char('e') => {
// Signal that we want to open editor
return Err("EDITOR_REQUESTED".into());
}
KeyCode::Char('t') => {
if app.telemetry.config().enabled {
app.disable_telemetry();
info!("Audio telemetry disabled");
} else {
app.enable_debug_telemetry();
info!("Audio telemetry enabled - press 't' again to disable");
}
}
KeyCode::Char('w') => {
// Toggle timeline waveform view while playing
app.show_timeline_while_playing = !app.show_timeline_while_playing;
}
KeyCode::Char('m') => {
// Cycle waveform display mode: Line → Scatter → Vectorscope → Line
app.waveform_display_mode = app.waveform_display_mode.next();
}
KeyCode::Char('n') => {
// Next track in playlist
if app.has_next_track()
&& let Err(e) = app.load_next_track()
{
log::error!("Failed to load next track: {e}");
}
}
KeyCode::Char('p') => {
// Previous track in playlist
if app.has_previous_track()
&& let Err(e) = app.load_previous_track()
{
log::error!("Failed to load previous track: {e}");
}
}
_ => {}
}
Ok(())
}
fn seek_audio(app: &mut App, seconds: f32) {
if let Some(engine) = &mut app.audio_engine {
let _ = engine.seek_relative(seconds);
}
}
fn seek_audio_percentage(app: &mut App, percentage: f32) {
if let (Some(engine), Some(duration)) = (&mut app.audio_engine, app.duration) {
let seconds = duration.as_secs_f32() * percentage;
let _ = engine.seek_relative(seconds);
}
}
fn init_logging() -> Result<(), Box<dyn Error>> {
use simplelog::*;
use std::fs::File;
let log_file = "/tmp/zim-player.log";
CombinedLogger::init(vec![WriteLogger::new(
LevelFilter::Debug,
Config::default(),
File::create(log_file)?,
)])?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn test_new_app_initial_state() {
let app = App::new();
assert!(!app.should_quit);
assert!(app.current_file.is_none());
assert!(!app.is_playing);
assert!(app.audio_engine.is_none());
assert_eq!(app.left_level, 0.0);
assert_eq!(app.right_level, 0.0);
assert!(!app.is_stereo);
assert_eq!(app.playback_position, 0.0);
assert!(app.duration.is_none());
assert!(app.mark_in.is_none());
assert!(app.mark_out.is_none());
assert!(app.save_dialog.is_none());
assert!(!app.is_looping);
assert_eq!(app.view_mode, ViewMode::Player);
}
#[test]
fn test_set_mark_in() {
let mut app = App::new();
app.playback_position = 0.5;
app.set_mark_in();
assert_eq!(app.mark_in, Some(0.5));
}
#[test]
fn test_set_mark_out() {
let mut app = App::new();
app.playback_position = 0.8;
app.set_mark_out();
assert_eq!(app.mark_out, Some(0.8));
}
#[test]
fn test_clear_marks() {
let mut app = App::new();
app.mark_in = Some(0.2);
app.mark_out = Some(0.8);
app.is_looping = true;
app.clear_marks();
assert!(app.mark_in.is_none());
assert!(app.mark_out.is_none());
assert!(!app.is_looping);
}
#[test]
fn test_get_selection_duration_no_marks() {
let app = App::new();
assert!(app.get_selection_duration().is_none());
}
#[test]
fn test_get_selection_duration_with_marks() {
let mut app = App::new();
app.mark_in = Some(0.2);
app.mark_out = Some(0.8);
app.duration = Some(Duration::from_secs(10));
let selection = app.get_selection_duration();
assert!(selection.is_some());
let duration = selection.unwrap();
assert_eq!(duration.as_secs_f32(), 6.0); // (0.8 - 0.2) * 10
}
#[test]
fn test_get_selection_duration_invalid_range() {
let mut app = App::new();
app.mark_in = Some(0.8);
app.mark_out = Some(0.2); // Invalid: out before in
app.duration = Some(Duration::from_secs(10));
let selection = app.get_selection_duration();
// The function uses abs() so it still returns a valid duration
assert!(selection.is_some());
let duration = selection.unwrap();
assert_eq!(duration.as_secs_f32(), 6.0); // abs(0.2 - 0.8) * 10
}
#[test]
fn test_toggle_playback_initial_state() {
let mut app = App::new();
// Without audio engine, toggle should not crash
app.toggle_playback();
assert!(!app.is_playing);
}
#[test]
fn test_toggle_loop_without_marks() {
let mut app = App::new();
app.toggle_loop();
// Should not enable looping without marks
assert!(!app.is_looping);
}
#[test]
fn test_toggle_loop_with_marks() {
let mut app = App::new();
app.mark_in = Some(0.2);
app.mark_out = Some(0.8);
app.toggle_loop();
assert!(app.is_looping);
app.toggle_loop();
assert!(!app.is_looping);
}
#[test]
fn test_open_save_dialog_without_file() {
let mut app = App::new();
app.open_save_dialog();
// Dialog is only created when there's a current file
assert!(app.save_dialog.is_none());
}
#[test]
fn test_open_save_dialog_with_selection() {
let mut app = App::new();
app.current_file = Some("/path/to/audio.wav".to_string());
app.mark_in = Some(0.2);
app.mark_out = Some(0.8);
app.edit_counter = 1;
app.open_save_dialog();
assert!(app.save_dialog.is_some());
let dialog = app.save_dialog.as_ref().unwrap();
assert!(dialog.has_selection);
assert!(dialog.filename.contains("_edit"));
}
#[test]
fn test_check_loop_boundaries_no_marks() {
let app = App::new();
assert!(app.check_loop_boundaries().is_none());
}
#[test]
fn test_check_loop_boundaries_within_bounds() {
let mut app = App::new();
app.mark_in = Some(0.2);
app.mark_out = Some(0.8);
app.playback_position = 0.5;
app.duration = Some(Duration::from_secs(10));
assert!(app.check_loop_boundaries().is_none());
}
#[test]
fn test_check_loop_boundaries_at_end() {
let mut app = App::new();
app.mark_in = Some(0.2);
app.mark_out = Some(0.8);
app.playback_position = 0.9; // Past the end
app.duration = Some(Duration::from_secs(10));
let seek = app.check_loop_boundaries();
assert!(seek.is_some());
assert!(seek.unwrap() < 0.0); // Should seek backwards
}
#[test]
fn test_convert_sample_to_16bit() {
let app = App::new();
// Test 16-bit (no conversion)
assert_eq!(app.convert_sample_to_16bit(1000, 16), 1000);
// Test 24-bit conversion
assert_eq!(app.convert_sample_to_16bit(256000, 24), 1000);
// Test 32-bit conversion
assert_eq!(app.convert_sample_to_16bit(65536000, 32), 1000);
}
#[test]
fn test_apply_level_decay_playing() {
let mut app = App::new();
app.is_playing = true;
app.left_level = 1.0;
app.right_level = 1.0;
app.apply_level_decay();
assert!(app.left_level < 1.0);
assert!(app.right_level < 1.0);
assert_eq!(app.left_level, 0.99);
assert_eq!(app.right_level, 0.99);
}
#[test]
fn test_apply_level_decay_stopped() {
let mut app = App::new();
app.is_playing = false;
app.left_level = 0.5;
app.right_level = 0.5;
app.apply_level_decay();
assert_eq!(app.left_level, 0.0);
assert_eq!(app.right_level, 0.0);
}
#[test]
fn test_get_playlist_position_no_playlist() {
let app = App::new();
assert_eq!(app.get_playlist_position(), None);
}
#[test]
fn test_get_playlist_position_basic() {
let mut app = App::new();
app.playlist = Some(vec![
"file1.flac".to_string(),
"file2.flac".to_string(),
"file3.flac".to_string(),
]);
app.playlist_index = 1; // Second track (0-indexed)
let position = app.get_playlist_position();
assert!(position.is_some());
let pos_str = position.unwrap();
// Should show "2/3" at minimum, may include total duration if files exist
assert!(pos_str.starts_with("2/3"));
}
#[test]
fn test_get_playlist_position_with_cached_duration() {
let mut app = App::new();
app.playlist = Some(vec!["file1.flac".to_string(), "file2.flac".to_string()]);
app.playlist_index = 0;
// Simulate cached total duration (2 minutes 30 seconds)
app.playlist_total_duration = Some(Duration::from_secs(150));
let position = app.get_playlist_position();
assert!(position.is_some());
let pos_str = position.unwrap();
// Should show "1/2 [02:30 total]"
assert_eq!(pos_str, "1/2 [02:30 total]");
}
#[test]
fn test_get_playlist_position_with_cached_duration_hours() {
let mut app = App::new();
app.playlist = Some(vec!["file1.flac".to_string()]);
app.playlist_index = 0;
// Simulate cached total duration (1 hour 23 minutes 45 seconds)
app.playlist_total_duration = Some(Duration::from_secs(5025));
let position = app.get_playlist_position();
assert!(position.is_some());
let pos_str = position.unwrap();
// Should show "1/1 [01:23:45 total]"
assert_eq!(pos_str, "1/1 [01:23:45 total]");
}
}