deepmind-midi 26.5.2

Sans-IO protocol library for Behringer DeepMind synthesizers: SysEx, NRPN, programs and device state
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
//! The state machine a host drives: what the synthesizer holds, and what to send.
//!
//! This is where the layers below meet. Bytes off a port go in, a dump becomes a
//! confirmed [`Program`], an edit becomes the NRPN messages that carry it, a
//! request that goes unanswered becomes an [`Event::Timeout`], and bytes for the
//! port come out. It is also the first layer that needs a clock, which the host
//! supplies.
//!
//! ```
//! use deepmind_midi::device::{Device, Event};
//! use deepmind_midi::ids::{DeviceId, ProtocolVersion};
//! use deepmind_midi::program::{Program, ProgramName};
//! use deepmind_midi::sysex::{Frame, Message};
//!
//! let mut device: Device = Device::new(DeviceId::Unit(0));
//!
//! // Ask for the edit buffer. The bytes wait until the host takes them.
//! device.request_edit_buffer()?;
//! let mut asked = [0; 8];
//! device.drain_tx(|bytes| {
//!     asked.get_mut(..bytes.len()).map(|slot| slot.copy_from_slice(bytes));
//!     Ok::<(), core::convert::Infallible>(())
//! }).ok();
//! assert_eq!(asked, [0xF0, 0x00, 0x20, 0x32, 0x20, 0x00, 0x03, 0xF7]);
//!
//! // What comes back, in whatever chunks the port delivers it.
//! let mut program = Program::new(ProtocolVersion::V6);
//! program.set_name(ProgramName::new("Bass Sweep")?);
//! let mut packed = [0; Program::PACKED_MAX_LEN];
//! let packed_len = program.pack_into(&mut packed)?;
//! let mut reply = [0; 320];
//! let reply_len = Frame::new(
//!     DeviceId::Unit(0),
//!     Message::EditBufferDumpResponse {
//!         version: program.version(),
//!         packed: packed.get(..packed_len).unwrap_or_default(),
//!     },
//! )
//! .encode_into(&mut reply)?;
//! device.feed(reply.get(..reply_len).unwrap_or_default());
//!
//! assert!(matches!(device.poll_event(), Some(Event::EditBuffer(_))));
//! assert!(device.program().is_confirmed());
//!
//! // Change one thing. The library works out which message that implies.
//! assert_eq!(device.edit(|program| program.set_lfo1_rate(64))?, 1);
//! assert!(device.program().is_assumed());
//! # Ok::<(), deepmind_midi::Error>(())
//! ```
//!
//! # The loop a host writes
//!
//! Four calls, in whatever order suits the host:
//!
//! ```text
//! device.feed(&bytes_from_port);                 // inbound, any chunking
//! device.tick(now_ms);                           // the host owns the clock
//! device.drain_tx(|bytes| port.send(bytes))?;    // outbound
//! while let Some(event) = device.poll_event() {} // results
//! ```
//!
//! No IO, no threads, no blocking and no clock of its own, so a fake clock and a
//! byte vector reproduce any timing bug exactly.
//!
//! # Nothing is sent until it is drained
//!
//! [`request_edit_buffer`](Device::request_edit_buffer) and its neighbours put an
//! item in the outbound queue and return. The bytes exist once
//! [`drain_tx`](Device::drain_tx) hands them to the host, and a request's timeout
//! starts then rather than when it was queued, so a host that never drains never
//! times out.
//!
//! The queue holds items rather than bytes. A request is a few bytes and a
//! whole-program edit is 242, so its depth bounds what is waiting rather than the
//! worst case of what might be.
//!
//! # State is a set of claims
//!
//! [`Known`] is what the synthesizer is believed to hold and how that belief was
//! reached. The synthesizer answers no per-parameter reads, so there are two ways
//! to believe something about it: it said so, or the host told it so and nothing
//! has contradicted that. [`Device::program`] says which.
//!
//! An edit makes the tracked program [`Known::Assumed`]. Only an edit buffer dump
//! turns it back into [`Known::Confirmed`], and this layer never asks for one on
//! its own, since whether a resync is worth its latency is the host's call.
//!
//! Two answers are reported and deliberately not tracked. A stored program is not
//! the sound the synthesizer is making, and a [`ControlApp`] reply names the slot
//! the unit had selected at one moment. Both arrive as events for the host to
//! hold.
//!
//! # What arrives from the synthesizer
//!
//! Turning a knob on the front panel sends the parameter out, so inbound traffic
//! changes the tracked program too. An NRPN carries the parameter's whole value
//! and the tracked program stays confirmed; a control change carries seven bits
//! of it, less than most parameters have, so applying one leaves the program
//! assumed. Either way [`Event::Parameter`] reports it.
//!
//! Real-time bytes are dropped rather than queued. A running MIDI clock is
//! twenty-four messages a beat, none of which says anything about what the
//! synthesizer holds, and queuing them would crowd out the events that do. A host
//! that wants everything on the port drives [`Decoder`] itself.
//!
//! # Sizing
//!
//! Three capacities, all const parameters with defaults, because the right
//! numbers differ by two orders of magnitude between a desktop host and a
//! microcontroller:
//!
//! | Parameter | Default | What it bounds |
//! |---|---|---|
//! | `RX` | [`MAX_SYSEX_LEN`] | The longest `SysEx` frame that can be reassembled |
//! | `TX` | [`DEFAULT_TX_DEPTH`] | Items waiting to be sent; a whole-program edit is 242 |
//! | `EV` | [`DEFAULT_EVENT_DEPTH`] | Events waiting to be polled |
//!
//! ```
//! use deepmind_midi::device::Device;
//! use deepmind_midi::ids::DeviceId;
//!
//! // A host that sends single edits and reads the edit buffer needs none of the
//! // room a bank transfer wants.
//! let device: Device<300, 8, 2> = Device::new(DeviceId::Unit(0));
//! ```
//!
//! An event that does not fit is dropped and counted, and the count arrives as
//! [`Event::Lost`] once the queue has room again.

mod control_app;
mod event;
mod known;
mod request;

pub use control_app::ControlApp;
pub use event::Event;
pub use known::Known;
pub use request::{MAX_OUTBOUND_LEN, Request};

use request::Outbound;

