ph-haptics 0.1.0

Host-compiled haptics DSL and no-std, no-alloc scheduling runtime modeling ERM and LRA motors using ph-curves
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
use crate::compiled::CompiledHapticDef;
use crate::dsl::{Instruction, LoopMode, Program};
use crate::error::Error;
use crate::motor::{DriveCommand, MotorConfig, MotorProfile, frac_to_level};
use ph_curves::{MonotonicCurve, MonotonicCurveLut256, Tickless};

/// One output frame produced by [`Runner::poll`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Frame {
    /// Driver command for the current time.
    pub command: DriveCommand,
    /// Earliest wrapping `u32` clock value at which output may change.
    ///
    /// While this is `Some(deadline)`, [`Self::command`] is guaranteed not to
    /// change before `deadline`, so the caller may sleep until then. Compare or
    /// wait using wrapping arithmetic rather than absolute `<` / `>`. A deadline
    /// equal to the current poll time requests another poll at that same time to
    /// drain an immediate control-flow transition. `None` means there is no
    /// active or pending transition because the runner is idle or has finished.
    pub next_transition_ms: Option<u32>,
    /// Active instruction index in the current cycle.
    pub instruction_index: Option<usize>,
    /// `true` only when a finite program has completed.
    ///
    /// This is edge-triggered, not a latched state: it is set on the single
    /// [`Runner::poll`] that observes the end of the program, which also stops
    /// the runner. Later polls return an idle frame with `finished == false`.
    /// Act on completion when you first see it rather than polling for it.
    pub finished: bool,
}

impl Frame {
    const fn idle() -> Self {
        Self {
            command: DriveCommand::Off,
            next_transition_ms: None,
            instruction_index: None,
            finished: false,
        }
    }

    /// Returns `true` for an ordinary idle frame with no active instruction.
    ///
    /// The one-shot completion frame is not considered idle; it instead reports
    /// [`Self::is_finished`].
    pub const fn is_idle(&self) -> bool {
        self.instruction_index.is_none() && self.next_transition_ms.is_none() && !self.finished
    }

    /// Returns `true` when an instruction is active.
    pub const fn is_active(&self) -> bool {
        self.instruction_index.is_some() && !self.finished
    }

    /// Returns `true` when a finite program reached the end.
    pub const fn is_finished(&self) -> bool {
        self.finished
    }

    /// Convenience getter for driver command.
    pub const fn command(&self) -> DriveCommand {
        self.command
    }

    /// Return the earliest wrapping clock value at which output may change.
    ///
    /// See [`Frame::next_transition_ms`] for the sleep and same-timestamp polling
    /// contract.
    pub const fn next_transition_ms(&self) -> Option<u32> {
        self.next_transition_ms
    }
}

impl Default for Frame {
    fn default() -> Self {
        Self::idle()
    }
}

#[derive(Copy, Clone, Debug)]
struct Located<'a, C> {
    index: usize,
    instruction: &'a Instruction<C>,
    segment_start_ms: u32,
}

/// Executes a [`Program`] against an ERM or LRA motor configuration.
///
/// The caller supplies a free-running wrapping `u32` millisecond clock to
/// [`Runner::poll`] and applies the returned [`DriveCommand`]. Polling may then
/// pause until [`Frame::next_transition_ms`]; fixed-rate polling is unnecessary.
#[derive(Debug)]
pub struct Runner<'a, C = MonotonicCurveLut256>
where
    C: MonotonicCurve<u8, u8> + Copy,
{
    program: &'a Program<'a, C>,
    gamma_curve: Option<&'a MonotonicCurveLut256>,
    motor: MotorConfig,
    start_ms: u32,
    running: bool,
    /// Minimum level below which output snaps to off (from profile min_run_frac).
    min_level: u16,
    /// Maximum level ceiling (from profile max_frac).
    max_level: u16,
    /// Level to drive during a kick pulse (from profile kick_frac, clamped to max).
    kick_level: u16,
    /// Kick pulse duration in ms (from profile kick_ms).
    kick_duration_ms: u32,
    /// Set when output was floor-snapped to off (motor has stalled).
    needs_kick: bool,
    /// Whether a kick pulse is currently active.
    kick_active: bool,
    /// Absolute time at which an active kick pulse ends.
    kick_end_ms: u32,
}

