diff --git a/Cargo.lock b/Cargo.lock index 12e1441..3d5c112 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,11 +2,12 @@ # It is not intended for manual editing. [[package]] name = "bwavfile" -version = "0.1.3" +version = "0.1.5" 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" diff --git a/Cargo.toml b/Cargo.toml index 7f487aa..beba134 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bwavfile" -version = "0.1.3" +version = "0.1.5" authors = ["Jamie Hardt "] edition = "2018" license = "MIT" @@ -17,6 +17,7 @@ keywords = ["audio", "broadcast", "multimedia","smpte"] byteorder = "1.3.4" encoding = "0.2.33" serde_json = "1.0.59" +uuid = "0.8.1" [profile.release] debug = true diff --git a/README.md b/README.md index 61104ed..38bb12c 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,25 @@ Rust Wave File Reader/Writer with Broadcast-WAV, MBWF and RF64 Support 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 -### Reading a File +### Reading Audio Frames From a File ```rust diff --git a/src/audio_frame_reader.rs b/src/audio_frame_reader.rs index ddc36d1..10ffa48 100644 --- a/src/audio_frame_reader.rs +++ b/src/audio_frame_reader.rs @@ -4,8 +4,9 @@ use std::io::SeekFrom::{Start,}; use byteorder::LittleEndian; use byteorder::ReadBytesExt; -use super::fmt::WaveFmt; +use super::fmt::{WaveFmt}; use super::errors::Error; +use super::CommonFormat; /// Read audio frames /// @@ -33,13 +34,18 @@ impl AudioFrameReader { "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); + + assert!(format.common_format() == CommonFormat::IntegerPCM , + "Unsupported format tag {:?}", format.tag); + AudioFrameReader { inner , format } } /// Locate the read position to a different frame /// /// Seeks within the audio stream. + /// + /// Returns the new location of the read position. pub fn locate(&mut self, to :u64) -> Result { let position = to * self.format.block_alignment as u64; let seek_result = self.inner.seek(Start(position))?; @@ -59,6 +65,15 @@ impl AudioFrameReader { /// 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 @@ -83,5 +98,4 @@ impl AudioFrameReader { Ok( 1 ) } -} - +} \ No newline at end of file diff --git a/src/chunks.rs b/src/chunks.rs index e7402c0..1f3e4c4 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -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,7 +7,10 @@ use encoding::all::ASCII; use byteorder::LittleEndian; 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; pub trait ReadBWaveChunks: Read { @@ -26,7 +27,7 @@ pub trait WriteBWaveChunks: Write { impl WriteBWaveChunks for T where T: Write { fn write_wave_fmt(&mut self, format : &WaveFmt) -> Result<(), ParserError> { - self.write_u16::(format.tag)?; + self.write_u16::(format.tag as u16 )?; self.write_u16::(format.channel_count)?; self.write_u32::(format.sample_rate)?; self.write_u32::(format.bytes_per_second)?; @@ -86,14 +87,34 @@ impl WriteBWaveChunks for T where T: Write { impl ReadBWaveChunks for T where T: Read { fn read_wave_fmt(&mut self) -> Result { + let tag_value : u16; Ok(WaveFmt { - tag: self.read_u16::()?, + tag: { + tag_value = self.read_u16::()?; + tag_value + }, channel_count: self.read_u16::()?, sample_rate: self.read_u32::()?, bytes_per_second: self.read_u32::()?, block_alignment: self.read_u16::()?, bits_per_sample: self.read_u16::()?, - extended_format: None + extended_format: { + if tag_value == 0xFFFE { + let cb_size = self.read_u16::()?; + assert!(cb_size >= 22, "Format extension is not correct size"); + Some(WaveFmtExtended { + valid_bits_per_sample: self.read_u16::()?, + channel_mask: self.read_u32::()?, + 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 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); } \ No newline at end of file diff --git a/src/common_format.rs b/src/common_format.rs new file mode 100644 index 0000000..211774d --- /dev/null +++ b/src/common_format.rs @@ -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) -> 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) + } + } +} diff --git a/src/errors.rs b/src/errors.rs index 84b8794..291812e 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -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 for Error { fn from(error: io::Error) -> Error { Error::IOError(error) } +} + +impl From for Error { + fn from(error: uuid::Error) -> Error { + Error::UuidError(error) + } } \ No newline at end of file diff --git a/src/fmt.rs b/src/fmt.rs index 5aaeeea..ca12e02 100644 --- a/src/fmt.rs +++ b/src/fmt.rs @@ -1,44 +1,15 @@ +use uuid::Uuid; +use super::common_format::CommonFormat; -/** - * References: - * - http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf -*/ -#[derive(PartialEq)] -enum FormatTags { - Integer = 0x0001, - Float = 0x0003, - Extensible = 0xFFFE -} +#[allow(dead_code)] - -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 /// /// 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 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. /// /// 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. pub struct ChannelDescriptor { /// Index, the offset of this channel's samples in one frame. - index: u16, + 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. - speaker: WaveFmtExtendedChannelMask, + pub speaker: ChannelMask, /// ADM audioTrackUIDs - adm_track_audio_ids: Vec, + pub adm_track_audio_ids: Vec, } @@ -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 */ -#[derive(Debug)] -pub enum WaveFmtExtendedChannelMask { +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum ChannelMask { DirectOut = 0x0, FrontLeft = 0x1, FrontRight = 0x2, @@ -94,13 +65,53 @@ pub enum WaveFmtExtendedChannelMask { TopBackRight = 0x20000, } +impl From 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 { + 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::::into(mask)) + .collect() + } + } +} /** * Extended Wave Format * * https://docs.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatextensible */ -#[derive(Debug)] +#[derive(Debug, Copy, Clone)] pub struct WaveFmtExtended { /// Valid bits per sample @@ -109,12 +120,12 @@ pub struct WaveFmtExtended { /// Channel mask /// /// Identifies the speaker assignment for each channel in the file - pub channel_mask : WaveFmtExtendedChannelMask, + pub channel_mask : u32, /// Codec GUID /// /// 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. * */ -#[derive(Debug)] +#[derive(Debug, Copy, Clone)] pub struct WaveFmt { /// 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_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, + let tag : u16 = match channel_count { + 1..=2 => 0x01, + x if x > 2 => 0xFFFE, + x => panic!("Invalid channel count {}", x) }; WaveFmt { @@ -184,5 +195,52 @@ impl WaveFmt { 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 { + 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), + } + } } diff --git a/src/fourcc.rs b/src/fourcc.rs index 3583824..7bdc3b8 100644 --- a/src/fourcc.rs +++ b/src/fourcc.rs @@ -106,7 +106,6 @@ 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"); - #[cfg(test)] mod tests { use super::*; diff --git a/src/lib.rs b/src/lib.rs index 08d7fe3..f3939b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -100,10 +100,14 @@ Things that are _not_ necessarily in the scope of this package: extern crate encoding; extern crate byteorder; +extern crate uuid; -mod parser; mod fourcc; mod errors; +mod common_format; + +mod parser; + mod raw_chunk_reader; mod audio_frame_reader; @@ -114,8 +118,10 @@ mod fmt; mod wavereader; mod wavewriter; -pub use wavereader::{WaveReader}; -pub use bext::Bext; -pub use fmt::{WaveFmt, WaveFmtExtended}; 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; \ No newline at end of file diff --git a/src/wavereader.rs b/src/wavereader.rs index 2e24496..5b42fb7 100644 --- a/src/wavereader.rs +++ b/src/wavereader.rs @@ -5,12 +5,12 @@ 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::raw_chunk_reader::RawChunkReader; -use super::fmt::WaveFmt; +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 std::io::{Read, Seek}; @@ -132,6 +132,69 @@ impl WaveReader { 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, ParserError> { + + let format = self.format()?; + let channel_masks : Vec = 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) -> Result { + 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) -> Result { + 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. * diff --git a/src/wavewriter.rs b/src/wavewriter.rs index 0fcee76..7805cbe 100644 --- a/src/wavewriter.rs +++ b/src/wavewriter.rs @@ -11,7 +11,8 @@ use super::fourcc::{FourCC, RIFF_SIG, WAVE_SIG, FMT__SIG, JUNK_SIG, BEXT_SIG, DA use byteorder::LittleEndian; use byteorder::WriteBytesExt; -struct WaveWriter where W: Write + Seek { +/// This isn't working yet, do not use. +pub struct WaveWriter where W: Write + Seek { inner : W } @@ -91,14 +92,3 @@ impl WaveWriter { } } -#[test] -fn test_chunk_append() -> Result<(), Error> { - let mut test :Vec = vec![]; - let mut cursor = Cursor::new(test); - let f = WaveFmt::new_pcm(48000, 16, 1); - let mut w = WaveWriter::make(cursor, f, None)?; - - - - Ok(()) -} diff --git a/tests/ffprobe_media_tests.json b/tests/ffprobe_media_tests.json index 324f426..66b1e7b 100644 --- a/tests/ffprobe_media_tests.json +++ b/tests/ffprobe_media_tests.json @@ -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": [ { diff --git a/tests/integration_test.rs b/tests/integration_test.rs index 7386f82..e53aa10 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -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,85 @@ fn test_minimal_wave() { } else { assert!(true); } -} \ No newline at end of file +} + +#[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); +} diff --git a/tests/test_media.tgz b/tests/test_media.tgz index f3bd717..0d08320 100644 Binary files a/tests/test_media.tgz and b/tests/test_media.tgz differ