audioview/src/agents/audio_agent.rs

116 lines
3.5 KiB
Rust
Raw Normal View History

2020-09-05 12:33:06 +00:00
use js_sys::Uint8Array;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::JsFuture;
use web_sys::{AudioContext, File};
2020-09-04 15:25:16 +00:00
use yew::services::reader::{FileChunk, ReaderTask};
use yew::services::{ConsoleService, ReaderService};
use yew::worker::*;
2020-09-05 12:33:06 +00:00
use yewtil::future::LinkFuture;
2020-09-04 15:25:16 +00:00
2020-09-05 12:36:22 +00:00
const FILE_LOAD_CHUNK_SIZE: usize = 4096;
2020-09-04 15:25:16 +00:00
pub struct AudioAgent {
link: AgentLink<Self>,
reader_service: ReaderService,
reader_task: Option<ReaderTask>,
2020-09-05 12:33:06 +00:00
audio_context: AudioContext,
bytes_buffer: Vec<u8>,
2020-09-04 15:25:16 +00:00
}
pub enum Request {
LoadSamplesFromFile(File),
}
pub enum Msg {
FileProgress(Option<FileChunk>),
2020-09-05 12:33:06 +00:00
AudioDecoded(JsValue),
AudioDecodingFailed(JsValue),
}
impl From<Result<JsValue, JsValue>> for Msg {
fn from(item: Result<JsValue, JsValue>) -> Self {
match item {
Ok(samples) => Msg::AudioDecoded(samples),
Err(e) => Msg::AudioDecodingFailed(e),
}
}
2020-09-04 15:25:16 +00:00
}
impl Agent for AudioAgent {
type Reach = Context<Self>;
type Message = Msg;
type Input = Request;
type Output = ();
fn create(link: AgentLink<Self>) -> Self {
2020-09-05 12:33:06 +00:00
// TODO: where should the AudioContext be initialized and stored?
2020-09-04 15:25:16 +00:00
Self {
link,
reader_service: ReaderService::new(),
reader_task: None,
2020-09-05 12:33:06 +00:00
audio_context: AudioContext::new().unwrap(),
bytes_buffer: vec![],
2020-09-04 15:25:16 +00:00
}
}
fn update(&mut self, msg: Self::Message) {
match msg {
2020-09-05 12:33:06 +00:00
Msg::FileProgress(Some(FileChunk::DataChunk { data, progress })) => {
2020-09-05 12:36:22 +00:00
self.handle_file_progress(data, progress)
2020-09-05 12:33:06 +00:00
}
Msg::FileProgress(Some(FileChunk::Finished)) => {
if let Err(e) = self.handle_file_loaded() {
2020-09-04 15:25:16 +00:00
ConsoleService::error(&e);
}
}
2020-09-05 12:33:06 +00:00
Msg::AudioDecoded(samples) => {
2020-09-05 22:02:19 +00:00
let audio_buffer = web_sys::AudioBuffer::from(samples);
let data = audio_buffer.get_channel_data(0).unwrap(); // TODO: error handling
let vec: Vec<f32> = data.to_vec();
ConsoleService::log(&format!("Success decoding: {:?}", vec));
2020-09-05 12:33:06 +00:00
}
Msg::AudioDecodingFailed(err) => {
ConsoleService::error(&format!("Error decoding: {:?}", err));
}
_ => (),
2020-09-04 15:25:16 +00:00
};
}
fn handle_input(&mut self, input: Self::Input, _: HandlerId) {
match input {
Request::LoadSamplesFromFile(file) => self.load_samples_from_file(file),
};
}
}
impl AudioAgent {
fn load_samples_from_file(&mut self, file: File) -> Result<(), String> {
2020-09-05 12:33:06 +00:00
self.bytes_buffer = Vec::with_capacity(file.size() as usize);
2020-09-04 15:25:16 +00:00
let cb = self.link.callback(Msg::FileProgress);
let task = self
.reader_service
2020-09-05 12:36:22 +00:00
.read_file_by_chunks(file, cb, FILE_LOAD_CHUNK_SIZE)
2020-09-04 15:25:16 +00:00
.map_err(|e| e.to_string())?;
self.reader_task = Some(task);
Ok(())
}
2020-09-05 12:36:22 +00:00
fn handle_file_progress(&mut self, mut data: Vec<u8>, _progress: f32) {
2020-09-05 12:33:06 +00:00
self.bytes_buffer.append(&mut data);
}
fn handle_file_loaded(&self) -> Result<(), String> {
let audio_data = Uint8Array::from(&self.bytes_buffer[..]);
match self.audio_context.decode_audio_data(&audio_data.buffer()) {
Ok(promise) => {
self.link.send_future(JsFuture::from(promise));
Ok(())
2020-09-04 15:25:16 +00:00
}
2020-09-05 12:33:06 +00:00
Err(e) => Err(format!("Error from decode_audio_data: {:?}", e)),
2020-09-04 15:25:16 +00:00
}
}
}