This commit is contained in:
Jamie Hardt
2020-11-28 16:36:59 -08:00
15 changed files with 529 additions and 83 deletions

9
Cargo.lock generated
View File

@@ -2,11 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
[[package]] [[package]]
name = "bwavfile" name = "bwavfile"
version = "0.1.3" version = "0.1.5"
dependencies = [ dependencies = [
"byteorder", "byteorder",
"encoding", "encoding",
"serde_json", "serde_json",
"uuid",
] ]
[[package]] [[package]]
@@ -107,3 +108,9 @@ dependencies = [
"ryu", "ryu",
"serde", "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] [package]
name = "bwavfile" name = "bwavfile"
version = "0.1.3" version = "0.1.5"
authors = ["Jamie Hardt <jamiehardt@me.com>"] authors = ["Jamie Hardt <jamiehardt@me.com>"]
edition = "2018" edition = "2018"
license = "MIT" license = "MIT"
@@ -17,6 +17,7 @@ keywords = ["audio", "broadcast", "multimedia","smpte"]
byteorder = "1.3.4" byteorder = "1.3.4"
encoding = "0.2.33" encoding = "0.2.33"
serde_json = "1.0.59" serde_json = "1.0.59"
uuid = "0.8.1"
[profile.release] [profile.release]
debug = true debug = true

View File

@@ -8,9 +8,25 @@ Rust Wave File Reader/Writer with Broadcast-WAV, MBWF and RF64 Support
This is currently a work-in-progress! This is currently a work-in-progress!
### Features
- Read standard WAV, Broadcast-Wave, and 64-bit RF64 and BW64 wave files with one interface for
all types with transparent format detection.
- Unified format definition interface for standard and extended-format wave files.
- Read channel/speaker map metadata.
- Read standard EBU Broadcast-Wave metadata and decode to fields, including timestamp and SMPTE UMID.
- Validate the compatibility of a given wave file for certain regimes.
- Metadata support for ambisonic B-format.
### In Progress
- Wave/RF64 file writing.
- iXML and ADM XML metadata reading/writing.
## Use Examples ## Use Examples
### Reading a File ### Reading Audio Frames From a File
```rust ```rust

View File

@@ -4,8 +4,9 @@ use std::io::SeekFrom::{Start,};
use byteorder::LittleEndian; use byteorder::LittleEndian;
use byteorder::ReadBytesExt; use byteorder::ReadBytesExt;
use super::fmt::WaveFmt; use super::fmt::{WaveFmt};
use super::errors::Error; use super::errors::Error;
use super::CommonFormat;
/// Read audio frames /// Read audio frames
/// ///
@@ -33,13 +34,18 @@ impl<R: Read + Seek> AudioFrameReader<R> {
"Unable to read audio frames from packed formats: block alignment is {}, should be {}", "Unable to read audio frames from packed formats: block alignment is {}, should be {}",
format.block_alignment, (format.bits_per_sample / 8 ) * format.channel_count); format.block_alignment, (format.bits_per_sample / 8 ) * format.channel_count);
assert!(format.tag == 1, "Unsupported format tag {}", format.tag);
assert!(format.common_format() == CommonFormat::IntegerPCM ,
"Unsupported format tag {:?}", format.tag);
AudioFrameReader { inner , format } AudioFrameReader { inner , format }
} }
/// Locate the read position to a different frame /// Locate the read position to a different frame
/// ///
/// Seeks within the audio stream. /// Seeks within the audio stream.
///
/// Returns the new location of the read position.
pub fn locate(&mut self, to :u64) -> Result<u64,Error> { pub fn locate(&mut self, to :u64) -> Result<u64,Error> {
let position = to * self.format.block_alignment as u64; let position = to * self.format.block_alignment as u64;
let seek_result = self.inner.seek(Start(position))?; let seek_result = self.inner.seek(Start(position))?;
@@ -59,6 +65,15 @@ impl<R: Read + Seek> AudioFrameReader<R> {
/// A single frame is read from the audio stream and the read location /// A single frame is read from the audio stream and the read location
/// is advanced one frame. /// 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 /// ### Panics
/// ///
/// The `buffer` must have a number of elements equal to the number of /// The `buffer` must have a number of elements equal to the number of
@@ -83,5 +98,4 @@ impl<R: Read + Seek> AudioFrameReader<R> {
Ok( 1 ) Ok( 1 )
} }
} }