use crate::error::{Error, Result};
use crate::ids::{Bank, DeviceId, ProgramNumber, Slot};
use crate::nrpn::{Change, Nrpn};
use crate::param::{DEFAULT_FIRMWARE, ParamId};
use crate::program::Program;
use crate::queue::Queue;
use crate::sysex::inquiry::{self, Version};
use crate::sysex::{Frame, Identity, Message};
use crate::wire::{Channel, ChannelMessage, Decoder, Event as WireEvent, MAX_SYSEX_LEN};

/// Outbound items a [`Device`] holds by default.
///
/// Enough for a whole-program edit, which is 242 of them, and a few requests
/// beside it.
pub const DEFAULT_TX_DEPTH: usize = 256;

/// Events a [`Device`] holds by default.
pub const DEFAULT_EVENT_DEPTH: usize = 8;

/// Milliseconds a request waits for its answer before timing out.
///
/// A dump crosses a MIDI port in a few tens of milliseconds. This is generous
/// rather than tight, so that a slow port does not time out.
/// [`Device::with_timeout`] sets another.
pub const DEFAULT_TIMEOUT_MS: u64 = 2_000;

/// Requests that can be outstanding at once and still be timed.
///
/// Beyond it, requests are still sent; they are simply not timed, and never
/// raise [`Event::Timeout`].
pub const MAX_PENDING: usize = 8;

/// A request that has gone out and is waiting for its answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Pending {
    request: Request,
    sent_at: u64,
}

/// One synthesizer, tracked.
///
/// See the [module documentation](self) for the loop a host writes around it and
/// for what the three capacities bound.
#[derive(Debug)]
pub struct Device<
    const RX: usize = MAX_SYSEX_LEN,
    const TX: usize = DEFAULT_TX_DEPTH,
    const EV: usize = DEFAULT_EVENT_DEPTH,
> {
    id: DeviceId,
    channel: Channel,
    now: u64,
    timeout: u64,
    decoder: Decoder<RX>,
    tx: Queue<Outbound, TX>,
    events: Queue<Event, EV>,
    lost: u16,
    pending: [Option<Pending>; MAX_PENDING],
    program: Known<Program>,
    identity: Known<Identity>,
    nrpn: Nrpn,
}

impl<const RX: usize, const TX: usize, const EV: usize> Device<RX, TX, EV> {
    /// Builds a device that talks to `id` on MIDI channel 1.
    ///
    /// [`DeviceId::Broadcast`] reaches every unit on the port and accepts what
    /// any of them answers, which is how a host finds a synthesizer whose device
    /// ID it does not know yet.
    #[must_use]
    pub const fn new(id: DeviceId) -> Self {
        Self {
            id,
            channel: Channel::ONE,
            now: 0,
            timeout: DEFAULT_TIMEOUT_MS,
            decoder: Decoder::new(),
            tx: Queue::new(),
            events: Queue::new(),
            lost: 0,
            pending: [const { None }; MAX_PENDING],
            program: Known::Unknown,
            identity: Known::Unknown,
            nrpn: Nrpn::new(),
        }
    }

    /// Sets the MIDI channel edits are sent on and parameter traffic is read on.
    #[must_use]
    pub const fn with_channel(mut self, channel: Channel) -> Self {
        self.channel = channel;
        self
    }

    /// Sets how long a request waits for its answer, in milliseconds.
    ///
    /// Zero times a request out at the first [`tick`](Device::tick) after it is
    /// sent, which is as strict as it gets. `u64::MAX` never times one out.
    #[must_use]
    pub const fn with_timeout(mut self, milliseconds: u64) -> Self {
        self.timeout = milliseconds;
        self
    }

    /// Returns the unit this device talks to.
    #[must_use]
    pub const fn id(&self) -> DeviceId {
        self.id
    }

    /// Returns the MIDI channel it talks on.
    #[must_use]
    pub const fn channel(&self) -> Channel {
        self.channel
    }

    /// Returns the host clock reading of the last [`tick`](Device::tick).
    #[must_use]
    pub const fn now(&self) -> u64 {
        self.now
    }

    /// Returns the edit buffer as the library believes it to be.
    ///
    /// [`Known::Confirmed`] means the synthesizer sent it and nothing lossy has
    /// been applied since. [`Known::Assumed`] means the host has edited it, or a
    /// control change has moved a parameter by seven bits of resolution.
    #[must_use]
    pub const fn program(&self) -> &Known<Program> {
        &self.program
    }

    /// Returns what a device inquiry answered, if one has.
    #[must_use]
    pub const fn identity(&self) -> &Known<Identity> {
        &self.identity
    }

    /// Returns the firmware version to read value tables against.
    ///
    /// What the synthesizer reported, or [`DEFAULT_FIRMWARE`] where it has not
    /// been asked. Firmware 1.1 renumbered three value tables, so reading them
    /// against the wrong version misnames a modulation source.
    #[must_use]
    pub fn firmware(&self) -> Version {
        self.identity
            .value()
            .map_or(DEFAULT_FIRMWARE, |identity| identity.firmware)
    }

    /// Returns how long a request waits for its answer.
    ///
    /// [`DEFAULT_TIMEOUT_MS`] unless [`with_timeout`](Device::with_timeout) said
    /// otherwise. A driver loop around this reads it to know how long waiting
    /// can reasonably last.
    #[must_use]
    pub const fn timeout(&self) -> u64 {
        self.timeout
    }

