playr-app 0.19.0

What playr's Rust frontends share: actions, : commands, key bindings, settings and dispatch
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
//! Two DJ decks in playr: `:dj` actions, loading library tracks onto the
//! decks, and editing their beat grids. The engine is `playr-dj`; its design
//! is in `docs/dev/dj-engine.md`.

use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
use std::sync::Arc;

use playr_core::analysis::tempo;
use playr_core::analysis::TempoFix;
use playr_core::audio::bus::Cue;
use playr_core::audio::output::DeviceEvent;
use playr_core::audio::resample::Resample;
use playr_core::audio::{Attachment, Sources, State};
use playr_core::db::Track;
use playr_core::event::JobId;
use playr_core::notice::Notice;
use playr_core::samples;
use playr_core::wave::Peaks;
pub use playr_dj::{Band, CueOut, Curve, Nudge, Range, Side, EQ_DB, HOT_CUES, LOOP_BEATS};
use playr_dj::{BusSetting, DelayParam, Engine, Handle, Returned, Setting};

use crate::dispatch::Frontend;
use crate::fx::{Division, FxSetting, FxState};
use crate::message::Message;
use crate::mix::Strip;

/// A change to a deck's beat grid. Each is stored with the track, so it
/// holds across loads and analyses.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GridEdit {
    /// Twice the tempo, as `:bpm x2` sets it.
    Double,
    Halve,
    /// The grid's beat one beat earlier, to set the downbeat.
    Earlier,
    Later,
    /// The grid moved this many ms later; negative is earlier.
    Offset(f32),
    /// A tap at the deck's position: two or more set the tempo, the last
    /// sets a beat.
    Tap,
    /// Back to the analysis's grid at the analysed tempo.
    Reset,
}

/// What `:dj` does. Values are checked where they are parsed.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DjAction {
    /// Load the track under the cursor.
    Load(Side),
    /// Take over the track the player is playing: load it, then play it
    /// from where the player is, and pause the player.
    Take(Side),
    /// Play, pausing the player; during a held cue, keep playing.
    Play(Side),
    Pause(Side),
    /// CUE pressed and released at once.
    Cue(Side),
    /// CUE pressed (`true`) or released, as a held button sends it.
    CueHold(Side, bool),
    Sync(Side, bool),
    /// The rate fader, in percent.
    Rate(Side, f32),
    Range(Side, Range),
    Nudge(Side, Nudge),
    /// The trim, in dB.
    Gain(Side, f32),
    /// The channel fader, 0 to 1.
    Level(Side, f32),
    /// The crossfader, 0 for deck A to 1 for deck B.
    Xfade(f32),
    /// The crossfader glides to deck A's end, deck B's, or with `None` the
    /// centre.
    XfadeTo(Option<Side>),
    Quantize(bool),
    /// The deck heard on the cue side of the output, or none.
    CueBus(Option<Side>),
    Grid(Side, GridEdit),
    /// An EQ band's gain, in dB.
    Eq(Side, Band, f32),
    Kill(Side, Band, bool),
    /// The filter knob: -1 low-pass, 0 open, 1 high-pass.
    Filter(Side, f32),
    /// Hot cue `n`, from 1: set when empty, else jump there and play.
    HotCue(Side, u8),
    HotClear(Side, u8),
    /// Jump this many beats.
    Jump(Side, f32),
    /// Loop this many beats, or stop looping.
    Loop(Side, Option<f32>),
    CueOut(CueOut),
    Curve(Curve),
    /// Move the head to a time, or a percentage of the track.
    Seek(Side, crate::tape::Pos),
    /// Silence the deck in the main mix; the cue still hears it.
    Mute(Side, bool),
    /// Forget the track waiting to load onto a playing deck.
    Unqueue(Side),
    /// Jump to the next mark (`true`) or the previous one.
    Mark(Side, bool),
    /// On: a track picked for a playing deck waits until it stops. Off: it
    /// replaces the playing track, which fades out, and plays.
    Strict(bool),
    /// The deck's sends to the delay and the reverb, 0 to 1, after its
    /// fader, the crossfader and mute.
    DelaySend(Side, f32),
    ReverbSend(Side, f32),
    /// A setting of the delay or the reverb. Print is the tape's and does
    /// nothing here.
    Fx(FxSetting),
}

/// What the decks report.
#[derive(Debug, Clone, PartialEq)]
pub enum DjMessage {
    Loading(Side),
    Loaded {
        side: Side,
        title: String,
        bpm: Option<f64>,
    },
    /// The track loaded has no current analysis; one runs.
    FindingGrid(Side),
    /// The track has no beat grid: analysis found no clear pulse.
    NoGrid(Side),
    /// The action took effect.
    Done(DjAction),
    /// An action on a deck with nothing loaded.
    Empty(Side),
    /// `load` with no track under the cursor.
    NoTrack,
    /// A load onto a deck that is playing.
    Playing(Side),
    /// Sync to a tempo no rate range reaches.
    OutOfReach(Side),
    /// A take while the player's speed, in cents, is beyond any range.
    SpeedOutOfReach(i32),
    /// The deck took over from the player.
    Took(Side),
    /// A tap that started a new count; one more sets the tempo.
    Tapped(Side),
    /// The cue on channels 3 and 4 with a device of this many channels.
    NoCueChannels(u16),
    /// No mark that way from the head.
    NoMark(Side),
    /// A track picked for a playing deck; it loads once the deck stops.
    Queued {
        side: Side,
        title: String,
    },
    /// A grid edit took effect; the grid now.
    Grid {
        side: Side,
        bpm: f64,
        t0: f64,
    },
    /// The output device went away, and the tracks with it.
    DeviceLost(String),
    Failed(String),
}

impl From<DjMessage> for Message {
    fn from(m: DjMessage) -> Self {
        Message::Dj(m)
    }
}

