SpaceManiac / opus-rs

Safe Rust bindings for libopus
Apache License 2.0
70 stars 64 forks source link

Best practice for real-time usage #19

Open morajabi opened 2 years ago

morajabi commented 2 years ago

It'd be cool to have a simple tip or snippet in the readme for how to pre-allocate enough memory and which methods to use for the best performance in a Rust loop.

e.g. what I have for decode:

// pre-allocate
 let mut decoder_output = Vec::<f32>::with_capacity(sample_rate / 2)      

 // ... inside loop
 let sample_count = decoder
          .decode_float(&input_sample.data[..], &mut decoder_output, false)
          .unwrap();
// pass the decoder_output.as_slice() to the resampler, and then to the player loop

and what I have for encode:

// no pre-allocate, will it be beneficial?
// ... inside the loop
let output = encoder
  .encode_vec_float(&data, max_buffer_2x)
  .expect("Failed to encode");

let bytes = Bytes::from(output);
// pass the bytes to a channel to be sent over the network

but as a new Rust dev, I'm not sure if it's the most efficient way for a realtime usecase.