    /// Returns the requests that have been sent and not yet answered.
    pub fn outstanding(&self) -> impl Iterator<Item = Request> + '_ {
        self.pending
            .iter()
            .filter_map(|slot| slot.map(|pending| pending.request))
    }

    /// Returns how many items are waiting to be sent.
    #[must_use]
    pub const fn queued(&self) -> usize {
        self.tx.len()
    }

    /// Returns how many more items the outbound queue has room for.
    #[must_use]
    pub const fn room(&self) -> usize {
        self.tx.remaining()
    }

    /// Forgets everything: the part-decoded frame, both queues, what was asked
    /// for and what was believed.
    ///
    /// What a host does when it reopens the port, since none of the above
    /// survives that.
    pub fn reset(&mut self) {
        self.decoder.reset();
        self.tx.clear();
        self.events.clear();
        self.lost = 0;
        self.pending = [const { None }; MAX_PENDING];
        self.program = Known::Unknown;
        self.identity = Known::Unknown;
        self.nrpn = Nrpn::new();
    }

    /// Seeds the tracked program with one the host already has.
    ///
    /// Assumed, not confirmed: a program read from a file says what a host wants
    /// the synthesizer to hold, which is exactly the claim
    /// [`Known::Assumed`] makes. It sends nothing; a following
    /// [`edit`](Device::edit) diffs against it.
    pub fn assume_program(&mut self, program: Program) {
        self.program = Known::Assumed {
            value: program,
            at: self.now,
        };
    }

    /// Advances the clock and raises a timeout for anything now overdue.
    ///
    /// The host owns the clock. Milliseconds, monotonic; a reading behind the
    /// last one is ignored rather than treated as time passing backwards.
    pub fn tick(&mut self, now_ms: u64) {
        if now_ms < self.now {
            return;
        }
        self.now = now_ms;
        let Self {
            timeout,
            pending,
            events,
            lost,
            ..
        } = self;
        for slot in pending.iter_mut() {
            let overdue =
                slot.is_some_and(|entry| now_ms.saturating_sub(entry.sent_at) >= *timeout);
            if !overdue {
                continue;
            }
            if let Some(entry) = slot.take() {
                enqueue(events, lost, Event::Timeout(entry.request));
            }
        }
    }

    /// Takes the oldest event, if there is one.
    pub fn poll_event(&mut self) -> Option<Event> {
        if let Some(event) = self.events.pop() {
            return Some(event);
        }
        let lost = core::mem::take(&mut self.lost);
        (lost > 0).then_some(Event::Lost(lost))
    }

    /// Feeds inbound bytes, in whatever chunks they arrived in.
    ///
    /// Decodes them, updates what is known, and queues what happened.
    pub fn feed(&mut self, bytes: &[u8]) {
        let Self {
            id,
            channel,
            now,
            decoder,
            events,
            lost,
            pending,
            program,
            identity,
            nrpn,
            ..
        } = self;
        let mut inbound = Inbound {
            id: *id,
            channel: *channel,
            now: *now,
            events,
            lost,
            pending,
            program,
            identity,
            nrpn,
        };
        decoder.feed(bytes, |event| inbound.handle(event));
    }

    /// Hands every queued item to `send`, oldest first, and returns how many
    /// went.
    ///
    /// One call per message, which is the granularity a MIDI port wants. A host
    /// that would rather make fewer, larger writes buffers inside the closure.
    ///
    /// A request becomes outstanding as its bytes go out, which is when its
    /// timeout starts. An item `send` refuses stays queued, along with
    /// everything behind it, so a port that blocks costs nothing but latency.
    ///
    /// # Errors
    ///
    /// Returns whatever `send` returns, unchanged.
    pub fn drain_tx<E, F>(&mut self, mut send: F) -> core::result::Result<usize, E>
    where
        F: FnMut(&[u8]) -> core::result::Result<(), E>,
    {
        let mut count = 0;
        while let Some(item) = self.tx.peek() {
            let mut bytes = [0; MAX_OUTBOUND_LEN];
            let written = match item.encode_into(self.id, self.channel, &mut bytes) {
                Ok(written) => written,
                Err(error) => {
                    self.tx.pop();
                    enqueue(&mut self.events, &mut self.lost, Event::Failed(error));
                    continue;
                }
            };
            send(bytes.get(..written).unwrap_or_default())?;
            self.tx.pop();
            if let Some(request) = item.request() {
                self.start(request);
            }
            count += 1;
        }
        Ok(count)
    }

    /// Queues a device inquiry, which is the only thing that reports firmware.
    ///
    /// # Errors
    ///
    /// Returns [`Error::QueueFull`] when the outbound queue has no room.
    pub fn request_identity(&mut self) -> Result<()> {
        self.ask(Request::Identity)
    }

    /// Queues a control app notification, which is the only thing that reports
    /// which program the synthesizer has selected.
    ///
    /// The answer arrives as [`Event::ControlApp`] and is not tracked: see
    /// [`ControlApp`] for why. Announcing the host and reading the reply are one
    /// message because the protocol makes them one message.
    ///
    /// # Errors
    ///
    /// Returns [`Error::QueueFull`] when the outbound queue has no room.
    pub fn request_control_app(&mut self) -> Result<()> {
        self.ask(Request::ControlApp)
    }

    /// Queues a request for the edit buffer, the program as it currently sounds.
    ///
    /// # Errors
    ///
    /// Returns [`Error::QueueFull`] when the outbound queue has no room.
    pub fn request_edit_buffer(&mut self) -> Result<()> {
        self.ask(Request::EditBuffer)
    }

    /// Queues a request for one stored program.
    ///
    /// # Errors
    ///
    /// Returns [`Error::QueueFull`] when the outbound queue has no room.
    pub fn request_program(&mut self, slot: Slot) -> Result<()> {
        self.ask(Request::Program(slot))
    }

    /// Queues a request for a run of stored programs, answered one dump at a
    /// time.
    ///
    /// Every dump arrives as its own [`Event::Program`], so a host reading a
    /// whole bank drains events as they come rather than waiting for all 128.
    ///
    /// # Errors
    ///
    /// Returns [`Error::EmptyRun`] when `last` is before `first`, and
    /// [`Error::QueueFull`] when the outbound queue has no room.
    pub fn request_bank(
        &mut self,
        bank: Bank,
        first: ProgramNumber,
        last: ProgramNumber,
    ) -> Result<()> {
        if last.get() < first.get() {
            return Err(Error::EmptyRun {
                first: first.get(),
                last: last.get(),
            });
        }
        self.ask(Request::Bank { bank, first, last })
    }

    /// Edits the tracked program and queues the messages that carry the change.
    ///
    /// The closure is handed the program as the synthesizer is believed to hold
    /// it. What it changes is what gets sent: the diff is
    /// [`Program::changes`], so two writes to one parameter inside one closure
    /// are one message, and a write that puts a parameter back where it was is
    /// none. Returns how many parameters changed.
    ///
    /// Afterwards the tracked program is [`Known::Assumed`]. Nothing confirms it
    /// but a dump, and asking for one is the host's call.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ProgramNotKnown`] when no program is tracked yet, since
    /// there is then nothing to diff against. Ask for the edit buffer, or seed
    /// one with [`assume_program`](Device::assume_program).
    ///
    /// Returns [`Error::ValueOutOfRange`] when the closure left a parameter
    /// holding something it does not accept, and [`Error::QueueFull`] when the
    /// change needs more room than the outbound queue has. Either way nothing is
    /// queued and the tracked program is left as it was, so a failed edit never
    /// half-lands.
    pub fn edit<F>(&mut self, edit: F) -> Result<usize>
    where
        F: FnOnce(&mut Program),
    {
        let current = self.program.value().ok_or(Error::ProgramNotKnown)?;
        let mut target = current.clone();
        edit(&mut target);

        let mut needed = 0;
        for (parameter, value) in current.changes(&target) {
            parameter.edit(u16::from(value))?;
            needed += 1;
        }
        if needed == 0 {
            return Ok(0);
        }
        let available = self.tx.remaining();
        if needed > available {
            return Err(Error::QueueFull { needed, available });
        }

        for (parameter, value) in current.changes(&target) {
            if let Ok(message) = parameter.edit(u16::from(value)) {
                self.tx.push(Outbound::Edit(message));
            }
        }
        self.program = Known::Assumed {
            value: target,
            at: self.now,
        };
        Ok(needed)
    }

    /// Queues one request.
    fn ask(&mut self, request: Request) -> Result<()> {
        if self.tx.push(Outbound::Ask(request)) {
            Ok(())
        } else {
            Err(Error::QueueFull {
                needed: 1,
                available: 0,
            })
        }
    }

    /// Marks a request outstanding, as its bytes go out.
    fn start(&mut self, request: Request) {
        let now = self.now;
        let existing = self
            .pending
            .iter_mut()
            .find(|slot| slot.is_some_and(|entry| entry.request == request));
        if let Some(slot) = existing {
            *slot = Some(Pending {
                request,
                sent_at: now,
            });
            return;
        }
        if let Some(slot) = self.pending.iter_mut().find(|slot| slot.is_none()) {
            *slot = Some(Pending {
                request,
                sent_at: now,
            });
        }
    }
}