/// Where the decks play.
enum Output {
    /// The player's stream, summed with what else plays there.
    Bus(Sources),
    /// Nowhere: [`Decks::process`] runs the engine, for tests.
    Manual,
}

/// The engine as a source on the player's stream: its main mix, and its cue
/// routed as the decks' cue-out says.
struct Played(Engine);

impl playr_core::audio::bus::Source for Played {
    fn process(&mut self, main: &mut [f32], cue: &mut [f32]) -> Cue {
        match self.0.process_buses(main, cue) {
            None => Cue::None,
            Some((CueOut::Split, swap)) => Cue::Split { swap },
            Some((CueOut::Channels, swap)) => Cue::Channels { swap },
        }
    }
}

/// The engine playing, or ready to.
struct Live {
    handle: Handle,
    /// Where the engine plays on the player's stream; `None` for manual decks.
    attached: Option<Attachment>,
    engine: Option<Engine>,
    rate: u32,
    /// The interpolation last sent; `None` until one is.
    interp: Option<playr_dsp::Interp>,
}

/// A track read and ready to load.
struct Read {
    samples: Vec<f32>,
    channels: u16,
    peaks: Peaks,
}

/// A load in progress.
struct Loading {
    path: PathBuf,
    title: String,
    result: Receiver<Result<Read, String>>,
}

/// A queued track's load, kept until the engine takes it, so a deck that
/// starts again first leaves it queued.
type Sent = [Option<Track>; 2];

/// A track on a deck.
#[derive(Debug, Clone)]
pub struct Loaded {
    pub path: PathBuf,
    pub title: String,
    pub frames: usize,
    pub peaks: Arc<Peaks>,
    pub grid: Option<tempo::Grid>,
    /// The hot cues, in frames, as last stored.
    pub hot: [Option<f64>; HOT_CUES],
    /// The track's marks, as the sampler set them, in frames, earliest first.
    pub marks: Vec<f64>,
}

/// The mixer's settings as last sent. Rate, range, sync and the transport
/// are read from [`playr_dj::Status`], since sync moves them.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DjState {
    pub gain: [f32; 2],
    pub level: [f32; 2],
    pub xfade: f32,
    pub quantize: bool,
    pub cue_bus: Option<Side>,
    /// Each deck's EQ bands, low to high, in dB, and whether each is killed.
    pub eq: [[f32; 3]; 2],
    pub kill: [[bool; 3]; 2],
    pub filter: [f32; 2],
    pub cue_out: CueOut,
    pub curve: Curve,
    pub mute: [bool; 2],
    pub strict: bool,
    /// Each deck's sends, delay then reverb.
    pub sends: [[f32; 2]; 2],
    pub fx: FxState,
}

impl Default for DjState {
    fn default() -> Self {
        DjState {
            gain: [0.0; 2],
            level: [1.0; 2],
            xfade: 0.5,
            quantize: false,
            cue_bus: None,
            eq: [[0.0; 3]; 2],
            kill: [[false; 3]; 2],
            filter: [0.0; 2],
            cue_out: CueOut::default(),
            curve: Curve::default(),
            mute: [false; 2],
            strict: false,
            sends: [[0.0; 2]; 2],
            fx: FxState::default(),
        }
    }
}

/// Taps longer apart than this, in track seconds, start a new count.
const TAP_GAP: f64 = 2.0;

/// The decks' state on the interface's side.
pub struct Decks {
    /// The master's soft clip knee.
    knee: f32,
    output: Output,
    live: Option<Live>,
    loaded: [Option<Loaded>; 2],
    loading: [Option<Loading>; 2],
    /// Tracks sent to the engine, until it takes or refuses them.
    arriving: [Option<Loaded>; 2],
    /// Analyses started for a loaded track with none, by job.
    analysing: Vec<(JobId, Side, PathBuf)>,
    /// Each deck's taps since the last gap, as track positions in seconds.
    taps: [Vec<f64>; 2],
    /// Tracks each deck's engine has taken, to match against its status.
    loads: [u64; 2],
    /// The track picked for each deck while it played, to load once it stops.
    next: [Option<Track>; 2],
    sent: Sent,
    /// The track reading for each deck replaces the one playing, crossfading.
    crossfade: [bool; 2],
    /// Takes over from the player once the track loads.
    handover: [bool; 2],
    /// The main mix's and the cue's volumes last sent.
    volume: (f32, f32),
    state: DjState,
    errors: (Sender<DeviceEvent>, Receiver<DeviceEvent>),
}

fn i(side: Side) -> usize {
    match side {
        Side::A => 0,
        Side::B => 1,
    }
}

impl Decks {
    /// Decks playing on the player's stream through `sources`, with the
    /// master's soft clip at `knee`.
    pub fn new(sources: Sources, knee: f32) -> Self {
        Decks::with(Output::Bus(sources), knee)
    }

    /// Decks with no device, which play only as [`Decks::process`] is called.
    pub fn manual() -> Self {
        Decks::with(Output::Manual, playr_dj::DEFAULT_KNEE)
    }

    fn with(output: Output, knee: f32) -> Self {
        Decks {
            knee,
            output,
            live: None,
            loaded: [None, None],
            loading: [None, None],
            arriving: [None, None],
            analysing: Vec::new(),
            taps: [Vec::new(), Vec::new()],
            loads: [0; 2],
            next: [None, None],
            sent: [None, None],
            crossfade: [false; 2],
            handover: [false; 2],
            volume: (f32::NAN, f32::NAN),
            state: DjState::default(),
            errors: channel(),
        }
    }

    /// The track on `side`.
    pub fn loaded(&self, side: Side) -> Option<&Loaded> {
        self.loaded[i(side)].as_ref()
    }

    pub fn loading(&self, side: Side) -> bool {
        self.loading[i(side)].is_some()
    }

    pub fn state(&self) -> &DjState {
        &self.state
    }