impl<'a, C> Runner<'a, C>
where
    C: MonotonicCurve<u8, u8> + Copy,
{
    fn build(
        program: &'a Program<'a, C>,
        profile: Option<&'a MotorProfile>,
        motor: MotorConfig,
    ) -> Result<Self, Error> {
        if program.is_empty() {
            return Err(Error::EmptyProgram);
        }

        if program.motor() != motor.kind() {
            return Err(Error::MotorKindMismatch {
                expected: program.motor(),
                got: motor.kind(),
            });
        }

        let (min_level, max_level, kick_level, kick_duration_ms) = match profile {
            Some(p) => {
                let max = frac_to_level(p.max_frac);
                let kick = frac_to_level(p.kick_frac).min(max);
                (
                    frac_to_level(p.min_run_frac),
                    max,
                    kick,
                    u32::from(p.kick_ms),
                )
            }
            None => (0, 0, 0, 0),
        };

        Ok(Self {
            program,
            gamma_curve: profile.and_then(|profile| profile.gamma_curve),
            motor,
            start_ms: 0,
            running: false,
            min_level,
            max_level,
            kick_level,
            kick_duration_ms,
            needs_kick: false,
            kick_active: false,
            kick_end_ms: 0,
        })
    }

    /// Start playback at `now_ms`.
    pub fn start(&mut self, now_ms: u32) {
        self.start_ms = now_ms;
        self.running = true;
        // Motor is at rest — request a kick on the first above-min poll.
        self.needs_kick = self.kick_duration_ms > 0;
        self.kick_active = false;
        self.kick_end_ms = 0;
    }

    /// Restart playback from the beginning at `now_ms`.
    pub fn restart(&mut self, now_ms: u32) {
        self.start(now_ms);
    }

    /// Start playback at `now_ms` and return the first frame.
    pub fn start_and_poll(&mut self, now_ms: u32) -> Frame {
        self.start(now_ms);
        self.poll(now_ms)
    }

    /// Poll current output; if not running, start playback at `now_ms` first.
    pub fn poll_or_start(&mut self, now_ms: u32) -> Frame {
        if !self.running {
            self.start(now_ms);
        }
        self.poll(now_ms)
    }

    /// Stop playback.
    pub fn stop(&mut self) {
        self.running = false;
    }

    /// Whether the program is currently running.
    pub const fn is_running(&self) -> bool {
        self.running
    }

    /// Motor configuration assigned to this runner.
    pub const fn motor(&self) -> MotorConfig {
        self.motor
    }

    /// Current start timestamp used as cycle origin.
    pub const fn start_ms(&self) -> u32 {
        self.start_ms
    }

    /// Evaluate output for the wrapping millisecond clock value `now_ms`.
    ///
    /// The returned frame's deadline is the earliest time the command may
    /// change. Callers should wait with wrapping arithmetic and poll again at
    /// that deadline. If the deadline equals `now_ms`, poll again immediately to
    /// drain the control-flow transition. Completion is edge-triggered; see
    /// [`Frame::finished`].
    pub fn poll(&mut self, now_ms: u32) -> Frame {
        if !self.running {
            return Frame::idle();
        }

        let elapsed_ms = now_ms.wrapping_sub(self.start_ms);
        let located = locate_instruction(self.program, self.start_ms, elapsed_ms);

        let Some(located) = located else {
            self.running = false;
            return Frame {
                command: DriveCommand::Off,
                next_transition_ms: None,
                instruction_index: None,
                finished: true,
            };
        };

        let (level, lra_frequency_hz, next_transition_ms) =
            eval_instruction(located.instruction, located.segment_start_ms, now_ms);
        let mut level = level;

        // Floor enforcement in logical (pre-gamma) space. Codegen clamps authored
        // levels *up* to `min_run_frac` so they survive this check; anything still
        // below the floor here cannot spin the motor, so it snaps to full off.
        if self.min_level > 0 && level > 0 && level < self.min_level {
            level = 0;
        }

        // Re-arm kick whenever the motor is at rest (Pause, hold 0, or floor-snap).
        if level == 0 && self.kick_duration_ms > 0 {
            self.needs_kick = true;
            self.kick_active = false;
        }

        // Kick injection: when recovering from rest/stall, overdrive the motor
        // for kick_duration_ms so it overcomes static friction. The `level > 0`
        // guard matters when `min_level == 0`: without it a resting segment would
        // both arm and consume the kick on every poll, pushing `kick_end_ms`
        // forward forever and forcing a wake-up every `kick_ms` through a Pause.
        if self.needs_kick && level > 0 && level >= self.min_level {
            self.needs_kick = false;
            self.kick_active = true;
            self.kick_end_ms = now_ms.wrapping_add(self.kick_duration_ms);
        }
        // Expiry uses remaining-time half-range so kick_end_ms after a u32 wrap
        // still terminates; plain `now < kick_end` would keep the kick forever.
        let kick_remaining_ms = self.kick_end_ms.wrapping_sub(now_ms);
        if self.kick_active && (kick_remaining_ms == 0 || kick_remaining_ms > i32::MAX as u32) {
            self.kick_active = false;
        }
        let kick_active = self.kick_active;
        if kick_active && level > 0 {
            level = level.max(self.kick_level);
        }

        // Ceiling enforcement in logical (pre-gamma) space.
        if self.max_level > 0 && level > self.max_level {
            level = self.max_level;
        }

        let level = apply_gamma(level, self.gamma_curve);

        // Wake at kick expiry if it precedes the instruction deadline.
        let instruction_remaining_ms = next_transition_ms.wrapping_sub(now_ms);
        let next_transition_ms = if kick_active && kick_remaining_ms < instruction_remaining_ms {
            self.kick_end_ms
        } else {
            next_transition_ms
        };

        Frame {
            command: self.motor.drive(level, lra_frequency_hz),
            next_transition_ms: Some(next_transition_ms),
            instruction_index: Some(located.index),
            finished: false,
        }
    }
}

impl<'a> Runner<'a, MonotonicCurveLut256> {
    /// Build a runner directly from a generated [`CompiledHapticDef`].
    pub(crate) fn from_compiled(
        compiled: &'a CompiledHapticDef<'a>,
        motor: MotorConfig,
    ) -> Result<Self, Error> {
        Self::build(&compiled.program, compiled.profile, motor)
    }

    /// Build from a generated [`CompiledHapticDef`] and start at `now_ms`.
    pub(crate) fn from_compiled_started(
        compiled: &'a CompiledHapticDef<'a>,
        motor: MotorConfig,
        now_ms: u32,
    ) -> Result<Self, Error> {
        let mut runner = Self::build(&compiled.program, compiled.profile, motor)?;
        runner.start(now_ms);
        Ok(runner)
    }
}

