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
//! This is a crate for reading in and writing out wave files. It supports uncompressed PCM bit
//! depths of 8, 16, 24 bits, and 32bit IEEE Float formats, both with any number of channels.
//! Unfortunately other types of data format (e.g. compressed WAVE files) are not supported. There
//! is also no support for any metadata chunks or any chunks other than the `"fmt "` and `"data"`
//! chunks.
//!
//! ## Example
//!
//! ```rust
//! # fn main() -> std::io::Result<()> {
//! use std::fs::File;
//! use std::path::Path;
//!
//! let mut inp_file = File::open(Path::new("data/sine.wav"))?;
//! let (header, data) = wav::read(&mut inp_file)?;
//!
//! let mut out_file = File::create(Path::new("data/output.wav"))?;
//! wav::write(header, &data, &mut out_file)?;
//! # Ok(())
//! # }
//! ```

#![warn(missing_docs)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]

use std::{
    convert::TryFrom,
    io::{self, Read, Write},
};

pub mod header;
pub use header::{Header, WAV_FORMAT_IEEE_FLOAT, WAV_FORMAT_PCM};

pub mod bit_depth;
pub use bit_depth::BitDepth;

mod tuple_iterator;
use tuple_iterator::{PairIter, QuadrupletIter, TripletIter};

/// Reads in the given `reader` and attempts to extract the audio data and header from it.
///
/// ## Errors
///
/// This function fails under the following circumstances:
///
/// * Any error occurring from the `reader` parameter during reading.
/// * The data isn't RIFF data.
/// * The wave header specifies a compressed data format.
/// * The wave header specifies an unsupported bit-depth.
/// * The wave data is malformed, or otherwise couldn't be parsed into samples.
#[allow(clippy::similar_names)]
pub fn read<R>(reader: &mut R) -> io::Result<(Header, BitDepth)>
where
    R: Read + io::Seek,
{
    let header = read_header(reader)?;
    Ok((header, read_data(reader, &header)?))
}

/// Writes the given wav data to the given `writer`.
///
/// ## Notes
///
/// Although `track` is a borrowed value, its contents will be formatted into an owned `Vec<u8>` so
/// that it can be written to the `writer` through [`riff::ChunkContents::write`].
///
/// ## Errors
///
/// This function fails under the following circumstances:
///
/// * Any error occurring from the `writer` parameter during writing.
/// * The given [`BitDepth`] is [`BitDepth::Empty`].
pub fn write<W>(header: Header, track: &BitDepth, writer: &mut W) -> std::io::Result<()>
where
    W: Write + io::Seek,
{
    const WAVE_ID: riff::ChunkId = riff::ChunkId {
        value: [b'W', b'A', b'V', b'E'],
    };
    const HEADER_ID: riff::ChunkId = riff::ChunkId {
        value: [b'f', b'm', b't', b' '],
    };
    const DATA_ID: riff::ChunkId = riff::ChunkId {
        value: [b'd', b'a', b't', b'a'],
    };

    let h_vec: [u8; 16] = header.into();
    let h_dat = riff::ChunkContents::Data(HEADER_ID, Vec::from(h_vec));

    let d_vec = match track {
        BitDepth::Eight(v) => v.clone(),
        BitDepth::Sixteen(v) => v
            .iter()
            .flat_map(|s| {
                let v = s.to_le_bytes();
                PairIter::new((v[0], v[1]))
            })
            .collect::<Vec<_>>(),
        BitDepth::TwentyFour(v) => v
            .iter()
            .flat_map(|s| {
                let v = s.to_le_bytes().split_at(1).1.to_owned();
                TripletIter::new((v[0], v[1], v[2]))
            })
            .collect::<Vec<_>>(),
        BitDepth::ThirtyTwoFloat(v) => v
            .iter()
            .flat_map(|s| {
                let v = s.to_le_bytes().to_owned();
                QuadrupletIter::new((v[0], v[1], v[2], v[3]))
            })
            .collect::<Vec<_>>(),
        _ => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "Empty audio data given",
            ))
        }
    };
    let d_dat = riff::ChunkContents::Data(DATA_ID, d_vec);

    let r = riff::ChunkContents::Children(riff::RIFF_ID.clone(), WAVE_ID, vec![h_dat, d_dat]);

    r.write(writer)?;

    Ok(())
}

#[allow(clippy::similar_names)]
fn read_header<R>(reader: &mut R) -> io::Result<Header>
where
    R: Read + io::Seek,
{
    let wav = verify_wav_file(reader)?;

    for c in wav.iter(reader) {
        if c.id().as_str() == "fmt " {
            // Read header contents
            let header_bytes = c.read_contents(reader)?;
            let header = Header::try_from(header_bytes.as_slice())
                .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;

            // Return error if not using PCM
            match header.audio_format {
                WAV_FORMAT_PCM | WAV_FORMAT_IEEE_FLOAT => return Ok(header),
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Unsupported data format, data is not in uncompressed PCM format, aborting",
                    ))
                }
            };
        }
    }

    Err(io::Error::new(
        io::ErrorKind::InvalidData,
        "RIFF data is missing the \"fmt \" chunk, aborting",
    ))
}

#[allow(clippy::similar_names)]
fn read_data<R>(reader: &mut R, header: &Header) -> io::Result<BitDepth>
where
    R: Read + io::Seek,
{
    let wav = verify_wav_file(reader)?;

    for c in wav.iter(reader) {
        if c.id().as_str() == "data" {
            // Read data contents
            let data_bytes = c.read_contents(reader)?;

            let wav_data = match header.audio_format {
                WAV_FORMAT_PCM => match header.bits_per_sample {
                    8 => Ok(BitDepth::Eight(data_bytes)),
                    16 => Ok(BitDepth::Sixteen({
                        let mut tmpv = Vec::with_capacity(data_bytes.len() / 2);
                        tmpv.extend(
                            data_bytes
                                .chunks_exact(2)
                                .map(|i| i16::from_le_bytes([i[0], i[1]])),
                        );
                        tmpv
                    })),
                    24 => Ok(BitDepth::TwentyFour({
                        let mut tmpv = Vec::with_capacity(data_bytes.len() / 3);
                        tmpv.extend(
                            data_bytes
                                .chunks_exact(3)
                                .map(|i| i32::from_le_bytes([0, i[0], i[1], i[2]])),
                        );
                        tmpv
                    })),
                    _ => Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Unsupported PCM bit depth",
                    )),
                },
                WAV_FORMAT_IEEE_FLOAT => match header.bits_per_sample {
                    32 => Ok(BitDepth::ThirtyTwoFloat({
                        let mut tmpv = Vec::with_capacity(data_bytes.len() / 4);
                        tmpv.extend(
                            data_bytes
                                .chunks_exact(4)
                                .map(|f| f32::from_le_bytes([f[0], f[1], f[2], f[3]])),
                        );
                        tmpv
                    })),
                    _ => Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Unsupported IEEE Float bit depth",
                    )),
                },
                _ => Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Unsupported WAV format",
                )),
            };

            return wav_data;
        }
    }

    Err(io::Error::new(
        io::ErrorKind::Other,
        "Could not parse audio data",
    ))
}

fn verify_wav_file<R>(reader: &mut R) -> io::Result<riff::Chunk>
where
    R: Read + io::Seek,
{
    let wav = riff::Chunk::read(reader, 0)?;

    let form_type = wav.read_type(reader)?;

    if form_type.as_str() == "WAVE" {
        Ok(wav)
    } else {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "RIFF file type not \"WAVE\"",
        ))
    }
}