56 Commits

Author SHA1 Message Date
Jamie Hardt
e502913f4f Updated readme 2020-12-10 18:11:48 -08:00
Jamie Hardt
4890483dcd Cue lists implemented 2020-12-10 18:09:28 -08:00
Jamie Hardt
8519854596 Cue lists in progress
Need to clean up zero-terminated strings in adtl
2020-12-10 14:48:25 -08:00
Jamie Hardt
c947904d0f Cue point implementation 2020-12-10 12:26:49 -08:00
Jamie Hardt
2323d61ee9 Added test media from izotope RX Editor 2020-12-09 20:35:06 -08:00
Jamie Hardt
60af2f43ff Update README.md 2020-12-06 12:16:49 -08:00
Jamie Hardt
eb431f865f Update README.md 2020-12-06 11:47:53 -08:00
Jamie Hardt
8b049e4245 Chanegd reader interface
broadcast_extension returns an Option<> now
2020-12-04 22:22:40 -08:00
Jamie Hardt
dfe90fba4a Documentation 2020-12-04 22:11:25 -08:00
Jamie Hardt
b2d4bff28b Update lib.rs 2020-12-04 20:39:58 -08:00
Jamie Hardt
79173b0576 Update README.md 2020-12-04 20:39:04 -08:00
Jamie Hardt
e15e36d65d Update README.md 2020-12-04 20:35:39 -08:00
Jamie Hardt
1dc5f153b0 Update README.md 2020-12-04 20:34:08 -08:00
Jamie Hardt
7a9f9c8bb3 Update README.md
Roadmap updates to "Features"
2020-12-04 20:33:30 -08:00
Jamie Hardt
0dd7ee4d18 Merge branch 'master' of https://github.com/iluvcapra/bwavfile 2020-12-03 23:57:43 -08:00
Jamie Hardt
a213e748db Sampler resources 2020-12-03 23:47:41 -08:00
Jamie Hardt
d221629b3e More notes on things to do 2020-12-02 22:39:02 -08:00
Jamie Hardt
2fcb211a67 Docs 2020-12-02 22:28:33 -08:00
Jamie Hardt
dfe513b596 iXML and axml cleanup impl 2020-12-02 22:27:14 -08:00
Jamie Hardt
7e1c368862 Nudged version 2020-12-02 21:45:40 -08:00
Jamie Hardt
8985361029 AudioFrameReader consumes the file of WaveReader 2020-12-02 21:36:50 -08:00
Jamie Hardt
e23529e7b6 Note 2020-12-02 17:05:03 -08:00
Jamie Hardt
538aedd413 Playing with comment 2020-12-02 12:52:58 -08:00
Jamie Hardt
09a9413ff2 Changed audio_frame_reader interface
to hide RawChunkReader
2020-12-02 12:21:20 -08:00
Jamie Hardt
016f5e3e3b Update wavereader.rs
Fixed typo
2020-11-29 14:06:16 -08:00
Jamie Hardt
11b834be76 Update fmt.rs
Documentation
2020-11-29 14:04:52 -08:00
Jamie Hardt
a4ded50112 Merge branch 'master' of https://github.com/iluvcapra/bwavfile 2020-11-28 16:36:59 -08:00
Jamie Hardt
9b2a9783a0 Updated Cargo.toml 2020-11-28 16:35:55 -08:00
Jamie Hardt
1e53436d4b Update README.md 2020-11-28 15:57:34 -08:00
Jamie Hardt
a9d9081fad Update README.md 2020-11-28 15:55:12 -08:00
Jamie Hardt
c43144c9db Update README.md 2020-11-28 15:53:53 -08:00
Jamie Hardt
082a8596af Made changes to eliminate warnings 2020-11-28 11:30:21 -08:00
Jamie Hardt
208aa7f064 Fixed typo 2020-11-28 11:24:05 -08:00
Jamie Hardt
69da33b3dc Renamed axml method 2020-11-28 11:01:50 -08:00
Jamie Hardt
9cbb2664d4 axml and iXML access methods 2020-11-27 22:47:48 -08:00
Jamie Hardt
a4c4936665 Fixed thinko in documentation 2020-11-27 22:32:55 -08:00
Jamie Hardt
5f69ec8c61 Nudged version 0.1.5 2020-11-27 22:14:52 -08:00
Jamie Hardt
ac6bd9c1e8 Added tests for channel info 2020-11-27 22:10:01 -08:00
Jamie Hardt
010f261598 Channel descriptor implementation 2020-11-27 22:03:54 -08:00
Jamie Hardt
b40e8edf23 Have created read tests 2020-11-27 21:42:53 -08:00
Jamie Hardt
3c221bce40 Update common_format.rs 2020-11-23 23:15:27 -08:00
Jamie Hardt
883b6c73e8 Documentation 2020-11-23 22:56:46 -08:00
Jamie Hardt
5bd292e964 Bumped version 2020-11-23 22:39:08 -08:00
Jamie Hardt
34e473dc49 Implementation of complex formats 2020-11-23 22:38:10 -08:00
Jamie Hardt
358aa06f7c Removed validation methods
and added to main implementation
2020-11-23 13:16:28 -08:00
Jamie Hardt
8191eedf14 ADM anc channel structures 2020-11-23 11:11:12 -08:00
Jamie Hardt
521e9d0670 Reorganized source, comments 2020-11-23 00:23:17 -08:00
Jamie Hardt
dea68662f8 Comments and documentation 2020-11-22 23:32:25 -08:00
Jamie Hardt
0685e7baca Removed dead line 2020-11-22 22:38:53 -08:00
Jamie Hardt
123d971624 Comments 2020-11-22 22:38:47 -08:00
Jamie Hardt
f410cda9ed removed .DS_Store 2020-11-22 22:15:58 -08:00
Jamie Hardt
cf06b50fea Comment 2020-11-22 22:04:04 -08:00
Jamie Hardt
e8d679b725 Merge branch 'master' of https://github.com/iluvcapra/bwavfile 2020-11-22 22:02:50 -08:00
Jamie Hardt
e63ab6bffd Renamed some files 2020-11-22 22:02:45 -08:00
Jamie Hardt
271da75f90 Update ffprobe_media_tests.rs 2020-11-22 22:01:11 -08:00
Jamie Hardt
6c393d9958 Restructred test files 2020-11-22 21:36:40 -08:00
27 changed files with 1522 additions and 417 deletions

9
Cargo.lock generated
View File

@@ -2,11 +2,12 @@
# It is not intended for manual editing.
[[package]]
name = "bwavfile"
version = "0.1.3"
version = "0.1.7"
dependencies = [
"byteorder",
"encoding",
"serde_json",
"uuid",
]
[[package]]
@@ -107,3 +108,9 @@ dependencies = [
"ryu",
"serde",
]
[[package]]
name = "uuid"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fde2f6a4bea1d6e007c4ad38c6839fa71cbb63b6dbf5b595aa38dc9b1093c11"

View File

@@ -1,6 +1,6 @@
[package]
name = "bwavfile"
version = "0.1.3"
version = "0.1.7"
authors = ["Jamie Hardt <jamiehardt@me.com>"]
edition = "2018"
license = "MIT"
@@ -16,4 +16,9 @@ keywords = ["audio", "broadcast", "multimedia","smpte"]
[dependencies]
byteorder = "1.3.4"
encoding = "0.2.33"
serde_json = "1.0.59"
serde_json = "1.0.59"
uuid = "0.8.1"
[profile.release]
debug = true

View File

@@ -6,11 +6,27 @@
# bwavfile
Rust Wave File Reader/Writer with Broadcast-WAV, MBWF and RF64 Support
This is currently a work-in-progress!
### Features
This is currently a work-in-progress! However many features presently work:
- [x] Read standard WAV, Broadcast-Wave, and 64-bit RF64 and BW64 wave files with one interface for
all types with transparent format detection.
- [ ] Wave/RF64 file writing with transparent promotion from WAV to RF64.
- [x] Unified format definition interface for standard and extended-format wave files.
- [x] Read channel/speaker map metadata.
- [x] Read standard EBU Broadcast-Wave metadata and decode to fields, including timestamp and SMPTE UMID.
- [x] iXML and ADM XML metadata.
- [ ] Broadcast-WAV Level and Quality metadata.
- [x] Cue list metadata.
- [ ] Sampler and instrument metadata.
- [x] Validate the compatibility of a given wave file for certain regimes.
- [x] Metadata support for ambisonic B-format.
## Use Examples
### Reading a File
### Reading Audio Frames From a File
```rust
@@ -30,6 +46,21 @@ This is currently a work-in-progress!
assert_eq!(read, 1);
```
### Accessing Channel Descriptions
```rust
use bwavfile::{WaveReader, ChannelMask};
let mut f = WaveReader::open("tests/media/pt_24bit_51.wav").unwrap();
let chans = f.channels().unwrap();
assert_eq!(chans[0].index, 0);
assert_eq!(chans[0].speaker, ChannelMask::FrontLeft);
assert_eq!(chans[3].index, 3);
assert_eq!(chans[3].speaker, ChannelMask::LowFrequency);
assert_eq!(chans[4].speaker, ChannelMask::BackLeft);
```
## Note on Testing
All of the media for the integration tests is committed to the respository

View File

