autd3-rs 0.3.0

Core async client library for the AUTD3 phased-array kit.
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
use std::sync::{Arc, Mutex, PoisonError};

use crate::command::Command;
use crate::error::Error;
use crate::mirror::FirmwareState;
use crate::operation::{Distribution, Nop, Operation};
use crate::protocol::{Cmd, PAYLOAD_BYTES};

#[derive(Clone, Debug)]
pub(crate) enum Mirror {
    Synced(Vec<FirmwareState>),
    Desynced,
}

#[derive(Clone)]
pub(crate) struct MirrorHandle {
    pub(crate) state: Arc<Mutex<Mirror>>,
    pub(crate) enabled: bool,
}

#[derive(Clone, Debug)]
pub struct Datagram {
    pub cmd: Cmd,
    pub payload: [u8; PAYLOAD_BYTES],
}

impl Datagram {
    #[must_use]
    pub const fn no_payload(cmd: Cmd) -> Self {
        Self {
            cmd,
            payload: [0u8; PAYLOAD_BYTES],
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct Frame<'a> {
    dist: Distribution,
    datagrams: &'a [Datagram],
}

impl<'a> Frame<'a> {
    #[must_use]
    pub fn distribution(&self) -> Distribution {
        self.dist
    }

    #[must_use]
    pub fn datagrams(&self) -> &'a [Datagram] {
        self.datagrams
    }
}

#[derive(Debug)]
struct FrameDesc {
    dist: Distribution,
    start: usize,
    len: usize,
}

#[derive(Debug, Default)]
pub struct Frames {
    payloads: Vec<Datagram>,
    frames: Vec<FrameDesc>,
}

impl Frames {
    #[must_use]
    pub fn len(&self) -> usize {
        self.frames.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.frames.is_empty()
    }

    #[must_use]
    pub fn frame(&self, index: usize) -> Option<Frame<'_>> {
        self.frames.get(index).map(|desc| Frame {
            dist: desc.dist,
            datagrams: &self.payloads[desc.start..desc.start + desc.len],
        })
    }

    #[must_use]
    pub fn iter(&self) -> FrameIter<'_> {
        FrameIter {
            frames: self,
            index: 0,
        }
    }

    fn clear(&mut self) {
        self.payloads.clear();
        self.frames.clear();
    }

    pub(crate) fn push_op<O: Operation + ?Sized>(
        &mut self,
        op: &O,
        num_devices: usize,
    ) -> Result<(), Error> {
        let dist = op.distribution();
        let encode_devices = match dist {
            Distribution::Broadcast => 1,
            Distribution::PerDevice => num_devices,
        };
        for frame in 0..op.frames() {
            let start = self.payloads.len();
            for device in 0..encode_devices {
                let mut payload = [0u8; PAYLOAD_BYTES];
                let cmd = op.encode(device, frame, &mut payload)?;
                self.payloads.push(Datagram { cmd, payload });
            }
            self.frames.push(FrameDesc {
                dist,
                start,
                len: encode_devices,
            });
        }
        Ok(())
    }

    fn push_each_step(
        &mut self,
        devices: &[Vec<Box<dyn Operation + '_>>],
        num_devices: usize,
    ) -> Result<(), Error> {
        let slot_frames = each_slot_frames(devices);
        let total: usize = slot_frames.iter().sum();
        for frame in 0..total {
            let start = self.payloads.len();
            for device in 0..num_devices {
                let mut payload = [0u8; PAYLOAD_BYTES];
                let cmd = each_encode(devices, &slot_frames, device, frame, &mut payload)?;
                self.payloads.push(Datagram { cmd, payload });
            }
            self.frames.push(FrameDesc {
                dist: Distribution::PerDevice,
                start,
                len: num_devices,
            });
        }
        Ok(())
    }
}

pub struct FrameIter<'a> {
    frames: &'a Frames,
    index: usize,
}

impl<'a> Iterator for FrameIter<'a> {
    type Item = Frame<'a>;

