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
use jack_sys as j;
use std::fmt::Debug;
use std::sync::Arc;
use std::{ffi, fmt, ptr};
use crate::client::common::{sleep_on_test, CREATE_OR_DESTROY_CLIENT_MUTEX};
use crate::jack_utils::collect_strs;
use crate::properties::PropertyChangeHandler;
use crate::transport::Transport;
use crate::{
AsyncClient, ClientOptions, ClientStatus, Error, Frames, NotificationHandler, Port, PortFlags,
PortId, PortSpec, ProcessHandler, Time, Unowned,
};
pub type InternalClientID = j::jack_intclient_t;
pub struct Client(
*mut j::jack_client_t,
Arc<()>,
Option<Box<dyn PropertyChangeHandler>>,
);
unsafe impl Send for Client {}
unsafe impl Sync for Client {}
impl Client {
pub fn new(client_name: &str, options: ClientOptions) -> Result<(Self, ClientStatus), Error> {
let _m = CREATE_OR_DESTROY_CLIENT_MUTEX.lock().unwrap();
#[cfg(feature = "dynamic_loading")]
if let Err(err) = jack_sys::library() {
return Err(Error::LibraryError(err.to_string()));
}
unsafe {
jack_sys::jack_set_error_function(Some(error_handler));
jack_sys::jack_set_info_function(Some(info_handler));
}
sleep_on_test();
let mut status_bits = 0;
let client = unsafe {
let client_name = ffi::CString::new(client_name).unwrap();
j::jack_client_open(client_name.as_ptr(), options.bits(), &mut status_bits)
};
sleep_on_test();
let status = ClientStatus::from_bits(status_bits).unwrap_or_else(ClientStatus::empty);
if client.is_null() {
Err(Error::ClientError(status))
} else {
Ok((Client(client, Arc::default(), None), status))
}
}
pub fn activate_async<N, P>(
self,
notification_handler: N,
process_handler: P,
) -> Result<AsyncClient<N, P>, Error>
where
N: 'static + Send + Sync + NotificationHandler,
P: 'static + Send + ProcessHandler,
{
AsyncClient::new(self, notification_handler, process_handler)
}
pub fn sample_rate(&self) -> usize {
let srate = unsafe { j::jack_get_sample_rate(self.raw()) };
srate as usize
}
pub fn cpu_load(&self) -> f32 {
unsafe { j::jack_cpu_load(self.raw()) }
}
pub fn name(&self) -> &str {
unsafe {
let ptr = j::jack_get_client_name(self.raw());
let cstr = ffi::CStr::from_ptr(ptr);
cstr.to_str().unwrap()
}
}
pub fn buffer_size(&self) -> Frames {
unsafe { j::jack_get_buffer_size(self.raw()) }
}
pub fn set_buffer_size(&self, n_frames: Frames) -> Result<(), Error> {
let res = unsafe { j::jack_set_buffer_size(self.raw(), n_frames) };
match res {
0 => Ok(()),
_ => Err(Error::SetBufferSizeError),
}
}
#[cfg(feature = "metadata")]
pub fn uuid(&self) -> j::jack_uuid_t {
unsafe {
let mut uuid: j::jack_uuid_t = Default::default();
let uuid_s = j::jack_client_get_uuid(self.raw());
assert!(!uuid_s.is_null());
assert_eq!(0, j::jack_uuid_parse(uuid_s, &mut uuid));
j::jack_free(uuid_s as _);
uuid
}
}
#[cfg(feature = "metadata")]
pub fn uuid_of_client_by_name(&self, name: &str) -> Option<jack_sys::jack_uuid_t> {
Self::uuid_of_client_by_name_raw(self.raw(), name)
}
#[cfg(feature = "metadata")]
pub(crate) fn uuid_of_client_by_name_raw(
raw: *mut jack_sys::jack_client_t,
name: &str,
) -> Option<jack_sys::jack_uuid_t> {
let name = ffi::CString::new(name).unwrap();
let mut uuid: jack_sys::jack_uuid_t = Default::default();
unsafe {
let uuid_s = jack_sys::jack_get_uuid_for_client_name(raw, name.as_ptr());
if uuid_s.is_null() {
return None;
}
assert_eq!(0, jack_sys::jack_uuid_parse(uuid_s, &mut uuid));
jack_sys::jack_free(uuid_s as _);
}
Some(uuid)
}
pub fn uuid_string(&self) -> String {
unsafe {
let uuid_s = j::jack_client_get_uuid(self.raw());
assert!(!uuid_s.is_null());
let uuid = ffi::CStr::from_ptr(uuid_s)
.to_str()
.expect("uuid is valid string")
.to_string();
j::jack_free(uuid_s as _);
uuid
}
}
unsafe fn name_by_uuid_raw(&self, uuid: *const ::libc::c_char) -> Option<String> {
let name_ptr = j::jack_get_client_name_by_uuid(self.raw(), uuid);
if name_ptr.is_null() {
None
} else {
Some(
ffi::CStr::from_ptr(name_ptr)
.to_str()
.expect("name convert to a valid str")
.to_string(),
)
}
}
#[cfg(feature = "metadata")]
pub fn name_by_uuid(&self, uuid: j::jack_uuid_t) -> Option<String> {
let mut uuid_s = ['\0' as _; 37]; unsafe {
j::jack_uuid_unparse(uuid, uuid_s.as_mut_ptr());
self.name_by_uuid_raw(uuid_s.as_ptr())
}
}
pub fn name_by_uuid_str(&self, uuid: &str) -> Option<String> {
let uuid = ffi::CString::new(uuid).unwrap();
unsafe { self.name_by_uuid_raw(uuid.as_ptr()) }
}
pub fn ports(
&self,
port_name_pattern: Option<&str>,
type_name_pattern: Option<&str>,
flags: PortFlags,
) -> Vec<String> {
let port_name_pattern_cstr = ffi::CString::new(port_name_pattern.unwrap_or("")).unwrap();
let type_name_pattern_cstr = ffi::CString::new(type_name_pattern.unwrap_or("")).unwrap();
let flags = libc::c_ulong::from(flags.bits());
unsafe {
let ports = j::jack_get_ports(
self.raw(),
port_name_pattern_cstr.as_ptr(),
type_name_pattern_cstr.as_ptr(),
flags,
);
collect_strs(ports)
}
}
pub fn register_port<PS: PortSpec>(
&self,
port_name: &str,
port_spec: PS,
) -> Result<Port<PS>, Error> {
let port_name_c = ffi::CString::new(port_name).unwrap();
let port_type_c = ffi::CString::new(port_spec.jack_port_type()).unwrap();
let port_flags = port_spec.jack_flags().bits();
let buffer_size = port_spec.jack_buffer_size();
let pp = unsafe {
j::jack_port_register(
self.raw(),
port_name_c.as_ptr(),
port_type_c.as_ptr(),
libc::c_ulong::from(port_flags),
buffer_size,
)
};
if pp.is_null() {
Err(Error::PortRegistrationError(port_name.to_string()))
} else {
Ok(unsafe { Port::from_raw(port_spec, self.raw(), pp, Arc::downgrade(&self.1)) })
}
}
pub fn port_by_id(&self, port_id: PortId) -> Option<Port<Unowned>> {
let pp = unsafe { j::jack_port_by_id(self.raw(), port_id) };
if pp.is_null() {
None
} else {
Some(unsafe { Port::from_raw(Unowned {}, self.raw(), pp, Arc::downgrade(&self.1)) })
}
}
pub fn port_by_name(&self, port_name: &str) -> Option<Port<Unowned>> {
let port_name = ffi::CString::new(port_name).unwrap();
let pp = unsafe { j::jack_port_by_name(self.raw(), port_name.as_ptr()) };
if pp.is_null() {
None
} else {
Some(unsafe { Port::from_raw(Unowned {}, self.raw(), pp, Arc::downgrade(&self.1)) })
}
}
pub fn load_internal_client(
&self,
client_name: &str,
client_bin_name: &str,
client_args: &str,
) -> Result<InternalClientID, Error> {
let ffi_client_name = ffi::CString::new(client_name).unwrap();
let ffi_client_bin = ffi::CString::new(client_bin_name).unwrap();
let ffi_client_args = ffi::CString::new(client_args).unwrap();
let mut status_bits = 0;
let options: j::Enum_JackOptions = j::JackLoadName | j::JackLoadInit;
let intclient = unsafe {
j::jack_internal_client_load(
self.raw(),
ffi_client_name.as_ptr(),
options,
&mut status_bits,
ffi_client_bin.as_ptr(),
ffi_client_args.as_ptr(),
)
};
match intclient {
Some(0) => {
let status =
ClientStatus::from_bits(status_bits).unwrap_or_else(ClientStatus::empty);
Err(Error::ClientError(status))
}
Some(i) => Ok(i),
None => Err(Error::WeakFunctionNotFound("jack_internal_client_load")),
}
}
pub fn unload_internal_client(&self, client: InternalClientID) -> Result<(), Error> {
let status = unsafe {
let status = match j::jack_internal_client_unload(self.raw(), client) {
Some(s) => s,
None => return Err(Error::WeakFunctionNotFound("jack_internal_client_unload")),
};
ClientStatus::from_bits_unchecked(status)
};
if status.is_empty() {
Ok(())
} else {
Err(Error::ClientError(status))
}
}
pub fn frames_since_cycle_start(&self) -> Frames {
unsafe { j::jack_frames_since_cycle_start(self.raw()) }
}
pub fn frame_time(&self) -> Frames {
unsafe { j::jack_frame_time(self.raw()) }
}
pub fn frames_to_time(&self, n_frames: Frames) -> Time {
unsafe { j::jack_frames_to_time(self.raw(), n_frames) }
}
pub fn time_to_frames(&self, t: Time) -> Frames {
unsafe { j::jack_time_to_frames(self.raw(), t) }
}
pub fn is_mine<PS: PortSpec>(&self, port: &Port<PS>) -> bool {
matches!(unsafe { j::jack_port_is_mine(self.raw(), port.raw()) }, 1)
}
pub fn request_monitor_by_name(
&self,
port_name: &str,
enable_monitor: bool,
) -> Result<(), Error> {
let port_name_cstr = ffi::CString::new(port_name).unwrap();
let res = unsafe {
j::jack_port_request_monitor_by_name(
self.raw(),
port_name_cstr.as_ptr(),
i32::from(enable_monitor),
)
};
match res {
0 => Ok(()),
_ => Err(Error::PortMonitorError),
}
}
pub fn connect_ports_by_name(
&self,
source_port: &str,
destination_port: &str,
) -> Result<(), Error> {
let source_cstr = ffi::CString::new(source_port).unwrap();
let destination_cstr = ffi::CString::new(destination_port).unwrap();
let res =
unsafe { j::jack_connect(self.raw(), source_cstr.as_ptr(), destination_cstr.as_ptr()) };
match res {
0 => Ok(()),
::libc::EEXIST => Err(Error::PortAlreadyConnected(
source_port.to_string(),
destination_port.to_string(),
)),
_ => Err(Error::PortConnectionError(
source_port.to_string(),
destination_port.to_string(),
)),
}
}
pub fn connect_ports<A: PortSpec, B: PortSpec>(
&self,
source_port: &Port<A>,
destination_port: &Port<B>,
) -> Result<(), Error> {
let _m = CREATE_OR_DESTROY_CLIENT_MUTEX.lock().unwrap();
self.connect_ports_by_name(&source_port.name()?, &destination_port.name()?)
}
pub fn disconnect<PS>(&self, port: &Port<PS>) -> Result<(), Error> {
let res = unsafe { j::jack_port_disconnect(self.raw(), port.raw()) };
match res {
0 => Ok(()),
_ => Err(Error::PortDisconnectionError),
}
}
pub fn unregister_port<PS>(&self, port: Port<PS>) -> Result<(), Error> {
let res = unsafe { j::jack_port_unregister(self.raw(), port.raw()) };
match res {
0 => Ok(()),
_ => Err(Error::PortDisconnectionError),
}
}
pub fn disconnect_ports<A: PortSpec, B: PortSpec>(
&self,
source: &Port<A>,
destination: &Port<B>,
) -> Result<(), Error> {
self.disconnect_ports_by_name(&source.name()?, &destination.name()?)
}
pub fn disconnect_ports_by_name(
&self,
source_port: &str,
destination_port: &str,
) -> Result<(), Error> {
let source_port = ffi::CString::new(source_port).unwrap();
let destination_port = ffi::CString::new(destination_port).unwrap();
let res = unsafe {
j::jack_disconnect(self.raw(), source_port.as_ptr(), destination_port.as_ptr())
};
match res {
0 => Ok(()),
_ => Err(Error::PortDisconnectionError),
}
}
pub unsafe fn type_buffer_size(&self, port_type: &str) -> usize {
let port_type = ffi::CString::new(port_type).unwrap();
j::jack_port_type_get_buffer_size(self.raw(), port_type.as_ptr())
}
#[inline(always)]
pub fn raw(&self) -> *mut j::jack_client_t {
self.0
}
pub unsafe fn from_raw(p: *mut j::jack_client_t) -> Self {
Client(p, Arc::default(), None)
}
pub fn transport(&self) -> Transport {
Transport {
client_ptr: self.0,
client_life: Arc::downgrade(&self.1),
}
}
#[cfg(feature = "metadata")]
pub fn register_property_change_handler<H: PropertyChangeHandler + 'static>(
&mut self,
handler: H,
) -> Result<(), Error> {
assert!(self.2.is_none());
let handler = Box::into_raw(Box::new(handler));
unsafe {
self.2 = Some(Box::from_raw(handler));
if j::jack_set_property_change_callback(
self.raw(),
Some(crate::properties::property_changed::<H>),
std::mem::transmute::<_, _>(handler),
) == 0
{
Ok(())
} else {
Err(Error::UnknownError)
}
}
}
}
impl Drop for Client {
fn drop(&mut self) {
let _m = CREATE_OR_DESTROY_CLIENT_MUTEX.lock().unwrap();
debug_assert!(!self.raw().is_null()); sleep_on_test();
let res = unsafe { j::jack_client_close(self.raw()) }; sleep_on_test();
assert_eq!(res, 0);
self.0 = ptr::null_mut();
}
}
impl Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Client")
.field("name", &self.name())
.field("sample_rate", &self.sample_rate())
.field("buffer_size", &self.buffer_size())
.field("cpu_usage", &format!("{}%", self.cpu_load() / 100.0))
.field("frame_time", &self.frame_time())
.finish()
}
}
#[derive(Debug)]
pub struct ProcessScope {
client_ptr: *mut j::jack_client_t,
n_frames: Frames,
}
impl ProcessScope {
#[inline(always)]
pub fn n_frames(&self) -> Frames {
self.n_frames
}
pub fn last_frame_time(&self) -> Frames {
unsafe { j::jack_last_frame_time(self.client_ptr()) }
}
pub fn frames_since_cycle_start(&self) -> Frames {
unsafe { j::jack_frames_since_cycle_start(self.client_ptr()) }
}
pub fn cycle_times(&self) -> Result<CycleTimes, Error> {
let mut current_frames: Frames = 0;
let mut current_usecs: Time = 0;
let mut next_usecs: Time = 0;
let mut period_usecs: libc::c_float = 0.0;
let res = unsafe {
(jack_sys::jack_get_cycle_times)(
self.client_ptr(),
&mut current_frames,
&mut current_usecs,
&mut next_usecs,
&mut period_usecs,
)
};
match res {
None => Err(Error::WeakFunctionNotFound("jack_get_cycle_times")),
Some(0) => Ok(CycleTimes {
current_frames,
current_usecs,
next_usecs,
period_usecs,
}),
_ => Err(Error::TimeError),
}
}
#[inline(always)]
pub fn client_ptr(&self) -> *mut j::jack_client_t {
self.client_ptr
}
pub unsafe fn from_raw(n_frames: Frames, client_ptr: *mut j::jack_client_t) -> Self {
ProcessScope {
n_frames,
client_ptr,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CycleTimes {
pub current_frames: Frames,
pub current_usecs: Time,
pub next_usecs: Time,
pub period_usecs: libc::c_float,
}
unsafe extern "C" fn error_handler(msg: *const libc::c_char) {
match std::ffi::CStr::from_ptr(msg).to_str() {
Ok(msg) => log::error!("{}", msg),
Err(err) => log::error!("failed to parse JACK error: {:?}", err),
}
}
unsafe extern "C" fn info_handler(msg: *const libc::c_char) {
match std::ffi::CStr::from_ptr(msg).to_str() {
Ok(msg) => log::info!("{}", msg),
Err(err) => log::error!("failed to parse JACK error: {:?}", err),
}
}