mirror of
https://github.com/iluvcapra/bwavfile.git
synced 2025-12-31 08:50:44 +00:00
prettify code
This commit is contained in:
@@ -12,16 +12,16 @@ use std::f64;
|
|||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
extern crate bwavfile;
|
extern crate bwavfile;
|
||||||
use bwavfile::{WaveWriter, WaveFmt, Error};
|
use bwavfile::{Error, WaveFmt, WaveWriter};
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate clap;
|
extern crate clap;
|
||||||
use clap::{Arg, App};
|
use clap::{App, Arg};
|
||||||
|
|
||||||
|
|
||||||
fn sine_wave(t: u64, amplitude: i32, wavelength: u32) -> i32 {
|
fn sine_wave(t: u64, amplitude: i32, wavelength: u32) -> i32 {
|
||||||
//I did it this way because I'm weird
|
//I did it this way because I'm weird
|
||||||
Some(t).map(|i| (i as f64) * 2f64 * f64::consts::PI / wavelength as f64 )
|
Some(t)
|
||||||
|
.map(|i| (i as f64) * 2f64 * f64::consts::PI / wavelength as f64)
|
||||||
.map(|f| f.sin())
|
.map(|f| f.sin())
|
||||||
.map(|s| (s * amplitude as f64) as i32)
|
.map(|s| (s * amplitude as f64) as i32)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -39,7 +39,6 @@ fn dbfs_to_signed_int(dbfs: f32, bit_depth: u16) -> i32 {
|
|||||||
((full_code as f32) * dbfs_to_f32(dbfs)) as i32
|
((full_code as f32) * dbfs_to_f32(dbfs)) as i32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq)]
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
enum ToneBurst {
|
enum ToneBurst {
|
||||||
/// Tone of .0 frequency (hz) for .1 duration (ms) at .2 dBfs
|
/// Tone of .0 frequency (hz) for .1 duration (ms) at .2 dBfs
|
||||||
@@ -52,24 +51,21 @@ impl ToneBurst {
|
|||||||
fn duration(&self, sample_rate: u32) -> u64 {
|
fn duration(&self, sample_rate: u32) -> u64 {
|
||||||
match self {
|
match self {
|
||||||
Self::Tone(_, dur, _) => *dur * sample_rate as u64 / 1000,
|
Self::Tone(_, dur, _) => *dur * sample_rate as u64 / 1000,
|
||||||
Self::Silence(dur) => *dur * sample_rate as u64 / 1000
|
Self::Silence(dur) => *dur * sample_rate as u64 / 1000,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ToneBurstSignal {
|
trait ToneBurstSignal {
|
||||||
|
|
||||||
fn duration(&self, sample_rate: u32) -> u64;
|
fn duration(&self, sample_rate: u32) -> u64;
|
||||||
|
|
||||||
fn signal(&self, t: u64, sample_rate: u32, bit_depth: u16) -> i32;
|
fn signal(&self, t: u64, sample_rate: u32, bit_depth: u16) -> i32;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ToneBurstSignal for Vec<ToneBurst> {
|
impl ToneBurstSignal for Vec<ToneBurst> {
|
||||||
|
|
||||||
fn duration(&self, sample_rate: u32) -> u64 {
|
fn duration(&self, sample_rate: u32) -> u64 {
|
||||||
self.iter().fold(0u64, |accum, &item| {
|
self.iter()
|
||||||
accum + &item.duration(sample_rate)
|
.fold(0u64, |accum, &item| accum + &item.duration(sample_rate))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signal(&self, t: u64, sample_rate: u32, bit_depth: u16) -> i32 {
|
fn signal(&self, t: u64, sample_rate: u32, bit_depth: u16) -> i32 {
|
||||||
@@ -81,22 +77,18 @@ impl ToneBurstSignal for Vec<ToneBurst> {
|
|||||||
Some((this_time_range, item))
|
Some((this_time_range, item))
|
||||||
})
|
})
|
||||||
.find(|(range, _)| range.contains(&t))
|
.find(|(range, _)| range.contains(&t))
|
||||||
.map(|(_, item)| {
|
.map(|(_, item)| match item {
|
||||||
match item {
|
|
||||||
ToneBurst::Tone(freq, _, dbfs) => {
|
ToneBurst::Tone(freq, _, dbfs) => {
|
||||||
let gain = dbfs_to_signed_int(dbfs, bit_depth);
|
let gain = dbfs_to_signed_int(dbfs, bit_depth);
|
||||||
sine_wave(t, gain, (sample_rate as f32 / freq) as u32)
|
sine_wave(t, gain, (sample_rate as f32 / freq) as u32)
|
||||||
},
|
|
||||||
ToneBurst::Silence(_) => {
|
|
||||||
0
|
|
||||||
}
|
}
|
||||||
}
|
ToneBurst::Silence(_) => 0,
|
||||||
}).unwrap_or(0i32)
|
})
|
||||||
|
.unwrap_or(0i32)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_blits_file(file_name: &str, sample_rate: u32, bits_per_sample: u16) -> Result<(), Error> {
|
fn create_blits_file(file_name: &str, sample_rate: u32, bits_per_sample: u16) -> Result<(), Error> {
|
||||||
|
|
||||||
// BLITS Tone signal format
|
// BLITS Tone signal format
|
||||||
// From EBU Tech 3304 §4 - https://tech.ebu.ch/docs/tech/tech3304.pdf
|
// From EBU Tech 3304 §4 - https://tech.ebu.ch/docs/tech/tech3304.pdf
|
||||||
let left_channel_sequence: Vec<ToneBurst> = vec![
|
let left_channel_sequence: Vec<ToneBurst> = vec![
|
||||||
@@ -104,7 +96,6 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
ToneBurst::Tone(880.0, 600, -18.0),
|
ToneBurst::Tone(880.0, 600, -18.0),
|
||||||
ToneBurst::Silence(200),
|
ToneBurst::Silence(200),
|
||||||
ToneBurst::Silence(4000),
|
ToneBurst::Silence(4000),
|
||||||
|
|
||||||
// LR ident
|
// LR ident
|
||||||
ToneBurst::Tone(1000.0, 1000, -18.0),
|
ToneBurst::Tone(1000.0, 1000, -18.0),
|
||||||
ToneBurst::Silence(300),
|
ToneBurst::Silence(300),
|
||||||
@@ -116,10 +107,9 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
ToneBurst::Silence(300),
|
ToneBurst::Silence(300),
|
||||||
ToneBurst::Tone(1000.0, 2000, -18.0),
|
ToneBurst::Tone(1000.0, 2000, -18.0),
|
||||||
ToneBurst::Silence(300),
|
ToneBurst::Silence(300),
|
||||||
|
|
||||||
// Phase check,
|
// Phase check,
|
||||||
ToneBurst::Tone(2000.0, 3000, -24.0),
|
ToneBurst::Tone(2000.0, 3000, -24.0),
|
||||||
ToneBurst::Silence(200)
|
ToneBurst::Silence(200),
|
||||||
];
|
];
|
||||||
|
|
||||||
let right_channel_sequence: Vec<ToneBurst> = vec![
|
let right_channel_sequence: Vec<ToneBurst> = vec![
|
||||||
@@ -128,14 +118,12 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
ToneBurst::Tone(880.0, 600, -18.0),
|
ToneBurst::Tone(880.0, 600, -18.0),
|
||||||
ToneBurst::Silence(200),
|
ToneBurst::Silence(200),
|
||||||
ToneBurst::Silence(3200),
|
ToneBurst::Silence(3200),
|
||||||
|
|
||||||
// LR ident
|
// LR ident
|
||||||
ToneBurst::Tone(1000.0, 5100, -18.0),
|
ToneBurst::Tone(1000.0, 5100, -18.0),
|
||||||
ToneBurst::Silence(300),
|
ToneBurst::Silence(300),
|
||||||
|
|
||||||
// Phase check,
|
// Phase check,
|
||||||
ToneBurst::Tone(2000.0, 3000, -24.0),
|
ToneBurst::Tone(2000.0, 3000, -24.0),
|
||||||
ToneBurst::Silence(200)
|
ToneBurst::Silence(200),
|
||||||
];
|
];
|
||||||
|
|
||||||
let center_channel_sequence: Vec<ToneBurst> = vec![
|
let center_channel_sequence: Vec<ToneBurst> = vec![
|
||||||
@@ -144,13 +132,11 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
ToneBurst::Tone(1320.0, 600, -18.0),
|
ToneBurst::Tone(1320.0, 600, -18.0),
|
||||||
ToneBurst::Silence(200),
|
ToneBurst::Silence(200),
|
||||||
ToneBurst::Silence(2400),
|
ToneBurst::Silence(2400),
|
||||||
|
|
||||||
// LR ident
|
// LR ident
|
||||||
ToneBurst::Silence(5400),
|
ToneBurst::Silence(5400),
|
||||||
|
|
||||||
// Phase check,
|
// Phase check,
|
||||||
ToneBurst::Tone(2000.0, 3000, -24.0),
|
ToneBurst::Tone(2000.0, 3000, -24.0),
|
||||||
ToneBurst::Silence(200)
|
ToneBurst::Silence(200),
|
||||||
];
|
];
|
||||||
|
|
||||||
let lfe_channel_sequence: Vec<ToneBurst> = vec![
|
let lfe_channel_sequence: Vec<ToneBurst> = vec![
|
||||||
@@ -159,13 +145,11 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
ToneBurst::Tone(82.5, 600, -18.0),
|
ToneBurst::Tone(82.5, 600, -18.0),
|
||||||
ToneBurst::Silence(200),
|
ToneBurst::Silence(200),
|
||||||
ToneBurst::Silence(1600),
|
ToneBurst::Silence(1600),
|
||||||
|
|
||||||
// LR ident
|
// LR ident
|
||||||
ToneBurst::Silence(5400),
|
ToneBurst::Silence(5400),
|
||||||
|
|
||||||
// Phase check,
|
// Phase check,
|
||||||
ToneBurst::Tone(2000.0, 3000, -24.0),
|
ToneBurst::Tone(2000.0, 3000, -24.0),
|
||||||
ToneBurst::Silence(200)
|
ToneBurst::Silence(200),
|
||||||
];
|
];
|
||||||
|
|
||||||
let ls_channel_sequence: Vec<ToneBurst> = vec![
|
let ls_channel_sequence: Vec<ToneBurst> = vec![
|
||||||
@@ -174,13 +158,11 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
ToneBurst::Tone(660.0, 600, -18.0),
|
ToneBurst::Tone(660.0, 600, -18.0),
|
||||||
ToneBurst::Silence(200),
|
ToneBurst::Silence(200),
|
||||||
ToneBurst::Silence(800),
|
ToneBurst::Silence(800),
|
||||||
|
|
||||||
// LR ident
|
// LR ident
|
||||||
ToneBurst::Silence(5400),
|
ToneBurst::Silence(5400),
|
||||||
|
|
||||||
// Phase check,
|
// Phase check,
|
||||||
ToneBurst::Tone(2000.0, 3000, -24.0),
|
ToneBurst::Tone(2000.0, 3000, -24.0),
|
||||||
ToneBurst::Silence(200)
|
ToneBurst::Silence(200),
|
||||||
];
|
];
|
||||||
|
|
||||||
let rs_channel_sequence: Vec<ToneBurst> = vec![
|
let rs_channel_sequence: Vec<ToneBurst> = vec![
|
||||||
@@ -188,28 +170,35 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
ToneBurst::Silence(4000),
|
ToneBurst::Silence(4000),
|
||||||
ToneBurst::Tone(660.0, 600, -18.0),
|
ToneBurst::Tone(660.0, 600, -18.0),
|
||||||
ToneBurst::Silence(200),
|
ToneBurst::Silence(200),
|
||||||
|
|
||||||
// LR ident
|
// LR ident
|
||||||
ToneBurst::Silence(5400),
|
ToneBurst::Silence(5400),
|
||||||
|
|
||||||
// Phase check,
|
// Phase check,
|
||||||
ToneBurst::Tone(2000.0, 3000, -24.0),
|
ToneBurst::Tone(2000.0, 3000, -24.0),
|
||||||
ToneBurst::Silence(200)
|
ToneBurst::Silence(200),
|
||||||
];
|
];
|
||||||
|
|
||||||
let length = [&left_channel_sequence, &right_channel_sequence,
|
let length = [
|
||||||
¢er_channel_sequence, &lfe_channel_sequence,
|
&left_channel_sequence,
|
||||||
&ls_channel_sequence, &rs_channel_sequence].iter()
|
&right_channel_sequence,
|
||||||
|
¢er_channel_sequence,
|
||||||
|
&lfe_channel_sequence,
|
||||||
|
&ls_channel_sequence,
|
||||||
|
&rs_channel_sequence,
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
.map(|i| i.duration(sample_rate))
|
.map(|i| i.duration(sample_rate))
|
||||||
.max().unwrap_or(0);
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
let frames = (0..=length).map(|frame| {
|
let frames = (0..=length).map(|frame| {
|
||||||
(left_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
(
|
||||||
|
left_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
||||||
right_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
right_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
||||||
center_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
center_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
||||||
lfe_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
lfe_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
||||||
ls_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
ls_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
||||||
rs_channel_sequence.signal(frame, sample_rate, bits_per_sample))
|
rs_channel_sequence.signal(frame, sample_rate, bits_per_sample),
|
||||||
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
let format = WaveFmt::new_pcm_multichannel(sample_rate, bits_per_sample, 0b111111);
|
let format = WaveFmt::new_pcm_multichannel(sample_rate, bits_per_sample, 0b111111);
|
||||||
@@ -227,33 +216,41 @@ fn create_blits_file(file_name: &str, sample_rate : u32, bits_per_sample : u16)
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> io::Result<()> {
|
fn main() -> io::Result<()> {
|
||||||
|
|
||||||
let matches = App::new("blits")
|
let matches = App::new("blits")
|
||||||
.version(crate_version!())
|
.version(crate_version!())
|
||||||
.author(crate_authors!())
|
.author(crate_authors!())
|
||||||
.about("Generate a BLITS 5.1 alignment tone.")
|
.about("Generate a BLITS 5.1 alignment tone.")
|
||||||
.arg(Arg::with_name("sample_rate")
|
.arg(
|
||||||
|
Arg::with_name("sample_rate")
|
||||||
.long("sample-rate")
|
.long("sample-rate")
|
||||||
.short("s")
|
.short("s")
|
||||||
.help("Sample rate of output")
|
.help("Sample rate of output")
|
||||||
.default_value("48000")
|
.default_value("48000"),
|
||||||
)
|
)
|
||||||
.arg(Arg::with_name("bit_depth")
|
.arg(
|
||||||
|
Arg::with_name("bit_depth")
|
||||||
.long("bit-depth")
|
.long("bit-depth")
|
||||||
.short("b")
|
.short("b")
|
||||||
.help("Bit depth of output")
|
.help("Bit depth of output")
|
||||||
.default_value("24")
|
.default_value("24"),
|
||||||
)
|
)
|
||||||
.arg(Arg::with_name("OUTPUT")
|
.arg(
|
||||||
|
Arg::with_name("OUTPUT")
|
||||||
.help("Output wave file")
|
.help("Output wave file")
|
||||||
.default_value("blits.wav")
|
.default_value("blits.wav"),
|
||||||
)
|
)
|
||||||
.get_matches();
|
.get_matches();
|
||||||
|
|
||||||
let sample_rate = matches.value_of("sample_rate").unwrap().parse::<u32>()
|
let sample_rate = matches
|
||||||
|
.value_of("sample_rate")
|
||||||
|
.unwrap()
|
||||||
|
.parse::<u32>()
|
||||||
.expect("Failed to read sample rate");
|
.expect("Failed to read sample rate");
|
||||||
|
|
||||||
let bits_per_sample = matches.value_of("bit_depth").unwrap().parse::<u16>()
|
let bits_per_sample = matches
|
||||||
|
.value_of("bit_depth")
|
||||||
|
.unwrap()
|
||||||
|
.parse::<u16>()
|
||||||
.expect("Failed to read bit depth");
|
.expect("Failed to read bit depth");
|
||||||
|
|
||||||
let filename = matches.value_of("OUTPUT").unwrap();
|
let filename = matches.value_of("OUTPUT").unwrap();
|
||||||
@@ -261,6 +258,6 @@ fn main() -> io::Result<()> {
|
|||||||
match create_blits_file(&filename, sample_rate, bits_per_sample) {
|
match create_blits_file(&filename, sample_rate, bits_per_sample) {
|
||||||
Err(Error::IOError(x)) => panic!("IO Error: {:?}", x),
|
Err(Error::IOError(x)) => panic!("IO Error: {:?}", x),
|
||||||
Err(err) => panic!("Error: {:?}", err),
|
Err(err) => panic!("Error: {:?}", err),
|
||||||
Ok(()) => Ok(())
|
Ok(()) => Ok(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,13 +8,18 @@ use std::io;
|
|||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
extern crate bwavfile;
|
extern crate bwavfile;
|
||||||
use bwavfile::{Error,WaveReader, WaveWriter, ChannelDescriptor, ChannelMask, WaveFmt};
|
use bwavfile::{ChannelDescriptor, ChannelMask, Error, WaveFmt, WaveReader, WaveWriter};
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate clap;
|
extern crate clap;
|
||||||
use clap::{Arg, App};
|
use clap::{App, Arg};
|
||||||
|
|
||||||
fn name_suffix(force_numeric : bool, delim : &str, index: usize, channel_descriptor : &ChannelDescriptor) -> String {
|
fn name_suffix(
|
||||||
|
force_numeric: bool,
|
||||||
|
delim: &str,
|
||||||
|
index: usize,
|
||||||
|
channel_descriptor: &ChannelDescriptor,
|
||||||
|
) -> String {
|
||||||
if force_numeric || channel_descriptor.speaker == ChannelMask::DirectOut {
|
if force_numeric || channel_descriptor.speaker == ChannelMask::DirectOut {
|
||||||
format!("{}A{:02}", delim, index)
|
format!("{}A{:02}", delim, index)
|
||||||
} else {
|
} else {
|
||||||
@@ -37,7 +42,7 @@ fn name_suffix(force_numeric : bool, delim : &str, index: usize, channel_descrip
|
|||||||
ChannelMask::TopBackLeft => "Ltb",
|
ChannelMask::TopBackLeft => "Ltb",
|
||||||
ChannelMask::TopBackCenter => "Ctb",
|
ChannelMask::TopBackCenter => "Ctb",
|
||||||
ChannelMask::TopBackRight => "Rtb",
|
ChannelMask::TopBackRight => "Rtb",
|
||||||
ChannelMask::DirectOut => panic!("Error, can't get here")
|
ChannelMask::DirectOut => panic!("Error, can't get here"),
|
||||||
};
|
};
|
||||||
format!("{}{}", delim, chan_name)
|
format!("{}{}", delim, chan_name)
|
||||||
}
|
}
|
||||||
@@ -54,20 +59,31 @@ fn process_file(infile: &str, delim : &str, numeric_channel_names : bool) -> Res
|
|||||||
}
|
}
|
||||||
|
|
||||||
let infile_path = Path::new(infile);
|
let infile_path = Path::new(infile);
|
||||||
let basename = infile_path.file_stem().expect("Unable to extract file basename").to_str().unwrap();
|
let basename = infile_path
|
||||||
let output_dir = infile_path.parent().expect("Unable to derive parent directory");
|
.file_stem()
|
||||||
|
.expect("Unable to extract file basename")
|
||||||
|
.to_str()
|
||||||
|
.unwrap();
|
||||||
|
let output_dir = infile_path
|
||||||
|
.parent()
|
||||||
|
.expect("Unable to derive parent directory");
|
||||||
|
|
||||||
let ouptut_format = WaveFmt::new_pcm_mono(input_format.sample_rate, input_format.bits_per_sample);
|
let ouptut_format =
|
||||||
|
WaveFmt::new_pcm_mono(input_format.sample_rate, input_format.bits_per_sample);
|
||||||
let mut input_wave_reader = input_file.audio_frame_reader()?;
|
let mut input_wave_reader = input_file.audio_frame_reader()?;
|
||||||
|
|
||||||
for (n, channel) in channel_desc.iter().enumerate() {
|
for (n, channel) in channel_desc.iter().enumerate() {
|
||||||
let suffix = name_suffix(numeric_channel_names, delim, n + 1, channel);
|
let suffix = name_suffix(numeric_channel_names, delim, n + 1, channel);
|
||||||
let outfile_name = output_dir.join(format!("{}{}.wav", basename, suffix))
|
let outfile_name = output_dir
|
||||||
.into_os_string().into_string().unwrap();
|
.join(format!("{}{}.wav", basename, suffix))
|
||||||
|
.into_os_string()
|
||||||
|
.into_string()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
println!("Will create file {}", outfile_name);
|
println!("Will create file {}", outfile_name);
|
||||||
|
|
||||||
let output_file = WaveWriter::create(&outfile_name, ouptut_format).expect("Failed to create new file");
|
let output_file =
|
||||||
|
WaveWriter::create(&outfile_name, ouptut_format).expect("Failed to create new file");
|
||||||
|
|
||||||
let mut output_wave_writer = output_file.audio_frame_writer()?;
|
let mut output_wave_writer = output_file.audio_frame_writer()?;
|
||||||
let mut buffer = input_format.create_frame_buffer(1);
|
let mut buffer = input_format.create_frame_buffer(1);
|
||||||
@@ -88,22 +104,25 @@ fn main() -> io::Result<()> {
|
|||||||
.version(crate_version!())
|
.version(crate_version!())
|
||||||
.author(crate_authors!())
|
.author(crate_authors!())
|
||||||
.about("Extract each channel of a polyphonic wave file as a new monoaural wave file.")
|
.about("Extract each channel of a polyphonic wave file as a new monoaural wave file.")
|
||||||
.arg(Arg::with_name("numeric_names")
|
.arg(
|
||||||
|
Arg::with_name("numeric_names")
|
||||||
.long("numeric")
|
.long("numeric")
|
||||||
.short("n")
|
.short("n")
|
||||||
.help("Use numeric channel names \"01\" \"02\" etc.")
|
.help("Use numeric channel names \"01\" \"02\" etc.")
|
||||||
.takes_value(false)
|
.takes_value(false),
|
||||||
)
|
)
|
||||||
.arg(Arg::with_name("channel_delimiter")
|
.arg(
|
||||||
|
Arg::with_name("channel_delimiter")
|
||||||
.long("delim")
|
.long("delim")
|
||||||
.short("d")
|
.short("d")
|
||||||
.help("Channel label delimiter.")
|
.help("Channel label delimiter.")
|
||||||
.default_value(".")
|
.default_value("."),
|
||||||
)
|
)
|
||||||
.arg(Arg::with_name("INPUT")
|
.arg(
|
||||||
|
Arg::with_name("INPUT")
|
||||||
.help("Input wave file")
|
.help("Input wave file")
|
||||||
.required(true)
|
.required(true)
|
||||||
.multiple(true)
|
.multiple(true),
|
||||||
)
|
)
|
||||||
.get_matches();
|
.get_matches();
|
||||||
|
|
||||||
@@ -114,6 +133,6 @@ fn main() -> io::Result<()> {
|
|||||||
match process_file(infile, delimiter, use_numeric_names) {
|
match process_file(infile, delimiter, use_numeric_names) {
|
||||||
Err(Error::IOError(io)) => Err(io),
|
Err(Error::IOError(io)) => Err(io),
|
||||||
Err(e) => panic!("Error: {:?}", e),
|
Err(e) => panic!("Error: {:?}", e),
|
||||||
Ok(()) => Ok(())
|
Ok(()) => Ok(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ extern crate bwavfile;
|
|||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate clap;
|
extern crate clap;
|
||||||
use clap::{Arg, App};
|
use clap::{App, Arg};
|
||||||
|
|
||||||
fn main() -> io::Result<()> {
|
fn main() -> io::Result<()> {
|
||||||
let matches = App::new("wave-inter")
|
let matches = App::new("wave-inter")
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
|
|
||||||
pub type LU = f32;
|
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
|
||||||
@@ -26,7 +24,6 @@ pub type Decibels = f32;
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Bext {
|
pub struct Bext {
|
||||||
|
|
||||||
/// 256 ASCII character field with free text.
|
/// 256 ASCII character field with free text.
|
||||||
pub description: String,
|
pub description: String,
|
||||||
|
|
||||||
@@ -82,7 +79,6 @@ pub struct Bext {
|
|||||||
/// This field is `None` if the version is less than 2.
|
/// This field is `None` if the version is less than 2.
|
||||||
pub max_short_term_loudness: Option<LUFS>,
|
pub max_short_term_loudness: Option<LUFS>,
|
||||||
// 180 bytes of nothing
|
// 180 bytes of nothing
|
||||||
|
|
||||||
/// Coding History.
|
/// Coding History.
|
||||||
pub coding_history: String
|
pub coding_history: String,
|
||||||
}
|
}
|
||||||
|
|||||||
127
src/chunks.rs
127
src/chunks.rs
@@ -1,17 +1,17 @@
|
|||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
|
||||||
use encoding::{DecoderTrap, EncoderTrap};
|
|
||||||
use encoding::{Encoding};
|
|
||||||
use encoding::all::ASCII;
|
use encoding::all::ASCII;
|
||||||
|
use encoding::Encoding;
|
||||||
|
use encoding::{DecoderTrap, EncoderTrap};
|
||||||
|
|
||||||
use byteorder::LittleEndian;
|
use byteorder::LittleEndian;
|
||||||
use byteorder::{ReadBytesExt, WriteBytesExt};
|
use byteorder::{ReadBytesExt, WriteBytesExt};
|
||||||
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::bext::Bext;
|
||||||
use super::errors::Error as ParserError;
|
use super::errors::Error as ParserError;
|
||||||
use super::fmt::{WaveFmt, WaveFmtExtended};
|
use super::fmt::{WaveFmt, WaveFmtExtended};
|
||||||
use super::bext::Bext;
|
|
||||||
|
|
||||||
pub trait ReadBWaveChunks: Read {
|
pub trait ReadBWaveChunks: Read {
|
||||||
fn read_bext(&mut self) -> Result<Bext, ParserError>;
|
fn read_bext(&mut self) -> Result<Bext, ParserError>;
|
||||||
@@ -21,11 +21,18 @@ pub trait ReadBWaveChunks: Read {
|
|||||||
|
|
||||||
pub trait WriteBWaveChunks: Write {
|
pub trait WriteBWaveChunks: Write {
|
||||||
fn write_wave_fmt(&mut self, format: &WaveFmt) -> Result<(), ParserError>;
|
fn write_wave_fmt(&mut self, format: &WaveFmt) -> Result<(), ParserError>;
|
||||||
fn write_bext_string_field(&mut self, string: &String, length: usize) -> Result<(),ParserError>;
|
fn write_bext_string_field(
|
||||||
|
&mut self,
|
||||||
|
string: &String,
|
||||||
|
length: usize,
|
||||||
|
) -> Result<(), ParserError>;
|
||||||
fn write_bext(&mut self, bext: &Bext) -> Result<(), ParserError>;
|
fn write_bext(&mut self, bext: &Bext) -> Result<(), ParserError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
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 as u16)?;
|
self.write_u16::<LittleEndian>(format.tag as u16)?;
|
||||||
self.write_u16::<LittleEndian>(format.channel_count)?;
|
self.write_u16::<LittleEndian>(format.channel_count)?;
|
||||||
@@ -44,8 +51,14 @@ impl<T> WriteBWaveChunks for T where T: Write {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_bext_string_field(&mut self, string: &String, length: usize) -> Result<(),ParserError> {
|
fn write_bext_string_field(
|
||||||
let mut buf = ASCII.encode(&string, EncoderTrap::Ignore).expect("Error encoding text");
|
&mut self,
|
||||||
|
string: &String,
|
||||||
|
length: usize,
|
||||||
|
) -> Result<(), ParserError> {
|
||||||
|
let mut buf = ASCII
|
||||||
|
.encode(&string, EncoderTrap::Ignore)
|
||||||
|
.expect("Error encoding text");
|
||||||
buf.truncate(length);
|
buf.truncate(length);
|
||||||
let filler_length = length - buf.len();
|
let filler_length = length - buf.len();
|
||||||
if filler_length > 0 {
|
if filler_length > 0 {
|
||||||
@@ -69,21 +82,21 @@ impl<T> WriteBWaveChunks for T where T: Write {
|
|||||||
let buf = bext.umid.unwrap_or([0u8; 64]);
|
let buf = bext.umid.unwrap_or([0u8; 64]);
|
||||||
self.write_all(&buf)?;
|
self.write_all(&buf)?;
|
||||||
|
|
||||||
|
self.write_i16::<LittleEndian>((bext.loudness_value.unwrap_or(0.0) * 100.0) as i16)?;
|
||||||
|
self.write_i16::<LittleEndian>((bext.loudness_range.unwrap_or(0.0) * 100.0) as i16)?;
|
||||||
|
self.write_i16::<LittleEndian>((bext.max_true_peak_level.unwrap_or(0.0) * 100.0) as i16)?;
|
||||||
self.write_i16::<LittleEndian>(
|
self.write_i16::<LittleEndian>(
|
||||||
(bext.loudness_value.unwrap_or(0.0) * 100.0) as i16 )?;
|
(bext.max_momentary_loudness.unwrap_or(0.0) * 100.0) as i16,
|
||||||
|
)?;
|
||||||
self.write_i16::<LittleEndian>(
|
self.write_i16::<LittleEndian>(
|
||||||
(bext.loudness_range.unwrap_or(0.0) * 100.0) as i16 )?;
|
(bext.max_short_term_loudness.unwrap_or(0.0) * 100.0) as i16,
|
||||||
self.write_i16::<LittleEndian>(
|
)?;
|
||||||
(bext.max_true_peak_level.unwrap_or(0.0) * 100.0) as i16 )?;
|
|
||||||
self.write_i16::<LittleEndian>(
|
|
||||||
(bext.max_momentary_loudness.unwrap_or(0.0) * 100.0) as i16 )?;
|
|
||||||
self.write_i16::<LittleEndian>(
|
|
||||||
(bext.max_short_term_loudness.unwrap_or(0.0) * 100.0) as i16 )?;
|
|
||||||
|
|
||||||
let padding = [0u8; 180];
|
let padding = [0u8; 180];
|
||||||
self.write_all(&padding)?;
|
self.write_all(&padding)?;
|
||||||
|
|
||||||
let coding = ASCII.encode(&bext.coding_history, EncoderTrap::Ignore)
|
let coding = ASCII
|
||||||
|
.encode(&bext.coding_history, EncoderTrap::Ignore)
|
||||||
.expect("Error");
|
.expect("Error");
|
||||||
|
|
||||||
self.write_all(&coding)?;
|
self.write_all(&coding)?;
|
||||||
@@ -91,8 +104,10 @@ 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;
|
let tag_value: u16;
|
||||||
Ok(WaveFmt {
|
Ok(WaveFmt {
|
||||||
@@ -116,20 +131,26 @@ impl<T> ReadBWaveChunks for T where T: Read {
|
|||||||
let mut buf: [u8; 16] = [0; 16];
|
let mut buf: [u8; 16] = [0; 16];
|
||||||
self.read_exact(&mut buf)?;
|
self.read_exact(&mut buf)?;
|
||||||
Uuid::from_slice(&buf)?
|
Uuid::from_slice(&buf)?
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_bext_string_field(&mut self, length: usize) -> Result<String, ParserError> {
|
fn read_bext_string_field(&mut self, length: usize) -> Result<String, ParserError> {
|
||||||
let mut buffer: Vec<u8> = vec![0; length];
|
let mut buffer: Vec<u8> = vec![0; length];
|
||||||
self.read(&mut buffer)?;
|
self.read(&mut buffer)?;
|
||||||
let trimmed : Vec<u8> = buffer.iter().take_while(|c| **c != 0 as u8).cloned().collect();
|
let trimmed: Vec<u8> = buffer
|
||||||
Ok(ASCII.decode(&trimmed, DecoderTrap::Ignore).expect("Error decoding text"))
|
.iter()
|
||||||
|
.take_while(|c| **c != 0 as u8)
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
Ok(ASCII
|
||||||
|
.decode(&trimmed, DecoderTrap::Ignore)
|
||||||
|
.expect("Error decoding text"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_bext(&mut self) -> Result<Bext, ParserError> {
|
fn read_bext(&mut self) -> Result<Bext, ParserError> {
|
||||||
@@ -148,42 +169,70 @@ impl<T> ReadBWaveChunks for T where T: Read {
|
|||||||
umid: {
|
umid: {
|
||||||
let mut buf = [0u8; 64];
|
let mut buf = [0u8; 64];
|
||||||
self.read(&mut buf)?;
|
self.read(&mut buf)?;
|
||||||
if version > 0 { Some(buf) } else { None }
|
if version > 0 {
|
||||||
|
Some(buf)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
},
|
},
|
||||||
loudness_value: {
|
loudness_value: {
|
||||||
let val = (self.read_i16::<LittleEndian>()? as f32) / 100f32;
|
let val = (self.read_i16::<LittleEndian>()? as f32) / 100f32;
|
||||||
if version > 1 { Some(val) } else { None }
|
if version > 1 {
|
||||||
|
Some(val)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
},
|
},
|
||||||
loudness_range: {
|
loudness_range: {
|
||||||
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
||||||
if version > 1 { Some(val) } else { None }
|
if version > 1 {
|
||||||
|
Some(val)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
},
|
},
|
||||||
max_true_peak_level: {
|
max_true_peak_level: {
|
||||||
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
||||||
if version > 1 { Some(val) } else { None }
|
if version > 1 {
|
||||||
|
Some(val)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
},
|
},
|
||||||
max_momentary_loudness: {
|
max_momentary_loudness: {
|
||||||
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
||||||
if version > 1 { Some(val) } else { None }
|
if version > 1 {
|
||||||
|
Some(val)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
},
|
},
|
||||||
max_short_term_loudness: {
|
max_short_term_loudness: {
|
||||||
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
let val = self.read_i16::<LittleEndian>()? as f32 / 100f32;
|
||||||
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]
|
#[test]
|
||||||
fn test_read_51_wav() {
|
fn test_read_51_wav() {
|
||||||
use super::fmt::ChannelMask;
|
|
||||||
use super::common_format::CommonFormat;
|
use super::common_format::CommonFormat;
|
||||||
|
use super::fmt::ChannelMask;
|
||||||
|
|
||||||
let path = "tests/media/pt_24bit_51.wav";
|
let path = "tests/media/pt_24bit_51.wav";
|
||||||
|
|
||||||
@@ -198,9 +247,17 @@ fn test_read_51_wav() {
|
|||||||
|
|
||||||
let channels = ChannelMask::channels(extended.channel_mask, format.channel_count);
|
let channels = ChannelMask::channels(extended.channel_mask, format.channel_count);
|
||||||
|
|
||||||
assert_eq!(channels, [ChannelMask::FrontLeft, ChannelMask::FrontRight,
|
assert_eq!(
|
||||||
ChannelMask::FrontCenter, ChannelMask::LowFrequency,
|
channels,
|
||||||
ChannelMask::BackLeft, ChannelMask::BackRight]);
|
[
|
||||||
|
ChannelMask::FrontLeft,
|
||||||
|
ChannelMask::FrontRight,
|
||||||
|
ChannelMask::FrontCenter,
|
||||||
|
ChannelMask::LowFrequency,
|
||||||
|
ChannelMask::BackLeft,
|
||||||
|
ChannelMask::BackRight
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
assert_eq!(format.common_format(), CommonFormat::IntegerPCM);
|
assert_eq!(format.common_format(), CommonFormat::IntegerPCM);
|
||||||
}
|
}
|
||||||
@@ -15,21 +15,25 @@ const BASIC_EXTENDED: u16 = 0xFFFE;
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
pub const UUID_PCM: Uuid = Uuid::from_bytes([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
pub const UUID_PCM: Uuid = Uuid::from_bytes([
|
||||||
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71,
|
||||||
|
]);
|
||||||
|
|
||||||
pub const UUID_FLOAT: Uuid = Uuid::from_bytes([0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
pub const UUID_FLOAT: Uuid = Uuid::from_bytes([
|
||||||
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71,
|
||||||
|
]);
|
||||||
|
|
||||||
pub const UUID_MPEG: Uuid = Uuid::from_bytes([0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00,
|
pub const UUID_MPEG: Uuid = Uuid::from_bytes([
|
||||||
0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
|
0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71,
|
||||||
|
]);
|
||||||
|
|
||||||
pub 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([
|
||||||
0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00]);
|
0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1, 0xca, 0x00, 0x00, 0x00,
|
||||||
|
]);
|
||||||
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]);
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
]);
|
||||||
|
|
||||||
fn uuid_from_basic_tag(tag: u16) -> Uuid {
|
fn uuid_from_basic_tag(tag: u16) -> Uuid {
|
||||||
let tail: [u8; 6] = [0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71];
|
let tail: [u8; 6] = [0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71];
|
||||||
@@ -75,7 +79,7 @@ impl CommonFormat {
|
|||||||
(BASIC_EXTENDED, Some(UUID_BFORMAT_PCM)) => Self::AmbisonicBFormatIntegerPCM,
|
(BASIC_EXTENDED, Some(UUID_BFORMAT_PCM)) => Self::AmbisonicBFormatIntegerPCM,
|
||||||
(BASIC_EXTENDED, Some(UUID_BFORMAT_FLOAT)) => Self::AmbisonicBFormatIeeeFloatPCM,
|
(BASIC_EXTENDED, Some(UUID_BFORMAT_FLOAT)) => Self::AmbisonicBFormatIeeeFloatPCM,
|
||||||
(BASIC_EXTENDED, Some(x)) => CommonFormat::UnknownExtended(x),
|
(BASIC_EXTENDED, Some(x)) => CommonFormat::UnknownExtended(x),
|
||||||
(x, _) => CommonFormat::UnknownBasic(x)
|
(x, _) => CommonFormat::UnknownBasic(x),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,7 +95,7 @@ impl CommonFormat {
|
|||||||
Self::AmbisonicBFormatIntegerPCM => (BASIC_EXTENDED, UUID_BFORMAT_PCM),
|
Self::AmbisonicBFormatIntegerPCM => (BASIC_EXTENDED, UUID_BFORMAT_PCM),
|
||||||
Self::AmbisonicBFormatIeeeFloatPCM => (BASIC_EXTENDED, UUID_BFORMAT_FLOAT),
|
Self::AmbisonicBFormatIeeeFloatPCM => (BASIC_EXTENDED, UUID_BFORMAT_FLOAT),
|
||||||
Self::UnknownBasic(x) => (x, uuid_from_basic_tag(x)),
|
Self::UnknownBasic(x) => (x, uuid_from_basic_tag(x)),
|
||||||
Self::UnknownExtended(x) => ( BASIC_EXTENDED, x)
|
Self::UnknownExtended(x) => (BASIC_EXTENDED, x),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
149
src/cue.rs
149
src/cue.rs
@@ -1,12 +1,13 @@
|
|||||||
use super::fourcc::{FourCC,ReadFourCC, WriteFourCC, LABL_SIG, NOTE_SIG,
|
use super::fourcc::{
|
||||||
ADTL_SIG, LTXT_SIG, DATA_SIG};
|
FourCC, ReadFourCC, WriteFourCC, ADTL_SIG, DATA_SIG, LABL_SIG, LTXT_SIG, NOTE_SIG,
|
||||||
|
};
|
||||||
use super::list_form::collect_list_form;
|
use super::list_form::collect_list_form;
|
||||||
|
|
||||||
use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian};
|
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
|
||||||
|
|
||||||
use encoding::{DecoderTrap,EncoderTrap};
|
|
||||||
use encoding::{Encoding};
|
|
||||||
use encoding::all::ASCII;
|
use encoding::all::ASCII;
|
||||||
|
use encoding::Encoding;
|
||||||
|
use encoding::{DecoderTrap, EncoderTrap};
|
||||||
|
|
||||||
use std::io::{Cursor, Error, Read, Write};
|
use std::io::{Cursor, Error, Read, Write};
|
||||||
|
|
||||||
@@ -17,11 +18,10 @@ struct RawCue {
|
|||||||
chunk_id: FourCC,
|
chunk_id: FourCC,
|
||||||
chunk_start: u32,
|
chunk_start: u32,
|
||||||
block_start: u32,
|
block_start: u32,
|
||||||
frame_offset : u32
|
frame_offset: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RawCue {
|
impl RawCue {
|
||||||
|
|
||||||
fn write_to(cues: Vec<Self>) -> Vec<u8> {
|
fn write_to(cues: Vec<Self>) -> Vec<u8> {
|
||||||
let mut writer = Cursor::new(vec![0u8; 0]);
|
let mut writer = Cursor::new(vec![0u8; 0]);
|
||||||
|
|
||||||
@@ -50,7 +50,7 @@ impl RawCue {
|
|||||||
chunk_id: rdr.read_fourcc()?,
|
chunk_id: rdr.read_fourcc()?,
|
||||||
chunk_start: rdr.read_u32::<LittleEndian>()?,
|
chunk_start: rdr.read_u32::<LittleEndian>()?,
|
||||||
block_start: rdr.read_u32::<LittleEndian>()?,
|
block_start: rdr.read_u32::<LittleEndian>()?,
|
||||||
frame_offset : rdr.read_u32::<LittleEndian>()?
|
frame_offset: rdr.read_u32::<LittleEndian>()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,14 +61,15 @@ impl RawCue {
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
struct RawLabel {
|
struct RawLabel {
|
||||||
cue_point_id: u32,
|
cue_point_id: u32,
|
||||||
text : Vec<u8>
|
text: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RawLabel {
|
impl RawLabel {
|
||||||
|
|
||||||
fn write_to(&self) -> Vec<u8> {
|
fn write_to(&self) -> Vec<u8> {
|
||||||
let mut writer = Cursor::new(vec![0u8; 0]);
|
let mut writer = Cursor::new(vec![0u8; 0]);
|
||||||
writer.write_u32::<LittleEndian>(self.cue_point_id as u32).unwrap();
|
writer
|
||||||
|
.write_u32::<LittleEndian>(self.cue_point_id as u32)
|
||||||
|
.unwrap();
|
||||||
writer.write(&self.text).unwrap();
|
writer.write(&self.text).unwrap();
|
||||||
writer.into_inner()
|
writer.into_inner()
|
||||||
}
|
}
|
||||||
@@ -83,7 +84,7 @@ impl RawLabel {
|
|||||||
let mut buf = vec![0u8; (length - 4) as usize];
|
let mut buf = vec![0u8; (length - 4) as usize];
|
||||||
rdr.read_exact(&mut buf)?;
|
rdr.read_exact(&mut buf)?;
|
||||||
buf
|
buf
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,11 +92,10 @@ impl RawLabel {
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
struct RawNote {
|
struct RawNote {
|
||||||
cue_point_id: u32,
|
cue_point_id: u32,
|
||||||
text : Vec<u8>
|
text: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RawNote {
|
impl RawNote {
|
||||||
|
|
||||||
fn write_to(&self) -> Vec<u8> {
|
fn write_to(&self) -> Vec<u8> {
|
||||||
let mut writer = Cursor::new(vec![0u8; 0]);
|
let mut writer = Cursor::new(vec![0u8; 0]);
|
||||||
writer.write_u32::<LittleEndian>(self.cue_point_id).unwrap();
|
writer.write_u32::<LittleEndian>(self.cue_point_id).unwrap();
|
||||||
@@ -113,7 +113,7 @@ impl RawNote {
|
|||||||
let mut buf = vec![0u8; (length - 4) as usize];
|
let mut buf = vec![0u8; (length - 4) as usize];
|
||||||
rdr.read_exact(&mut buf)?;
|
rdr.read_exact(&mut buf)?;
|
||||||
buf
|
buf
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -127,11 +127,10 @@ struct RawLtxt {
|
|||||||
language: u16,
|
language: u16,
|
||||||
dialect: u16,
|
dialect: u16,
|
||||||
code_page: u16,
|
code_page: u16,
|
||||||
text: Option<Vec<u8>>
|
text: Option<Vec<u8>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RawLtxt {
|
impl RawLtxt {
|
||||||
|
|
||||||
fn write_to(&self) -> Vec<u8> {
|
fn write_to(&self) -> Vec<u8> {
|
||||||
let mut writer = Cursor::new(vec![0u8; 0]);
|
let mut writer = Cursor::new(vec![0u8; 0]);
|
||||||
writer.write_u32::<LittleEndian>(self.cue_point_id).unwrap();
|
writer.write_u32::<LittleEndian>(self.cue_point_id).unwrap();
|
||||||
@@ -167,7 +166,7 @@ impl RawLtxt {
|
|||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -177,7 +176,7 @@ enum RawAdtlMember {
|
|||||||
Label(RawLabel),
|
Label(RawLabel),
|
||||||
Note(RawNote),
|
Note(RawNote),
|
||||||
LabeledText(RawLtxt),
|
LabeledText(RawLtxt),
|
||||||
Unrecognized(FourCC)
|
Unrecognized(FourCC),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RawAdtlMember {
|
impl RawAdtlMember {
|
||||||
@@ -189,18 +188,22 @@ impl RawAdtlMember {
|
|||||||
RawAdtlMember::Label(l) => ((LABL_SIG, l.write_to())),
|
RawAdtlMember::Label(l) => ((LABL_SIG, l.write_to())),
|
||||||
RawAdtlMember::Note(n) => ((NOTE_SIG, n.write_to())),
|
RawAdtlMember::Note(n) => ((NOTE_SIG, n.write_to())),
|
||||||
RawAdtlMember::LabeledText(t) => ((LTXT_SIG, t.write_to())),
|
RawAdtlMember::LabeledText(t) => ((LTXT_SIG, t.write_to())),
|
||||||
RawAdtlMember::Unrecognized(f) => (*f, vec![0u8;0] ) // <-- this is a dopey case but here for completeness
|
RawAdtlMember::Unrecognized(f) => (*f, vec![0u8; 0]), // <-- this is a dopey case but here for completeness
|
||||||
};
|
};
|
||||||
w.write_fourcc(fcc).unwrap();
|
w.write_fourcc(fcc).unwrap();
|
||||||
w.write_u32::<LittleEndian>(buf.len() as u32).unwrap();
|
w.write_u32::<LittleEndian>(buf.len() as u32).unwrap();
|
||||||
w.write(&buf).unwrap();
|
w.write(&buf).unwrap();
|
||||||
if buf.len() % 2 == 1 { w.write_u8(0).unwrap(); }
|
if buf.len() % 2 == 1 {
|
||||||
|
w.write_u8(0).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let chunk_content = w.into_inner();
|
let chunk_content = w.into_inner();
|
||||||
let mut writer = Cursor::new(vec![0u8; 0]);
|
let mut writer = Cursor::new(vec![0u8; 0]);
|
||||||
writer.write_fourcc(ADTL_SIG).unwrap();
|
writer.write_fourcc(ADTL_SIG).unwrap();
|
||||||
writer.write_u32::<LittleEndian>(chunk_content.len() as u32).unwrap();
|
writer
|
||||||
|
.write_u32::<LittleEndian>(chunk_content.len() as u32)
|
||||||
|
.unwrap();
|
||||||
writer.write(&chunk_content).unwrap();
|
writer.write(&chunk_content).unwrap();
|
||||||
writer.into_inner()
|
writer.into_inner()
|
||||||
}
|
}
|
||||||
@@ -210,14 +213,12 @@ impl RawAdtlMember {
|
|||||||
let mut retval: Vec<RawAdtlMember> = vec![];
|
let mut retval: Vec<RawAdtlMember> = vec![];
|
||||||
|
|
||||||
for chunk in chunks.iter() {
|
for chunk in chunks.iter() {
|
||||||
retval.push(
|
retval.push(match chunk.signature {
|
||||||
match chunk.signature {
|
|
||||||
LABL_SIG => RawAdtlMember::Label(RawLabel::read_from(&chunk.contents)?),
|
LABL_SIG => RawAdtlMember::Label(RawLabel::read_from(&chunk.contents)?),
|
||||||
NOTE_SIG => RawAdtlMember::Note(RawNote::read_from(&chunk.contents)?),
|
NOTE_SIG => RawAdtlMember::Note(RawNote::read_from(&chunk.contents)?),
|
||||||
LTXT_SIG => RawAdtlMember::LabeledText(RawLtxt::read_from(&chunk.contents)?),
|
LTXT_SIG => RawAdtlMember::LabeledText(RawLtxt::read_from(&chunk.contents)?),
|
||||||
x => RawAdtlMember::Unrecognized(x)
|
x => RawAdtlMember::Unrecognized(x),
|
||||||
}
|
})
|
||||||
)
|
|
||||||
}
|
}
|
||||||
Ok(retval)
|
Ok(retval)
|
||||||
}
|
}
|
||||||
@@ -230,33 +231,29 @@ trait AdtlMemberSearch {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AdtlMemberSearch for Vec<RawAdtlMember> {
|
impl AdtlMemberSearch for Vec<RawAdtlMember> {
|
||||||
|
|
||||||
fn labels_for_cue_point(&self, id: u32) -> Vec<&RawLabel> {
|
fn labels_for_cue_point(&self, id: u32) -> Vec<&RawLabel> {
|
||||||
self.iter().filter_map(|item| {
|
self.iter()
|
||||||
match item {
|
.filter_map(|item| match item {
|
||||||
RawAdtlMember::Label(x) if x.cue_point_id == id => Some(x),
|
RawAdtlMember::Label(x) if x.cue_point_id == id => Some(x),
|
||||||
_ => None
|
_ => None,
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn notes_for_cue_point(&self, id: u32) -> Vec<&RawNote> {
|
fn notes_for_cue_point(&self, id: u32) -> Vec<&RawNote> {
|
||||||
self.iter().filter_map(|item| {
|
self.iter()
|
||||||
match item {
|
.filter_map(|item| match item {
|
||||||
RawAdtlMember::Note(x) if x.cue_point_id == id => Some(x),
|
RawAdtlMember::Note(x) if x.cue_point_id == id => Some(x),
|
||||||
_ => None
|
_ => None,
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ltxt_for_cue_point(&self, id: u32) -> Vec<&RawLtxt> {
|
fn ltxt_for_cue_point(&self, id: u32) -> Vec<&RawLtxt> {
|
||||||
self.iter().filter_map(|item| {
|
self.iter()
|
||||||
match item {
|
.filter_map(|item| match item {
|
||||||
RawAdtlMember::LabeledText(x) if x.cue_point_id == id => Some(x),
|
RawAdtlMember::LabeledText(x) if x.cue_point_id == id => Some(x),
|
||||||
_ => None
|
_ => None,
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -270,7 +267,6 @@ impl AdtlMemberSearch for Vec<RawAdtlMember> {
|
|||||||
/// ### Not Implemented
|
/// ### Not Implemented
|
||||||
/// - [EBU 3285 Supplement 2](https://tech.ebu.ch/docs/tech/tech3285s2.pdf) (July 2001): Quality chunk and cuesheet
|
/// - [EBU 3285 Supplement 2](https://tech.ebu.ch/docs/tech/tech3285s2.pdf) (July 2001): Quality chunk and cuesheet
|
||||||
pub struct Cue {
|
pub struct Cue {
|
||||||
|
|
||||||
/// The time of this marker
|
/// The time of this marker
|
||||||
pub frame: u32,
|
pub frame: u32,
|
||||||
|
|
||||||
@@ -290,24 +286,31 @@ pub struct Cue {
|
|||||||
/// marker position to *both* fields, while a Sound Devices
|
/// marker position to *both* fields, while a Sound Devices
|
||||||
/// recorder writes the marker position to *only* the `offset`
|
/// recorder writes the marker position to *only* the `offset`
|
||||||
/// field.
|
/// field.
|
||||||
pub offset : u32
|
pub offset: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fn convert_to_cue_string(buffer: &[u8]) -> String {
|
fn convert_to_cue_string(buffer: &[u8]) -> String {
|
||||||
let trimmed : Vec<u8> = buffer.iter().take_while(|c| **c != 0 as u8).cloned().collect();
|
let trimmed: Vec<u8> = buffer
|
||||||
ASCII.decode(&trimmed, DecoderTrap::Ignore).expect("Error decoding text")
|
.iter()
|
||||||
|
.take_while(|c| **c != 0 as u8)
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
ASCII
|
||||||
|
.decode(&trimmed, DecoderTrap::Ignore)
|
||||||
|
.expect("Error decoding text")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn convert_from_cue_string(val: &str) -> Vec<u8> {
|
fn convert_from_cue_string(val: &str) -> Vec<u8> {
|
||||||
ASCII.encode(&val, EncoderTrap::Ignore).expect("Error encoding text")
|
ASCII
|
||||||
|
.encode(&val, EncoderTrap::Ignore)
|
||||||
|
.expect("Error encoding text")
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Cue {
|
impl Cue {
|
||||||
|
|
||||||
/// Take a list of `Cue`s and convert it into `RawCue` and `RawAdtlMember`s
|
/// Take a list of `Cue`s and convert it into `RawCue` and `RawAdtlMember`s
|
||||||
fn compile_to(cues: &[Cue]) -> (Vec<RawCue>, Vec<RawAdtlMember>) {
|
fn compile_to(cues: &[Cue]) -> (Vec<RawCue>, Vec<RawAdtlMember>) {
|
||||||
cues.iter().enumerate()
|
cues.iter()
|
||||||
|
.enumerate()
|
||||||
.map(|(n, cue)| {
|
.map(|(n, cue)| {
|
||||||
let raw_cue = RawCue {
|
let raw_cue = RawCue {
|
||||||
cue_point_id: n as u32,
|
cue_point_id: n as u32,
|
||||||
@@ -315,25 +318,20 @@ impl Cue {
|
|||||||
chunk_id: DATA_SIG,
|
chunk_id: DATA_SIG,
|
||||||
chunk_start: 0,
|
chunk_start: 0,
|
||||||
block_start: 0,
|
block_start: 0,
|
||||||
frame_offset: cue.offset
|
frame_offset: cue.offset,
|
||||||
};
|
};
|
||||||
|
|
||||||
let raw_label = cue.label.as_ref().map(|val| {
|
let raw_label = cue.label.as_ref().map(|val| RawLabel {
|
||||||
RawLabel {
|
|
||||||
cue_point_id: n as u32,
|
cue_point_id: n as u32,
|
||||||
text: convert_from_cue_string(&val)
|
text: convert_from_cue_string(&val),
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let raw_note = cue.note.as_ref().map(|val| {
|
let raw_note = cue.note.as_ref().map(|val| RawNote {
|
||||||
RawNote {
|
|
||||||
cue_point_id: n as u32,
|
cue_point_id: n as u32,
|
||||||
text : convert_from_cue_string(&val)
|
text: convert_from_cue_string(&val),
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let raw_ltxt = cue.length.map(|val| {
|
let raw_ltxt = cue.length.map(|val| RawLtxt {
|
||||||
RawLtxt {
|
|
||||||
cue_point_id: n as u32,
|
cue_point_id: n as u32,
|
||||||
frame_length: val,
|
frame_length: val,
|
||||||
purpose: FourCC::make(b"rgn "),
|
purpose: FourCC::make(b"rgn "),
|
||||||
@@ -341,20 +339,21 @@ impl Cue {
|
|||||||
language: 0,
|
language: 0,
|
||||||
dialect: 0,
|
dialect: 0,
|
||||||
code_page: 0,
|
code_page: 0,
|
||||||
text : None
|
text: None,
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
(raw_cue, raw_label, raw_note, raw_ltxt)
|
(raw_cue, raw_label, raw_note, raw_ltxt)
|
||||||
})
|
})
|
||||||
.fold((Vec::<RawCue>::new(), Vec::<RawAdtlMember>::new()),
|
.fold(
|
||||||
|
(Vec::<RawCue>::new(), Vec::<RawAdtlMember>::new()),
|
||||||
|(mut cues, mut adtls), (cue, label, note, ltxt)| {
|
|(mut cues, mut adtls), (cue, label, note, ltxt)| {
|
||||||
cues.push(cue);
|
cues.push(cue);
|
||||||
label.map(|l| adtls.push(RawAdtlMember::Label(l)));
|
label.map(|l| adtls.push(RawAdtlMember::Label(l)));
|
||||||
note.map(|n| adtls.push(RawAdtlMember::Note(n)));
|
note.map(|n| adtls.push(RawAdtlMember::Note(n)));
|
||||||
ltxt.map(|m| adtls.push(RawAdtlMember::LabeledText(m)));
|
ltxt.map(|m| adtls.push(RawAdtlMember::LabeledText(m)));
|
||||||
(cues, adtls)
|
(cues, adtls)
|
||||||
})
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn collect_from(cue_chunk: &[u8], adtl_chunk: Option<&[u8]>) -> Result<Vec<Cue>, Error> {
|
pub fn collect_from(cue_chunk: &[u8], adtl_chunk: Option<&[u8]>) -> Result<Vec<Cue>, Error> {
|
||||||
@@ -367,33 +366,37 @@ impl Cue {
|
|||||||
raw_adtl = vec![];
|
raw_adtl = vec![];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(raw_cues
|
||||||
Ok(
|
.iter()
|
||||||
raw_cues.iter()
|
|
||||||
.map(|i| {
|
.map(|i| {
|
||||||
Cue {
|
Cue {
|
||||||
//ident : i.cue_point_id,
|
//ident : i.cue_point_id,
|
||||||
frame: i.frame,
|
frame: i.frame,
|
||||||
length: {
|
length: {
|
||||||
raw_adtl.ltxt_for_cue_point(i.cue_point_id).first()
|
raw_adtl
|
||||||
|
.ltxt_for_cue_point(i.cue_point_id)
|
||||||
|
.first()
|
||||||
.filter(|x| x.purpose == FourCC::make(b"rgn "))
|
.filter(|x| x.purpose == FourCC::make(b"rgn "))
|
||||||
.map(|x| x.frame_length)
|
.map(|x| x.frame_length)
|
||||||
},
|
},
|
||||||
label: {
|
label: {
|
||||||
raw_adtl.labels_for_cue_point(i.cue_point_id).iter()
|
raw_adtl
|
||||||
|
.labels_for_cue_point(i.cue_point_id)
|
||||||
|
.iter()
|
||||||
.map(|s| convert_to_cue_string(&s.text))
|
.map(|s| convert_to_cue_string(&s.text))
|
||||||
.next()
|
.next()
|
||||||
},
|
},
|
||||||
note: {
|
note: {
|
||||||
raw_adtl.notes_for_cue_point(i.cue_point_id).iter()
|
raw_adtl
|
||||||
|
.notes_for_cue_point(i.cue_point_id)
|
||||||
|
.iter()
|
||||||
//.filter_map(|x| str::from_utf8(&x.text).ok())
|
//.filter_map(|x| str::from_utf8(&x.text).ok())
|
||||||
.map(|s| convert_to_cue_string(&s.text))
|
.map(|s| convert_to_cue_string(&s.text))
|
||||||
.next()
|
.next()
|
||||||
},
|
},
|
||||||
offset: i.frame_offset
|
offset: i.frame_offset,
|
||||||
}
|
}
|
||||||
}).collect()
|
})
|
||||||
)
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
use std::{fmt::{Debug,Display}, io};
|
|
||||||
use std::error::Error as StdError;
|
|
||||||
use super::fourcc::FourCC;
|
use super::fourcc::FourCC;
|
||||||
|
use std::error::Error as StdError;
|
||||||
|
use std::{
|
||||||
|
fmt::{Debug, Display},
|
||||||
|
io,
|
||||||
|
};
|
||||||
|
|
||||||
use uuid;
|
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 {
|
||||||
|
|
||||||
/// An `io::Error` occurred
|
/// An `io::Error` occurred
|
||||||
IOError(io::Error),
|
IOError(io::Error),
|
||||||
|
|
||||||
@@ -41,7 +43,6 @@ pub enum Error {
|
|||||||
|
|
||||||
/// The file is not optimized for writing new data
|
/// The file is not optimized for writing new data
|
||||||
DataChunkNotPreparedForAppend,
|
DataChunkNotPreparedForAppend,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StdError for Error {}
|
impl StdError for Error {}
|
||||||
@@ -52,7 +53,6 @@ impl Display for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl From<io::Error> for Error {
|
impl From<io::Error> for Error {
|
||||||
fn from(error: io::Error) -> Error {
|
fn from(error: io::Error) -> Error {
|
||||||
Error::IOError(error)
|
Error::IOError(error)
|
||||||
|
|||||||
143
src/fmt.rs
143
src/fmt.rs
@@ -1,9 +1,9 @@
|
|||||||
use uuid::Uuid;
|
use super::common_format::{CommonFormat, UUID_BFORMAT_PCM, UUID_PCM};
|
||||||
use super::common_format::{CommonFormat, UUID_PCM,UUID_BFORMAT_PCM};
|
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
use byteorder::LittleEndian;
|
use byteorder::LittleEndian;
|
||||||
use byteorder::{WriteBytesExt, ReadBytesExt};
|
use byteorder::{ReadBytesExt, WriteBytesExt};
|
||||||
|
|
||||||
// Need more test cases for ADMAudioID
|
// Need more test cases for ADMAudioID
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@@ -22,7 +22,7 @@ use byteorder::{WriteBytesExt, ReadBytesExt};
|
|||||||
pub struct ADMAudioID {
|
pub struct ADMAudioID {
|
||||||
pub track_uid: [char; 12],
|
pub track_uid: [char; 12],
|
||||||
pub channel_format_ref: [char; 14],
|
pub channel_format_ref: [char; 14],
|
||||||
pub 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.
|
||||||
@@ -44,7 +44,6 @@ pub struct ChannelDescriptor {
|
|||||||
pub adm_track_audio_ids: Vec<ADMAudioID>,
|
pub adm_track_audio_ids: Vec<ADMAudioID>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// A bitmask indicating which channels are present in
|
/// A bitmask indicating which channels are present in
|
||||||
/// the file.
|
/// the file.
|
||||||
///
|
///
|
||||||
@@ -72,7 +71,6 @@ pub enum ChannelMask {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<u32> for ChannelMask {
|
impl From<u32> for ChannelMask {
|
||||||
|
|
||||||
fn from(value: u32) -> Self {
|
fn from(value: u32) -> Self {
|
||||||
match value {
|
match value {
|
||||||
0x1 => Self::FrontLeft,
|
0x1 => Self::FrontLeft,
|
||||||
@@ -93,7 +91,7 @@ impl From<u32> for ChannelMask {
|
|||||||
0x8000 => Self::TopBackLeft,
|
0x8000 => Self::TopBackLeft,
|
||||||
0x10000 => Self::TopBackCenter,
|
0x10000 => Self::TopBackCenter,
|
||||||
0x20000 => Self::TopBackRight,
|
0x20000 => Self::TopBackRight,
|
||||||
_ => Self::DirectOut
|
_ => Self::DirectOut,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -104,7 +102,8 @@ impl ChannelMask {
|
|||||||
if (input_mask & reserved_mask) > 0 {
|
if (input_mask & reserved_mask) > 0 {
|
||||||
vec![ChannelMask::DirectOut; channel_count as usize]
|
vec![ChannelMask::DirectOut; channel_count as usize]
|
||||||
} else {
|
} else {
|
||||||
(0..18).map(|i| 1 << i )
|
(0..18)
|
||||||
|
.map(|i| 1 << i)
|
||||||
.filter(|mask| mask & input_mask > 0)
|
.filter(|mask| mask & input_mask > 0)
|
||||||
.map(|mask| Into::<ChannelMask>::into(mask))
|
.map(|mask| Into::<ChannelMask>::into(mask))
|
||||||
.collect()
|
.collect()
|
||||||
@@ -119,7 +118,6 @@ impl ChannelMask {
|
|||||||
*/
|
*/
|
||||||
#[derive(Debug, Copy, Clone)]
|
#[derive(Debug, Copy, Clone)]
|
||||||
pub struct WaveFmtExtended {
|
pub struct WaveFmtExtended {
|
||||||
|
|
||||||
/// Valid bits per sample
|
/// Valid bits per sample
|
||||||
pub valid_bits_per_sample: u16,
|
pub valid_bits_per_sample: u16,
|
||||||
|
|
||||||
@@ -157,10 +155,8 @@ pub struct WaveFmtExtended {
|
|||||||
///
|
///
|
||||||
/// [rfc3261]: https://tools.ietf.org/html/rfc2361
|
/// [rfc3261]: https://tools.ietf.org/html/rfc2361
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug, Copy, Clone)]
|
#[derive(Debug, Copy, Clone)]
|
||||||
pub struct WaveFmt {
|
pub struct WaveFmt {
|
||||||
|
|
||||||
/// A tag identifying the codec in use.
|
/// A tag identifying the codec in use.
|
||||||
///
|
///
|
||||||
/// If this is 0xFFFE, the codec will be identified by a GUID
|
/// If this is 0xFFFE, the codec will be identified by a GUID
|
||||||
@@ -202,12 +198,10 @@ pub struct WaveFmt {
|
|||||||
///
|
///
|
||||||
/// Additional format metadata if `channel_count` is greater than 2,
|
/// Additional format metadata if `channel_count` is greater than 2,
|
||||||
/// or if certain codecs are used.
|
/// or if certain codecs are used.
|
||||||
pub extended_format: Option<WaveFmtExtended>
|
pub extended_format: Option<WaveFmtExtended>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl WaveFmt {
|
impl WaveFmt {
|
||||||
|
|
||||||
pub fn valid_bits_per_sample(&self) -> u16 {
|
pub fn valid_bits_per_sample(&self) -> u16 {
|
||||||
if let Some(ext) = self.extended_format {
|
if let Some(ext) = self.extended_format {
|
||||||
ext.valid_bits_per_sample
|
ext.valid_bits_per_sample
|
||||||
@@ -236,14 +230,16 @@ impl WaveFmt {
|
|||||||
tag: 0xFFFE,
|
tag: 0xFFFE,
|
||||||
channel_count,
|
channel_count,
|
||||||
sample_rate,
|
sample_rate,
|
||||||
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: Some(WaveFmtExtended {
|
extended_format: Some(WaveFmtExtended {
|
||||||
valid_bits_per_sample: bits_per_sample,
|
valid_bits_per_sample: bits_per_sample,
|
||||||
channel_mask: ChannelMask::DirectOut as u32,
|
channel_mask: ChannelMask::DirectOut as u32,
|
||||||
type_guid: UUID_BFORMAT_PCM
|
type_guid: UUID_BFORMAT_PCM,
|
||||||
})
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,23 +248,41 @@ impl WaveFmt {
|
|||||||
/// The order of `channels` is not important. When reading or writing
|
/// The order of `channels` is not important. When reading or writing
|
||||||
/// audio frames you must use the standard multichannel order for Wave
|
/// audio frames you must use the standard multichannel order for Wave
|
||||||
/// files, the numerical order of the cases of `ChannelMask`.
|
/// 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 {
|
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_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 channel_count: u16 = (0..=31).fold(0u16, |accum, n| accum + (0x1 & (channel_bitmap >> n) as u16) );
|
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 {
|
let result: (u16, Option<WaveFmtExtended>) = match channel_bitmap {
|
||||||
ch if bits_per_sample != container_bits_per_sample => (
|
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 }) )
|
0xFFFE,
|
||||||
),
|
Some(WaveFmtExtended {
|
||||||
|
valid_bits_per_sample: bits_per_sample,
|
||||||
|
channel_mask: ch,
|
||||||
|
type_guid: UUID_PCM,
|
||||||
|
}),
|
||||||
|
))
|
||||||
|
}
|
||||||
0b0100 => (0x0001, None),
|
0b0100 => (0x0001, None),
|
||||||
0b0011 => (0x0001, None),
|
0b0011 => (0x0001, None),
|
||||||
ch => (
|
ch => {
|
||||||
(0xFFFE, Some( WaveFmtExtended { valid_bits_per_sample: bits_per_sample, channel_mask: ch,
|
((
|
||||||
type_guid: UUID_PCM}))
|
0xFFFE,
|
||||||
)
|
Some(WaveFmtExtended {
|
||||||
|
valid_bits_per_sample: bits_per_sample,
|
||||||
|
channel_mask: ch,
|
||||||
|
type_guid: UUID_PCM,
|
||||||
|
}),
|
||||||
|
))
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let (tag, extformat) = result;
|
let (tag, extformat) = result;
|
||||||
@@ -277,10 +291,12 @@ impl WaveFmt {
|
|||||||
tag,
|
tag,
|
||||||
channel_count,
|
channel_count,
|
||||||
sample_rate,
|
sample_rate,
|
||||||
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: extformat
|
extended_format: extformat,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -311,8 +327,10 @@ impl WaveFmt {
|
|||||||
pub fn pack_frames(&self, from_frames: &[i32], into_bytes: &mut [u8]) -> () {
|
pub fn pack_frames(&self, from_frames: &[i32], into_bytes: &mut [u8]) -> () {
|
||||||
let mut write_cursor = Cursor::new(into_bytes);
|
let mut write_cursor = Cursor::new(into_bytes);
|
||||||
|
|
||||||
assert!(from_frames.len() % self.channel_count as usize == 0,
|
assert!(
|
||||||
"frames buffer does not contain a number of samples % channel_count == 0");
|
from_frames.len() % self.channel_count as usize == 0,
|
||||||
|
"frames buffer does not contain a number of samples % channel_count == 0"
|
||||||
|
);
|
||||||
|
|
||||||
for n in 0..from_frames.len() {
|
for n in 0..from_frames.len() {
|
||||||
match (self.valid_bits_per_sample(), self.bits_per_sample) {
|
match (self.valid_bits_per_sample(), self.bits_per_sample) {
|
||||||
@@ -342,55 +360,69 @@ impl WaveFmt {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// 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 {
|
||||||
1 => vec![
|
1 => vec![ChannelDescriptor {
|
||||||
ChannelDescriptor {
|
|
||||||
index: 0,
|
index: 0,
|
||||||
speaker: ChannelMask::FrontCenter,
|
speaker: ChannelMask::FrontCenter,
|
||||||
adm_track_audio_ids: vec![]
|
adm_track_audio_ids: vec![],
|
||||||
}
|
}],
|
||||||
],
|
|
||||||
2 => vec![
|
2 => vec![
|
||||||
ChannelDescriptor {
|
ChannelDescriptor {
|
||||||
index: 0,
|
index: 0,
|
||||||
speaker: ChannelMask::FrontLeft,
|
speaker: ChannelMask::FrontLeft,
|
||||||
adm_track_audio_ids: vec![]
|
adm_track_audio_ids: vec![],
|
||||||
},
|
},
|
||||||
ChannelDescriptor {
|
ChannelDescriptor {
|
||||||
index: 1,
|
index: 1,
|
||||||
speaker: ChannelMask::FrontRight,
|
speaker: ChannelMask::FrontRight,
|
||||||
adm_track_audio_ids: vec![]
|
adm_track_audio_ids: vec![],
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
x if x > 2 => {
|
x if x > 2 => {
|
||||||
let channel_mask = self.extended_format.map(|x| x.channel_mask).unwrap_or(0);
|
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 = ChannelMask::channels(channel_mask, self.channel_count);
|
||||||
let channels_expanded = channels.iter().chain(std::iter::repeat(&ChannelMask::DirectOut));
|
let channels_expanded = channels
|
||||||
|
.iter()
|
||||||
|
.chain(std::iter::repeat(&ChannelMask::DirectOut));
|
||||||
|
|
||||||
(0..self.channel_count)
|
(0..self.channel_count)
|
||||||
.zip(channels_expanded)
|
.zip(channels_expanded)
|
||||||
.map(|(n, chan)| ChannelDescriptor {
|
.map(|(n, chan)| ChannelDescriptor {
|
||||||
index: n,
|
index: n,
|
||||||
speaker: *chan,
|
speaker: *chan,
|
||||||
adm_track_audio_ids: vec![]
|
adm_track_audio_ids: vec![],
|
||||||
}).collect()
|
})
|
||||||
},
|
.collect()
|
||||||
|
}
|
||||||
x => panic!("Channel count ({}) was illegal!", x),
|
x => panic!("Channel count ({}) was illegal!", x),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ReadWavAudioData {
|
trait ReadWavAudioData {
|
||||||
fn read_i32_frames(&mut self, format: WaveFmt, into: &mut [i32]) -> Result<usize,std::io::Error>;
|
fn read_i32_frames(
|
||||||
fn read_f32_frames(&mut self, format: WaveFmt, into: &mut [f32]) -> Result<usize,std::io::Error>;
|
&mut self,
|
||||||
|
format: WaveFmt,
|
||||||
|
into: &mut [i32],
|
||||||
|
) -> Result<usize, std::io::Error>;
|
||||||
|
fn read_f32_frames(
|
||||||
|
&mut self,
|
||||||
|
format: WaveFmt,
|
||||||
|
into: &mut [f32],
|
||||||
|
) -> Result<usize, std::io::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> ReadWavAudioData for T where T: std::io::Read {
|
impl<T> ReadWavAudioData for T
|
||||||
|
where
|
||||||
fn read_i32_frames(&mut self, format: WaveFmt, into: &mut [i32]) -> Result<usize, std::io::Error> {
|
T: std::io::Read,
|
||||||
|
{
|
||||||
|
fn read_i32_frames(
|
||||||
|
&mut self,
|
||||||
|
format: WaveFmt,
|
||||||
|
into: &mut [i32],
|
||||||
|
) -> Result<usize, std::io::Error> {
|
||||||
assert!(into.len() % format.channel_count as usize == 0);
|
assert!(into.len() % format.channel_count as usize == 0);
|
||||||
|
|
||||||
for n in 0..(into.len()) {
|
for n in 0..(into.len()) {
|
||||||
@@ -406,11 +438,14 @@ impl<T> ReadWavAudioData for T where T: std::io::Read {
|
|||||||
|
|
||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
fn read_f32_frames(&mut self, format: WaveFmt, into: &mut [f32]) -> Result<usize, std::io::Error> {
|
fn read_f32_frames(
|
||||||
|
&mut self,
|
||||||
|
format: WaveFmt,
|
||||||
|
into: &mut [f32],
|
||||||
|
) -> Result<usize, std::io::Error> {
|
||||||
assert!(into.len() % format.channel_count as usize == 0);
|
assert!(into.len() % format.channel_count as usize == 0);
|
||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
trait WriteWavAudioData {
|
trait WriteWavAudioData {
|
||||||
@@ -418,8 +453,10 @@ trait WriteWavAudioData {
|
|||||||
fn write_f32_frames(&mut self, format: WaveFmt, from: &[f32]) -> Result<usize, std::io::Error>;
|
fn write_f32_frames(&mut self, format: WaveFmt, from: &[f32]) -> Result<usize, std::io::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> WriteWavAudioData for T where T: std::io::Write {
|
impl<T> WriteWavAudioData for T
|
||||||
|
where
|
||||||
|
T: std::io::Write,
|
||||||
|
{
|
||||||
fn write_i32_frames(&mut self, format: WaveFmt, _: &[i32]) -> Result<usize, std::io::Error> {
|
fn write_i32_frames(&mut self, format: WaveFmt, _: &[i32]) -> Result<usize, std::io::Error> {
|
||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,12 @@ impl FourCC {
|
|||||||
|
|
||||||
impl From<[char; 4]> for FourCC {
|
impl From<[char; 4]> for FourCC {
|
||||||
fn from(chars: [char; 4]) -> Self {
|
fn from(chars: [char; 4]) -> Self {
|
||||||
Self([chars[0] as u8 , chars[1] as u8, chars[2] as u8, chars[3] as u8])
|
Self([
|
||||||
|
chars[0] as u8,
|
||||||
|
chars[1] as u8,
|
||||||
|
chars[2] as u8,
|
||||||
|
chars[3] as u8,
|
||||||
|
])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,20 +37,28 @@ impl From<FourCC> for [u8; 4] {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl From<&FourCC> for [char; 4] {
|
impl From<&FourCC> for [char; 4] {
|
||||||
fn from(f: &FourCC) -> Self {
|
fn from(f: &FourCC) -> Self {
|
||||||
[f.0[0] as char, f.0[1] as char, f.0[2] as char, f.0[3] as char,]
|
[
|
||||||
|
f.0[0] as char,
|
||||||
|
f.0[1] as char,
|
||||||
|
f.0[2] as char,
|
||||||
|
f.0[3] as char,
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<FourCC> for [char; 4] {
|
impl From<FourCC> for [char; 4] {
|
||||||
fn from(f: FourCC) -> Self {
|
fn from(f: FourCC) -> Self {
|
||||||
[f.0[0] as char, f.0[1] as char, f.0[2] as char, f.0[3] as char,]
|
[
|
||||||
|
f.0[0] as char,
|
||||||
|
f.0[1] as char,
|
||||||
|
f.0[2] as char,
|
||||||
|
f.0[3] as char,
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl From<&FourCC> for String {
|
impl From<&FourCC> for String {
|
||||||
fn from(f: &FourCC) -> Self {
|
fn from(f: &FourCC) -> Self {
|
||||||
let chars: [char; 4] = f.into();
|
let chars: [char; 4] = f.into();
|
||||||
@@ -75,7 +88,10 @@ pub trait WriteFourCC: io::Write {
|
|||||||
fn write_fourcc(&mut self, fourcc: FourCC) -> Result<(), io::Error>;
|
fn write_fourcc(&mut self, fourcc: FourCC) -> Result<(), io::Error>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> ReadFourCC for T where T: io::Read {
|
impl<T> ReadFourCC for T
|
||||||
|
where
|
||||||
|
T: io::Read,
|
||||||
|
{
|
||||||
fn read_fourcc(&mut self) -> Result<FourCC, io::Error> {
|
fn read_fourcc(&mut self) -> Result<FourCC, io::Error> {
|
||||||
let mut buf: [u8; 4] = [0; 4];
|
let mut buf: [u8; 4] = [0; 4];
|
||||||
self.read_exact(&mut buf)?;
|
self.read_exact(&mut buf)?;
|
||||||
@@ -83,7 +99,10 @@ impl<T> ReadFourCC for T where T: io::Read {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> WriteFourCC for T where T: io::Write {
|
impl<T> WriteFourCC for T
|
||||||
|
where
|
||||||
|
T: io::Write,
|
||||||
|
{
|
||||||
fn write_fourcc(&mut self, fourcc: FourCC) -> Result<(), io::Error> {
|
fn write_fourcc(&mut self, fourcc: FourCC) -> Result<(), io::Error> {
|
||||||
let buf: [u8; 4] = fourcc.into();
|
let buf: [u8; 4] = fourcc.into();
|
||||||
self.write_all(&buf)?;
|
self.write_all(&buf)?;
|
||||||
@@ -91,7 +110,6 @@ impl<T> WriteFourCC for T where T: io::Write {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub const RIFF_SIG: FourCC = FourCC::make(b"RIFF");
|
pub const RIFF_SIG: FourCC = FourCC::make(b"RIFF");
|
||||||
pub const WAVE_SIG: FourCC = FourCC::make(b"WAVE");
|
pub const WAVE_SIG: FourCC = FourCC::make(b"WAVE");
|
||||||
pub const RF64_SIG: FourCC = FourCC::make(b"RF64");
|
pub const RF64_SIG: FourCC = FourCC::make(b"RF64");
|
||||||
@@ -117,7 +135,6 @@ pub const LABL_SIG: FourCC = FourCC::make(b"labl");
|
|||||||
pub const NOTE_SIG: FourCC = FourCC::make(b"note");
|
pub const NOTE_SIG: FourCC = FourCC::make(b"note");
|
||||||
pub const LTXT_SIG: FourCC = FourCC::make(b"ltxt");
|
pub const LTXT_SIG: FourCC = FourCC::make(b"ltxt");
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
18
src/lib.rs
18
src/lib.rs
@@ -36,29 +36,29 @@ Apps we test against:
|
|||||||
[github]: https://github.com/iluvcapra/bwavfile
|
[github]: https://github.com/iluvcapra/bwavfile
|
||||||
*/
|
*/
|
||||||
|
|
||||||
extern crate encoding;
|
|
||||||
extern crate byteorder;
|
extern crate byteorder;
|
||||||
|
extern crate encoding;
|
||||||
extern crate uuid;
|
extern crate uuid;
|
||||||
|
|
||||||
mod fourcc;
|
|
||||||
mod errors;
|
|
||||||
mod common_format;
|
mod common_format;
|
||||||
|
mod errors;
|
||||||
|
mod fourcc;
|
||||||
|
|
||||||
mod parser;
|
|
||||||
mod list_form;
|
mod list_form;
|
||||||
|
mod parser;
|
||||||
|
|
||||||
|
mod bext;
|
||||||
mod chunks;
|
mod chunks;
|
||||||
mod cue;
|
mod cue;
|
||||||
mod bext;
|
|
||||||
mod fmt;
|
mod fmt;
|
||||||
|
|
||||||
mod wavereader;
|
mod wavereader;
|
||||||
mod wavewriter;
|
mod wavewriter;
|
||||||
|
|
||||||
pub use errors::Error;
|
|
||||||
pub use wavereader::{WaveReader, AudioFrameReader};
|
|
||||||
pub use wavewriter::{WaveWriter, AudioFrameWriter};
|
|
||||||
pub use bext::Bext;
|
pub use bext::Bext;
|
||||||
pub use fmt::{WaveFmt, WaveFmtExtended, ChannelDescriptor, ChannelMask, ADMAudioID};
|
|
||||||
pub use common_format::CommonFormat;
|
pub use common_format::CommonFormat;
|
||||||
pub use cue::Cue;
|
pub use cue::Cue;
|
||||||
|
pub use errors::Error;
|
||||||
|
pub use fmt::{ADMAudioID, ChannelDescriptor, ChannelMask, WaveFmt, WaveFmtExtended};
|
||||||
|
pub use wavereader::{AudioFrameReader, WaveReader};
|
||||||
|
pub use wavewriter::{AudioFrameWriter, WaveWriter};
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use super::fourcc::{FourCC, ReadFourCC};
|
use super::fourcc::{FourCC, ReadFourCC};
|
||||||
use byteorder::{ReadBytesExt, LittleEndian};
|
use byteorder::{LittleEndian, ReadBytesExt};
|
||||||
use std::io::{Cursor, Error, Read};
|
use std::io::{Cursor, Error, Read};
|
||||||
|
|
||||||
pub struct ListFormItem {
|
pub struct ListFormItem {
|
||||||
pub signature: FourCC,
|
pub signature: FourCC,
|
||||||
pub contents : Vec<u8>
|
pub contents: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A helper that will accept a LIST chunk as a [u8]
|
/// A helper that will accept a LIST chunk as a [u8]
|
||||||
@@ -26,7 +26,10 @@ pub fn collect_list_form(list_contents :& [u8]) -> Result<Vec<ListFormItem>, Err
|
|||||||
cursor.read_exact(&mut content_buf)?;
|
cursor.read_exact(&mut content_buf)?;
|
||||||
remain -= this_size;
|
remain -= this_size;
|
||||||
|
|
||||||
retval.push( ListFormItem { signature : this_sig, contents : content_buf } );
|
retval.push(ListFormItem {
|
||||||
|
signature: this_sig,
|
||||||
|
contents: content_buf,
|
||||||
|
});
|
||||||
|
|
||||||
if this_size % 2 == 1 {
|
if this_size % 2 == 1 {
|
||||||
cursor.read_u8()?;
|
cursor.read_u8()?;
|
||||||
@@ -35,6 +38,5 @@ pub fn collect_list_form(list_contents :& [u8]) -> Result<Vec<ListFormItem>, Err
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Ok(retval)
|
Ok(retval)
|
||||||
}
|
}
|
||||||
112
src/parser.rs
112
src/parser.rs
@@ -1,15 +1,14 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::io::SeekFrom::{Current, Start};
|
use std::io::SeekFrom::{Current, Start};
|
||||||
use std::io::{Seek, Read};
|
use std::io::{Read, Seek};
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use byteorder::LittleEndian;
|
use byteorder::LittleEndian;
|
||||||
use byteorder::ReadBytesExt;
|
use byteorder::ReadBytesExt;
|
||||||
|
|
||||||
use super::errors::Error;
|
use super::errors::Error;
|
||||||
use super::fourcc::{FourCC, ReadFourCC};
|
use super::fourcc::{FourCC, ReadFourCC};
|
||||||
use super::fourcc::{RIFF_SIG, RF64_SIG, BW64_SIG, WAVE_SIG, DS64_SIG, DATA_SIG};
|
use super::fourcc::{BW64_SIG, DATA_SIG, DS64_SIG, RF64_SIG, RIFF_SIG, WAVE_SIG};
|
||||||
|
|
||||||
// just for your reference...
|
// just for your reference...
|
||||||
// RF64 documentation https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.2088-1-201910-I!!PDF-E.pdf
|
// RF64 documentation https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.2088-1-201910-I!!PDF-E.pdf
|
||||||
@@ -21,12 +20,26 @@ const RF64_SIZE_MARKER: u32 = 0xFF_FF_FF_FF;
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Event {
|
pub enum Event {
|
||||||
StartParse,
|
StartParse,
|
||||||
ReadHeader { signature: FourCC, length_field: u32 },
|
ReadHeader {
|
||||||
ReadRF64Header { signature: FourCC },
|
signature: FourCC,
|
||||||
ReadDS64 {file_size: u64, long_sizes: HashMap<FourCC,u64> },
|
length_field: u32,
|
||||||
BeginChunk { signature: FourCC, content_start: u64, content_length: u64 },
|
},
|
||||||
Failed { error: Error },
|
ReadRF64Header {
|
||||||
FinishParse
|
signature: FourCC,
|
||||||
|
},
|
||||||
|
ReadDS64 {
|
||||||
|
file_size: u64,
|
||||||
|
long_sizes: HashMap<FourCC, u64>,
|
||||||
|
},
|
||||||
|
BeginChunk {
|
||||||
|
signature: FourCC,
|
||||||
|
content_start: u64,
|
||||||
|
content_length: u64,
|
||||||
|
},
|
||||||
|
Failed {
|
||||||
|
error: Error,
|
||||||
|
},
|
||||||
|
FinishParse,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -36,24 +49,23 @@ enum State {
|
|||||||
ReadyForDS64,
|
ReadyForDS64,
|
||||||
ReadyForChunk { at: u64, remaining: u64 },
|
ReadyForChunk { at: u64, remaining: u64 },
|
||||||
Error,
|
Error,
|
||||||
Complete
|
Complete,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Parser<R: Read + Seek> {
|
pub struct Parser<R: Read + Seek> {
|
||||||
stream: R,
|
stream: R,
|
||||||
state: State,
|
state: State,
|
||||||
ds64state: HashMap<FourCC,u64>
|
ds64state: HashMap<FourCC, u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub struct ChunkIteratorItem {
|
pub struct ChunkIteratorItem {
|
||||||
pub signature: FourCC,
|
pub signature: FourCC,
|
||||||
pub start: u64,
|
pub start: u64,
|
||||||
pub length: u64
|
pub length: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read + Seek> Parser<R> {
|
impl<R: Read + Seek> Parser<R> {
|
||||||
|
|
||||||
// wraps a stream
|
// wraps a stream
|
||||||
pub fn make(stream: R) -> Result<Self, Error> {
|
pub fn make(stream: R) -> Result<Self, Error> {
|
||||||
let newmap: HashMap<FourCC, u64> = HashMap::new();
|
let newmap: HashMap<FourCC, u64> = HashMap::new();
|
||||||
@@ -63,7 +75,7 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
stream: the_stream,
|
stream: the_stream,
|
||||||
state: State::New,
|
state: State::New,
|
||||||
ds64state: newmap,
|
ds64state: newmap,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub fn into_inner(self) -> R {
|
// pub fn into_inner(self) -> R {
|
||||||
@@ -71,24 +83,39 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
pub fn into_chunk_iterator(self) -> impl Iterator<Item = Result<ChunkIteratorItem, Error>> {
|
pub fn into_chunk_iterator(self) -> impl Iterator<Item = Result<ChunkIteratorItem, Error>> {
|
||||||
self.filter_map({|event|
|
self.filter_map({
|
||||||
if let Event::BeginChunk {signature , content_start, content_length } = event {
|
|event| {
|
||||||
Some(Ok(ChunkIteratorItem {signature, start: content_start, length: content_length }))
|
if let Event::BeginChunk {
|
||||||
|
signature,
|
||||||
|
content_start,
|
||||||
|
content_length,
|
||||||
|
} = event
|
||||||
|
{
|
||||||
|
Some(Ok(ChunkIteratorItem {
|
||||||
|
signature,
|
||||||
|
start: content_start,
|
||||||
|
length: content_length,
|
||||||
|
}))
|
||||||
} else if let Event::Failed { error } = event {
|
} else if let Event::Failed { error } = event {
|
||||||
Some(Err(error))
|
Some(Err(error))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn into_chunk_list(self) -> Result<Vec<ChunkIteratorItem>, Error> {
|
pub fn into_chunk_list(self) -> Result<Vec<ChunkIteratorItem>, Error> {
|
||||||
let mut error = Ok(());
|
let mut error = Ok(());
|
||||||
|
|
||||||
let chunks = self.into_chunk_iterator()
|
let chunks = self
|
||||||
|
.into_chunk_iterator()
|
||||||
.scan(&mut error, |err, res| match res {
|
.scan(&mut error, |err, res| match res {
|
||||||
Ok(ok) => Some(ok),
|
Ok(ok) => Some(ok),
|
||||||
Err(e) => { **err = Err(e); None }
|
Err(e) => {
|
||||||
|
**err = Err(e);
|
||||||
|
None
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@@ -96,7 +123,6 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
|
|
||||||
Ok(chunks)
|
Ok(chunks)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read + Seek> Iterator for Parser<R> {
|
impl<R: Read + Seek> Iterator for Parser<R> {
|
||||||
@@ -110,7 +136,6 @@ impl<R: Read + Seek> Iterator for Parser<R> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read + Seek> Parser<R> {
|
impl<R: Read + Seek> Parser<R> {
|
||||||
|
|
||||||
fn parse_header(&mut self) -> Result<(Event, State), io::Error> {
|
fn parse_header(&mut self) -> Result<(Event, State), io::Error> {
|
||||||
let file_sig = self.stream.read_fourcc()?;
|
let file_sig = self.stream.read_fourcc()?;
|
||||||
let length = self.stream.read_u32::<LittleEndian>()?;
|
let length = self.stream.read_u32::<LittleEndian>()?;
|
||||||
@@ -123,24 +148,24 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
(RIFF_SIG, size, WAVE_SIG) => {
|
(RIFF_SIG, size, WAVE_SIG) => {
|
||||||
event = Event::ReadHeader {
|
event = Event::ReadHeader {
|
||||||
signature: file_sig,
|
signature: file_sig,
|
||||||
length_field: size
|
length_field: size,
|
||||||
};
|
};
|
||||||
|
|
||||||
next_state = State::ReadyForChunk {
|
next_state = State::ReadyForChunk {
|
||||||
at: 12,
|
at: 12,
|
||||||
remaining: (length - 4) as u64,
|
remaining: (length - 4) as u64,
|
||||||
};
|
};
|
||||||
},
|
}
|
||||||
(RF64_SIG, RF64_SIZE_MARKER, WAVE_SIG) | (BW64_SIG, RF64_SIZE_MARKER, WAVE_SIG) => {
|
(RF64_SIG, RF64_SIZE_MARKER, WAVE_SIG) | (BW64_SIG, RF64_SIZE_MARKER, WAVE_SIG) => {
|
||||||
event = Event::ReadRF64Header {
|
event = Event::ReadRF64Header {
|
||||||
signature: file_sig
|
signature: file_sig,
|
||||||
};
|
};
|
||||||
|
|
||||||
next_state = State::ReadyForDS64;
|
next_state = State::ReadyForDS64;
|
||||||
},
|
}
|
||||||
_ => {
|
_ => {
|
||||||
event = Event::Failed {
|
event = Event::Failed {
|
||||||
error: Error::HeaderNotRecognized
|
error: Error::HeaderNotRecognized,
|
||||||
};
|
};
|
||||||
next_state = State::Error;
|
next_state = State::Error;
|
||||||
}
|
}
|
||||||
@@ -158,7 +183,6 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
|
|
||||||
if ds64_sig != DS64_SIG {
|
if ds64_sig != DS64_SIG {
|
||||||
return Err(Error::MissingRequiredDS64);
|
return Err(Error::MissingRequiredDS64);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
let long_file_size = self.stream.read_u64::<LittleEndian>()?;
|
let long_file_size = self.stream.read_u64::<LittleEndian>()?;
|
||||||
let long_data_size = self.stream.read_u64::<LittleEndian>()?;
|
let long_data_size = self.stream.read_u64::<LittleEndian>()?;
|
||||||
@@ -202,14 +226,12 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn enter_chunk(&mut self, at: u64, remaining: u64) -> Result<(Event, State), io::Error> {
|
fn enter_chunk(&mut self, at: u64, remaining: u64) -> Result<(Event, State), io::Error> {
|
||||||
|
|
||||||
let event;
|
let event;
|
||||||
let state;
|
let state;
|
||||||
|
|
||||||
if remaining == 0 {
|
if remaining == 0 {
|
||||||
event = Event::FinishParse;
|
event = Event::FinishParse;
|
||||||
state = State::Complete;
|
state = State::Complete;
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
let this_fourcc = self.stream.read_fourcc()?;
|
let this_fourcc = self.stream.read_fourcc()?;
|
||||||
let this_size: u64;
|
let this_size: u64;
|
||||||
@@ -221,18 +243,22 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
this_size = self.stream.read_u32::<LittleEndian>()? as u64;
|
this_size = self.stream.read_u32::<LittleEndian>()? as u64;
|
||||||
}
|
}
|
||||||
|
|
||||||
let this_displacement :u64 = if this_size % 2 == 1 { this_size + 1 } else { this_size };
|
let this_displacement: u64 = if this_size % 2 == 1 {
|
||||||
|
this_size + 1
|
||||||
|
} else {
|
||||||
|
this_size
|
||||||
|
};
|
||||||
self.stream.seek(Current(this_displacement as i64))?;
|
self.stream.seek(Current(this_displacement as i64))?;
|
||||||
|
|
||||||
event = Event::BeginChunk {
|
event = Event::BeginChunk {
|
||||||
signature: this_fourcc,
|
signature: this_fourcc,
|
||||||
content_start: at + 8,
|
content_start: at + 8,
|
||||||
content_length: this_size
|
content_length: this_size,
|
||||||
};
|
};
|
||||||
|
|
||||||
state = State::ReadyForChunk {
|
state = State::ReadyForChunk {
|
||||||
at: at + 8 + this_displacement,
|
at: at + 8 + this_displacement,
|
||||||
remaining: remaining - 8 - this_displacement
|
remaining: remaining - 8 - this_displacement,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,22 +269,22 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
match self.state {
|
match self.state {
|
||||||
State::New => {
|
State::New => {
|
||||||
return Ok((Some(Event::StartParse), State::ReadyForHeader));
|
return Ok((Some(Event::StartParse), State::ReadyForHeader));
|
||||||
},
|
}
|
||||||
State::ReadyForHeader => {
|
State::ReadyForHeader => {
|
||||||
let (event, state) = self.parse_header()?;
|
let (event, state) = self.parse_header()?;
|
||||||
return Ok((Some(event), state));
|
return Ok((Some(event), state));
|
||||||
},
|
}
|
||||||
State::ReadyForDS64 => {
|
State::ReadyForDS64 => {
|
||||||
let (event, state) = self.parse_ds64()?;
|
let (event, state) = self.parse_ds64()?;
|
||||||
return Ok((Some(event), state));
|
return Ok((Some(event), state));
|
||||||
},
|
}
|
||||||
State::ReadyForChunk { at, remaining } => {
|
State::ReadyForChunk { at, remaining } => {
|
||||||
let (event, state) = self.enter_chunk(at, remaining)?;
|
let (event, state) = self.enter_chunk(at, remaining)?;
|
||||||
return Ok((Some(event), state));
|
return Ok((Some(event), state));
|
||||||
},
|
}
|
||||||
State::Error => {
|
State::Error => {
|
||||||
return Ok((Some(Event::FinishParse), State::Complete));
|
return Ok((Some(Event::FinishParse), State::Complete));
|
||||||
},
|
}
|
||||||
State::Complete => {
|
State::Complete => {
|
||||||
return Ok((None, State::Complete));
|
return Ok((None, State::Complete));
|
||||||
}
|
}
|
||||||
@@ -269,11 +295,15 @@ impl<R: Read + Seek> Parser<R> {
|
|||||||
match self.handle_state() {
|
match self.handle_state() {
|
||||||
Ok((event, state)) => {
|
Ok((event, state)) => {
|
||||||
return (event, state);
|
return (event, state);
|
||||||
},
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
return (Some(Event::Failed { error: error.into() } ), State::Error );
|
return (
|
||||||
|
Some(Event::Failed {
|
||||||
|
error: error.into(),
|
||||||
|
}),
|
||||||
|
State::Error,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,29 +1,28 @@
|
|||||||
|
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use std::io::SeekFrom;
|
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
use std::io::{Read, Seek, BufReader};
|
use std::io::SeekFrom;
|
||||||
use std::io::SeekFrom::{Start,Current,};
|
use std::io::SeekFrom::{Current, Start};
|
||||||
|
use std::io::{BufReader, Read, Seek};
|
||||||
|
|
||||||
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, AXML_SIG, IXML_SIG};
|
|
||||||
use super::errors::Error as ParserError;
|
|
||||||
use super::fmt::{WaveFmt, ChannelDescriptor, ChannelMask};
|
|
||||||
use super::bext::Bext;
|
use super::bext::Bext;
|
||||||
use super::chunks::ReadBWaveChunks;
|
use super::chunks::ReadBWaveChunks;
|
||||||
use super::cue::Cue;
|
use super::cue::Cue;
|
||||||
|
use super::errors::Error as ParserError;
|
||||||
use super::errors::Error;
|
use super::errors::Error;
|
||||||
|
use super::fmt::{ChannelDescriptor, ChannelMask, WaveFmt};
|
||||||
|
use super::fourcc::{
|
||||||
|
FourCC, ReadFourCC, ADTL_SIG, AXML_SIG, BEXT_SIG, CUE__SIG, DATA_SIG, FLLR_SIG, FMT__SIG,
|
||||||
|
IXML_SIG, JUNK_SIG, LIST_SIG,
|
||||||
|
};
|
||||||
|
use super::parser::Parser;
|
||||||
use super::CommonFormat;
|
use super::CommonFormat;
|
||||||
|
|
||||||
use byteorder::LittleEndian;
|
use byteorder::LittleEndian;
|
||||||
use byteorder::ReadBytesExt;
|
use byteorder::ReadBytesExt;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// Read audio frames
|
/// Read audio frames
|
||||||
///
|
///
|
||||||
/// The inner reader is interpreted as a raw audio data
|
/// The inner reader is interpreted as a raw audio data
|
||||||
@@ -34,11 +33,10 @@ pub struct AudioFrameReader<R: Read + Seek> {
|
|||||||
inner: R,
|
inner: R,
|
||||||
format: WaveFmt,
|
format: WaveFmt,
|
||||||
start: u64,
|
start: u64,
|
||||||
length: u64
|
length: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read + Seek> AudioFrameReader<R> {
|
impl<R: Read + Seek> AudioFrameReader<R> {
|
||||||
|
|
||||||
/// Create a new `AudioFrameReader`
|
/// Create a new `AudioFrameReader`
|
||||||
///
|
///
|
||||||
/// ### Panics
|
/// ### Panics
|
||||||
@@ -48,15 +46,27 @@ impl<R: Read + Seek> AudioFrameReader<R> {
|
|||||||
/// and the format tag is readable by this implementation (only
|
/// and the format tag is readable by this implementation (only
|
||||||
/// format 0x01 is supported at this time.)
|
/// format 0x01 is supported at this time.)
|
||||||
pub fn new(mut inner: R, format: WaveFmt, start: u64, length: u64) -> Result<Self, Error> {
|
pub fn new(mut inner: R, format: WaveFmt, start: u64, length: u64) -> Result<Self, Error> {
|
||||||
assert!(format.block_alignment * 8 == format.bits_per_sample * format.channel_count,
|
assert!(
|
||||||
|
format.block_alignment * 8 == format.bits_per_sample * format.channel_count,
|
||||||
"Unable to read audio frames from packed formats: block alignment is {}, should be {}",
|
"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.common_format() == CommonFormat::IntegerPCM || format.common_format() == CommonFormat::IeeeFloatPCM,
|
assert!(
|
||||||
"Unsupported format tag {:?}", format.tag);
|
format.common_format() == CommonFormat::IntegerPCM
|
||||||
|
|| format.common_format() == CommonFormat::IeeeFloatPCM,
|
||||||
|
"Unsupported format tag {:?}",
|
||||||
|
format.tag
|
||||||
|
);
|
||||||
|
|
||||||
inner.seek(Start(start))?;
|
inner.seek(Start(start))?;
|
||||||
Ok( AudioFrameReader { inner , format , start, length} )
|
Ok(AudioFrameReader {
|
||||||
|
inner,
|
||||||
|
format,
|
||||||
|
start,
|
||||||
|
length,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unwrap the inner reader.
|
/// Unwrap the inner reader.
|
||||||
@@ -78,7 +88,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Read a frame
|
/// Read a frame
|
||||||
///
|
///
|
||||||
/// 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
|
||||||
@@ -98,9 +107,12 @@ impl<R: Read + Seek> AudioFrameReader<R> {
|
|||||||
/// 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
|
||||||
/// channels and this method will panic if this is not the case.
|
/// channels and this method will panic if this is not the case.
|
||||||
pub fn read_integer_frame(&mut self, buffer: &mut [i32]) -> Result<u64, Error> {
|
pub fn read_integer_frame(&mut self, buffer: &mut [i32]) -> Result<u64, Error> {
|
||||||
assert!(buffer.len() as u16 == self.format.channel_count,
|
assert!(
|
||||||
|
buffer.len() as u16 == self.format.channel_count,
|
||||||
"read_integer_frame was called with a mis-sized buffer, expected {}, was {}",
|
"read_integer_frame was called with a mis-sized buffer, expected {}, was {}",
|
||||||
self.format.channel_count, buffer.len());
|
self.format.channel_count,
|
||||||
|
buffer.len()
|
||||||
|
);
|
||||||
|
|
||||||
let framed_bits_per_sample = self.format.block_alignment * 8 / self.format.channel_count;
|
let framed_bits_per_sample = self.format.block_alignment * 8 / self.format.channel_count;
|
||||||
|
|
||||||
@@ -124,9 +136,12 @@ impl<R: Read + Seek> AudioFrameReader<R> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn read_float_frame(&mut self, buffer: &mut [f32]) -> Result<u64, Error> {
|
pub fn read_float_frame(&mut self, buffer: &mut [f32]) -> Result<u64, Error> {
|
||||||
assert!(buffer.len() as u16 == self.format.channel_count,
|
assert!(
|
||||||
|
buffer.len() as u16 == self.format.channel_count,
|
||||||
"read_float_frame was called with a mis-sized buffer, expected {}, was {}",
|
"read_float_frame was called with a mis-sized buffer, expected {}, was {}",
|
||||||
self.format.channel_count, buffer.len());
|
self.format.channel_count,
|
||||||
|
buffer.len()
|
||||||
|
);
|
||||||
|
|
||||||
let framed_bits_per_sample = self.format.block_alignment * 8 / self.format.channel_count;
|
let framed_bits_per_sample = self.format.block_alignment * 8 / self.format.channel_count;
|
||||||
|
|
||||||
@@ -192,14 +207,12 @@ impl<R: Read + Seek> AudioFrameReader<R> {
|
|||||||
/// [itu2088]: https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.2088-1-201910-I!!PDF-E.pdf
|
/// [itu2088]: https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.2088-1-201910-I!!PDF-E.pdf
|
||||||
/// [rfc3261]: https://tools.ietf.org/html/rfc2361
|
/// [rfc3261]: https://tools.ietf.org/html/rfc2361
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct WaveReader<R: Read + Seek> {
|
pub struct WaveReader<R: Read + Seek> {
|
||||||
pub inner: R,
|
pub inner: R,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WaveReader<BufReader<File>> {
|
impl WaveReader<BufReader<File>> {
|
||||||
|
|
||||||
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, ParserError> {
|
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, ParserError> {
|
||||||
let f = File::open(path)?;
|
let f = File::open(path)?;
|
||||||
let inner = BufReader::new(f);
|
let inner = BufReader::new(f);
|
||||||
@@ -208,19 +221,17 @@ impl WaveReader<BufReader<File>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl WaveReader<File> {
|
impl WaveReader<File> {
|
||||||
|
|
||||||
/// Open a file for reading with unbuffered IO.
|
/// Open a file for reading with unbuffered IO.
|
||||||
///
|
///
|
||||||
/// A convenience that opens `path` and calls `Self::new()`
|
/// A convenience that opens `path` and calls `Self::new()`
|
||||||
|
|
||||||
pub fn open_unbuffered<P: AsRef<Path>>(path: P) -> Result<Self, ParserError> {
|
pub fn open_unbuffered<P: AsRef<Path>>(path: P) -> Result<Self, ParserError> {
|
||||||
let inner = File::open(path)?;
|
let inner = File::open(path)?;
|
||||||
return Ok( Self::new(inner)? )
|
return Ok(Self::new(inner)?);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read + Seek> WaveReader<R> {
|
impl<R: Read + Seek> WaveReader<R> {
|
||||||
|
|
||||||
/// Wrap a `Read` struct in a new `WaveReader`.
|
/// Wrap a `Read` struct in a new `WaveReader`.
|
||||||
///
|
///
|
||||||
/// This is the primary entry point into the `WaveReader` interface. The
|
/// This is the primary entry point into the `WaveReader` interface. The
|
||||||
@@ -257,7 +268,6 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
Ok(retval)
|
Ok(retval)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Unwrap the inner reader.
|
/// Unwrap the inner reader.
|
||||||
pub fn into_inner(self) -> R {
|
pub fn into_inner(self) -> R {
|
||||||
return self.inner;
|
return self.inner;
|
||||||
@@ -269,10 +279,14 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
pub fn audio_frame_reader(mut self) -> Result<AudioFrameReader<R>, ParserError> {
|
pub fn audio_frame_reader(mut self) -> Result<AudioFrameReader<R>, ParserError> {
|
||||||
let format = self.format()?;
|
let format = self.format()?;
|
||||||
let audio_chunk_reader = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
|
let audio_chunk_reader = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
|
||||||
Ok(AudioFrameReader::new(self.inner, format, audio_chunk_reader.0, audio_chunk_reader.1)?)
|
Ok(AudioFrameReader::new(
|
||||||
|
self.inner,
|
||||||
|
format,
|
||||||
|
audio_chunk_reader.0,
|
||||||
|
audio_chunk_reader.1,
|
||||||
|
)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// The count of audio frames in the file.
|
/// The count of audio frames in the file.
|
||||||
pub fn frame_length(&mut self) -> Result<u64, ParserError> {
|
pub fn frame_length(&mut self) -> Result<u64, ParserError> {
|
||||||
let (_, data_length) = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
|
let (_, data_length) = self.get_chunk_extent_at_index(DATA_SIG, 0)?;
|
||||||
@@ -280,7 +294,6 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
Ok(data_length / (format.block_alignment as u64))
|
Ok(data_length / (format.block_alignment as u64))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Sample and frame format of this wave file.
|
/// Sample and frame format of this wave file.
|
||||||
///
|
///
|
||||||
pub fn format(&mut self) -> Result<WaveFmt, ParserError> {
|
pub fn format(&mut self) -> Result<WaveFmt, ParserError> {
|
||||||
@@ -300,7 +313,6 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
} else {
|
} else {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Describe the channels in this file
|
/// Describe the channels in this file
|
||||||
@@ -321,17 +333,21 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
/// assert_eq!(chans[4].speaker, ChannelMask::BackLeft);
|
/// assert_eq!(chans[4].speaker, ChannelMask::BackLeft);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn channels(&mut self) -> Result<Vec<ChannelDescriptor>, ParserError> {
|
pub fn channels(&mut self) -> Result<Vec<ChannelDescriptor>, ParserError> {
|
||||||
|
|
||||||
let format = self.format()?;
|
let format = self.format()?;
|
||||||
let channel_masks: Vec<ChannelMask> = match (format.channel_count, format.extended_format) {
|
let channel_masks: Vec<ChannelMask> = match (format.channel_count, format.extended_format) {
|
||||||
(1, _) => vec![ChannelMask::FrontCenter],
|
(1, _) => vec![ChannelMask::FrontCenter],
|
||||||
(2, _) => vec![ChannelMask::FrontLeft, ChannelMask::FrontRight],
|
(2, _) => vec![ChannelMask::FrontLeft, ChannelMask::FrontRight],
|
||||||
(n, Some(x)) => ChannelMask::channels(x.channel_mask, n),
|
(n, Some(x)) => ChannelMask::channels(x.channel_mask, n),
|
||||||
(n,_) => vec![ChannelMask::DirectOut; n as usize]
|
(n, _) => vec![ChannelMask::DirectOut; n as usize],
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok( (0..format.channel_count).zip(channel_masks)
|
Ok((0..format.channel_count)
|
||||||
.map(|(i,m)| ChannelDescriptor { index: i, speaker:m, adm_track_audio_ids: vec![] } )
|
.zip(channel_masks)
|
||||||
|
.map(|(i, m)| ChannelDescriptor {
|
||||||
|
index: i,
|
||||||
|
speaker: m,
|
||||||
|
adm_track_audio_ids: vec![],
|
||||||
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -371,7 +387,7 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
match (cue_read, adtl_read) {
|
match (cue_read, adtl_read) {
|
||||||
(0, _) => Ok(vec![]),
|
(0, _) => Ok(vec![]),
|
||||||
(_, 0) => Ok(Cue::collect_from(&cue_buffer, None)?),
|
(_, 0) => Ok(Cue::collect_from(&cue_buffer, None)?),
|
||||||
(_,_) => Ok( Cue::collect_from(&cue_buffer, Some(&adtl_buffer) )? )
|
(_, _) => Ok(Cue::collect_from(&cue_buffer, Some(&adtl_buffer))?),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,7 +411,6 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
self.read_chunk(AXML_SIG, 0, buffer)
|
self.read_chunk(AXML_SIG, 0, buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate file is readable.
|
* Validate file is readable.
|
||||||
*
|
*
|
||||||
@@ -446,7 +461,10 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
self.validate_readable()?;
|
self.validate_readable()?;
|
||||||
|
|
||||||
let chunk_fourccs: Vec<FourCC> = Parser::make(&mut self.inner)?
|
let chunk_fourccs: Vec<FourCC> = Parser::make(&mut self.inner)?
|
||||||
.into_chunk_list()?.iter().map(|c| c.signature ).collect();
|
.into_chunk_list()?
|
||||||
|
.iter()
|
||||||
|
.map(|c| c.signature)
|
||||||
|
.collect();
|
||||||
|
|
||||||
if chunk_fourccs == vec![FMT__SIG, DATA_SIG] {
|
if chunk_fourccs == vec![FMT__SIG, DATA_SIG] {
|
||||||
Ok(()) /* FIXME: finish implementation */
|
Ok(()) /* FIXME: finish implementation */
|
||||||
@@ -509,28 +527,37 @@ impl<R: Read + Seek> WaveReader<R> {
|
|||||||
let chunks = Parser::make(&mut self.inner)?.into_chunk_list()?;
|
let chunks = Parser::make(&mut self.inner)?.into_chunk_list()?;
|
||||||
let ds64_space_required = 92;
|
let ds64_space_required = 92;
|
||||||
|
|
||||||
let eligible_filler_chunks = chunks.iter()
|
let eligible_filler_chunks = chunks
|
||||||
|
.iter()
|
||||||
.take_while(|c| c.signature == JUNK_SIG || c.signature == FLLR_SIG);
|
.take_while(|c| c.signature == JUNK_SIG || c.signature == FLLR_SIG);
|
||||||
|
|
||||||
let filler = eligible_filler_chunks
|
let filler = eligible_filler_chunks
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.fold(0, |accum, (n, item)| if n == 0 { accum + item.length } else {accum + item.length + 8});
|
.fold(0, |accum, (n, item)| {
|
||||||
|
if n == 0 {
|
||||||
|
accum + item.length
|
||||||
|
} else {
|
||||||
|
accum + item.length + 8
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if filler < ds64_space_required {
|
if filler < ds64_space_required {
|
||||||
Err(ParserError::InsufficientDS64Reservation {expected: ds64_space_required, actual: filler})
|
Err(ParserError::InsufficientDS64Reservation {
|
||||||
|
expected: ds64_space_required,
|
||||||
|
actual: filler,
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
let data_pos = chunks.iter().position(|c| c.signature == DATA_SIG);
|
let data_pos = chunks.iter().position(|c| c.signature == DATA_SIG);
|
||||||
|
|
||||||
match data_pos {
|
match data_pos {
|
||||||
Some(p) if p == chunks.len() - 1 => Ok(()),
|
Some(p) if p == chunks.len() - 1 => Ok(()),
|
||||||
_ => Err(ParserError::DataChunkNotPreparedForAppend)
|
_ => Err(ParserError::DataChunkNotPreparedForAppend),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Read + Seek> WaveReader<R> {
|
impl<R: Read + Seek> WaveReader<R> {
|
||||||
|
|
||||||
// Private implementation
|
// Private implementation
|
||||||
//
|
//
|
||||||
// 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
|
||||||
@@ -549,17 +576,22 @@ impl<R:Read+Seek> WaveReader<R> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn read_chunk(
|
||||||
fn read_chunk(&mut self, ident: FourCC, at: u32, mut buffer: &mut Vec<u8>) -> Result<usize, ParserError> {
|
&mut self,
|
||||||
|
ident: FourCC,
|
||||||
|
at: u32,
|
||||||
|
mut buffer: &mut Vec<u8>,
|
||||||
|
) -> Result<usize, ParserError> {
|
||||||
match self.get_chunk_extent_at_index(ident, at) {
|
match self.get_chunk_extent_at_index(ident, at) {
|
||||||
Ok((start, length)) => {
|
Ok((start, length)) => {
|
||||||
buffer.resize(length as usize, 0x0);
|
buffer.resize(length as usize, 0x0);
|
||||||
self.inner.seek(SeekFrom::Start(start))?;
|
self.inner.seek(SeekFrom::Start(start))?;
|
||||||
self.inner.read(&mut buffer).map_err(|e| ParserError::IOError(e))
|
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()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -567,8 +599,10 @@ impl<R:Read+Seek> WaveReader<R> {
|
|||||||
fn get_chunks_extents(&mut self, fourcc: FourCC) -> Result<Vec<(u64, u64)>, ParserError> {
|
fn get_chunks_extents(&mut self, fourcc: FourCC) -> Result<Vec<(u64, u64)>, ParserError> {
|
||||||
let p = Parser::make(&mut self.inner)?.into_chunk_list()?;
|
let p = Parser::make(&mut self.inner)?.into_chunk_list()?;
|
||||||
|
|
||||||
Ok( p.iter().filter(|item| item.signature == fourcc)
|
Ok(p.iter()
|
||||||
.map(|item| (item.start, item.length)).collect() )
|
.filter(|item| item.signature == fourcc)
|
||||||
|
.map(|item| (item.start, item.length))
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Index of first LIST for with the given FORM fourcc
|
/// Index of first LIST for with the given FORM fourcc
|
||||||
@@ -584,7 +618,11 @@ impl<R:Read+Seek> WaveReader<R> {
|
|||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_chunk_extent_at_index(&mut self, fourcc: FourCC, index: u32) -> Result<(u64,u64), ParserError> {
|
fn get_chunk_extent_at_index(
|
||||||
|
&mut self,
|
||||||
|
fourcc: FourCC,
|
||||||
|
index: u32,
|
||||||
|
) -> Result<(u64, u64), ParserError> {
|
||||||
if let Some((start, length)) = self.get_chunks_extents(fourcc)?.iter().nth(index as usize) {
|
if let Some((start, length)) = self.get_chunks_extents(fourcc)?.iter().nth(index as usize) {
|
||||||
Ok((*start, *length))
|
Ok((*start, *length))
|
||||||
} else {
|
} else {
|
||||||
@@ -601,5 +639,4 @@ fn test_list_form() {
|
|||||||
f.read_list(ADTL_SIG, &mut buf).unwrap();
|
f.read_list(ADTL_SIG, &mut buf).unwrap();
|
||||||
|
|
||||||
assert_ne!(buf.len(), 0);
|
assert_ne!(buf.len(), 0);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
use std::io::{BufWriter, Cursor, Seek, SeekFrom, Write};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::io::{Write,Seek,SeekFrom,Cursor,BufWriter};
|
|
||||||
|
|
||||||
use super::Error;
|
|
||||||
use super::fourcc::{FourCC, WriteFourCC, RIFF_SIG, RF64_SIG, DS64_SIG,
|
|
||||||
WAVE_SIG, FMT__SIG, DATA_SIG, ELM1_SIG, JUNK_SIG, BEXT_SIG,AXML_SIG,
|
|
||||||
IXML_SIG};
|
|
||||||
use super::fmt::WaveFmt;
|
use super::fmt::WaveFmt;
|
||||||
|
use super::fourcc::{
|
||||||
|
FourCC, WriteFourCC, AXML_SIG, BEXT_SIG, DATA_SIG, DS64_SIG, ELM1_SIG, FMT__SIG, IXML_SIG,
|
||||||
|
JUNK_SIG, RF64_SIG, RIFF_SIG, WAVE_SIG,
|
||||||
|
};
|
||||||
|
use super::Error;
|
||||||
//use super::common_format::CommonFormat;
|
//use super::common_format::CommonFormat;
|
||||||
use super::chunks::WriteBWaveChunks;
|
|
||||||
use super::bext::Bext;
|
use super::bext::Bext;
|
||||||
|
use super::chunks::WriteBWaveChunks;
|
||||||
|
|
||||||
use byteorder::LittleEndian;
|
use byteorder::LittleEndian;
|
||||||
use byteorder::WriteBytesExt;
|
use byteorder::WriteBytesExt;
|
||||||
@@ -17,19 +18,26 @@ use byteorder::WriteBytesExt;
|
|||||||
/// Write audio frames to a `WaveWriter`.
|
/// Write audio frames to a `WaveWriter`.
|
||||||
///
|
///
|
||||||
///
|
///
|
||||||
pub struct AudioFrameWriter<W> where W: Write + Seek {
|
pub struct AudioFrameWriter<W>
|
||||||
inner : WaveChunkWriter<W>
|
where
|
||||||
|
W: Write + Seek,
|
||||||
|
{
|
||||||
|
inner: WaveChunkWriter<W>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<W> AudioFrameWriter<W> where W: Write + Seek {
|
impl<W> AudioFrameWriter<W>
|
||||||
|
where
|
||||||
|
W: Write + Seek,
|
||||||
|
{
|
||||||
fn new(inner: WaveChunkWriter<W>) -> Self {
|
fn new(inner: WaveChunkWriter<W>) -> Self {
|
||||||
AudioFrameWriter { inner }
|
AudioFrameWriter { inner }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_integer_frames_to_buffer(&self, from_frames: &[i32], to_buffer: &mut [u8]) -> () {
|
fn write_integer_frames_to_buffer(&self, from_frames: &[i32], to_buffer: &mut [u8]) -> () {
|
||||||
assert!(from_frames.len() % self.inner.inner.format.channel_count as usize == 0,
|
assert!(
|
||||||
"frames buffer does not contain a number of samples % channel_count == 0");
|
from_frames.len() % self.inner.inner.format.channel_count as usize == 0,
|
||||||
|
"frames buffer does not contain a number of samples % channel_count == 0"
|
||||||
|
);
|
||||||
self.inner.inner.format.pack_frames(&from_frames, to_buffer);
|
self.inner.inner.format.pack_frames(&from_frames, to_buffer);
|
||||||
()
|
()
|
||||||
}
|
}
|
||||||
@@ -41,7 +49,10 @@ impl<W> AudioFrameWriter<W> where W: Write + Seek {
|
|||||||
/// This function will panic if `buffer.len()` modulo the Wave file's channel count
|
/// This function will panic if `buffer.len()` modulo the Wave file's channel count
|
||||||
/// is not zero.
|
/// is not zero.
|
||||||
pub fn write_integer_frames(&mut self, buffer: &[i32]) -> Result<u64, Error> {
|
pub fn write_integer_frames(&mut self, buffer: &[i32]) -> Result<u64, Error> {
|
||||||
let mut write_buffer = self.inner.inner.format
|
let mut write_buffer = self
|
||||||
|
.inner
|
||||||
|
.inner
|
||||||
|
.format
|
||||||
.create_raw_buffer(buffer.len() / self.inner.inner.format.channel_count as usize);
|
.create_raw_buffer(buffer.len() / self.inner.inner.format.channel_count as usize);
|
||||||
|
|
||||||
self.write_integer_frames_to_buffer(&buffer, &mut write_buffer);
|
self.write_integer_frames_to_buffer(&buffer, &mut write_buffer);
|
||||||
@@ -68,22 +79,32 @@ impl<W> AudioFrameWriter<W> where W: Write + Seek {
|
|||||||
///
|
///
|
||||||
/// When you are done writing to a chunk you must call `end()` in order to
|
/// When you are done writing to a chunk you must call `end()` in order to
|
||||||
/// finalize the chunk for storage.
|
/// finalize the chunk for storage.
|
||||||
pub struct WaveChunkWriter<W> where W: Write + Seek {
|
pub struct WaveChunkWriter<W>
|
||||||
|
where
|
||||||
|
W: Write + Seek,
|
||||||
|
{
|
||||||
ident: FourCC,
|
ident: FourCC,
|
||||||
inner: WaveWriter<W>,
|
inner: WaveWriter<W>,
|
||||||
content_start_pos: u64,
|
content_start_pos: u64,
|
||||||
length : u64
|
length: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<W> WaveChunkWriter<W> where W: Write + Seek {
|
impl<W> WaveChunkWriter<W>
|
||||||
|
where
|
||||||
|
W: Write + Seek,
|
||||||
|
{
|
||||||
fn begin(mut inner: WaveWriter<W>, ident: FourCC) -> Result<Self, Error> {
|
fn begin(mut inner: WaveWriter<W>, ident: FourCC) -> Result<Self, Error> {
|
||||||
let length: u64 = 0;
|
let length: u64 = 0;
|
||||||
inner.inner.write_fourcc(ident)?;
|
inner.inner.write_fourcc(ident)?;
|
||||||
inner.inner.write_u32::<LittleEndian>(length as u32)?;
|
inner.inner.write_u32::<LittleEndian>(length as u32)?;
|
||||||
inner.increment_form_length(8)?;
|
inner.increment_form_length(8)?;
|
||||||
let content_start_pos = inner.inner.seek(SeekFrom::End(0))?;
|
let content_start_pos = inner.inner.seek(SeekFrom::End(0))?;
|
||||||
Ok( WaveChunkWriter { ident, inner , content_start_pos, length } )
|
Ok(WaveChunkWriter {
|
||||||
|
ident,
|
||||||
|
inner,
|
||||||
|
content_start_pos,
|
||||||
|
length,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn end(mut self) -> Result<WaveWriter<W>, Error> {
|
fn end(mut self) -> Result<WaveWriter<W>, Error> {
|
||||||
@@ -98,29 +119,38 @@ impl<W> WaveChunkWriter<W> where W: Write + Seek {
|
|||||||
fn increment_chunk_length(&mut self, amount: u64) -> Result<(), std::io::Error> {
|
fn increment_chunk_length(&mut self, amount: u64) -> Result<(), std::io::Error> {
|
||||||
self.length = self.length + amount;
|
self.length = self.length + amount;
|
||||||
if !self.inner.is_rf64 {
|
if !self.inner.is_rf64 {
|
||||||
self.inner.inner.seek(SeekFrom::Start(self.content_start_pos - 4))?;
|
self.inner
|
||||||
self.inner.inner.write_u32::<LittleEndian>(self.length as u32)?;
|
.inner
|
||||||
|
.seek(SeekFrom::Start(self.content_start_pos - 4))?;
|
||||||
|
self.inner
|
||||||
|
.inner
|
||||||
|
.write_u32::<LittleEndian>(self.length as u32)?;
|
||||||
} else {
|
} else {
|
||||||
if self.ident == DATA_SIG {
|
if self.ident == DATA_SIG {
|
||||||
let data_chunk_64bit_field_offset = 8 + 4 + 8 + 8;
|
let data_chunk_64bit_field_offset = 8 + 4 + 8 + 8;
|
||||||
self.inner.inner.seek(SeekFrom::Start(self.content_start_pos - 4))?;
|
self.inner
|
||||||
|
.inner
|
||||||
|
.seek(SeekFrom::Start(self.content_start_pos - 4))?;
|
||||||
self.inner.inner.write_u32::<LittleEndian>(0xFFFF_FFFF)?;
|
self.inner.inner.write_u32::<LittleEndian>(0xFFFF_FFFF)?;
|
||||||
// this only need to happen once, not every time we increment
|
// 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
|
||||||
|
.seek(SeekFrom::Start(data_chunk_64bit_field_offset))?;
|
||||||
self.inner.inner.write_u64::<LittleEndian>(self.length)?;
|
self.inner.inner.write_u64::<LittleEndian>(self.length)?;
|
||||||
} else {
|
} else {
|
||||||
todo!("FIXME RF64 wave writing is not yet supported for chunks other than `data`")
|
todo!("FIXME RF64 wave writing is not yet supported for chunks other than `data`")
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<W> Write for WaveChunkWriter<W> where W: Write + Seek {
|
impl<W> Write for WaveChunkWriter<W>
|
||||||
|
where
|
||||||
|
W: Write + Seek,
|
||||||
|
{
|
||||||
fn write(&mut self, buffer: &[u8]) -> Result<usize, std::io::Error> {
|
fn write(&mut self, buffer: &[u8]) -> Result<usize, std::io::Error> {
|
||||||
self.inner.inner.seek(SeekFrom::End(0))?;
|
self.inner.inner.seek(SeekFrom::End(0))?;
|
||||||
let written = self.inner.inner.write(buffer)?;
|
let written = self.inner.inner.write(buffer)?;
|
||||||
@@ -198,7 +228,10 @@ impl<W> Write for WaveChunkWriter<W> where W: Write + Seek {
|
|||||||
/// [ebu3306v2]: https://tech.ebu.ch/docs/tech/tech3306.pdf
|
/// [ebu3306v2]: https://tech.ebu.ch/docs/tech/tech3306.pdf
|
||||||
/// [itu2088]: https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.2088-1-201910-I!!PDF-E.pdf
|
/// [itu2088]: https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.2088-1-201910-I!!PDF-E.pdf
|
||||||
/// [rfc3261]: https://tools.ietf.org/html/rfc2361
|
/// [rfc3261]: https://tools.ietf.org/html/rfc2361
|
||||||
pub struct WaveWriter<W> where W: Write + Seek {
|
pub struct WaveWriter<W>
|
||||||
|
where
|
||||||
|
W: Write + Seek,
|
||||||
|
{
|
||||||
inner: W,
|
inner: W,
|
||||||
form_length: u64,
|
form_length: u64,
|
||||||
|
|
||||||
@@ -206,13 +239,12 @@ pub struct WaveWriter<W> where W: Write + Seek {
|
|||||||
pub is_rf64: bool,
|
pub is_rf64: bool,
|
||||||
|
|
||||||
/// Format of the wave file.
|
/// Format of the wave file.
|
||||||
pub format: WaveFmt
|
pub format: WaveFmt,
|
||||||
}
|
}
|
||||||
|
|
||||||
const DS64_RESERVATION_LENGTH: u32 = 96;
|
const DS64_RESERVATION_LENGTH: u32 = 96;
|
||||||
|
|
||||||
impl WaveWriter<BufWriter<File>> {
|
impl WaveWriter<BufWriter<File>> {
|
||||||
|
|
||||||
/// Create a new Wave file at `path`.
|
/// Create a new Wave file at `path`.
|
||||||
pub fn create<P: AsRef<Path>>(path: P, format: WaveFmt) -> Result<Self, Error> {
|
pub fn create<P: AsRef<Path>>(path: P, format: WaveFmt) -> Result<Self, Error> {
|
||||||
let f = File::create(path)?;
|
let f = File::create(path)?;
|
||||||
@@ -229,8 +261,10 @@ impl WaveWriter<File> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<W> WaveWriter<W> where W: Write + Seek {
|
impl<W> WaveWriter<W>
|
||||||
|
where
|
||||||
|
W: Write + Seek,
|
||||||
|
{
|
||||||
/// Wrap a writer in a Wave writer.
|
/// Wrap a writer in a Wave writer.
|
||||||
///
|
///
|
||||||
/// The inner writer will immediately have a RIFF WAVE file header
|
/// The inner writer will immediately have a RIFF WAVE file header
|
||||||
@@ -241,7 +275,12 @@ impl<W> WaveWriter<W> where W: Write + Seek {
|
|||||||
inner.write_u32::<LittleEndian>(0)?;
|
inner.write_u32::<LittleEndian>(0)?;
|
||||||
inner.write_fourcc(WAVE_SIG)?;
|
inner.write_fourcc(WAVE_SIG)?;
|
||||||
|
|
||||||
let mut retval = WaveWriter { inner, form_length: 0, is_rf64: false, format};
|
let mut retval = WaveWriter {
|
||||||
|
inner,
|
||||||
|
form_length: 0,
|
||||||
|
is_rf64: false,
|
||||||
|
format,
|
||||||
|
};
|
||||||
|
|
||||||
retval.increment_form_length(4)?;
|
retval.increment_form_length(4)?;
|
||||||
|
|
||||||
@@ -350,10 +389,10 @@ impl<W> WaveWriter<W> where W: Write + Seek {
|
|||||||
self.inner.write_u64::<LittleEndian>(self.form_length)?;
|
self.inner.write_u64::<LittleEndian>(self.form_length)?;
|
||||||
} else if self.form_length < u32::MAX as u64 {
|
} else if self.form_length < u32::MAX as u64 {
|
||||||
self.inner.seek(SeekFrom::Start(4))?;
|
self.inner.seek(SeekFrom::Start(4))?;
|
||||||
self.inner.write_u32::<LittleEndian>(self.form_length as u32)?;
|
self.inner
|
||||||
|
.write_u32::<LittleEndian>(self.form_length as u32)?;
|
||||||
} else {
|
} else {
|
||||||
self.promote_to_rf64()?;
|
self.promote_to_rf64()?;
|
||||||
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -361,9 +400,9 @@ impl<W> WaveWriter<W> where W: Write + Seek {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_new() {
|
fn test_new() {
|
||||||
use std::io::Cursor;
|
|
||||||
use super::fourcc::ReadFourCC;
|
use super::fourcc::ReadFourCC;
|
||||||
use byteorder::ReadBytesExt;
|
use byteorder::ReadBytesExt;
|
||||||
|
use std::io::Cursor;
|
||||||
|
|
||||||
let mut cursor = Cursor::new(vec![0u8; 0]);
|
let mut cursor = Cursor::new(vec![0u8; 0]);
|
||||||
let format = WaveFmt::new_pcm_mono(4800, 24);
|
let format = WaveFmt::new_pcm_mono(4800, 24);
|
||||||
@@ -387,9 +426,9 @@ fn test_new() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_write_audio() {
|
fn test_write_audio() {
|
||||||
use std::io::Cursor;
|
|
||||||
use super::fourcc::ReadFourCC;
|
use super::fourcc::ReadFourCC;
|
||||||
use byteorder::ReadBytesExt;
|
use byteorder::ReadBytesExt;
|
||||||
|
use std::io::Cursor;
|
||||||
|
|
||||||
let mut cursor = Cursor::new(vec![0u8; 0]);
|
let mut cursor = Cursor::new(vec![0u8; 0]);
|
||||||
let format = WaveFmt::new_pcm_mono(48000, 24);
|
let format = WaveFmt::new_pcm_mono(48000, 24);
|
||||||
@@ -430,7 +469,10 @@ fn test_write_audio() {
|
|||||||
let tell = cursor.seek(SeekFrom::Current(0)).unwrap();
|
let tell = cursor.seek(SeekFrom::Current(0)).unwrap();
|
||||||
assert!(tell % 0x4000 == 0);
|
assert!(tell % 0x4000 == 0);
|
||||||
|
|
||||||
assert_eq!(form_size, 4 + 8 + junk_size + 8 + fmt_size + 8 + elm1_size + 8 + data_size + data_size % 2)
|
assert_eq!(
|
||||||
|
form_size,
|
||||||
|
4 + 8 + junk_size + 8 + fmt_size + 8 + elm1_size + 8 + data_size + data_size % 2
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -469,7 +511,6 @@ fn test_write_bext() {
|
|||||||
frame_writer.end().unwrap();
|
frame_writer.end().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// NOTE! This test of RF64 writing takes several minutes to complete.
|
// NOTE! This test of RF64 writing takes several minutes to complete.
|
||||||
#[test]
|
#[test]
|
||||||
fn test_create_rf64() {
|
fn test_create_rf64() {
|
||||||
@@ -493,7 +534,10 @@ fn test_create_rf64() {
|
|||||||
}
|
}
|
||||||
af.end().unwrap();
|
af.end().unwrap();
|
||||||
|
|
||||||
assert!(cursor.seek(SeekFrom::End(0)).unwrap() > 0xFFFF_FFFFu64, "internal test error, Created file is not long enough to be RF64" );
|
assert!(
|
||||||
|
cursor.seek(SeekFrom::End(0)).unwrap() > 0xFFFF_FFFFu64,
|
||||||
|
"internal test error, Created file is not long enough to be RF64"
|
||||||
|
);
|
||||||
let expected_data_length = four_and_a_half_hours_of_frames * format.block_alignment as u64;
|
let expected_data_length = four_and_a_half_hours_of_frames * format.block_alignment as u64;
|
||||||
|
|
||||||
cursor.seek(SeekFrom::Start(0)).unwrap();
|
cursor.seek(SeekFrom::Start(0)).unwrap();
|
||||||
@@ -506,20 +550,33 @@ fn test_create_rf64() {
|
|||||||
let form_size = cursor.read_u64::<LittleEndian>().unwrap();
|
let form_size = cursor.read_u64::<LittleEndian>().unwrap();
|
||||||
let data_size = cursor.read_u64::<LittleEndian>().unwrap();
|
let data_size = cursor.read_u64::<LittleEndian>().unwrap();
|
||||||
assert_eq!(data_size, expected_data_length);
|
assert_eq!(data_size, expected_data_length);
|
||||||
cursor.seek(SeekFrom::Current(ds64_size as i64 - 16)).unwrap();
|
cursor
|
||||||
|
.seek(SeekFrom::Current(ds64_size as i64 - 16))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(cursor.read_fourcc().unwrap(), FMT__SIG);
|
assert_eq!(cursor.read_fourcc().unwrap(), FMT__SIG);
|
||||||
let fmt_size = cursor.read_u32::<LittleEndian>().unwrap();
|
let fmt_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
cursor.seek(SeekFrom::Current((fmt_size + fmt_size % 2) as i64)).unwrap();
|
cursor
|
||||||
|
.seek(SeekFrom::Current((fmt_size + fmt_size % 2) as i64))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(cursor.read_fourcc().unwrap(), ELM1_SIG);
|
assert_eq!(cursor.read_fourcc().unwrap(), ELM1_SIG);
|
||||||
let elm1_size = cursor.read_u32::<LittleEndian>().unwrap();
|
let elm1_size = cursor.read_u32::<LittleEndian>().unwrap();
|
||||||
let data_start = cursor.seek(SeekFrom::Current((elm1_size + elm1_size % 2) as i64)).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!(
|
||||||
|
(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_fourcc().unwrap(), DATA_SIG);
|
||||||
assert_eq!(cursor.read_u32::<LittleEndian>().unwrap(), 0xFFFF_FFFF);
|
assert_eq!(cursor.read_u32::<LittleEndian>().unwrap(), 0xFFFF_FFFF);
|
||||||
cursor.seek(SeekFrom::Current(data_size as i64)).unwrap();
|
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)
|
assert_eq!(
|
||||||
|
4 + 8 + ds64_size as u64 + 8 + data_size + 8 + fmt_size as u64 + 8 + elm1_size as u64,
|
||||||
|
form_size
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
|
|
||||||
extern crate serde_json;
|
extern crate serde_json;
|
||||||
use core::fmt::Debug;
|
use core::fmt::Debug;
|
||||||
use serde_json::{Value, from_str};
|
use serde_json::{from_str, Value};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
@@ -13,20 +12,18 @@ use bwavfile::WaveReader;
|
|||||||
// as read by `WaveReader`.
|
// as read by `WaveReader`.
|
||||||
|
|
||||||
// This is rickety but we're going with it
|
// This is rickety but we're going with it
|
||||||
fn assert_match_stream<T>(stream_key: &str,
|
fn assert_match_stream<T>(stream_key: &str, other: impl Fn(&mut WaveReader<File>) -> T)
|
||||||
other: impl Fn(&mut WaveReader<File>) -> T)
|
where
|
||||||
where T: PartialEq + Debug,
|
T: PartialEq + Debug,
|
||||||
T: Into<Value>
|
T: Into<Value>,
|
||||||
{
|
{
|
||||||
|
|
||||||
let mut json_file = File::open("tests/ffprobe_media_tests.json").unwrap();
|
let mut json_file = File::open("tests/ffprobe_media_tests.json").unwrap();
|
||||||
let mut s = String::new();
|
let mut s = String::new();
|
||||||
json_file.read_to_string(&mut s).unwrap();
|
json_file.read_to_string(&mut s).unwrap();
|
||||||
if let Value::Array(v) = from_str(&mut s).unwrap() { /* */
|
if let Value::Array(v) = from_str(&mut s).unwrap() {
|
||||||
|
/* */
|
||||||
v.iter()
|
v.iter()
|
||||||
.filter(|value| {
|
.filter(|value| !value["format"]["filename"].is_null())
|
||||||
!value["format"]["filename"].is_null()
|
|
||||||
})
|
|
||||||
.for_each(|value| {
|
.for_each(|value| {
|
||||||
let filen: &str = value["format"]["filename"].as_str().unwrap();
|
let filen: &str = value["format"]["filename"].as_str().unwrap();
|
||||||
let json_value: &Value = &value["streams"][0][stream_key];
|
let json_value: &Value = &value["streams"][0][stream_key];
|
||||||
@@ -34,7 +31,6 @@ fn assert_match_stream<T>(stream_key: &str,
|
|||||||
let wavfile_value: T = other(&mut wavfile);
|
let wavfile_value: T = other(&mut wavfile);
|
||||||
println!("asserting {} for {}", stream_key, filen);
|
println!("asserting {} for {}", stream_key, filen);
|
||||||
assert_eq!(Into::<Value>::into(wavfile_value), *json_value);
|
assert_eq!(Into::<Value>::into(wavfile_value), *json_value);
|
||||||
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,7 +42,9 @@ fn test_frame_count() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_sample_rate() {
|
fn test_sample_rate() {
|
||||||
assert_match_stream("sample_rate", |w| format!("{}", w.format().unwrap().sample_rate) );
|
assert_match_stream("sample_rate", |w| {
|
||||||
|
format!("{}", w.format().unwrap().sample_rate)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,17 +1,15 @@
|
|||||||
extern crate bwavfile;
|
extern crate bwavfile;
|
||||||
|
|
||||||
use bwavfile::WaveReader;
|
use bwavfile::ChannelMask;
|
||||||
use bwavfile::Error;
|
use bwavfile::Error;
|
||||||
use bwavfile::{ ChannelMask};
|
use bwavfile::WaveReader;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_open() {
|
fn test_open() {
|
||||||
let path = "tests/media/ff_silence.wav";
|
let path = "tests/media/ff_silence.wav";
|
||||||
|
|
||||||
match WaveReader::open(path) {
|
match WaveReader::open(path) {
|
||||||
Ok(_) => {
|
Ok(_) => (),
|
||||||
()
|
|
||||||
},
|
|
||||||
Err(x) => {
|
Err(x) => {
|
||||||
assert!(false, "Opened error.wav with unexpected error {:?}", x)
|
assert!(false, "Opened error.wav with unexpected error {:?}", x)
|
||||||
}
|
}
|
||||||
@@ -86,8 +84,6 @@ fn test_read() {
|
|||||||
|
|
||||||
let mut reader = w.audio_frame_reader().unwrap();
|
let mut reader = w.audio_frame_reader().unwrap();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
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);
|
||||||
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
|
assert_eq!(reader.read_integer_frame(&mut buffer).unwrap(), 1);
|
||||||
@@ -162,9 +158,11 @@ fn test_channels_stereo_no_fmt_extended() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_frame_reader_consumes_reader() {
|
fn test_frame_reader_consumes_reader() {
|
||||||
// Issue #6
|
// Issue #6
|
||||||
use bwavfile::{WaveFmt, AudioFrameReader};
|
use bwavfile::{AudioFrameReader, WaveFmt};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
fn from_wav_filename(wav_filename: &str) -> Result<(WaveFmt, AudioFrameReader<std::io::BufReader<File>>), ()> {
|
fn from_wav_filename(
|
||||||
|
wav_filename: &str,
|
||||||
|
) -> Result<(WaveFmt, AudioFrameReader<std::io::BufReader<File>>), ()> {
|
||||||
if let Ok(mut r) = WaveReader::open(&wav_filename) {
|
if let Ok(mut r) = WaveReader::open(&wav_filename) {
|
||||||
let format = r.format().unwrap();
|
let format = r.format().unwrap();
|
||||||
let frame_reader = r.audio_frame_reader().unwrap();
|
let frame_reader = r.audio_frame_reader().unwrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user