    fn next(&mut self) -> Option<Frame<'a>> {
        let frame = self.frames.frame(self.index)?;
        self.index += 1;
        Some(frame)
    }
}

impl<'a> IntoIterator for &'a Frames {
    type Item = Frame<'a>;
    type IntoIter = FrameIter<'a>;

    fn into_iter(self) -> FrameIter<'a> {
        self.iter()
    }
}

enum Step<'a> {
    Op(Box<dyn Operation + 'a>),
    Each {
        devices: Vec<Vec<Box<dyn Operation + 'a>>>,
    },
}

pub struct DatagramBuilder<'a> {
    num_devices: usize,
    ops: Vec<Step<'a>>,
    mirror: Option<MirrorHandle>,
}

impl<'a> DatagramBuilder<'a> {
    #[must_use]
    pub fn new(num_devices: usize) -> Self {
        Self {
            num_devices,
            ops: Vec::new(),
            mirror: None,
        }
    }

    #[must_use]
    pub(crate) fn with_mirror(num_devices: usize, mirror: MirrorHandle) -> Self {
        Self {
            num_devices,
            ops: Vec::new(),
            mirror: Some(mirror),
        }
    }

    pub fn push<C: Command<'a>>(&mut self, cmd: C) -> &mut Self {
        cmd.expand(self);
        self
    }

    pub fn push_each<C, F>(&mut self, mut assign: F) -> &mut Self
    where
        C: Command<'a>,
        F: FnMut(usize) -> Option<C>,
    {
        let num_devices = self.num_devices;
        let mut new_devices: Vec<Vec<Box<dyn Operation + 'a>>> = Vec::with_capacity(num_devices);
        for device in 0..num_devices {
            match assign(device) {
                Some(cmd) => {
                    let mut sub = DatagramBuilder::new(num_devices);
                    cmd.expand(&mut sub);
                    new_devices.push(sub.take_ops());
                }
                None => new_devices.push(Vec::new()),
            }
        }

        let fuse = matches!(
            self.ops.last(),
            Some(Step::Each { devices }) if (0..num_devices)
                .all(|d| devices[d].is_empty() || new_devices[d].is_empty())
        );
        if fuse {
            if let Some(Step::Each { devices }) = self.ops.last_mut() {
                for (device, ops) in new_devices.into_iter().enumerate() {
                    if !ops.is_empty() {
                        devices[device] = ops;
                    }
                }
            }
        } else {
            self.ops.push(Step::Each {
                devices: new_devices,
            });
        }
        self
    }

    pub(crate) fn push_op<O: Operation + 'a>(&mut self, op: O) -> &mut Self {
        self.ops.push(Step::Op(Box::new(op)));
        self
    }

    pub(crate) fn take_ops(self) -> Vec<Box<dyn Operation + 'a>> {
        self.ops
            .into_iter()
            .map(|step| match step {
                Step::Op(op) => op,
                Step::Each { devices } => {
                    let slot_frames = each_slot_frames(&devices);
                    Box::new(EachOwned {
                        devices,
                        slot_frames,
                    }) as Box<dyn Operation + 'a>
                }
            })
            .collect()
    }

    pub fn build(&self) -> Result<Frames, Error> {
        let mut out = Frames::default();
        self.build_into(&mut out)?;
        Ok(out)
    }

    pub fn build_into(&self, out: &mut Frames) -> Result<(), Error> {
        out.clear();

        let mut guard = self
            .mirror
            .as_ref()
            .filter(|handle| handle.enabled)
            .map(|handle| handle.state.lock().unwrap_or_else(PoisonError::into_inner));

        let mut work = match guard.as_deref() {
            Some(Mirror::Synced(states)) => Some(states.clone()),
            _ => None,
        };

        for step in &self.ops {
            match step {
                Step::Op(op) => {
                    out.push_op(op.as_ref(), self.num_devices)?;
                    if let Some(work) = work.as_mut() {
                        for (device, state) in work.iter_mut().enumerate() {
                            op.reflect(device, state)?;
                        }
                    }
                }
                Step::Each { devices } => {
                    out.push_each_step(devices, self.num_devices)?;
                    if let Some(work) = work.as_mut() {
                        for (device, state) in work.iter_mut().enumerate() {
                            each_reflect(devices, device, state)?;
                        }
                    }
                }
            }
        }

        if let (Some(guard), Some(work)) = (guard.as_mut(), work) {
            **guard = Mirror::Synced(work);
        }
        Ok(())
    }
}

