More work on Rust
This commit is contained in:
+107
-84
@@ -1,25 +1,93 @@
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
use cpal::{SampleFormat, SampleRate, Stream, StreamConfig};
|
||||
use cpal::{BufferSize, SupportedBufferSize};
|
||||
use cpal::{Sample, SampleFormat, StreamConfig, SupportedBufferSize, SampleRate, BufferSize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use crate::AudioOutput;
|
||||
use crate::{TrackManager, Timestamp, Duration, SampleCount, AudioOutput, PlaybackState};
|
||||
|
||||
|
||||
// #[cfg(feature = "wasm")]
|
||||
// use wasm_bindgen::prelude::*;
|
||||
|
||||
// #[cfg(feature="wasm")]
|
||||
// #[wasm_bindgen]
|
||||
pub struct CpalAudioOutput {
|
||||
stream: Option<Stream>,
|
||||
buffer: Arc<Mutex<Vec<f32>>>, // Shared buffer for audio chunks
|
||||
track_manager: Option<Arc<Mutex<TrackManager>>>,
|
||||
_stream: Option<cpal::Stream>,
|
||||
playback_state: PlaybackState,
|
||||
timestamp: Arc<Mutex<Timestamp>>,
|
||||
chunk_size: usize,
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
}
|
||||
|
||||
// #[cfg(feature="wasm")]
|
||||
// #[wasm_bindgen]
|
||||
impl CpalAudioOutput {
|
||||
pub fn new(sample_rate: u32, channels: u16) -> Self {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
stream: None,
|
||||
buffer: Arc::new(Mutex::new(Vec::new())),
|
||||
sample_rate,
|
||||
channels,
|
||||
track_manager: None,
|
||||
_stream: None,
|
||||
playback_state: PlaybackState::Stopped,
|
||||
timestamp: Arc::new(Mutex::new(Timestamp::from_seconds(0.0))),
|
||||
chunk_size: 0,
|
||||
sample_rate: 44100, // Default sample rate, updated later
|
||||
}
|
||||
}
|
||||
|
||||
fn build_stream<T>(
|
||||
&mut self,
|
||||
device: &cpal::Device,
|
||||
config: cpal::SupportedStreamConfig,
|
||||
) -> Result<cpal::Stream, anyhow::Error>
|
||||
where
|
||||
T: Sample + From<f32> + cpal::SizedSample,
|
||||
{
|
||||
let supported_config = config.config();
|
||||
self.sample_rate = supported_config.sample_rate.0;
|
||||
let num_channels = supported_config.channels as usize; // Get channel count
|
||||
|
||||
let track_manager = self.track_manager.clone();
|
||||
let playback_state = self.playback_state.clone();
|
||||
let timestamp = self.timestamp.clone();
|
||||
let sample_rate = self.sample_rate;
|
||||
|
||||
let err_fn = |err| eprintln!("Audio stream error: {:?}", err);
|
||||
|
||||
let stream = device.build_output_stream(
|
||||
&supported_config,
|
||||
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
|
||||
if let Some(track_manager) = &track_manager {
|
||||
let num_frames = data.len() / num_channels; // Stereo: divide by 2
|
||||
let sample_count = SampleCount::new(num_frames);
|
||||
let chunk_duration = Duration::new(num_frames as f64 / sample_rate as f64);
|
||||
|
||||
let mut track_manager = track_manager.lock().unwrap();
|
||||
let playing = matches!(playback_state, PlaybackState::Playing);
|
||||
|
||||
let mut timestamp_guard = timestamp.lock().unwrap();
|
||||
let timestamp = &mut *timestamp_guard;
|
||||
|
||||
let chunk = track_manager.update_audio(
|
||||
timestamp.clone(),
|
||||
playing,
|
||||
sample_count,
|
||||
sample_rate,
|
||||
);
|
||||
|
||||
// Write samples (interleaved stereo)
|
||||
for (i, frame) in chunk.iter().enumerate() {
|
||||
let sample = T::from(*frame);
|
||||
data[i * num_channels] = sample; // Left channel
|
||||
data[i * num_channels + 1] = sample; // Right channel (or process separately)
|
||||
}
|
||||
|
||||
*timestamp_guard += chunk_duration;
|
||||
}
|
||||
},
|
||||
err_fn,
|
||||
None,
|
||||
)?;
|
||||
|
||||
Ok(stream)
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioOutput for CpalAudioOutput {
|
||||
@@ -27,79 +95,34 @@ impl AudioOutput for CpalAudioOutput {
|
||||
let host = cpal::default_host();
|
||||
let device = host
|
||||
.default_output_device()
|
||||
.ok_or("No output device available")?;
|
||||
let supported_config = device
|
||||
.default_output_config().unwrap();
|
||||
// .with_sample_rate(SampleRate(self.sample_rate));
|
||||
let config = StreamConfig {
|
||||
channels: self.channels,
|
||||
sample_rate: SampleRate(self.sample_rate),
|
||||
buffer_size: match supported_config.buffer_size() {
|
||||
SupportedBufferSize::Range { min, max: _ } => BufferSize::Fixed(*min),
|
||||
SupportedBufferSize::Unknown => BufferSize::Default,
|
||||
},
|
||||
};
|
||||
|
||||
let buffer = self.buffer.clone();
|
||||
let sample_format = supported_config.sample_format();
|
||||
|
||||
let stream = match sample_format {
|
||||
SampleFormat::F32 => device.build_output_stream(
|
||||
&config,
|
||||
move |data: &mut [f32], _| {
|
||||
let mut buffer = buffer.lock().unwrap();
|
||||
for (out_sample, buffer_sample) in data.iter_mut().zip(buffer.iter()) {
|
||||
*out_sample = *buffer_sample;
|
||||
}
|
||||
buffer.clear(); // Clear buffer after playback
|
||||
},
|
||||
move |err| {
|
||||
eprintln!("Audio stream error: {:?}", err);
|
||||
},
|
||||
),
|
||||
SampleFormat::I16 => device.build_output_stream(
|
||||
&config,
|
||||
move |data: &mut [i16], _| {
|
||||
let mut buffer = buffer.lock().unwrap();
|
||||
for (out_sample, buffer_sample) in data.iter_mut().zip(buffer.iter()) {
|
||||
*out_sample = (*buffer_sample * i16::MAX as f32) as i16;
|
||||
}
|
||||
buffer.clear();
|
||||
},
|
||||
move |err| {
|
||||
eprintln!("Audio stream error: {:?}", err);
|
||||
},
|
||||
),
|
||||
SampleFormat::U16 => device.build_output_stream(
|
||||
&config,
|
||||
move |data: &mut [u16], _| {
|
||||
let mut buffer = buffer.lock().unwrap();
|
||||
for (out_sample, buffer_sample) in data.iter_mut().zip(buffer.iter()) {
|
||||
*out_sample = ((*buffer_sample + 1.0) * 0.5 * u16::MAX as f32) as u16;
|
||||
}
|
||||
buffer.clear();
|
||||
},
|
||||
move |err| {
|
||||
eprintln!("Audio stream error: {:?}", err);
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
// If the stream creation failed, return the error
|
||||
let stream = stream.map_err(|e| {
|
||||
format!(
|
||||
"Failed to build output stream for sample format {:?}: {:?}",
|
||||
sample_format, e
|
||||
)
|
||||
})?;
|
||||
|
||||
stream.play()?;
|
||||
self.stream = Some(stream);
|
||||
.ok_or_else(|| "No output device available")?;
|
||||
let supported_config = device.default_output_config()?;
|
||||
self._stream = Some(self.build_stream::<f32>(&device, supported_config)?);
|
||||
if let Some(stream) = self._stream.as_ref() {
|
||||
stream.play().unwrap();
|
||||
} else {
|
||||
eprintln!("Stream is not initialized!");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn play_chunk(&mut self, chunk: Vec<f32>) {
|
||||
let mut buffer = self.buffer.lock().unwrap();
|
||||
buffer.extend(chunk);
|
||||
|
||||
fn play(&mut self, start_timestamp: Timestamp) {
|
||||
self.timestamp.lock().unwrap().set(start_timestamp);
|
||||
self.playback_state = PlaybackState::Playing;
|
||||
}
|
||||
}
|
||||
|
||||
fn stop(&mut self) {
|
||||
self.playback_state = PlaybackState::Stopped;
|
||||
}
|
||||
|
||||
fn register_track_manager(&mut self, track_manager: Arc<Mutex<TrackManager>>) {
|
||||
self.track_manager = Some(track_manager);
|
||||
}
|
||||
|
||||
fn get_timestamp(&mut self) -> Timestamp {
|
||||
*self.timestamp.lock().unwrap()
|
||||
}
|
||||
fn set_chunk_size(&mut self, chunk_size: usize) {
|
||||
self.chunk_size = chunk_size
|
||||
}
|
||||
}
|
||||
|
||||
+183
-32
@@ -1,20 +1,30 @@
|
||||
mod time;
|
||||
use time::{Timestamp, Duration, Frame};
|
||||
use time::{Timestamp, Duration, Frame, SampleCount};
|
||||
mod audio;
|
||||
use audio::{CpalAudioOutput};
|
||||
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
mod wasm_imports {
|
||||
pub use wasm_bindgen::prelude::*;
|
||||
pub use web_sys::console;
|
||||
use wasm_logger;
|
||||
}
|
||||
#[cfg(feature = "wasm")]
|
||||
use wasm_imports::*;
|
||||
|
||||
pub trait AudioTrack {
|
||||
|
||||
pub trait AudioTrack: Send {
|
||||
/// Render a chunk of audio for the given timestamp and duration.
|
||||
fn render_chunk(&self, timestamp: Timestamp, duration: Duration) -> Vec<f32>;
|
||||
fn render_chunk(&mut self, timestamp: Timestamp, duration: SampleCount) -> Vec<f32>;
|
||||
|
||||
/// Get the sample rate of the audio track.
|
||||
fn sample_rate(&self) -> u32;
|
||||
}
|
||||
|
||||
pub trait VideoTrack {
|
||||
pub trait VideoTrack: Send {
|
||||
/// Render a frame for the given timestamp.
|
||||
fn render_frame(&self, timestamp: Timestamp) -> Frame;
|
||||
|
||||
@@ -25,8 +35,10 @@ pub trait VideoTrack {
|
||||
pub struct TrackManager {
|
||||
audio_tracks: Vec<Box<dyn AudioTrack>>,
|
||||
video_tracks: Vec<Box<dyn VideoTrack>>,
|
||||
sample_rate: u32,
|
||||
frame_duration: Duration, // Duration of each frame in seconds (e.g., 1/60 for 60 FPS)
|
||||
// sample_rate: u32,
|
||||
// frame_duration: Duration, // Duration of each frame in seconds (e.g., 1/60 for 60 FPS)
|
||||
timestamp: Timestamp,
|
||||
playback_state: PlaybackState,
|
||||
}
|
||||
|
||||
impl TrackManager {
|
||||
@@ -34,8 +46,10 @@ impl TrackManager {
|
||||
Self {
|
||||
audio_tracks: Vec::new(),
|
||||
video_tracks: Vec::new(),
|
||||
sample_rate,
|
||||
frame_duration: Duration::new(frame_duration),
|
||||
// sample_rate,
|
||||
// frame_duration: Duration::new(frame_duration),
|
||||
playback_state: PlaybackState::Stopped,
|
||||
timestamp: Timestamp::from_seconds(0.0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,47 +60,180 @@ impl TrackManager {
|
||||
pub fn add_video_track(&mut self, track: Box<dyn VideoTrack>) {
|
||||
self.video_tracks.push(track);
|
||||
}
|
||||
|
||||
pub fn play(&mut self, start_timestamp: Timestamp) {
|
||||
self.timestamp = start_timestamp;
|
||||
self.playback_state = PlaybackState::Playing;
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
self.playback_state = PlaybackState::Stopped;
|
||||
}
|
||||
|
||||
pub fn play(&mut self, timestamp: Timestamp, audio_output: &mut dyn AudioOutput, video_output: &mut dyn FrameTarget) {
|
||||
let mut timestamp = timestamp.clone();
|
||||
// pub fn play(&mut self, timestamp: Timestamp, audio_output: &mut dyn AudioOutput, video_output: &mut dyn FrameTarget) {
|
||||
// let mut timestamp = timestamp.clone();
|
||||
|
||||
// Main playback loop
|
||||
loop {
|
||||
// Render and play audio chunks
|
||||
let mut audio_mix: Vec<f32> = vec![0.0; self.frame_duration.to_samples(self.sample_rate) as usize];
|
||||
for track in &mut self.audio_tracks {
|
||||
let chunk = track.render_chunk(timestamp, self.frame_duration);
|
||||
for (i, sample) in chunk.iter().enumerate() {
|
||||
audio_mix[i] += sample; // Simple mixing (sum of samples)
|
||||
}
|
||||
}
|
||||
audio_output.play_chunk(audio_mix);
|
||||
// // Main playback loop
|
||||
// loop {
|
||||
// // Render and play audio chunks
|
||||
// let mut audio_mix: Vec<f32> = vec![0.0; self.frame_duration.to_samples(self.sample_rate) as usize];
|
||||
// for track in &mut self.audio_tracks {
|
||||
// let chunk = track.render_chunk(timestamp, self.frame_duration);
|
||||
// for (i, sample) in chunk.iter().enumerate() {
|
||||
// audio_mix[i] += sample; // Simple mixing (sum of samples)
|
||||
// }
|
||||
// }
|
||||
// audio_output.play_chunk(audio_mix);
|
||||
|
||||
// Render video frames
|
||||
for track in &self.video_tracks {
|
||||
let track_frame = track.render_frame(timestamp);
|
||||
}
|
||||
// // Render video frames
|
||||
// for track in &self.video_tracks {
|
||||
// let track_frame = track.render_frame(timestamp);
|
||||
// }
|
||||
|
||||
// Update timestamp
|
||||
timestamp += self.frame_duration;
|
||||
// // Update timestamp
|
||||
// timestamp += self.frame_duration;
|
||||
|
||||
// Break condition (e.g., end of tracks)
|
||||
if self.audio_tracks.iter().all(|t| t.render_chunk(timestamp, self.frame_duration).is_empty()) {
|
||||
break;
|
||||
// // Break condition (e.g., end of tracks)
|
||||
// if self.audio_tracks.iter().all(|t| t.render_chunk(timestamp, self.frame_duration).is_empty()) {
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
pub fn update_audio(&mut self, timestamp: Timestamp, playing: bool, chunk_size: SampleCount, sample_rate: u32) -> Vec<f32> {
|
||||
let mut mixed_audio = vec![0.0; chunk_size.as_usize()];
|
||||
|
||||
// TODO: render video
|
||||
for track in &mut self.audio_tracks {
|
||||
let track_audio = track.render_chunk(timestamp, chunk_size);
|
||||
for (i, sample) in track_audio.iter().enumerate() {
|
||||
mixed_audio[i] += *sample; // Simple mixing, add samples together
|
||||
}
|
||||
}
|
||||
|
||||
mixed_audio
|
||||
}
|
||||
}
|
||||
|
||||
pub trait AudioOutput {
|
||||
fn start(&mut self) -> Result<(), Box<dyn std::error::Error>>;
|
||||
fn play_chunk(&mut self, chunk: Vec<f32>);
|
||||
fn play(&mut self, start_timestamp: Timestamp);
|
||||
fn stop(&mut self);
|
||||
fn register_track_manager(&mut self, track_manager: Arc<Mutex<TrackManager>>);
|
||||
fn get_timestamp(&mut self) -> Timestamp;
|
||||
fn set_chunk_size(&mut self, chunk_size: usize);
|
||||
}
|
||||
|
||||
pub trait FrameTarget {
|
||||
fn draw(&mut self, frame: &[u8], width: u32, height: u32);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
enum PlaybackState {
|
||||
Playing,
|
||||
Stopped,
|
||||
}
|
||||
|
||||
pub struct SineWaveTrack {
|
||||
frequency: f32,
|
||||
phase: f32,
|
||||
sample_rate: u32,
|
||||
}
|
||||
|
||||
impl SineWaveTrack {
|
||||
pub fn new(frequency: f32, sample_rate: u32) -> Self {
|
||||
Self {
|
||||
frequency,
|
||||
phase: 0.0,
|
||||
sample_rate,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioTrack for SineWaveTrack {
|
||||
fn render_chunk(&mut self, timestamp: Timestamp, chunk_size: SampleCount) -> Vec<f32> {
|
||||
let mut chunk = Vec::with_capacity(chunk_size.as_usize());
|
||||
let phase_increment = (2.0 * std::f32::consts::PI * self.frequency) / self.sample_rate as f32;
|
||||
|
||||
for _ in 0..chunk_size.as_usize() {
|
||||
chunk.push((self.phase).sin());
|
||||
self.phase += phase_increment;
|
||||
if self.phase > 2.0 * std::f32::consts::PI {
|
||||
self.phase -= 2.0 * std::f32::consts::PI;
|
||||
}
|
||||
}
|
||||
|
||||
chunk
|
||||
}
|
||||
fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(feature="wasm")]
|
||||
#[wasm_bindgen]
|
||||
pub struct CoreInterface {
|
||||
#[wasm_bindgen(skip)]
|
||||
track_manager: Arc<Mutex<TrackManager>>,
|
||||
#[wasm_bindgen(skip)]
|
||||
cpal_audio_output: Box<dyn AudioOutput>,
|
||||
}
|
||||
|
||||
#[cfg(feature="wasm")]
|
||||
#[wasm_bindgen]
|
||||
impl CoreInterface {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(sample_rate: u32, frame_duration: f64) -> Self {
|
||||
Self {
|
||||
track_manager: Arc::new(Mutex::new(TrackManager::new(sample_rate, frame_duration))),
|
||||
cpal_audio_output: Box::new(CpalAudioOutput::new())
|
||||
}
|
||||
}
|
||||
pub fn init(&mut self) {
|
||||
println!("Init CoreInterface");
|
||||
let track_manager_clone = self.track_manager.clone();
|
||||
self.cpal_audio_output.register_track_manager(track_manager_clone);
|
||||
self.cpal_audio_output.start();
|
||||
}
|
||||
pub fn play(&mut self, timestamp: f64) {
|
||||
// Lock the Mutex to get access to TrackManager
|
||||
let mut track_manager = self.track_manager.lock().unwrap();
|
||||
track_manager.play(Timestamp::new(timestamp));
|
||||
}
|
||||
pub fn get_timestamp(&mut self) -> f64 {
|
||||
self.cpal_audio_output.get_timestamp().as_seconds()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct PlainTextLogger;
|
||||
|
||||
impl Log for PlainTextLogger {
|
||||
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||
metadata.level() <= Level::Info
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
pub fn init_plain_text_logger() -> Result<(), SetLoggerError> {
|
||||
log::set_boxed_logger(Box::new(PlainTextLogger))?;
|
||||
log::set_max_level(LevelFilter::Info);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -106,6 +253,10 @@ pub fn main_js() -> Result<(), JsValue> {
|
||||
// It's disabled in release mode so it doesn't bloat up the file size.
|
||||
#[cfg(debug_assertions)]
|
||||
console_error_panic_hook::set_once();
|
||||
init_plain_text_logger().expect("Failed to initialize plain text logger");
|
||||
|
||||
|
||||
log::info!("Logger initialized!");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -6,12 +6,21 @@ pub struct Timestamp(f64);
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Duration(f64);
|
||||
|
||||
/// A strongly-typed representation of a number of samples.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SampleCount(usize);
|
||||
|
||||
impl Timestamp {
|
||||
/// Create a new timestamp in seconds.
|
||||
pub fn new(seconds: f64) -> Self {
|
||||
Timestamp(seconds)
|
||||
}
|
||||
|
||||
/// Create a new timestamp from seconds. (dummy method)
|
||||
pub fn from_seconds(seconds: f64) -> Self {
|
||||
Timestamp(seconds)
|
||||
}
|
||||
|
||||
/// Create a new timestamp from milliseconds.
|
||||
pub fn from_millis(milliseconds: u64) -> Self {
|
||||
Timestamp(milliseconds as f64 / 1000.0)
|
||||
@@ -41,6 +50,10 @@ impl Timestamp {
|
||||
pub fn subtract_timestamp(&self, other: Timestamp) -> Duration {
|
||||
Duration(self.0 - other.0)
|
||||
}
|
||||
|
||||
pub fn set(&mut self, other: Timestamp) {
|
||||
self.0 = other.as_seconds();
|
||||
}
|
||||
}
|
||||
|
||||
impl Duration {
|
||||
@@ -79,6 +92,10 @@ impl Duration {
|
||||
(self.0 * sample_rate as f64).round() as u64
|
||||
}
|
||||
|
||||
pub fn to_std(&self) -> std::time::Duration {
|
||||
std::time::Duration::from_nanos((self.0/1_000_000_000.0).round() as u64)
|
||||
}
|
||||
|
||||
/// Add two durations together.
|
||||
pub fn add(&self, other: Duration) -> Duration {
|
||||
Duration(self.0 + other.0)
|
||||
@@ -90,6 +107,18 @@ impl Duration {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl SampleCount {
|
||||
/// Create a new count of samples.
|
||||
pub fn new(samples: usize) -> Self {
|
||||
SampleCount(samples)
|
||||
}
|
||||
|
||||
pub fn as_usize(&self) -> usize {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
// Overloading operators for more natural usage
|
||||
use std::ops::{Add, Sub, AddAssign, SubAssign};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user