use std::{path::Path, process};
use avio::{AsyncAudioDecoder, AsyncAudioEncoder, AudioCodec, AudioDecoder, AudioEncoder};
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let mut input = None::<String>;
let mut output = None::<String>;
let mut codec_str = "aac".to_string();
let mut bitrate: u64 = 192_000;
while let Some(flag) = args.next() {
match flag.as_str() {
"--input" | "-i" => input = Some(args.next().unwrap_or_default()),
"--output" | "-o" => output = Some(args.next().unwrap_or_default()),
"--codec" | "-c" => codec_str = args.next().unwrap_or_else(|| "aac".to_string()),
"--bitrate" => {
let v = args.next().unwrap_or_default();
bitrate = v.parse().unwrap_or(192_000);
}
other => {
eprintln!("Unknown flag: {other}");
process::exit(1);
}
}
}
let input = input.unwrap_or_else(|| {
eprintln!(
"Usage: async_encode_audio --input <file> --output <file> \
[--codec aac|mp3|opus|flac] [--bitrate N]"
);
process::exit(1);
});
let output = output.unwrap_or_else(|| {
eprintln!("--output is required");
process::exit(1);
});
let codec = match codec_str.to_lowercase().as_str() {
"aac" => AudioCodec::Aac,
"mp3" => AudioCodec::Mp3,
"opus" => AudioCodec::Opus,
"flac" => AudioCodec::Flac,
other => {
eprintln!("Unknown codec '{other}' (try aac, mp3, opus, flac)");
process::exit(1);
}
};
let in_name = Path::new(&input)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&input);
let out_name = Path::new(&output)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(&output);
let probe = match AudioDecoder::open(&input).build() {
Ok(d) => d,
Err(e) => {
eprintln!("Error opening input: {e}");
process::exit(1);
}
};
let sample_rate = probe.sample_rate();
let channels = probe.channels();
let in_codec = probe.stream_info().codec_name().to_string();
drop(probe);
println!("Input: {in_name} codec={in_codec} sample_rate={sample_rate} channels={channels}");
println!("Output: {out_name} codec={codec_str} bitrate={bitrate}");
println!();
println!("=== Pattern 1: basic async encode ===");
let mut encoder = match AsyncAudioEncoder::from_builder(
AudioEncoder::create(&output)
.audio(sample_rate, channels)
.audio_codec(codec)
.audio_bitrate(bitrate),
) {
Ok(e) => e,
Err(e) => {
eprintln!("Error building encoder: {e}");
process::exit(1);
}
};
let decoder = match AsyncAudioDecoder::open(input.clone()).await {
Ok(d) => d,
Err(e) => {
eprintln!("Error opening decoder: {e}");
process::exit(1);
}
};
let mut frames: u64 = 0;
let stream = decoder.into_stream();
tokio::pin!(stream);
while let Some(result) = stream.next().await {
match result {
Ok(frame) => {
encoder.push(frame).await?;
frames += 1;
}
Err(e) => {
eprintln!("Decode error: {e}");
break;
}
}
}
encoder.finish().await?;
let size_str = file_size_str(&output);
println!("Done. {out_name} {size_str} {frames} frames encoded");
println!();
println!("=== Pattern 2: streaming from an async source ===");
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let producer_input = input.clone();
let producer = tokio::spawn(async move {
match AsyncAudioDecoder::open(producer_input).await {
Ok(decoder) => {
let stream = decoder.into_stream();
tokio::pin!(stream);
while let Some(result) = stream.next().await {
match result {
Ok(frame) => {
if tx.send(frame).await.is_err() {
break; }
}
Err(e) => {
eprintln!("Producer decode error: {e}");
break;
}
}
}
}
Err(e) => eprintln!("Producer open error: {e}"),
}
});
let mut encoder2 = match AsyncAudioEncoder::from_builder(
AudioEncoder::create(&output)
.audio(sample_rate, channels)
.audio_codec(codec)
.audio_bitrate(bitrate),
) {
Ok(e) => e,
Err(e) => {
eprintln!("Error building encoder: {e}");
process::exit(1);
}
};
let mut frames2: u64 = 0;
while let Some(frame) = rx.recv().await {
encoder2.push(frame).await?;
frames2 += 1;
}
encoder2.finish().await?;
producer.await?;
let size_str2 = file_size_str(&output);
println!("Done. {out_name} {size_str2} {frames2} frames encoded");
Ok(())
}
fn file_size_str(path: &str) -> String {
match std::fs::metadata(path) {
Ok(m) => {
#[allow(clippy::cast_precision_loss)]
let kb = m.len() as f64 / 1024.0;
if kb < 1024.0 {
format!("{kb:.0} KB")
} else {
format!("{:.1} MB", kb / 1024.0)
}
}
Err(_) => "(unknown size)".to_string(),
}
}