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
use std::ffi::{CString, CStr};
use std::ptr;
use std::thread::sleep;
use std::time::Duration;
use libc::c_void;

use jack_sys::*;

use port::*;
use callbacks::{JackControl, JackHandler, register_callbacks};
use error::{ClientStatus, JackErr};

pub enum ClientOption {
    SessionID,
    ServerName,
    NoStartServer,
    UseExactName,
    FreeWheel
}

impl ClientOption {
    fn as_u32(&self) -> u32 {
        match *self {
            ClientOption::SessionID => JackSessionID,
            ClientOption::ServerName => JackServerName,
            ClientOption::NoStartServer => JackNoStartServer,
            ClientOption::UseExactName => JackUseExactName,
            _ => 0
        }
    }
}

pub struct JackClient<T: JackHandler>
{
    client_name: Option<String>,
    handler: Option<*mut T>,
    options: u32,
    client: Option<*mut jack_client_t>,
    freewheel: bool
}

impl<T: JackHandler> JackClient<T>
{
    pub fn new() -> JackClient<T>
    {
        JackClient { client_name: None, handler: None, options: 0, client: None, freewheel: false }
    }

    pub fn name<'b>(mut self, name: &'b str) -> JackClient<T> {
        self.client_name = Some(name.into());
        self
    }

    pub fn get_name(&mut self) -> Option<String> {
        self.client_name.clone()
    }

    pub fn option(mut self, option: ClientOption) -> JackClient<T> {
        match option {
            ClientOption::FreeWheel => self.freewheel = true,
            _ => self.options = self.options|option.as_u32()
        }

        self
    }

    pub fn buffer_size(&mut self, nframes: u32) {
        unsafe { jack_set_buffer_size(self.client.expect("Cannot change buffer_size!"), nframes); }
    }

    pub fn get_buffer_size(&mut self) -> u32{
        unsafe { jack_get_buffer_size(self.client.expect("Client not connected!")) }
    }

    pub fn get_sample_rate(&mut self) -> u32 {
        unsafe { jack_get_sample_rate(self.client.unwrap()) }
    }

    pub fn get_cpu_load(&mut self) -> f32 {
        unsafe { jack_cpu_load(self.client.unwrap()) }
    }

    pub fn connect(mut self) -> Result<JackClient<T>, ClientStatus> {
        let c_name = {
            let name = match self.client_name {
                Some(ref name) => name.as_str(),
                None => "unknown_client"
            };
       
            CString::new(name).unwrap_or(CString::new("unknown_client").unwrap())
        };
      
        let i: jack_status_t = 0;
        let client: *mut jack_client_t;
            
        unsafe {
            client = jack_client_open(c_name.as_ptr(), self.options, i as *mut jack_status_t);
            if client.is_null() {
                return Err(ClientStatus(i));
            }

            if self.freewheel {
                jack_set_freewheel(client, 1);
            } else {
                jack_set_freewheel(client, 0);
            }
        }


        self.client = Some(client);

        Ok(self)
    }

    pub fn new_port(&self) -> JackPort {
        JackPort::new(self.client.expect("Error: client is no connected!"))
    }

    pub fn activate(&mut self, mut handler_obj: T) -> Result<*mut T, ()> {
        let client = self.client.expect("Error: Client is not connected!");

        let handler = unsafe { register_callbacks(client, handler_obj).unwrap() };

        unsafe {
            if jack_activate(client) == 1 {
                return Err(());
            }
        }

        unsafe { (*handler).activated(self); }

        self.handler = Some(handler);

        Ok(handler)
    }

    pub fn search(&mut self) -> PortIterator {
        PortIterator::new(self.client.unwrap())
    }
}

impl<T: JackHandler> Drop for JackClient<T> {
    fn drop(&mut self) {
        if let Some(client) = self.client {
            unsafe {
                jack_client_close(client);
            }
        }
    }
}

pub struct PortIterator {
    client: *mut jack_client_t,
    ports: *mut *const i8,
    idx: isize
}

impl PortIterator {
    pub fn new(client: *mut jack_client_t) -> PortIterator {
        let ports: *mut *const i8 = unsafe {
            jack_get_ports(client, ptr::null(), ptr::null(), 0)
        };

        let mut idx = 0;
        if ports == ptr::null_mut() {
            // search has failed, yield None
            idx = -1;
        }

        PortIterator { client: client,ports: ports, idx: idx }
    }
}

impl<'a> Iterator for PortIterator {
    type Item = JackPort;

    fn next(&mut self) -> Option<Self::Item> {
        if self.idx == -1 {
            return None;
        }

        let name = unsafe {
            let maybe_str = ptr::read(self.ports.offset(self.idx));
            
            if maybe_str.is_null() {
                self.idx = -1;
                return None;
            }

            CStr::from_ptr(maybe_str as *mut i8).to_str()
        };
        
        match name {
            Ok(name) => {
                self.idx += 1;
                JackPort::from_name(self.client, name)
            },
            Err(_) => {
                self.idx = -1;
                None
            }
        }
    }
}