    /// The track waiting to load onto `side` once it stops.
    pub fn next(&self, side: Side) -> Option<&Track> {
        self.next[i(side)].as_ref()
    }

    /// What the engine publishes: each deck's transport, rate and phase.
    pub fn status(&self) -> Option<&playr_dj::Status> {
        self.live.as_ref().map(|l| &**l.handle.status())
    }

    /// The engine's rate, which every deck's frames count at.
    pub fn rate(&self) -> Option<u32> {
        self.live.as_ref().map(|l| l.rate)
    }

    /// Whether the crossfader is still moving to where it was last set.
    pub fn gliding(&self) -> bool {
        self.status()
            .is_some_and(|s| (s.xfade() - f64::from(self.state.xfade)).abs() > 1e-6)
    }

    pub fn playing(&self) -> bool {
        self.status()
            .is_some_and(|s| s.deck(Side::A).playing() || s.deck(Side::B).playing())
    }

    /// Runs manual decks' engine for `out`, interleaved stereo.
    pub fn process(&mut self, out: &mut [f32]) {
        if let Some(engine) = self.live.as_mut().and_then(|l| l.engine.as_mut()) {
            engine.process(out);
        }
    }

    /// The engine, opened at the first load: at `rate` where the device
    /// plays it, else at the device's.
    fn live(&mut self, rate: u32) -> Result<&mut Live, String> {
        if self.live.is_none() {
            let rate = match &self.output {
                Output::Bus(sources) => sources.rate_for(rate),
                Output::Manual => rate,
            };
            let (engine, mut handle) = playr_dj::new(rate);
            handle
                .set(Setting::Knee(self.knee))
                .map_err(|e| e.to_string())?;
            let (attached, engine) = match &self.output {
                Output::Bus(sources) => {
                    (Some(sources.attach(rate, Box::new(Played(engine)))), None)
                }
                Output::Manual => (None, Some(engine)),
            };
            self.live = Some(Live {
                handle,
                attached,
                engine,
                rate,
                interp: None,
            });
        }
        Ok(self.live.as_mut().expect("opened above"))
    }

    /// Starts reading `track` for `side`.
    fn load(&mut self, side: Side, track: &Track) -> Result<(), String> {
        let path = PathBuf::from(&track.path);
        let from = match track.sample_rate {
            Some(rate) => rate,
            None => native_rate(&path)?,
        };
        let to = self.live(from)?.rate;
        let (tx, rx) = channel();
        let read_path = path.clone();
        std::thread::spawn(move || _ = tx.send(read(&read_path, from, to)));
        self.loading[i(side)] = Some(Loading {
            path,
            title: track.display_title(),
            result: rx,
        });
        Ok(())
    }

    /// Sends the main mix's and the cue's volumes, when they changed. Once
    /// the engine is open; a new engine starts at NaN, so it gets them too.
    fn follow_volume(&mut self, main: f32, cue: f32) {
        let Some(live) = &mut self.live else { return };
        if main != self.volume.0 && live.handle.set(Setting::Volume(f64::from(main))).is_ok() {
            self.volume.0 = main;
        }
        if cue != self.volume.1 && live.handle.set(Setting::Headphones(f64::from(cue))).is_ok() {
            self.volume.1 = cue;
        }
    }

    /// Sends the heads' interpolation, when it changed. A new engine has
    /// none sent, so it gets it too.
    fn follow_interp(&mut self, interp: playr_dsp::Interp) {
        let Some(live) = &mut self.live else { return };
        if live.interp != Some(interp) && live.handle.set(Setting::Interp(interp)).is_ok() {
            live.interp = Some(interp);
        }
    }

    /// Where manual decks' device events are reported, by whatever drives
    /// them. Decks on the player's stream learn of a loss from the player.
    pub fn device_events(&self) -> Sender<DeviceEvent> {
        self.errors.0.clone()
    }

    /// Starts afresh after the device went: the next load opens a new
    /// engine. Analyses under way still store their grids.
    fn lose_device(&mut self) {
        let output = std::mem::replace(&mut self.output, Output::Manual);
        let analysing = std::mem::take(&mut self.analysing);
        *self = Decks::with(output, self.knee);
        self.analysing = analysing;
    }

    fn set(&mut self, s: Setting) -> Result<(), String> {
        let live = self.live.as_mut().ok_or("no deck is loaded")?;
        live.handle.set(s).map_err(|e| e.to_string())
    }

    /// The delay time, in ms, `division` of a bar of 4 beats makes at the
    /// tempo of the deck heard most: playing, with a grid, and the larger of
    /// its fader times its side of the crossfader. `None` while none plays.
    fn synced(&self, division: Division) -> Option<f32> {
        let status = self.status()?;
        let st = &self.state;
        let bpm = |side: Side| {
            let grid = self.loaded(side)?.grid?;
            let d = status.deck(side);
            let reach = match side {
                Side::A => 1.0 - st.xfade,
                Side::B => st.xfade,
            };
            let heard = st.level[i(side)] * reach * f32::from(u8::from(!st.mute[i(side)]));
            (d.playing() && heard > 0.0).then(|| (heard, grid.bpm * (1.0 + d.pct() / 100.0)))
        };
        let (_, bpm) = [bpm(Side::A), bpm(Side::B)]
            .into_iter()
            .flatten()
            .reduce(|a, b| if b.0 > a.0 { b } else { a })?;
        let ms = 4.0 * 60_000.0 / bpm * division.fraction();
        let ms_of = |s: f32| s * 1000.0;
        let (lo, hi) = (
            ms_of(playr_looper::DELAY_MIN),
            ms_of(playr_looper::DELAY_SECONDS),
        );
        Some((ms as f32).clamp(lo, hi))
    }

