1use std::path::PathBuf;
21use std::sync::Arc;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::mpsc::{self, Receiver, RecvError, RecvTimeoutError, Sender, TryRecvError};
24use std::thread::{self, JoinHandle};
25use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
26
27use midir::{Ignore, MidiInput, MidiInputConnection, MidiOutput, MidiOutputConnection};
28
29#[cfg(feature = "ble")]
30use crate::ble::{self, Ble};
31use crate::capture::{self, Entry};
32use crate::catalog::Module;
33use crate::midi::{Msg, hex, host, req};
34use crate::queue::{RequestQueue, follow_up, handshake};
35use crate::records::{Preset, Settings};
36use crate::upload::{self, UploadError, UserAmpInfo};
37use crate::{Assembler, Origin, is_ble_port, is_stomp_port};
38
39#[derive(Clone, Debug)]
41pub struct Config {
42 pub client_name: String,
44 pub auto_connect: bool,
47 pub sync: bool,
49 pub reply_timeout: Duration,
51 pub scan_interval: Duration,
53 pub bluetooth: bool,
55}
56
57impl Default for Config {
58 fn default() -> Self {
59 Config {
60 client_name: "Open Stomp".into(),
61 auto_connect: true,
62 sync: true,
63 reply_timeout: Duration::from_secs(1),
64 scan_interval: Duration::from_millis(1500),
65 bluetooth: true,
66 }
67 }
68}
69
70pub enum Command {
71 Connect(String),
73 Disconnect,
74 Resync,
76 SetSync(bool),
78 Send(Vec<u8>),
80 Write(Vec<Vec<u8>>),
82 Replay { path: PathBuf, speed: f32 },
84 StopReplay,
85}
86
87#[derive(Clone, Debug, PartialEq)]
88pub enum Status {
89 Disconnected,
90 Connected {
91 port: String,
92 output: bool,
94 },
95 Replaying {
96 file: String,
97 progress: f32,
98 },
99}
100
101#[derive(Clone, Debug, PartialEq)]
102pub enum Update {
103 Ports(Vec<String>),
105 Status(Status),
106 Sync { done: usize, total: usize },
108 Message { at: SystemTime, origin: Origin, bytes: Vec<u8> },
110 Mark { at: SystemTime, text: String },
112 Info { at: SystemTime, text: String, error: bool },
114 Reset,
116}
117
118enum Internal {
119 Cmd(Command),
120 Input(Vec<u8>),
121 #[cfg(feature = "ble")]
122 Ble(ble::Event),
123 Shutdown,
124}
125
126type Waker = Arc<dyn Fn() + Send + Sync>;
127
128pub struct Device {
130 tx: Sender<Internal>,
131 rx: Receiver<Update>,
132 thread: Option<JoinHandle<()>>,
133}
134
135impl Device {
136 pub fn spawn(config: Config) -> Device {
138 Device::spawn_with_waker(config, || {})
139 }
140
141 pub fn spawn_with_waker(config: Config, wake: impl Fn() + Send + Sync + 'static) -> Device {
143 let (tx, rx_internal) = mpsc::channel();
144 let (tx_updates, rx) = mpsc::channel();
145 let engine_tx = tx.clone();
146 let wake: Waker = Arc::new(wake);
147 let thread = thread::Builder::new()
148 .name("open-stomp-engine".into())
149 .spawn(move || Engine::new(config, tx_updates, engine_tx, wake).run(rx_internal))
150 .expect("spawn engine thread");
151 Device { tx, rx, thread: Some(thread) }
152 }
153
154 pub fn command(&self, c: Command) {
155 let _ = self.tx.send(Internal::Cmd(c));
156 }
157
158 pub fn try_recv(&self) -> Result<Update, TryRecvError> {
159 self.rx.try_recv()
160 }
161
162 pub fn recv(&self) -> Result<Update, RecvError> {
163 self.rx.recv()
164 }
165
166 pub fn recv_timeout(&self, timeout: Duration) -> Result<Update, RecvTimeoutError> {
167 self.rx.recv_timeout(timeout)
168 }
169
170 pub fn drain(&self) -> impl Iterator<Item = Update> + '_ {
172 self.rx.try_iter()
173 }
174
175 pub fn connect(&self, port: impl Into<String>) {
176 self.command(Command::Connect(port.into()));
177 }
178
179 pub fn disconnect(&self) {
180 self.command(Command::Disconnect);
181 }
182
183 pub fn resync(&self) {
184 self.command(Command::Resync);
185 }
186
187 pub fn set_sync(&self, on: bool) {
188 self.command(Command::SetSync(on));
189 }
190
191 pub fn replay(&self, path: impl Into<PathBuf>, speed: f32) {
192 self.command(Command::Replay { path: path.into(), speed });
193 }
194
195 pub fn stop_replay(&self) {
196 self.command(Command::StopReplay);
197 }
198
199 pub fn send(&self, bytes: Vec<u8>) {
201 self.command(Command::Send(bytes));
202 }
203
204 pub fn write(&self, msgs: Vec<Vec<u8>>) {
206 self.command(Command::Write(msgs));
207 }
208
209 pub fn select_preset(&self, index: u8) {
211 self.send(host::program(index));
212 }
213
214 pub fn set_head(&self, m: Module, model: u8, on: bool) {
216 if let Some(b) = host::head(m, model, on) {
217 self.send(b);
218 }
219 }
220
221 pub fn set_param(&self, m: Module, slot: usize, value: u8) {
223 if let Some(b) = host::param(m, slot, value) {
224 self.send(b);
225 }
226 }
227
228 pub fn set_volume(&self, value: u8) {
229 self.send(host::volume(value));
230 }
231
232 pub fn show_page(&self, m: Module) {
234 self.send(host::page(m));
235 }
236
237 pub fn set_chain(&self, order: &[u8]) {
241 if let Some(b) = host::chain(order) {
242 self.write(vec![b]);
243 }
244 }
245
246 pub fn looper_button(&self, button: u8) {
248 self.send(host::looper_button(button));
249 }
250
251 pub fn set_tuner(&self, on: bool) {
254 self.write(vec![host::tuner(on)]);
255 }
256
257 pub fn save_preset(&self, source_slot: u8, preset: &Preset) {
260 self.write(host::save_preset(source_slot, preset));
261 }
262
263 pub fn import_user_amp(&self, slot: u8, name: &str, data: &[f32], factor: f32) -> Result<(), UploadError> {
267 upload::check(slot, data)?;
268 if let Some(b) = host::head(Module::Amp, upload::USER_MODEL_BASE + slot, true) {
269 self.send(b);
270 }
271 self.write(upload::user_amp_upload(&UserAmpInfo::new(slot, name, factor), data));
272 Ok(())
273 }
274
275 #[cfg(feature = "nam")]
283 pub fn import_nam_file(
284 &self,
285 slot: u8,
286 path: impl AsRef<std::path::Path>,
287 ) -> Result<crate::nam::Converted, Box<dyn std::error::Error + Send + Sync>> {
288 self.import_nam_file_as(slot, path, crate::nam::convert::Measure::Optimised, true)
289 }
290
291 #[cfg(feature = "nam")]
296 pub fn import_nam_file_with(
297 &self,
298 slot: u8,
299 path: impl AsRef<std::path::Path>,
300 measure: crate::nam::convert::Measure,
301 ) -> Result<crate::nam::Converted, Box<dyn std::error::Error + Send + Sync>> {
302 self.import_nam_file_as(slot, path, measure, false)
303 }
304
305 #[cfg(feature = "nam")]
309 pub fn import_nam_file_as(
310 &self,
311 slot: u8,
312 path: impl AsRef<std::path::Path>,
313 measure: crate::nam::convert::Measure,
314 normalise: bool,
315 ) -> Result<crate::nam::Converted, Box<dyn std::error::Error + Send + Sync>> {
316 let path = path.as_ref();
317 if slot >= upload::USER_SLOTS {
318 return Err(Box::new(UploadError::Slot(slot)));
319 }
320 let mut model = crate::nam::Model::load(path)?;
321 let mut converted =
322 crate::nam::convert::convert_measured(&mut model, &crate::nam::convert::excitation(), measure);
323 if normalise {
324 crate::nam::convert::normalise_level(&mut converted, &mut model);
325 }
326 let name = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
327 self.import_user_amp(slot, &name, &converted.data, converted.factor)?;
328 Ok(converted)
329 }
330
331 pub fn delete_user_amp(&self, slot: u8) -> Result<(), UploadError> {
333 if slot >= upload::USER_SLOTS {
334 return Err(UploadError::Slot(slot));
335 }
336 self.write(vec![upload::user_amp_delete(slot), req::user_amp(slot)]);
337 Ok(())
338 }
339
340 pub fn rename_user_amp(&self, slot: u8, name: &str) -> Result<(), UploadError> {
345 if slot >= upload::USER_SLOTS {
346 return Err(UploadError::Slot(slot));
347 }
348 self.write(vec![UserAmpInfo::new(slot, name, 1.0).write_frame(), req::user_amp(slot)]);
349 Ok(())
350 }
351
352 pub fn import_user_ir(&self, slot: u8, name: &str, data: &[f32]) -> Result<(), UploadError> {
356 upload::check(slot, data)?;
357 self.send(host::page(Module::Cab));
358 if let Some(b) = host::head(Module::Cab, upload::USER_MODEL_BASE + slot, true) {
359 self.send(b);
360 }
361 self.write(upload::user_ir_upload(slot, name, data));
362 Ok(())
363 }
364
365 pub fn rename_user_ir(&self, slot: u8, name: &str) -> Result<(), UploadError> {
370 if slot >= upload::USER_SLOTS {
371 return Err(UploadError::Slot(slot));
372 }
373 self.write(vec![upload::user_ir_name(slot, name), req::ir_slot(slot)]);
374 Ok(())
375 }
376
377 pub fn import_ir_file(
384 &self,
385 slot: u8,
386 path: impl AsRef<std::path::Path>,
387 ) -> Result<crate::ir::ConvertedIr, Box<dyn std::error::Error + Send + Sync>> {
388 #[cfg(feature = "nam")]
389 let method = crate::ir::Method::Optimised;
390 #[cfg(not(feature = "nam"))]
391 let method = crate::ir::Method::App;
392 self.import_ir_file_with(slot, path, method)
393 }
394
395 pub fn import_ir_file_with(
397 &self,
398 slot: u8,
399 path: impl AsRef<std::path::Path>,
400 method: crate::ir::Method,
401 ) -> Result<crate::ir::ConvertedIr, Box<dyn std::error::Error + Send + Sync>> {
402 let path = path.as_ref();
403 if slot >= upload::USER_SLOTS {
404 return Err(Box::new(UploadError::Slot(slot)));
405 }
406 let converted = crate::ir::convert_with(&crate::ir::Wav::load(path)?, method);
407 self.import_user_ir(slot, &crate::ir::slot_name(path), &converted.data)?;
408 Ok(converted)
409 }
410
411 pub fn read_user_amp(&self, slot: u8) -> Result<(), UploadError> {
414 if slot >= upload::USER_SLOTS {
415 return Err(UploadError::Slot(slot));
416 }
417 self.write(upload::user_amp_read(slot));
418 Ok(())
419 }
420
421 pub fn read_user_ir(&self, slot: u8) -> Result<(), UploadError> {
423 if slot >= upload::USER_SLOTS {
424 return Err(UploadError::Slot(slot));
425 }
426 self.write(upload::user_ir_read(slot));
427 Ok(())
428 }
429
430 pub fn write_settings(&self, settings: &Settings) {
432 self.write(vec![host::settings_write(settings)]);
433 }
434}
435
436impl Drop for Device {
437 fn drop(&mut self) {
438 let _ = self.tx.send(Internal::Shutdown);
439 if let Some(t) = self.thread.take() {
440 let _ = t.join();
441 }
442 }
443}
444
445struct Connection {
446 port: String,
447 link: Link,
448}
449
450enum Link {
451 Midi {
452 _input: MidiInputConnection<()>,
453 output: Option<MidiOutputConnection>,
454 },
455 #[cfg(feature = "ble")]
457 Ble,
458}
459
460struct Engine {
461 config: Config,
462 out: Sender<Update>,
463 self_tx: Sender<Internal>,
464 wake: Waker,
465 scanner: Option<MidiInput>,
466 ports: Vec<String>,
467 last_scan: Option<Instant>,
468 conn: Option<Connection>,
469 replay: Option<Arc<AtomicBool>>,
470 asm: Assembler,
471 queue: RequestQueue,
472 #[cfg(feature = "ble")]
473 ble: Option<Ble>,
474 #[cfg(feature = "ble")]
476 ble_ports: Vec<String>,
477}
478
479impl Engine {
480 fn new(config: Config, out: Sender<Update>, self_tx: Sender<Internal>, wake: Waker) -> Self {
481 let scanner = MidiInput::new(&format!("{} scan", config.client_name)).ok();
482 let queue = RequestQueue::new(config.reply_timeout);
483 #[cfg(feature = "ble")]
484 let ble = config.bluetooth.then(|| Ble::spawn(ble::forward(self_tx.clone(), Internal::Ble)));
485 Engine {
486 config,
487 out,
488 self_tx,
489 wake,
490 scanner,
491 ports: vec![],
492 last_scan: None,
493 conn: None,
494 replay: None,
495 asm: Assembler::default(),
496 queue,
497 #[cfg(feature = "ble")]
498 ble,
499 #[cfg(feature = "ble")]
500 ble_ports: vec![],
501 }
502 }
503
504 fn emit(&self, u: Update) {
505 let _ = self.out.send(u);
506 (self.wake)();
507 }
508
509 fn info(&self, text: impl Into<String>, error: bool) {
510 self.emit(Update::Info { at: SystemTime::now(), text: text.into(), error });
511 }
512
513 fn emit_progress(&self) {
514 let (done, total) = self.queue.progress();
515 self.emit(Update::Sync { done, total });
516 }
517
518 fn run(mut self, rx: Receiver<Internal>) {
519 if self.scanner.is_none() {
520 self.info("MIDI is unavailable on this system (could not create a MIDI client)", true);
521 }
522 loop {
523 match rx.recv_timeout(Duration::from_millis(50)) {
524 Ok(Internal::Cmd(c)) => self.command(c),
525 Ok(Internal::Input(data)) => self.input(&data),
526 #[cfg(feature = "ble")]
527 Ok(Internal::Ble(e)) => self.ble_event(e),
528 Ok(Internal::Shutdown) | Err(RecvTimeoutError::Disconnected) => break,
529 Err(RecvTimeoutError::Timeout) => {}
530 }
531 self.pump();
532 #[cfg(target_os = "macos")]
533 run_loop_tick();
534 if self.last_scan.is_none_or(|t| t.elapsed() > self.config.scan_interval) {
535 self.scan();
536 }
537 }
538 self.stop_replay();
539 self.conn = None;
540 }
541
542 fn command(&mut self, c: Command) {
543 match c {
544 Command::Connect(port) => {
545 self.stop_replay();
546 self.config.auto_connect = true;
547 self.connect(&port);
548 }
549 Command::Disconnect => {
550 self.config.auto_connect = false;
551 self.disconnect("Disconnected");
552 }
553 Command::Resync => {
554 if self.conn.is_some() {
555 self.emit(Update::Reset);
556 self.start_sync();
557 }
558 }
559 Command::SetSync(on) => {
560 self.config.sync = on;
561 if !on {
562 self.queue.clear();
563 self.emit_progress();
564 }
565 }
566 Command::Send(bytes) => {
567 if self.writable() {
568 self.transmit(&bytes);
569 }
570 }
571 Command::Write(msgs) => {
572 if self.writable() {
573 for bytes in msgs {
574 self.queue.write(bytes);
575 }
576 }
577 }
578 Command::Replay { path, speed } => {
579 self.config.auto_connect = false;
580 self.disconnect("Disconnected for replay");
581 self.start_replay(path, speed);
582 }
583 Command::StopReplay => {
584 if self.stop_replay() {
585 self.emit(Update::Status(Status::Disconnected));
586 }
587 }
588 }
589 }
590
591 fn scan(&mut self) {
592 self.last_scan = Some(Instant::now());
593 let mut ports: Vec<String> = match &self.scanner {
594 Some(s) => s.ports().iter().filter_map(|p| s.port_name(p).ok()).collect(),
595 None => vec![],
596 };
597 #[cfg(feature = "ble")]
598 ports.extend(self.ble_ports.iter().cloned());
599 if ports != self.ports {
600 self.ports = ports.clone();
601 self.emit(Update::Ports(ports.clone()));
602 }
603 if let Some(c) = &self.conn
604 && !ports.contains(&c.port)
605 {
606 self.disconnect("Pedal unplugged");
607 }
608 if self.conn.is_none()
609 && self.replay.is_none()
610 && self.config.auto_connect
611 && let Some(p) = ports
612 .iter()
613 .find(|p| is_stomp_port(p) && !is_ble_port(p))
614 .or_else(|| ports.iter().find(|p| is_stomp_port(p)))
615 {
616 self.connect(&p.clone());
617 }
618 if self.config.auto_connect
620 && self.conn.as_ref().is_some_and(|c| is_ble_port(&c.port))
621 && let Some(p) = ports.iter().find(|p| is_stomp_port(p) && !is_ble_port(p))
622 {
623 self.connect(&p.clone());
624 }
625 }
626
627 #[cfg(feature = "ble")]
628 fn ble_event(&mut self, e: ble::Event) {
629 match e {
630 ble::Event::Ports(p) => {
631 self.ble_ports = p;
632 self.scan();
633 }
634 ble::Event::Input(bytes) => {
635 if self.conn.as_ref().is_some_and(|c| matches!(c.link, Link::Ble)) {
636 self.input(&bytes);
637 }
638 }
639 ble::Event::Lost => {
640 if self.conn.as_ref().is_some_and(|c| matches!(c.link, Link::Ble)) {
641 self.disconnect("Bluetooth connection lost");
642 }
643 }
644 ble::Event::Unavailable(why) => {
645 self.ble = None;
646 self.info(format!("Bluetooth is unavailable: {why}"), false);
647 }
648 }
649 }
650
651 fn connect(&mut self, port_name: &str) {
652 self.disconnect_quiet();
653 #[cfg(feature = "ble")]
654 if is_ble_port(port_name)
655 && let Some(ble) = &self.ble
656 {
657 self.info(format!("Connecting to {port_name} …"), false);
658 match ble.connect(port_name) {
659 Ok(()) => self.connected(Connection { port: port_name.to_owned(), link: Link::Ble }),
660 Err(e) => self.info(format!("Could not connect: {e}"), true),
661 }
662 return;
663 }
664 let result = (|| -> Result<Connection, String> {
665 let mut input = MidiInput::new(&self.config.client_name).map_err(|e| e.to_string())?;
666 input.ignore(Ignore::None);
667 let port = input
668 .ports()
669 .into_iter()
670 .find(|p| input.port_name(p).as_deref() == Ok(port_name))
671 .ok_or_else(|| format!("port “{port_name}” not found"))?;
672 let tx = self.self_tx.clone();
673 let input = input
674 .connect(
675 &port,
676 "stomp-in",
677 move |_ts, data, _| {
678 let _ = tx.send(Internal::Input(data.to_vec()));
679 },
680 (),
681 )
682 .map_err(|e| e.to_string())?;
683 let output = open_output(&self.config.client_name, port_name);
684 Ok(Connection { port: port_name.to_owned(), link: Link::Midi { _input: input, output } })
685 })();
686 match result {
687 Ok(c) => self.connected(c),
688 Err(e) => self.info(format!("Could not connect: {e}"), true),
689 }
690 }
691
692 fn connected(&mut self, c: Connection) {
693 let port = c.port.clone();
694 self.conn = Some(c);
695 let output = self.has_output();
696 self.emit(Update::Reset);
697 self.emit(Update::Status(Status::Connected { port: port.clone(), output }));
698 self.info(format!("Connected to {port}"), false);
699 if !output {
700 self.info("No MIDI output to the pedal: listening only", true);
701 }
702 self.start_sync();
703 }
704
705 fn disconnect_quiet(&mut self) {
706 #[cfg(feature = "ble")]
707 if let Some(Connection { link: Link::Ble, .. }) = self.conn
708 && let Some(ble) = &self.ble
709 {
710 ble.disconnect();
711 }
712 self.conn = None;
713 self.queue.clear();
714 self.asm = Assembler::default();
715 }
716
717 fn disconnect(&mut self, why: &str) {
718 if self.conn.is_some() {
719 self.disconnect_quiet();
720 self.emit(Update::Status(Status::Disconnected));
721 self.emit_progress();
722 self.info(why, false);
723 }
724 }
725
726 fn has_output(&self) -> bool {
727 self.conn.as_ref().is_some_and(|c| match &c.link {
728 Link::Midi { output, .. } => output.is_some(),
729 #[cfg(feature = "ble")]
730 Link::Ble => true,
731 })
732 }
733
734 fn start_sync(&mut self) {
735 self.queue.clear();
736 if !self.config.sync || !self.has_output() {
737 return;
738 }
739 self.queue.start_sync(handshake());
740 self.emit_progress();
741 }
742
743 fn writable(&self) -> bool {
745 let ok = self.config.sync && self.has_output();
746 if !ok {
747 self.info("Not sent: listen-only mode, or no MIDI output to the pedal", true);
748 }
749 ok
750 }
751
752 fn transmit(&mut self, bytes: &[u8]) -> bool {
754 let sent = match self.conn.as_mut().map(|c| &mut c.link) {
755 Some(Link::Midi { output: Some(out), .. }) => out.send(bytes).map_err(|e| e.to_string()),
756 #[cfg(feature = "ble")]
757 Some(Link::Ble) => match &self.ble {
758 Some(ble) if ble.send(vec![bytes.to_vec()]) => Ok(()),
759 _ => Err("Bluetooth stopped".into()),
760 },
761 _ => return false,
762 };
763 if let Err(e) = sent {
764 self.info(format!("Send failed: {e}"), true);
765 return false;
766 }
767 self.emit(Update::Message { at: SystemTime::now(), origin: Origin::Host, bytes: bytes.to_vec() });
768 true
769 }
770
771 fn pump(&mut self) {
773 if let Some(done) = self.queue.expire(Instant::now()) {
774 let b = done.request.bytes();
775 self.info(format!("No reply from pedal to {} …", hex(&b[..b.len().min(8)])), true);
776 if done.request.is_sync() {
777 self.emit_progress();
778 }
779 }
780 while let Some(r) = self.queue.pop() {
781 if !self.has_output() {
782 self.queue.clear();
783 return;
784 }
785 if !self.transmit(r.bytes()) {
786 return;
787 }
788 self.queue.sent(r, Instant::now());
789 }
790 }
791
792 fn input(&mut self, data: &[u8]) {
793 if self.conn.is_none() {
794 return;
795 }
796 let at = SystemTime::now();
797 for bytes in self.asm.push(data) {
798 let msg = Msg::parse(&bytes);
799 if let Some(done) = self.queue.on_message(&msg)
800 && done.request.is_sync()
801 {
802 self.emit_progress();
803 }
804 if self.config.sync {
805 for r in follow_up(&msg) {
806 self.queue.read(r);
807 }
808 }
809 self.emit(Update::Message { at, origin: Origin::Pedal, bytes });
810 }
811 }
812
813 fn start_replay(&mut self, path: PathBuf, speed: f32) {
814 self.stop_replay();
815 let text = match std::fs::read_to_string(&path) {
816 Ok(t) => t,
817 Err(e) => {
818 self.info(format!("Could not read {}: {e}", path.display()), true);
819 return;
820 }
821 };
822 let entries = capture::parse(&text);
823 let file = path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
824 let stop = Arc::new(AtomicBool::new(false));
825 self.replay = Some(stop.clone());
826 self.emit(Update::Reset);
827 self.emit(Update::Status(Status::Replaying { file: file.clone(), progress: 0.0 }));
828 self.info(format!("Replaying {file} ({} messages) at {speed}×", entries.len()), false);
829 let (out, wake) = (self.out.clone(), self.wake.clone());
830 thread::spawn(move || replay(entries, file, speed, stop, out, wake));
831 }
832
833 fn stop_replay(&mut self) -> bool {
835 match self.replay.take() {
836 Some(stop) => {
837 stop.store(true, Ordering::Relaxed);
838 true
839 }
840 None => false,
841 }
842 }
843}
844
845#[cfg(target_os = "macos")]
849fn run_loop_tick() {
850 use core_foundation_sys::runloop::{CFRunLoopRunInMode, kCFRunLoopDefaultMode};
851 unsafe {
853 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, 1);
854 }
855}
856
857fn open_output(client: &str, port_name: &str) -> Option<MidiOutputConnection> {
858 let out = MidiOutput::new(client).ok()?;
859 let ports = out.ports();
860 let names: Vec<String> = ports.iter().map(|p| out.port_name(p).unwrap_or_default()).collect();
861 let i = names.iter().position(|n| n == port_name).or_else(|| names.iter().position(|n| is_stomp_port(n)))?;
863 out.connect(&ports[i], "stomp-out").ok()
864}
865
866fn replay(entries: Vec<Entry>, file: String, speed: f32, stop: Arc<AtomicBool>, out: Sender<Update>, wake: Waker) {
868 let total = entries.len().max(1);
869 let mut prev_ms: Option<u64> = None;
870 for (i, e) in entries.into_iter().enumerate() {
871 if stop.load(Ordering::Relaxed) {
872 return;
873 }
874 let ms = match &e {
875 Entry::Mark { ms, .. } | Entry::Message { ms, .. } => *ms,
876 };
877 if let Some(p) = prev_ms {
878 let gap = ms.saturating_sub(p).min(1500) as f32 / speed.max(0.01);
879 if gap >= 1.0 {
880 thread::sleep(Duration::from_millis(gap as u64));
881 }
882 }
883 prev_ms = Some(ms);
884 let at = UNIX_EPOCH + Duration::from_millis(ms);
885 let u = match e {
886 Entry::Mark { text, .. } => Update::Mark { at, text },
887 Entry::Message { origin, bytes, .. } => Update::Message { at, origin, bytes },
888 };
889 if out.send(u).is_err() {
890 return;
891 }
892 if i % 25 == 0 {
893 let progress = i as f32 / total as f32;
894 let _ = out.send(Update::Status(Status::Replaying { file: file.clone(), progress }));
895 }
896 wake();
897 }
898 let _ = out.send(Update::Status(Status::Replaying { file, progress: 1.0 }));
899 let _ = out.send(Update::Info { at: SystemTime::now(), text: "Replay finished".into(), error: false });
900 wake();
901}