ableton-link-rs 0.1.2

Native Rust implementation of the Ableton Link protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
#![allow(clippy::too_many_arguments)]

pub mod beats;
pub mod clock;
pub mod controller;
pub mod error;
pub mod ghostxform;
pub mod host_time_filter;
pub mod linear_regression;
pub mod measurement;
pub mod median;
pub mod node;
pub mod payload;
pub mod phase;
pub mod pingresponder;
pub mod rt_session_state;
pub mod sessions;
pub mod state;
pub mod tempo;
pub mod timeline;

use std::{
    result,
    sync::{Arc, Mutex},
};

use chrono::Duration;

use self::{
    beats::Beats,
    clock::Clock,
    controller::Controller,
    phase::{force_beat_at_time_impl, from_phase_encoded_beats, phase, to_phase_encoded_beats},
    rt_session_state::RtSessionStateHandler,
    state::{ClientStartStopState, ClientState},
    tempo::Tempo,
    timeline::{clamp_tempo, Timeline},
};

pub type Result<T> = result::Result<T, error::Error>;

pub type PeerCountCallback = Arc<Mutex<Box<dyn Fn(usize) + Send>>>;
pub type TempoCallback = Arc<Mutex<Box<dyn Fn(f64) + Send>>>;
pub type StartStopCallback = Arc<Mutex<Box<dyn Fn(bool) + Send>>>;

pub struct BasicLink {
    peer_count_callback: Option<PeerCountCallback>,
    tempo_callback: Option<TempoCallback>,
    start_stop_callback: Option<StartStopCallback>,
    controller: Controller,
    clock: Clock,
    rt_session_handler: Option<RtSessionStateHandler>,
    last_is_playing_for_callback: bool,
}

impl BasicLink {
    pub async fn new(bpm: f64) -> Self {
        // Only set up tracing if not already set up
        let _ = tracing_subscriber::fmt::try_init();

        let clock = Clock::default();

        let controller = Controller::new(tempo::Tempo::new(bpm), clock).await;

        Self {
            peer_count_callback: None,
            tempo_callback: None,
            start_stop_callback: None,
            controller,
            clock,
            rt_session_handler: None,
            last_is_playing_for_callback: false,
        }
    }
}

impl BasicLink {
    pub async fn enable(&mut self) {
        self.controller.enable().await;
    }

    pub async fn disable(&mut self) {
        self.controller.disable().await;
    }

    pub fn is_enabled(&self) -> bool {
        self.controller.is_enabled()
    }

    pub fn is_start_stop_sync_enabled(&self) -> bool {
        self.controller.is_start_stop_sync_enabled()
    }

    pub fn enable_start_stop_sync(&mut self, enable: bool) {
        self.controller.enable_start_stop_sync(enable);
    }

    pub fn num_peers(&self) -> usize {
        self.controller.num_peers()
    }

    pub fn set_num_peers_callback<F>(&mut self, callback: F)
    where
        F: Fn(usize) + Send + 'static,
    {
        self.peer_count_callback = Some(Arc::new(Mutex::new(Box::new(callback))));

        // Trigger initial callback with current peer count
        let current_count = self.num_peers();
        if let Some(ref callback) = self.peer_count_callback {
            if let Ok(callback) = callback.try_lock() {
                callback(current_count);
            }
        }
    }

    pub fn set_tempo_callback<F>(&mut self, callback: F)
    where
        F: Fn(f64) + Send + 'static,
    {
        self.tempo_callback = Some(Arc::new(Mutex::new(Box::new(callback))));

        // Trigger initial callback with current tempo
        if let Ok(client_state) = self.controller.client_state.try_lock() {
            if let Some(ref callback) = self.tempo_callback {
                if let Ok(callback) = callback.try_lock() {
                    callback(client_state.timeline.tempo.bpm());
                }
            }
        }
    }