    /// Whether a deck heard in the main mix sends to bus `b`: 0 the delay,
    /// 1 the reverb.
    fn fed(&self, b: usize) -> bool {
        let st = &self.state;
        [Side::A, Side::B].into_iter().any(|side| {
            let k = i(side);
            let reach = match side {
                Side::A => st.xfade < 1.0,
                Side::B => st.xfade > 0.0,
            };
            self.loaded(side).is_some()
                && reach
                && !st.mute[k]
                && st.level[k] > 0.0
                && st.sends[k][b] > 0.0
        })
    }

    /// Why an effect's `field` does nothing as the decks are set.
    pub fn fx_idle(&self, field: crate::fx::FxField) -> Option<crate::tape::Idle> {
        crate::fx::idle(&self.state.fx, [self.fed(0), self.fed(1)], field)
    }

    /// Why `side`'s sends do nothing: they follow the deck as heard.
    pub fn send_idle(&self, side: Side) -> Option<crate::tape::Idle> {
        use crate::tape::Idle;
        let st = &self.state;
        let k = i(side);
        st.mute[k]
            .then_some(Idle::Muted)
            .or((st.level[k] == 0.0).then_some(Idle::Silent))
    }

    /// Sets a synced delay's time from the deck heard most, when its tempo
    /// moved it by more than 0.5 ms.
    fn resync(&mut self) {
        let fx = self.state.fx;
        let Some(ms) = fx.sync.and_then(|d| self.synced(d)) else {
            return;
        };
        let s = Setting::Fx(BusSetting::Delay(DelayParam::Time, ms / 1000.0));
        if (ms - fx.time).abs() > 0.5 && self.set(s).is_ok() {
            self.state.fx.time = ms;
        }
    }
}

/// The rate of the track at `path`, for one played from outside the
/// library, whose row does not record it. Decodes one chunk.
fn native_rate(path: &Path) -> Result<u32, String> {
    let fail = |e: playr_core::audio::decode::DecodeError| format!("{}: {e}", path.display());
    let mut stream = playr_core::audio::decode::AudioStream::open(path).map_err(fail)?;
    stream.next_chunk().map_err(fail)?;
    Ok(stream.spec().rate)
}

/// The whole track at `path`, at most 2 channels, resampled from `from` to
/// `to`, with its peaks.
fn read(path: &Path, from: u32, to: u32) -> Result<Read, String> {
    let (mut audio, channels) = samples::read_frames(path, from, 0, u64::MAX)?;
    if channels > 2 {
        audio = audio
            .chunks_exact(channels)
            .flat_map(|f| [f[0], f[1]])
            .collect();
    }
    let channels = channels.min(2) as u16;
    if to != from {
        let mut r = Resample::new(from, to, channels, 1.0)
            .ok_or_else(|| format!("cannot resample {from} Hz to {to} Hz"))?;
        let mut out = Vec::with_capacity(audio.len() * to as usize / from as usize + 64);
        r.push(&audio, &mut out);
        r.flush(&mut out);
        audio = out;
    }
    let peaks = Peaks::from_interleaved(&audio, channels.into(), to);
    Ok(Read {
        samples: audio,
        channels,
        peaks,
    })
}

fn dj_grid(g: tempo::Grid) -> Option<playr_dj::Grid> {
    playr_dj::Grid::new(g.bpm, g.t0).ok()
}

/// Takes in what finished since the last frame: reads, and the stream's
/// errors.
pub fn poll(f: &mut impl Frontend) {
    for side in [Side::A, Side::B] {
        let done = match f.dj().loading[i(side)]
            .as_ref()
            .map(|l| l.result.try_recv())
        {
            Some(Ok(result)) => Some(result),
            Some(Err(TryRecvError::Disconnected)) => Some(Err("the read stopped".into())),
            Some(Err(TryRecvError::Empty)) | None => None,
        };
        if let Some(result) = done {
            let loading = f.dj().loading[i(side)].take().expect("polled above");
            if let Err(e) = result.and_then(|r| start(f, side, loading, r)) {
                f.notify(DjMessage::Failed(e).into());
            }
        }
    }
    // Old tracks, and tracks a playing deck refused, are dropped here.
    while let Some(r) = f.dj().live.as_mut().and_then(|l| l.handle.poll()) {
        let message = match r {
            Returned::Replaced(side, _) | Returned::Fading(side) => taken(f, side),
            Returned::Faded(..) => None,
            Returned::Refused(side, _) => {
                let d = f.dj();
                d.arriving[i(side)] = None;
                match d.sent[i(side)].take() {
                    // Started again before the queued track arrived: it waits on.
                    Some(t) => {
                        d.next[i(side)] = Some(t);
                        None
                    }
                    None => Some(DjMessage::Playing(side)),
                }
            }
        };
        if let Some(m) = message {
            f.notify(m.into());
        }
    }
    // The player's stream lost its device, and the engine with it.
    if f.dj()
        .live
        .as_ref()
        .and_then(|l| l.attached.as_ref())
        .is_some_and(Attachment::lost)
    {
        f.dj().lose_device();
        let e = "the output device went away".to_string();
        f.notify(DjMessage::DeviceLost(e).into());
    }
    while let Ok(e) = f.dj().errors.1.try_recv() {
        match e {
            DeviceEvent::Rerouted => {}
            DeviceEvent::Error(e) => f.notify(DjMessage::Failed(e).into()),
            // The tracks played in the stream's callback, and went with it.
            DeviceEvent::Lost(e) => {
                f.dj().lose_device();
                f.notify(DjMessage::DeviceLost(e).into());
            }
        }
    }
    let mix = f.mix();
    let (main, cue) = (mix.gain(Strip::Decks), mix.gain(Strip::Headphones));
    f.dj().follow_volume(main, cue);
    let interp = f.mix().interp();
    f.dj().follow_interp(interp);
    for side in [Side::A, Side::B] {
        if let Err(e) = keep_hot_cues(f, side) {
            f.notify(DjMessage::Failed(e).into());
        }
        load_next(f, side);
    }
    // Rates move with sync and nudges, and a synced delay with them.
    f.dj().resync();
}

