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
259
260
261
262
263
264
265
/**************************************************************************
 *                                                                        *
 * Rust implementation of the X3 lossless audio compression protocol.     *
 *                                                                        *
 * Copyright (C) 2019 Simon M. Werner <simonwerner@gmail.com>             *
 *                                                                        *
 * This program is free software; you can redistribute it and/or modify   *
 * it under the terms of the GNU General Public License as published by   *
 * the Free Software Foundation, either version 3 of the License, or      *
 * (at your option) any later version.                                    *
 *                                                                        *
 * This program is distributed in the hope that it will be useful,        *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the           *
 * GNU General Public License for more details.                           *
 *                                                                        *
 * You should have received a copy of the GNU General Public License      *
 * along with this program. If not, see <http://www.gnu.org/licenses/>.   *
 *                                                                        *
 **************************************************************************/

// std
use std::fs::File;
use std::io::prelude::*;
use std::path;

// externs
use crate::hound;

// this crate
use crate::bitpack::ByteReader;
use crate::decoder;
use crate::error;
use crate::x3;

use error::X3Error;
use quick_xml::events::Event;
use quick_xml::Reader;

///
/// Convert an .x3a (X3 Archive) file to a .wav file.  
///
/// Note: the x3a can contain some meta data of the recording that may be lost, such as the time
///       of the recording and surplus XML payload data that has been embedded into the X3A header.
///
/// ### Arguments
///
/// * `x3a_filename` - the input X3A file to decode.
/// * `wav_filename` - the output wav file to write to.  It will be overwritten.
///
pub fn x3a_to_wav<P: AsRef<path::Path>>(x3a_filename: P, wav_filename: P) -> Result<(), X3Error> {
  let mut file = File::open(x3a_filename).unwrap();

  let mut buf = Vec::new();
  file.read_to_end(&mut buf).unwrap();
  let bytes = &mut ByteReader::new(&buf);
  let (sample_rate, params) = read_archive_header(bytes).expect("Invalid X3 Archive header");
  let (wav, num_errors) = decoder::decode_frames(bytes, &params)?;
  if num_errors > 0 {
    eprintln!("Encountered {} decoding errors", num_errors);
  }

  let spec = hound::WavSpec {
    channels: 1,
    sample_rate: sample_rate as u32,
    bits_per_sample: 16,
    sample_format: hound::SampleFormat::Int,
  };

  let mut writer = hound::WavWriter::create(wav_filename, spec)?;
  for w in wav {
    writer.write_sample(w)?;
  }

  Ok(())
}

///
/// Convert an .bin (x3 binary without archive details) file to a .wav file.  
///
/// ### Arguments
///
/// * `x3bin_filename` - the input x3 bin (.bin) file to decode.
/// * `wav_filename` - the output wav file to write to.  It will be overwritten.
///
/// ### Returns
///
/// * errors - The number of encoding errors encountered
///
pub fn x3bin_to_wav<P: AsRef<path::Path>>(x3bin_filename: P, wav_filename: P) -> Result<usize, X3Error> {
  let mut file = File::open(x3bin_filename).unwrap();

  let mut buf = Vec::new();
  file.read_to_end(&mut buf).unwrap();
  let bytes = &mut ByteReader::new(&buf);

  let (sample_rate, params) = read_header(bytes)?;

  let (wav, num_errors) = decoder::decode_frames(bytes, &params)?;
  if num_errors > 0 {
    eprintln!("Encountered {} decoding errors", num_errors);
  }

  let spec = hound::WavSpec {
    channels: 1,
    sample_rate: sample_rate as u32,
    bits_per_sample: 16,
    sample_format: hound::SampleFormat::Int,
  };

  // writer_u16 is faster than the plain writer
  let mut writer = hound::WavWriter::create(wav_filename, spec).unwrap();
  let mut writer_u16 = writer.get_i16_writer(wav.len() as u32);
  for w in wav {
    writer_u16.write_sample(w);
  }
  writer_u16.flush()?;

  Ok(num_errors)
}

///
/// Read the frame header to the ByteReader output.
///
fn read_header(bytes: &mut ByteReader) -> Result<(u32, x3::Parameters), X3Error> {
  // Move to the beginning of the next frame, this is helpful when we are reading the middle of
  // a stream.
  decoder::move_to_next_frame(bytes)?;

  let buf = &mut [0u8; x3::FrameHeader::HEADER_CRC_BYTE];
  bytes.read(buf)?;

  let sample_rate = 48000; // FIXME: Need to set this somehow else

  let params = x3::Parameters::default();

  Ok((sample_rate as u32, params))
}