View File

@@ -1,7 +1,5 @@
use std::io::{Read, Write}; use std::io::{Read, Write};
use super::errors::Error as ParserError;
use encoding::{DecoderTrap, EncoderTrap}; use encoding::{DecoderTrap, EncoderTrap};
use encoding::{Encoding}; use encoding::{Encoding};
use encoding::all::ASCII; use encoding::all::ASCII;
@@ -9,7 +7,10 @@ use encoding::all::ASCII;
use byteorder::LittleEndian; use byteorder::LittleEndian;
use byteorder::{ReadBytesExt, WriteBytesExt}; use byteorder::{ReadBytesExt, WriteBytesExt};
use super::fmt::WaveFmt; use uuid::Uuid;
use super::errors::Error as ParserError;
use super::fmt::{WaveFmt, WaveFmtExtended};
use super::bext::Bext; use super::bext::Bext;
pub trait ReadBWaveChunks: Read { pub trait ReadBWaveChunks: Read {
@@ -26,7 +27,7 @@ pub trait WriteBWaveChunks: Write {
impl<T> WriteBWaveChunks for T where T: Write { impl<T> WriteBWaveChunks for T where T: Write {
fn write_wave_fmt(&mut self, format : &WaveFmt) -> Result<(), ParserError> { 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_u16::<LittleEndian>(format.channel_count)?;
self.write_u32::<LittleEndian>(format.sample_rate)?; self.write_u32::<LittleEndian>(format.sample_rate)?;
self.write_u32::<LittleEndian>(format.bytes_per_second)?; self.write_u32::<LittleEndian>(format.bytes_per_second)?;
@@ -86,14 +87,34 @@ impl<T> WriteBWaveChunks for T where T: Write {
impl<T> ReadBWaveChunks for T where T: Read { impl<T> ReadBWaveChunks for T where T: Read {
fn read_wave_fmt(&mut self) -> Result<WaveFmt, ParserError> { fn read_wave_fmt(&mut self) -> Result<WaveFmt, ParserError> {
let tag_value : u16;
Ok(WaveFmt { Ok(WaveFmt {
tag: self.read_u16::<LittleEndian>()?, tag: {
tag_value = self.read_u16::<LittleEndian>()?;
tag_value
},
channel_count: self.read_u16::<LittleEndian>()?, channel_count: self.read_u16::<LittleEndian>()?,
sample_rate: self.read_u32::<LittleEndian>()?, sample_rate: self.read_u32::<LittleEndian>()?,
bytes_per_second: self.read_u32::<LittleEndian>()?, bytes_per_second: self.read_u32::<LittleEndian>()?,
block_alignment: self.read_u16::<LittleEndian>()?, block_alignment: self.read_u16::<LittleEndian>()?,
bits_per_sample: 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
}
}
}) })
} }
@@ -143,11 +164,36 @@ impl<T> ReadBWaveChunks for T where T: Read {
if version > 1 { Some(val) } else { None } if version > 1 { Some(val) } else { None }
}, },
coding_history: { coding_history: {
for _ in 0..=180 { self.read_u8()?; } for _ in 0..180 { self.read_u8()?; }
let mut buf = vec![]; let mut buf = vec![];
self.read_to_end(&mut buf)?; self.read_to_end(&mut buf)?;
ASCII.decode(&buf, DecoderTrap::Ignore).expect("Error decoding text") 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)
}
}
}

View File

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

View File

@@ -1,44 +1,15 @@
use uuid::Uuid;
use super::common_format::CommonFormat;
/** #[allow(dead_code)]
* References:
* - http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
*/
#[derive(PartialEq)]
enum FormatTags {
Integer = 0x0001,
Float = 0x0003,
Extensible = 0xFFFE
}
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];
/*
http://dream.cs.bath.ac.uk/researchdev/wave-ex/bformat.html
Integer format:
SUBTYPE_AMBISONIC_B_FORMAT_PCM
{00000001-0721-11d3-8644-C8C1CA000000}
Floating-point format:
SUBTYPE_AMBISONIC_B_FORMAT_IEEE_FLOAT
{00000003-0721-11d3-8644-C8C1CA000000}
In the case of ambisonics, I'm guessing we'd ignore the channel map and implied
channels W, X, Y, Z
*/
/// ADM Audio ID record /// ADM Audio ID record
/// ///
/// This structure relates a channel in the wave file to either a common ADM /// 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 /// channel definition or further definition in the WAV file's ADM metadata
/// chunk. /// chunk.
/// ///
/// An individial channel in a WAV file can have multiple Audio IDs in an ADM /// An individual channel in a WAV file can have multiple Audio IDs in an ADM
/// AudioProgramme. /// AudioProgramme.
/// ///
/// See BS.2088-1 § 8, also BS.2094, also blahblahblah... /// See BS.2088-1 § 8, also BS.2094, also blahblahblah...
@@ -51,16 +22,16 @@ pub struct ADMAudioID {
/// Describes a single channel in a WAV file. /// Describes a single channel in a WAV file.
pub struct ChannelDescriptor { pub struct ChannelDescriptor {
/// Index, the offset of this channel's samples in one frame. /// Index, the offset of this channel's samples in one frame.
index: u16, pub index: u16,
/// Channel assignment /// Channel assignment
/// ///
/// This is either implied (in the case of mono or stereo wave files) or /// This is either implied (in the case of mono or stereo wave files) or
/// explicitly given in `WaveFormatExtentended` for files with more tracks. /// explicitly given in `WaveFormatExtentended` for files with more tracks.
speaker: WaveFmtExtendedChannelMask, pub speaker: ChannelMask,
/// ADM audioTrackUIDs /// ADM audioTrackUIDs
adm_track_audio_ids: Vec<ADMAudioID>, pub adm_track_audio_ids: Vec<ADMAudioID>,
} }
@@ -71,8 +42,8 @@ https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/subformat-guids-
These are from http://dream.cs.bath.ac.uk/researchdev/wave-ex/mulchaud.rtf These are from http://dream.cs.bath.ac.uk/researchdev/wave-ex/mulchaud.rtf
*/ */
#[derive(Debug)] #[derive(Debug, Clone, Copy, PartialEq)]
pub enum WaveFmtExtendedChannelMask { pub enum ChannelMask {
DirectOut = 0x0, DirectOut = 0x0,
FrontLeft = 0x1, FrontLeft = 0x1,
FrontRight = 0x2, FrontRight = 0x2,
@@ -94,13 +65,53 @@ pub enum WaveFmtExtendedChannelMask {
TopBackRight = 0x20000, 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 * Extended Wave Format
* *
* https://docs.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible * https://docs.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible
*/ */
#[derive(Debug)] #[derive(Debug, Copy, Clone)]
pub struct WaveFmtExtended { pub struct WaveFmtExtended {
/// Valid bits per sample /// Valid bits per sample
@@ -109,12 +120,12 @@ pub struct WaveFmtExtended {
/// Channel mask /// Channel mask
/// ///
/// Identifies the speaker assignment for each channel in the file /// Identifies the speaker assignment for each channel in the file
pub channel_mask : WaveFmtExtendedChannelMask, pub channel_mask : u32,
/// Codec GUID /// Codec GUID
/// ///
/// Identifies the codec of the audio stream /// Identifies the codec of the audio stream
pub type_guid : [u8; 16], pub type_guid : Uuid,
} }
/** /**
@@ -125,7 +136,7 @@ pub struct WaveFmtExtended {
* rate, sample binary format, channel count, etc. * rate, sample binary format, channel count, etc.
* *
*/ */
#[derive(Debug)] #[derive(Debug, Copy, Clone)]
pub struct WaveFmt { pub struct WaveFmt {
/// A tag identifying the codec in use. /// A tag identifying the codec in use.
@@ -168,10 +179,10 @@ impl WaveFmt {
let container_bits_per_sample = bits_per_sample + (bits_per_sample % 8); let container_bits_per_sample = bits_per_sample + (bits_per_sample % 8);
let container_bytes_per_sample= container_bits_per_sample / 8; let container_bytes_per_sample= container_bits_per_sample / 8;
let tag :u16 = match channel_count { let tag : u16 = match channel_count {
0 => panic!("Error"), 1..=2 => 0x01,
1..=2 => FormatTags::Integer as u16, x if x > 2 => 0xFFFE,
_ => FormatTags::Extensible as u16, x => panic!("Invalid channel count {}", x)
}; };
WaveFmt { WaveFmt {
@@ -184,5 +195,52 @@ impl WaveFmt {
extended_format: None 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

@@ -106,7 +106,6 @@ pub const BEXT_SIG: FourCC = FourCC::make(b"bext");
pub const JUNK_SIG: FourCC = FourCC::make(b"JUNK"); pub const JUNK_SIG: FourCC = FourCC::make(b"JUNK");
pub const FLLR_SIG: FourCC = FourCC::make(b"FLLR"); pub const FLLR_SIG: FourCC = FourCC::make(b"FLLR");
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View File

@@ -100,10 +100,14 @@ Things that are _not_ necessarily in the scope of this package:
extern crate encoding; extern crate encoding;
extern crate byteorder; extern crate byteorder;
extern crate uuid;
mod parser;
mod fourcc; mod fourcc;
mod errors; mod errors;
mod common_format;
mod parser;
mod raw_chunk_reader; mod raw_chunk_reader;
mod audio_frame_reader; mod audio_frame_reader;
@@ -114,8 +118,10 @@ mod fmt;
mod wavereader; mod wavereader;
mod wavewriter; mod wavewriter;
pub use wavereader::{WaveReader};
pub use bext::Bext;
pub use fmt::{WaveFmt, WaveFmtExtended};
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 audio_frame_reader::AudioFrameReader;

View File

@@ -5,12 +5,12 @@ use super::parser::Parser;
use super::fourcc::{FourCC, FMT__SIG,DATA_SIG, BEXT_SIG, JUNK_SIG, FLLR_SIG}; use super::fourcc::{FourCC, FMT__SIG,DATA_SIG, BEXT_SIG, JUNK_SIG, FLLR_SIG};
use super::errors::Error as ParserError; use super::errors::Error as ParserError;
use super::raw_chunk_reader::RawChunkReader; use super::raw_chunk_reader::RawChunkReader;
use super::fmt::WaveFmt; use super::fmt::{WaveFmt, ChannelDescriptor, ChannelMask};
use super::bext::Bext; use super::bext::Bext;
use super::audio_frame_reader::AudioFrameReader; use super::audio_frame_reader::AudioFrameReader;
use super::chunks::ReadBWaveChunks; use super::chunks::ReadBWaveChunks;
//use super::validation;
//use std::io::SeekFrom::{Start};
use std::io::{Read, Seek}; use std::io::{Read, Seek};
@@ -132,6 +132,69 @@ impl<R: Read + Seek> WaveReader<R> {
self.chunk_reader(BEXT_SIG, 0)?.read_bext() self.chunk_reader(BEXT_SIG, 0)?.read_bext()
} }
/// 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 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())
}
}
/// 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())
}
}
/** /**
* Validate file is readable. * Validate file is readable.
* *

View File

@@ -11,7 +11,8 @@ use super::fourcc::{FourCC, RIFF_SIG, WAVE_SIG, FMT__SIG, JUNK_SIG, BEXT_SIG, DA
use byteorder::LittleEndian; use byteorder::LittleEndian;
use byteorder::WriteBytesExt; 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 inner : W
} }
@@ -91,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(())
}

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": [ "streams": [
{ {

View File

@@ -2,6 +2,7 @@ extern crate bwavfile;
use bwavfile::WaveReader; use bwavfile::WaveReader;
use bwavfile::Error; use bwavfile::Error;
use bwavfile::{ ChannelMask};
#[test] #[test]
fn test_open() { fn test_open() {
@@ -27,7 +28,7 @@ fn test_format_silence() -> Result<(),Error> {
assert_eq!(format.sample_rate, 44100); assert_eq!(format.sample_rate, 44100);
assert_eq!(format.channel_count, 1); assert_eq!(format.channel_count, 1);
assert_eq!(format.tag, 1); assert_eq!(format.tag as u16, 1);
Ok( () ) Ok( () )
} }
@@ -74,4 +75,85 @@ fn test_minimal_wave() {
} else { } else {
assert!(true); assert!(true);
} }
} }
#[test]
fn test_read() {
let path = "tests/media/audacity_16bit.wav";
let mut 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 mut 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);
}

Binary file not shown.