/// Loads the track queued for `side` once the deck has stopped and nothing
/// else is on its way to it.
fn load_next(f: &mut impl Frontend, side: Side) {
    let d = f.dj();
    let k = i(side);
    let stopped = d.status().is_some_and(|s| {
        let s = s.deck(side);
        !s.playing() && s.loads() == d.loads[k]
    });
    let busy = d.loading[k].is_some() || d.arriving[k].is_some() || d.sent[k].is_some();
    if !stopped || busy {
        return;
    }
    let Some(track) = d.next[k].take() else {
        return;
    };
    match d.load(side, &track) {
        Ok(()) => {
            d.sent[k] = Some(track);
            f.notify(DjMessage::Loading(side).into());
        }
        Err(e) => f.notify(DjMessage::Failed(e).into()),
    }
}

/// Stores the hot cues the engine has set or cleared on `side` since the
/// last call, once its status is of the track the deck holds.
fn keep_hot_cues(f: &mut impl Frontend, side: Side) -> Result<(), String> {
    let d = f.dj();
    let (Some(status), Some(loaded), Some(rate)) = (d.status(), d.loaded(side), d.rate()) else {
        return Ok(());
    };
    let s = status.deck(side);
    if s.loads() != d.loads[i(side)] || s.hot_cues() == loaded.hot {
        return Ok(());
    }
    let (now, was, path) = (s.hot_cues(), loaded.hot, loaded.path.clone());
    for (slot, n) in now.iter().enumerate().filter(|(k, n)| **n != was[*k]) {
        let at = n.map(|frames| frames / f64::from(rate));
        f.session_mut().set_hot_cue(&path, slot as u8 + 1, at)?;
    }
    if let Some(l) = f.dj().loaded[i(side)].as_mut() {
        l.hot = now;
    }
    Ok(())
}

/// Sends a read track to the engine with its grid. The deck holds it once
/// the engine takes it, in [`taken`].
fn start(f: &mut impl Frontend, side: Side, loading: Loading, read: Read) -> Result<(), String> {
    let grid = f.session().grid(&loading.path);
    let rate = f64::from(f.dj().rate().ok_or("no engine")?);
    let mut hot = [None; HOT_CUES];
    for (slot, at) in f.session().hot_cues(&loading.path) {
        if let Some(h) = hot.get_mut(usize::from(slot).wrapping_sub(1)) {
            *h = Some(at * rate);
        }
    }
    let frames = read.samples.len() / usize::from(read.channels);
    let track = playr_dj::Track::new(read.samples, read.channels, grid.and_then(dj_grid))
        .map_err(|e| e.to_string())?
        .with_hot_cues(hot);
    let crossfade = std::mem::take(&mut f.dj().crossfade[i(side)]);
    let live = f.dj().live.as_mut().ok_or("no engine")?;
    match crossfade {
        true => live.handle.replace(side, track),
        false => live.handle.load(side, track),
    }
    .map_err(|e| e.to_string())?;
    f.dj().arriving[i(side)] = Some(Loaded {
        path: loading.path,
        title: loading.title,
        frames,
        peaks: Arc::new(read.peaks),
        grid,
        hot,
        marks: Vec::new(),
    });
    Ok(())
}

/// The engine has taken the track sent to `side`: the deck holds it, and a
/// track never analysed is analysed for its grid.
fn taken(f: &mut impl Frontend, side: Side) -> Option<DjMessage> {
    f.dj().sent[i(side)] = None;
    let mut loaded = f.dj().arriving[i(side)].take()?;
    let rate = f64::from(f.dj().rate()?);
    loaded.marks = f
        .session()
        .marks_of(&loaded.path)
        .iter()
        .map(|m| m.time().as_secs_f64() * rate)
        .collect();
    let d = f.dj();
    d.taps[i(side)].clear();
    d.loads[i(side)] += 1;
    d.loaded[i(side)] = Some(loaded.clone());
    let took = match std::mem::take(&mut f.dj().handover[i(side)]) {
        true => hand_over(f, side, &loaded.path),
        false => Ok(false),
    };
    match took {
        Ok(true) => return Some(DjMessage::Took(side)),
        Ok(false) => {}
        Err(m) => return Some(m),
    }
    let analysed = f.session().analysis_of(&loaded.path).is_some();
    if loaded.grid.is_none() && !analysed {
        if let Ok(job) = f.session_mut().analyze(Some(loaded.path.clone())) {
            f.dj().analysing.push((job, side, loaded.path));
            return Some(DjMessage::FindingGrid(side));
        }
    }
    Some(DjMessage::Loaded {
        side,
        title: loaded.title,
        bpm: loaded.grid.map(|g| g.bpm),
    })
}

/// Takes in an analysis [`start`] began, once it lands: true if it was one.
/// The deck gets the grid if it still holds the track.
pub fn analysed(f: &mut impl Frontend, job: JobId) -> bool {
    let Some(at) = f.dj().analysing.iter().position(|(j, ..)| *j == job) else {
        return false;
    };
    let (_, side, path) = f.dj().analysing.remove(at);
    if f.dj().loaded(side).map(|l| &l.path) != Some(&path) {
        return true;
    }
    let grid = f.session().grid(&path);
    let message = match grid {
        Some(g) => match send_grid(f, side, Some(g)) {
            Ok(()) => DjMessage::Loaded {
                side,
                title: f
                    .dj()
                    .loaded(side)
                    .map(|l| l.title.clone())
                    .unwrap_or_default(),
                bpm: Some(g.bpm),
            },
            Err(e) => DjMessage::Failed(e),
        },
        None => DjMessage::NoGrid(side),
    };
    f.notify(message.into());
    true
}

