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
/// dxx is a library for io and converting audio files with a .DXX extension.
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::fmt;
use std::fmt::{Formatter, Display};
use std::str;
use std::str::FromStr;
use std::error::Error;
use std::fs;
use std::fs::File;
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian};

const TEXT_BIN_FILE_SIZE_MEAN_RATE: &'static usize = &13;
const DSX_AMP: i16 = i16::max_value();
const DFX_AMP: f32 = 10000.;
const DDX_AMP: f64 = 10000.;

/// DType is an enum for describing data type of file.
pub enum DType {
    DSA,
    DFA,
    DDA,
    DSB,
    DFB,
    DDB,
}

impl Display for DType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match *self {
            DType::DSA => write!(f, "DSA"),
            DType::DFA => write!(f, "DFA"),
            DType::DDA => write!(f, "DDA"),
            DType::DSB => write!(f, "DSB"),
            DType::DFB => write!(f, "DFB"),
            DType::DDB => write!(f, "DDB"),
        }
    }
}

impl FromStr for DType {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "DSA" => Ok(DType::DSA),
            "DFA" => Ok(DType::DFA),
            "DDA" => Ok(DType::DDA),
            "DSB" => Ok(DType::DSB),
            "DFB" => Ok(DType::DFB),
            "DDB" => Ok(DType::DDB),
            _ => Err("invalid string")
        }
    }
}

impl DType {
    /// from_filename determines the data type from the specified file name.
    pub fn from_filename(filename: &str) -> Result<DType, &'static str> {
        let suffix = match filename.split(".").last() {
            Some(s) => s,
            None => return Err("invalid file name") // TODO improve filename
        };
        DType::from_str(suffix)
    }

    /// byte_width returns the byte width of a sample.
    pub fn byte_width(&self) -> u32 {
        match *self {
            DType::DSA | DType::DSB => 2,
            DType::DFA | DType::DFB => 4,
            DType::DDA | DType::DDB => 8,
        }
    }

    /// byte_width returns the bits width of a sample.
    pub fn bits_width(&self) -> u32 {
        match *self {
            DType::DSA | DType::DSB => 16,
            DType::DFA | DType::DFB => 32,
            DType::DDA | DType::DDB => 64,
        }
    }
}

/// len_file returns the byte length of the specified file.
pub fn len_file(filename: &str) -> Result<u64, Box<dyn Error>> {
    let meta = fs::metadata(filename)?;
    Ok(meta.len())
}

/// read_file reads .DXX file.
/// This func determines the data type from the filename extension and reads that data.
/// The return type is Vec<f64> to make the data easier to handle.
pub fn read_file(filename: &str) -> Result<Vec<f64>, Box<dyn Error>> {
    let mut f = File::open(filename)?;
    let file_size = f.metadata()?.len() as usize;
    let dtype = DType::from_filename(filename)?;

    match dtype {
        DType::DSA |
        DType::DFA |
        DType::DDA => read_dxa(&mut f, file_size),

        DType::DSB => read_dsb(&mut f, file_size),
        DType::DFB => read_dfb(&mut f, file_size),
        DType::DDB => read_ddb(&mut f, file_size),
    }
}


fn read_dxa<T: Read>(src: &mut T, size: usize) -> Result<Vec<f64>, Box<dyn Error>> {
    let mut ret: Vec<f64> = Vec::with_capacity(size / *TEXT_BIN_FILE_SIZE_MEAN_RATE);
    for result in BufReader::new(src).lines() {
        let line = result?;
        let buf: f64 = line.parse::<f64>()?;
        ret.push(buf);
    }
    Ok(ret)
}

fn read_dsb<T: Read>(src: &mut T, size: usize) -> Result<Vec<f64>, Box<dyn Error>> {
    let byte_width = DType::DSB.byte_width();
    let mut buf: Vec<i16> = vec![0; size / byte_width as usize];
    let mut reader = BufReader::new(src);
    reader.read_i16_into::<LittleEndian>(&mut buf)?;
    Ok(buf.iter().map(|x| f64::from(*x)).collect())
}

fn read_dfb<T: Read>(src: &mut T, size: usize) -> Result<Vec<f64>, Box<dyn Error>> {
    let byte_width = DType::DFB.byte_width();
    let mut buf: Vec<f32> = vec![0.; size / byte_width as usize];
    let mut reader = BufReader::new(src);
    reader.read_f32_into::<LittleEndian>(&mut buf)?;
    Ok(buf.iter().map(|x| f64::from(*x)).collect())
}

fn read_ddb<T: Read>(src: &mut T, size: usize) -> Result<Vec<f64>, Box<dyn Error>> {
    let byte_width = DType::DDB.byte_width();
    let mut buf: Vec<f64> = vec![0.; size / byte_width as usize];
    let mut reader = BufReader::new(src);
    reader.read_f64_into::<LittleEndian>(&mut buf)?;
    Ok(buf.iter().map(|x| f64::from(*x)).collect())
}

