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
use jack_sys as j;
use libc;
use std::{ffi, fmt, ptr};
use std::sync::Arc;
use AsyncClient;
use ClientOptions;
use ClientStatus;
use Error;
use Frames;
use NotificationHandler;
use Port;
use PortFlags;
use PortId;
use PortSpec;
use ProcessHandler;
use Time;
use Unowned;
use client::common::{sleep_on_test, CREATE_OR_DESTROY_CLIENT_MUTEX};
use jack_utils::collect_strs;
pub struct Client(*mut j::jack_client_t, Arc<()>);
unsafe impl Send for Client {}
impl Client {
pub fn new(client_name: &str, options: ClientOptions) -> Result<(Self, ClientStatus), Error> {
let _ = *CREATE_OR_DESTROY_CLIENT_MUTEX.lock().unwrap();
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(ClientStatus::empty());
if client.is_null() {
Err(Error::ClientError(status))
} else {
Ok((Client(client, Arc::default()), status))
}
}
pub fn activate_async<N, P>(
self,
notification_handler: N,
process_handler: P,
) -> Result<AsyncClient<N, P>, Error>
where
N: NotificationHandler,
P: 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 {
let load = unsafe { j::jack_cpu_load(self.raw()) };
load as f32
}
pub fn name<'a>(&'a self) -> &'a 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),
}
}
pub fn ports(
&self,
port_name_pattern: Option<&str>,
type_name_pattern: Option<&str>,
flags: PortFlags,
) -> Vec<String> {
let pnp = ffi::CString::new(port_name_pattern.unwrap_or("")).unwrap();
let tnp = ffi::CString::new(type_name_pattern.unwrap_or("")).unwrap();
let flags = flags.bits() as libc::c_ulong;
unsafe {
let ports = j::jack_get_ports(self.raw(), pnp.as_ptr(), tnp.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(),
port_flags as libc::c_ulong,
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 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 {
match unsafe { j::jack_port_is_mine(self.raw(), port.raw()) } {
1 => true,
_ => false,
}
}
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(),
if enable_monitor { 1 } else { 0 },
)
};
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 _ = *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();
let n = j::jack_port_type_get_buffer_size(self.raw(), port_type.as_ptr());
n
}
#[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())
}
}
impl Drop for Client {
fn drop(&mut self) {
let _ = *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 fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{:?}", ClientInfo::from(self))
}
}
#[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 jack_get_cycle_times = {
match *j::jack_get_cycle_times {
Some(f) => f,
None => return Err(Error::WeakFunctionNotFound),
}
};
let res = unsafe {
(jack_get_cycle_times)(
self.client_ptr(),
&mut current_frames,
&mut current_usecs,
&mut next_usecs,
&mut period_usecs,
)
};
match res {
0 => Ok(CycleTimes {
current_frames: current_frames,
current_usecs: current_usecs,
next_usecs: next_usecs,
period_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: n_frames,
client_ptr: 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,
}
#[derive(Debug)]
struct ClientInfo {
name: String,
sample_rate: usize,
buffer_size: u32,
cpu_usage: String,
ports: Vec<String>,
frame_time: Frames,
}
impl<'a> From<&'a Client> for ClientInfo {
fn from(c: &Client) -> ClientInfo {
ClientInfo {
name: c.name().into(),
sample_rate: c.sample_rate(),
buffer_size: c.buffer_size(),
cpu_usage: format!("{}%", c.cpu_load() / 100.0),
ports: c.ports(None, None, PortFlags::empty()),
frame_time: c.frame_time(),
}
}
}