/// Gives `side` the grid `grid`, in the engine and on the interface's side.
fn send_grid(f: &mut impl Frontend, side: Side, grid: Option<tempo::Grid>) -> Result<(), String> {
    f.dj().set(Setting::Grid(side, grid.and_then(dj_grid)))?;
    if let Some(l) = f.dj().loaded[i(side)].as_mut() {
        l.grid = grid;
    }
    Ok(())
}

/// Does `action`.
pub fn act(f: &mut impl Frontend, action: DjAction) {
    let result = match action {
        DjAction::Load(side) => return load(f, side),
        DjAction::Take(side) => return take(f, side),
        DjAction::Grid(side, edit) => return grid(f, side, edit),
        _ => send(f, action),
    };
    match result {
        Ok(()) => f.notify(DjMessage::Done(action).into()),
        Err(m) => f.notify(m.into()),
    }
}

fn load(f: &mut impl Frontend, side: Side) {
    let Some(track) = crate::dispatch::cursor_track(f) else {
        return f.notify(DjMessage::NoTrack.into());
    };
    let d = f.dj();
    if d.status().is_some_and(|s| s.deck(side).playing()) {
        if d.state.strict {
            let title = track.display_title();
            d.next[i(side)] = Some(track);
            return f.notify(DjMessage::Queued { side, title }.into());
        }
        // Not strict: read now, while the deck plays on, then crossfade.
        d.next[i(side)] = None;
        d.crossfade[i(side)] = true;
        d.handover[i(side)] = false;
        return match d.load(side, &track) {
            Ok(()) => {
                d.sent[i(side)] = Some(track);
                f.notify(DjMessage::Loading(side).into())
            }
            Err(e) => {
                d.crossfade[i(side)] = false;
                f.notify(DjMessage::Failed(e).into())
            }
        };
    }
    d.next[i(side)] = None;
    d.crossfade[i(side)] = false;
    d.handover[i(side)] = false;
    match f.dj().load(side, &track) {
        Ok(()) => f.notify(DjMessage::Loading(side).into()),
        Err(e) => f.notify(DjMessage::Failed(e).into()),
    }
}

/// The deck rate, in percent, that plays as the player's speed of `cents`,
/// and the narrowest range that holds it; `None` past every range.
fn rate_for(cents: i32) -> Option<(f64, Range)> {
    let pct = (playr_core::audio::speed_at(cents) - 1.0) * 100.0;
    [Range::Narrow, Range::Medium, Range::Wide]
        .into_iter()
        .find(|r| pct.abs() <= r.percent() + 1e-9)
        .map(|r| (pct, r))
}

/// Loads the player's track onto `side`, to take over once it is read. The
/// player plays on meanwhile.
fn take(f: &mut impl Frontend, side: Side) {
    if f.dj().status().is_some_and(|s| s.deck(side).playing()) {
        return f.notify(DjMessage::Playing(side).into());
    }
    let (path, rate) = match f.session().playing_track() {
        Ok(track) => track,
        Err(refusal) => return f.notify(refusal.into()),
    };
    let cents = f.session().player().status().cents;
    if rate_for(cents).is_none() {
        return f.notify(DjMessage::SpeedOutOfReach(cents).into());
    }
    // A track played from outside the library has no row.
    let track = (f.session().tracks_at(std::slice::from_ref(&path)).pop()).unwrap_or(Track {
        path: path.to_string_lossy().into(),
        sample_rate: Some(rate),
        ..Default::default()
    });
    let d = f.dj();
    d.next[i(side)] = None;
    d.crossfade[i(side)] = false;
    match d.load(side, &track) {
        Ok(()) => {
            d.handover[i(side)] = true;
            f.notify(DjMessage::Loading(side).into());
        }
        Err(e) => f.notify(DjMessage::Failed(e).into()),
    }
}

/// Moves the player's track, now loaded on `side`, from the player to the
/// deck: its rate as the player's speed, its trim as the ReplayGain the
/// player applies, at the player's position. With the other deck silent,
/// the crossfader moves to this one, which its centre would take 3 dB from.
/// A playing player pauses as the deck starts; a paused one leaves the deck
/// cued there. False when the player has moved on to another track.
fn hand_over(f: &mut impl Frontend, side: Side, path: &Path) -> Result<bool, DjMessage> {
    if f.session().playing_track().map(|(p, _)| p).as_deref() != Ok(path) {
        return Ok(false);
    }
    let status = f.session().player().status();
    let Some((pct, range)) = rate_for(status.cents) else {
        return Err(DjMessage::SpeedOutOfReach(status.cents));
    };
    let trim = status.gain_db.unwrap_or(0.0);
    let playing = status.state == State::Playing;
    let rate = f64::from(f.dj().rate().ok_or(DjMessage::Empty(side))?);
    let at = f.session().player().position().as_secs_f64() * rate;
    let start = match playing {
        true => Setting::PlayFrom(side, at),
        false => Setting::Seek(side, at),
    };
    let d = f.dj();
    let alone = !d.status().is_some_and(|s| s.deck(side.other()).playing());
    let x = if side == Side::A { 0.0 } else { 1.0 };
    let xfade = alone.then_some(Setting::Xfade(x));
    let settings = [
        Some(Setting::Range(side, range)),
        Some(Setting::Rate(side, pct)),
        Some(Setting::Gain(side, f64::from(trim))),
        xfade,
        Some(start),
    ];
    for s in settings.into_iter().flatten() {
        d.set(s).map_err(DjMessage::Failed)?;
    }
    d.state.gain[i(side)] = trim;
    if alone {
        d.state.xfade = x as f32;
    }
    if playing {
        f.session().send(playr_core::audio::Cmd::TogglePause);
    }
    Ok(true)
}

