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
#[macro_use]
extern crate bitflags;
extern crate libc;
extern crate jack_sys;
extern crate failure;
#[macro_use]
extern crate failure_derive;
#[macro_use]
extern crate lazy_static;

static JACK_DEFAULT_AUDIO_TYPE: &'static [u8] = b"32 bit float mono audio\0";
pub mod errors;
pub mod handler;
pub mod port;

#[cfg(test)]
mod tests;

use std::ffi::{CString, CStr};
use std::marker::PhantomData;
use errors::JackError;
pub use errors::JackResult;
pub use handler::{JackCallbackContext, JackControl, JackHandler, JackLoggingHandler, set_logging_handler};
pub use port::JackPort;
pub use jack_sys::*;

pub type JackNFrames = jack_nframes_t;
pub type JackPortPtr = *mut jack_port_t;
bitflags! {
    /// Status of an operation.
    ///
    /// See `STATUS_*` constants for possible values.
    pub flags JackStatus: jack_status_t {
        /// Overall operation failed.
        const STATUS_FAILURE = jack_sys::JackFailure,
        /// The operation contained an invalid or unsupported option.
        const STATUS_INVALID_OPTION = jack_sys::JackInvalidOption,
        /// The desired client name was not unique. With the JackUseExactName option this
        /// situation is fatal. Otherwise, the name was modified by appending a dash and a
        /// two-digit number in the range "-01" to "-99". The jack_get_client_name()
        /// function will return the exact string that was used. If the specified
        /// client_name plus these extra characters would be too long, the open fails
        /// instead.
        const STATUS_NAME_NOT_UNIQUE = jack_sys::JackNameNotUnique,
        /// The JACK server was started as a result of this operation. Otherwise,
        /// it was running already. In either case the caller is now connected to jackd,
        /// so there is no race condition. When the server shuts down, the client will find
        /// out.
        const STATUS_SERVER_STARTED = jack_sys::JackServerStarted,
        /// Unable to connect to the JACK server.
        const STATUS_SERVER_FAILED = jack_sys::JackServerFailed,
        /// Communication error with the JACK server.
        const STATUS_SERVER_ERROR = jack_sys::JackServerError,
        /// Requested client does not exist.
        const STATUS_NO_SUCH_CLIENT = jack_sys::JackNoSuchClient,
        /// Unable to load internal client.
        const STATUS_LOAD_FAILURE = jack_sys::JackLoadFailure,
        /// Unable to initialise client.
        const STATUS_INIT_FAILURE = jack_sys::JackInitFailure,
        /// Unable to access shared memory.
        const STATUS_SHM_FAILURE = jack_sys::JackShmFailure,
        /// Client's protocol version does not match.
        const STATUS_VERSION_ERROR = jack_sys::JackShmFailure
    }
}
bitflags! {
    /// A port has a set of flags that are formed by OR-ing together the desired values
    /// from the consts `PORT_*`. The flags "JackPortIsInput" and "JackPortIsOutput" are
    /// mutually exclusive and it is an error to use them both.
    pub flags JackPortFlags: libc::c_ulong {
        /// This port can receive data.
        const PORT_IS_INPUT = JackPortIsInput as libc::c_ulong,
        /// Data can be read from this port.
        const PORT_IS_OUTPUT = JackPortIsOutput as libc::c_ulong,
        /// The port corresponds to some kind of physical I/O connector.
        const PORT_IS_PHYSICAL = JackPortIsPhysical as libc::c_ulong,
        /// A call to jack_port_request_monitor() makes sense.
        ///
        /// Precisely what this means is dependent on the client. A typical result of it
        /// being called with TRUE as the second argument is that data that would be
        /// available from an output port (with JackPortIsPhysical set) is sent to a
        /// physical output connector as well, so that it can be heard/seen/whatever.
        ///
        /// Clients that do not control physical interfaces should never create ports with
        /// this bit set.
        const PORT_CAN_MONITOR = JackPortCanMonitor as libc::c_ulong,
        /// For an input port: the data received by this port will not be passed on or
        /// made available at any other port.
        ///
        /// For an output port: the data available at the port does not originate from any
        /// other port.
        ///
        /// Audio synthesizers, I/O hardware interface clients, HDR systems are examples
        /// of clients that would set this flag for their ports.
        const PORT_IS_TERMINAL = JackPortIsTerminal as libc::c_ulong
    }
}
bitflags! {
    /// Options for opening a connection to JACK, formed by OR-ing together desired values
    /// from the consts `OPEN_*`.
    pub flags JackOpenOptions: libc::c_uint {
        /// Do not automatically start the JACK server when it is not already running.
        /// This option is always selected if $JACK_NO_START_SERVER is defined in the
        /// calling process environment.
        const OPEN_NO_START_SERVER = JackNoStartServer,
        /// Use the exact client name requested. Otherwise, JACK automatically generates
        /// a unique one, if needed.
        const OPEN_USE_EXACT_NAME = JackUseExactName,
    }
}
/// Type argument for deactivated connections.
pub struct Deactivated;
/// Type argument for activated connections.
pub struct Activated;
/// A connection to a JACK server (known as a "client" in the JACK docs).
///
/// Exists in two types: `JackConnection<Activated>` when `activate()` has been called
/// (i.e. audio is being processed), and `<Deactivated>` when this has not happened,
/// or `deactivate()` has been called.
pub struct JackConnection<T> {
    handle: *mut jack_client_t,
    sample_rate: u32,
    _phantom: PhantomData<T>
}