/// Queues an event, counting it as lost when there is no room.
fn enqueue<const EV: usize>(events: &mut Queue<Event, EV>, lost: &mut u16, event: Event) {
    if !events.push(event) {
        *lost = lost.saturating_add(1);
    }
}

/// The parts of a device that inbound bytes touch.
///
/// [`Device::feed`] borrows the decoder for the length of the call, so what the
/// decoder's closure needs has to be reachable without it. Naming those fields
/// here is what makes the two halves disjoint.
struct Inbound<'a, const EV: usize> {
    id: DeviceId,
    channel: Channel,
    now: u64,
    events: &'a mut Queue<Event, EV>,
    lost: &'a mut u16,
    pending: &'a mut [Option<Pending>; MAX_PENDING],
    program: &'a mut Known<Program>,
    identity: &'a mut Known<Identity>,
    nrpn: &'a mut Nrpn,
}

impl<const EV: usize> Inbound<'_, EV> {
    /// Queues an event.
    fn push(&mut self, event: Event) {
        enqueue(self.events, self.lost, event);
    }

    /// Takes one decoded MIDI message.
    fn handle(&mut self, event: core::result::Result<WireEvent<'_>, Error>) {
        match event {
            Ok(WireEvent::SysEx(bytes)) => self.sysex(bytes),
            Ok(WireEvent::Channel { channel, message }) => self.channel(channel, message),
            // Real-time and system common carry nothing about what the
            // synthesizer holds, and a running clock would drown the queue.
            Ok(WireEvent::Realtime(_) | WireEvent::Common(_)) => {}
            Err(error) => self.push(Event::Failed(error)),
        }
    }

    /// Takes one whole `SysEx` frame.
    fn sysex(&mut self, bytes: &[u8]) {
        match Frame::parse(bytes) {
            Ok(frame) => {
                // A frame addressed to another unit on the same port is not this
                // device's business.
                if self.id == DeviceId::Broadcast || frame.device.addresses(self.id) {
                    self.message(&frame.message);
                }
            }
            // A device inquiry reply is a universal frame, so it reaches here as
            // another manufacturer's: 0x7E is the universal non-real-time ID.
            Err(Error::Foreign {
                manufacturer,
                model,
            }) => match inquiry::parse_reply(bytes) {
                Ok(identity) => self.identity(identity),
                Err(_) => self.push(Event::Foreign {
                    manufacturer,
                    model,
                }),
            },
            Err(error) => self.push(Event::Failed(error)),
        }
    }

    /// Takes one `DeepMind` message addressed to this device.
    fn message(&mut self, message: &Message<'_>) {
        match *message {
            Message::EditBufferDumpResponse { version, packed } => {
                match Program::from_packed(version, packed) {
                    Ok(program) => {
                        *self.program = Known::Confirmed {
                            value: program.clone(),
                            at: self.now,
                        };
                        self.resolve(|request| request == Request::EditBuffer);
                        self.push(Event::EditBuffer(program));
                    }
                    Err(error) => self.push(Event::Failed(error)),
                }
            }
            Message::ProgramDumpResponse {
                version,
                bank,
                program,
                packed,
            } => {
                let slot = Slot::new(bank, program);
                match Program::from_packed(version, packed) {
                    Ok(program) => {
                        self.arrived(slot);
                        self.push(Event::Program { slot, program });
                    }
                    Err(error) => self.push(Event::Failed(error)),
                }
            }
            Message::ControlAppNotifyResponse {
                rx_channel,
                tx_channel,
                interface,
                bank,
                program,
            } => {
                self.resolve(|request| request == Request::ControlApp);
                self.push(Event::ControlApp(ControlApp {
                    rx_channel,
                    tx_channel,
                    interface,
                    bank,
                    program,
                }));
            }
            _ => self.push(Event::Unhandled(message.command())),
        }
    }

    /// Takes a device inquiry reply.
    ///
    /// A broadcast inquiry is answered by every unit on the port, so a reply
    /// from one this device does not talk to is another unit's answer.
    fn identity(&mut self, identity: Identity) {
        if self.id != DeviceId::Broadcast && !identity.device.addresses(self.id) {
            return;
        }
        *self.identity = Known::Confirmed {
            value: identity,
            at: self.now,
        };
        self.resolve(|request| request == Request::Identity);
        self.push(Event::Identity(identity));
    }

    /// Takes one channel message.
    fn channel(&mut self, channel: Channel, message: ChannelMessage) {
        if !self.consumed(channel, message) {
            self.push(Event::Channel { channel, message });
        }
    }

    /// Returns whether the message was a parameter edit on this device's channel.
    fn consumed(&mut self, channel: Channel, message: ChannelMessage) -> bool {
        if channel != self.channel {
            return false;
        }
        match message {
            ChannelMessage::ControlChange { controller, value } => {
                self.control_change(controller, value)
            }
            _ => false,
        }
    }

    /// Takes one control change, returning whether it was a parameter edit.
    fn control_change(&mut self, controller: u8, value: u8) -> bool {
        match self.nrpn.control_change(controller, value) {
            Change::Ignored => false,
            Change::Pending => true,
            Change::Parameter {
                parameter,
                value,
                exact,
            } => {
                self.parameter(parameter, value, exact);
                true
            }
        }
    }

    /// Records that a parameter now holds `value`.
    fn parameter(&mut self, parameter: ParamId, value: u16, exact: bool) {
        self.push(Event::Parameter { parameter, value });

        let Ok(byte) = u8::try_from(value) else {
            return;
        };
        let Some(current) = self.program.value_mut() else {
            return;
        };
        if current.set(parameter, byte).is_err() {
            return;
        }
        // The value changed in place; only the claim is rewritten, and the
        // program moves rather than copies.
        let now = self.now;
        *self.program = match core::mem::take(self.program) {
            Known::Confirmed { value, .. } if exact => Known::Confirmed { value, at: now },
            Known::Confirmed { value, .. } | Known::Assumed { value, .. } => {
                Known::Assumed { value, at: now }
            }
            Known::Unknown => Known::Unknown,
        };
    }

    /// Drops the first outstanding request `matches` accepts.
    fn resolve<F: Fn(Request) -> bool>(&mut self, matches: F) {
        if let Some(slot) = self
            .pending
            .iter_mut()
            .find(|slot| slot.is_some_and(|entry| matches(entry.request)))
        {
            *slot = None;
        }
    }

    /// Notes that the dump for `slot` arrived.
    ///
    /// A bank request is answered one dump at a time, so every dump inside its
    /// range is progress and only the last one ends it. One dump answers every
    /// outstanding request it fits, since a program asked for on its own and
    /// again as part of a run arrives once.
    fn arrived(&mut self, slot: Slot) {
        let now = self.now;
        for entry in self.pending.iter_mut() {
            match *entry {
                Some(Pending {
                    request: Request::Program(asked),
                    ..
                }) if asked == slot => {
                    *entry = None;
                }
                Some(Pending {
                    request: Request::Bank { bank, first, last },
                    ..
                }) if bank == slot.bank
                    && (first.get()..=last.get()).contains(&slot.number.get()) =>
                {
                    if slot.number.get() == last.get() {
                        *entry = None;
                    } else if let Some(pending) = entry.as_mut() {
                        pending.sent_at = now;
                    }
                }
                _ => {}
            }
        }
    }
}