///
/// Read <Archive Header> to the BitReader output.
///
fn read_archive_header(bytes: &mut ByteReader) -> Result<(u32, x3::Parameters), X3Error> {
  // <Archive Id>
  if !bytes.eq(x3::Archive::ID) {
    return Err(X3Error::ArchiveHeaderXMLInvalidKey);
  }
  bytes.inc_counter(x3::Archive::ID.len())?;

  // <XML MetaData>
  let (_, payload_size) = decoder::read_frame_header(bytes)?;

  // Get the payload
  let mut payload: Vec<u8> = vec![0; payload_size];
  bytes.read(&mut payload)?;

  let xml = String::from_utf8_lossy(&payload);

  let (sample_rate, params) = parse_xml(&xml)?;

  Ok((sample_rate, params))
}

///
/// Parse the XML header that contains the parameters for the wav output.
///
fn parse_xml(xml: &str) -> Result<(u32, x3::Parameters), X3Error> {
  let mut reader = Reader::from_str(xml);
  reader.trim_text(true);

  let mut buf = Vec::new();
  let mut fs = Vec::with_capacity(3);
  let mut bl = Vec::with_capacity(3);
  let mut codes = Vec::with_capacity(3);
  let mut th = Vec::with_capacity(3);

  // The `Reader` does not implement `Iterator` because it outputs borrowed data (`Cow`s)
  loop {
    match reader.read_event(&mut buf) {
      Ok(Event::Start(ref e)) => match e.name() {
        b"FS" => fs.push(reader.read_text(e.name(), &mut Vec::new()).unwrap()),
        b"BLKLEN" => bl.push(reader.read_text(e.name(), &mut Vec::new()).unwrap()),
        b"CODES" => codes.push(reader.read_text(e.name(), &mut Vec::new()).unwrap()),
        b"T" => th.push(reader.read_text(e.name(), &mut Vec::new()).unwrap()),
        _ => (),
      },
      Ok(Event::Eof) => break, // exits the loop when reaching end of file
      Err(e) => {
        println!(
          "Error reading X3 Archive header (XML) at position {}: {:?}",
          reader.buffer_position(),
          e
        );
        return Err(X3Error::ArchiveHeaderXMLInvalid);
      }
      _ => (), // There are several other `Event`s we do not consider here
    }

    // if we don't keep a borrow elsewhere, we can clear the buffer to keep memory usage low
    buf.clear();
  }
  println!("sample rate: {}", fs[0]);
  println!("block length: {}", bl[0]);
  println!("Rice codes: {}", codes[0]);
  println!("thresholds: {}", th[0]);

  let sample_rate = fs[0].parse::<u32>().unwrap();
  let block_len = bl[0].parse::<u32>().unwrap();
  let mut rice_code_ids = Vec::new();
  for word in codes[0].split(',') {
    match word {
      "RICE0" => rice_code_ids.push(0),
      "RICE1" => rice_code_ids.push(1),
      "RICE2" => rice_code_ids.push(2),
      "RICE3" => rice_code_ids.push(3),
      "BFP" => (),
      _ => return Err(X3Error::ArchiveHeaderXMLRiceCode),
    };
  }
  let thresholds: Vec<usize> = th[0].split(',').map(|s| s.parse::<usize>().unwrap()).collect();

  let mut rc_array: [usize; 3] = [0; 3];
  let mut th_array: [usize; 3] = [0; 3];

  #[allow(clippy::manual_memcpy)]
  for i in 0..3 {
    rc_array[i] = rice_code_ids[i];
    th_array[i] = thresholds[i];
  }
  let params = x3::Parameters::new(
    block_len as usize,
    x3::Parameters::DEFAULT_BLOCKS_PER_FRAME,
    rc_array,
    th_array,
  )?;

  Ok((sample_rate, params))
}

//
//
//            #######
//               #       ######     ####     #####     ####
//               #       #         #           #      #
//               #       #####      ####       #       ####
//               #       #              #      #           #
//               #       #         #    #      #      #    #
//               #       ######     ####       #       ####
//
//

#[cfg(test)]
mod tests {
//   use crate::decodefile::{x3a_to_wav, x3bin_to_wav};

//   #[test]
//   fn test_decode_bin_file() {
//     x3bin_to_wav("~/tmp/test.bin", "~/tmp/test.linux.wav").unwrap();
//   }

//   #[test]
//   fn test_decode_x3a_file() {
//     x3a_to_wav("~/tmp/test.x3a", "~/tmp/test.wav").unwrap();
//   }
}