/// The deck an action acts on, if it acts on one.
fn deck_of(action: DjAction) -> Option<Side> {
    use DjAction as D;
    match action {
        D::Load(s)
        | D::Take(s)
        | D::Play(s)
        | D::Pause(s)
        | D::Cue(s)
        | D::CueHold(s, _)
        | D::Sync(s, _)
        | D::Rate(s, _)
        | D::Range(s, _)
        | D::Nudge(s, _)
        | D::Gain(s, _)
        | D::Level(s, _)
        | D::Grid(s, _)
        | D::Eq(s, ..)
        | D::Kill(s, ..)
        | D::Filter(s, _)
        | D::HotCue(s, _)
        | D::HotClear(s, _)
        | D::Jump(s, _)
        | D::Loop(s, _)
        | D::Seek(s, _)
        | D::Mark(s, _) => Some(s),
        D::Xfade(_)
        | D::XfadeTo(_)
        | D::Quantize(_)
        | D::CueBus(_)
        | D::CueOut(_)
        | D::Curve(_)
        | D::Mute(..)
        | D::Unqueue(_)
        | D::Strict(_)
        | D::DelaySend(..)
        | D::ReverbSend(..)
        | D::Fx(_) => None,
    }
}

/// Sends `action` to the engine, pausing the player when a deck starts.
fn send(f: &mut impl Frontend, action: DjAction) -> Result<(), DjMessage> {
    use DjAction as D;
    if let Some(side) = deck_of(action) {
        if f.dj().loaded(side).is_none() {
            return Err(DjMessage::Empty(side));
        }
    }
    match action {
        D::Sync(side, true) => sync_check(f, side)?,
        D::Jump(side, _) | D::Loop(side, Some(_))
            if f.dj().loaded(side).is_some_and(|l| l.grid.is_none()) =>
        {
            return Err(DjMessage::NoGrid(side));
        }
        D::CueOut(CueOut::Channels) => {
            let n = match &f.dj().output {
                Output::Bus(sources) => sources.widen(4),
                Output::Manual => 2,
            };
            if n < 4 {
                return Err(DjMessage::NoCueChannels(n));
            }
        }
        _ => {}
    }
    let slot = |n: u8| usize::from(n) - 1;
    if let D::Mark(side, next) = action {
        let d = f.dj();
        let (Some(l), Some(s), Some(rate)) = (d.loaded(side), d.status(), d.rate()) else {
            return Err(DjMessage::Empty(side));
        };
        let pos = s.deck(side).pos();
        // Back past a mark just left, as a CDJ's previous does.
        let back = pos - 0.5 * f64::from(rate);
        let to = match next {
            true => l.marks.iter().find(|&&m| m > pos + 1.0),
            false => l.marks.iter().rev().find(|&&m| m < back),
        };
        let Some(&to) = to else {
            return Err(DjMessage::NoMark(side));
        };
        return d.set(Setting::Seek(side, to)).map_err(DjMessage::Failed);
    }
    let seek;
    let fx;
    let seek_to = match action {
        D::Seek(s, pos) => {
            let d = f.dj();
            let frames = d.loaded(s).map_or(0, |l| l.frames) as f64;
            let rate = f64::from(d.rate().unwrap_or(1));
            match pos {
                crate::tape::Pos::Percent(p) => frames * f64::from(p) / 100.0,
                crate::tape::Pos::Time(t) => t.as_secs_f64() * rate,
            }
        }
        _ => 0.0,
    };
    let settings: &[Setting] = match action {
        D::Play(s) => &[Setting::Play(s)],
        D::Pause(s) => &[Setting::Pause(s)],
        D::Cue(s) => &[Setting::Cue(s, true), Setting::Cue(s, false)],
        D::CueHold(s, down) => &[Setting::Cue(s, down)],
        D::Sync(s, on) => &[Setting::Sync(s, on)],
        D::Rate(s, pct) => &[Setting::Rate(s, f64::from(pct))],
        D::Range(s, r) => &[Setting::Range(s, r)],
        D::Nudge(s, n) => &[Setting::Nudge(s, n)],
        D::Gain(s, db) => &[Setting::Gain(s, f64::from(db))],
        D::Level(s, l) => &[Setting::Level(s, f64::from(l))],
        D::Xfade(x) => &[Setting::Xfade(f64::from(x))],
        D::XfadeTo(None) => &[Setting::XfadeGlide(0.5)],
        D::XfadeTo(Some(Side::A)) => &[Setting::XfadeGlide(0.0)],
        D::XfadeTo(Some(Side::B)) => &[Setting::XfadeGlide(1.0)],
        D::Quantize(on) => &[Setting::Quantize(on)],
        D::CueBus(c) => &[Setting::CueBus(c)],
        D::Eq(s, b, db) => &[Setting::Eq(s, b, f64::from(db))],
        D::Kill(s, b, on) => &[Setting::Kill(s, b, on)],
        D::Filter(s, k) => &[Setting::Filter(s, f64::from(k))],
        D::HotCue(s, n) => &[Setting::HotCue(s, slot(n))],
        D::HotClear(s, n) => &[Setting::HotClear(s, slot(n))],
        D::Jump(s, beats) => &[Setting::BeatJump(s, f64::from(beats))],
        D::Loop(s, beats) => &[Setting::Loop(s, beats.map(f64::from))],
        D::CueOut(c) => &[Setting::CueOut(c)],
        D::Curve(c) => &[Setting::Curve(c)],
        D::Seek(s, _) => {
            seek = [Setting::Seek(s, seek_to)];
            &seek
        }
        D::Mute(s, on) => &[Setting::Mute(s, on)],
        D::Unqueue(s) => {
            let d = f.dj();
            d.next[i(s)] = None;
            // A replace still reading is dropped with its read.
            if std::mem::take(&mut d.crossfade[i(s)]) {
                d.loading[i(s)] = None;
                d.sent[i(s)] = None;
            }
            &[]
        }
        D::Strict(on) => {
            f.dj().state.strict = on;
            &[]
        }
        D::Mark(..) => &[],
        D::Load(_) | D::Take(_) | D::Grid(..) => &[],
        D::DelaySend(s, v) => {
            fx = [Setting::DelaySend(s, v)];
            &fx
        }
        D::ReverbSend(s, v) => {
            fx = [Setting::ReverbSend(s, v)];
            &fx
        }
        D::Fx(setting) => match setting.bus() {
            Some(b) => {
                fx = [Setting::Fx(b)];
                &fx
            }
            // Sync is set from the decks' tempo below; Print is the tape's.
            None => &[],
        },
    };
    let d = f.dj();
    for s in settings {
        d.set(*s).map_err(DjMessage::Failed)?;
    }
    let st = &mut d.state;
    match action {
        D::Gain(s, db) => st.gain[i(s)] = db,
        D::Level(s, l) => st.level[i(s)] = l,
        D::Xfade(x) => st.xfade = x,
        D::XfadeTo(to) => {
            st.xfade = match to {
                None => 0.5,
                Some(Side::A) => 0.0,
                Some(Side::B) => 1.0,
            }
        }
        D::Quantize(on) => st.quantize = on,
        D::CueBus(c) => st.cue_bus = c,
        D::Eq(s, b, db) => st.eq[i(s)][b as usize] = db,
        D::Kill(s, b, on) => st.kill[i(s)][b as usize] = on,
        D::Filter(s, k) => st.filter[i(s)] = k,
        D::CueOut(c) => st.cue_out = c,
        D::Curve(c) => st.curve = c,
        D::Mute(s, on) => st.mute[i(s)] = on,
        D::DelaySend(s, v) => st.sends[i(s)][0] = v,
        D::ReverbSend(s, v) => st.sends[i(s)][1] = v,
        D::Fx(FxSetting::Sync(division)) => st.fx.sync = division,
        D::Fx(setting) => {
            if let Some(b) = setting.bus() {
                st.fx.apply(b);
            }
            if matches!(setting, FxSetting::Time(_)) {
                st.fx.sync = None;
            }
        }
        _ => {}
    }
    d.resync();
    Ok(())
}