#[cfg(test)]
#[expect(
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic,
    reason = "a failed expectation is the test failure"
)]
mod tests {
    use super::*;
    use crate::ids::ProtocolVersion;
    use crate::param::{DATA_ENTRY_LSB, DATA_ENTRY_MSB, NRPN_NUMBER_LSB, NRPN_NUMBER_MSB};
    use crate::program::ProgramName;
    use crate::sysex::{Command, Interface, inquiry};
    use crate::testing::assert_display;

    /// Room for the longest frame these tests build, which is a program dump.
    const FRAME: usize = 320;

    /// A port that remembers what it was handed.
    struct Port {
        bytes: [u8; 4096],
        len: usize,
        writes: usize,
    }

    impl Port {
        const fn new() -> Self {
            Self {
                bytes: [0; 4096],
                len: 0,
                writes: 0,
            }
        }

        fn send(&mut self, chunk: &[u8]) -> core::result::Result<(), ()> {
            let end = self.len + chunk.len();
            if end > self.bytes.len() {
                return Err(());
            }
            self.bytes[self.len..end].copy_from_slice(chunk);
            self.len = end;
            self.writes += 1;
            Ok(())
        }

        fn sent(&self) -> &[u8] {
            &self.bytes[..self.len]
        }
    }

    fn program(name: &str) -> Program {
        let mut program = Program::new(ProtocolVersion::V6);
        program.set_name(ProgramName::new(name).expect("a name the display can write"));
        program
    }

    fn slot(bank: Bank, number: u8) -> Slot {
        Slot::new(
            bank,
            ProgramNumber::new(number).expect("a program in range"),
        )
    }

    /// Encodes a frame from unit 0 into `out`.
    fn frame<'a>(out: &'a mut [u8; FRAME], message: Message<'_>) -> &'a [u8] {
        let len = Frame::new(DeviceId::Unit(0), message)
            .encode_into(out)
            .expect("the buffer fits");
        &out[..len]
    }

    /// Feeds the dump that answers an edit buffer request.
    fn feed_edit_buffer<const RX: usize, const TX: usize, const EV: usize>(
        device: &mut Device<RX, TX, EV>,
        program: &Program,
    ) {
        let mut packed = [0; Program::PACKED_MAX_LEN];
        let len = program.pack_into(&mut packed).expect("the buffer fits");
        let mut out = [0; FRAME];
        device.feed(frame(
            &mut out,
            Message::EditBufferDumpResponse {
                version: program.version(),
                packed: &packed[..len],
            },
        ));
    }

    /// Feeds the dump that answers a stored program request.
    fn feed_program<const RX: usize, const TX: usize, const EV: usize>(
        device: &mut Device<RX, TX, EV>,
        slot: Slot,
        program: &Program,
    ) {
        let mut packed = [0; Program::PACKED_MAX_LEN];
        let len = program.pack_into(&mut packed).expect("the buffer fits");
        let mut out = [0; FRAME];
        device.feed(frame(
            &mut out,
            Message::ProgramDumpResponse {
                version: program.version(),
                bank: slot.bank,
                program: slot.number,
                packed: &packed[..len],
            },
        ));
    }

    /// Feeds one control change on channel 1.
    fn feed_cc<const RX: usize, const TX: usize, const EV: usize>(
        device: &mut Device<RX, TX, EV>,
        controller: u8,
        value: u8,
    ) {
        device.feed(&[0xB0, controller, value]);
    }

    fn drain(device: &mut Device) -> Port {
        let mut port = Port::new();
        device.drain_tx(|bytes| port.send(bytes)).unwrap_or(0);
        port
    }

