mirror of
https://github.com/iluvcapra/bwavfile.git
synced 2026-01-01 17:30:44 +00:00
Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25589ea848 | ||
|
|
d242dff686 | ||
|
|
155a26ace0 | ||
|
|
1d2edcb675 | ||
|
|
213a856e41 | ||
|
|
70bf402776 | ||
|
|
3ab3a28d0e | ||
|
|
620ca8a968 | ||
|
|
bb6390a95c | ||
|
|
15b4ccf851 | ||
|
|
ea9a0b6cbe | ||
|
|
95700b642d | ||
|
|
f3b646868f | ||
|
|
b303a74d45 | ||
|
|
73d2cf8cd9 | ||
|
|
e4fc4732b5 | ||
|
|
e8b030bd1e | ||
|
|
1219a4162f | ||
|
|
9a275a69c3 | ||
|
|
3d7c74fc94 | ||
|
|
e6e42f1c09 | ||
|
|
465bad40fc | ||
|
|
388c46d0ee | ||
|
|
5dba30fe23 | ||
|
|
84e4ed1e50 | ||
|
|
23dccecedb | ||
|
|
e2e029d3a3 | ||
|
|
1edfa7384d | ||
|
|
c73c9ad81d | ||
|
|
1edce82525 | ||
|
|
f4b27f8545 | ||
|
|
4cb6105073 | ||
|
|
ad0736dcc6 | ||
|
|
45311ad748 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -2,7 +2,7 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bwavfile"
|
name = "bwavfile"
|
||||||
version = "0.1.7"
|
version = "0.9.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"byteorder",
|
"byteorder",
|
||||||
"encoding",
|
"encoding",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "bwavfile"
|
name = "bwavfile"
|
||||||
version = "0.1.7"
|
version = "0.9.1"
|
||||||
authors = ["Jamie Hardt <jamiehardt@me.com>"]
|
authors = ["Jamie Hardt <jamiehardt@me.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|||||||
28
README.md
28
README.md
@@ -10,18 +10,20 @@ Rust Wave File Reader/Writer with Broadcast-WAV, MBWF and RF64 Support
|
|||||||
|
|
||||||
This is currently a work-in-progress! However many features presently work:
|
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
|
| Feature |Read |Write|
|
||||||
all types with transparent format detection.
|
|---------------------------------------|:---:|:-----:|
|
||||||
- [ ] Wave/RF64 file writing with transparent promotion from WAV to RF64.
|
| Standard .wav files | ☑️ | ☑ ️ |
|
||||||
- [x] Unified format definition interface for standard and extended-format wave files.
|
| Transparent promotion to RF64/BW64 | ☑️ | ☑️ |
|
||||||
- [x] Read channel/speaker map metadata.
|
| Unified interface for regular and extended Wave format | ☑️ | ☑️ |
|
||||||
- [x] Read standard EBU Broadcast-Wave metadata and decode to fields, including timestamp and SMPTE UMID.
|
| Channel/speaker map metadata | ☑️ | ☑️ |
|
||||||
- [x] iXML and ADM XML metadata.
|
| Ambisonic B-format metadata | ☑️ | ☑️ |
|
||||||
- [ ] Broadcast-WAV Level and Quality metadata.
|
| EBU Broadcast-WAVE metadata | ☑️ | ☑️ |
|
||||||
- [x] Cue list metadata.
|
| Basic iXML/ADM metadata | ☑️ | |
|
||||||
- [ ] Sampler and instrument metadata.
|
| Enhanced iXML metadata support | | |
|
||||||
- [x] Validate the compatibility of a given wave file for certain regimes.
|
| Broadcast-WAVE Level overview `levl` metadata | | |
|
||||||
- [x] Metadata support for ambisonic B-format.
|
| Cue list metadata | ☑️ | |
|
||||||
|
| Sampler and instrument metadata | | |
|
||||||
|
| Enhanced Wave file form validation | ☑ ️ | |
|
||||||
|
|
||||||
|
|
||||||
## Use Examples
|
## Use Examples
|
||||||
@@ -37,8 +39,8 @@ This is currently a work-in-progress! However many features presently work:
|
|||||||
assert_eq!(format.sample_rate, 44100);
|
assert_eq!(format.sample_rate, 44100);
|
||||||
assert_eq!(format.channel_count, 1);
|
assert_eq!(format.channel_count, 1);
|
||||||
|
|
||||||
|
let mut buffer = format.create_frame_buffer();
|
||||||
let mut frame_reader = r.audio_frame_reader().unwrap();
|
let mut frame_reader = r.audio_frame_reader().unwrap();
|
||||||
let mut buffer = frame_reader.create_frame_buffer();
|
|
||||||
|
|
||||||
let read = frame_reader.read_integer_frame(&mut buffer).unwrap();
|
let read = frame_reader.read_integer_frame(&mut buffer).unwrap();
|
||||||
|
|
||||||
|
|||||||
8
bwavefile.code-workspace
Normal file
8
bwavefile.code-workspace
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"folders": [
|
||||||
|
{
|
||||||
|
"path": "."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"settings": {}
|
||||||
|
}
|
||||||
@@ -62,13 +62,6 @@ impl<R: Read + Seek> AudioFrameReader<R> {
|
|||||||
Ok( (seek_result - self.start) / self.format.block_alignment as u64 )
|
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
|
/// Read a frame
|
||||||
///
|
///
|
||||||
|
|||||||
28
src/bext.rs
28
src/bext.rs
@@ -3,20 +3,19 @@ pub type LU = f32;
|
|||||||
pub type LUFS = f32;
|
pub type LUFS = f32;
|
||||||
pub type Decibels = f32;
|
pub type Decibels = f32;
|
||||||
|
|
||||||
/**
|
|
||||||
* Broadcast-WAV metadata record.
|
/// Broadcast-WAV metadata record.
|
||||||
*
|
///
|
||||||
* The `bext` record contains information about the original recording of the
|
/// The `bext` record contains information about the original recording of the
|
||||||
* Wave file, including a longish (256 ASCII chars) description field,
|
/// Wave file, including a longish (256 ASCII chars) description field,
|
||||||
* originator identification fields, creation calendar date and time, a
|
/// originator identification fields, creation calendar date and time, a
|
||||||
* sample-accurate recording time field, and a SMPTE UMID.
|
/// sample-accurate recording time field, and a SMPTE UMID.
|
||||||
*
|
///
|
||||||
* For a Wave file to be a complaint "Broadcast-WAV" file, it must contain
|
/// For a Wave file to be a complaint "Broadcast-WAV" file, it must contain
|
||||||
* a `bext` metadata record.
|
/// a `bext` metadata record.
|
||||||
*
|
///
|
||||||
* For reference on the structure and use of the BEXT 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).
|
/// check out [EBU Tech 3285](https://tech.ebu.ch/docs/tech/tech3285.pdf).
|
||||||
*/
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Bext {
|
pub struct Bext {
|
||||||
|
|
||||||
@@ -47,7 +46,6 @@ pub struct Bext {
|
|||||||
|
|
||||||
/// SMPTE 330M UMID
|
/// SMPTE 330M UMID
|
||||||
///
|
///
|
||||||
///
|
|
||||||
/// This field is `None` if the version is less than 1.
|
/// This field is `None` if the version is less than 1.
|
||||||
pub umid: Option<[u8; 64]>,
|
pub umid: Option<[u8; 64]>,
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,5 @@
|
|||||||
use uuid::Uuid;
|
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_PCM: u16 = 0x0001;
|
||||||
const BASIC_FLOAT: u16 = 0x0003;
|
const BASIC_FLOAT: u16 = 0x0003;
|
||||||
const BASIC_MPEG: u16 = 0x0050;
|
const BASIC_MPEG: u16 = 0x0050;
|
||||||
@@ -22,19 +15,19 @@ const BASIC_EXTENDED: u16 = 0xFFFE;
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const UUID_PCM: Uuid = Uuid::from_bytes([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
pub const UUID_PCM: Uuid = Uuid::from_bytes([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
||||||
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
||||||
|
|
||||||
const UUID_FLOAT: Uuid = Uuid::from_bytes([0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
pub const UUID_FLOAT: Uuid = Uuid::from_bytes([0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
||||||
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
||||||
|
|
||||||
const UUID_MPEG: Uuid = Uuid::from_bytes([0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
pub const UUID_MPEG: Uuid = Uuid::from_bytes([0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
||||||
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
||||||
|
|
||||||
const UUID_BFORMAT_PCM: Uuid = Uuid::from_bytes([0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11,
|
pub const UUID_BFORMAT_PCM: Uuid = Uuid::from_bytes([0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11,
|
||||||
0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00]);
|
0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00]);
|
||||||
|
|
||||||
const UUID_BFORMAT_FLOAT: Uuid = Uuid::from_bytes([0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11,
|
pub const UUID_BFORMAT_FLOAT: Uuid = Uuid::from_bytes([0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11,
|
||||||
0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00]);
|
0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00]);
|
||||||
|
|
||||||
|
|
||||||
@@ -71,6 +64,7 @@ pub enum CommonFormat {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CommonFormat {
|
impl CommonFormat {
|
||||||
|
/// Resolve a tag and Uuid to a `CommonFormat`.
|
||||||
pub fn make(basic: u16, uuid: Option<Uuid>) -> Self {
|
pub fn make(basic: u16, uuid: Option<Uuid>) -> Self {
|
||||||
match (basic, uuid) {
|
match (basic, uuid) {
|
||||||
(BASIC_PCM, _) => Self::IntegerPCM,
|
(BASIC_PCM, _) => Self::IntegerPCM,
|
||||||
@@ -85,6 +79,10 @@ impl CommonFormat {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the appropriate tag and `Uuid` for the callee.
|
||||||
|
///
|
||||||
|
/// If there is no appropriate tag for the format of the callee, the
|
||||||
|
/// returned tag will be 0xFFFE and the `Uuid` will describe the format.
|
||||||
pub fn take(self) -> (u16, Uuid) {
|
pub fn take(self) -> (u16, Uuid) {
|
||||||
match self {
|
match self {
|
||||||
Self::IntegerPCM => (BASIC_PCM, UUID_PCM),
|
Self::IntegerPCM => (BASIC_PCM, UUID_PCM),
|
||||||
|
|||||||
91
src/fmt.rs
91
src/fmt.rs
@@ -1,22 +1,22 @@
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use super::common_format::CommonFormat;
|
use super::common_format::{CommonFormat, UUID_PCM,UUID_BFORMAT_PCM};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
|
||||||
/// 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 individual 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...
|
||||||
pub struct ADMAudioID {
|
pub struct ADMAudioID {
|
||||||
track_uid: [char; 12],
|
pub track_uid: [char; 12],
|
||||||
channel_format_ref: [char; 14],
|
pub channel_format_ref: [char; 14],
|
||||||
pack_ref: [char; 11]
|
pub pack_ref: [char; 11]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Describes a single channel in a WAV file.
|
/// Describes a single channel in a WAV file.
|
||||||
@@ -35,13 +35,9 @@ pub struct ChannelDescriptor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// A bitmask indicating which channels are present in
|
||||||
/*
|
/// the file.
|
||||||
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)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub enum ChannelMask {
|
pub enum ChannelMask {
|
||||||
DirectOut = 0x0,
|
DirectOut = 0x0,
|
||||||
@@ -186,17 +182,63 @@ pub struct WaveFmt {
|
|||||||
|
|
||||||
impl WaveFmt {
|
impl WaveFmt {
|
||||||
|
|
||||||
/// Create a new integer PCM format `WaveFmt`
|
/// Create a new integer PCM format for a monoaural audio stream.
|
||||||
pub fn new_pcm(sample_rate: u32, bits_per_sample: u16, channel_count: u16) -> Self {
|
pub fn new_pcm_mono(sample_rate: u32, bits_per_sample: u16) -> Self {
|
||||||
|
Self::new_pcm_multichannel(sample_rate, bits_per_sample, 0x4)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new integer PCM format for a standard Left-Right stereo audio
|
||||||
|
/// stream.
|
||||||
|
pub fn new_pcm_stereo(sample_rate: u32, bits_per_sample: u16) -> Self {
|
||||||
|
Self::new_pcm_multichannel(sample_rate, bits_per_sample, 0x3)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new integer PCM format for ambisonic b-format.
|
||||||
|
pub fn new_pcm_ambisonic(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_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 {
|
WaveFmt {
|
||||||
1..=2 => 0x01,
|
tag : 0xFFFE,
|
||||||
x if x > 2 => 0xFFFE,
|
channel_count,
|
||||||
x => panic!("Invalid channel count {}", x)
|
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: Some(WaveFmtExtended {
|
||||||
|
valid_bits_per_sample: bits_per_sample,
|
||||||
|
channel_mask: ChannelMask::DirectOut as u32,
|
||||||
|
type_guid: UUID_BFORMAT_PCM
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new integer PCM format `WaveFmt` with a custom channel bitmap.
|
||||||
|
///
|
||||||
|
/// The order of `channels` is not important. When reading or writing
|
||||||
|
/// audio frames you must use the standard multichannel order for Wave
|
||||||
|
/// files, the numerical order of the cases of `ChannelMask`.
|
||||||
|
pub fn new_pcm_multichannel(sample_rate: u32, bits_per_sample: u16, channel_bitmap: u32) -> Self {
|
||||||
|
let container_bits_per_sample = bits_per_sample + (bits_per_sample % 8);
|
||||||
|
let container_bytes_per_sample= container_bits_per_sample / 8;
|
||||||
|
|
||||||
|
let channel_count: u16 = (0..=31).fold(0u16, |accum, n| accum + (0x1 & (channel_bitmap >> n) as u16) );
|
||||||
|
|
||||||
|
let result : (u16, Option<WaveFmtExtended>) = match channel_bitmap {
|
||||||
|
ch if bits_per_sample != container_bits_per_sample => (
|
||||||
|
(0xFFFE, Some(WaveFmtExtended { valid_bits_per_sample: bits_per_sample, channel_mask: ch,
|
||||||
|
type_guid: UUID_PCM }) )
|
||||||
|
),
|
||||||
|
0b0100 => (0x0001, None),
|
||||||
|
0b0011 => (0x0001, None),
|
||||||
|
ch => (
|
||||||
|
(0xFFFE, Some( WaveFmtExtended { valid_bits_per_sample: bits_per_sample, channel_mask: ch,
|
||||||
|
type_guid: UUID_PCM}))
|
||||||
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let (tag, extformat) = result;
|
||||||
|
|
||||||
WaveFmt {
|
WaveFmt {
|
||||||
tag,
|
tag,
|
||||||
channel_count,
|
channel_count,
|
||||||
@@ -204,7 +246,7 @@ impl WaveFmt {
|
|||||||
bytes_per_second: container_bytes_per_sample as u32 * sample_rate * channel_count as u32,
|
bytes_per_second: container_bytes_per_sample as u32 * sample_rate * channel_count as u32,
|
||||||
block_alignment: container_bytes_per_sample * channel_count,
|
block_alignment: container_bytes_per_sample * channel_count,
|
||||||
bits_per_sample: container_bits_per_sample,
|
bits_per_sample: container_bits_per_sample,
|
||||||
extended_format: None
|
extended_format: extformat
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,6 +258,15 @@ impl WaveFmt {
|
|||||||
CommonFormat::make( self.tag, self.extended_format.map(|ext| ext.type_guid))
|
CommonFormat::make( self.tag, self.extended_format.map(|ext| ext.type_guid))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create a frame buffer sized to hold frames for a reader or writer
|
||||||
|
///
|
||||||
|
/// 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.channel_count as usize]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Channel descriptors for each channel.
|
/// Channel descriptors for each channel.
|
||||||
pub fn channels(&self) -> Vec<ChannelDescriptor> {
|
pub fn channels(&self) -> Vec<ChannelDescriptor> {
|
||||||
match self.channel_count {
|
match self.channel_count {
|
||||||
|
|||||||
@@ -102,9 +102,11 @@ pub const DATA_SIG: FourCC = FourCC::make(b"data");
|
|||||||
pub const FMT__SIG: FourCC = FourCC::make(b"fmt ");
|
pub const FMT__SIG: FourCC = FourCC::make(b"fmt ");
|
||||||
|
|
||||||
pub const BEXT_SIG: FourCC = FourCC::make(b"bext");
|
pub const BEXT_SIG: FourCC = FourCC::make(b"bext");
|
||||||
|
//pub const FACT_SIG: FourCC = FourCC::make(b"fact");
|
||||||
|
|
||||||
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");
|
||||||
|
pub const ELM1_SIG: FourCC = FourCC::make(b"elm1");
|
||||||
pub const LIST_SIG: FourCC = FourCC::make(b"LIST");
|
pub const LIST_SIG: FourCC = FourCC::make(b"LIST");
|
||||||
|
|
||||||
pub const CUE__SIG: FourCC = FourCC::make(b"cue ");
|
pub const CUE__SIG: FourCC = FourCC::make(b"cue ");
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ Things that are _not_ necessarily in the scope of this package:
|
|||||||
- [Supplement 6](https://tech.ebu.ch/docs/tech/tech3285s6.pdf) (October 2009): Dolby 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
|
- [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"
|
<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"
|
- [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
|
[ebu3285]: https://tech.ebu.ch/docs/tech/tech3285.pdf
|
||||||
[ebu3306v1]: https://tech.ebu.ch/docs/tech/tech3306v1_1.pdf
|
[ebu3306v1]: https://tech.ebu.ch/docs/tech/tech3306v1_1.pdf
|
||||||
@@ -111,8 +111,6 @@ mod common_format;
|
|||||||
|
|
||||||
mod parser;
|
mod parser;
|
||||||
|
|
||||||
|
|
||||||
mod raw_chunk_reader;
|
|
||||||
mod audio_frame_reader;
|
mod audio_frame_reader;
|
||||||
mod list_form;
|
mod list_form;
|
||||||
|
|
||||||
@@ -126,9 +124,9 @@ mod wavewriter;
|
|||||||
|
|
||||||
pub use errors::Error;
|
pub use errors::Error;
|
||||||
pub use wavereader::WaveReader;
|
pub use wavereader::WaveReader;
|
||||||
pub use wavewriter::WaveWriter;
|
pub use wavewriter::{WaveWriter, AudioFrameWriter};
|
||||||
pub use bext::Bext;
|
pub use bext::Bext;
|
||||||
pub use fmt::{WaveFmt, WaveFmtExtended, ChannelDescriptor, ChannelMask};
|
pub use fmt::{WaveFmt, WaveFmtExtended, ChannelDescriptor, ChannelMask, ADMAudioID};
|
||||||
pub use common_format::CommonFormat;
|
pub use common_format::CommonFormat;
|
||||||
pub use audio_frame_reader::AudioFrameReader;
|
pub use audio_frame_reader::AudioFrameReader;
|
||||||
pub use cue::Cue;
|
pub use cue::Cue;
|
||||||
@@ -45,6 +45,7 @@ pub struct Parser<R: Read + Seek> {
|
|||||||
ds64state: HashMap<FourCC,u64>
|
ds64state: HashMap<FourCC,u64>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub struct ChunkIteratorItem {
|
pub struct ChunkIteratorItem {
|
||||||
pub signature: FourCC,
|
pub signature: FourCC,
|
||||||
pub start: u64,
|
pub start: u64,
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
use std::cmp::min;
|
|
||||||
|
|
||||||
use std::io::SeekFrom;
|
|
||||||
use std::io::SeekFrom::{Start, Current, End};
|
|
||||||
use std::io::{Seek,Read,Error,ErrorKind};
|
|
||||||
|
|
||||||
// I'm not sure this hasn't already been written somewhere in
|
|
||||||
// std but I'm just doing this here as an exercise.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct RawChunkReader<'a, R: Read + Seek> {
|
|
||||||
reader: &'a mut R,
|
|
||||||
pub start: u64,
|
|
||||||
pub length: u64,
|
|
||||||
position: u64
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a,R: Read + Seek> RawChunkReader<'a, R> {
|
|
||||||
pub fn new(reader: &'a mut R, start: u64, length: u64) -> Self {
|
|
||||||
return Self {
|
|
||||||
reader: reader,
|
|
||||||
start: start,
|
|
||||||
length: length,
|
|
||||||
position: 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, R:Read + Seek> Read for RawChunkReader<'_, R> {
|
|
||||||
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
|
|
||||||
if self.position >= self.length {
|
|
||||||
Ok(0)
|
|
||||||
} else {
|
|
||||||
self.reader.seek(Start(self.start + self.position))?;
|
|
||||||
let to_read = min(self.length - self.position, buf.len() as u64);
|
|
||||||
self.reader.take(to_read).read(buf)?;
|
|
||||||
self.position += to_read;
|
|
||||||
Ok(to_read as usize)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, R:Read + Seek> Seek for RawChunkReader<'_, R> {
|
|
||||||
fn seek(&mut self, seek: SeekFrom) -> Result<u64, std::io::Error> {
|
|
||||||
match seek {
|
|
||||||
Start(s) => {
|
|
||||||
self.position = s;
|
|
||||||
Ok(self.position)
|
|
||||||
},
|
|
||||||
Current(s) => {
|
|
||||||
let new_position = s + self.position as i64;
|
|
||||||
if new_position < 0 {
|
|
||||||
Err( Error::new(ErrorKind::Other, "Attempted seek before beginning of chunk") )
|
|
||||||
} else {
|
|
||||||
self.position = new_position as u64;
|
|
||||||
Ok(self.position)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
End(s) => {
|
|
||||||
let new_position = s + self.length as i64;
|
|
||||||
if new_position < 0 {
|
|
||||||
Err( Error::new(ErrorKind::Other, "Attempted seek before beginning of chunk") )
|
|
||||||
} else {
|
|
||||||
self.position = new_position as u64;
|
|
||||||
Ok(self.position)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
|
|
||||||
|
use std::io::SeekFrom;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
|
||||||
use super::parser::Parser;
|
use super::parser::Parser;
|
||||||
use super::fourcc::{FourCC, ReadFourCC, FMT__SIG,DATA_SIG, BEXT_SIG, LIST_SIG, JUNK_SIG, FLLR_SIG, CUE__SIG, ADTL_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::errors::Error as ParserError;
|
||||||
use super::raw_chunk_reader::RawChunkReader;
|
|
||||||
use super::fmt::{WaveFmt, ChannelDescriptor, ChannelMask};
|
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;
|
||||||
@@ -27,7 +27,7 @@ use std::io::{Read, Seek};
|
|||||||
* assert_eq!(format.channel_count, 1);
|
* assert_eq!(format.channel_count, 1);
|
||||||
*
|
*
|
||||||
* let mut frame_reader = r.audio_frame_reader().unwrap();
|
* let mut frame_reader = r.audio_frame_reader().unwrap();
|
||||||
* let mut buffer = frame_reader.create_frame_buffer();
|
* let mut buffer = format.create_frame_buffer();
|
||||||
*
|
*
|
||||||
* let read = frame_reader.read_integer_frame(&mut buffer).unwrap();
|
* let read = frame_reader.read_integer_frame(&mut buffer).unwrap();
|
||||||
*
|
*
|
||||||
@@ -123,7 +123,9 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
/// Sample and frame format of this wave file.
|
/// Sample and frame format of this wave file.
|
||||||
///
|
///
|
||||||
pub fn format(&mut self) -> Result<WaveFmt, ParserError> {
|
pub fn format(&mut self) -> Result<WaveFmt, ParserError> {
|
||||||
self.chunk_reader(FMT__SIG, 0)?.read_wave_fmt()
|
let (start, _) = self.get_chunk_extent_at_index(FMT__SIG, 0)?;
|
||||||
|
self.inner.seek(SeekFrom::Start(start))?;
|
||||||
|
self.inner.read_wave_fmt()
|
||||||
}
|
}
|
||||||
|
|
||||||
///
|
///
|
||||||
@@ -385,10 +387,10 @@ impl<R:Read+Seek> WaveReader<R> {
|
|||||||
// As time passes thi get smore obnoxious because I haven't implemented recursive chunk
|
// 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
|
// 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> {
|
// 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)?;
|
// let (start, length) = self.get_chunk_extent_at_index(signature, at_index)?;
|
||||||
Ok( RawChunkReader::new(&mut self.inner, start, length) )
|
// Ok( RawChunkReader::new(&mut self.inner, start, length) )
|
||||||
}
|
// }
|
||||||
|
|
||||||
fn read_list(&mut self, ident: FourCC, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
|
fn read_list(&mut self, ident: FourCC, buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
|
||||||
if let Some(index) = self.get_list_form(ident)? {
|
if let Some(index) = self.get_list_form(ident)? {
|
||||||
@@ -398,15 +400,14 @@ impl<R:Read+Seek> WaveReader<R> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
fn read_chunk(&mut self, ident: FourCC, at: u32, mut buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
|
||||||
Ok(mut chunk) => {
|
|
||||||
match chunk.read_to_end(buffer) {
|
match self.get_chunk_extent_at_index(ident, at) {
|
||||||
Ok(read) => Ok(read),
|
Ok((start, length)) => {
|
||||||
Err(err) => Err(err.into())
|
buffer.resize(length as usize, 0x0);
|
||||||
}
|
self.inner.seek(SeekFrom::Start(start))?;
|
||||||
|
self.inner.read(&mut buffer).map_err(|e| ParserError::IOError(e))
|
||||||
},
|
},
|
||||||
Err(ParserError::ChunkMissing { signature : _} ) => Ok(0),
|
Err(ParserError::ChunkMissing { signature : _} ) => Ok(0),
|
||||||
Err( any ) => Err(any.into())
|
Err( any ) => Err(any.into())
|
||||||
@@ -423,9 +424,9 @@ impl<R:Read+Seek> WaveReader<R> {
|
|||||||
|
|
||||||
/// Index of first LIST for with the given FORM fourcc
|
/// Index of first LIST for with the given FORM fourcc
|
||||||
fn get_list_form(&mut self, fourcc: FourCC) -> Result<Option<u32>, ParserError> {
|
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() {
|
for (n, (start, _)) in self.get_chunks_extents(LIST_SIG)?.iter().enumerate() {
|
||||||
let mut reader = RawChunkReader::new(&mut self.inner, *start, *length);
|
self.inner.seek(SeekFrom::Start(*start as u64))?;
|
||||||
let this_fourcc = reader.read_fourcc()?;
|
let this_fourcc = self.inner.read_fourcc()?;
|
||||||
if this_fourcc == fourcc {
|
if this_fourcc == fourcc {
|
||||||
return Ok( Some( n as u32 ) );
|
return Ok( Some( n as u32 ) );
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,94 +1,449 @@
|
|||||||
use std::io::{Write, Seek, SeekFrom};
|
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Cursor;
|
use std::io::{Write,Seek,SeekFrom};
|
||||||
|
|
||||||
use super::errors::Error;
|
use super::Error;
|
||||||
use super::chunks::{WriteBWaveChunks};
|
use super::fourcc::{FourCC, WriteFourCC, RIFF_SIG, RF64_SIG, DS64_SIG,
|
||||||
|
WAVE_SIG, FMT__SIG, DATA_SIG, ELM1_SIG, JUNK_SIG, BEXT_SIG};
|
||||||
|
use super::fmt::WaveFmt;
|
||||||
|
//use super::common_format::CommonFormat;
|
||||||
|
use super::chunks::WriteBWaveChunks;
|
||||||
use super::bext::Bext;
|
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::LittleEndian;
|
||||||
use byteorder::WriteBytesExt;
|
use byteorder::WriteBytesExt;
|
||||||
|
|
||||||
/// This isn't working yet, do not use.
|
/// Write audio frames to a `WaveWriter`.
|
||||||
pub struct WaveWriter<W> where W: Write + Seek {
|
///
|
||||||
inner : W
|
///
|
||||||
|
pub struct AudioFrameWriter<W> where W: Write + Seek {
|
||||||
|
inner : WaveChunkWriter<W>
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WaveWriter<File> {
|
impl<W> AudioFrameWriter<W> where W: Write + Seek {
|
||||||
pub fn create(path : &str, format:WaveFmt, broadcast_extension: Option<Bext>) -> Result<Self,Error> {
|
|
||||||
let inner = File::create(path)?;
|
|
||||||
Self::make(inner, format, broadcast_extension)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<W:Write + Seek> WaveWriter<W> {
|
/// Write one audio frame.
|
||||||
|
///
|
||||||
|
pub fn write_integer_frame(&mut self, buffer: &[i32]) -> Result<u64,Error> {
|
||||||
|
let format = self.inner.inner.format;
|
||||||
|
assert!(buffer.len() as u16 == format.channel_count,
|
||||||
|
"read_integer_frame was called with a mis-sized buffer, expected {}, was {}",
|
||||||
|
format.channel_count, buffer.len());
|
||||||
|
|
||||||
pub fn make(inner : W, format: WaveFmt, broadcast_extension: Option<Bext>) -> Result<Self, Error> {
|
let framed_bits_per_sample = format.block_alignment * 8 / format.channel_count;
|
||||||
let mut retval = Self { inner };
|
|
||||||
retval.prepare_created(format, broadcast_extension)?;
|
|
||||||
Ok(retval)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_created(&mut self, format : WaveFmt, broadcast_extension: Option<Bext>) -> Result<(),Error> {
|
for n in 0..(format.channel_count as usize) {
|
||||||
self.inner.write_fourcc(RIFF_SIG)?;
|
match (format.bits_per_sample, framed_bits_per_sample) {
|
||||||
self.inner.write_u32::<LittleEndian>(4)?;
|
(0..=8,8) => self.inner.write_u8((buffer[n] + 0x80) as u8 )?, // EBU 3285 §A2.2
|
||||||
self.inner.write_fourcc(WAVE_SIG)?;
|
(9..=16,16) => self.inner.write_i16::<LittleEndian>(buffer[n] as i16)?,
|
||||||
let mut written : u64 = 4;
|
(10..=24,24) => self.inner.write_i24::<LittleEndian>(buffer[n])?,
|
||||||
|
(25..=32,32) => self.inner.write_i32::<LittleEndian>(buffer[n])?,
|
||||||
let ds64_reservation = [0u8; 92];
|
(b,_)=> panic!("Unrecognized integer format, bits per sample {}, channels {}, block_alignment {}",
|
||||||
|
b, format.channel_count, format.block_alignment)
|
||||||
written += self.primitive_append_chunk(JUNK_SIG, &ds64_reservation)?;
|
}
|
||||||
|
|
||||||
let fmt_data : Vec<u8> = {
|
|
||||||
let mut c = Cursor::new(vec![]);
|
|
||||||
c.write_wave_fmt(&format)?;
|
|
||||||
c.into_inner()
|
|
||||||
};
|
|
||||||
|
|
||||||
written += self.primitive_append_chunk(FMT__SIG, &fmt_data)?;
|
|
||||||
|
|
||||||
if let Some(bext) = broadcast_extension {
|
|
||||||
let mut b = Cursor::new(vec![]);
|
|
||||||
b.write_bext(&bext)?;
|
|
||||||
let data = b.into_inner();
|
|
||||||
written += self.primitive_append_chunk(BEXT_SIG, &data)?;
|
|
||||||
}
|
}
|
||||||
|
self.inner.flush()?;
|
||||||
|
Ok(1)
|
||||||
|
}
|
||||||
|
|
||||||
// show our work
|
/// Finish writing audio frames and unwrap the inner `WaveWriter`.
|
||||||
let desired_data_alignment = 0x4000;
|
///
|
||||||
let data_fourcc_start = desired_data_alignment - 8;
|
/// This method must be called when the client has finished writing audio
|
||||||
let current_position_from_start = written + 8;
|
/// data. This will finalize the audio data chunk.
|
||||||
let data_pad_length = data_fourcc_start - current_position_from_start;
|
pub fn end(self) -> Result<WaveWriter<W>, Error> {
|
||||||
|
self.inner.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let data_padding = vec![0u8; data_pad_length as usize];
|
/// Write a wave data chunk.
|
||||||
|
///
|
||||||
|
/// `WaveChunkWriter` implements `Write` and as bytes are written to it,
|
||||||
|
///
|
||||||
|
/// ### Important!
|
||||||
|
///
|
||||||
|
/// When you are done writing to a chunk you must call `end()` in order to
|
||||||
|
/// finalize the chunk for storage.
|
||||||
|
pub struct WaveChunkWriter<W> where W: Write + Seek {
|
||||||
|
ident : FourCC,
|
||||||
|
inner : WaveWriter<W>,
|
||||||
|
content_start_pos : u64,
|
||||||
|
length : u64
|
||||||
|
}
|
||||||
|
|
||||||
written += self.primitive_append_chunk(JUNK_SIG, &data_padding)?;
|
impl<W> WaveChunkWriter<W> where W: Write + Seek {
|
||||||
|
|
||||||
self.inner.write_fourcc(DATA_SIG)?;
|
fn begin(mut inner : WaveWriter<W>, ident : FourCC) -> Result<Self,Error> {
|
||||||
self.inner.write_u32::<LittleEndian>(0)?;
|
let length : u64 = 0;
|
||||||
|
inner.inner.write_fourcc(ident)?;
|
||||||
|
inner.inner.write_u32::<LittleEndian>(length as u32)?;
|
||||||
|
inner.increment_form_length(8)?;
|
||||||
|
let content_start_pos = inner.inner.seek(SeekFrom::End(0))?;
|
||||||
|
Ok( WaveChunkWriter { ident, inner , content_start_pos, length } )
|
||||||
|
}
|
||||||
|
|
||||||
written += 8;
|
fn end(mut self) -> Result<WaveWriter<W>, Error> {
|
||||||
self.inner.seek(SeekFrom::Start(4))?;
|
if self.length % 2 == 1 {
|
||||||
self.inner.write_u32::<LittleEndian>(written as u32)?;
|
self.inner.inner.seek(SeekFrom::End(0))?;
|
||||||
|
self.inner.inner.write(&[0u8])?;
|
||||||
|
self.inner.increment_form_length(1)?;
|
||||||
|
}
|
||||||
|
Ok( self.inner )
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment_chunk_length(&mut self, amount: u64) -> Result<(), std::io::Error> {
|
||||||
|
self.length = self.length + amount;
|
||||||
|
if !self.inner.is_rf64 {
|
||||||
|
self.inner.inner.seek(SeekFrom::Start(self.content_start_pos - 4))?;
|
||||||
|
self.inner.inner.write_u32::<LittleEndian>(self.length as u32)?;
|
||||||
|
} else {
|
||||||
|
if self.ident == DATA_SIG {
|
||||||
|
let data_chunk_64bit_field_offset = 8 + 4 + 8 + 8;
|
||||||
|
self.inner.inner.seek(SeekFrom::Start(self.content_start_pos - 4))?;
|
||||||
|
self.inner.inner.write_u32::<LittleEndian>(0xFFFF_FFFF)?;
|
||||||
|
// this only need to happen once, not every time we increment
|
||||||
|
|
||||||
|
self.inner.inner.seek(SeekFrom::Start(data_chunk_64bit_field_offset))?;
|
||||||
|
self.inner.inner.write_u64::<LittleEndian>(self.length)?;
|
||||||
|
} else {
|
||||||
|
todo!("FIXME RF64 wave writing is not yet supported for chunks other than `data`")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn primitive_append_chunk(&mut self, signature: FourCC, data: &[u8]) -> Result<u64,Error> {
|
impl<W> Write for WaveChunkWriter<W> where W: Write + Seek {
|
||||||
assert!((data.len() as u32) < u32::MAX,
|
|
||||||
"primitive_append_chunk called with a long data buffer");
|
|
||||||
|
|
||||||
self.inner.write_fourcc(signature)?;
|
fn write(&mut self, buffer: &[u8]) -> Result<usize, std::io::Error> {
|
||||||
self.inner.write_u32::<LittleEndian>(data.len() as u32)?;
|
self.inner.inner.seek(SeekFrom::End(0))?;
|
||||||
self.inner.write_all(&data)?;
|
let written = self.inner.inner.write(buffer)?;
|
||||||
let padding : u64 = data.len() as u64 % 2;
|
self.inner.increment_form_length(written as u64)?;
|
||||||
if padding == 1 {
|
self.increment_chunk_length(written as u64)?;
|
||||||
self.inner.write_u8(0)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(8 + data.len() as u64 + padding)
|
Ok( written )
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> Result<(), std::io::Error> {
|
||||||
|
self.inner.inner.flush()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Wave, Broadcast-WAV and RF64/BW64 writer.
|
||||||
|
///
|
||||||
|
/// A `WaveWriter` creates a new wave file at the given path (with `create()`)
|
||||||
|
/// or into the given `Write`- and `Seek`-able inner writer.
|
||||||
|
///
|
||||||
|
/// Audio is added to the wave file by starting the audio data chunk with
|
||||||
|
/// `WaveWriter::audio_frame_writer()`. All of the functions that add chunks
|
||||||
|
/// move the WaveWriter and return it to the host when complete.
|
||||||
|
///
|
||||||
|
/// # Structure of New Wave Files
|
||||||
|
///
|
||||||
|
/// `WaveWriter` will create a Wave file with two chunks automatically: a 96
|
||||||
|
/// byte `JUNK` chunk and a standard `fmt ` chunk, which has the extended
|
||||||
|
/// length if the format your provided requires it. The first `JUNK` chunk is
|
||||||
|
/// a reservation for a `ds64` record which will be written over it if
|
||||||
|
/// the file needs to be upgraded to RF64 format.
|
||||||
|
///
|
||||||
|
/// Chunks are added to the file in the order the client adds them.
|
||||||
|
/// `audio_file_writer()` will add a `data` chunk for the audio data, and will
|
||||||
|
/// also add an `elm1` filler chunk prior to the data chunk to ensure that the
|
||||||
|
/// first byte of the data chunk's content is aligned with 0x4000.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use bwavfile::{WaveWriter,WaveFmt};
|
||||||
|
/// # use std::io::Cursor;
|
||||||
|
///
|
||||||
|
/// // Write a three-sample wave file to a cursor
|
||||||
|
/// let mut cursor = Cursor::new(vec![0u8;0]);
|
||||||
|
/// let format = WaveFmt::new_pcm_mono(48000, 24);
|
||||||
|
/// let w = WaveWriter::new(&mut cursor, format).unwrap();
|
||||||
|
///
|
||||||
|
/// let mut frame_writer = w.audio_frame_writer().unwrap();
|
||||||
|
///
|
||||||
|
/// frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
/// frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
/// frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
/// frame_writer.end().unwrap();
|
||||||
|
/// ```
|
||||||
|
pub struct WaveWriter<W> where W: Write + Seek {
|
||||||
|
inner : W,
|
||||||
|
form_length: u64,
|
||||||
|
|
||||||
|
/// True if file is RF64
|
||||||
|
pub is_rf64: bool,
|
||||||
|
|
||||||
|
/// Format of the wave file.
|
||||||
|
pub format: WaveFmt
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WaveWriter<File> {
|
||||||
|
|
||||||
|
/// Create a new Wave file at `path`.
|
||||||
|
pub fn create(path : &str, format : WaveFmt) -> Result<Self, Error> {
|
||||||
|
let f = File::create(path)?;
|
||||||
|
Ok( Self::new(f, format)? )
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W> WaveWriter<W> where W: Write + Seek {
|
||||||
|
|
||||||
|
/// Wrap a writer in a Wave writer.
|
||||||
|
///
|
||||||
|
/// The inner writer will immediately have a RIFF WAVE file header
|
||||||
|
/// written to it along with the format descriptor (and possibly a `fact`
|
||||||
|
/// chunk if appropriate).
|
||||||
|
pub fn new(mut inner : W, format: WaveFmt) -> Result<Self, Error> {
|
||||||
|
inner.write_fourcc(RIFF_SIG)?;
|
||||||
|
inner.write_u32::<LittleEndian>(0)?;
|
||||||
|
inner.write_fourcc(WAVE_SIG)?;
|
||||||
|
|
||||||
|
let mut retval = WaveWriter { inner, form_length: 0, is_rf64: false, format};
|
||||||
|
|
||||||
|
retval.increment_form_length(4)?;
|
||||||
|
|
||||||
|
let mut chunk = retval.chunk(JUNK_SIG)?;
|
||||||
|
chunk.write(&[0u8; 96])?;
|
||||||
|
let retval = chunk.end()?;
|
||||||
|
|
||||||
|
let mut chunk = retval.chunk(FMT__SIG)?;
|
||||||
|
chunk.write_wave_fmt(&format)?;
|
||||||
|
let retval = chunk.end()?;
|
||||||
|
|
||||||
|
Ok( retval )
|
||||||
|
}
|
||||||
|
|
||||||
|
fn promote_to_rf64(&mut self) -> Result<(), std::io::Error> {
|
||||||
|
if !self.is_rf64 {
|
||||||
|
self.inner.seek(SeekFrom::Start(0))?;
|
||||||
|
self.inner.write_fourcc(RF64_SIG)?;
|
||||||
|
self.inner.write_u32::<LittleEndian>(0xFFFF_FFFF)?;
|
||||||
|
self.inner.seek(SeekFrom::Start(12))?;
|
||||||
|
|
||||||
|
self.inner.write_fourcc(DS64_SIG)?;
|
||||||
|
self.inner.seek(SeekFrom::Current(4))?;
|
||||||
|
self.inner.write_u64::<LittleEndian>(self.form_length)?;
|
||||||
|
self.is_rf64 = true;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fn chunk(mut self, ident: FourCC) -> Result<WaveChunkWriter<W>,Error> {
|
||||||
|
self.inner.seek(SeekFrom::End(0))?;
|
||||||
|
WaveChunkWriter::begin(self, ident)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write Broadcast-Wave metadata to the file.
|
||||||
|
///
|
||||||
|
/// This function will write the metadata chunk immediately to the end of
|
||||||
|
/// the file; if you have already written and closed the audio data the
|
||||||
|
/// bext chunk will be positioned after it.
|
||||||
|
fn write_broadcast_metadata(self, bext: &Bext) -> Result<Self,Error> {
|
||||||
|
let mut b = self.chunk(BEXT_SIG)?;
|
||||||
|
b.write_bext(bext)?;
|
||||||
|
Ok(b.end()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create an audio frame writer, which takes possession of the callee
|
||||||
|
/// `WaveWriter`.
|
||||||
|
///
|
||||||
|
///
|
||||||
|
pub fn audio_frame_writer(mut self) -> Result<AudioFrameWriter<W>, Error> {
|
||||||
|
// append elm1 chunk
|
||||||
|
|
||||||
|
let framing = 0x4000;
|
||||||
|
|
||||||
|
let lip = self.inner.seek(SeekFrom::End(0))?;
|
||||||
|
let to_add = framing - (lip % framing) - 16;
|
||||||
|
let mut chunk = self.chunk(ELM1_SIG)?;
|
||||||
|
let buf = vec![0u8; to_add as usize];
|
||||||
|
chunk.write(&buf)?;
|
||||||
|
let closed = chunk.end()?;
|
||||||
|
let inner = closed.chunk(DATA_SIG)?;
|
||||||
|
Ok( AudioFrameWriter { inner } )
|
||||||
|
}
|
||||||
|
|
||||||
|
fn increment_form_length(&mut self, amount: u64) -> Result<(), std::io::Error> {
|
||||||
|
self.form_length = self.form_length + amount;
|
||||||
|
if self.is_rf64 {
|
||||||
|
self.inner.seek(SeekFrom::Start(8 + 4 + 8))?;
|
||||||
|
self.inner.write_u64::<LittleEndian>(self.form_length)?;
|
||||||
|
} else if self.form_length < u32::MAX as u64 {
|
||||||
|
self.inner.seek(SeekFrom::Start(4))?;
|
||||||
|
self.inner.write_u32::<LittleEndian>(self.form_length as u32)?;
|
||||||
|
} else {
|
||||||
|
self.promote_to_rf64()?;
|
||||||
|
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_new() {
|
||||||
|
use std::io::Cursor;
|
||||||
|
use super::fourcc::ReadFourCC;
|
||||||
|
use byteorder::ReadBytesExt;
|
||||||
|
|
||||||
|
let mut cursor = Cursor::new(vec![0u8;0]);
|
||||||
|
let format = WaveFmt::new_pcm_mono(4800, 24);
|
||||||
|
WaveWriter::new(&mut cursor, format).unwrap();
|
||||||
|
|
||||||
|
cursor.seek(SeekFrom::Start(0)).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), RIFF_SIG);
|
||||||
|
let form_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), WAVE_SIG);
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), JUNK_SIG);
|
||||||
|
let junk_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
|
assert_eq!(junk_size,96);
|
||||||
|
cursor.seek(SeekFrom::Current(junk_size as i64)).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), FMT__SIG);
|
||||||
|
let fmt_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
|
assert_eq!(form_size, 4 + 8 + junk_size + 8 + fmt_size);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_write_audio() {
|
||||||
|
use std::io::Cursor;
|
||||||
|
use super::fourcc::ReadFourCC;
|
||||||
|
use byteorder::ReadBytesExt;
|
||||||
|
|
||||||
|
let mut cursor = Cursor::new(vec![0u8;0]);
|
||||||
|
let format = WaveFmt::new_pcm_mono(48000, 24);
|
||||||
|
let w = WaveWriter::new(&mut cursor, format).unwrap();
|
||||||
|
|
||||||
|
let mut frame_writer = w.audio_frame_writer().unwrap();
|
||||||
|
|
||||||
|
frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
|
||||||
|
frame_writer.end().unwrap();
|
||||||
|
|
||||||
|
cursor.seek(SeekFrom::Start(0)).unwrap();
|
||||||
|
|
||||||
|
cursor.seek(SeekFrom::Start(0)).unwrap();
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), RIFF_SIG);
|
||||||
|
let form_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), WAVE_SIG); //4
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), JUNK_SIG); //4
|
||||||
|
let junk_size = cursor.read_u32::<LittleEndian>().unwrap(); //4
|
||||||
|
cursor.seek(SeekFrom::Current(junk_size as i64)).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), FMT__SIG); //4
|
||||||
|
let fmt_size = cursor.read_u32::<LittleEndian>().unwrap(); //4
|
||||||
|
cursor.seek(SeekFrom::Current(fmt_size as i64)).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), ELM1_SIG); //4
|
||||||
|
let elm1_size = cursor.read_u32::<LittleEndian>().unwrap(); //4
|
||||||
|
cursor.seek(SeekFrom::Current(elm1_size as i64)).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(cursor.read_fourcc().unwrap(), DATA_SIG); //4
|
||||||
|
let data_size = cursor.read_u32::<LittleEndian>().unwrap(); //4
|
||||||
|
assert_eq!(data_size, 9);
|
||||||
|
|
||||||
|
let tell = cursor.seek(SeekFrom::Current(0)).unwrap();
|
||||||
|
assert!(tell % 0x4000 == 0);
|
||||||
|
|
||||||
|
assert_eq!(form_size, 4 + 8 + junk_size + 8 + fmt_size + 8 + elm1_size + 8 + data_size + data_size % 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_write_bext() {
|
||||||
|
use std::io::Cursor;
|
||||||
|
|
||||||
|
let mut cursor = Cursor::new(vec![0u8;0]);
|
||||||
|
let format = WaveFmt::new_pcm_mono(48000, 24);
|
||||||
|
let w = WaveWriter::new(&mut cursor, format).unwrap();
|
||||||
|
|
||||||
|
let bext = Bext {
|
||||||
|
description: String::from("Test description"),
|
||||||
|
originator: String::from(""),
|
||||||
|
originator_reference: String::from(""),
|
||||||
|
origination_date: String::from("2020-01-01"),
|
||||||
|
origination_time: String::from("12:34:56"),
|
||||||
|
time_reference: 0,
|
||||||
|
version: 0,
|
||||||
|
umid: None,
|
||||||
|
loudness_value: None,
|
||||||
|
loudness_range: None,
|
||||||
|
max_true_peak_level: None,
|
||||||
|
max_momentary_loudness: None,
|
||||||
|
max_short_term_loudness: None,
|
||||||
|
coding_history: String::from(""),
|
||||||
|
};
|
||||||
|
|
||||||
|
let w = w.write_broadcast_metadata(&bext).unwrap();
|
||||||
|
|
||||||
|
let mut frame_writer = w.audio_frame_writer().unwrap();
|
||||||
|
|
||||||
|
frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
frame_writer.write_integer_frame(&[0i32]).unwrap();
|
||||||
|
|
||||||
|
frame_writer.end().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// NOTE! This test of RF64 writing passes on my machine but because it takes
|
||||||
|
// nearly 5 mins to run I have omitted it from the source for now...
|
||||||
|
|
||||||
|
// #[test]
|
||||||
|
// fn test_create_rf64() {
|
||||||
|
// use std::io::Cursor;
|
||||||
|
// use super::fourcc::ReadFourCC;
|
||||||
|
// use byteorder::ReadBytesExt;
|
||||||
|
|
||||||
|
// let mut cursor = Cursor::new(vec![0u8;0]);
|
||||||
|
// let format = WaveFmt::new_pcm_stereo(48000, 24);
|
||||||
|
// let w = WaveWriter::new(&mut cursor, format).unwrap();
|
||||||
|
|
||||||
|
|
||||||
|
// let buf = format.create_frame_buffer();
|
||||||
|
|
||||||
|
// let four_and_a_half_hours = 48000 * 16_200; // 4,665,600,000 bytes / 777,600,000 frames
|
||||||
|
|
||||||
|
// let mut af = w.audio_frame_writer().unwrap();
|
||||||
|
|
||||||
|
// for _ in 0..four_and_a_half_hours {
|
||||||
|
// af.write_integer_frame(&buf).unwrap();
|
||||||
|
// }
|
||||||
|
// af.end().unwrap();
|
||||||
|
|
||||||
|
// let expected_data_length = four_and_a_half_hours * format.block_alignment as u64;
|
||||||
|
|
||||||
|
// cursor.seek(SeekFrom::Start(0)).unwrap();
|
||||||
|
// assert_eq!(cursor.read_fourcc().unwrap(), RF64_SIG);
|
||||||
|
// assert_eq!(cursor.read_u32::<LittleEndian>().unwrap(), 0xFFFF_FFFF);
|
||||||
|
// assert_eq!(cursor.read_fourcc().unwrap(), WAVE_SIG);
|
||||||
|
|
||||||
|
// assert_eq!(cursor.read_fourcc().unwrap(), DS64_SIG);
|
||||||
|
// let ds64_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
|
// let form_size = cursor.read_u64::<LittleEndian>().unwrap();
|
||||||
|
// let data_size = cursor.read_u64::<LittleEndian>().unwrap();
|
||||||
|
// assert_eq!(data_size, expected_data_length);
|
||||||
|
// cursor.seek(SeekFrom::Current(ds64_size as i64 - 16)).unwrap();
|
||||||
|
|
||||||
|
// assert_eq!(cursor.read_fourcc().unwrap(), FMT__SIG);
|
||||||
|
// let fmt_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
|
// cursor.seek(SeekFrom::Current((fmt_size + fmt_size % 2) as i64)).unwrap();
|
||||||
|
|
||||||
|
// assert_eq!(cursor.read_fourcc().unwrap(), ELM1_SIG);
|
||||||
|
// let elm1_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
|
// let data_start = cursor.seek(SeekFrom::Current((elm1_size + elm1_size % 2) as i64)).unwrap();
|
||||||
|
|
||||||
|
// assert!((data_start + 8) % 0x4000 == 0, "data content start is not aligned, starts at {}", data_start + 8);
|
||||||
|
// assert_eq!(cursor.read_fourcc().unwrap(), DATA_SIG);
|
||||||
|
// assert_eq!(cursor.read_u32::<LittleEndian>().unwrap(), 0xFFFF_FFFF);
|
||||||
|
// cursor.seek(SeekFrom::Current(data_size as i64)).unwrap();
|
||||||
|
|
||||||
|
// assert_eq!(4 + 8 + ds64_size as u64 + 8 + data_size + 8 + fmt_size as u64 + 8 + elm1_size as u64, form_size)
|
||||||
|
// }
|
||||||
@@ -81,11 +81,12 @@ fn test_minimal_wave() {
|
|||||||
fn test_read() {
|
fn test_read() {
|
||||||
let path = "tests/media/audacity_16bit.wav";
|
let path = "tests/media/audacity_16bit.wav";
|
||||||
|
|
||||||
let w = WaveReader::open(path).expect("Failure opening test file");
|
let mut w = WaveReader::open(path).expect("Failure opening test file");
|
||||||
|
let mut buffer = w.format().unwrap().create_frame_buffer();
|
||||||
|
|
||||||
let mut reader = w.audio_frame_reader().unwrap();
|
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!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
|
||||||
assert_eq!(buffer[0], -2823_i32);
|
assert_eq!(buffer[0], -2823_i32);
|
||||||
@@ -99,12 +100,11 @@ fn test_read() {
|
|||||||
fn test_locate_multichannel_read() {
|
fn test_locate_multichannel_read() {
|
||||||
let path = "tests/media/ff_pink.wav";
|
let path = "tests/media/ff_pink.wav";
|
||||||
|
|
||||||
let w = WaveReader::open(path).expect("Failure opening test file");
|
let mut w = WaveReader::open(path).expect("Failure opening test file");
|
||||||
|
let mut buffer = w.format().unwrap().create_frame_buffer();
|
||||||
|
|
||||||
let mut reader = w.audio_frame_reader().unwrap();
|
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!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
|
||||||
assert_eq!(buffer[0], 332702_i32);
|
assert_eq!(buffer[0], 332702_i32);
|
||||||
assert_eq!(buffer[1], 3258791_i32);
|
assert_eq!(buffer[1], 3258791_i32);
|
||||||
|
|||||||
Reference in New Issue
Block a user