use std::path::Path;
use std::time::Duration;
use crate::audio::AudioFormat;
use crate::error::UnbundleError;
use crate::unbundle::MediaFile;
pub struct Transcoder<'a> {
unbundler: &'a mut MediaFile,
format: AudioFormat,
start: Option<Duration>,
end: Option<Duration>,
bitrate: Option<usize>,
}
impl<'a> Transcoder<'a> {
pub fn new(unbundler: &'a mut MediaFile) -> Self {
Self {
unbundler,
format: AudioFormat::Wav,
start: None,
end: None,
bitrate: None,
}
}
pub fn format(mut self, format: AudioFormat) -> Self {
self.format = format;
self
}
pub fn with_format(self, format: AudioFormat) -> Self {
self.format(format)
}
pub fn start(mut self, start: Duration) -> Self {
self.start = Some(start);
self
}
pub fn with_start(self, start: Duration) -> Self {
self.start(start)
}
pub fn end(mut self, end: Duration) -> Self {
self.end = Some(end);
self
}
pub fn with_end(self, end: Duration) -> Self {
self.end(end)
}
pub fn bitrate(mut self, bitrate: usize) -> Self {
self.bitrate = Some(bitrate);
self
}
pub fn with_bitrate(self, bitrate: usize) -> Self {
self.bitrate(bitrate)
}
pub fn run<P: AsRef<Path>>(self, path: P) -> Result<(), UnbundleError> {
log::info!(
"Transcoding audio to {:?} (format={:?})",
path.as_ref(),
self.format
);
match (self.start, self.end) {
(Some(start), Some(end)) => self
.unbundler
.audio()
.save_range(path, start, end, self.format)
.map_err(|e| UnbundleError::TranscodeError(e.to_string())),
_ => self
.unbundler
.audio()
.save(path, self.format)
.map_err(|e| UnbundleError::TranscodeError(e.to_string())),
}
}
pub fn run_to_memory(self) -> Result<Vec<u8>, UnbundleError> {
log::debug!("Transcoding audio to memory (format={:?})", self.format);
match (self.start, self.end) {
(Some(start), Some(end)) => self
.unbundler
.audio()
.extract_range(start, end, self.format)
.map_err(|e| UnbundleError::TranscodeError(e.to_string())),
_ => self
.unbundler
.audio()
.extract(self.format)
.map_err(|e| UnbundleError::TranscodeError(e.to_string())),
}
}
}