fn each_slot_frames(devices: &[Vec<Box<dyn Operation + '_>>]) -> Vec<usize> {
    let num_slots = devices.iter().map(Vec::len).max().unwrap_or(0);
    let mut slot_frames = vec![0usize; num_slots];
    for ops in devices {
        for (slot, op) in ops.iter().enumerate() {
            slot_frames[slot] = slot_frames[slot].max(op.frames());
        }
    }
    slot_frames
}

fn each_locate(slot_frames: &[usize], frame: usize) -> Option<(usize, usize)> {
    let mut remaining = frame;
    for (slot, &frames) in slot_frames.iter().enumerate() {
        if remaining < frames {
            return Some((slot, remaining));
        }
        remaining -= frames;
    }
    None
}

fn each_encode(
    devices: &[Vec<Box<dyn Operation + '_>>],
    slot_frames: &[usize],
    device: usize,
    frame: usize,
    out: &mut [u8; PAYLOAD_BYTES],
) -> Result<Cmd, Error> {
    if let Some((slot, subframe)) = each_locate(slot_frames, frame) {
        if let Some(op) = devices.get(device).and_then(|ops| ops.get(slot))
            && subframe < op.frames()
        {
            return op.encode(device, subframe, out);
        }
        return Nop.encode(device, subframe, out);
    }
    Nop.encode(device, frame, out)
}

fn each_reflect(
    devices: &[Vec<Box<dyn Operation + '_>>],
    device: usize,
    state: &mut FirmwareState,
) -> Result<(), Error> {
    if let Some(ops) = devices.get(device) {
        for op in ops {
            op.reflect(device, state)?;
        }
    }
    Ok(())
}

struct EachOwned<'a> {
    devices: Vec<Vec<Box<dyn Operation + 'a>>>,
    slot_frames: Vec<usize>,
}

impl Operation for EachOwned<'_> {
    fn frames(&self) -> usize {
        self.slot_frames.iter().sum()
    }

    fn distribution(&self) -> Distribution {
        Distribution::PerDevice
    }

    fn encode(
        &self,
        device: usize,
        frame: usize,
        out: &mut [u8; PAYLOAD_BYTES],
    ) -> Result<Cmd, Error> {
        each_encode(&self.devices, &self.slot_frames, device, frame, out)
    }

    fn reflect(&self, device: usize, state: &mut FirmwareState) -> Result<(), Error> {
        each_reflect(&self.devices, device, state)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::Pattern;
    use crate::operation::{ConfigModulation, ConfigPattern, WritePatternBuffer};
    use crate::value::{LoopBehavior, ModulationBank, SamplingConfig};

    #[derive(Clone, Copy)]
    struct Multi(usize);

    impl Operation for Multi {
        fn frames(&self) -> usize {
            self.0
        }

        fn distribution(&self) -> Distribution {
            Distribution::PerDevice
        }

        fn encode(
            &self,
            _device: usize,
            frame: usize,
            out: &mut [u8; PAYLOAD_BYTES],
        ) -> Result<Cmd, Error> {
            out[0] = u8::try_from(frame).unwrap();
            Ok(Cmd::ConfigModulation)
        }
    }

    fn cmd_at(frames: &Frames, frame: usize, device: usize) -> Cmd {
        frames.frame(frame).unwrap().datagrams()[device].cmd
    }

    #[test]
    fn push_each_routes_per_device() {
        let mut b = DatagramBuilder::new(2);
        b.push_each(|device| {
            Some(ConfigModulation {
                bank: if device == 0 {
                    ModulationBank::B0
                } else {
                    ModulationBank::B1
                },
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 1);
        let frame = frames.frame(0).unwrap();
        assert_eq!(frame.distribution(), Distribution::PerDevice);
        assert_eq!(frame.datagrams()[0].payload[0], 0, "device 0 -> bank B0");
        assert_eq!(frame.datagrams()[1].payload[0], 1, "device 1 -> bank B1");
    }

    #[test]
    fn push_each_fills_unassigned_with_nop() {
        let mut b = DatagramBuilder::new(2);
        b.push_each(|device| {
            (device == 0).then_some(ConfigModulation {
                bank: ModulationBank::B0,
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        let frames = b.build().unwrap();

        assert_eq!(cmd_at(&frames, 0, 0), Cmd::ConfigModulation);
        assert_eq!(cmd_at(&frames, 0, 1), Cmd::Nop, "unassigned -> Nop");
    }

    #[test]
    fn push_each_pads_shorter_device_with_nop() {
        let mut b = DatagramBuilder::new(2);
        b.push_each(|device| Some(if device == 0 { Multi(1) } else { Multi(3) }));
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 3, "frame count = max over devices");
        assert_eq!(cmd_at(&frames, 0, 0), Cmd::ConfigModulation);
        assert_eq!(cmd_at(&frames, 1, 0), Cmd::Nop);
        assert_eq!(cmd_at(&frames, 2, 0), Cmd::Nop);
        for frame in 0..3 {
            assert_eq!(cmd_at(&frames, frame, 1), Cmd::ConfigModulation);
            assert_eq!(
                frames.frame(frame).unwrap().datagrams()[1].payload[0] as usize,
                frame
            );
        }
    }

    #[test]
    fn push_each_accepts_heterogeneous_boxed_commands() {
        let patterns = vec![vec![crate::value::Emission::default(); Autd3::NUM_TRANSDUCERS]; 2];
        let mut b = DatagramBuilder::new(2);
        b.push_each(|device| {
            Some(if device == 0 {
                Pattern::new(&patterns).boxed()
            } else {
                ConfigModulation {
                    bank: ModulationBank::B0,
                    config: SamplingConfig::FREQ_40K,
                    size: 1,
                    loop_behavior: LoopBehavior::Infinite,
                }
                .boxed()
            })
        });
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 3);
        assert_eq!(cmd_at(&frames, 0, 0), Cmd::WritePatternBuffer);
        assert_eq!(cmd_at(&frames, 0, 1), Cmd::ConfigModulation);
        assert_eq!(cmd_at(&frames, 1, 1), Cmd::Nop);
        assert_eq!(cmd_at(&frames, 2, 1), Cmd::Nop);
    }

    #[test]
    fn adjacent_disjoint_push_each_fuse_into_shared_frames() {
        let mut b = DatagramBuilder::new(2);
        b.push_each(|device| {
            (device == 0).then_some(ConfigModulation {
                bank: ModulationBank::B0,
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        b.push_each(|device| {
            (device == 1).then_some(ConfigModulation {
                bank: ModulationBank::B1,
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 1, "disjoint groups fuse into one frame");
        let frame = frames.frame(0).unwrap();
        assert_eq!(frame.datagrams()[0].payload[0], 0, "device 0 -> B0");
        assert_eq!(frame.datagrams()[1].payload[0], 1, "device 1 -> B1");
    }

    #[test]
    fn adjacent_overlapping_push_each_stay_sequential() {
        let mut b = DatagramBuilder::new(2);
        b.push_each(|_| {
            Some(ConfigModulation {
                bank: ModulationBank::B0,
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        b.push_each(|_| {
            Some(ConfigModulation {
                bank: ModulationBank::B1,
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 2, "overlapping coverage stays sequential");
        assert_eq!(frames.frame(0).unwrap().datagrams()[0].payload[0], 0);
        assert_eq!(frames.frame(1).unwrap().datagrams()[0].payload[0], 1);
    }

    #[test]
    fn broadcast_push_is_a_fuse_barrier() {
        let mut b = DatagramBuilder::new(2);
        b.push_each(|device| {
            (device == 0).then_some(ConfigModulation {
                bank: ModulationBank::B0,
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        b.push(ConfigPattern {
            bank: PatternBank::B0,
            config: SamplingConfig::FREQ_40K,
            size: 1,
            loop_behavior: LoopBehavior::Infinite,
        });
        b.push_each(|device| {
            (device == 1).then_some(ConfigModulation {
                bank: ModulationBank::B1,
                config: SamplingConfig::FREQ_40K,
                size: 1,
                loop_behavior: LoopBehavior::Infinite,
            })
        });
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 3, "broadcast between steps prevents fusion");
        assert_eq!(
            frames.frame(1).unwrap().distribution(),
            Distribution::Broadcast
        );
    }
    use crate::geometry::Autd3;
    use crate::value::{Emission, PatternBank};

    #[test]
    fn broadcast_op_yields_one_frame_of_one_datagram() {
        let op = ConfigPattern {
            bank: PatternBank::B0,
            config: SamplingConfig::FREQ_40K,
            size: 1,
            loop_behavior: LoopBehavior::Infinite,
        };
        let mut b = DatagramBuilder::new(4);
        b.push(op);
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 1);
        let frame = frames.frame(0).unwrap();
        assert_eq!(frame.distribution(), Distribution::Broadcast);
        assert_eq!(frame.datagrams().len(), 1);
        assert_eq!(frame.datagrams()[0].cmd, Cmd::ConfigPattern);
    }

    #[test]
    fn per_device_op_yields_one_datagram_per_device() {
        let patterns = vec![vec![Emission::default(); Autd3::NUM_TRANSDUCERS]; 3];
        let op = WritePatternBuffer {
            bank: PatternBank::B0,
            index: 0,
            emissions: &patterns,
        };
        let mut b = DatagramBuilder::new(3);
        b.push(op);
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 1);
        let frame = frames.frame(0).unwrap();
        assert_eq!(frame.distribution(), Distribution::PerDevice);
        assert_eq!(frame.datagrams().len(), 3);
    }

    #[test]
    fn composite_emission_orders_write_then_config() {
        let patterns = vec![vec![Emission::default(); Autd3::NUM_TRANSDUCERS]; 2];
        let we = WritePatternBuffer {
            bank: PatternBank::B0,
            index: 0,
            emissions: &patterns,
        };
        let ce = ConfigPattern {
            bank: PatternBank::B0,
            config: SamplingConfig::FREQ_40K,
            size: 1,
            loop_behavior: LoopBehavior::Infinite,
        };
        let mut b = DatagramBuilder::new(2);
        b.push(we).push(ce);
        let frames = b.build().unwrap();

        assert_eq!(frames.len(), 2);
        assert_eq!(
            frames.frame(0).unwrap().distribution(),
            Distribution::PerDevice
        );
        assert_eq!(frames.frame(0).unwrap().datagrams().len(), 2);
        assert_eq!(
            frames.frame(1).unwrap().distribution(),
            Distribution::Broadcast
        );
        assert_eq!(
            frames.frame(1).unwrap().datagrams()[0].cmd,
            Cmd::ConfigPattern
        );
    }

    #[test]
    fn build_into_reuses_buffer_without_growing() {
        let op = ConfigPattern {
            bank: PatternBank::B0,
            config: SamplingConfig::FREQ_40K,
            size: 1,
            loop_behavior: LoopBehavior::Infinite,
        };
        let mut b = DatagramBuilder::new(1);
        b.push(op);

        let mut buf = Frames::default();
        b.build_into(&mut buf).unwrap();
        let cap_after_first = buf.payloads.capacity();
        b.build_into(&mut buf).unwrap();

        assert_eq!(buf.len(), 1);
        assert_eq!(
            buf.payloads.capacity(),
            cap_after_first,
            "second build must not reallocate"
        );
    }
}