fn locate_instruction<'a, C>(
    program: &'a Program<'a, C>,
    start_ms: u32,
    elapsed_ms: u32,
) -> Option<Located<'a, C>> {
    let cycle_duration = program.total_duration_ms();
    if cycle_duration == 0 {
        return None;
    }

    let cycle_elapsed = match program.loop_mode() {
        LoopMode::Once => {
            if elapsed_ms >= cycle_duration {
                return None;
            }
            elapsed_ms
        }
        LoopMode::Forever => elapsed_ms % cycle_duration,
        LoopMode::Count(n) => {
            let total = cycle_duration.saturating_mul(n);
            if elapsed_ms >= total {
                return None;
            }
            elapsed_ms % cycle_duration
        }
    };

    // Wrap-safe rebase: derive the active cycle origin from conceptual now and
    // in-cycle phase so long Forever/Count runs do not clamp at u32::MAX.
    let now_ms = start_ms.wrapping_add(elapsed_ms);
    let cycle_origin = now_ms.wrapping_sub(cycle_elapsed);
    let instructions = program.instructions();

    let mut index = 0usize;
    let mut offset = 0u32;

    while index < instructions.len() {
        let instruction = &instructions[index];
        let next_offset = offset.saturating_add(instruction.duration_ms());
        if cycle_elapsed < next_offset {
            return Some(Located {
                index,
                instruction,
                segment_start_ms: cycle_origin.wrapping_add(offset),
            });
        }
        offset = next_offset;
        index += 1;
    }

    None
}

fn eval_instruction<C>(
    instruction: &Instruction<C>,
    segment_start_ms: u32,
    now_ms: u32,
) -> (u16, Option<u16>, u32)
where
    C: MonotonicCurve<u8, u8> + Copy,
{
    match instruction {
        Instruction::Ramp(ramp) => {
            // ph-curves ≥ 0.2.1 TicklessSchedule is wrap-safe on free-running
            // u32 clocks, so feed wall-clock segment_start / now directly.
            let elapsed = now_ms.wrapping_sub(segment_start_ms).min(ramp.duration_ms);
            let schedule = ramp.curve.tickless_schedule(
                segment_start_ms,
                ramp.duration_ms,
                ramp.from,
                ramp.to,
                ramp.step,
                ramp.rounding,
                ramp.min_dt_ms,
            );
            let deadline = schedule.next_deadline(now_ms);

            // LRA Hz lerp stays segment-relative. Merge wakeups by converting
            // the amplitude deadline back to an offset before .min() — absolute
            // .min() on wrapped timestamps is wrong — then map to wall-clock.
            let amp_offset = deadline.deadline_ms.wrapping_sub(segment_start_ms);
            let (lra_freq, next_transition_offset_ms) =
                match (ramp.lra_frequency_hz, ramp.lra_frequency_hz_to) {
                    (Some(from_hz), Some(to_hz)) => {
                        let hz = lerp_lra_hz(from_hz, to_hz, elapsed, ramp.duration_ms);
                        let hz_deadline =
                            next_lra_hz_change_offset_ms(ramp.duration_ms, from_hz, to_hz, elapsed);
                        let next = match hz_deadline {
                            Some(hz_offset_ms) => amp_offset.min(hz_offset_ms),
                            None => amp_offset,
                        };
                        (Some(hz), next)
                    }
                    (freq, _) => (freq, amp_offset),
                };
            let next_transition_ms = segment_start_ms.wrapping_add(next_transition_offset_ms);

            (deadline.current_val, lra_freq, next_transition_ms)
        }
        Instruction::Hold {
            duration_ms,
            level,
            lra_frequency_hz,
        } => (
            *level,
            *lra_frequency_hz,
            segment_start_ms.wrapping_add(*duration_ms),
        ),
        Instruction::Pause { duration_ms } => {
            (0, None, segment_start_ms.wrapping_add(*duration_ms))
        }
    }
}

fn lerp_lra_hz(from_hz: u16, to_hz: u16, t_ms: u32, duration_ms: u32) -> u16 {
    // Widened to u64: `delta * t` overflows u32 for long sweeps (a 200 Hz delta
    // over a ramp of more than ~6 hours), which would panic in debug builds.
    let from = u64::from(from_hz);
    let to = u64::from(to_hz);
    let dur = u64::from(duration_ms.max(1));
    let t = u64::from(t_ms.min(duration_ms));
    let hz = if to >= from {
        from + (to - from) * t / dur
    } else {
        from - (from - to) * t / dur
    };
    hz as u16
}

/// Segment-relative ms of the next quantized LRA Hz change under linear lerp, if any.
fn next_lra_hz_change_offset_ms(
    duration_ms: u32,
    from_hz: u16,
    to_hz: u16,
    elapsed_ms: u32,
) -> Option<u32> {
    if from_hz == to_hz || duration_ms == 0 || elapsed_ms >= duration_ms {
        return None;
    }

    // Widened to u64 for the same overflow reason as `lerp_lra_hz`.
    let from = u64::from(from_hz);
    let to = u64::from(to_hz);
    let current = u64::from(lerp_lra_hz(from_hz, to_hz, elapsed_ms, duration_ms));
    let dur = u64::from(duration_ms);

    let t = if to >= from {
        let delta = to - from;
        if delta == 0 || current >= to {
            return None;
        }
        let need = current + 1 - from;
        (need * dur).div_ceil(delta)
    } else {
        let delta = from - to;
        if delta == 0 || current <= to {
            return None;
        }
        let need = from - current + 1;
        (need * dur).div_ceil(delta)
    };

    let t = t.max(u64::from(elapsed_ms) + 1);
    if t > dur {
        return None;
    }
    let mut t = t as u32;

    // Guard closed-form rounding: advance until the quantized Hz actually changes.
    let current_hz = current as u16;
    while t <= duration_ms {
        if lerp_lra_hz(from_hz, to_hz, t, duration_ms) != current_hz {
            return Some(t);
        }
        t = t.saturating_add(1);
    }
    None
}