    pub fn set_start_stop_callback<F>(&mut self, callback: F)
    where
        F: Fn(bool) + Send + 'static,
    {
        self.start_stop_callback = Some(Arc::new(Mutex::new(Box::new(callback))));

        // Update our cached playing state and trigger initial callback
        if let Ok(client_state) = self.controller.client_state.try_lock() {
            self.last_is_playing_for_callback = client_state.start_stop_state.is_playing;
            if let Some(ref callback) = self.start_stop_callback {
                if let Ok(callback) = callback.try_lock() {
                    callback(self.last_is_playing_for_callback);
                }
            }
        }
    }

    pub fn clock(&self) -> Clock {
        self.clock
    }

    pub fn capture_audio_session_state(&mut self) -> SessionState {
        // Initialize rt_session_handler if not already done
        if self.rt_session_handler.is_none() {
            if let Ok(client_state_guard) = self.controller.client_state.try_lock() {
                let client_state = *client_state_guard;
                self.rt_session_handler = Some(RtSessionStateHandler::new(
                    client_state,
                    controller::LOCAL_MOD_GRACE_PERIOD,
                ));
            } else {
                // If we can't get the lock, return a default state
                return SessionState::default();
            }
        }

        // For real-time access, we use the rt_session_handler
        if let Some(ref handler) = self.rt_session_handler {
            let client_state = handler.get_rt_client_state(self.clock.micros());
            to_session_state(&client_state, self.num_peers() > 0)
        } else {
            // Fallback to non-realtime access
            if let Ok(client_state_guard) = self.controller.client_state.try_lock() {
                to_session_state(&client_state_guard, self.num_peers() > 0)
            } else {
                SessionState::default()
            }
        }
    }

    pub fn commit_audio_session_state(&mut self, state: SessionState) {
        let current_time = self.clock.micros();
        let is_enabled = self.is_enabled();

        let incoming_state =
            to_incoming_client_state(&state.state, &state.original_state, current_time);

        // Use real-time handler if available
        if let Some(ref mut handler) = self.rt_session_handler {
            handler.update_rt_client_state(incoming_state, current_time, is_enabled);

            // Process any pending updates to sync with the main controller
            if let Some(processed_state) = handler.process_pending_updates() {
                // This should be done asynchronously in a real implementation
                // For now, we'll update the controller state directly
                if let Ok(mut client_state) = self.controller.client_state.try_lock() {
                    if let Some(timeline) = processed_state.timeline {
                        client_state.timeline = timeline;
                    }
                    if let Some(start_stop_state) = processed_state.start_stop_state {
                        client_state.start_stop_state = start_stop_state;
                    }
                }
            }
        } else {
            // Fallback to the original non-realtime method
            if let Ok(mut client_state) = self.controller.client_state.try_lock() {
                if let Some(timeline) = incoming_state.timeline {
                    client_state.timeline = timeline;
                }
                if let Some(start_stop_state) = incoming_state.start_stop_state {
                    client_state.start_stop_state = start_stop_state;
                }
            }
        }
    }

    pub fn capture_app_session_state(&self) -> SessionState {
        if let Ok(client_state_guard) = self.controller.client_state.try_lock() {
            to_session_state(&client_state_guard, self.num_peers() > 0)
        } else {
            // Return a default state if we can't get the lock
            SessionState::default()
        }
    }

    pub async fn commit_app_session_state(&mut self, state: SessionState) {
        let incoming_state =
            to_incoming_client_state(&state.state, &state.original_state, self.clock.micros());

        // Check if start/stop state changed for callback
        let should_invoke_callback = if let Some(start_stop_state) = incoming_state.start_stop_state
        {
            let changed = self.last_is_playing_for_callback != start_stop_state.is_playing;
            if changed {
                self.last_is_playing_for_callback = start_stop_state.is_playing;
            }
            changed
        } else {
            false
        };

        // Update the controller state
        self.controller.set_state(incoming_state).await;

        // Invoke start/stop callback if needed
        if should_invoke_callback {
            if let Some(ref callback) = self.start_stop_callback {
                if let Ok(callback) = callback.try_lock() {
                    callback(self.last_is_playing_for_callback);
                }
            }
        }

        // Check for tempo changes and invoke callback
        if let Some(ref callback) = self.tempo_callback {
            if let Ok(client_state) = self.controller.client_state.try_lock() {
                if let Ok(callback) = callback.try_lock() {
                    callback(client_state.timeline.tempo.bpm());
                }
            }
        }
    }
}

