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
//! FrameSession and FrameSessionConfig — public frame-mode API.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use crate::backend::{BackendKind, WriteOutcome};
use crate::error::{Error, Result};
use crate::reconnect::{reconnect_backend_with_retry, ReconnectPolicy};
use crate::scheduler;
use crate::stream::StreamControl;
use crate::types::{DacInfo, LaserPoint, RunExit};
use super::engine::{ColorDelayLine, PresentationEngine};
use super::{
default_transition, Frame, OutputFilter, OutputFilterContext, OutputResetReason,
PresentedSliceKind, TransitionFn,
};
/// Convert a duration to a point count at the given PPS rate.
fn duration_to_points(d: Duration, pps: u32) -> usize {
if d.is_zero() {
0
} else {
(d.as_secs_f64() * pps as f64).ceil() as usize
}
}
// =============================================================================
// FrameSessionConfig
// =============================================================================
/// Configuration for a frame-mode streaming session.
pub struct FrameSessionConfig {
/// Points per second output rate.
pub pps: u32,
/// Transition function for blanking between frames.
pub transition_fn: TransitionFn,
/// Duration of forced blanking after arming (default: 1ms).
pub startup_blank: std::time::Duration,
/// Number of points to shift RGB relative to XY (0 = disabled).
///
/// Delays color channels relative to XY coordinates, compensating for
/// the difference in galvo mirror and laser modulation response times.
/// Applied at composition time. Set to 0 to disable.
pub color_delay_points: usize,
/// Reconnection configuration (default: disabled).
///
/// Set via [`with_reconnect`](Self::with_reconnect) to enable automatic
/// reconnection when the device disconnects.
pub reconnect: Option<crate::types::ReconnectConfig>,
/// Policy for what to output when the stream is idle (disarmed).
///
/// Controls scanner behavior when disarmed. Default: [`Blank`](crate::types::IdlePolicy::Blank)
/// (park at origin with laser off). Use [`Park`](crate::types::IdlePolicy::Park) to park at a
/// specific position.
pub idle_policy: crate::types::IdlePolicy,
/// Optional hook for processing the final presented output.
pub output_filter: Option<Box<dyn OutputFilter>>,
}
impl FrameSessionConfig {
const DEFAULT_COLOR_DELAY: std::time::Duration = std::time::Duration::from_micros(150);
/// Create a new config with the given PPS and default transition.
pub fn new(pps: u32) -> Self {
let color_delay_points =
(Self::DEFAULT_COLOR_DELAY.as_secs_f64() * pps as f64).ceil() as usize;
Self {
pps,
transition_fn: default_transition(pps),
startup_blank: std::time::Duration::from_millis(1),
color_delay_points,
idle_policy: crate::types::IdlePolicy::default(),
reconnect: None,
output_filter: None,
}
}
/// Set the transition function (builder pattern).
pub fn with_transition_fn(mut self, f: TransitionFn) -> Self {
self.transition_fn = f;
self
}
/// Set the startup blank duration (builder pattern).
pub fn with_startup_blank(mut self, duration: std::time::Duration) -> Self {
self.startup_blank = duration;
self
}
/// Set the color delay in points (builder pattern).
pub fn with_color_delay_points(mut self, n: usize) -> Self {
self.color_delay_points = n;
self
}
/// Enable automatic reconnection (builder pattern).
///
/// Requires the device to have been opened via [`open_device`](crate::open_device).
pub fn with_reconnect(mut self, config: crate::types::ReconnectConfig) -> Self {
self.reconnect = Some(config);
self
}
/// Set the idle policy (builder pattern).
///
/// Controls scanner behavior when disarmed. See [`crate::types::IdlePolicy`].
pub fn with_idle_policy(mut self, policy: crate::types::IdlePolicy) -> Self {
self.idle_policy = policy;
self
}
/// Install a final-output filter (builder pattern).
pub fn with_output_filter(mut self, filter: Box<dyn OutputFilter>) -> Self {
self.output_filter = Some(filter);
self
}
}
// =============================================================================
// FrameSession
// =============================================================================
/// Read-only liveness and connectivity metrics for a [`FrameSession`].
#[derive(Clone)]
pub struct FrameSessionMetrics {
inner: Arc<FrameSessionMetricsInner>,
}
struct FrameSessionMetricsInner {
connected: AtomicBool,
origin: Instant,
last_loop_activity_nanos: AtomicU64,
last_write_success_nanos: AtomicU64,
}
impl FrameSessionMetrics {
fn new(connected: bool) -> Self {
let metrics = Self {
inner: Arc::new(FrameSessionMetricsInner {
connected: AtomicBool::new(connected),
origin: Instant::now(),
last_loop_activity_nanos: AtomicU64::new(0),
last_write_success_nanos: AtomicU64::new(0),
}),
};
metrics.mark_loop_activity();
metrics
}
/// Returns whether the session currently has a connected backend.
pub fn connected(&self) -> bool {
self.inner.connected.load(Ordering::SeqCst)
}
/// Returns the last time the scheduler thread showed progress.
pub fn last_loop_activity(&self) -> Option<Instant> {
self.instant_from_nanos(self.inner.last_loop_activity_nanos.load(Ordering::SeqCst))
}
/// Returns the last time a backend write completed successfully.
pub fn last_write_success(&self) -> Option<Instant> {
self.instant_from_nanos(self.inner.last_write_success_nanos.load(Ordering::SeqCst))
}
fn instant_from_nanos(&self, nanos: u64) -> Option<Instant> {
if nanos == 0 {
None
} else {
self.inner.origin.checked_add(Duration::from_nanos(nanos))
}
}
fn now_nanos(&self) -> u64 {
(self.inner.origin.elapsed().as_nanos().min(u64::MAX as u128) as u64).max(1)
}
fn mark_loop_activity(&self) {
self.inner
.last_loop_activity_nanos
.store(self.now_nanos(), Ordering::SeqCst);
}
fn mark_write_success(&self) {
let now = self.now_nanos();
self.inner
.last_loop_activity_nanos
.store(now, Ordering::SeqCst);
self.inner
.last_write_success_nanos
.store(now, Ordering::SeqCst);
}
fn set_connected(&self, connected: bool) {
self.inner.connected.store(connected, Ordering::SeqCst);
self.mark_loop_activity();
}
}
struct MetricsDisconnectGuard(FrameSessionMetrics);
impl Drop for MetricsDisconnectGuard {
fn drop(&mut self) {
self.0.set_connected(false);
}
}
/// A frame-mode streaming session.
///
/// Owns a scheduler thread that reads frames from a channel and writes them
/// to the DAC backend using the appropriate strategy (FIFO or frame-swap).
///
/// # Example
///
/// ```ignore
/// use laser_dac::{open_device, FrameSessionConfig, Frame, LaserPoint};
///
/// let device = open_device("my-device")?;
/// let config = FrameSessionConfig::new(30_000);
/// let (session, _info) = device.start_frame_session(config)?;
///
/// session.control().arm()?;
/// session.send_frame(Frame::new(vec![
/// LaserPoint::new(0.0, 0.0, 65535, 0, 0, 65535),
/// ]));
/// ```
pub struct FrameSession {
control: StreamControl,
thread: Option<JoinHandle<Result<RunExit>>>,
frame_slot: Arc<Mutex<Option<Frame>>>,
metrics: FrameSessionMetrics,
}
impl FrameSession {
/// Start a frame session on the given backend.
pub(crate) fn start(
mut backend: BackendKind,
config: FrameSessionConfig,
reconnect_policy: Option<ReconnectPolicy>,
) -> Result<Self> {
// Connect if needed
if !backend.is_connected() {
backend.connect()?;
}
let (control_tx, control_rx) = mpsc::channel();
let initial_color_delay = if config.color_delay_points > 0 {
Duration::from_secs_f64(config.color_delay_points as f64 / config.pps as f64)
} else {
Duration::ZERO
};
let control = StreamControl::new(control_tx, initial_color_delay, config.pps);
let frame_slot: Arc<Mutex<Option<Frame>>> = Arc::new(Mutex::new(None));
let metrics = FrameSessionMetrics::new(backend.is_connected());
let control_clone = control.clone();
let is_frame_swap = backend.is_frame_swap();
let slot_clone = frame_slot.clone();
let metrics_clone = metrics.clone();
let thread = std::thread::spawn(move || {
let _disconnect_guard = MetricsDisconnectGuard(metrics_clone.clone());
if is_frame_swap {
Self::run_frame_swap_loop(
backend,
config,
control_clone,
control_rx,
slot_clone,
metrics_clone,
reconnect_policy,
)
} else {
Self::run_fifo_loop(
backend,
config,
control_clone,
control_rx,
slot_clone,
metrics_clone,
reconnect_policy,
)
}
});
Ok(Self {
control,
thread: Some(thread),
frame_slot,
metrics,
})
}
/// Returns a control handle for arm/disarm/stop.
pub fn control(&self) -> StreamControl {
self.control.clone()
}
/// Submit a frame for display. Latest-wins: overwrites any unconsumed
/// pending frame immediately, with no buffering or memory growth.
pub fn send_frame(&self, frame: Frame) {
*self.frame_slot.lock().unwrap() = Some(frame);
}
/// Returns true if the scheduler thread has finished.
pub fn is_finished(&self) -> bool {
self.thread.as_ref().is_some_and(|h| h.is_finished())
}
/// Returns a metrics handle for observing scheduler liveness.
pub fn metrics(&self) -> FrameSessionMetrics {
self.metrics.clone()
}
/// Wait for the session thread to finish and return the exit reason.
pub fn join(mut self) -> Result<RunExit> {
if let Some(handle) = self.thread.take() {
handle
.join()
.unwrap_or(Err(Error::disconnected("thread panicked")))
} else {
Ok(RunExit::Stopped)
}
}
// =========================================================================
// FIFO scheduler loop
// =========================================================================
fn run_fifo_loop(
backend: BackendKind,
config: FrameSessionConfig,
control: StreamControl,
control_rx: mpsc::Receiver<crate::stream::ControlMsg>,
frame_slot: Arc<Mutex<Option<Frame>>>,
metrics: FrameSessionMetrics,
reconnect_policy: Option<ReconnectPolicy>,
) -> Result<RunExit> {
let is_udp_timed = backend.caps().output_model == crate::types::OutputModel::UdpTimed;
if is_udp_timed {
Self::run_udp_timed_loop(
backend,
config,
control,
control_rx,
frame_slot,
metrics,
reconnect_policy,
)
} else {
Self::run_fifo_estimation_loop(
backend,
config,
control,
control_rx,
frame_slot,
metrics,
reconnect_policy,
)
}
}
/// Fixed-rate loop for UdpTimed backends (LaserCube WiFi).
///
/// Sends a fixed chunk every cycle at precise intervals. No buffer
/// estimation — just metronomic pacing. This avoids all the overflow
/// and estimation issues that plague UDP-based laser DACs.
fn run_udp_timed_loop(
mut backend: BackendKind,
config: FrameSessionConfig,
control: StreamControl,
control_rx: mpsc::Receiver<crate::stream::ControlMsg>,
frame_slot: Arc<Mutex<Option<Frame>>>,
metrics: FrameSessionMetrics,
reconnect_policy: Option<ReconnectPolicy>,
) -> Result<RunExit> {
let FrameSessionConfig {
pps: initial_pps,
transition_fn,
startup_blank,
color_delay_points,
idle_policy,
reconnect: _,
output_filter,
} = config;
let initial_pps_f64 = initial_pps as f64;
// Fixed chunk: ~10ms worth of points (small enough to avoid overflow,
// large enough for efficient packets). At 30kpps = 300 points = ~2 packets.
let mut chunk_points =
((initial_pps_f64 * 0.010).ceil() as usize).min(backend.caps().max_points_per_chunk);
let mut chunk_duration = Duration::from_secs_f64(chunk_points as f64 / initial_pps_f64);
let mut engine = PresentationEngine::new(transition_fn);
let mut chunk_buffer = vec![LaserPoint::default(); chunk_points];
let mut color_delay = ColorDelayLine::new(color_delay_points);
let mut shutter_open = false;
let mut startup_blank_remaining: usize = 0;
let mut last_armed = false;
let mut next_send = Instant::now();
let mut last_frame: Option<Frame> = None;
let mut retry_points: Option<usize> = None;
let mut output_filter = output_filter;
Self::reset_output_filter(&mut output_filter, OutputResetReason::SessionStart);
loop {
metrics.mark_loop_activity();
// 1. High-precision wait until next send time
Self::sleep_until_precise(
&control,
&control_rx,
next_send,
&mut shutter_open,
&mut backend,
&metrics,
)?;
next_send += chunk_duration;
// Catch up if we fell behind (don't accumulate debt)
let now = Instant::now();
if next_send < now {
next_send = now;
}
let pps = control.pps();
let pps_f64 = pps as f64;
let new_chunk_points =
((pps_f64 * 0.010).ceil() as usize).min(backend.caps().max_points_per_chunk);
if new_chunk_points != chunk_points {
chunk_points = new_chunk_points;
chunk_buffer.resize(chunk_points, LaserPoint::default());
chunk_duration = Duration::from_secs_f64(chunk_points as f64 / pps_f64);
}
let startup_blank_points = duration_to_points(startup_blank, pps);
color_delay.resize(duration_to_points(control.color_delay(), pps));
// 2. Check stop
if control.is_stop_requested() {
return Ok(RunExit::Stopped);
}
// 3. Check for new frame (latest-wins slot)
if let Some(frame) = frame_slot.lock().unwrap().take() {
last_frame = Some(frame.clone());
engine.set_pending(frame);
}
// 4. Check connection
if !backend.is_connected() {
if let Some(ref policy) = reconnect_policy {
match Self::try_reconnect(
&mut backend,
policy,
&control,
&mut shutter_open,
&mut last_armed,
&mut engine,
&last_frame,
false,
&metrics,
) {
Ok(_info) => {
next_send = Instant::now();
color_delay.reset();
Self::reset_output_filter(
&mut output_filter,
OutputResetReason::Reconnect,
);
retry_points = None;
continue;
}
Err(exit) => return Ok(exit),
}
}
return Ok(RunExit::Disconnected);
}
// 5. Process control messages
if Self::process_control_messages(&control_rx, &mut shutter_open, &mut backend) {
return Ok(RunExit::Stopped);
}
// 6. Handle arm/disarm transitions
let is_armed = control.is_armed();
if let Some(reason) = Self::handle_shutter_transition(
is_armed,
&mut last_armed,
&mut shutter_open,
&mut startup_blank_remaining,
startup_blank_points,
&mut backend,
) {
Self::reset_output_filter(&mut output_filter, reason);
}
// 7. Fill chunk from engine
let n = if let Some(n) = retry_points {
n
} else {
let n = engine.fill_chunk(&mut chunk_buffer, chunk_points);
if n == 0 {
continue;
}
// Apply blanking modifications
Self::apply_blanking(
is_armed,
&mut startup_blank_remaining,
&mut chunk_buffer[..n],
&idle_policy,
);
// Apply color delay (stateful — carries across chunks)
color_delay.apply(&mut chunk_buffer[..n]);
if engine.has_logical_frame() {
Self::apply_output_filter(
&mut output_filter,
&mut chunk_buffer[..n],
OutputFilterContext {
pps,
kind: PresentedSliceKind::FifoChunk,
is_cyclic: false,
},
);
}
retry_points = Some(n);
n
};
// 8. Write. On backpressure, retry the exact same transmit
// buffer next cycle instead of advancing frame state.
match backend.try_write(pps, &chunk_buffer[..n]) {
Ok(WriteOutcome::Written) => {
metrics.mark_write_success();
retry_points = None;
}
Ok(WriteOutcome::WouldBlock) => {
metrics.mark_loop_activity();
// Device busy — keep retry_points set and retry next cycle
}
Err(e) if e.is_disconnected() => {
if let Some(ref policy) = reconnect_policy {
match Self::try_reconnect(
&mut backend,
policy,
&control,
&mut shutter_open,
&mut last_armed,
&mut engine,
&last_frame,
false,
&metrics,
) {
Ok(_info) => {
next_send = Instant::now();
color_delay.reset();
Self::reset_output_filter(
&mut output_filter,
OutputResetReason::Reconnect,
);
retry_points = None;
continue;
}
Err(exit) => return Ok(exit),
}
}
return Ok(RunExit::Disconnected);
}
Err(_) => {}
}
}
}
/// Buffer-estimation loop for standard FIFO backends (Ether Dream, IDN, etc).
fn run_fifo_estimation_loop(
mut backend: BackendKind,
config: FrameSessionConfig,
control: StreamControl,
control_rx: mpsc::Receiver<crate::stream::ControlMsg>,
frame_slot: Arc<Mutex<Option<Frame>>>,
metrics: FrameSessionMetrics,
reconnect_policy: Option<ReconnectPolicy>,
) -> Result<RunExit> {
let FrameSessionConfig {
transition_fn,
startup_blank,
color_delay_points,
idle_policy,
output_filter,
..
} = config;
let mut max_points = backend.caps().max_points_per_chunk;
let target_buffer_secs = 0.020_f64;
let mut engine = PresentationEngine::new(transition_fn);
let mut scheduled_ahead: u64 = 0;
let mut fractional_consumed: f64 = 0.0;
let mut last_iteration = Instant::now();
let mut chunk_buffer = vec![LaserPoint::default(); max_points];
let mut color_delay = ColorDelayLine::new(color_delay_points);
let mut shutter_open = false;
let mut startup_blank_remaining: usize = 0;
let mut last_armed = false;
let mut last_frame: Option<Frame> = None;
let mut output_filter = output_filter;
Self::reset_output_filter(&mut output_filter, OutputResetReason::SessionStart);
loop {
metrics.mark_loop_activity();
// 1. Check stop
if control.is_stop_requested() {
return Ok(RunExit::Stopped);
}
let pps = control.pps();
let pps_f64 = pps as f64;
let target_buffer_points = (target_buffer_secs * pps_f64) as u64;
let startup_blank_points = duration_to_points(startup_blank, pps);
color_delay.resize(duration_to_points(control.color_delay(), pps));
// Time-based decay of scheduled_ahead
let now = Instant::now();
scheduler::advance_scheduled_ahead(
&mut scheduled_ahead,
&mut fractional_consumed,
&mut last_iteration,
now,
pps_f64,
);
// 2. Check for new frame (latest-wins slot)
if let Some(frame) = frame_slot.lock().unwrap().take() {
last_frame = Some(frame.clone());
engine.set_pending(frame);
}
// 3. Estimate buffer
let buffered =
scheduler::conservative_buffered_points(scheduled_ahead, backend.queued_points());
// 4. Sleep if buffer healthy
if buffered > target_buffer_points {
let excess = buffered - target_buffer_points;
let sleep_time = Duration::from_secs_f64(excess as f64 / pps_f64);
Self::sleep_with_control_check(
&control,
&control_rx,
sleep_time,
&mut shutter_open,
&mut backend,
&metrics,
)?;
continue;
}
// 5. Check connection
if !backend.is_connected() {
if let Some(ref policy) = reconnect_policy {
match Self::try_reconnect(
&mut backend,
policy,
&control,
&mut shutter_open,
&mut last_armed,
&mut engine,
&last_frame,
false,
&metrics,
) {
Ok(info) => {
scheduled_ahead = 0;
fractional_consumed = 0.0;
last_iteration = Instant::now();
max_points = info.caps.max_points_per_chunk;
chunk_buffer.resize(max_points, LaserPoint::default());
color_delay.reset();
Self::reset_output_filter(
&mut output_filter,
OutputResetReason::Reconnect,
);
continue;
}
Err(exit) => return Ok(exit),
}
}
return Ok(RunExit::Disconnected);
}
// 6. Process control messages
if Self::process_control_messages(&control_rx, &mut shutter_open, &mut backend) {
return Ok(RunExit::Stopped);
}
// 7. Handle arm/disarm transitions
let is_armed = control.is_armed();
if let Some(reason) = Self::handle_shutter_transition(
is_armed,
&mut last_armed,
&mut shutter_open,
&mut startup_blank_remaining,
startup_blank_points,
&mut backend,
) {
Self::reset_output_filter(&mut output_filter, reason);
}
// 8. Fill chunk from engine
let deficit = (target_buffer_secs - buffered as f64 / pps_f64).max(0.0);
let target_points = ((deficit * pps_f64).ceil() as usize).min(max_points);
if target_points == 0 {
Self::sleep_and_mark_activity(Duration::from_millis(1), &metrics);
continue;
}
let n = engine.fill_chunk(&mut chunk_buffer, target_points);
if n == 0 {
Self::sleep_and_mark_activity(Duration::from_millis(1), &metrics);
continue;
}
// Apply blanking modifications
Self::apply_blanking(
is_armed,
&mut startup_blank_remaining,
&mut chunk_buffer[..n],
&idle_policy,
);
// Apply color delay (stateful — carries across chunks)
color_delay.apply(&mut chunk_buffer[..n]);
if engine.has_logical_frame() {
Self::apply_output_filter(
&mut output_filter,
&mut chunk_buffer[..n],
OutputFilterContext {
pps,
kind: PresentedSliceKind::FifoChunk,
is_cyclic: false,
},
);
}
// 9. Write to backend with retry on WouldBlock
loop {
match backend.try_write(pps, &chunk_buffer[..n]) {
Ok(WriteOutcome::Written) => {
metrics.mark_write_success();
scheduled_ahead += n as u64;
break;
}
Ok(WriteOutcome::WouldBlock) => {
metrics.mark_loop_activity();
std::thread::yield_now();
if control.is_stop_requested() {
return Ok(RunExit::Stopped);
}
Self::sleep_and_mark_activity(Duration::from_micros(100), &metrics);
}
Err(e) if e.is_disconnected() => {
if let Some(ref policy) = reconnect_policy {
match Self::try_reconnect(
&mut backend,
policy,
&control,
&mut shutter_open,
&mut last_armed,
&mut engine,
&last_frame,
false,
&metrics,
) {
Ok(info) => {
scheduled_ahead = 0;
fractional_consumed = 0.0;
last_iteration = Instant::now();
max_points = info.caps.max_points_per_chunk;
chunk_buffer.resize(max_points, LaserPoint::default());
color_delay.reset();
Self::reset_output_filter(
&mut output_filter,
OutputResetReason::Reconnect,
);
break;
}
Err(exit) => return Ok(exit),
}
}
return Ok(RunExit::Disconnected);
}
Err(_) => {
break;
}
}
}
}
}
// =========================================================================
// Frame-swap scheduler loop
// =========================================================================
fn run_frame_swap_loop(
mut backend: BackendKind,
config: FrameSessionConfig,
control: StreamControl,
control_rx: mpsc::Receiver<crate::stream::ControlMsg>,
frame_slot: Arc<Mutex<Option<Frame>>>,
metrics: FrameSessionMetrics,
reconnect_policy: Option<ReconnectPolicy>,
) -> Result<RunExit> {
let FrameSessionConfig {
transition_fn,
startup_blank,
color_delay_points,
idle_policy,
output_filter,
..
} = config;
let mut engine = PresentationEngine::new(transition_fn);
engine.set_frame_capacity(backend.frame_capacity());
let mut shutter_open = false;
let mut startup_blank_remaining: usize = 0;
let mut last_armed = false;
let mut last_frame: Option<Frame> = None;
let mut frame_buf: Vec<LaserPoint> = Vec::new();
let mut color_delay = ColorDelayLine::new(color_delay_points);
let mut write_pending = false;
let mut output_filter = output_filter;
Self::reset_output_filter(&mut output_filter, OutputResetReason::SessionStart);
loop {
metrics.mark_loop_activity();
// 1. Check stop
if control.is_stop_requested() {
return Ok(RunExit::Stopped);
}
let pps = control.pps();
let startup_blank_points = duration_to_points(startup_blank, pps);
color_delay.resize(duration_to_points(control.color_delay(), pps));
// 2. Check for new frame (latest-wins slot)
if let Some(frame) = frame_slot.lock().unwrap().take() {
last_frame = Some(frame.clone());
engine.set_pending(frame);
}
// 3. Check connection
if !backend.is_connected() {
if let Some(ref policy) = reconnect_policy {
match Self::try_reconnect(
&mut backend,
policy,
&control,
&mut shutter_open,
&mut last_armed,
&mut engine,
&last_frame,
true,
&metrics,
) {
Ok(_info) => {
engine.set_frame_capacity(backend.frame_capacity());
color_delay.reset();
Self::reset_output_filter(
&mut output_filter,
OutputResetReason::Reconnect,
);
write_pending = false;
continue;
}
Err(exit) => return Ok(exit),
}
}
return Ok(RunExit::Disconnected);
}
// 4. Process control messages
if Self::process_control_messages(&control_rx, &mut shutter_open, &mut backend) {
return Ok(RunExit::Stopped);
}
// 5. Handle arm/disarm transitions
let is_armed = control.is_armed();
if let Some(reason) = Self::handle_shutter_transition(
is_armed,
&mut last_armed,
&mut shutter_open,
&mut startup_blank_remaining,
startup_blank_points,
&mut backend,
) {
Self::reset_output_filter(&mut output_filter, reason);
}
// 6. Check if device is ready
if !write_pending && !backend.is_ready_for_frame() {
Self::sleep_and_mark_activity(Duration::from_millis(1), &metrics);
continue;
}
// 7. Compose frame and copy to reusable buffer
if !write_pending {
let composed = engine.compose_hardware_frame();
if composed.is_empty() {
Self::sleep_and_mark_activity(Duration::from_millis(1), &metrics);
continue;
}
frame_buf.clear();
frame_buf.extend_from_slice(composed);
// Apply blanking modifications
Self::apply_blanking(
is_armed,
&mut startup_blank_remaining,
&mut frame_buf,
&idle_policy,
);
color_delay.apply(&mut frame_buf);
Self::apply_output_filter(
&mut output_filter,
&mut frame_buf,
OutputFilterContext {
pps,
kind: PresentedSliceKind::FrameSwapFrame,
is_cyclic: true,
},
);
}
// 8. Write frame
match backend.try_write(pps, &frame_buf) {
Ok(WriteOutcome::Written) => {
metrics.mark_write_success();
write_pending = false;
}
Ok(WriteOutcome::WouldBlock) => {
metrics.mark_loop_activity();
write_pending = true;
Self::sleep_and_mark_activity(Duration::from_millis(1), &metrics);
}
Err(e) if e.is_disconnected() => {
if let Some(ref policy) = reconnect_policy {
match Self::try_reconnect(
&mut backend,
policy,
&control,
&mut shutter_open,
&mut last_armed,
&mut engine,
&last_frame,
true,
&metrics,
) {
Ok(_info) => {
engine.set_frame_capacity(backend.frame_capacity());
color_delay.reset();
Self::reset_output_filter(
&mut output_filter,
OutputResetReason::Reconnect,
);
write_pending = false;
continue;
}
Err(exit) => return Ok(exit),
}
}
return Ok(RunExit::Disconnected);
}
Err(_) => {}
}
}
}
// =========================================================================
// Shared helpers
// =========================================================================
/// Attempt to reconnect the backend using the reconnection policy.
///
/// On success, replaces `backend` and resets scheduler state.
/// Returns the new `DacInfo` on success.
#[allow(clippy::too_many_arguments)]
fn try_reconnect(
backend: &mut BackendKind,
policy: &ReconnectPolicy,
control: &StreamControl,
shutter_open: &mut bool,
last_armed: &mut bool,
engine: &mut PresentationEngine,
last_frame: &Option<Frame>,
expected_frame_swap: bool,
metrics: &FrameSessionMetrics,
) -> std::result::Result<DacInfo, RunExit> {
metrics.set_connected(false);
let current_pps = control.pps();
let (info, new_backend) = reconnect_backend_with_retry(
policy,
|| control.is_stop_requested(),
|info, new_backend| {
if current_pps < info.caps.pps_min || current_pps > info.caps.pps_max {
log::error!(
"'{}' PPS {} outside new device range [{}, {}]",
policy.target.device_id,
current_pps,
info.caps.pps_min,
info.caps.pps_max
);
return Err(RunExit::Disconnected);
}
if new_backend.is_frame_swap() != expected_frame_swap {
log::error!(
"'{}' reconnected device has incompatible backend type",
policy.target.device_id
);
return Err(RunExit::Disconnected);
}
Ok(())
},
|| metrics.mark_loop_activity(),
)?;
// Swap backend
*backend = new_backend;
*shutter_open = false;
*last_armed = false;
metrics.set_connected(true);
// Reset engine and replay last frame
engine.reset();
if let Some(frame) = last_frame {
engine.set_pending(frame.clone());
}
// Fire on_reconnect
if let Some(cb) = policy.on_reconnect.lock().unwrap().as_mut() {
cb(&info);
}
Ok(info)
}
/// Handle arm/disarm shutter transitions.
fn handle_shutter_transition(
is_armed: bool,
last_armed: &mut bool,
shutter_open: &mut bool,
startup_blank_remaining: &mut usize,
startup_blank_points: usize,
backend: &mut BackendKind,
) -> Option<OutputResetReason> {
if !*last_armed && is_armed {
*startup_blank_remaining = startup_blank_points;
if !*shutter_open {
let _ = backend.set_shutter(true);
*shutter_open = true;
}
*last_armed = is_armed;
return Some(OutputResetReason::Arm);
} else if *last_armed && !is_armed {
if *shutter_open {
let _ = backend.set_shutter(false);
*shutter_open = false;
}
*last_armed = is_armed;
return Some(OutputResetReason::Disarm);
}
*last_armed = is_armed;
None
}
/// Apply disarm blanking and startup blanking to a buffer.
fn apply_blanking(
is_armed: bool,
startup_blank_remaining: &mut usize,
buffer: &mut [LaserPoint],
idle_policy: &crate::types::IdlePolicy,
) {
if !is_armed {
// When disarmed, apply idle policy: park scanners instead of tracing shapes
let park = match idle_policy {
crate::types::IdlePolicy::Park { x, y } => LaserPoint::blanked(*x, *y),
// RepeatLast falls back to Blank when disarmed
_ => LaserPoint::blanked(0.0, 0.0),
};
buffer.fill(park);
} else if *startup_blank_remaining > 0 {
let blank_count = buffer.len().min(*startup_blank_remaining);
for p in &mut buffer[..blank_count] {
p.r = 0;
p.g = 0;
p.b = 0;
p.intensity = 0;
}
*startup_blank_remaining -= blank_count;
}
}
fn process_control_messages(
control_rx: &mpsc::Receiver<crate::stream::ControlMsg>,
shutter_open: &mut bool,
backend: &mut BackendKind,
) -> bool {
use std::sync::mpsc::TryRecvError;
loop {
match control_rx.try_recv() {
Ok(crate::stream::ControlMsg::Arm) => {
if !*shutter_open {
let _ = backend.set_shutter(true);
*shutter_open = true;
}
}
Ok(crate::stream::ControlMsg::Disarm) => {
if *shutter_open {
let _ = backend.set_shutter(false);
*shutter_open = false;
}
}
Ok(crate::stream::ControlMsg::Stop) => {
return true;
}
Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => break,
}
}
false
}
fn reset_output_filter(
output_filter: &mut Option<Box<dyn OutputFilter>>,
reason: OutputResetReason,
) {
if let Some(filter) = output_filter.as_deref_mut() {
filter.reset(reason);
}
}
fn apply_output_filter(
output_filter: &mut Option<Box<dyn OutputFilter>>,
points: &mut [LaserPoint],
ctx: OutputFilterContext,
) {
if let Some(filter) = output_filter.as_deref_mut() {
filter.filter(points, &ctx);
}
}
fn sleep_with_control_check(
control: &StreamControl,
control_rx: &mpsc::Receiver<crate::stream::ControlMsg>,
duration: std::time::Duration,
shutter_open: &mut bool,
backend: &mut BackendKind,
metrics: &FrameSessionMetrics,
) -> Result<()> {
const SLICE: std::time::Duration = std::time::Duration::from_millis(2);
let mut remaining = duration;
while remaining > std::time::Duration::ZERO {
let slice = remaining.min(SLICE);
std::thread::sleep(slice);
remaining = remaining.saturating_sub(slice);
metrics.mark_loop_activity();
if control.is_stop_requested() {
return Err(Error::Stopped);
}
Self::process_control_messages(control_rx, shutter_open, backend);
}
Ok(())
}
/// High-precision sleep for UdpTimed backends.
///
/// Uses coarse sleeps first, then busy-waits near the deadline to
/// minimize wake-up jitter. Matches `Stream::sleep_until_with_control_check`.
fn sleep_until_precise(
control: &StreamControl,
control_rx: &mpsc::Receiver<crate::stream::ControlMsg>,
deadline: std::time::Instant,
shutter_open: &mut bool,
backend: &mut BackendKind,
metrics: &FrameSessionMetrics,
) -> Result<()> {
const BUSY_WAIT_THRESHOLD: std::time::Duration = std::time::Duration::from_micros(500);
const SLEEP_SLICE: std::time::Duration = std::time::Duration::from_millis(1);
loop {
let now = std::time::Instant::now();
if now >= deadline {
return Ok(());
}
let remaining = deadline.duration_since(now);
if remaining > BUSY_WAIT_THRESHOLD {
let slice = remaining
.saturating_sub(BUSY_WAIT_THRESHOLD)
.min(SLEEP_SLICE);
std::thread::sleep(slice);
} else {
std::thread::yield_now();
}
metrics.mark_loop_activity();
if control.is_stop_requested() {
return Err(Error::Stopped);
}
Self::process_control_messages(control_rx, shutter_open, backend);
}
}
fn sleep_and_mark_activity(duration: Duration, metrics: &FrameSessionMetrics) {
std::thread::sleep(duration);
metrics.mark_loop_activity();
}
}
impl Drop for FrameSession {
fn drop(&mut self) {
let _ = self.control.stop();
if let Some(handle) = self.thread.take() {
let _ = handle.join();
}
}
}