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
use std::{fmt, slice};
use std::ffi::{CString, CStr};
use libc::{c_void, EEXIST};
use jack_sys::*;

use client::JackClient;
use error::PortError;

#[derive(Debug,Clone)]
pub enum Direction {
    Input,
    Output,
    NoInOrOut
}

impl Direction {
    pub fn is_input(&self) -> bool {
        match *self {
            Direction::Input => true,
            _ => false
        }
    }

    pub fn is_output(&self) -> bool {
        match *self {
            Direction::Output => true,
            _ => false
        }
    }
}

#[derive(Debug, Clone)]
pub enum Kind {
    Physical,
    Virtual
}

impl Kind {
    pub fn is_physical(&self) -> bool {
        match *self {
            Kind::Physical => true,
            _ => false
        }
    }
}

pub struct JackPort {
    pub client: *mut jack_client_t,
    pub name: Option<String>,
    pub direction: Option<Direction>,
    pub kind: Option<Kind>,
    pub port: Option<*mut jack_port_t>
}

impl JackPort {
    pub fn new(client: *mut jack_client_t) -> JackPort  {
        JackPort { client: client, direction: None, kind: None, name: None, port: None }
    }

    pub fn from_name(client: *mut jack_client_t, name: &str) -> Option<JackPort> {
        let c_name = match CString::new(name) {
            Ok(s) => s,
            Err(_) => return None
        };
        
        let port = unsafe { jack_port_by_name(client, c_name.as_ptr()) };
        if port.is_null() {
            return None;
        }

        // get the full name with client prefix
        let full_name = unsafe { CStr::from_ptr(jack_port_name(port)).to_str().unwrap() };

        return Some(JackPort { client: client, direction: None, kind: None, name: Some(full_name.into()), port: Some(port) });
    }

    pub fn get_port(&mut self) ->  *mut jack_port_t {
        if self.port.is_none() {
            let name = match self.name {
                Some(ref n) => n.as_str(),
                None => panic!("Port has no name!")
            };

            let c_name = match CString::new(name) {
                Ok(s) => s,
                Err(_) => panic!("Cannot conert client name!")
            };
        
            let port = unsafe { jack_port_by_name(self.client, c_name.as_ptr()) };
            if port.is_null() {
                panic!("Invalid port name!");
            }

            self.port = Some(port);
        }

        self.port.unwrap()
    }

    pub fn name<T>(mut self, name: T) -> JackPort
    where T: Into<String> {
        self.name = Some(name.into());
        self
    }

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

    pub fn direction(mut self, direction: Direction) -> JackPort {
        self.direction = Some(direction);
        self
    }

    pub fn get_direction(&mut self) -> Direction {
        let dir = match self.direction.clone() {
            Some(d) => d,
            None => {
                let flags = unsafe { jack_port_flags(self.port.unwrap()) as u32 };
                if (flags & JackPortIsInput) != 0 {
                    Direction::Input
                } else if (flags & JackPortIsOutput) != 0 {
                    Direction::Output
                } else {
                    Direction::NoInOrOut
                }
            }
        };

        if self.direction.is_none() {
            self.direction = Some(dir.clone());
        }
        
        dir
    }

    pub fn kind(mut self, kind: Kind) -> JackPort {
        self.kind = Some(kind);
        self
    }

    pub fn get_kind(&mut self) -> Kind {
        let kind = match self.kind.clone() {
            Some(k) => k,
            None => { 
                let flags = unsafe { jack_port_flags(self.port.unwrap()) as u32 };
                if (flags & JackPortIsPhysical) != 0 {
                    Kind::Physical
                }  else {
                    Kind::Virtual
                }
            }
        };

        if self.kind.is_none() {
            self.kind = Some(kind.clone());
        }

        kind

    }

    pub fn register(mut self) -> Result<JackPort, PortError> {
        let c_name = {
            let name = match self.name {
                Some(ref name) => name.as_str(),
                None => "unknown_client"
            };
        
            match CString::new(name) {
                Ok(s) => s,
                Err(e) => panic!("..")
            }
        };

        let c_type = {
            CString::new("32 bit float mono audio").unwrap()
        };

        let mut flags: u32 = 0;
        if let Some(ref direction) = self.direction {
            flags = match direction {
                &Direction::Input => JackPortIsInput,
                &Direction::Output => JackPortIsOutput,
                &Direction::NoInOrOut => 0
            };
        };

        let port = unsafe {
            jack_port_register(self.client, c_name.as_ptr(), c_type.as_ptr(), flags as u64, 0)
        };

        if port.is_null() {
            return Err(PortError::Unknown);
        }
        // get the full name with client prefix
        let full_name = unsafe { CStr::from_ptr(jack_port_name(port)).to_str().unwrap() };
        self.name = Some(full_name.into());
        self.port = Some(port);

        Ok(self)
    }

    pub fn connect_to(&mut self, port: &JackPort) -> Result<(), PortError> {
        let name1 = {
            if let Some(name) = self.get_name() {
                CString::new(name).unwrap()
            } else {
                return Err(PortError::NotRegistered);
            }
        };
        let name2 = {
            if let Some(name) = port.name.clone() {
                CString::new(name).unwrap()
            } else {
                return Err(PortError::NotRegistered);
            }
        };

        let code;
        unsafe {
            code = jack_connect(self.client, name1.as_ptr(), name2.as_ptr());
        }

        if code == EEXIST {
            Err(PortError::AlreadyExist)
        } else if code != 0 {
            Err(PortError::Unknown)
        } else {
            Ok(())
        }
    }

    pub unsafe fn buffer(&self, nframes: u32) -> *mut c_void {
        jack_port_get_buffer(self.port.unwrap(), nframes)
    }

    pub unsafe fn get_slice<T>(&self, nframes: u32) -> &[T] {
        let buffer = self.buffer(nframes) as *const  T;
        slice::from_raw_parts(buffer, nframes as usize)
    }

    pub unsafe fn get_slice_mut<T>(&self, nframes: u32) -> &mut [T] {
        let buffer = self.buffer(nframes) as *mut T;
        slice::from_raw_parts_mut(buffer, nframes as usize)
    }

}

impl fmt::Debug for JackPort {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Name: {:?}, Direction: {:?}, Kind: {:?}", self.get_name(), self.direction, self.kind)
    }
}