/// Refuses sync without both grids, or to a tempo no range reaches.
fn sync_check(f: &mut impl Frontend, side: Side) -> Result<(), DjMessage> {
    let d = f.dj();
    let grid = |s: Side| d.loaded(s).and_then(|l| l.grid);
    let Some(gf) = grid(side) else {
        return Err(DjMessage::NoGrid(side));
    };
    let Some(gl) = grid(side.other()) else {
        return Err(DjMessage::NoGrid(side.other()));
    };
    let pct = d.status().map_or(0.0, |s| s.deck(side.other()).pct());
    let lead = gl.bpm * (1.0 + pct / 100.0);
    match playr_dj::sync_pct(gf.bpm, lead).abs() <= Range::Wide.percent() {
        true => Ok(()),
        false => Err(DjMessage::OutOfReach(side)),
    }
}

/// Edits `side`'s grid and stores it with the track.
fn grid(f: &mut impl Frontend, side: Side, edit: GridEdit) {
    let Some(loaded) = f.dj().loaded(side).cloned() else {
        return f.notify(DjMessage::Empty(side).into());
    };
    let path = loaded.path;
    let stored = match edit {
        GridEdit::Double | GridEdit::Halve => {
            let fix = match edit {
                GridEdit::Double => TempoFix::Double,
                _ => TempoFix::Halve,
            };
            match f.session_mut().fix_tempo_of(&path, fix) {
                Notice::Done(_) => Ok(()),
                other => return f.notify(other.into()),
            }
        }
        GridEdit::Reset => f
            .session_mut()
            .set_grid(&path, None)
            .map(|()| _ = f.session_mut().fix_tempo_of(&path, TempoFix::Reset)),
        GridEdit::Tap => match tap(f, side, loaded.grid) {
            Some(g) => f.session_mut().set_grid(&path, Some(g)),
            None => return f.notify(DjMessage::Tapped(side).into()),
        },
        GridEdit::Earlier | GridEdit::Later | GridEdit::Offset(_) => {
            let Some(g) = loaded.grid else {
                return f.notify(DjMessage::NoGrid(side).into());
            };
            let by = match edit {
                GridEdit::Earlier => -g.bpm.recip() * 60.0,
                GridEdit::Later => g.bpm.recip() * 60.0,
                GridEdit::Offset(ms) => f64::from(ms) / 1000.0,
                _ => unreachable!("matched above"),
            };
            let moved = tempo::Grid { t0: g.t0 + by, ..g };
            f.session_mut().set_grid(&path, Some(moved))
        }
    };
    if let Err(e) = stored {
        return f.notify(DjMessage::Failed(e).into());
    }
    let grid = f.session().grid(&path);
    if let Err(e) = send_grid(f, side, grid) {
        return f.notify(DjMessage::Failed(e).into());
    }
    match grid {
        Some(g) => f.notify(
            DjMessage::Grid {
                side,
                bpm: g.bpm,
                t0: g.t0,
            }
            .into(),
        ),
        None => f.notify(DjMessage::NoGrid(side).into()),
    }
}

/// Counts a tap at `side`'s position. From the second tap of a count, the
/// grid: the mean interval's tempo, with a beat at the last tap. Taps on a
/// grid already set keep its tempo until the count has 4.
fn tap(f: &mut impl Frontend, side: Side, had: Option<tempo::Grid>) -> Option<tempo::Grid> {
    let d = f.dj();
    let rate = f64::from(d.rate()?);
    let at = d.status()?.deck(side).pos() / rate;
    let taps = &mut d.taps[i(side)];
    if taps.last().is_some_and(|&t| at <= t || at - t > TAP_GAP) {
        taps.clear();
    }
    taps.push(at);
    let n = taps.len();
    let bpm = match (n, had) {
        (1, _) => return None,
        (2..4, Some(g)) => g.bpm,
        _ => 60.0 * (n - 1) as f64 / (taps[n - 1] - taps[0]),
    };
    Some(tempo::Grid { bpm, t0: at })
}