aboutsummaryrefslogtreecommitdiffstats
path: root/src/fl2k.rs
blob: 695d32a7349ff071c583a35b3138eae717ffc6f2 (plain)
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
use std::{ffi::{c_int, c_void}, sync::mpsc, mem::swap};
use fl2k_ampliphase::{fl2k_dev_t, fl2k_get_device_count, fl2k_open, fl2k_close, fl2k_stop_tx, fl2k_set_sample_rate, fl2k_get_sample_rate, fl2k_start_tx, FL2K_BUF_LEN};

const BUF_LEN : usize = FL2K_BUF_LEN as usize;

#[derive(Debug)]
pub enum FL2KError {
    InvalidParam,
    NoDevice,
    NotFound,
    Busy,
    Timeout,
    NoMem,
    Unknown(c_int)
}

fn handle_return_value(val: c_int) -> Result<(), FL2KError> {
    if val == fl2k_ampliphase::fl2k_error_FL2K_SUCCESS { Ok(()) }
    else if val == fl2k_ampliphase::fl2k_error_FL2K_TRUE { Ok(()) }
    else if val == fl2k_ampliphase::fl2k_error_FL2K_ERROR_INVALID_PARAM { Err(FL2KError::InvalidParam) }
    else if val == fl2k_ampliphase::fl2k_error_FL2K_ERROR_NO_DEVICE { Err(FL2KError::NoDevice) }
    else if val == fl2k_ampliphase::fl2k_error_FL2K_ERROR_NOT_FOUND { Err(FL2KError::NotFound) }
    else if val == fl2k_ampliphase::fl2k_error_FL2K_ERROR_BUSY { Err(FL2KError::Busy) }
    else if val == fl2k_ampliphase::fl2k_error_FL2K_ERROR_TIMEOUT { Err(FL2KError::Timeout) }
    else if val == fl2k_ampliphase::fl2k_error_FL2K_ERROR_NO_MEM { Err(FL2KError::NoMem) }
    else { Err(FL2KError::Unknown(val)) }
}

pub fn get_device_count() -> u32 {
    unsafe { fl2k_get_device_count() }
}

pub struct FL2K {
    device: *mut fl2k_dev_t,
    callback_ctx: Box<CallbackCtx>,
    tx : mpsc::SyncSender<(Vec<i8>, Vec<i8>)>,

    r_buf : Vec<i8>,
    g_buf : Vec<i8>
}

pub struct CallbackCtx {
    // All three buffers must have same length!
    r_buf: Vec<i8>,
    g_buf: Vec<i8>,

    rg_bufs_channel: mpsc::Receiver<(Vec<i8>, Vec<i8>)>,

    underflow_count: u32,
    buffer_underflows: u32,

    abort: bool,
}

extern "C" fn tx_callback(data_info: *mut fl2k_ampliphase::fl2k_data_info_t) {
    unsafe {
        let ctx = (*data_info).ctx as *mut CallbackCtx;

        if (*data_info).device_error != 0 {
            (*ctx).abort = true;
        }
        else {
            (*ctx).underflow_count = (*data_info).underflow_cnt;

            match (*ctx).rg_bufs_channel.try_recv() {
                Ok((r, g)) => {
                    (*data_info).sampletype_signed = 1;

                    (*ctx).r_buf = r;
                    (*ctx).g_buf = g;

                    (*data_info).r_buf = (*ctx).r_buf.as_mut_ptr();
                    (*data_info).g_buf = (*ctx).g_buf.as_mut_ptr();
                },
                Err(_) => {
                    (*ctx).buffer_underflows += 1;
                    eprintln!("FL2K buffers not ready on callback");
                },
            }
        }
    }
}

impl FL2K {
    pub fn open(device_index: u32) -> Result<Self, FL2KError> {
        let (tx, rx) = mpsc::sync_channel(2);
        let ctx = CallbackCtx {
            r_buf: Vec::new(),
            g_buf: Vec::new(),
            rg_bufs_channel: rx,
            underflow_count: 0,
            buffer_underflows: 0,
            abort: false,
        };
        unsafe {

            let r_buf = Vec::with_capacity(2 * BUF_LEN);
            let g_buf = Vec::with_capacity(2 * BUF_LEN);

            let mut fl2k = FL2K { device: std::mem::zeroed(), callback_ctx: Box::new(ctx), tx, r_buf, g_buf };
            handle_return_value(fl2k_open(&mut fl2k.device, device_index))?;
            Ok(fl2k)
        }
    }

    pub fn set_sample_rate(&mut self, sample_rate: u32) -> Result<(), FL2KError> {
        let r = unsafe { fl2k_set_sample_rate(self.device, sample_rate) };
        if r < 0 {
            handle_return_value(r)
        }
        else {
            Ok(())
        }
    }

    pub fn get_sample_rate(&mut self) -> Result<u32, FL2KError> {
        let sr = unsafe { fl2k_get_sample_rate(self.device) };
        if sr == 0 { Err(FL2KError::Unknown(0)) } else { Ok(sr) }
    }

    pub fn start_tx(&mut self) -> Result<(), FL2KError> {
        let r = unsafe { fl2k_start_tx(self.device, Some(tx_callback), self.callback_ctx.as_mut() as *mut CallbackCtx as *mut c_void, 0) };
        handle_return_value(r)
    }

    pub fn stop_tx(&self) -> Result<(), FL2KError> {
        handle_return_value( unsafe { fl2k_stop_tx(self.device) } )
    }

    pub fn send(&mut self, mut r_buf: Vec<i8>, mut g_buf: Vec<i8>) -> bool {
        if r_buf.len() != g_buf.len() {
            panic!("r_buf and g_buf must have same length");
        }

        self.r_buf.append(&mut r_buf);
        self.g_buf.append(&mut g_buf);

        if self.r_buf.len() >= BUF_LEN {
            let mut r = self.r_buf.split_off(BUF_LEN);
            let mut g = self.g_buf.split_off(BUF_LEN);
            /* self.r_buf contains head, r contains tail. Swap them, as we want to give the head and keep the tail. */
            swap(&mut r, &mut self.r_buf);
            swap(&mut g, &mut self.g_buf);
            self.tx.send((r, g)).is_ok()
        }
        else {
            true
        }
    }
}


impl Drop for FL2K {
    fn drop(&mut self) {
        match unsafe {
            handle_return_value(fl2k_close(self.device))
        } {
            Ok(_) => (),
            Err(e) => eprintln!("Failed to close FL2K: {:?}", e),
        }
    }
}