Add RecordedAudioTrack

This commit is contained in:
Skyler Lehmkuhl
2025-01-29 04:41:59 -05:00
parent e12c2e8877
commit 749caa14a5
9 changed files with 800 additions and 30 deletions
+327 -23
View File
@@ -3,8 +3,29 @@ use time::{Timestamp, Duration, Frame, SampleCount};
mod audio;
use audio::{CpalAudioOutput};
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use rubato::{FftFixedIn, Resampler};
use std::io::Cursor;
use std::sync::{Arc, Mutex};
use std::error::Error;
use symphonia::core::{
audio::AudioBufferRef,
audio::Signal,
codecs::{DecoderOptions},
formats::{FormatOptions},
io::MediaSourceStream,
meta::MetadataOptions,
probe::Hint,
};
#[cfg(not(target_arch = "wasm32"))]
use std::io;
#[cfg(not(target_arch = "wasm32"))]
use std::io::Write;
#[cfg(target_arch = "wasm32")]
use std::fmt;
#[cfg(feature = "wasm")]
@@ -20,7 +41,7 @@ pub trait Track: Send {
fn get_name(&self) -> &str {
"Unnamed Track"
}
fn set_name(&mut self, _name: String) {
}
/// Render audio for the given timestamp and duration.
@@ -34,6 +55,10 @@ pub trait Track: Send {
fn render_video(&self, _timestamp: Timestamp, _playing: bool) -> Option<Frame> {
None
}
// Set the sample rate of any audio this track might contain
fn set_sample_rate(&mut self, _sample_rate: u32) {
}
}
pub struct TrackManager {
@@ -154,34 +179,288 @@ impl Track for SineWaveTrack {
}
}
#[derive(Debug, Clone)]
struct AudioBuffer {
original_data: Vec<f32>,
original_sample_rate: u32,
resampled_data: Vec<f32>,
start_time: Timestamp,
}
impl AudioBuffer {
fn duration(&self) -> Duration {
if self.resampled_data.is_empty() {
Duration::from_seconds(0.0)
} else {
Duration::from_seconds(
self.resampled_data.len() as f64 /
self.original_sample_rate as f64
)
}
}
}
pub struct RecordedAudioTrack {
name: String,
buffers: Vec<AudioBuffer>,
target_sample_rate: Option<u32>,
}
impl RecordedAudioTrack {
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
buffers: Vec::new(),
target_sample_rate: None,
}
}
pub fn add_buffer(&mut self, start_time: Timestamp, sample_rate: u32, data: Vec<f32>) {
let resampled_data = match self.target_sample_rate {
Some(target_rate) if sample_rate != target_rate =>
self::resample(&data, sample_rate, target_rate),
Some(_target_rate) =>
data.clone(), // Already at target rate
None =>
Vec::new(), // Will be resampled later
};
self.buffers.push(AudioBuffer {
original_data: data,
original_sample_rate: sample_rate,
resampled_data,
start_time,
});
// Keep buffers sorted by start time
self.buffers.sort_by(|a, b| a.start_time.partial_cmp(&b.start_time).unwrap());
}
}
impl Track for RecordedAudioTrack {
fn get_name(&self) -> &str {
&self.name
}
fn set_sample_rate(&mut self, target_rate: u32) {
self.target_sample_rate = Some(target_rate);
for buffer in &mut self.buffers {
if buffer.original_sample_rate == target_rate {
buffer.resampled_data = buffer.original_data.clone();
} else {
buffer.resampled_data = self::resample(
&buffer.original_data,
buffer.original_sample_rate,
target_rate
);
}
}
}
fn render_audio(
&mut self,
timestamp: Timestamp,
duration: SampleCount,
sample_rate: u32,
playing: bool,
) -> Option<Vec<f32>> {
if !playing || self.target_sample_rate != Some(sample_rate) {
return Some(vec![0.0; duration.as_usize()]);
}
// let chunk_samples = duration.as_usize();
let mut output = vec![0.0; duration.as_usize()];
let mut remaining_samples = duration;
let mut current_time = timestamp;
// Find the first buffer that overlaps with the requested time
let mut buffer_index = match self.buffers.binary_search_by(|b| {
b.start_time.partial_cmp(&current_time).unwrap()
}) {
Ok(i) => i,
Err(i) if i > 0 => i - 1, // Check previous buffer if timestamp is between buffers
_ => 0,
};
while remaining_samples.as_usize() > 0 && buffer_index < self.buffers.len() {
let buffer = &self.buffers[buffer_index];
// Calculate overlap with current buffer
let buffer_start = buffer.start_time;
let buffer_end = buffer_start + buffer.duration();
if current_time >= buffer_end {
// Move to next buffer
buffer_index += 1;
continue;
}
// Calculate how many samples we can take from this buffer
let buffer_offset = ((current_time - buffer_start).as_seconds() * sample_rate as f64) as usize;
let available_samples = SampleCount::new(buffer.resampled_data.len().saturating_sub(buffer_offset));
let samples_to_take = remaining_samples.min(available_samples);
if samples_to_take == 0 {
// No more samples in this buffer
buffer_index += 1;
continue;
}
// Copy samples from buffer to output
let output_offset = duration - remaining_samples;
output[output_offset.as_usize()..(output_offset + samples_to_take).as_usize()]
.copy_from_slice(&buffer.resampled_data[buffer_offset..buffer_offset + samples_to_take.as_usize()]);
// Update state
remaining_samples -= samples_to_take;
current_time += samples_to_take.to_duration(sample_rate);
}
Some(output)
}
}
fn resample(input: &[f32], input_rate: u32, output_rate: u32) -> Vec<f32> {
if input_rate == output_rate {
return input.to_vec();
}
let input_rate = input_rate.try_into().unwrap();
let output_rate = output_rate.try_into().unwrap();
let chunk_size = input.len();
let mut resampler = FftFixedIn::new(
output_rate,
input_rate,
chunk_size,
1, // channel count
2, // fft size
).unwrap();
let output = resampler.process(&[input], None).unwrap();
output[0].clone()
}
pub trait AudioLoader {
fn load_audio(
&self,
track: &mut RecordedAudioTrack,
start_time: Timestamp,
audio_data: &[u8],
) -> Result<(), Box<dyn Error>>;
}
pub struct GenericAudioLoader;
impl AudioLoader for GenericAudioLoader {
fn load_audio(
&self,
track: &mut RecordedAudioTrack,
start_time: Timestamp,
audio_data: &[u8],
) -> Result<(), Box<dyn Error>> {
decode_audio(track, start_time, audio_data)
}
}
fn decode_audio(
track: &mut RecordedAudioTrack,
start_time: Timestamp,
audio_data: &[u8],
) -> Result<(), Box<dyn Error>> {
// Create a media source from the byte slice
let mss = MediaSourceStream::new(
Box::new(Cursor::new(audio_data.to_vec())),
Default::default(),
);
// Use a fresh hint (no extension specified) for format detection
let hint = Hint::new();
// Probe the media source for a supported format
let probed = symphonia::default::get_probe()
.format(&hint, mss, &FormatOptions::default(), &MetadataOptions::default())?;
// Get the format reader
let mut format = probed.format;
// Find the first supported audio track
let default_track = format
.tracks()
.iter()
.find(|t| t.codec_params.codec != symphonia::core::codecs::CODEC_TYPE_NULL)
.ok_or("No supported audio track found")?;
// Create a decoder for the track
let mut decoder = symphonia::default::get_codecs()
.make(&default_track.codec_params, &DecoderOptions::default())?;
// Get the sample rate from the track
let sample_rate = default_track.codec_params.sample_rate.ok_or("Unknown sample rate")?;
let mut decoded_samples = Vec::new();
// Decode loop
loop {
let packet = match format.next_packet() {
Ok(packet) => packet,
Err(_) => break, // End of stream
};
match decoder.decode(&packet)? {
AudioBufferRef::F32(buf) => {
for i in 0..buf.frames() {
for c in 0..buf.spec().channels.count() {
decoded_samples.push(buf.chan(c)[i]);
}
}
}
AudioBufferRef::S16(buf) => {
for i in 0..buf.frames() {
for c in 0..buf.spec().channels.count() {
decoded_samples.push(buf.chan(c)[i] as f32 / 32768.0);
}
}
}
_ => return Err("Unsupported audio format".into()),
}
}
// Add the decoded audio to the track
track.add_buffer(start_time, sample_rate, decoded_samples);
Ok(())
}
#[cfg(feature="wasm")]
#[wasm_bindgen]
pub struct JsTrack {
name: String,
name: String,
}
#[cfg(feature="wasm")]
#[wasm_bindgen]
impl JsTrack {
#[wasm_bindgen(getter)]
pub fn name(&self) -> String {
self.name.clone()
}
#[wasm_bindgen(getter)]
pub fn name(&self) -> String {
self.name.clone()
}
}
#[cfg(feature="wasm")]
impl fmt::Display for JsTrack {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "JsTrack {{ name: {} }}", self.name)
write!(f, "JsTrack {{ name: {} }}", self.name)
}
}
#[cfg(feature="wasm")]
#[wasm_bindgen]
impl JsTrack {
#[wasm_bindgen(js_name = toString)]
pub fn to_string(&self) -> String {
format!("{}", self) // Calls the Display implementation
}
#[wasm_bindgen(js_name = toString)]
pub fn to_string(&self) -> String {
format!("{}", self) // Calls the Display implementation
}
}
#[cfg(feature="wasm")]
@@ -222,7 +501,7 @@ impl CoreInterface {
pub fn resume_audio(&mut self) -> Result<(), JsValue> {
// Call this on user gestures if audio gets suspended
self.cpal_audio_output.resume()
.map_err(|e| JsValue::from_str(&format!("Failed to resume audio: {}", e)))
.map_err(|e| JsValue::from_str(&format!("Failed to resume audio: {}", e)))
}
pub fn add_sine_track(&mut self, frequency: f32) -> Result<(), String> {
if frequency.is_nan() || frequency.is_infinite() || frequency <= 0.0 {
@@ -232,10 +511,10 @@ impl CoreInterface {
let mut track_manager = self.track_manager.lock().unwrap();
let sine_track = SineWaveTrack::new(frequency);
track_manager.add_track(Box::new(sine_track));
Ok(())
}
pub fn get_timestamp(&mut self) -> f64 {
self.cpal_audio_output.get_timestamp().as_seconds()
}
@@ -245,7 +524,7 @@ impl CoreInterface {
tracks
.iter()
.map(|track| JsTrack {
name: track.get_name().to_string(),
name: track.get_name().to_string(),
})
.collect()
}
@@ -261,17 +540,42 @@ impl Log for PlainTextLogger {
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
console::log_1(&format!(
"{} [{}:{}] {}",
record.level(),
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.args()
).into());
#[cfg(target_arch = "wasm32")]
{
// WASM: Log to the JS console
console::log_1(
&format!(
"{} [{}:{}] {}",
record.level(),
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.args()
)
.into(),
);
}
#[cfg(not(target_arch = "wasm32"))]
{
// Native: Log to stderr
let _ = writeln!(
io::stderr(),
"{} [{}:{}] {}",
record.level(),
record.file().unwrap_or("unknown"),
record.line().unwrap_or(0),
record.args()
);
}
}
}
fn flush(&self) {}
fn flush(&self) {
#[cfg(not(target_arch = "wasm32"))]
{
let _ = io::stderr().flush();
}
}
}
pub fn init_plain_text_logger() -> Result<(), SetLoggerError> {
+66
View File
@@ -54,6 +54,14 @@ impl Timestamp {
pub fn set(&mut self, other: Timestamp) {
self.0 = other.as_seconds();
}
pub fn max(&self, other: Timestamp) -> Timestamp {
Timestamp(self.0.max(other.0))
}
pub fn min(&self, other: Timestamp) -> Timestamp {
Timestamp(self.0.min(other.0))
}
}
impl Duration {
@@ -62,6 +70,11 @@ impl Duration {
Duration(seconds)
}
/// Create a new duration from seconds. (dummy method)
pub fn from_seconds(seconds: f64) -> Self {
Duration(seconds)
}
/// Create a new duration from milliseconds.
pub fn from_millis(milliseconds: u64) -> Self {
Duration(milliseconds as f64 / 1000.0)
@@ -117,6 +130,24 @@ impl SampleCount {
pub fn as_usize(&self) -> usize {
self.0
}
pub fn to_duration(&self, sample_rate: u32) -> Duration {
Duration((self.0 as f64) / (sample_rate as f64))
}
pub fn max(&self, other: SampleCount) -> SampleCount {
SampleCount(self.0.max(other.0))
}
pub fn min(&self, other: SampleCount) -> SampleCount {
SampleCount(self.0.min(other.0))
}
}
impl PartialEq<usize> for SampleCount{
fn eq(&self, other: &usize) -> bool {
self.0 == *other
}
}
// Overloading operators for more natural usage
@@ -138,6 +169,14 @@ impl Sub<Duration> for Timestamp {
}
}
impl Sub<Timestamp> for Timestamp {
type Output = Duration;
fn sub(self, other: Timestamp) -> Duration {
self.subtract_timestamp(other)
}
}
impl AddAssign<Duration> for Timestamp {
fn add_assign(&mut self, duration: Duration) {
self.0 += duration.0;
@@ -150,6 +189,33 @@ impl SubAssign<Duration> for Timestamp {
}
}
impl Add for SampleCount {
type Output = SampleCount;
fn add(self, other: SampleCount) -> SampleCount {
SampleCount(self.0 + other.0)
}
}
impl Sub for SampleCount {
type Output = SampleCount;
fn sub(self, other: SampleCount) -> SampleCount {
SampleCount(self.0 - other.0)
}
}
impl AddAssign<SampleCount> for SampleCount {
fn add_assign(&mut self, other: SampleCount) {
self.0 += other.0;
}
}
impl SubAssign<SampleCount> for SampleCount {
fn sub_assign(&mut self, other: SampleCount) {
self.0 -= other.0;
}
}
/// Represents a video frame.
#[derive(Debug, Clone)]
pub struct Frame {