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
//! # WAV
//!
//! This is a crate for reading in and writing out wave files. It supports bit-
//! depths of 8, 16, and 24 bits, any number of channels, and uncompressed PCM
//! data. 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(())
//! # }
//! ```

#![deny(broken_intra_doc_links)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]

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

pub mod header;
pub use header::Header;

pub mod bit_depth;
pub use bit_depth::BitDepth;

mod tuple_iterator;
use tuple_iterator::{PairIter, 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.
pub fn read<R>(reader: &mut R) -> io::Result<(Header, BitDepth)>
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" {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            "RIFF file type not \"WAVE\"",
        ));
    }

    let mut head = Header::default();
    let mut head_filled = false;

    let chunks: Vec<_> = wav.iter(reader).collect();

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

            // Return error if not using PCM
            if head.audio_format != 1 {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Unsupported data format, data is not in uncompressed PCM format, aborting",
                ));
            }

            head_filled = true;
            break;
        }
    }

    if !head_filled {
        return Err(
            io::Error::new(
                io::ErrorKind::InvalidData,
                "RIFF data is missing the \"fmt \" chunk, aborting"
            )
        );
    }

    let mut data = BitDepth::default();

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

            data = match head.bits_per_sample {
                8 => BitDepth::Eight(data_bytes.clone()),
                16 => BitDepth::Sixteen(data_bytes.chunks_exact(2).map(|i| i16::from_le_bytes([i[0], i[1]])).collect()),
                24 => BitDepth::TwentyFour(data_bytes.chunks_exact(3).map(|i| i32::from_le_bytes([0, i[0], i[1], i[2]])).collect()),
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Unsupported bit depth",
                    ))
                }
            }
        }
    }

    if data == BitDepth::Empty {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            "Could not parse audio data",
        ));
    }

    Ok((head, data))
}

/// 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::write_chunk`][0].
///
/// ## Errors
///
/// This function fails under the following circumstances:
/// * Any error occurring from the `writer` parameter during writing.
/// * The given BitDepth is `BitDepth::Empty`.
///
/// [0]: riff::write_chunk
pub fn write<W>(header: Header, track: &BitDepth, writer: &mut W) -> std::io::Result<()>
where
    W: Write + io::Seek
{
    let w_id = riff::ChunkId::new("WAVE").unwrap();

    let h_id = riff::ChunkId::new("fmt ").unwrap();
    let h_vec: [u8; 16] = header.into();
    let h_dat = riff::ChunkContents::Data(h_id, Vec::from(&h_vec[0..16]));

    let d_id = riff::ChunkId::new("data").unwrap();
    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<_>>(),
        _ => return Err(
            std::io::Error::new(
                std::io::ErrorKind::Other,
                "Empty audio data given",
            )
        ),
    };
    let d_dat = riff::ChunkContents::Data(d_id, d_vec);

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

    r.write(writer)?;

    Ok(())
}