/// write_file writes data to .DXX file.
/// This func determines the data type from the filename extension and writes the data to the file.
pub fn write_file(filename: &str, src: Vec<f64>) -> Result<(), Box<dyn Error>> {
    let mut f = File::create(filename)?;
    let dtype = DType::from_filename(filename)?;

    match dtype {
        DType::DSA => write_dxa(&mut f, f64s_to_i16s(&src, DSX_AMP)),
        DType::DFA => write_dxa(&mut f, f64s_to_f32s(&src, DFX_AMP)),
        DType::DDA => write_dxa(&mut f, normalize_f64s(src, DDX_AMP)),

        DType::DSB => write_dsb(&mut f, f64s_to_i16s(&src, DSX_AMP)),
        DType::DFB => write_dfb(&mut f, f64s_to_f32s(&src, DFX_AMP)),
        DType::DDB => write_ddb(&mut f, normalize_f64s(src, DDX_AMP)),
    }
}

fn write_dxa<T: Write, U: std::fmt::Display>(dst: T, src: Vec<U>) -> Result<(), Box<dyn Error>> {
    let mut writer = BufWriter::new(dst);
    for x in src {
        writeln!(writer, "{}", x)?;
    }
    Ok(())
}

fn write_dsb<T: Write>(dst: T, src: Vec<i16>) -> Result<(), Box<dyn Error>> {
    let mut writer = BufWriter::new(dst);
    for x in src {
        writer.write_i16::<LittleEndian>(x)?;
    }
    Ok(())
}

fn write_dfb<T: Write>(dst: T, src: Vec<f32>) -> Result<(), Box<dyn Error>> {
    let mut writer = BufWriter::new(dst);
    for x in src {
        writer.write_f32::<LittleEndian>(x)?;
    }
    Ok(())
}

fn write_ddb<T: Write>(dst: T, src: Vec<f64>) -> Result<(), Box<dyn Error>> {
    let mut writer = BufWriter::new(dst);
    for x in src {
        writer.write_f64::<LittleEndian>(x)?;
    }
    Ok(())
}

fn normalize_f64s(src: Vec<f64>, amp: f64) -> Vec<f64> {
    let abs_src: Vec<f64> = src.iter().map(|x| x.clone().abs()).collect();
    let max = max_f64s(&abs_src);
    src.iter().map(|x| (x / max * amp)).collect()
}

fn f64s_to_i16s(src: &Vec<f64>, amp: i16) -> Vec<i16> {
    let abs_src: Vec<f64> = src.iter().map(|x| x.clone().abs()).collect();
    let max = max_f64s(&abs_src);
    src.iter().map(|x| (x / max * amp as f64) as i16).collect()
}

fn f64s_to_f32s(src: &Vec<f64>, amp: f32) -> Vec<f32> {
    let abs_src: Vec<f64> = src.iter().map(|x| x.clone().abs()).collect();
    let max = max_f64s(&abs_src);
    src.iter().map(|x| (x / max * amp as f64) as f32).collect()
}

fn max_f64s(src: &Vec<f64>) -> f64 {
    src.iter().fold(0.0 / 0.0, |m, v| v.max(m))
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn test_f64s_to_i16s() {
        let src: Vec<f64> = vec![5., -2., 4., -3.];
        assert_eq!(f64s_to_i16s(&src, DSX_AMP), vec![32767, -13106, 26213, -19660]);
    }

    #[test]
    fn test_write_file() {
        let src: Vec<f64> = vec![5., -2., 4., -3.];
        write_file("a.DSA", src).unwrap();
        let src: Vec<f64> = vec![5., -2., 4., -3.];
        write_file("a.DFA", src).unwrap();
        let src: Vec<f64> = vec![5., -2., 4., -3.];
        write_file("a.DDA", src).unwrap();
        let src: Vec<f64> = vec![5., -2., 4., -3.];
        write_file("a.DSB", src).unwrap();
        let src: Vec<f64> = vec![5., -2., 4., -3.];
        write_file("a.DFB", src).unwrap();
        let src: Vec<f64> = vec![5., -2., 4., -3.];
        write_file("a.DDB", src).unwrap();
    }

    #[test]
    fn test_convert() {
        let data = read_file("sine.DSB").unwrap();
        write_file("sine.DSA", data).unwrap();
        let data = read_file("sine.DSB").unwrap();
        write_file("sine.DFA", data).unwrap();
        let data = read_file("sine.DSB").unwrap();
        write_file("sine.DFB", data).unwrap();
        let data = read_file("sine.DSB").unwrap();
        write_file("sine.DDA", data).unwrap();
        let data = read_file("sine.DSB").unwrap();
        write_file("sine.DDB", data).unwrap();
        let data = read_file("sine.DSA").unwrap();
        write_file("sine1.DSB", data).unwrap();
    }
}