/// Helper function to convert Rust `&str`s to `CString`s.
fn str_to_cstr(st: &str) -> JackResult<CString> {
    Ok(CString::new(st).map_err(|_| JackError::NulError)?)
}

impl<T> JackConnection<T> {
    pub fn as_ptr(&self) -> *const jack_client_t {
        self.handle
    }
    /// Get the sample rate of the JACK server.
    pub fn sample_rate(&self) -> jack_nframes_t {
        self.sample_rate
    }
    /// Get the CPU load of the JACK server.
    pub fn cpu_load(&self) -> libc::c_float {
        unsafe {
            jack_cpu_load(self.handle)
        }
    }
    /// Get the buffer size passed to the `process()` callback.
    pub fn buffer_size(&self) -> jack_nframes_t {
        unsafe {
            jack_get_buffer_size(self.handle)
        }
    }
    /// Change the buffer size passed to the `process()` callback.
    ///
    /// This operation **stops the JACK engine process cycle**, then calls all registered
    /// bufsize_callback functions before restarting the process cycle. This will cause a
    /// gap in the audio flow, so it should only be done at appropriate stopping points.
    ///
    /// # Parameters
    ///
    /// - bufsize: new buffer size. Must be a power of two.
    ///
    /// # Errors
    ///
    /// - `NotPowerOfTwo`: if the new buffer size isn't a power of two
    /// - `UnknownErrorCode`
    pub fn set_buffer_size(&mut self, bufsize: jack_nframes_t) -> JackResult<()> {
        if bufsize.next_power_of_two() != bufsize {
            Err(JackError::NotPowerOfTwo)?
        }
        let code = unsafe {
            jack_set_buffer_size(self.handle, bufsize)
        };
        if code != 0 {
            Err(JackError::UnknownErrorCode { from: "set_buffer_size()", code: code })?
        }
        else {
            Ok(())
        }
    }
    unsafe fn activate_or_deactivate<X>(self, activate: bool) -> Result<JackConnection<X>, (Self, JackError)> {
        let code = {
            if activate {
                jack_activate(self.handle)
            }
            else {
                jack_deactivate(self.handle)
            }
        };
        if code != 0 {
            Err((self, JackError::UnknownErrorCode { from: "activate_or_deactivate()", code }))
        }
        else {
            Ok(::std::mem::transmute::<JackConnection<T>, JackConnection<X>>(self))
        }
    }
    fn connect_or_disconnect_ports(&mut self, from: &JackPort, to: &JackPort, conn: bool) -> JackResult<()> {
        if from.get_type()? != to.get_type()? {
            Err(JackError::InvalidPortType)?;
        }
        if !from.get_flags().contains(PORT_IS_OUTPUT) || !to.get_flags().contains(PORT_IS_INPUT) {
            Err(JackError::InvalidPortFlags)?;
        }
        let code = unsafe {
            if conn {
                jack_connect(self.handle, from.get_name_raw(false)?, to.get_name_raw(false)?)
            }
            else {
                jack_disconnect(self.handle, from.get_name_raw(false)?, to.get_name_raw(false)?)
            }
        };
        match code {
            libc::EEXIST => Ok(()),
            0 => Ok(()),
            _ => Err(JackError::UnknownErrorCode { from: "connect_or_disconnect_ports()", code: code })?
        }
    }
    /// Establish a connection between two ports.
    ///
    /// When a connection exists, data written to the source port will be available to be
    /// read at the destination port.
    ///
    /// # Preconditions
    ///
    /// - The port types must be identical.
    /// - The JackPortFlags of the source_port must include `PORT_IS_OUTPUT`.
    /// - The JackPortFlags of the destination_port must include `PORT_IS_INPUT`.
    ///
    /// # Errors
    ///
    /// - `InvalidPortType`: when the types are not identical
    /// - `InvalidPortFlags`: when the flags do not satisfy the preconditions above
    /// - `UnknownErrorCode`
    pub fn connect_ports(&mut self, from: &JackPort, to: &JackPort) -> JackResult<()> {
        self.connect_or_disconnect_ports(from, to, true)
    }
    /// Remove a connection between two ports.
    ///
    /// When a connection exists, data written to the source port will be available to be
    /// read at the destination port.
    ///
    /// # Preconditions
    ///
    /// - The port types must be identical.
    /// - The JackPortFlags of the source_port must include `PORT_IS_OUTPUT`.
    /// - The JackPortFlags of the destination_port must include `PORT_IS_INPUT`.
    ///
    /// # Errors
    ///
    /// - `InvalidPortType`: when the types are not identical
    /// - `InvalidPortFlags`: when the flags do not satisfy the preconditions above
    /// - `UnknownErrorCode`
    pub fn disconnect_ports(&mut self, from: &JackPort, to: &JackPort) -> JackResult<()> {
        self.connect_or_disconnect_ports(from, to, false)
    }
    /// Get a port from the JACK server by its name.
    ///
    /// # Errors
    ///
    /// - `PortNotFound`: if no port with that name was found
    /// - `NulError`: if any `&str` argument contains a NUL byte (`\0`).
    pub fn get_port_by_name(&self, name: &str) -> JackResult<JackPort> {
        let name = str_to_cstr(name)?;
        let ptr = unsafe {
            jack_port_by_name(self.handle, name.as_ptr())
        };
        if ptr.is_null() {
            Err(JackError::PortNotFound)?
        }
        unsafe {
            Ok(JackPort::from_ptr(ptr))
        }
    }
    /// Get all (or a selection of) ports available in the JACK server.
    ///
    /// # Parameters
    ///
    /// - port_filter: A regular expression used to select ports by name. If `None`, no
    /// selection based on name will be carried out.
    /// - type_filter: A regular expression used to select ports by type. If `None`, no
    /// selection based on type will be carried out.
    /// - flags_filter: A value used to select ports by their flags. If `None`, no
    /// selection based on flags will be carried out.
    ///
    /// # Errors
    ///
    /// - `NulError`: if any `&str` argument contains a NUL byte (`\0`).
    /// - `ProgrammerError`: if I've made a mistake, or your program is utterly degenerate
    pub fn get_ports(&self, port_filter: Option<&str>, type_filter: Option<&str>, flags_filter: Option<JackPortFlags>) -> JackResult<Vec<JackPort>> {
        let mut flags = JackPortFlags::empty();
        let mut pf = CString::new("").unwrap();
        let mut tf = CString::new("").unwrap();
        if let Some(f) = flags_filter {
            flags = f;
        }
        if let Some(f) = port_filter {
            pf = str_to_cstr(f)?;
        }
        if let Some(f) = type_filter {
            tf = str_to_cstr(f)?;
        }
        let mut ptr = unsafe {
            jack_get_ports(self.handle, pf.as_ptr(), tf.as_ptr(), flags.bits())
        };
        if ptr.is_null() {
            Err(JackError::ProgrammerError)?
        }
        let mut cstrs: Vec<&CStr> = vec![];
        loop {
            unsafe {
                if (*ptr).is_null() {
                    break;
                }
                else {
                    let cs = CStr::from_ptr(*ptr);
                    cstrs.push(cs);
                    ptr = ptr.offset(1);
                }
            }
        }
        let mut ret: Vec<JackPort> = vec![];
        for st in cstrs {
            let ptr = unsafe {
                jack_port_by_name(self.handle, st.as_ptr())
            };
            if !ptr.is_null() {
                unsafe {
                    ret.push(JackPort::from_ptr(ptr));
                }
            }
        }
        Ok(ret)
    }
    /// Create a new port for the client.
    ///
    /// This is an object used for moving data of any type in or out of the client.
    /// Ports may be connected in various ways.
    ///
    /// Each port has a short name. The port's full name contains the name of the client
    /// concatenated with a colon (:) followed by its short name. The jack_port_name_size()
    /// is the maximum length of this full name. Exceeding that will cause the port
    /// registration to fail and return `ProgrammerError`.
    ///
    /// The port_name must be unique among all ports owned by this client. If the name is
    /// not unique, the registration will fail.
    ///
    /// All ports have a type, which may be any non-NULL and non-zero length string,
    /// passed as an argument. Some port types are built into the JACK API, like
    /// JACK_DEFAULT_AUDIO_TYPE or JACK_DEFAULT_MIDI_TYPE. *[By default, sqa-jack makes a
    /// JACK_DEFAULT_AUDIO_TYPE port - this will be changeable in later releases.]*
    ///
    /// # Errors
    ///
    /// - `NulError`: if any `&str` argument contains a NUL byte (`\0`).
    /// - `PortRegistrationFailed`: if port registration failed (TODO: why could this happen?)
    pub fn register_port(&mut self, name: &str, ty: JackPortFlags) -> JackResult<JackPort> {
        let ptr = unsafe {
            let name = str_to_cstr(name)?;
            jack_port_register(self.handle, name.as_ptr(), JACK_DEFAULT_AUDIO_TYPE.as_ptr() as *const libc::c_char, ty.bits(), 0)
        };
        if ptr.is_null() {
            Err(JackError::PortRegistrationFailed)?
        }
        else {
            unsafe {
                Ok(JackPort::from_ptr(ptr))
            }
        }
    }
    /// Remove the port from the client, disconnecting any existing connections.
    ///
    /// # Errors
    ///
    /// - `PortNotMine`: if you deregister a port that this client doesn't own
    /// - `InvalidPort`
    /// - `UnknownErrorCode`
    pub fn unregister_port(&mut self, port: JackPort) -> JackResult<()> {
        let mine = unsafe {
            jack_port_is_mine(self.handle, port.as_ptr())
        };
        if mine == 0 {
           Err(JackError::PortNotMine)?
        }
        let code = unsafe {
            jack_port_unregister(self.handle, port.as_ptr())
        };
        match code {
            0 => Ok(()),
            -1 => Err(JackError::InvalidPort)?,
            x @ _ => Err(JackError::UnknownErrorCode { from: "unregister_port()", code: x })?
        }
    }
}
impl JackConnection<Deactivated> {
    /// Open an external client session with a JACK server, optionally specifying
    /// a number of `JackOpenOptions`.
    ///
    /// # Errors
    ///
    /// - `JackOpenFailed(status)`: if the connection could not be opened. Contains a
    /// `JackStatus` detailing what went wrong.
    /// - `NulError`: if any `&str` argument contains a NUL byte (`\0`).
    pub fn connect(client_name: &str, opts: Option<JackOpenOptions>) -> JackResult<Self> {
        let mut status = 0;
        let opts = opts.map(|x| x.bits()).unwrap_or(JackNullOption);
        let client = unsafe {
            let name = str_to_cstr(client_name)?;
            jack_client_open(name.as_ptr(), opts, &mut status)
        };
        if client.is_null() {
            Err(JackError::JackOpenFailed(
                JackStatus::from_bits_truncate(status)
            ))?;
        }
        let sample_rate = unsafe { jack_get_sample_rate(client) };
        Ok(JackConnection {
            handle: client,
            sample_rate: sample_rate,
            _phantom: PhantomData
        })
    }
    /// Register a handler (a struct that implements `JackHandler`).
    ///
    /// # Safety
    ///
    /// **Warning:** Your handler will never be deallocated / `Drop`ped.
    ///
    /// # Errors
    ///
    /// - `UnknownErrorCode`
    pub fn set_handler<F>(&mut self, handler: F) -> JackResult<()> where F: JackHandler {
        handler::set_handler(self, handler)
    }
    /// Tell the Jack server that the program is ready to start processing audio.
    ///
    /// # Returns
    ///
    /// Returns the `Activated` connection type on success, or the current structure and
    /// an error on failure.
    ///
    /// # Errors
    ///
    /// - `UnknownErrorCode`
    pub fn activate(self) -> Result<JackConnection<Activated>, (Self, JackError)> {
        unsafe {
            self.activate_or_deactivate(true)
        }
    }
}
impl JackConnection<Activated> {
    /// Tell the Jack server to remove this client from the process graph.
    /// Also, **disconnect all ports belonging to it**, since inactive clients have no port
    /// connections.
    ///
    /// # Returns
    ///
    /// Returns the `Dectivated` connection type on success, or the current structure and
    /// an error on failure.
    ///
    /// # Errors
    ///
    /// - `UnknownErrorCode`
    pub fn deactivate(self) -> Result<JackConnection<Deactivated>, (Self, JackError)> {
        unsafe {
            self.activate_or_deactivate(false)
        }
    }
}
impl<T> Drop for JackConnection<T> {
    fn drop(&mut self) {
        unsafe {
            jack_deactivate(self.handle);
            jack_client_close(self.handle);
        }
    }
}