fn apply_gamma(level: u16, gamma_curve: Option<&MonotonicCurveLut256>) -> u16 {
    if level == 0 {
        return 0;
    }
    let Some(curve) = gamma_curve else {
        return level;
    };

    let index = ((u32::from(level) * 255) + (u32::from(u16::MAX) / 2)) / u32::from(u16::MAX);
    let mapped = u32::from(curve.fwd_lut()[index as usize]);
    (((mapped * u32::from(u16::MAX)) + 127) / 255) as u16
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compiled::CompiledHapticDef;
    use crate::dsl::{Instruction, LoopMode, Program, Ramp};
    use crate::motor::{DriveCommand, ErmConfig, LraConfig, MotorConfig, MotorKind, MotorProfile};
    use ph_curves::{MonotonicCurveLut256, Rounding};

    const fn linear_lut() -> [u8; 256] {
        let mut lut = [0u8; 256];
        let mut index = 0usize;

        while index < lut.len() {
            lut[index] = index as u8;
            index += 1;
        }

        lut
    }

    const fn square_lut() -> [u8; 256] {
        let mut lut = [0u8; 256];
        let mut index = 0usize;

        while index < lut.len() {
            let x = index as u32;
            let y = ((x * x) + 127) / 255;
            lut[index] = y as u8;
            index += 1;
        }

        lut
    }

    const fn monotonic_inv_lut(fwd: &[u8; 256]) -> [u8; 256] {
        let mut inv = [0u8; 256];
        let mut out = 0usize;

        while out < inv.len() {
            let mut input = 0usize;
            while input < fwd.len() && (fwd[input] as usize) < out {
                input += 1;
            }
            inv[out] = input as u8;
            out += 1;
        }

        inv
    }

    static LINEAR_FWD: [u8; 256] = linear_lut();
    static LINEAR_INV: [u8; 256] = linear_lut();
    const LINEAR: MonotonicCurveLut256 = MonotonicCurveLut256::new(&LINEAR_FWD, &LINEAR_INV);
    static SQUARE_FWD: [u8; 256] = square_lut();
    static SQUARE_INV: [u8; 256] = monotonic_inv_lut(&SQUARE_FWD);
    const SQUARE: MonotonicCurveLut256 = MonotonicCurveLut256::new(&SQUARE_FWD, &SQUARE_INV);

    #[test]
    fn erm_ramp_is_shaped_and_finishes() {
        let instructions = [Instruction::Ramp(Ramp::new(100, 0, u16::MAX, LINEAR))];
        let program = Program::new(MotorKind::Erm, &instructions);
        let compiled = CompiledHapticDef::new("demo", program, None);
        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Erm(ErmConfig::new(255))).unwrap();
        runner.start(1_000);

        let start = runner.poll(1_000);
        assert_eq!(start.command, DriveCommand::Off);
        assert_eq!(start.instruction_index, Some(0));

        let mid = runner.poll(1_050);
        match mid.command {
            DriveCommand::Erm { duty } => assert!((120..=136).contains(&duty)),
            _ => panic!("expected ERM command"),
        }
        assert_eq!(mid.instruction_index, Some(0));
        assert!(mid.next_transition_ms.is_some());
        assert!(!mid.finished);

        let finished = runner.poll(1_101);
        assert_eq!(finished.command, DriveCommand::Off);
        assert_eq!(finished.next_transition_ms, None);
        assert_eq!(finished.instruction_index, None);
        assert!(finished.finished);
        assert!(!runner.is_running());
    }

    #[test]
    fn lra_hold_uses_frequency_override() {
        let instructions: [Instruction<MonotonicCurveLut256>; 1] =
            [Instruction::hold_with_lra_frequency(20, u16::MAX, 190)];
        let program = Program::new(MotorKind::Lra, &instructions);
        let compiled = CompiledHapticDef::new("demo", program, None);
        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Lra(LraConfig::new(2047, 235))).unwrap();
        runner.start(0);

        let frame = runner.poll(0);
        assert_eq!(
            frame.command,
            DriveCommand::Lra {
                amplitude: 2047,
                frequency_hz: 190
            }
        );
        assert_eq!(frame.next_transition_ms, Some(20));
        assert!(!frame.finished);
    }

    #[test]
    fn repeat_forever_rolls_cycle_origin() {
        let instructions: [Instruction<MonotonicCurveLut256>; 1] =
            [Instruction::hold(10, u16::MAX)];
        let program = Program::new(MotorKind::Erm, &instructions).repeat_forever();
        let compiled = CompiledHapticDef::new("demo", program, None);
        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Erm(ErmConfig::new(255))).unwrap();
        runner.start(0);

        let frame = runner.poll(25);
        assert_eq!(frame.command, DriveCommand::Erm { duty: 255 });
        assert_eq!(frame.next_transition_ms, Some(30));
        assert_eq!(frame.instruction_index, Some(0));
        assert!(!frame.finished);
    }

    #[test]
    fn lra_ramp_defaults_to_resonant_frequency() {
        let instructions = [Instruction::Ramp(Ramp::new(20, 0, u16::MAX, LINEAR))];
        let program = Program::new(MotorKind::Lra, &instructions);
        let compiled = CompiledHapticDef::new("demo", program, None);
        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Lra(LraConfig::new(1023, 240))).unwrap();
        runner.start(0);

        let frame = runner.poll(10);
        match frame.command {
            DriveCommand::Lra {
                amplitude,
                frequency_hz,
            } => {
                assert!(amplitude > 0);
                assert_eq!(frequency_hz, 240);
            }
            _ => panic!("expected LRA command"),
        }
    }

    #[test]
    fn construction_validates_program_and_motor_kind() {
        let empty: [Instruction<MonotonicCurveLut256>; 0] = [];
        let program = Program::new(MotorKind::Erm, &empty);
        let compiled = CompiledHapticDef::new("empty", program, None);
        let error =
            Runner::from_compiled(&compiled, MotorConfig::Erm(ErmConfig::new(255))).unwrap_err();
        assert_eq!(error, Error::EmptyProgram);

        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(5, 100)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let compiled = CompiledHapticDef::new("erm", program, None);
        let error = Runner::from_compiled(&compiled, MotorConfig::Lra(LraConfig::new(1000, 240)))
            .unwrap_err();
        assert_eq!(
            error,
            Error::MotorKindMismatch {
                expected: MotorKind::Erm,
                got: MotorKind::Lra,
            }
        );
    }

    #[test]
    fn ergonomic_start_helpers_work() {
        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(10, 1000)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let compiled = CompiledHapticDef::new("demo", program, None);
        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Erm(ErmConfig::new(255))).unwrap();
        let first = runner.poll_or_start(42);
        assert!(first.is_active());
        assert_eq!(runner.start_ms(), 42);

        let restarted = runner.start_and_poll(100);
        assert!(restarted.is_active());
        assert_eq!(runner.start_ms(), 100);

        runner.stop();
        let idle = runner.poll(110);
        assert!(idle.is_idle());
    }

    #[test]
    fn from_compiled_helpers_work() {
        let instructions = [Instruction::Ramp(Ramp::new(20, 0, u16::MAX, LINEAR))];
        let program = Program::new(MotorKind::Erm, &instructions);
        let compiled = CompiledHapticDef::new("demo", program, None);

        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Erm(ErmConfig::new(255))).unwrap();
        runner.start(10);
        assert!(runner.is_running());
        assert_eq!(runner.start_ms(), 10);

        let mut from_compiled =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 20)
                .unwrap();
        let frame = from_compiled.poll(25);
        assert!(frame.is_active());
        assert_eq!(from_compiled.motor().kind(), MotorKind::Erm);
    }

    #[test]
    fn profile_gamma_curve_maps_output_level() {
        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(20, 32_768)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(0, 255, 64, 255, Some(&SQUARE), 2, 1, 8);
        let compiled = CompiledHapticDef::new("gamma_hold", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        let frame = runner.poll(0);
        match frame.command {
            DriveCommand::Erm { duty } => assert!((60..=66).contains(&duty)),
            _ => panic!("expected ERM command"),
        }
    }

    #[test]
    fn floor_snaps_low_level_to_off() {
        // min_run_frac=153 (~60%), so levels below ~60% of u16::MAX should snap to 0.
        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(20, 10_000)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(0, 255, 153, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("floor_test", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        let frame = runner.poll(0);
        assert_eq!(frame.command, DriveCommand::Off);
    }

    #[test]
    fn max_level_ceiling_clamps_output() {
        // max_frac=128 (~50%), hold at u16::MAX should be clamped down.
        let instructions: [Instruction<MonotonicCurveLut256>; 1] =
            [Instruction::hold(20, u16::MAX)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(0, 128, 0, 128, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("max_test", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(1023)), 0)
                .unwrap();

        let frame = runner.poll(0);
        match frame.command {
            DriveCommand::Erm { duty } => {
                // max_frac=128 → max_level ≈ 32896.  scale(32896, 1023) ≈ 514
                assert!(duty <= 520, "duty {duty} should be clamped by max_level");
                assert!(duty > 0, "duty should be non-zero");
            }
            _ => panic!("expected ERM command"),
        }
    }

    #[test]
    fn kick_injection_after_floor_snap() {
        // First instruction: low level that gets floor-snapped → needs_kick.
        // Second instruction: level above min → kick should boost it.
        let instructions: [Instruction<MonotonicCurveLut256>; 2] = [
            Instruction::hold(5, 5_000),   // below min_run → snapped to off
            Instruction::hold(20, 40_000), // above min_run → should get kick
        ];
        let program = Program::new(MotorKind::Erm, &instructions);
        // kick_ms=10, kick_frac=255, min_run_frac=153 (~60%), max_frac=255
        let profile = MotorProfile::new(10, 255, 153, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("kick_test", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        // t=0: first hold at 5000, below floor → Off + needs_kick set
        let frame0 = runner.poll(0);
        assert_eq!(frame0.command, DriveCommand::Off);

        // t=5: second hold at 40000, above floor → kick active, so level >= kick_level
        let frame1 = runner.poll(5);
        match frame1.command {
            DriveCommand::Erm { duty } => {
                // kick_frac=255 → kick_level=65535 → scale(65535,255)=255
                assert_eq!(duty, 255, "during kick pulse, duty should be at kick level");
            }
            _ => panic!("expected ERM command"),
        }

        // t=16: kick expired (kick_ms=10, started at t=5, ends at t=15)
        let frame2 = runner.poll(16);
        match frame2.command {
            DriveCommand::Erm { duty } => {
                // Normal level: 40000 → scale(40000, 255) ≈ 155
                assert!(
                    duty < 200,
                    "after kick expires, duty {duty} should be normal level"
                );
            }
            _ => panic!("expected ERM command"),
        }
    }

    #[test]
    fn kick_level_clamped_to_max() {
        // kick_frac=255 but max_frac=128 → kick_level should be clamped to max_level.
        let instructions: [Instruction<MonotonicCurveLut256>; 2] = [
            Instruction::hold(5, 5_000),   // below min → snapped to off
            Instruction::hold(20, 40_000), // above min → gets kick, but kick clamped to max
        ];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(10, 255, 64, 128, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("kick_max_test", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(1023)), 0)
                .unwrap();

        let _frame0 = runner.poll(0); // floor-snapped
        let frame1 = runner.poll(5); // kick active
        match frame1.command {
            DriveCommand::Erm { duty } => {
                // max_frac=128 → max_level ≈ 32896.  scale(32896, 1023) ≈ 514
                assert!(
                    duty <= 520,
                    "kick duty {duty} should be clamped by max_level"
                );
            }
            _ => panic!("expected ERM command"),
        }
    }

    #[test]
    fn pause_instruction_outputs_off() {
        let instructions: [Instruction<MonotonicCurveLut256>; 3] = [
            Instruction::hold(10, u16::MAX),
            Instruction::Pause { duration_ms: 20 },
            Instruction::hold(10, u16::MAX),
        ];
        let program = Program::new(MotorKind::Erm, &instructions);
        let compiled = CompiledHapticDef::new("pause_test", program, None);
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        // t=0: first hold
        let frame0 = runner.poll(0);
        assert_eq!(frame0.command, DriveCommand::Erm { duty: 255 });
        assert_eq!(frame0.instruction_index, Some(0));

        // t=10: pause
        let frame1 = runner.poll(10);
        assert_eq!(frame1.command, DriveCommand::Off);
        assert_eq!(frame1.instruction_index, Some(1));

        // t=30: third hold
        let frame2 = runner.poll(30);
        assert_eq!(frame2.command, DriveCommand::Erm { duty: 255 });
        assert_eq!(frame2.instruction_index, Some(2));

        // t=40: finished
        let frame3 = runner.poll(40);
        assert!(frame3.finished);
        assert!(frame3.is_finished());
    }

    #[test]
    fn initial_kick_fires_on_startup() {
        // With needs_kick=true at start, first poll above min_level triggers kick.
        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(50, 40_000)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(12, 255, 64, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("startup_kick", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        // t=0: kick fires (needs_kick=true from start, level above min)
        let frame0 = runner.poll(0);
        match frame0.command {
            DriveCommand::Erm { duty } => assert_eq!(duty, 255, "kick should boost to max"),
            _ => panic!("expected ERM command"),
        }

        // t=12: kick expired, normal level
        let frame1 = runner.poll(12);
        match frame1.command {
            DriveCommand::Erm { duty } => {
                assert!(duty < 200, "after kick, duty {duty} should be normal level");
            }
            _ => panic!("expected ERM command"),
        }
    }

    #[test]
    fn next_transition_ms_reflects_kick_expiry() {
        // Hold for 100ms at a level above min. Kick should expire at kick_ms,
        // so next_transition_ms should be kick_end_ms rather than instruction end.
        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(100, 50_000)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(10, 255, 64, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("kick_deadline", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        // t=0: kick fires, kick_end_ms=10. next_transition = min(100, 10) = 10
        let frame0 = runner.poll(0);
        assert_eq!(frame0.next_transition_ms, Some(10));

        // t=10: kick expired, next_transition = instruction end = 100
        let frame1 = runner.poll(10);
        assert_eq!(frame1.next_transition_ms, Some(100));
    }

    #[test]
    fn multi_instruction_locate_iterates_correctly() {
        let instructions: [Instruction<MonotonicCurveLut256>; 3] = [
            Instruction::hold(10, 10_000),
            Instruction::hold(10, 30_000),
            Instruction::hold(10, u16::MAX),
        ];
        let program = Program::new(MotorKind::Erm, &instructions);
        let compiled = CompiledHapticDef::new("multi", program, None);
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        // Each hold is 10ms, so t=5→idx0, t=15→idx1, t=25→idx2
        assert_eq!(runner.poll(5).instruction_index, Some(0));
        assert_eq!(runner.poll(15).instruction_index, Some(1));
        assert_eq!(runner.poll(25).instruction_index, Some(2));
    }

    #[test]
    fn kick_rearms_after_pause_between_pulses() {
        // Two above-min holds with a Pause between them. Kick must fire on both.
        let instructions: [Instruction<MonotonicCurveLut256>; 3] = [
            Instruction::hold(20, 40_000),
            Instruction::Pause { duration_ms: 15 },
            Instruction::hold(20, 40_000),
        ];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(10, 255, 64, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("pause_kick", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        // t=0: first pulse gets startup kick
        let first = runner.poll(0);
        match first.command {
            DriveCommand::Erm { duty } => assert_eq!(duty, 255, "first pulse should kick"),
            _ => panic!("expected ERM command"),
        }

        // t=10: kick expired on first pulse
        let after_kick = runner.poll(10);
        match after_kick.command {
            DriveCommand::Erm { duty } => {
                assert!(duty < 200, "after first kick, duty {duty} should be normal");
            }
            _ => panic!("expected ERM command"),
        }

        // t=20: pause → Off and re-arm
        let pause = runner.poll(20);
        assert_eq!(pause.command, DriveCommand::Off);

        // t=35: second pulse must kick again
        let second = runner.poll(35);
        match second.command {
            DriveCommand::Erm { duty } => {
                assert_eq!(duty, 255, "second pulse after Pause should kick");
            }
            _ => panic!("expected ERM command"),
        }
    }

    #[test]
    fn lra_hz_to_wakes_between_coarse_amplitude_steps() {
        // Flat amplitude (tickless amplitude deadline = segment end only) with a
        // wide Hz sweep: polling solely at next_transition_ms must still advance Hz.
        let mut ramp = Ramp::new(1_000, u16::MAX, u16::MAX, LINEAR)
            .with_quantization(u16::MAX, Rounding::Nearest)
            .with_lra_frequency(100);
        ramp.lra_frequency_hz_to = Some(200);
        let instructions = [Instruction::Ramp(ramp)];
        let program = Program::new(MotorKind::Lra, &instructions);
        let compiled = CompiledHapticDef::new("hz_wake", program, None);
        let mut runner = Runner::from_compiled_started(
            &compiled,
            MotorConfig::Lra(LraConfig::new(2047, 240)),
            0,
        )
        .unwrap();

        let mut now = 0u32;
        let mut last_hz = None;
        let mut saw_hz_advance_before_amp_end = false;
        let mut polls = 0u32;

        while now < 1_000 && polls < 2_000 {
            let frame = runner.poll(now);
            let hz = match frame.command {
                DriveCommand::Lra { frequency_hz, .. } => frequency_hz,
                other => panic!("expected LRA command, got {other:?}"),
            };

            if let Some(prev) = last_hz
                && hz > prev
                && now < 1_000
            {
                saw_hz_advance_before_amp_end = true;
            }
            last_hz = Some(hz);

            let Some(next) = frame.next_transition_ms else {
                break;
            };
            if next <= now {
                break;
            }
            now = next;
            polls += 1;
        }

        assert!(
            saw_hz_advance_before_amp_end,
            "Hz should advance between coarse amplitude steps when following next_transition_ms"
        );
        assert!(
            last_hz.unwrap_or(0) > 100,
            "sweep should progress past starting Hz, last={last_hz:?}"
        );
    }

    /// Count the wake-ups a caller performs when it follows `next_transition_ms`
    /// exactly, over `window_ms` starting at t=0.
    fn count_wakeups(runner: &mut Runner<'_, MonotonicCurveLut256>, window_ms: u32) -> u32 {
        let mut now = 0u32;
        let mut wakeups = 0u32;

        while now < window_ms && wakeups < 10_000 {
            let frame = runner.poll(now);
            let Some(next) = frame.next_transition_ms else {
                break;
            };
            if next <= now {
                break;
            }
            now = next;
            wakeups += 1;
        }

        wakeups
    }

    #[test]
    fn pause_with_zero_min_level_does_not_storm_wakeups() {
        // Regression: with min_run_frac == 0 the kick used to arm and fire on
        // every poll of a resting segment, pushing kick_end_ms forward and
        // forcing a wake-up every kick_ms for the whole Pause.
        let instructions: [Instruction<MonotonicCurveLut256>; 2] =
            [Instruction::pause(5_000), Instruction::hold(20, 40_000)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(10, 255, 0, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("storm", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        assert_eq!(
            count_wakeups(&mut runner, 5_000),
            1,
            "a 5s pause should schedule exactly one wake-up at its end"
        );
    }

    #[test]
    fn kick_still_fires_after_pause_when_min_level_is_zero() {
        // The storm fix must not cost us the kick on the pulse after the Pause.
        let instructions: [Instruction<MonotonicCurveLut256>; 2] =
            [Instruction::pause(100), Instruction::hold(50, 40_000)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(10, 255, 0, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("kick_after_pause", program, Some(&profile));
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        assert_eq!(runner.poll(0).command, DriveCommand::Off);
        match runner.poll(100).command {
            DriveCommand::Erm { duty } => assert_eq!(duty, 255, "pulse after Pause should kick"),
            other => panic!("expected ERM command, got {other:?}"),
        }
        match runner.poll(111).command {
            DriveCommand::Erm { duty } => assert!(duty < 200, "kick should expire, got {duty}"),
            other => panic!("expected ERM command, got {other:?}"),
        }
    }

    #[test]
    fn level_scaling_to_zero_duty_reports_off() {
        // Regression: a non-zero level that scales to duty 0 used to emit
        // `Erm { duty: 0 }`, which reads as "driver on" to consumers.
        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(20, 100)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let compiled = CompiledHapticDef::new("tiny", program, None);
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), 0)
                .unwrap();

        assert_eq!(runner.poll(0).command, DriveCommand::Off);
    }

    #[test]
    fn long_lra_sweep_does_not_overflow() {
        // `delta * t` overflowed u32 past ~6 hours of ramp; u64 math keeps it sane.
        let mut ramp = Ramp::new(20_000_000, u16::MAX, u16::MAX, LINEAR).with_lra_frequency(100);
        ramp.lra_frequency_hz_to = Some(300);
        let instructions = [Instruction::Ramp(ramp)];
        let program = Program::new(MotorKind::Lra, &instructions);
        let compiled = CompiledHapticDef::new("long_sweep", program, None);
        let mut runner = Runner::from_compiled_started(
            &compiled,
            MotorConfig::Lra(LraConfig::new(2047, 240)),
            0,
        )
        .unwrap();

        match runner.poll(10_000_000).command {
            DriveCommand::Lra { frequency_hz, .. } => assert_eq!(frequency_hz, 200),
            other => panic!("expected LRA command, got {other:?}"),
        }
    }

    #[test]
    fn forever_near_u32_max_keeps_segment_deadlines() {
        let instructions: [Instruction<MonotonicCurveLut256>; 1] =
            [Instruction::hold(10, u16::MAX)];
        let program = Program::new(MotorKind::Erm, &instructions).repeat_forever();
        let compiled = CompiledHapticDef::new("near_max", program, None);
        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Erm(ErmConfig::new(255))).unwrap();
        runner.start(0);

        // 3ms into a 10ms cycle near the end of the u32 timeline.
        let now = (u32::MAX / 10) * 10 + 3;
        let frame = runner.poll(now);
        assert_eq!(frame.command, DriveCommand::Erm { duty: 255 });
        assert_eq!(frame.instruction_index, Some(0));
        assert_eq!(frame.next_transition_ms, Some(now.wrapping_add(7)));
        assert!(!frame.finished);
    }

    #[test]
    fn forever_continues_after_clock_wraparound() {
        let instructions: [Instruction<MonotonicCurveLut256>; 2] =
            [Instruction::hold(5, u16::MAX), Instruction::hold(5, 10_000)];
        let program = Program::new(MotorKind::Erm, &instructions).repeat_forever();
        let compiled = CompiledHapticDef::new("clock_wrap", program, None);
        let start = u32::MAX - 2;
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), start)
                .unwrap();

        let frame = runner.poll(start.wrapping_add(7));
        assert_eq!(frame.instruction_index, Some(1));
        assert_eq!(frame.next_transition_ms, Some(start.wrapping_add(10)));
        assert!(!frame.finished);
    }

    #[test]
    fn ramp_and_lra_sweep_continue_after_clock_wraparound() {
        let mut ramp = Ramp::new(10, 0, u16::MAX, LINEAR).with_lra_frequency(100);
        ramp.lra_frequency_hz_to = Some(200);
        let instructions = [Instruction::Ramp(ramp)];
        let program = Program::new(MotorKind::Lra, &instructions);
        let compiled = CompiledHapticDef::new("ramp_clock_wrap", program, None);
        let start = u32::MAX - 5;
        let mut runner = Runner::from_compiled_started(
            &compiled,
            MotorConfig::Lra(LraConfig::new(1_000, 200)),
            start,
        )
        .unwrap();

        let now = start.wrapping_add(6);
        let frame = runner.poll(now);
        match frame.command {
            DriveCommand::Lra {
                amplitude,
                frequency_hz,
            } => {
                assert!(amplitude > 0, "ramp amplitude should advance after wrap");
                assert_eq!(frequency_hz, 160);
            }
            _ => panic!("expected LRA command"),
        }
        let next = frame.next_transition_ms.unwrap();
        assert!(next.wrapping_sub(now) <= 4);
    }

    #[test]
    fn kick_expires_after_clock_wraparound() {
        let instructions: [Instruction<MonotonicCurveLut256>; 1] = [Instruction::hold(50, 40_000)];
        let program = Program::new(MotorKind::Erm, &instructions);
        let profile = MotorProfile::new(10, 255, 64, 255, None, 2, 1, 8);
        let compiled = CompiledHapticDef::new("kick_clock_wrap", program, Some(&profile));
        let start = u32::MAX - 5;
        let mut runner =
            Runner::from_compiled_started(&compiled, MotorConfig::Erm(ErmConfig::new(255)), start)
                .unwrap();

        let kick = runner.poll(start);
        assert_eq!(kick.command, DriveCommand::Erm { duty: 255 });
        assert_eq!(kick.next_transition_ms, Some(start.wrapping_add(10)));

        let after_kick = runner.poll(start.wrapping_add(10));
        match after_kick.command {
            DriveCommand::Erm { duty } => {
                assert!(duty < 200, "after kick, duty {duty} should be normal level");
            }
            _ => panic!("expected ERM command"),
        }
    }

    #[test]
    fn count_near_u32_max_keeps_segment_deadlines() {
        let instructions: [Instruction<MonotonicCurveLut256>; 2] =
            [Instruction::hold(5, u16::MAX), Instruction::hold(5, 10_000)];
        // Enough repeats that total duration saturates well past u32::MAX.
        let program = Program::new(MotorKind::Erm, &instructions)
            .with_loop_mode(LoopMode::Count(u32::MAX / 10 + 100));
        let compiled = CompiledHapticDef::new("count_near_max", program, None);
        let mut runner =
            Runner::from_compiled(&compiled, MotorConfig::Erm(ErmConfig::new(255))).unwrap();
        runner.start(0);

        // 7ms into a 10ms cycle → second hold, 3ms remaining (stay below u32::MAX).
        let now = u32::MAX - 8; // MAX ≡ 5 (mod 10) ⇒ now ≡ 7 (mod 10)
        let frame = runner.poll(now);
        assert_eq!(frame.instruction_index, Some(1));
        assert_eq!(frame.next_transition_ms, Some(now.wrapping_add(3)));
    }
}