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
use jack_sys as j;
use std::fmt;
use std::fmt::Debug;
use std::mem;

use super::callbacks::clear_callbacks;
use super::callbacks::{CallbackContext, NotificationHandler, ProcessHandler};
use crate::client::client_impl::Client;
use crate::client::common::{sleep_on_test, CREATE_OR_DESTROY_CLIENT_MUTEX};
use crate::Error;

/// A JACK client that is processing data asynchronously, in real-time.
///
/// To create input or output (either sound or midi), a `Port` can be used within the `process`
/// callback. See `Client::register_port` on creating ports. Also, see `Port` for documentation on
/// the API for port.
///
/// # Example
/// ```
/// // Create a client and a handler
/// let (client, _status) =
///     jack::Client::new("my_client", jack::ClientOptions::NO_START_SERVER).unwrap();
/// let process_handler = jack::ClosureProcessHandler::new(
///     move |_: &jack::Client, _: &jack::ProcessScope| jack::Control::Continue,
/// );
///
/// // An active async client is created, `client` is consumed.
/// let active_client = client.activate_async((), process_handler).unwrap();
/// // When done, deactivate the client.
/// active_client.deactivate().unwrap();
/// ```
#[must_use = "The jack client is shut down when the AsyncClient is dropped. You most likely want to keep this alive and manually tear down with `AsyncClient::deactivate`."]
pub struct AsyncClient<N, P> {
    callback: Option<Box<CallbackContext<N, P>>>,
}

unsafe impl<N, P> Send for AsyncClient<N, P> {}
unsafe impl<N, P> Sync for AsyncClient<N, P> {}

impl<N, P> AsyncClient<N, P>
where
    N: 'static + Send + Sync + NotificationHandler,
    P: 'static + Send + ProcessHandler,
{
    /// Tell the JACK server that the program is ready to start processing audio. JACK will call the
    /// methods specified by the `NotificationHandler` and `ProcessHandler` objects.
    ///
    /// On failure, either `Err(Error::CallbackRegistrationError)` or
    /// `Err(Error::ClientActivationError)` is returned.
    ///
    /// `notification_handler` and `process_handler` are consumed, but they are returned when
    /// `Client::deactivate` is called.
    pub fn new(client: Client, notification_handler: N, process_handler: P) -> Result<Self, Error> {
        let _m = CREATE_OR_DESTROY_CLIENT_MUTEX.lock().unwrap();
        unsafe {
            sleep_on_test();
            let mut callback_context = Box::new(CallbackContext {
                client,
                notification: notification_handler,
                process: process_handler,
            });
            CallbackContext::register_callbacks(&mut callback_context)?;
            sleep_on_test();
            let res = j::jack_activate(callback_context.client.raw());
            for _ in 0..4 {
                sleep_on_test();
            }
            match res {
                0 => Ok(AsyncClient {
                    callback: Some(callback_context),
                }),
                _ => {
                    mem::forget(callback_context);
                    Err(Error::ClientActivationError)
                }
            }
        }
    }
}

impl<N, P> AsyncClient<N, P> {
    /// Return the underlying `jack::Client`.
    #[inline(always)]
    pub fn as_client(&self) -> &Client {
        let callback = self.callback.as_ref().unwrap();
        &callback.client
    }

    /// 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.
    ///
    /// The `handler` that was used for `Client::activate` is returned on success. Its state may
    /// have changed due to JACK calling its methods.
    ///
    /// In the case of error, the `Client` is destroyed because its state is unknown, and it is
    /// therefore unsafe to continue using.
    pub fn deactivate(self) -> Result<(Client, N, P), Error> {
        let mut c = self;
        unsafe {
            c.maybe_deactivate()
                .map(|c| (c.client, c.notification, c.process))
        }
    }

    // Helper function for deactivating. Any function that calls this should
    // have ownership of self and no longer use it after this call.
    unsafe fn maybe_deactivate(&mut self) -> Result<CallbackContext<N, P>, Error> {
        let _m = CREATE_OR_DESTROY_CLIENT_MUTEX.lock().unwrap();
        if self.callback.is_none() {
            return Err(Error::ClientIsNoLongerAlive);
        }
        let client = self.callback.as_ref().unwrap().client.raw();
        // Prevent the callback from being deallocated in case deactivation
        // fails.
        let callback = Box::into_raw(self.callback.take().unwrap());

        // deactivate
        sleep_on_test();
        if j::jack_deactivate(client) != 0 {
            return Err(Error::ClientDeactivationError);
        }

        // clear the callbacks
        sleep_on_test();
        clear_callbacks(client)?;

        // done, take ownership of callback
        Ok(*Box::from_raw(callback))
    }
}

/// Closes the client.
impl<N, P> Drop for AsyncClient<N, P> {
    /// Deactivate and close the client.
    fn drop(&mut self) {
        let _ = unsafe { self.maybe_deactivate() };
    }
}

impl<N, P> Debug for AsyncClient<N, P> {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        f.debug_tuple("AsyncClient")
            .field(&self.as_client())
            .finish()
    }
}