    fn events(device: &mut Device) -> impl Iterator<Item = Event> + '_ {
        core::iter::from_fn(move || device.poll_event())
    }

    #[test]
    fn a_request_is_bytes_only_once_it_is_drained() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.request_edit_buffer().expect("room in the queue");

        assert_eq!(device.queued(), 1);
        assert_eq!(device.outstanding().count(), 0, "queued is not sent");

        let port = drain(&mut device);
        assert_eq!(
            port.sent(),
            [0xF0, 0x00, 0x20, 0x32, 0x20, 0x00, 0x03, 0xF7]
        );
        assert_eq!(device.queued(), 0);
        assert_eq!(
            device.outstanding().next(),
            Some(Request::EditBuffer),
            "sent is outstanding"
        );
    }

    #[test]
    fn an_edit_buffer_dump_confirms_the_program_and_answers_the_request() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.request_edit_buffer().expect("room in the queue");
        drain(&mut device);
        assert_eq!(device.outstanding().count(), 1);

        let sound = program("Bass Sweep");
        feed_edit_buffer(&mut device, &sound);

        assert!(matches!(device.poll_event(), Some(Event::EditBuffer(_))));
        assert_eq!(device.poll_event(), None);
        assert!(device.program().is_confirmed());
        assert_eq!(
            device.program().value().map(Program::name),
            Some(sound.name())
        );
        assert_eq!(device.outstanding().count(), 0);
    }

    #[test]
    fn the_same_bytes_arrive_the_same_way_one_at_a_time() {
        let sound = program("Bass Sweep");
        let mut packed = [0; Program::PACKED_MAX_LEN];
        let len = sound.pack_into(&mut packed).expect("the buffer fits");
        let mut out = [0; FRAME];
        let bytes = frame(
            &mut out,
            Message::EditBufferDumpResponse {
                version: sound.version(),
                packed: &packed[..len],
            },
        );

        let mut whole: Device = Device::new(DeviceId::Unit(0));
        whole.feed(bytes);

        let mut piecemeal: Device = Device::new(DeviceId::Unit(0));
        for byte in bytes {
            piecemeal.feed(&[*byte]);
        }

        assert_eq!(whole.program(), piecemeal.program());
        assert!(whole.program().is_confirmed());
    }

    #[test]
    fn a_request_that_goes_unanswered_times_out_once() {
        let mut device: Device = Device::new(DeviceId::Unit(0)).with_timeout(100);
        device.request_edit_buffer().expect("room in the queue");
        drain(&mut device);

        device.tick(99);
        assert_eq!(device.poll_event(), None, "not overdue yet");

        device.tick(100);
        assert_eq!(
            device.poll_event(),
            Some(Event::Timeout(Request::EditBuffer))
        );
        device.tick(10_000);
        assert_eq!(device.poll_event(), None, "raised once, then forgotten");
    }

    #[test]
    fn a_request_never_drained_never_times_out() {
        let mut device: Device = Device::new(DeviceId::Unit(0)).with_timeout(100);
        device.request_edit_buffer().expect("room in the queue");

        device.tick(10_000);
        assert_eq!(device.poll_event(), None);
        assert_eq!(device.queued(), 1, "still waiting to be sent");
    }

    #[test]
    fn a_clock_that_goes_backwards_is_ignored() {
        let mut device: Device = Device::new(DeviceId::Unit(0)).with_timeout(100);
        device.tick(1_000);
        device.tick(10);
        assert_eq!(device.now(), 1_000);
    }

    #[test]
    fn editing_before_anything_is_known_says_so() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        assert_eq!(
            device.edit(|program| program.set_lfo1_rate(64)),
            Err(Error::ProgramNotKnown)
        );
    }

    #[test]
    fn an_edit_sends_one_message_for_each_parameter_that_changed() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}

        let changed = device
            .edit(|program| {
                program.set_lfo1_rate(64);
                program.set_lfo1_rate(65);
                let was = program.vcf_frequency();
                program.set_vcf_frequency(was);
            })
            .expect("a program to diff against");

        assert_eq!(changed, 1, "two writes to one parameter, one message");
        let port = drain(&mut device);
        assert_eq!(
            port.sent(),
            [0xB0, 99, 0, 0xB0, 98, 0, 0xB0, 6, 0, 0xB0, 38, 65]
        );
        assert_eq!(port.writes, 1, "one call per message");
        assert!(device.program().is_assumed(), "sent, not confirmed");
    }

    #[test]
    fn an_edit_that_changes_nothing_sends_nothing() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}

        assert_eq!(device.edit(|_| {}), Ok(0));
        assert_eq!(device.queued(), 0);
        assert!(device.program().is_confirmed(), "still nothing sent");
    }

    #[test]
    fn an_edit_too_big_for_the_queue_queues_none_of_it() {
        let mut device: Device<MAX_SYSEX_LEN, 1, 4> = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}

        let outcome = device.edit(|program| {
            program.set_lfo1_rate(64);
            program.set_lfo2_rate(64);
        });

        assert_eq!(
            outcome,
            Err(Error::QueueFull {
                needed: 2,
                available: 1
            })
        );
        assert_eq!(device.queued(), 0, "nothing half-sent");
        assert!(device.program().is_confirmed(), "and nothing assumed");
    }

    #[test]
    fn an_nrpn_from_the_synthesizer_keeps_the_program_confirmed() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}

        feed_cc(&mut device, NRPN_NUMBER_MSB, 0);
        feed_cc(&mut device, NRPN_NUMBER_LSB, ParamId::Lfo1Rate.offset());
        feed_cc(&mut device, DATA_ENTRY_MSB, 0);
        feed_cc(&mut device, DATA_ENTRY_LSB, 99);

        assert_eq!(
            device.poll_event(),
            Some(Event::Parameter {
                parameter: ParamId::Lfo1Rate,
                value: 99
            })
        );
        assert_eq!(device.poll_event(), None, "the selection is not an event");
        assert!(device.program().is_confirmed(), "the whole value arrived");
        assert_eq!(device.program().value().map(Program::lfo1_rate), Some(99),);
    }

    #[test]
    fn a_selected_parameter_stays_selected_across_a_sweep() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}

        feed_cc(&mut device, NRPN_NUMBER_MSB, 0);
        feed_cc(&mut device, NRPN_NUMBER_LSB, ParamId::Lfo1Rate.offset());
        for value in [10, 11, 12] {
            feed_cc(&mut device, DATA_ENTRY_MSB, 0);
            feed_cc(&mut device, DATA_ENTRY_LSB, value);
        }

        let seen: usize = events(&mut device)
            .filter(|event| matches!(event, Event::Parameter { .. }))
            .count();
        assert_eq!(seen, 3);
        assert_eq!(device.program().value().map(Program::lfo1_rate), Some(12));
    }

    #[test]
    fn a_controller_carries_seven_bits_so_the_program_becomes_assumed() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}

        feed_cc(&mut device, 16, 64);

        let expected = ParamId::Lfo1Rate.from_cc_value(64);
        assert_eq!(
            device.poll_event(),
            Some(Event::Parameter {
                parameter: ParamId::Lfo1Rate,
                value: expected
            })
        );
        assert!(
            device.program().is_assumed(),
            "a controller does not confirm a value it cannot carry"
        );
    }

    #[test]
    fn a_message_on_another_channel_is_reported_and_not_applied() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}
        let before = device.program().clone();

        device.feed(&[0xB1, 16, 64]);

        assert!(matches!(device.poll_event(), Some(Event::Channel { .. })));
        assert_eq!(device.program(), &before);
    }

    #[test]
    fn a_note_is_reported_rather_than_swallowed() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.feed(&[0x90, 60, 100]);
        assert!(matches!(device.poll_event(), Some(Event::Channel { .. })));
    }

    #[test]
    fn a_running_clock_is_not_an_event() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.feed(&[0xF8; 64]);
        assert_eq!(device.poll_event(), None);
    }

    #[test]
    fn a_stored_program_is_reported_and_not_tracked() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        let target = slot(Bank::from_letter('B').expect("a bank letter"), 4);
        device.request_program(target).expect("room in the queue");
        drain(&mut device);

        feed_program(&mut device, target, &program("Lead"));

        match device.poll_event() {
            Some(Event::Program { slot, program }) => {
                assert_eq!(slot, target);
                assert_eq!(program.name().as_str(), "Lead");
            }
            other => panic!("expected a program dump, got {other:?}"),
        }
        assert!(
            device.program().is_unknown(),
            "a stored program is not the sound it is making"
        );
        assert_eq!(device.outstanding().count(), 0);
    }

    #[test]
    fn a_bank_request_ends_on_its_last_program() {
        let mut device: Device = Device::new(DeviceId::Unit(0)).with_timeout(100);
        let first = ProgramNumber::new(0).expect("a program in range");
        let last = ProgramNumber::new(2).expect("a program in range");
        device
            .request_bank(Bank::A, first, last)
            .expect("room in the queue");
        drain(&mut device);

        let sound = program("Lead");
        for number in 0..=1 {
            device.tick(u64::from(number) * 90);
            feed_program(&mut device, slot(Bank::A, number), &sound);
            assert_eq!(
                device.outstanding().count(),
                1,
                "a dump inside the run is progress, not an answer"
            );
        }
        device.tick(180);
        assert_eq!(device.outstanding().count(), 1, "and it stays progress");

        feed_program(&mut device, slot(Bank::A, 2), &sound);
        assert_eq!(device.outstanding().count(), 0);
    }

    /// A program asked for on its own and again inside a run arrives once, and
    /// that one dump answers both.
    #[test]
    fn one_dump_answers_every_request_it_fits() {
        let mut device: Device = Device::new(DeviceId::Unit(0)).with_timeout(100);
        let first = ProgramNumber::new(0).expect("a program in range");
        let last = ProgramNumber::new(1).expect("a program in range");
        device.request_program(slot(Bank::A, 1)).expect("room");
        device.request_bank(Bank::A, first, last).expect("room");
        drain(&mut device);
        assert_eq!(device.outstanding().count(), 2);

        let sound = program("Lead");
        feed_program(&mut device, slot(Bank::A, 0), &sound);
        assert_eq!(device.outstanding().count(), 2, "progress on the run");
        feed_program(&mut device, slot(Bank::A, 1), &sound);
        assert_eq!(device.outstanding().count(), 0, "both were answered");
    }

    #[test]
    fn a_bank_request_before_a_late_program_is_rejected() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        let first = ProgramNumber::new(4).expect("a program in range");
        let last = ProgramNumber::new(2).expect("a program in range");
        assert_eq!(
            device.request_bank(Bank::A, first, last),
            Err(Error::EmptyRun { first: 4, last: 2 })
        );
    }

    #[test]
    fn a_device_inquiry_reply_reports_firmware() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.request_identity().expect("room in the queue");
        drain(&mut device);

        let identity = Identity {
            device: DeviceId::Unit(0),
            firmware: inquiry::Version { major: 1, minor: 1 },
            voice: inquiry::Version { major: 1, minor: 0 },
        };
        let mut reply = [0; inquiry::REPLY_LEN];
        inquiry::reply_into(&identity, &mut reply).expect("the buffer fits");
        device.feed(&reply);

        assert_eq!(device.poll_event(), Some(Event::Identity(identity)));
        assert!(device.identity().is_confirmed());
        assert_eq!(device.firmware(), identity.firmware);
        assert_eq!(device.outstanding().count(), 0);
    }

    #[test]
    fn another_units_inquiry_reply_is_that_units_answer() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        let identity = Identity {
            device: DeviceId::Unit(1),
            firmware: inquiry::Version { major: 1, minor: 1 },
            voice: inquiry::Version { major: 1, minor: 0 },
        };
        let mut reply = [0; inquiry::REPLY_LEN];
        inquiry::reply_into(&identity, &mut reply).expect("the buffer fits");
        device.feed(&reply);

        assert_eq!(device.poll_event(), None);
        assert!(device.identity().is_unknown());
    }

    #[test]
    fn a_control_app_reply_reports_what_the_interface_holds() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.request_control_app().expect("room in the queue");
        drain(&mut device);
        assert_eq!(
            device.outstanding().next(),
            Some(Request::ControlApp),
            "announcing the host is a request like any other"
        );

        let mut out = [0; FRAME];
        device.feed(frame(
            &mut out,
            Message::ControlAppNotifyResponse {
                rx_channel: 1,
                tx_channel: 0,
                interface: Interface::Usb,
                bank: Bank::from_letter('C').expect("C is a bank"),
                program: ProgramNumber::new(40).expect("a program in a bank"),
            },
        ));

        let Some(Event::ControlApp(answer)) = device.poll_event() else {
            panic!("the only message that names the selected program was dropped");
        };
        assert_display(answer.slot(), "C41");
        assert_eq!(answer.interface, Interface::Usb);
        assert_eq!(answer.receive_channel(), Some(Channel::ONE));
        assert_eq!(answer.transmit_channel(), Some(Channel::ONE));
        assert_eq!(device.outstanding().count(), 0, "the request was answered");
    }

    /// Reported and not tracked: the selected program is the synthesizer's to
    /// change at its own panel, and nothing here would hear it.
    #[test]
    fn a_control_app_reply_leaves_the_tracked_program_alone() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        while device.poll_event().is_some() {}

        let mut out = [0; FRAME];
        device.feed(frame(
            &mut out,
            Message::ControlAppNotifyResponse {
                rx_channel: 0,
                tx_channel: 0,
                interface: Interface::Midi,
                bank: Bank::A,
                program: ProgramNumber::FIRST,
            },
        ));

        assert!(matches!(device.poll_event(), Some(Event::ControlApp(_))));
        assert!(device.program().is_confirmed());
        assert_eq!(
            device.program().value().map(Program::name),
            Some(ProgramName::new("Bass Sweep").expect("a name the display can write"))
        );
    }

    #[test]
    fn an_unanswered_control_app_notification_times_out_like_the_rest() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.request_control_app().expect("room in the queue");
        drain(&mut device);

        device.tick(DEFAULT_TIMEOUT_MS);

        assert_eq!(
            device.poll_event(),
            Some(Event::Timeout(Request::ControlApp))
        );
        assert_eq!(device.outstanding().count(), 0);
    }

    /// The manual prints one reserved byte and does not say what it is for, so
    /// the request this layer sends is the frame the manual prints with a zero
    /// in it.
    #[test]
    fn a_control_app_notification_is_the_frame_the_manual_prints() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.request_control_app().expect("room in the queue");
        let mut port = Port::new();
        device
            .drain_tx(|bytes| port.send(bytes))
            .expect("the port took it");
        assert_eq!(
            port.sent(),
            &[0xF0, 0x00, 0x20, 0x32, 0x20, 0x00, 0x00, 0x00, 0xF7]
        );
    }

    #[test]
    fn the_firmware_is_the_current_one_until_the_synthesizer_says_otherwise() {
        let device: Device = Device::new(DeviceId::Unit(0));
        assert_eq!(device.firmware(), DEFAULT_FIRMWARE);
    }

    #[test]
    fn another_manufacturers_frame_is_reported_as_theirs() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.feed(&[0xF0, 0x43, 0x00, 0x00, 0x01, 0x00, 0x00, 0xF7]);
        assert_eq!(
            device.poll_event(),
            Some(Event::Foreign {
                manufacturer: [0x43, 0x00, 0x00],
                model: 0x01
            })
        );
    }

    #[test]
    fn a_frame_for_another_unit_is_not_this_devices_business() {
        let mut device: Device = Device::new(DeviceId::Unit(1));
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        assert_eq!(device.poll_event(), None);
        assert!(device.program().is_unknown());
    }

    #[test]
    fn a_broadcast_host_listens_to_every_unit() {
        let mut device: Device = Device::new(DeviceId::Broadcast);
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        assert!(matches!(device.poll_event(), Some(Event::EditBuffer(_))));
    }

    #[test]
    fn a_message_this_layer_does_not_track_is_still_reported() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        let mut out = [0; FRAME];
        device.feed(frame(&mut out, Message::ChordMemoryDumpRequest));
        assert_eq!(
            device.poll_event(),
            Some(Event::Unhandled(Command::ChordMemoryDumpRequest))
        );
    }

    #[test]
    fn an_unreadable_frame_is_reported_with_its_reason() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        // A DeepMind header with a command byte no message uses.
        device.feed(&[0xF0, 0x00, 0x20, 0x32, 0x20, 0x00, 0x7E, 0xF7]);
        assert_eq!(
            device.poll_event(),
            Some(Event::Failed(Error::UnknownCommand(0x7E)))
        );
    }

    #[test]
    fn events_that_do_not_fit_are_counted_and_reported() {
        let mut device: Device<MAX_SYSEX_LEN, 8, 2> = Device::new(DeviceId::Unit(0));
        for _ in 0..5 {
            device.feed(&[0x90, 60, 100]);
        }

        assert!(matches!(device.poll_event(), Some(Event::Channel { .. })));
        assert!(matches!(device.poll_event(), Some(Event::Channel { .. })));
        assert_eq!(device.poll_event(), Some(Event::Lost(3)));
        assert_eq!(device.poll_event(), None);
    }

    #[test]
    fn a_port_that_refuses_keeps_everything_queued() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.request_identity().expect("room in the queue");
        device.request_edit_buffer().expect("room in the queue");

        let outcome: core::result::Result<usize, ()> = device.drain_tx(|_| Err(()));

        assert_eq!(outcome, Err(()));
        assert_eq!(device.queued(), 2, "the refused item stays first");
        assert_eq!(device.outstanding().count(), 0, "nothing went out");
    }

    #[test]
    fn a_full_outbound_queue_says_so() {
        let mut device: Device<MAX_SYSEX_LEN, 1, 2> = Device::new(DeviceId::Unit(0));
        device.request_identity().expect("room in the queue");
        assert_eq!(
            device.request_edit_buffer(),
            Err(Error::QueueFull {
                needed: 1,
                available: 0
            })
        );
    }

    #[test]
    fn a_seeded_program_is_assumed_and_sends_nothing() {
        let mut device: Device = Device::new(DeviceId::Unit(0));
        device.assume_program(program("From A File"));

        assert!(device.program().is_assumed());
        assert_eq!(device.queued(), 0);
        assert_eq!(device.edit(|program| program.set_lfo1_rate(64)), Ok(1));
    }

    #[test]
    fn a_reset_forgets_everything() {
        let mut device: Device = Device::new(DeviceId::Unit(0)).with_timeout(100);
        device.request_edit_buffer().expect("room in the queue");
        drain(&mut device);
        feed_edit_buffer(&mut device, &program("Bass Sweep"));
        device.feed(&[0x90, 60]);

        device.reset();

        assert!(device.program().is_unknown());
        assert!(device.identity().is_unknown());
        assert_eq!(device.queued(), 0);
        assert_eq!(device.poll_event(), None);
        assert_eq!(device.outstanding().count(), 0);
        device.tick(10_000);
        assert_eq!(device.poll_event(), None);
    }

    #[test]
    fn the_channel_an_edit_goes_out_on_is_the_one_it_was_given() {
        let channel = Channel::new(3).expect("a channel in range");
        let mut device: Device = Device::new(DeviceId::Unit(0)).with_channel(channel);
        device.assume_program(program("Bass Sweep"));
        device
            .edit(|program| program.set_lfo1_rate(1))
            .expect("a program to diff against");

        let port = drain(&mut device);
        assert_eq!(port.sent().first(), Some(&0xB3));
        assert_eq!(device.channel(), channel);
    }
}