This commit is contained in:
Jamie Hardt
2020-12-03 23:57:43 -08:00
6 changed files with 95 additions and 78 deletions

2
Cargo.lock generated
View File

@@ -2,7 +2,7 @@
# It is not intended for manual editing.
[[package]]
name = "bwavfile"
version = "0.1.5"
version = "0.1.6"
dependencies = [
"byteorder",
"encoding",

View File

@@ -1,6 +1,6 @@
[package]
name = "bwavfile"
version = "0.1.5"
version = "0.1.6"
authors = ["Jamie Hardt <jamiehardt@me.com>"]
edition = "2018"
license = "MIT"

View File

@@ -1,5 +1,5 @@
use std::io::{Read, Seek};
use std::io::SeekFrom::{Start,};
use std::io::SeekFrom::{Start,Current,};
use byteorder::LittleEndian;
use byteorder::ReadBytesExt;
@@ -7,7 +7,6 @@ use byteorder::ReadBytesExt;
use super::fmt::{WaveFmt};
use super::errors::Error;
use super::CommonFormat;
use super::raw_chunk_reader::RawChunkReader;
/// Read audio frames
///
@@ -15,12 +14,14 @@ use super::raw_chunk_reader::RawChunkReader;
/// bitstream having a format specified by `format`.
///
#[derive(Debug)]
pub struct AudioFrameReader<'a, R: Read + Seek> {
inner : RawChunkReader<'a,R>,
format: WaveFmt
pub struct AudioFrameReader<R: Read + Seek> {
inner : R,
format: WaveFmt,
start: u64,
length: u64
}
impl<'a, R: Read + Seek> AudioFrameReader<'a, R> {
impl<R: Read + Seek> AudioFrameReader<R> {
/// Create a new `AudioFrameReader`
///
@@ -30,16 +31,21 @@ impl<'a, R: Read + Seek> AudioFrameReader<'a, R> {
/// parameter to confirm the `block_alignment` law is fulfilled
/// and the format tag is readable by this implementation (only
/// format 0x01 is supported at this time.)
pub fn new(inner: RawChunkReader<'a, R>, format: WaveFmt) -> Self {
pub fn new(mut inner: R, format: WaveFmt, start: u64, length: u64) -> Result<Self, Error> {
assert!(format.block_alignment * 8 == format.bits_per_sample * format.channel_count,
"Unable to read audio frames from packed formats: block alignment is {}, should be {}",
format.block_alignment, (format.bits_per_sample / 8 ) * format.channel_count);
assert!(format.common_format() == CommonFormat::IntegerPCM ,
"Unsupported format tag {:?}", format.tag);
AudioFrameReader { inner , format }
inner.seek(Start(start))?;
Ok( AudioFrameReader { inner , format , start, length} )
}
/// Unwrap the inner reader.
pub fn into_inner(self) -> R {
self.inner
}
/// Locate the read position to a different frame
@@ -47,10 +53,13 @@ impl<'a, R: Read + Seek> AudioFrameReader<'a, R> {
/// Seeks within the audio stream.
///
/// Returns the new location of the read position.
///
/// locate() behaves similarly to Read methods in that
/// seeking after the end of the audio data is not an error.
pub fn locate(&mut self, to :u64) -> Result<u64,Error> {
let position = to * self.format.block_alignment as u64;
let seek_result = self.inner.seek(Start(position))?;
Ok( seek_result / self.format.block_alignment as u64 )
let seek_result = self.inner.seek(Start(self.start + position))?;
Ok( (seek_result - self.start) / self.format.block_alignment as u64 )
}
/// Create a frame buffer sized to hold frames of the reader
@@ -86,17 +95,22 @@ impl<'a, R: Read + Seek> AudioFrameReader<'a, R> {
let framed_bits_per_sample = self.format.block_alignment * 8 / self.format.channel_count;
for n in 0..(self.format.channel_count as usize) {
buffer[n] = match (self.format.bits_per_sample, framed_bits_per_sample) {
(0..=8,8) => self.inner.read_u8()? as i32 - 0x80_i32, // EBU 3285 §A2.2
(9..=16,16) => self.inner.read_i16::<LittleEndian>()? as i32,
(10..=24,24) => self.inner.read_i24::<LittleEndian>()?,
(25..=32,32) => self.inner.read_i32::<LittleEndian>()?,
(b,_)=> panic!("Unrecognized integer format, bits per sample {}, channels {}, block_alignment {}",
b, self.format.channel_count, self.format.block_alignment)
}
}
let tell = self.inner.seek(Current(0))?;
Ok( 1 )
if (tell - self.start) < self.length {
for n in 0..(self.format.channel_count as usize) {
buffer[n] = match (self.format.bits_per_sample, framed_bits_per_sample) {
(0..=8,8) => self.inner.read_u8()? as i32 - 0x80_i32, // EBU 3285 §A2.2
(9..=16,16) => self.inner.read_i16::<LittleEndian>()? as i32,
(10..=24,24) => self.inner.read_i24::<LittleEndian>()?,
(25..=32,32) => self.inner.read_i32::<LittleEndian>()?,
(b,_)=> panic!("Unrecognized integer format, bits per sample {}, channels {}, block_alignment {}",
b, self.format.channel_count, self.format.block_alignment)
}
}
Ok( 1 )
} else {
Ok( 0 )
}
}
}

View File

@@ -9,8 +9,8 @@ use std::io::{Seek,Read,Error,ErrorKind};
#[derive(Debug)]
pub struct RawChunkReader<'a, R: Read + Seek> {
reader: &'a mut R,
start: u64,
length: u64,
pub start: u64,
pub length: u64,
position: u64
}
@@ -23,10 +23,6 @@ impl<'a,R: Read + Seek> RawChunkReader<'a, R> {
position: 0
}
}
pub fn length(&self) -> u64 {
self.length
}
}
impl<'a, R:Read + Seek> Read for RawChunkReader<'_, R> {

View File

@@ -100,13 +100,13 @@ impl<R: Read + Seek> WaveReader<R> {
return self.inner;
}
/**
* Create an `AudioFrameReader` for reading each audio frame.
*/
pub fn audio_frame_reader(&mut self) -> Result<AudioFrameReader<R>, ParserError> {
///
/// Create an `AudioFrameReader` for reading each audio frame and consume the `WaveReader`.
///
pub fn audio_frame_reader(mut self) -> Result<AudioFrameReader<R>, ParserError> {
let format = self.format()?;
let audio_chunk_reader = self.chunk_reader(DATA_SIG, 0)?;
Ok(AudioFrameReader::new(audio_chunk_reader, format))
let audio_chunk_reader = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
Ok(AudioFrameReader::new(self.inner, format, audio_chunk_reader.0, audio_chunk_reader.1)?)
}
/**
@@ -166,35 +166,24 @@ impl<R: Read + Seek> WaveReader<R> {
/// Read iXML data.
///
/// If there are no iXML metadata present in the file,
/// Err(Error::ChunkMissing { "iXML" } will be returned.
pub fn ixml(&mut self, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
let ixml_sig: FourCC = FourCC::make(b"iXML");
let mut chunk = self.chunk_reader(ixml_sig, 0)?;
match chunk.read_to_end(buffer) {
Ok(read) => Ok(read),
Err(error) => Err(error.into())
}
/// Ok(0) will be returned.
pub fn read_ixml(&mut self, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
let ixml_fourcc = FourCC::make(b"iXML");
self.read_chunk(ixml_fourcc, 0, buffer)
}
/// Read AXML data.
///
/// By convention this will generally be ADM metadata.
///
/// If there are no iXML metadata present in the file,
/// Err(Error::ChunkMissing { "axml" } will be returned.
pub fn axml(&mut self, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
let axml_sig: FourCC = FourCC::make(b"axml");
let mut chunk = self.chunk_reader(axml_sig, 0)?;
match chunk.read_to_end(buffer) {
Ok(read) => Ok(read),
Err(error) => Err(error.into())
}
/// If there are no axml metadata present in the file,
/// Ok(0) will be returned
pub fn read_axml(&mut self, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
let axml_fourcc = FourCC::make(b"axml");
self.read_chunk(axml_fourcc, 0, buffer)
}
/**
* Validate file is readable.
*
@@ -220,6 +209,8 @@ impl<R: Read + Seek> WaveReader<R> {
* `Ok(())` if the source is `validate_readable()` AND
*
* - Contains _only_ a `fmt` chunk and `data` chunk, with no other chunks present
* - `fmt` chunk is exactly 16 bytes long and begins _exactly_ at file offset 12
* - `data` content begins _exactly_ at file offset 36
* - is not an RF64/BW64
*
* Some clients require a WAVE file to only contain format and data without any other
@@ -248,7 +239,7 @@ impl<R: Read + Seek> WaveReader<R> {
.into_chunk_list()?.iter().map(|c| c.signature ).collect();
if chunk_fourccs == vec![FMT__SIG, DATA_SIG] {
Ok(())
Ok(()) /* FIXME: finish implementation */
} else {
Err( ParserError::NotMinimalWaveFile )
}
@@ -339,6 +330,21 @@ impl<R:Read+Seek> WaveReader<R> { /* Private Implementation */
Ok( RawChunkReader::new(&mut self.inner, start, length) )
}
fn read_chunk(&mut self, ident: FourCC, at: u32, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
let result = self.chunk_reader(ident, at);
match result {
Ok(mut chunk) => {
match chunk.read_to_end(buffer) {
Ok(read) => Ok(read),
Err(err) => Err(err.into())
}
},
Err(ParserError::ChunkMissing { signature : _} ) => Ok(0),
Err( any ) => Err(any.into())
}
}
fn get_chunk_extent_at_index(&mut self, fourcc: FourCC, index: u32) -> Result<(u64,u64), ParserError> {
let p = Parser::make(&mut self.inner)?.into_chunk_list()?;

View File

@@ -81,7 +81,7 @@ fn test_minimal_wave() {
fn test_read() {
let path = "tests/media/audacity_16bit.wav";
let mut w = WaveReader::open(path).expect("Failure opening test file");
let w = WaveReader::open(path).expect("Failure opening test file");
let mut reader = w.audio_frame_reader().unwrap();
@@ -99,7 +99,7 @@ fn test_read() {
fn test_locate_multichannel_read() {
let path = "tests/media/ff_pink.wav";
let mut w = WaveReader::open(path).expect("Failure opening test file");
let w = WaveReader::open(path).expect("Failure opening test file");
let mut reader = w.audio_frame_reader().unwrap();
@@ -158,21 +158,22 @@ fn test_channels_stereo_no_fmt_extended() {
assert_eq!(channels[1].speaker,ChannelMask::FrontRight);
}
// THis is me playing around trying to work on #6 and #7
//
// #[test]
// fn test_sample_reader_type() {
// // Issue #6
// use bwavfile::WaveFmt;
// use bwavfile::AudioFrameReader;
//See issue 6 and 7
#[test]
fn test_frame_reader_consumes_reader() {
// Issue #6
use bwavfile::WaveFmt;
use bwavfile::AudioFrameReader;
use std::fs::File;
fn from_wav_filename(wav_filename: &str) -> Result<(WaveFmt, AudioFrameReader<File>), ()> {
if let Ok(mut r) = WaveReader::open(&wav_filename) {
let format = r.format().unwrap();
let frame_reader = r.audio_frame_reader().unwrap();
Ok((format, frame_reader))
} else {
Err(())
}
}
// fn from_wav_filename<'a>(wav_filename: &str) -> Result<(WaveReader<std::fs::File>, WaveFmt, AudioFrameReader<'a, std::fs::File>), ()> {
// if let Ok(mut r) = WaveReader::open(&wav_filename) {
// let format = r.format().unwrap();
// let frame_reader = r.audio_frame_reader().unwrap();
// Ok((r, format, frame_reader))
// } else {
// Err(())
// }
// }
// }
let _result = from_wav_filename("tests/media/pt_24bit_stereo.wav").unwrap();
}