Skip to main content

open_stomp/
device.rs

1//! Background engine (feature `device`): owns the MIDI connection (or a capture replay), finds
2//! and connects to the pedal, performs the startup sync, sends edits and reports every message.
3//!
4//! With feature `ble` the engine also finds the pedal over Bluetooth LE MIDI (the pedal's
5//! Wireless setting). A Bluetooth pedal is listed as a port named `"<name> (Bluetooth)"` and
6//! behaves like a USB one; auto-connect prefers USB when both are there.
7//!
8//! [`Device::spawn`] starts the engine on its own thread and returns a [`Device`] handle. Send it
9//! [`Command`]s (or use the helper methods) and read [`Update`]s from it. The engine only moves
10//! bytes; apply [`Update::Message`]s to a [`DeviceState`](crate::DeviceState) to follow the
11//! pedal's state, and reset that state on [`Update::Reset`].
12//!
13//! SysEx requests and writes go through a [`RequestQueue`] (one in flight, 1 s reply timeout,
14//! docs/protocol/sysex.md). Live CCs/PCs ([`Device::send`]) bypass it. The pedal never echoes host messages, so
15//! every message the engine sends is reported as an [`Update::Message`] with
16//! [`Origin::Host`]; applying those keeps a `DeviceState` in step with your own edits.
17//!
18//! Dropping the [`Device`] disconnects and stops the engine thread.
19
20use 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/// Engine settings.
40#[derive(Clone, Debug)]
41pub struct Config {
42    /// MIDI client name shown by the OS (ALSA sequencer, CoreMIDI).
43    pub client_name: String,
44    /// Connect to the first pedal-looking port found, and again whenever it is plugged back in.
45    /// [`Command::Disconnect`] turns this off, [`Command::Connect`] turns it back on.
46    pub auto_connect: bool,
47    /// Whether the engine may send anything (sync reads and edits). `false` = listen only.
48    pub sync: bool,
49    /// How long to wait for a SysEx reply or ack before moving on.
50    pub reply_timeout: Duration,
51    /// How often to rescan the MIDI ports (hotplug).
52    pub scan_interval: Duration,
53    /// Also look for the pedal over Bluetooth LE MIDI. Needs feature `ble`; ignored without it.
54    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 to a MIDI input port by name (and the matching output).
72    Connect(String),
73    Disconnect,
74    /// Read everything again (sends [`Update::Reset`] first).
75    Resync,
76    /// Whether the engine may send anything (sync reads and edits). Off = pure listening.
77    SetSync(bool),
78    /// Send a live message (CC/PC) right away.
79    Send(Vec<u8>),
80    /// Queue messages to send in order; SysEx writes wait for the pedal's ack.
81    Write(Vec<Vec<u8>>),
82    /// Play a capture log (docs/protocol/capturing.md) back instead of a pedal, at `speed`× its original timing.
83    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        /// An output to the pedal was opened; without one the engine only listens.
93        output: bool,
94    },
95    Replaying {
96        file: String,
97        progress: f32,
98    },
99}
100
101#[derive(Clone, Debug, PartialEq)]
102pub enum Update {
103    /// The MIDI input ports changed (sent on start and on every hotplug).
104    Ports(Vec<String>),
105    Status(Status),
106    /// Startup sync progress; `(0, 0)` when no sync is running.
107    Sync { done: usize, total: usize },
108    /// One complete MIDI message, either direction.
109    Message { at: SystemTime, origin: Origin, bytes: Vec<u8> },
110    /// A `# MARK` annotation from a replayed capture.
111    Mark { at: SystemTime, text: String },
112    /// A note for the user: connection changes, timeouts, refused sends.
113    Info { at: SystemTime, text: String, error: bool },
114    /// A new session starts (connect, resync or replay): reset your device model.
115    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
128/// Handle to the engine thread. Cheap methods; nothing blocks except the `recv*` calls.
129pub struct Device {
130    tx: Sender<Internal>,
131    rx: Receiver<Update>,
132    thread: Option<JoinHandle<()>>,
133}
134
135impl Device {
136    /// Start the engine with no wake-up callback (poll or block on [`recv`](Device::recv)).
137    pub fn spawn(config: Config) -> Device {
138        Device::spawn_with_waker(config, || {})
139    }
140
141    /// Start the engine; `wake` runs after every batch of updates (e.g. to repaint a GUI).
142    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    /// Every update available right now, without blocking.
171    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    /// Send a live message (CC/PC) now.
200    pub fn send(&self, bytes: Vec<u8>) {
201        self.command(Command::Send(bytes));
202    }
203
204    /// Queue messages behind any pending SysEx (writes wait for their ack).
205    pub fn write(&self, msgs: Vec<Vec<u8>>) {
206        self.command(Command::Write(msgs));
207    }
208
209    /// Select preset `index` (0-based, P01 = 0).
210    pub fn select_preset(&self, index: u8) {
211        self.send(host::program(index));
212    }
213
214    /// Set a module's model and on/off. Ignored for LOOP/DRUM (no head CC).
215    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    /// Set a module parameter by slot (app display order). Ignored for slots the module lacks.
222    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    /// Make the pedal display jump to a module's page.
233    pub fn show_page(&self, m: Module) {
234        self.send(host::page(m));
235    }
236
237    /// Reorder the live preset's signal chain (all eight effect modules, GATE included, as module
238    /// indices). Like other live edits it is lost on a preset change unless saved. Ignored unless
239    /// `order` is a [`valid_chain`](crate::records::valid_chain).
240    pub fn set_chain(&self, order: &[u8]) {
241        if let Some(b) = host::chain(order) {
242            self.write(vec![b]);
243        }
244    }
245
246    /// Press a looper button (`host::LOOP_*`).
247    pub fn looper_button(&self, button: u8) {
248        self.send(host::looper_button(button));
249    }
250
251    /// Switch the tuner on or off. The pedal answers with its tuner notification, so the state is
252    /// read back.
253    pub fn set_tuner(&self, on: bool) {
254        self.write(vec![host::tuner(on)]);
255    }
256
257    /// Store `preset` in slot `preset.index` (with its name) and select it, using the official
258    /// app's sequence. `source_slot` is the active preset the edits were made on.
259    pub fn save_preset(&self, source_slot: u8, preset: &Preset) {
260        self.write(host::save_preset(source_slot, preset));
261    }
262
263    /// Import converted NAM data into user AMP `slot` (0–9) the way the official app does: select
264    /// the slot's amp model, write the slot-info record (name, factor), then the 2048 floats.
265    /// [`import_nam_file`](Device::import_nam_file) converts a `.nam` file into those floats first.
266    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    /// Convert a `.nam` file with the best conversion, [`Measure::Optimised`](crate::nam::convert::Measure::Optimised)
276    /// (closer to the model on hardware than the official app's) at a normalised level
277    /// ([`crate::nam::convert::normalise_level`]), and import it into user AMP
278    /// `slot` (0–9), named after the file like the official app does. Never reads the official app
279    /// (see [`crate::nam::convert::official_excitation`] to opt in). The conversion runs on the
280    /// calling thread and takes about a minute (optimised build); [`Device::import_nam_file_with`]
281    /// with `Measure::App` gives the official algorithm in a few seconds. Returns the conversion.
282    #[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    /// [`Device::import_nam_file`] with a choice of conversion
292    /// ([`Measure`](crate::nam::convert::Measure)): `Optimised` (the default, about a minute),
293    /// `App` (the official algorithm, a few seconds) or `Clean`. Keeps the model's own level, as
294    /// the official app does; [`Device::import_nam_file_as`] can normalise it.
295    #[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    /// [`Device::import_nam_file_with`], optionally normalising the output level
306    /// ([`crate::nam::convert::normalise_level`]: every model plays at the same level, like NAM
307    /// plugins do; a pure volume change).
308    #[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    /// Delete user AMP `slot` and re-read its info, like the official app.
332    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    /// Rename user AMP `slot` (0–9) without touching its sound: write only the slot-info record
341    /// (the import's first step, factor 1.0 like every import) with the new name, then re-read it.
342    /// The official app has no rename; this was confirmed on the pedal (the slot's response is
343    /// unchanged within 0.1 dB, docs/protocol/uploads.md). Names are cut to 31 characters.
344    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    /// Import IR data into user IR `slot` (0–9) the way the official app does: show the CAB page,
353    /// select the slot's cab model, write the 2048 floats, then the name. Checked against the official
354    /// app's imports into all ten slots (`captures/logs/02-ir-tests.log`).
355    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    /// Rename user IR `slot` (0–9) without touching its sound: write only the `0x09` name record
366    /// (the import's last step), then re-read it. Confirmed on the pedal like
367    /// [`Device::rename_user_amp`]. Names are cut to 31 characters; the official app's imports use
368    /// at most 16 ([`crate::ir::slot_name`]).
369    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    /// Convert an IR audio file (WAV, any sample rate) with the best conversion,
378    /// [`crate::ir::convert_optimised`] (a 384-tap filter fitted to the whole IR: the pedal only
379    /// plays 384 taps, so this is much closer to the real IR than the official app's), and import
380    /// it into user IR `slot` (0–9), named after the file like the official app does (first 16
381    /// characters). [`Device::import_ir_file_with`] with `Method::App` gives exactly the official
382    /// conversion. Returns the conversion.
383    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    /// [`Device::import_ir_file`] with a choice of conversion ([`crate::ir::Method`]).
396    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    /// Ask the pedal for user AMP `slot`'s model data (0–9). The 61 replies arrive as
412    /// [`Update::Message`]s (`0x58`, `dir` 2); collect them with an [`upload::Reassembler`].
413    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    /// Ask for user IR `slot`'s data, like [`Device::read_user_amp`] (replies are `0x10`, `dir` 2).
422    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    /// Write the global settings (read-modify-write: start from the pedal's current record).
431    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    /// The [`Ble`] link thread owns the connection.
456    #[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    /// Pedals in Bluetooth range, as port names.
475    #[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        // the pedal was plugged in while connected over Bluetooth: move to USB
619        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    /// Edits are allowed when connected with an output and not in listen-only mode.
744    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    /// Send one message now and report it. The pedal never echoes host messages.
753    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    /// Send queued requests while nothing is in flight; expire a timed-out request.
772    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    /// Returns whether a replay was running.
834    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/// CoreMIDI updates a client's view of the devices (hotplug) through notifications delivered on
846/// the run loop of the thread that created the client. The engine thread has no run loop of its
847/// own, so give it one turn per tick without blocking.
848#[cfg(target_os = "macos")]
849fn run_loop_tick() {
850    use core_foundation_sys::runloop::{CFRunLoopRunInMode, kCFRunLoopDefaultMode};
851    // SAFETY: plain CoreFoundation call on the current thread; returns immediately (0 s timeout).
852    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    // exact name first (ALSA, CoreMIDI), else any pedal-looking port (Windows names differ)
862    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
866/// Play a capture log back with its original timing (gaps capped at 1.5 s), scaled by `speed`.
867fn 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}