pub fn to_session_state(state: &ClientState, _is_connected: bool) -> SessionState {
    SessionState::new(
        ApiState {
            timeline: state.timeline,
            start_stop_state: ApiStartStopState {
                is_playing: state.start_stop_state.is_playing,
                time: state.start_stop_state.time,
            },
        },
        true, // Always respect quantum like C++ implementation
    )
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct IncomingClientState {
    pub timeline: Option<Timeline>,
    pub start_stop_state: Option<ClientStartStopState>,
    pub timeline_timestamp: Duration,
}

pub fn to_incoming_client_state(
    state: &ApiState,
    original_state: &ApiState,
    timestamp: Duration,
) -> IncomingClientState {
    let timeline = if original_state.timeline != state.timeline {
        Some(state.timeline)
    } else {
        None
    };

    let start_stop_state = if original_state.start_stop_state != state.start_stop_state {
        Some(ClientStartStopState {
            is_playing: state.start_stop_state.is_playing,
            time: state.start_stop_state.time,
            timestamp,
        })
    } else {
        None
    };

    IncomingClientState {
        timeline,
        start_stop_state,
        timeline_timestamp: timestamp,
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct ApiState {
    timeline: Timeline,
    start_stop_state: ApiStartStopState,
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
struct ApiStartStopState {
    is_playing: bool,
    time: Duration,
}

impl Default for ApiStartStopState {
    fn default() -> Self {
        Self {
            is_playing: false,
            time: Duration::zero(),
        }
    }
}

impl ApiStartStopState {
    fn new(is_playing: bool, time: Duration) -> Self {
        Self { is_playing, time }
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct SessionState {
    original_state: ApiState,
    state: ApiState,
    respect_quantum: bool,
}

impl SessionState {
    pub fn new(state: ApiState, respect_quantum: bool) -> Self {
        Self {
            original_state: state,
            state,
            respect_quantum,
        }
    }

    pub fn tempo(&self) -> f64 {
        self.state.timeline.tempo.bpm()
    }

    pub fn set_tempo(&mut self, bpm: f64, at_time: Duration) {
        let desired_tl = clamp_tempo(Timeline {
            tempo: Tempo::new(bpm),
            beat_origin: self.state.timeline.to_beats(at_time),
            time_origin: at_time,
        });
        self.state.timeline.tempo = desired_tl.tempo;
        self.state.timeline.time_origin = desired_tl.from_beats(self.state.timeline.beat_origin);
    }

    pub fn beat_at_time(&self, time: Duration, quantum: f64) -> f64 {
        to_phase_encoded_beats(&self.state.timeline, time, Beats::new(quantum)).floating()
    }

    pub fn phase_at_time(&self, time: Duration, quantum: f64) -> f64 {
        phase(
            Beats::new(self.beat_at_time(time, quantum)),
            Beats::new(quantum),
        )
        .floating()
    }

    pub fn time_at_beat(&self, beat: f64, quantum: f64) -> Duration {
        from_phase_encoded_beats(&self.state.timeline, Beats::new(beat), Beats::new(quantum))
    }

    pub fn request_beat_at_time(&mut self, beat: f64, time: Duration, quantum: f64) {
        let time = if self.respect_quantum {
            self.time_at_beat(
                phase::next_phase_match(
                    Beats::new(self.beat_at_time(time, quantum)),
                    Beats::new(beat),
                    Beats::new(quantum),
                )
                .floating(),
                quantum,
            )
        } else {
            time
        };
        self.force_beat_at_time(beat, time, quantum);
    }

    pub fn force_beat_at_time(&mut self, beat: f64, time: Duration, quantum: f64) {
        force_beat_at_time_impl(
            &mut self.state.timeline,
            Beats::new(beat),
            time,
            Beats::new(quantum),
        );

        // Due to quantization errors the resulting BeatTime at 'time' after forcing can be
        // bigger than 'beat' which then violates intended behavior of the API and can lead
        // i.e. to missing a downbeat. Thus we have to shift the timeline forwards.
        if self.beat_at_time(time, quantum) > beat {
            force_beat_at_time_impl(
                &mut self.state.timeline,
                Beats::new(beat),
                time + Duration::microseconds(1),
                Beats::new(quantum),
            );
        }
    }

    pub fn set_is_playing(&mut self, is_playing: bool, time: Duration) {
        self.state.start_stop_state = ApiStartStopState::new(is_playing, time);
    }

    pub fn is_playing(&self) -> bool {
        self.state.start_stop_state.is_playing
    }

    pub fn time_for_is_playing(&self) -> Duration {
        self.state.start_stop_state.time
    }

    pub fn request_beat_at_start_playing_time(&mut self, beat: f64, quantum: f64) {
        if self.is_playing() {
            self.request_beat_at_time(beat, self.state.start_stop_state.time, quantum);
        }
    }

    pub fn set_is_playing_and_request_beat_at_time(
        &mut self,
        is_playing: bool,
        time: Duration,
        beat: f64,
        quantum: f64,
    ) {
        self.state.start_stop_state = ApiStartStopState::new(is_playing, time);
        self.request_beat_at_start_playing_time(beat, quantum);
    }
}

#[cfg(test)]
mod tests {
    use tracing::info;

    use super::*;

    #[tokio::test]
    async fn test_basic_link() {
        let _ = tracing_subscriber::fmt::try_init();

        let bpm = 140.0;
        let mut link = BasicLink::new(bpm).await;

        info!("initializing basic link at {} bpm", bpm);

        // Test basic initialization (Link starts disabled)
        assert!(!link.is_enabled());
        assert_eq!(link.num_peers(), 0);
        assert!(!link.is_start_stop_sync_enabled());

        // Test start/stop sync without enabling Link (to avoid blocking network operations)
        link.enable_start_stop_sync(true);
        assert!(link.is_start_stop_sync_enabled());

        link.enable_start_stop_sync(false);
        assert!(!link.is_start_stop_sync_enabled());

        // Test clock access
        let _clock = link.clock();

        // Test callback setters (they should not panic)
        link.set_num_peers_callback(|count| {
            println!("Peer count: {}", count);
        });

        link.set_tempo_callback(|bpm| {
            println!("Tempo changed: {}", bpm);
        });

        link.set_start_stop_callback(|is_playing| {
            println!("Playing state: {}", is_playing);
        });

        info!("test_basic_link completed successfully - Link functionality validated without network operations");
    }

    #[tokio::test]
    async fn test_peer_count_reset_on_disable() {
        let _ = tracing_subscriber::fmt::try_init();

        let bpm = 120.0;
        let mut link = BasicLink::new(bpm).await;

        info!("testing peer count reset when Link is disabled");

        // Initially disabled, should have 0 peers
        assert!(!link.is_enabled());
        assert_eq!(link.num_peers(), 0);

        // Enable Link briefly
        let enable_result =
            tokio::time::timeout(std::time::Duration::from_millis(100), link.enable()).await;
        let _ = enable_result; // May timeout, that's ok

        // Now disable Link
        link.disable().await;

        // After disabling, peer count should be reset to 0
        assert!(!link.is_enabled());
        assert_eq!(
            link.num_peers(),
            0,
            "Peer count should be reset to 0 when Link is disabled"
        );

        info!("test_peer_count_reset_on_disable completed - peer count correctly resets to 0 when disabled");
    }
}