@@ -1,39 +1,93 @@
use std::io::{Read, Seek};
use std::io::SeekFrom::{Start,};
use std::io::SeekFrom::{Start,Current,};
use byteorder::LittleEndian;
use byteorder::ReadBytesExt;
use super::chunks::WaveFmt;
use super::fmt::{WaveFmt};
use super::errors::Error;
use super::CommonFormat;
/// Read audio frames
///
/// The inner reader is interpreted as a raw audio data
/// bitstream having a format specified by `format`.
///
#[derive(Debug)]
pub struct AudioFrameReader<R: Read + Seek> {
inner : R,
format: WaveFmt
format: WaveFmt,
start: u64,
length: u64
}
impl<R: Read + Seek> AudioFrameReader<R> {
/// Create a new AudioFrameReader, taking possession of a reader.
pub fn new(inner: R, format: WaveFmt) -> Self {
/// Create a new `AudioFrameReader`
///
/// ### Panics
///
/// This method does a few sanity checks on the provided format
/// 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(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.tag == 1, "Unsupported format tag {}", format.tag);
AudioFrameReader { inner , format }
assert!(format.common_format() == CommonFormat::IntegerPCM ,
"Unsupported format tag {:?}", format.tag);
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
///
/// 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
///
/// This is a conveneince method that creates a `Vec<i32>` with
/// as many elements as there are channels in the underlying stream.
pub fn create_frame_buffer(&self) -> Vec<i32> {
vec![0i32; self.format.channel_count as usize]
}
/// Read a frame
///
/// A single frame is read from the audio stream and the read location
/// is advanced one frame.
///
/// Regardless of the number of bits in the audio sample, this method
/// always writes `i32` samples back to the buffer. These samples are
/// written back "right-aligned" so samples that are shorter than i32
/// will leave the MSB bits empty.
///
/// For example: A full-code sample in 16 bit (0xFFFF) will be written
/// back to the buffer as 0x0000FFFF.
///
///
/// ### Panics
///
/// The `buffer` must have a number of elements equal to the number of
/// channels and this method will panic if this is not the case.
pub fn read_integer_frame(&mut self, buffer:&mut [i32]) -> Result<u64,Error> {
assert!(buffer.len() as u16 == self.format.channel_count,
"read_integer_frame was called with a mis-sized buffer, expected {}, was {}",
@@ -41,18 +95,22 @@ impl<R: Read + Seek> AudioFrameReader<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))?;
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 )
}
Ok( 1 )
}
}
}

82
src/bext.rs Normal file
View File

@@ -0,0 +1,82 @@
pub type LU = f32;
pub type LUFS = f32;
pub type Decibels = f32;
/**
* Broadcast-WAV metadata record.
*
* The `bext` record contains information about the original recording of the
* Wave file, including a longish (256 ASCII chars) description field,
* originator identification fields, creation calendar date and time, a
* sample-accurate recording time field, and a SMPTE UMID.
*
* For a Wave file to be a complaint "Broadcast-WAV" file, it must contain
* a `bext` metadata record.
*
* For reference on the structure and use of the BEXT record
* check out [EBU Tech 3285](https://tech.ebu.ch/docs/tech/tech3285.pdf).
*/
#[derive(Debug)]
pub struct Bext {
/// 256 ASCII character field with free text.
pub description: String,
/// Originating application.
pub originator: String,
/// Application-specific UID.
pub originator_reference: String,
/// Creation date in format `YYYY-MM-DD`.
pub origination_date: String,
/// Creation time in format `HH:MM:SS`.
pub origination_time: String,
/// Time of the start of this wave file, expressed as the number of samples
/// since local midnight.
pub time_reference: u64,
/// Bext chunk version.
///
/// Version 1 contains a UMID, version 2 contains a UMID and
/// loudness metadata.
pub version: u16,
/// SMPTE 330M UMID
///
///
/// This field is `None` if the version is less than 1.
pub umid: Option<[u8; 64]>,
/// Integrated loudness in LUFS.
///
/// This field is `None` if the version is less than 2.
pub loudness_value: Option<LUFS>,
/// Loudness range in LU.
///
/// This field is `None` if the version is less than 2.
pub loudness_range: Option<LU>,
/// Maximum True Peak Level in decibels True Peak.
///
/// This field is `None` if the version is less than 2.
pub max_true_peak_level: Option<Decibels>,
/// Maximum momentary loudness in LUFS.
///
/// This field is `None` if the version is less than 2.
pub max_momentary_loudness: Option<LUFS>,
/// Maximum short-term loudness in LUFS.
///
/// This field is `None` if the version is less than 2.
pub max_short_term_loudness: Option<LUFS>,
// 180 bytes of nothing
/// Coding History.
pub coding_history: String
}

View File

@@ -1,7 +1,5 @@
use std::io::{Read, Write};
use super::errors::Error as ParserError;
use encoding::{DecoderTrap, EncoderTrap};
use encoding::{Encoding};
use encoding::all::ASCII;
@@ -9,180 +7,11 @@ use encoding::all::ASCII;
use byteorder::LittleEndian;
use byteorder::{ReadBytesExt, WriteBytesExt};
/**
* References:
* - http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
*/
#[derive(PartialEq)]
enum FormatTags {
Integer = 0x0001,
Float = 0x0003,
Extensible = 0xFFFE
}
use uuid::Uuid;
const PCM_SUBTYPE_UUID: [u8; 16] = [0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x10,
0x80, 0x00, 0x00, 0xaa,
0x00, 0x38, 0x9b, 0x71];
const FLOAT_SUBTYPE_UUID: [u8; 16] = [0x00, 0x00, 0x00, 0x03,
0x00, 0x00, 0x00, 0x10,
0x80, 0x00, 0x00, 0xaa,
0x00, 0x38, 0x9b, 0x71];
/*
https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/subformat-guids-for-compressed-audio-formats
http://dream.cs.bath.ac.uk/researchdev/wave-ex/bformat.html
These are from http://dream.cs.bath.ac.uk/researchdev/wave-ex/mulchaud.rtf
*/
#[derive(Debug)]
pub enum WaveFmtExtendedChannelMask {
FrontLeft = 0x1,
FrontRight = 0x2,
FrontCenter = 0x4,
LowFrequency = 0x8,
BackLeft = 0x10,
BackRight = 0x20,
FrontCenterLeft = 0x40,
FrontCenterRight = 0x80,
BackCenter = 0x100,
SideLeft = 0x200,
SideRight = 0x400,
TopCenter = 0x800,
TopFrontLeft = 0x1000,
TopFrontCenter = 0x2000,
TopFrontRight = 0x4000,
TopBackLeft = 0x8000,
TopBackCenter = 0x10000,
TopBackRight = 0x20000
}
/**
* Extended Wave Format
*
* https://docs.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible
*/
#[derive(Debug)]
pub struct WaveFmtExtended {
/// Valid bits per sample
pub valid_bits_per_sample : u16,
/// Channel mask
///
/// Identifies the speaker assignment for each channel in the file
pub channel_mask : WaveFmtExtendedChannelMask,
/// Codec GUID
///
/// Identifies the codec of the audio stream
pub type_guid : [u8; 16],
}
/**
* WAV file data format record.
*
* The `fmt` record contains essential information describing the binary
* structure of the data segment of the WAVE file, such as sample
* rate, sample binary format, channel count, etc.
*
*/
#[derive(Debug)]
pub struct WaveFmt {
/// A tag identifying the codec in use.
///
/// If this is 0xFFFE, the codec will be identified by a GUID
/// in `extended_format`
pub tag: u16,
/// Count of audio channels in each frame
pub channel_count: u16,
/// Sample rate of the audio data
pub sample_rate: u32,
/// Count of bytes per second
///
/// By rule, this is `block_alignment * sample_rate`
pub bytes_per_second: u32,
/// Count of bytes per audio frame
///
/// By rule, this is `channel_count * bits_per_sample / 8`
pub block_alignment: u16,
/// Count of bits stored in the file per sample
pub bits_per_sample: u16,
/// Extended format description
///
/// Additional format metadata if `channel_count` is greater than 2,
/// or if certain codecs are used.
pub extended_format: Option<WaveFmtExtended>
}
impl WaveFmt {
/// Create a new integer PCM format `WaveFmt`
pub fn new_pcm(sample_rate: u32, bits_per_sample: u16, channel_count: u16) -> Self {
let container_bits_per_sample = bits_per_sample + (bits_per_sample % 8);
let container_bytes_per_sample= container_bits_per_sample / 8;
let tag :u16 = match channel_count {
0 => panic!("Error"),
1..=2 => FormatTags::Integer as u16,
_ => FormatTags::Extensible as u16,
};
WaveFmt {
tag,
channel_count,
sample_rate,
bytes_per_second: container_bytes_per_sample as u32 * sample_rate * channel_count as u32,
block_alignment: container_bytes_per_sample * channel_count,
bits_per_sample: container_bits_per_sample,
extended_format: None
}
}
}
/**
* Broadcast-WAV metadata record.
*
* The `bext` record contains information about the original recording of the
* Wave file, including a longish (256 ASCII chars) description field,
* originator identification fields, creation calendar date and time, a
* sample-accurate recording time field, and a SMPTE UMID.
*
* For a Wave file to be a complaint "Broadcast-WAV" file, it must contain
* a `bext` metadata record.
*
* For reference on the structure and use of the BEXT record
* check out [EBU Tech 3285](https://tech.ebu.ch/docs/tech/tech3285.pdf).
*/
#[derive(Debug)]
pub struct Bext {
pub description: String,
pub originator: String,
pub originator_reference: String,
pub origination_date: String,
pub origination_time: String,
pub time_reference: u64,
pub version: u16,
pub umid: Option<[u8; 64]>,
pub loudness_value: Option<f32>,
pub loudness_range: Option<f32>,
pub max_true_peak_level: Option<f32>,
pub max_momentary_loudness: Option<f32>,
pub max_short_term_loudness: Option<f32>,
// 180 bytes of nothing
pub coding_history: String
}
use super::errors::Error as ParserError;
use super::fmt::{WaveFmt, WaveFmtExtended};
use super::bext::Bext;
pub trait ReadBWaveChunks: Read {
fn read_bext(&mut self) -> Result<Bext, ParserError>;
@@ -198,7 +27,7 @@ pub trait WriteBWaveChunks: Write {
impl<T> WriteBWaveChunks for T where T: Write {
fn write_wave_fmt(&mut self, format : &WaveFmt) -> Result<(), ParserError> {
self.write_u16::<LittleEndian>(format.tag)?;
self.write_u16::<LittleEndian>(format.tag as u16 )?;
self.write_u16::<LittleEndian>(format.channel_count)?;
self.write_u32::<LittleEndian>(format.sample_rate)?;
self.write_u32::<LittleEndian>(format.bytes_per_second)?;
@@ -258,14 +87,34 @@ impl<T> WriteBWaveChunks for T where T: Write {
impl<T> ReadBWaveChunks for T where T: Read {
fn read_wave_fmt(&mut self) -> Result<WaveFmt, ParserError> {
let tag_value : u16;
Ok(WaveFmt {
tag: self.read_u16::<LittleEndian>()?,
tag: {
tag_value = self.read_u16::<LittleEndian>()?;
tag_value
},
channel_count: self.read_u16::<LittleEndian>()?,
sample_rate: self.read_u32::<LittleEndian>()?,
bytes_per_second: self.read_u32::<LittleEndian>()?,
block_alignment: self.read_u16::<LittleEndian>()?,
bits_per_sample: self.read_u16::<LittleEndian>()?,
extended_format: None
extended_format: {
if tag_value == 0xFFFE {
let cb_size = self.read_u16::<LittleEndian>()?;
assert!(cb_size >= 22, "Format extension is not correct size");
Some(WaveFmtExtended {
valid_bits_per_sample: self.read_u16::<LittleEndian>()?,
channel_mask: self.read_u32::<LittleEndian>()?,
type_guid: {
let mut buf : [u8; 16] = [0; 16];
self.read_exact(&mut buf)?;
Uuid::from_slice(&buf)?
}
})
} else {
None
}
}
})
}
@@ -315,11 +164,36 @@ impl<T> ReadBWaveChunks for T where T: Read {
if version > 1 { Some(val) } else { None }
},
coding_history: {
for _ in 0..=180 { self.read_u8()?; }
for _ in 0..180 { self.read_u8()?; }
let mut buf = vec![];
self.read_to_end(&mut buf)?;
ASCII.decode(&buf, DecoderTrap::Ignore).expect("Error decoding text")
}
})
}
}
#[test]
fn test_read_51_wav() {
use super::fmt::ChannelMask;
use super::common_format::CommonFormat;
let path = "tests/media/pt_24bit_51.wav";
let mut w = super::wavereader::WaveReader::open(path).unwrap();
let format = w.format().unwrap();
assert_eq!(format.tag, 0xFFFE);
assert_eq!(format.channel_count, 6);
assert_eq!(format.sample_rate, 48000);
let extended = format.extended_format.unwrap();
assert_eq!(extended.valid_bits_per_sample, 24);
let channels = ChannelMask::channels(extended.channel_mask, format.channel_count);
assert_eq!(channels, [ChannelMask::FrontLeft, ChannelMask::FrontRight,
ChannelMask::FrontCenter, ChannelMask::LowFrequency,
ChannelMask::BackLeft, ChannelMask::BackRight]);
assert_eq!(format.common_format(), CommonFormat::IntegerPCM);
}

99
src/common_format.rs Normal file
View File

@@ -0,0 +1,99 @@
use uuid::Uuid;
/**
* References:
* - http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
*/
// http://dream.cs.bath.ac.uk/researchdev/wave-ex/bformat.html
const BASIC_PCM: u16 = 0x0001;
const BASIC_FLOAT: u16 = 0x0003;
const BASIC_MPEG: u16 = 0x0050;
const BASIC_EXTENDED: u16 = 0xFFFE;
/* RC 2361 §4:
WAVE Format IDs are converted to GUIDs by inserting the hexadecimal
value of the WAVE Format ID into the XXXXXXXX part of the following
template: {XXXXXXXX-0000-0010-8000-00AA00389B71}. For example, a WAVE
Format ID of 123 has the GUID value of {00000123-0000-0010-8000-
00AA00389B71}.
*/
const UUID_PCM: Uuid = Uuid::from_bytes([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
const UUID_FLOAT: Uuid = Uuid::from_bytes([0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
const UUID_MPEG: Uuid = Uuid::from_bytes([0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
const UUID_BFORMAT_PCM: Uuid = Uuid::from_bytes([0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11,
0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00]);
const UUID_BFORMAT_FLOAT: Uuid = Uuid::from_bytes([0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11,
0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00]);
fn uuid_from_basic_tag(tag: u16) -> Uuid {
let tail : [u8; 6] = [0x00,0xaa,0x00,0x38,0x9b,0x71];
Uuid::from_fields_le(tag as u32, 0x0000, 0x0010, &tail).unwrap()
}
/// Sample format of the Wave file.
///
///
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum CommonFormat {
/// Integer linear PCM
IntegerPCM,
/// IEEE Floating-point Linear PCM
IeeeFloatPCM,
/// MPEG
Mpeg,
/// Ambisonic B-Format Linear PCM
AmbisonicBFormatIntegerPCM,
/// Ambisonic B-Format Float PCM
AmbisonicBFormatIeeeFloatPCM,
/// An unknown format identified by a basic format tag.
UnknownBasic(u16),
/// An unknown format identified by an extension UUID.
UnknownExtended(Uuid),
}
impl CommonFormat {
pub fn make(basic: u16, uuid: Option<Uuid>) -> Self {
match (basic, uuid) {
(BASIC_PCM, _) => Self::IntegerPCM,
(BASIC_FLOAT, _) => Self::IeeeFloatPCM,
(BASIC_MPEG, _) => Self::Mpeg,
(BASIC_EXTENDED, Some(UUID_PCM)) => Self::IntegerPCM,
(BASIC_EXTENDED, Some(UUID_FLOAT))=> Self::IeeeFloatPCM,
(BASIC_EXTENDED, Some(UUID_BFORMAT_PCM)) => Self::AmbisonicBFormatIntegerPCM,
(BASIC_EXTENDED, Some(UUID_BFORMAT_FLOAT)) => Self::AmbisonicBFormatIeeeFloatPCM,
(BASIC_EXTENDED, Some(x)) => CommonFormat::UnknownExtended(x),
(x, _) => CommonFormat::UnknownBasic(x)
}
}
pub fn take(self) -> (u16, Uuid) {
match self {
Self::IntegerPCM => (BASIC_PCM, UUID_PCM),
Self::IeeeFloatPCM => (BASIC_FLOAT, UUID_FLOAT),
Self::Mpeg => (BASIC_MPEG, UUID_MPEG),
Self::AmbisonicBFormatIntegerPCM => (BASIC_EXTENDED, UUID_BFORMAT_PCM),
Self::AmbisonicBFormatIeeeFloatPCM => (BASIC_EXTENDED, UUID_BFORMAT_FLOAT),
Self::UnknownBasic(x) => ( x, uuid_from_basic_tag(x) ),
Self::UnknownExtended(x) => ( BASIC_EXTENDED, x)
}
}
}

258
src/cue.rs Normal file
View File

@@ -0,0 +1,258 @@
use super::fourcc::{FourCC,ReadFourCC, LABL_SIG, NOTE_SIG, LTXT_SIG};
use super::list_form::collect_list_form;
use byteorder::{ReadBytesExt, LittleEndian};
use encoding::{DecoderTrap};
use encoding::{Encoding};
use encoding::all::ASCII;
use std::io::{Cursor, Error, Read};
#[derive(Copy,Clone, Debug)]
struct RawCue {
cue_point_id : u32,
frame : u32,
chunk_id : FourCC,
chunk_start : u32,
block_start : u32,
frame_offset : u32
}
impl RawCue {
fn read_from(data : &[u8]) -> Result<Vec<Self>,Error> {
let mut rdr = Cursor::new(data);
let count = rdr.read_u32::<LittleEndian>()?;
let mut retval : Vec<Self> = vec![];
for _ in 0..count {
retval.push( Self {
cue_point_id : rdr.read_u32::<LittleEndian>()?,
frame : rdr.read_u32::<LittleEndian>()?,
chunk_id : rdr.read_fourcc()?,
chunk_start : rdr.read_u32::<LittleEndian>()?,
block_start : rdr.read_u32::<LittleEndian>()?,
frame_offset : rdr.read_u32::<LittleEndian>()?
})
}
Ok( retval )
}
}
#[derive(Clone, Debug)]
struct RawLabel {
cue_point_id : u32,
text : Vec<u8>
}
impl RawLabel {
fn read_from(data : &[u8]) -> Result<Self, Error> {
let mut rdr = Cursor::new(data);
let length = data.len();
Ok( Self {
cue_point_id : rdr.read_u32::<LittleEndian>()?,
text : {
let mut buf = vec![0u8; (length - 4) as usize ];
rdr.read_exact(&mut buf)?;
buf
}
})
}
}
#[derive(Clone, Debug)]
struct RawNote {
cue_point_id : u32,
text : Vec<u8>
}
impl RawNote {
fn read_from(data : &[u8]) -> Result<Self, Error> {
let mut rdr = Cursor::new(data);
let length = data.len();
Ok( Self {
cue_point_id : rdr.read_u32::<LittleEndian>()?,
text : {
let mut buf = vec![0u8; (length - 4) as usize ];
rdr.read_exact(&mut buf)?;
buf
}
})
}
}
#[derive(Clone, Debug)]
struct RawLtxt {
cue_point_id : u32,
frame_length : u32,
purpose : FourCC,
country : u16,
language : u16,
dialect : u16,
code_page : u16,
text: Option<Vec<u8>>
}
impl RawLtxt {
fn read_from(data : &[u8]) -> Result<Self, Error> {
let mut rdr = Cursor::new(data);
let length = data.len();
Ok( Self {
cue_point_id : rdr.read_u32::<LittleEndian>()?,
frame_length : rdr.read_u32::<LittleEndian>()?,
purpose : rdr.read_fourcc()?,
country : rdr.read_u16::<LittleEndian>()?,
language : rdr.read_u16::<LittleEndian>()?,
dialect : rdr.read_u16::<LittleEndian>()?,
code_page : rdr.read_u16::<LittleEndian>()?,
text : {
if length - 20 > 0 {
let mut buf = vec![0u8; (length - 20) as usize];
rdr.read_exact(&mut buf)?;
Some( buf )
} else {
None
}
}
})
}
}
#[derive(Clone, Debug)]
enum RawAdtlMember {
Label(RawLabel),
Note(RawNote),
LabeledText(RawLtxt),
Unrecognized(FourCC)
}
impl RawAdtlMember {
fn collect_from(chunk : &[u8]) -> Result<Vec<RawAdtlMember>,Error> {
let chunks = collect_list_form(chunk)?;
let mut retval : Vec<RawAdtlMember> = vec![];
for chunk in chunks.iter() {
retval.push(
match chunk.signature {
LABL_SIG => RawAdtlMember::Label( RawLabel::read_from(&chunk.contents)? ),
NOTE_SIG => RawAdtlMember::Note( RawNote::read_from(&chunk.contents)? ),
LTXT_SIG => RawAdtlMember::LabeledText( RawLtxt::read_from(&chunk.contents)? ),
x => RawAdtlMember::Unrecognized(x)
}
)
}
Ok( retval )
}
}
trait AdtlMemberSearch {
fn labels_for_cue_point(&self, id: u32) -> Vec<&RawLabel>;
fn notes_for_cue_point(&self, id : u32) -> Vec<&RawNote>;
fn ltxt_for_cue_point(&self, id: u32) -> Vec<&RawLtxt>;
}
impl AdtlMemberSearch for Vec<RawAdtlMember> {
fn labels_for_cue_point(&self, id: u32) -> Vec<&RawLabel> {
self.iter().filter_map(|item| {
match item {
RawAdtlMember::Label(x) if x.cue_point_id == id => Some(x),
_ => None
}
})
.collect()
}
fn notes_for_cue_point(&self, id: u32) -> Vec<&RawNote> {
self.iter().filter_map(|item| {
match item {
RawAdtlMember::Note(x) if x.cue_point_id == id => Some(x),
_ => None
}
})
.collect()
}
fn ltxt_for_cue_point(&self, id: u32) -> Vec<&RawLtxt> {
self.iter().filter_map(|item| {
match item {
RawAdtlMember::LabeledText(x) if x.cue_point_id == id => Some(x),
_ => None
}
})
.collect()
}
}
/// A cue point recorded in the `cue` and `adtl` metadata.
///
///
pub struct Cue {
/// Unique numeric identifier for this cue
pub ident : u32,
/// The time of this marker
pub frame : u32,
/// The length of this marker, if it is a range
pub length : Option<u32>,
/// The text "label"/name of this marker if provided
pub label : Option<String>,
/// The text "note"/comment of this marker if provided
pub note : Option<String>
}
fn convert_to_cue_string(buffer : &[u8]) -> String {
let trimmed : Vec<u8> = buffer.iter().take_while(|c| **c != 0 as u8).cloned().collect();
ASCII.decode(&trimmed, DecoderTrap::Ignore).expect("Error decoding text")
}
impl Cue {
pub fn collect_from(cue_chunk : &[u8], adtl_chunk : Option<&[u8]>) -> Result<Vec<Cue>, Error> {
let raw_cues = RawCue::read_from(cue_chunk)?;
let raw_adtl : Vec<RawAdtlMember>;
if let Some(adtl) = adtl_chunk {
raw_adtl = RawAdtlMember::collect_from(adtl)?;
} else {
raw_adtl = vec![];
}
Ok(
raw_cues.iter()
.map(|i| {
Cue {
ident : i.cue_point_id,
frame : i.frame,
length: {
raw_adtl.ltxt_for_cue_point(i.cue_point_id).first()
.filter(|x| x.purpose == FourCC::make(b"rgn "))
.map(|x| x.frame_length)
},
label: {
raw_adtl.labels_for_cue_point(i.cue_point_id).iter()
.map(|s| convert_to_cue_string(&s.text))
.next()
},
note : {
raw_adtl.notes_for_cue_point(i.cue_point_id).iter()
//.filter_map(|x| str::from_utf8(&x.text).ok())
.map(|s| convert_to_cue_string(&s.text))
.next()
}
}
}).collect()
)
}
}

View File

@@ -1,6 +1,8 @@
use std::io;
use super::fourcc::FourCC;
use uuid;
/// Errors returned by methods in this crate.
#[derive(Debug)]
pub enum Error {
@@ -8,6 +10,9 @@ pub enum Error {
/// An `io::Error` occurred
IOError(io::Error),
/// An error occured reading a tag UUID
UuidError(uuid::Error),
/// The file does not begin with a recognized WAVE header
HeaderNotRecognized,
@@ -34,7 +39,8 @@ pub enum Error {
InsufficientDS64Reservation {expected: u64, actual: u64},
/// The file is not optimized for writing new data
DataChunkNotPreparedForAppend
DataChunkNotPreparedForAppend,
}
@@ -42,4 +48,10 @@ impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::IOError(error)
}
}
impl From <uuid::Error> for Error {
fn from(error: uuid::Error) -> Error {
Error::UuidError(error)
}
}

258
src/fmt.rs Normal file
View File

@@ -0,0 +1,258 @@
use uuid::Uuid;
use super::common_format::CommonFormat;
#[allow(dead_code)]
/// ADM Audio ID record
///
/// This structure relates a channel in the wave file to either a common ADM
/// channel definition or further definition in the WAV file's ADM metadata
/// chunk.
///
/// An individual channel in a WAV file can have multiple Audio IDs in an ADM
/// AudioProgramme.
///
/// See BS.2088-1 § 8, also BS.2094, also blahblahblah...
pub struct ADMAudioID {
track_uid: [char; 12],
channel_format_ref: [char; 14],
pack_ref: [char; 11]
}
/// Describes a single channel in a WAV file.
pub struct ChannelDescriptor {
/// Index, the offset of this channel's samples in one frame.
pub index: u16,
/// Channel assignment
///
/// This is either implied (in the case of mono or stereo wave files) or
/// explicitly given in `WaveFormatExtentended` for files with more tracks.
pub speaker: ChannelMask,
/// ADM audioTrackUIDs
pub adm_track_audio_ids: Vec<ADMAudioID>,
}
/*
https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/subformat-guids-for-compressed-audio-formats
These are from http://dream.cs.bath.ac.uk/researchdev/wave-ex/mulchaud.rtf
*/
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ChannelMask {
DirectOut = 0x0,
FrontLeft = 0x1,
FrontRight = 0x2,
FrontCenter = 0x4,
LowFrequency = 0x8,
BackLeft = 0x10,
BackRight = 0x20,
FrontCenterLeft = 0x40,
FrontCenterRight = 0x80,
BackCenter = 0x100,
SideLeft = 0x200,
SideRight = 0x400,
TopCenter = 0x800,
TopFrontLeft = 0x1000,
TopFrontCenter = 0x2000,
TopFrontRight = 0x4000,
TopBackLeft = 0x8000,
TopBackCenter = 0x10000,
TopBackRight = 0x20000,
}
impl From<u32> for ChannelMask {
fn from(value: u32) -> Self {
match value {
0x1 => Self::FrontLeft,
0x2 => Self::FrontRight,
0x4 => Self::FrontCenter,
0x8 => Self::LowFrequency,
0x10 => Self::BackLeft,
0x20 => Self::BackRight,
0x40 => Self::FrontCenterLeft,
0x80 => Self::FrontCenterRight,
0x100 => Self::BackCenter,
0x200 => Self::SideLeft,
0x400 => Self::SideRight,
0x800 => Self::TopCenter,
0x1000 => Self::TopFrontLeft,
0x2000 => Self::TopFrontCenter,
0x4000 => Self::TopFrontRight,
0x8000 => Self::TopBackLeft,
0x10000 => Self::TopBackCenter,
0x20000 => Self::TopBackRight,
_ => Self::DirectOut
}
}
}
impl ChannelMask {
pub fn channels(input_mask : u32, channel_count: u16) -> Vec<ChannelMask> {
let reserved_mask = 0xfff2_0000_u32;
if (input_mask & reserved_mask) > 0 {
vec![ ChannelMask::DirectOut ; channel_count as usize ]
} else {
(0..18).map(|i| 1 << i )
.filter(|mask| mask & input_mask > 0)
.map(|mask| Into::<ChannelMask>::into(mask))
.collect()
}
}
}
/**
* Extended Wave Format
*
* https://docs.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible
*/
#[derive(Debug, Copy, Clone)]
pub struct WaveFmtExtended {
/// Valid bits per sample
pub valid_bits_per_sample : u16,
/// Channel mask
///
/// Identifies the speaker assignment for each channel in the file
pub channel_mask : u32,
/// Codec GUID
///
/// Identifies the codec of the audio stream
pub type_guid : Uuid,
}
/**
* WAV file data format record.
*
* The `fmt` record contains essential information describing the binary
* structure of the data segment of the WAVE file, such as sample
* rate, sample binary format, channel count, etc.
*
*/
#[derive(Debug, Copy, Clone)]
pub struct WaveFmt {
/// A tag identifying the codec in use.
///
/// If this is 0xFFFE, the codec will be identified by a GUID
/// in `extended_format`
pub tag: u16,
/// Count of audio channels in each frame
pub channel_count: u16,
/// Playback rate of the audio data
///
/// In frames per second.
pub sample_rate: u32,
/// Count of bytes per second
///
/// By rule, this is `block_alignment * sample_rate`
pub bytes_per_second: u32,
/// Count of bytes per audio frame
///
/// By rule, this is `channel_count * bits_per_sample / 8`
pub block_alignment: u16,
/// Count of bits stored in the file per sample
///
/// By rule, `bits_per_sample % 8 == 0` for Broadcast-Wave files.
///
/// Modern clients will encode
/// unusual sample sizes in normal byte sizes but will set the valid_bits
/// flag in extended format record.
///
/// Generally speaking this will be true for all modern wave files, though
/// there was an historical "packed" stereo format of 20 bits per sample,
/// 5 bytes per frame, 5 bytes block alignment.
pub bits_per_sample: u16,
/// Extended format description
///
/// Additional format metadata if `channel_count` is greater than 2,
/// or if certain codecs are used.
pub extended_format: Option<WaveFmtExtended>
}
impl WaveFmt {
/// Create a new integer PCM format `WaveFmt`
pub fn new_pcm(sample_rate: u32, bits_per_sample: u16, channel_count: u16) -> Self {
let container_bits_per_sample = bits_per_sample + (bits_per_sample % 8);
let container_bytes_per_sample= container_bits_per_sample / 8;
let tag : u16 = match channel_count {
1..=2 => 0x01,
x if x > 2 => 0xFFFE,
x => panic!("Invalid channel count {}", x)
};
WaveFmt {
tag,
channel_count,
sample_rate,
bytes_per_second: container_bytes_per_sample as u32 * sample_rate * channel_count as u32,
block_alignment: container_bytes_per_sample * channel_count,
bits_per_sample: container_bits_per_sample,
extended_format: None
}
}
/// Format or codec of the file's audio data.
///
/// The `CommonFormat` unifies the format tag and the format extension GUID. Use this
/// method to determine the codec.
pub fn common_format(&self) -> CommonFormat {
CommonFormat::make( self.tag, self.extended_format.map(|ext| ext.type_guid))
}
/// Channel descriptors for each channel.
pub fn channels(&self) -> Vec<ChannelDescriptor> {
match self.channel_count {
1 => vec![
ChannelDescriptor {
index: 0,
speaker: ChannelMask::FrontCenter,
adm_track_audio_ids: vec![]
}
],
2 => vec![
ChannelDescriptor {
index: 0,
speaker: ChannelMask::FrontLeft,
adm_track_audio_ids: vec![]
},
ChannelDescriptor {
index: 1,
speaker: ChannelMask::FrontRight,
adm_track_audio_ids: vec![]
}
],
x if x > 2 => {
let channel_mask = self.extended_format.map(|x| x.channel_mask).unwrap_or(0);
let channels = ChannelMask::channels(channel_mask, self.channel_count);
let channels_expanded = channels.iter().chain(std::iter::repeat(&ChannelMask::DirectOut));
(0..self.channel_count)
.zip(channels_expanded)
.map(|(n,chan)| ChannelDescriptor {
index: n,
speaker: *chan,
adm_track_audio_ids: vec![]
}).collect()
},
x => panic!("Channel count ({}) was illegal!", x),
}
}
}

View File

@@ -105,6 +105,13 @@ pub const BEXT_SIG: FourCC = FourCC::make(b"bext");
pub const JUNK_SIG: FourCC = FourCC::make(b"JUNK");
pub const FLLR_SIG: FourCC = FourCC::make(b"FLLR");
pub const LIST_SIG: FourCC = FourCC::make(b"LIST");
pub const CUE__SIG: FourCC = FourCC::make(b"cue ");
pub const ADTL_SIG: FourCC = FourCC::make(b"adtl");
pub const LABL_SIG: FourCC = FourCC::make(b"labl");
pub const NOTE_SIG: FourCC = FourCC::make(b"note");
pub const LTXT_SIG: FourCC = FourCC::make(b"ltxt");
#[cfg(test)]

View File

@@ -1,23 +1,64 @@
//
/*!
# bwavfile
Rust Wave File Reader/Writer with Broadcast-WAV, MBWF and RF64 Support
(Note: This crate is still in an alpha or pre-alpha stage of development. Reading of
__(Note: This crate is still in an alpha or pre-alpha stage of development. Reading of
files works however the interfaces may change significantly. Stay up-to-date on the
status of this project at [Github][github].)
status of this project at [Github][github].)__
## Objectives and Roadmap
This package aims to support read and writing any kind of WAV file you are likely
to encounter in a professional audio, motion picture production, broadcast, or music
production.
Apps we test against:
- Avid Pro Tools
- iZotope RX Audio Editor
- FFMpeg
- Audacity
Wave features we want to support with maximum reliability and ease of use:
- Large file size, RF64 support
- Multichannel audio formats
- Embedded metadata
In addition to reading the audio, we want to support all of the different
metadata planes you are liable to need to use.
- Broadcast-WAV metadata (including the SMPTE UMID and EBU v2 extensions)
- iXML Production recorder metadata
- ADM XML (with associated `chna` mappings)
- Dolby metadata block
Things that are _not_ necessarily in the scope of this package:
- Broad codec support. There are a little more than one-hundred
[registered wave codecs][rfc3261], but because this library is targeting
professional formats being created today, we only plan on supporting
two of them: tag 0x0001 (Integer Linear PCM) and tag 0x0003 (IEEE Float
Linear PCM).
- Music library metadata. There are several packages that can read ID3
metadata and it's not particuarly common in wave files in any case. INFO
metadata is more common though in professional applications it tends not
to be used by many applications.
## Resources
### Implementation of Broadcast Wave Files
- [EBU Tech 3285][ebu3285] (May 2011), "Specification of the Broadcast Wave Format (BWF)"
- [Supplement 1](https://tech.ebu.ch/docs/tech/tech3285s1.pdf) (July 1997): MPEG Audio
- [EBU Rec 68](https://tech.ebu.ch/docs/r/r068.pdf): Signal modulation and format constraints
### Implementation of 64-bit Wave Files
- [ITU-R 2088][itu2088] (October 2019), "Long-form file format for the international exchange of audio programme materials with metadata"
- Presently in force, adopted by the EBU in [EBU Tech 3306v2][ebu3306v2] (June 2018).
- Presently in force, adopted by the EBU in [EBU Tech 3306v2][ebu3306v2] (June 2018).
- [EBU Tech 3306v1][ebu3306v1] (July 2009), "MBWF / RF64: An extended File Format for Audio"
- No longer in force, however long-established.
- No longer in force, however long-established.
### Implementation of Wave format `fmt` chunk
@@ -26,12 +67,26 @@ status of this project at [Github][github].)
### Other resources
- [RFC 3261][rfc3261] (June 1998) "WAVE and AVI Codec Registries"
- [RFC 3261][rfc3261] (June 1998) "WAVE and AVI Codec Registries"
- [Sampler Metadata](http://www.piclist.com/techref/io/serial/midi/wave.html)
- [Cue list, label and other metadata](https://sites.google.com/site/musicgapi/technical-documents/wav-file-format#smpl)
- [Peter Kabal, McGill University](http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html)
- [Multimedia Programming Interface and Data Specifications 1.0](http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/riffmci.pdf)
IBM Corporation and Microsoft Corporation, (August 1991)
(August 1991), IBM Corporation and Microsoft Corporation
### Formatting of Specific Metadatums
- [iXML Metadata Specification](http://www.gallery.co.uk/ixml/) (April 2019)
- EBU 3285 Supplements:
- [Supplement 2](https://tech.ebu.ch/docs/tech/tech3285s2.pdf) (July 2001): Quality chunk and cuesheet
- [Supplement 3](https://tech.ebu.ch/docs/tech/tech3285s3.pdf) (July 2001): Peak Metadata
- [Supplement 4](https://tech.ebu.ch/docs/tech/tech3285s4.pdf) (April 2003): Link Metadata
- [Supplement 5](https://tech.ebu.ch/docs/tech/tech3285s5.pdf) (May 2018): ADM Metadata
- [Supplement 6](https://tech.ebu.ch/docs/tech/tech3285s6.pdf) (October 2009): Dolby Metadata
- [EBU Tech R099](https://tech.ebu.ch/docs/r/r099.pdf) (October 2011) "Unique Source Identifier (USID) for use in the
<OriginatorReference> field of the Broadcast Wave Format"
- [EBU Tech R098](https://tech.ebu.ch/docs/r/r098.pdf) (1999) "Format for the <CodingHistory> field in Broadcast Wave Format files, BWF"
[ebu3285]: https://tech.ebu.ch/docs/tech/tech3285.pdf
[ebu3306v1]: https://tech.ebu.ch/docs/tech/tech3306v1_1.pdf
[ebu3306v2]: https://tech.ebu.ch/docs/tech/tech3306.pdf
@@ -48,20 +103,32 @@ status of this project at [Github][github].)
extern crate encoding;
extern crate byteorder;
extern crate uuid;
mod parser;
mod fourcc;
mod errors;
mod common_format;
mod parser;
mod validation;
mod raw_chunk_reader;
mod audio_frame_reader;
mod list_form;
mod chunks;
mod cue;
mod bext;
mod fmt;
mod wavereader;
mod wavewriter;
pub use wavereader::{WaveReader};
pub use chunks::{WaveFmt,Bext};
pub use errors::Error;
pub use errors::Error;
pub use wavereader::WaveReader;
pub use wavewriter::WaveWriter;
pub use bext::Bext;
pub use fmt::{WaveFmt, WaveFmtExtended, ChannelDescriptor, ChannelMask};
pub use common_format::CommonFormat;
pub use audio_frame_reader::AudioFrameReader;
pub use cue::Cue;

40
src/list_form.rs Normal file
View File

@@ -0,0 +1,40 @@
use super::fourcc::{FourCC, ReadFourCC};
use byteorder::{ReadBytesExt, LittleEndian};
use std::io::{Cursor, Error, Read};
pub struct ListFormItem {
pub signature : FourCC,
pub contents : Vec<u8>
}
/// A helper that will accept a LIST chunk as a [u8]
/// and give you back each segment
///
pub fn collect_list_form(list_contents :& [u8]) -> Result<Vec<ListFormItem>, Error> {
let mut cursor = Cursor::new(list_contents);
let mut remain = list_contents.len();
let _ = cursor.read_fourcc()?; // skip signature
remain -= 4;
let mut retval : Vec<ListFormItem> = vec![];
while remain > 0 {
let this_sig = cursor.read_fourcc()?;
let this_size = cursor.read_u32::<LittleEndian>()? as usize;
remain -= 8;
let mut content_buf = vec![0u8; this_size];
cursor.read_exact(&mut content_buf)?;
remain -= this_size;
retval.push( ListFormItem { signature : this_sig, contents : content_buf } );
if this_size % 2 == 1 {
cursor.read_u8()?;
//panic!("Got this far!");
remain -= 1;
}
}
Ok( retval )
}

View File

@@ -103,7 +103,6 @@ impl<R: Read + Seek> Iterator for Parser<R> {
fn next(&mut self) -> Option<Event> {
let (event, next_state) = self.advance();
//println!("{:?}", event);
self.state = next_state;
return event;
}

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,16 +23,12 @@ 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> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
if self.position >= self.length {
Err(Error::new(ErrorKind::UnexpectedEof, "RawChunkReader encountered end-of-file"))
Ok(0)
} else {
self.reader.seek(Start(self.start + self.position))?;
let to_read = min(self.length - self.position, buf.len() as u64);

View File

@@ -1,144 +0,0 @@
use super::parser::{Parser};
use super::fourcc::{FourCC, FMT__SIG,DATA_SIG, BEXT_SIG, JUNK_SIG, FLLR_SIG};
use super::errors::Error as ParserError;
use super::wavereader::{WaveReader};
use std::io::{Read,Seek};
impl<R:Read + Seek> WaveReader<R> {
/**
* Returns without `Err` if the source meets the minimum standard of
* readability by a permissive client:
* 1. `fmt` chunk and `data` chunk are present
* 1. `fmt` chunk appears before `data` chunk
*/
pub fn validate_readable(&mut self) -> Result<(), ParserError> {
let (fmt_pos, _) = self.get_chunk_extent_at_index(FMT__SIG, 0)?;
let (data_pos, _) = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
if fmt_pos < data_pos {
Ok(())
} else {
Err( ParserError::FmtChunkAfterData)
}
}
/**
* Validate minimal WAVE file
*
* Returns without `Err` the source is `validate_readable` AND
*
* - Contains _only_ a `fmt` chunk and `data` chunk, with no other chunks present
* - is not an RF64/BW64
*
* Some clients require a WAVE file to only contain format and data without any other
* metadata and this function is provided to validate this condition.
*
* ```
* # use bwavfile::WaveReader;
*
* let mut w = WaveReader::open("tests/media/ff_minimal.wav").unwrap();
* w.validate_minimal().expect("Minimal wav did not validate not minimal!");
* ```
*
* ```
* # use bwavfile::WaveReader;
*
* let mut x = WaveReader::open("tests/media/pt_24bit_51.wav").unwrap();
* x.validate_minimal().expect_err("Complex WAV validated minimal!");
* ```
*/
pub fn validate_minimal(&mut self) -> Result<(), ParserError> {
self.validate_readable()?;
let chunk_fourccs : Vec<FourCC> = Parser::make(&mut self.inner)?
.into_chunk_list()?.iter().map(|c| c.signature ).collect();
if chunk_fourccs == vec![FMT__SIG, DATA_SIG] {
Ok(())
} else {
Err( ParserError::NotMinimalWaveFile )
}
}
/**
* Validate Broadcast-WAVE file format
*
* Returns without `Err` if `validate_readable()` and file contains a
* Broadcast-WAV metadata record (a `bext` chunk).
*
* ```
* # use bwavfile::WaveReader;
*
* let mut w = WaveReader::open("tests/media/ff_bwav_stereo.wav").unwrap();
* w.validate_broadcast_wave().expect("BWAVE file did not validate BWAVE");
*
* let mut x = WaveReader::open("tests/media/pt_24bit.wav").unwrap();
* x.validate_broadcast_wave().expect("BWAVE file did not validate BWAVE");
*
* let mut y = WaveReader::open("tests/media/audacity_16bit.wav").unwrap();
* y.validate_broadcast_wave().expect_err("Plain WAV file DID validate BWAVE");
* ```
*/
pub fn validate_broadcast_wave(&mut self) -> Result<(), ParserError> {
self.validate_readable()?;
let (_, _) = self.get_chunk_extent_at_index(BEXT_SIG, 0)?;
Ok(())
}
/**
* Verify data is aligned to a block boundary
*
* Returns without `Err` if `validate_readable()` and the start of the
* `data` chunk's content begins at 0x4000.
*/
pub fn validate_data_chunk_alignment(&mut self) -> Result<() , ParserError> {
self.validate_readable()?;
let (start, _) = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
if start == 0x4000 {
Ok(())
} else {
Err(ParserError::DataChunkNotAligned)
}
}
/**
* Returns without `Err` if:
* - `validate_readable()`
* - there is a `JUNK` or `FLLR` immediately at the beginning of the chunk
* list adequately large enough to be overwritten by a `ds64` (96 bytes)
* - `data` is the final chunk
*/
pub fn validate_prepared_for_append(&mut self) -> Result<(), ParserError> {
self.validate_readable()?;
let chunks = Parser::make(&mut self.inner)?.into_chunk_list()?;
let ds64_space_required = 92;
let eligible_filler_chunks = chunks.iter()
.take_while(|c| c.signature == JUNK_SIG || c.signature == FLLR_SIG);
let filler = eligible_filler_chunks
.enumerate()
.fold(0, |accum, (n, item)| if n == 0 { accum + item.length } else {accum + item.length + 8});
if filler < ds64_space_required {
Err(ParserError::InsufficientDS64Reservation {expected: ds64_space_required, actual: filler})
} else {
let data_pos = chunks.iter().position(|c| c.signature == DATA_SIG);
match data_pos {
Some(p) if p == chunks.len() - 1 => Ok(()),
_ => Err(ParserError::DataChunkNotPreparedForAppend)
}
}
}
}

View File

@@ -2,14 +2,16 @@
use std::fs::File;
use super::parser::Parser;
use super::fourcc::{FourCC, FMT__SIG, BEXT_SIG, DATA_SIG};
use super::fourcc::{FourCC, ReadFourCC, FMT__SIG,DATA_SIG, BEXT_SIG, LIST_SIG, JUNK_SIG, FLLR_SIG, CUE__SIG, ADTL_SIG};
use super::errors::Error as ParserError;
use super::raw_chunk_reader::RawChunkReader;
use super::chunks::{WaveFmt, Bext};
use super::fmt::{WaveFmt, ChannelDescriptor, ChannelMask};
use super::bext::Bext;
use super::audio_frame_reader::AudioFrameReader;
use super::chunks::ReadBWaveChunks;
//use super::validation;
//use std::io::SeekFrom::{Start};
use super::cue::Cue;
use std::io::Cursor;
use std::io::{Read, Seek};
@@ -64,7 +66,7 @@ impl<R: Read + Seek> WaveReader<R> {
* This function does a minimal validation on the provided stream and
* will return an `Err(errors::Error)` immediately if there is a structural
* inconsistency that makes the stream unreadable or if it's missing
* essential components that make interpreting the audio data impoossible.
* essential components that make interpreting the audio data impossible.
*
* ```rust
* use std::fs::File;
@@ -99,13 +101,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<RawChunkReader<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)?)
}
/**
@@ -117,35 +119,337 @@ impl<R: Read + Seek> WaveReader<R> {
Ok( data_length / (format.block_alignment as u64) )
}
/**
* Sample and frame format of this wave file.
*/
/// Sample and frame format of this wave file.
///
pub fn format(&mut self) -> Result<WaveFmt, ParserError> {
self.chunk_reader(FMT__SIG, 0)?.read_wave_fmt()
}
///
/// The Broadcast-WAV metadata record for this file, if present.
///
pub fn broadcast_extension(&mut self) -> Result<Option<Bext>, ParserError> {
let mut bext_buff : Vec<u8> = vec![ ];
let result = self.read_chunk(BEXT_SIG, 0, &mut bext_buff)?;
if result > 0 {
let mut bext_cursor = Cursor::new(bext_buff);
Ok( Some( bext_cursor.read_bext()? ) )
} else {
Ok( None)
}
}
/// Describe the channels in this file
///
/// Returns a vector of channel descriptors, one for each channel
///
/// ```rust
/// use bwavfile::WaveReader;
/// use bwavfile::ChannelMask;
///
/// let mut f = WaveReader::open("tests/media/pt_24bit_51.wav").unwrap();
///
/// let chans = f.channels().unwrap();
/// assert_eq!(chans[0].index, 0);
/// assert_eq!(chans[0].speaker, ChannelMask::FrontLeft);
/// assert_eq!(chans[3].index, 3);
/// assert_eq!(chans[3].speaker, ChannelMask::LowFrequency);
/// assert_eq!(chans[4].speaker, ChannelMask::BackLeft);
/// ```
pub fn channels(&mut self) -> Result<Vec<ChannelDescriptor>, ParserError> {
let format = self.format()?;
let channel_masks : Vec<ChannelMask> = match (format.channel_count, format.extended_format) {
(1,_) => vec![ChannelMask::FrontCenter],
(2,_) => vec![ChannelMask::FrontLeft, ChannelMask::FrontRight],
(n,Some(x)) => ChannelMask::channels(x.channel_mask, n),
(n,_) => vec![ChannelMask::DirectOut; n as usize]
};
Ok( (0..format.channel_count).zip(channel_masks)
.map(|(i,m)| ChannelDescriptor { index: i, speaker:m, adm_track_audio_ids: vec![] } )
.collect() )
}
/// Read cue points.
///
/// ```rust
/// use bwavfile::WaveReader;
/// use bwavfile::Cue;
///
/// let mut f = WaveReader::open("tests/media/izotope_test.wav").unwrap();
/// let cue_points = f.cue_points().unwrap();
///
/// assert_eq!(cue_points.len(), 3);
/// assert_eq!(cue_points[0].ident, 1);
/// assert_eq!(cue_points[0].frame, 12532);
/// assert_eq!(cue_points[0].length, None);
/// assert_eq!(cue_points[0].label, Some(String::from("Marker 1")));
/// assert_eq!(cue_points[0].note, Some(String::from("Marker 1 Comment")));
///
/// assert_eq!(cue_points[1].ident, 2);
/// assert_eq!(cue_points[1].frame, 20997);
/// assert_eq!(cue_points[1].length, None);
/// assert_eq!(cue_points[1].label, Some(String::from("Marker 2")));
/// assert_eq!(cue_points[1].note, Some(String::from("Marker 2 Comment")));
///
/// assert_eq!(cue_points[2].ident, 3);
/// assert_eq!(cue_points[2].frame, 26711);
/// assert_eq!(cue_points[2].length, Some(6465));
/// assert_eq!(cue_points[2].label, Some(String::from("Timed Region")));
/// assert_eq!(cue_points[2].note, Some(String::from("Region Comment")));
///
/// ```
pub fn cue_points(&mut self) -> Result<Vec<Cue>,ParserError> {
let mut cue_buffer : Vec<u8> = vec![];
let mut adtl_buffer : Vec<u8> = vec![];
let cue_read = self.read_chunk(CUE__SIG, 0, &mut cue_buffer)?;
let adtl_read = self.read_list(ADTL_SIG, &mut adtl_buffer)?;
match (cue_read, adtl_read) {
(0,_) => Ok( vec![] ),
(_,0) => Ok( Cue::collect_from(&cue_buffer, None)? ),
(_,_) => Ok( Cue::collect_from(&cue_buffer, Some(&adtl_buffer) )? )
}
}
/// Read iXML data.
///
/// The iXML data will be appended to `buffer`.
/// If there are no iXML metadata present in the file,
/// 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.
///
/// The axml data will be appended to `buffer`. By convention this will
/// generally be ADM metadata.
///
/// 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)
}
/**
* The Broadcast-WAV metadata record for this file.
*/
pub fn broadcast_extension(&mut self) -> Result<Bext, ParserError> {
self.chunk_reader(BEXT_SIG, 0)?.read_bext()
* Validate file is readable.
*
* `Ok(())` if the source meets the minimum standard of
* readability by a permissive client:
* - `fmt` chunk and `data` chunk are present
* - `fmt` chunk appears before `data` chunk
*/
pub fn validate_readable(&mut self) -> Result<(), ParserError> {
let (fmt_pos, _) = self.get_chunk_extent_at_index(FMT__SIG, 0)?;
let (data_pos, _) = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
if fmt_pos < data_pos {
Ok(())
} else {
Err( ParserError::FmtChunkAfterData)
}
}
/**
* Validate minimal WAVE file.
*
* `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
* metadata and this function is provided to validate this condition.
*
* ### Examples
*
* ```
* # use bwavfile::WaveReader;
*
* let mut w = WaveReader::open("tests/media/ff_minimal.wav").unwrap();
* w.validate_minimal().expect("Minimal wav did not validate not minimal!");
* ```
*
* ```
* # use bwavfile::WaveReader;
*
* let mut x = WaveReader::open("tests/media/pt_24bit_51.wav").unwrap();
* x.validate_minimal().expect_err("Complex WAV validated minimal!");
* ```
*/
pub fn validate_minimal(&mut self) -> Result<(), ParserError> {
self.validate_readable()?;
let chunk_fourccs : Vec<FourCC> = Parser::make(&mut self.inner)?
.into_chunk_list()?.iter().map(|c| c.signature ).collect();
if chunk_fourccs == vec![FMT__SIG, DATA_SIG] {
Ok(()) /* FIXME: finish implementation */
} else {
Err( ParserError::NotMinimalWaveFile )
}
}
/**
* Validate Broadcast-WAVE file format
*
* Returns `Ok(())` if `validate_readable()` and file contains a
* Broadcast-WAV metadata record (a `bext` chunk).
*
* ### Examples
*
* ```
* # use bwavfile::WaveReader;
*
* let mut w = WaveReader::open("tests/media/ff_bwav_stereo.wav").unwrap();
* w.validate_broadcast_wave().expect("BWAVE file did not validate BWAVE");
*
* let mut x = WaveReader::open("tests/media/pt_24bit.wav").unwrap();
* x.validate_broadcast_wave().expect("BWAVE file did not validate BWAVE");
*
* let mut y = WaveReader::open("tests/media/audacity_16bit.wav").unwrap();
* y.validate_broadcast_wave().expect_err("Plain WAV file DID validate BWAVE");
* ```
*/
pub fn validate_broadcast_wave(&mut self) -> Result<(), ParserError> {
self.validate_readable()?;
let (_, _) = self.get_chunk_extent_at_index(BEXT_SIG, 0)?;
Ok(())
}
/**
* Verify data is aligned to a block boundary.
*
* Returns `Ok(())` if `validate_readable()` and the start of the
* `data` chunk's content begins at 0x4000.
*/
pub fn validate_data_chunk_alignment(&mut self) -> Result<() , ParserError> {
self.validate_readable()?;
let (start, _) = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
if start == 0x4000 {
Ok(())
} else {
Err(ParserError::DataChunkNotAligned)
}
}
/**
* Verify audio data can be appended immediately to this file.
*
* Returns `Ok(())` if:
* - `validate_readable()`
* - there is a `JUNK` or `FLLR` immediately at the beginning of the chunk
* list adequately large enough to be overwritten by a `ds64` (92 bytes)
* - `data` is the final chunk
*/
pub fn validate_prepared_for_append(&mut self) -> Result<(), ParserError> {
self.validate_readable()?;
let chunks = Parser::make(&mut self.inner)?.into_chunk_list()?;
let ds64_space_required = 92;
let eligible_filler_chunks = chunks.iter()
.take_while(|c| c.signature == JUNK_SIG || c.signature == FLLR_SIG);
let filler = eligible_filler_chunks
.enumerate()
.fold(0, |accum, (n, item)| if n == 0 { accum + item.length } else {accum + item.length + 8});
if filler < ds64_space_required {
Err(ParserError::InsufficientDS64Reservation {expected: ds64_space_required, actual: filler})
} else {
let data_pos = chunks.iter().position(|c| c.signature == DATA_SIG);
match data_pos {
Some(p) if p == chunks.len() - 1 => Ok(()),
_ => Err(ParserError::DataChunkNotPreparedForAppend)
}
}
}
}
impl<R:Read+Seek> WaveReader<R> { /* Private Implementation */
impl<R:Read+Seek> WaveReader<R> {
// Private implementation
//
// As time passes thi get smore obnoxious because I haven't implemented recursive chunk
// parsing in the raw parser and I'm working around it
fn chunk_reader(&mut self, signature: FourCC, at_index: u32) -> Result<RawChunkReader<R>, ParserError> {
let (start, length) = self.get_chunk_extent_at_index(signature, at_index)?;
Ok( RawChunkReader::new(&mut self.inner, start, length) )
}
pub fn get_chunk_extent_at_index(&mut self, fourcc: FourCC, index: u32) -> Result<(u64,u64), ParserError> {
fn read_list(&mut self, ident: FourCC, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
if let Some(index) = self.get_list_form(ident)? {
self.read_chunk(LIST_SIG, index, buffer)
} else {
Ok( 0 )
}
}
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())
}
}
/// Extent of every chunk with the given fourcc
fn get_chunks_extents(&mut self, fourcc: FourCC) -> Result<Vec<(u64,u64)>, ParserError> {
let p = Parser::make(&mut self.inner)?.into_chunk_list()?;
if let Some(chunk) = p.iter().filter(|item| item.signature == fourcc).nth(index as usize) {
Ok ((chunk.start, chunk.length))
Ok( p.iter().filter(|item| item.signature == fourcc)
.map(|item| (item.start, item.length)).collect() )
}
/// Index of first LIST for with the given FORM fourcc
fn get_list_form(&mut self, fourcc: FourCC) -> Result<Option<u32>, ParserError> {
for (n, (start, length)) in self.get_chunks_extents(LIST_SIG)?.iter().enumerate() {
let mut reader = RawChunkReader::new(&mut self.inner, *start, *length);
let this_fourcc = reader.read_fourcc()?;
if this_fourcc == fourcc {
return Ok( Some( n as u32 ) );
}
}
Ok( None )
}
fn get_chunk_extent_at_index(&mut self, fourcc: FourCC, index: u32) -> Result<(u64,u64), ParserError> {
if let Some((start, length)) = self.get_chunks_extents(fourcc)?.iter().nth(index as usize) {
Ok ((*start, *length))
} else {
Err( ParserError::ChunkMissing { signature : fourcc })
Err( ParserError::ChunkMissing { signature : fourcc } )
}
}
}
#[test]
fn test_list_form() {
let mut f = WaveReader::open("tests/media/izotope_test.wav").unwrap();
let mut buf : Vec<u8> = vec![];
f.read_list(ADTL_SIG, &mut buf).unwrap();
assert_ne!(buf.len(), 0);
}

View File

@@ -3,13 +3,16 @@ use std::fs::File;
use std::io::Cursor;
use super::errors::Error;
use super::chunks::{WaveFmt, Bext, WriteBWaveChunks};
use super::chunks::{WriteBWaveChunks};
use super::bext::Bext;
use super::fmt::{WaveFmt};
use super::fourcc::{FourCC, RIFF_SIG, WAVE_SIG, FMT__SIG, JUNK_SIG, BEXT_SIG, DATA_SIG, WriteFourCC};
use byteorder::LittleEndian;
use byteorder::WriteBytesExt;
struct WaveWriter<W> where W: Write + Seek {
/// This isn't working yet, do not use.
pub struct WaveWriter<W> where W: Write + Seek {
inner : W
}
@@ -89,14 +92,3 @@ impl<W:Write + Seek> WaveWriter<W> {
}
}
#[test]
fn test_chunk_append() -> Result<(), Error> {
let mut test :Vec<u8> = vec![];
let mut cursor = Cursor::new(test);
let f = WaveFmt::new_pcm(48000, 16, 1);
let mut w = WaveWriter::make(cursor, f, None)?;
Ok(())
}

BIN
tests/.DS_Store vendored

Binary file not shown.

5
tests/Untitled.txt Normal file
View File

@@ -0,0 +1,5 @@
Marker file version: 1
Time format: Time
Marker 1 00:00:00.28417234 Marker 1 Comment
Marker 2 00:00:00.47612245 Marker 2 Comment
Timed Region 00:00:00.60569161 00:00:00.75226757 Region Comment

Binary file not shown.

Binary file not shown.

View File

@@ -1,15 +1,10 @@
#!/bin/zsh
mkdir -p media
cd media
touch media/error.wav
touch error.wav
unzip ../arch_pt_media.zip
unzip ../arch_audacity_media.zip
unzip ../arch_ff_media.zip
rm -rf __MACOSX
tar xzf test_media.tgz
# create a silent bext wave file with fixture metadata and a time refernce starting at
# one minute

View File

@@ -1,4 +1,57 @@
[
{
"streams": [
{
"index": 0,
"codec_name": "pcm_s24le",
"codec_long_name": "PCM signed 24-bit little-endian",
"codec_type": "audio",
"codec_time_base": "1/48000",
"codec_tag_string": "[1][0][0][0]",
"codec_tag": "0x0001",
"sample_fmt": "s32",
"sample_rate": "48000",
"channels": 2,
"channel_layout": "stereo",
"bits_per_sample": 24,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/48000",
"duration_ts": 4800,
"duration": "0.100000",
"bit_rate": "2304000",
"bits_per_raw_sample": "24",
"disposition": {
"default": 0,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0,
"timed_thumbnails": 0
}
}
],
"format": {
"filename": "tests/media/ff_pink.wav",
"nb_streams": 1,
"nb_programs": 0,
"format_name": "wav",
"format_long_name": "WAV / WAVE (Waveform Audio)",
"duration": "0.100000",
"size": "28902",
"bit_rate": "2312160",
"probe_score": 99,
"tags": {
"encoder": "Lavf58.45.100"
}
}
},
{
"streams": [
{

View File

@@ -7,14 +7,19 @@ use std::io::Read;
use bwavfile::WaveReader;
// This seems rickety but we're going with it
// Media Tests
//
// These tests compare metadata and format data read by ffprobe with the same values
// as read by `WaveReader`.
// This is rickety but we're going with it
fn assert_match_stream<T>(stream_key: &str,
other: impl Fn(&mut WaveReader<File>) -> T)
where T: PartialEq + Debug,
T: Into<Value>
{
let mut json_file = File::open("tests/media_ffprobe_result.json").unwrap();
let mut json_file = File::open("tests/ffprobe_media_tests.json").unwrap();
let mut s = String::new();
json_file.read_to_string(&mut s).unwrap();
if let Value::Array(v) = from_str(&mut s).unwrap() { /* */
@@ -47,4 +52,4 @@ fn test_sample_rate() {
#[test]
fn test_channel_count() {
assert_match_stream("channels", |w| w.format().unwrap().channel_count );
}
}

View File

@@ -2,6 +2,7 @@ extern crate bwavfile;
use bwavfile::WaveReader;
use bwavfile::Error;
use bwavfile::{ ChannelMask};
#[test]
fn test_open() {
@@ -27,7 +28,7 @@ fn test_format_silence() -> Result<(),Error> {
assert_eq!(format.sample_rate, 44100);
assert_eq!(format.channel_count, 1);
assert_eq!(format.tag, 1);
assert_eq!(format.tag as u16, 1);
Ok( () )
}
@@ -74,4 +75,105 @@ fn test_minimal_wave() {
} else {
assert!(true);
}
}
#[test]
fn test_read() {
let path = "tests/media/audacity_16bit.wav";
let w = WaveReader::open(path).expect("Failure opening test file");
let mut reader = w.audio_frame_reader().unwrap();
let mut buffer = reader.create_frame_buffer();
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
assert_eq!(buffer[0], -2823_i32);
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
assert_eq!(buffer[0], 2012_i32);
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
assert_eq!(buffer[0], 4524_i32);
}
#[test]
fn test_locate_multichannel_read() {
let path = "tests/media/ff_pink.wav";
let w = WaveReader::open(path).expect("Failure opening test file");
let mut reader = w.audio_frame_reader().unwrap();
let mut buffer = reader.create_frame_buffer();
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
assert_eq!(buffer[0], 332702_i32);
assert_eq!(buffer[1], 3258791_i32);
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
assert_eq!(buffer[0], -258742_i32); // 0x800000 = 8388608 // 8129866 - 8388608
assert_eq!(buffer[1], 0x0D7EF9_i32);
assert_eq!(reader.locate(100).unwrap(), 100);
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
assert_eq!(buffer[0], 0x109422_i32);
assert_eq!(buffer[1], -698901_i32); // 7689707 - 8388608
}
#[test]
fn test_channels_stereo() {
let path = "tests/media/ff_pink.wav";
let mut w = WaveReader::open(path).expect("Failure opening test file");
let channels = w.channels().unwrap();
assert_eq!(channels.len(), 2);
assert_eq!(channels[0].index,0);
assert_eq!(channels[1].index,1);
assert_eq!(channels[0].speaker,ChannelMask::FrontLeft);
assert_eq!(channels[1].speaker,ChannelMask::FrontRight);
}
#[test]
fn test_channels_mono_no_extended() {
let path = "tests/media/audacity_16bit.wav";
let mut w = WaveReader::open(path).expect("Failure opening test file");
let channels = w.channels().unwrap();
assert_eq!(channels.len(), 1);
assert_eq!(channels[0].index,0);
assert_eq!(channels[0].speaker,ChannelMask::FrontCenter);
}
#[test]
fn test_channels_stereo_no_fmt_extended() {
let path = "tests/media/pt_24bit_stereo.wav";
let mut w = WaveReader::open(path).expect("Failure opening test file");
let channels = w.channels().unwrap();
assert_eq!(channels.len(), 2);
assert_eq!(channels[0].index,0);
assert_eq!(channels[1].index,1);
assert_eq!(channels[0].speaker,ChannelMask::FrontLeft);
assert_eq!(channels[1].speaker,ChannelMask::FrontRight);
}
//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(())
}
}
let _result = from_wav_filename("tests/media/pt_24bit_stereo.wav").unwrap();
}