Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

fix streaming and memory issue (#371)

LuckyIYI2e9412558915
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/decode.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/decode.rs
index 9e3891f0f..c5b448575 100644
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/decode.rs
+++ b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/decode.rs
@@ -22,20 +22,20 @@ impl StructuredAudioCodecGraph {
let data_type = input.data_type();
let residual = input.clone();
- let x = snake1d_enqueue(
+ let mut x = snake1d_enqueue(
encoder,
input,
- ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_snake1"),
+ ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_snake1")?,
&unit.snake1_alpha,
batch_size,
channels,
seq_len,
kernels,
)?;
- let x = causal_conv1d_grouped_enqueue(
+ x = causal_conv1d_grouped_enqueue(
encoder,
&x,
- ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_conv1"),
+ ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_conv1")?,
&unit.conv1,
SequenceLayout::Ncs,
lengths,
@@ -44,10 +44,10 @@ impl StructuredAudioCodecGraph {
seq_len,
kernels,
)?;
- let x = snake1d_enqueue(
+ x = snake1d_enqueue(
encoder,
&x,
- ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_snake2"),
+ ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_snake2")?,
&unit.snake2_alpha,
batch_size,
channels,
@@ -58,7 +58,7 @@ impl StructuredAudioCodecGraph {
encoder,
&x,
&residual,
- ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_conv2"),
+ ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "res_conv2")?,
&unit.conv2,
lengths,
lengths_array,
@@ -110,6 +110,31 @@ impl StructuredAudioCodecGraph {
})?;
let ws = &resources.decode_workspace;
+ let vocoder_graph = self.vocoder_graph(resources)?;
+ let kernels = resources.kernels(self.vocoder_data_type)?;
+
+ let worst_case_bytes = {
+ let scratch_bytes = |channels: usize, frame_count: usize| -> usize {
+ size_for_shape(&[batch_size, channels, frame_count], self.vocoder_data_type)
+ };
+ let mut max_bytes = 0usize;
+ let mut current_frames = frames;
+ for (trans_conv, convnext) in vocoder_graph.upsample_blocks.iter() {
+ current_frames = current_frames.saturating_mul(trans_conv.stride);
+ max_bytes = max_bytes.max(scratch_bytes(trans_conv.cout, current_frames));
+ max_bytes = max_bytes.max(scratch_bytes(convnext.pwconv1.cout, current_frames));
+ }
+ let mut current_channels = vocoder_graph.first_conv.cout;
+ max_bytes = max_bytes.max(scratch_bytes(current_channels, current_frames));
+ for block in vocoder_graph.decoder_blocks.iter() {
+ max_bytes = max_bytes.max(scratch_bytes(current_channels, current_frames));
+ current_frames = current_frames.saturating_mul(block.trans_conv.stride);
+ current_channels = block.trans_conv.cout;
+ max_bytes = max_bytes.max(scratch_bytes(current_channels, current_frames));
+ }
+ max_bytes
+ };
+ ws.prime_for(context.as_ref(), worst_case_bytes)?;
let mut x;
let mut x_layout = SequenceLayout::Nsc;
@@ -134,8 +159,6 @@ impl StructuredAudioCodecGraph {
frames,
)?;
- let vocoder_graph = self.vocoder_graph(resources)?;
- let kernels = resources.kernels(self.vocoder_data_type)?;
let mut current_channels = self.input_dim;
let mut current_frames = frames;
let mut next_lengths_i32 = vec![0_i32; lengths_i32.len()];
@@ -161,7 +184,7 @@ impl StructuredAudioCodecGraph {
x = causal_conv_transpose1d_causal_pad_enqueue(
&mut encoder,
&x,
- ws.next_scratch(&context, &[batch_size, trans_conv.cout, next_frames], data_type, "up_tconv"),
+ ws.next_scratch(&context, &[batch_size, trans_conv.cout, next_frames], data_type, "up_tconv")?,
trans_conv,
&next_lengths_i32,
batch_size,
@@ -219,7 +242,7 @@ impl StructuredAudioCodecGraph {
&[batch_size, vocoder_graph.first_conv.cout, current_frames],
data_type,
"dec_first_conv",
- ),
+ )?,
&vocoder_graph.first_conv,
x_layout,
&lengths_i32,
@@ -240,7 +263,7 @@ impl StructuredAudioCodecGraph {
x = snake1d_enqueue(
&mut encoder,
&x,
- ws.next_scratch(&context, &[batch_size, current_channels, current_frames], data_type, "dec_snake"),
+ ws.next_scratch(&context, &[batch_size, current_channels, current_frames], data_type, "dec_snake")?,
&block.snake_alpha,
batch_size,
current_channels,
@@ -257,7 +280,7 @@ impl StructuredAudioCodecGraph {
x = causal_conv_transpose1d_causal_pad_enqueue(
&mut encoder,
&x,
- ws.next_scratch(&context, &[batch_size, block.trans_conv.cout, next_frames], data_type, "dec_tconv"),
+ ws.next_scratch(&context, &[batch_size, block.trans_conv.cout, next_frames], data_type, "dec_tconv")?,
&block.trans_conv,
&next_lengths_i32,
batch_size,
@@ -314,7 +337,7 @@ impl StructuredAudioCodecGraph {
x = snake1d_enqueue(
&mut encoder,
&x,
- ws.next_scratch(&context, &[batch_size, current_channels, current_frames], data_type, "final_snake"),
+ ws.next_scratch(&context, &[batch_size, current_channels, current_frames], data_type, "final_snake")?,
&vocoder_graph.final_snake_alpha,
batch_size,
current_channels,
@@ -329,7 +352,7 @@ impl StructuredAudioCodecGraph {
&[batch_size, vocoder_graph.final_conv.cout, current_frames],
data_type,
"final_conv",
- ),
+ )?,
&vocoder_graph.final_conv,
SequenceLayout::Ncs,
&lengths_i32,
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/fishaudio.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/fishaudio.rs
index 65c336e98..27b46d448 100644
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/fishaudio.rs
+++ b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/fishaudio.rs
@@ -45,32 +45,46 @@ pub(super) struct FishAudioQuantizerResources<B: Backend> {
pub(super) residual_out_bias: Array<B>,
}
-/// Ping-pong scratch pool for the sequential decode pipeline.
-///
-/// At any point in the pipeline at most two data buffers are live (the current
-/// input and the current output). `next_scratch` alternates between two slots,
-/// re-using a buffer when its `Rc` strong-count shows it is exclusively owned
-/// by the pool and it is large enough. When a residual connection keeps an
-/// extra reference alive, a fresh buffer is allocated transparently.
+// TODO: once `Array<B>` is bridged to `backends::common::allocator::Allocation`
+// project-wide, replace this whole workspace with `Encoder::allocate_scratch`.
+// That pool already handles auto-expand on demand, range aliasing for
+// non-overlapping lifetimes, and free-on-drop tied to command-buffer
+// completion — i.e. everything this struct reimplements by hand.
pub(super) struct DecodeWorkspace<B: Backend> {
- slots: [RefCell<Option<Rc<RefCell<B::Buffer>>>>; 2],
- toggle: Cell<bool>,
- /// Pair of reusable I32 arrays for per-stage sequence lengths. Cached to
- /// avoid allocating new GPU buffers on every decode call.
+ slots: RefCell<Vec<Rc<RefCell<B::Buffer>>>>,
+ next_search: Cell<usize>,
+ min_buffer_size: Cell<usize>,
lengths_pair: [RefCell<Option<Array<B>>>; 2],
}
impl<B: Backend> DecodeWorkspace<B> {
fn new() -> Self {
Self {
- slots: [RefCell::new(None), RefCell::new(None)],
- toggle: Cell::new(false),
+ slots: RefCell::new(Vec::new()),
+ next_search: Cell::new(0),
+ min_buffer_size: Cell::new(0),
lengths_pair: [RefCell::new(None), RefCell::new(None)],
}
}
- /// Return a reusable I32 array of at least `min_elements` entries for
- /// sequence length data. `index` must be 0 or 1 (ping-pong pair).
+ pub(super) fn prime_for(
+ &self,
+ context: &B::Context,
+ bytes: usize,
+ ) -> AudioResult<()> {
+ if bytes <= self.min_buffer_size.get() {
+ return Ok(());
+ }
+ self.min_buffer_size.set(bytes);
+ let mut slots = self.slots.borrow_mut();
+ for slot in slots.iter_mut() {
+ if Rc::strong_count(slot) == 1 && slot.borrow().length() < bytes {
+ *slot = create_labelled_buffer::<B>(context, bytes, "structured_audio_scratch")?;
+ }
+ }
+ Ok(())
+ }
+
pub(super) fn lengths_array(
&self,
context: &B::Context,
@@ -94,51 +108,63 @@ impl<B: Backend> DecodeWorkspace<B> {
array
}
- /// Return a scratch [`Array`] backed by the next slot in the ping-pong
- /// pair. The underlying GPU buffer is reused when possible.
pub(super) fn next_scratch(
&self,
context: &B::Context,
shape: &[usize],
data_type: DataType,
label: &str,
- ) -> Array<B> {
- let idx = usize::from(self.toggle.get());
- self.toggle.set(!self.toggle.get());
-
- let needed = size_for_shape(shape, data_type);
- let mut slot = self.slots[idx].borrow_mut();
+ ) -> AudioResult<Array<B>> {
+ let needed = size_for_shape(shape, data_type).max(self.min_buffer_size.get());
+ let mut slots = self.slots.borrow_mut();
+ let slot_count = slots.len();
- // Try to reuse the existing buffer if nobody else holds a reference
- // and it is large enough.
- if let Some(buf_rc) = slot.as_ref() {
- if Rc::strong_count(buf_rc) == 1 && buf_rc.borrow().length() >= needed {
- let array = unsafe { Array::from_parts(buf_rc.clone(), 0, shape, data_type) };
- return array;
+ if slot_count > 0 {
+ let start = self.next_search.get() % slot_count;
+ for offset in 0..slot_count {
+ let slot_index = (start + offset) % slot_count;
+ if Rc::strong_count(&slots[slot_index]) == 1 && slots[slot_index].borrow().length() >= needed {
+ self.next_search.set((slot_index + 1) % slot_count);
+ return Ok(unsafe { Array::from_parts(slots[slot_index].clone(), 0, shape, data_type) });
+ }
+ }
+ for offset in 0..slot_count {
+ let slot_index = (start + offset) % slot_count;
+ if Rc::strong_count(&slots[slot_index]) == 1 {
+ slots[slot_index] = create_labelled_buffer::<B>(context, needed, label)?;
+ self.next_search.set((slot_index + 1) % slot_count);
+ return Ok(unsafe { Array::from_parts(slots[slot_index].clone(), 0, shape, data_type) });
+ }
}
}
- // Allocate a fresh buffer and cache it.
- let mut buffer = context.create_buffer(needed).expect("Failed to create scratch buffer");
- buffer.set_label(Some(label));
- let buf_rc = Rc::new(RefCell::new(buffer));
- *slot = Some(buf_rc.clone());
- unsafe { Array::from_parts(buf_rc, 0, shape, data_type) }
+ let buffer_rc = create_labelled_buffer::<B>(context, needed, label)?;
+ slots.push(buffer_rc.clone());
+ self.next_search.set(0);
+ Ok(unsafe { Array::from_parts(buffer_rc, 0, shape, data_type) })
}
- /// Clear both scratch slots, forcing the next call to allocate fresh
- /// buffers. This must be called after submitting a command buffer that
- /// references scratch intermediates so that the in-flight GPU work is
- /// not corrupted by a subsequent decode pass reusing the same buffers.
pub(super) fn reset(&self) {
- *self.slots[0].borrow_mut() = None;
- *self.slots[1].borrow_mut() = None;
- self.toggle.set(false);
+ self.slots.borrow_mut().clear();
+ self.next_search.set(0);
+ self.min_buffer_size.set(0);
*self.lengths_pair[0].borrow_mut() = None;
*self.lengths_pair[1].borrow_mut() = None;
}
}
+fn create_labelled_buffer<B: Backend>(
+ context: &B::Context,
+ bytes: usize,
+ label: &str,
+) -> AudioResult<Rc<RefCell<B::Buffer>>> {
+ let mut buffer = context
+ .create_buffer(bytes)
+ .map_err(|err| AudioError::Runtime(format!("failed to create scratch buffer '{label}': {err}")))?;
+ buffer.set_label(Some(label));
+ Ok(Rc::new(RefCell::new(buffer)))
+}
+
pub(in crate::audio::nanocodec::runtime) struct StructuredAudioRuntimeResources<B: Backend> {
context: Rc<B::Context>,
pub(super) kernels_by_dtype: RefCell<HashMap<u8, Rc<StructuredAudioKernelCache<B>>>>,
diff --git a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
index befc554b2..53f5fdf31 100644
--- a/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
+++ b/crates/backend-uzu/src/audio/nanocodec/runtime/structured/post_module.rs
@@ -19,10 +19,10 @@ impl StructuredAudioCodecGraph {
let data_type = input.data_type();
let residual = input.clone();
- let x = causal_conv1d_grouped_enqueue(
+ let mut x = causal_conv1d_grouped_enqueue(
encoder,
input,
- ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "cnxt_dw"),
+ ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "cnxt_dw")?,
&layer.depthwise_conv,
SequenceLayout::Ncs,
lengths,
@@ -31,10 +31,10 @@ impl StructuredAudioCodecGraph {
seq_len,
kernels,
)?;
- let x = norm_ncs_enqueue(
+ x = norm_ncs_enqueue(
encoder,
&x,
- ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "cnxt_norm"),
+ ws.next_scratch(ctx, &[batch_size, channels, seq_len], data_type, "cnxt_norm")?,
&layer.norm,
lengths,
lengths_array,
@@ -43,10 +43,10 @@ impl StructuredAudioCodecGraph {
seq_len,
kernels,
)?;
- let x = conv1d_pointwise_ncs_enqueue(
+ x = conv1d_pointwise_ncs_enqueue(
encoder,
&x,
- ws.next_scratch(ctx, &[batch_size, layer.pwconv1.cout, seq_len], data_type, "cnxt_pw1"),
+ ws.next_scratch(ctx, &[batch_size, layer.pwconv1.cout, seq_len], data_type, "cnxt_pw1")?,
&layer.pwconv1,
lengths,
lengths_array,
@@ -54,11 +54,11 @@ impl StructuredAudioCodecGraph {
seq_len,
kernels,
)?;
- let x = gelu_enqueue(encoder, &x, ws.next_scratch(ctx, x.shape(), data_type, "cnxt_gelu"), kernels)?;
- let x = conv1d_pointwise_ncs_enqueue(
+ x = gelu_enqueue(encoder, &x, ws.next_scratch(ctx, x.shape(), data_type, "cnxt_gelu")?, kernels)?;
+ x = conv1d_pointwise_ncs_enqueue(
encoder,
&x,
- ws.next_scratch(ctx, &[batch_size, layer.pwconv2.cout, seq_len], data_type, "cnxt_pw2"),
+ ws.next_scratch(ctx, &[batch_size, layer.pwconv2.cout, seq_len], data_type, "cnxt_pw2")?,
&layer.pwconv2,
lengths,
lengths_array,
@@ -66,7 +66,7 @@ impl StructuredAudioCodecGraph {
seq_len,
kernels,
)?;
- add_enqueue(encoder, &x, &residual, ws.next_scratch(ctx, x.shape(), data_type, "cnxt_add"), kernels)
+ add_enqueue(encoder, &x, &residual, ws.next_scratch(ctx, x.shape(), data_type, "cnxt_add")?, kernels)
}
pub(super) fn build_post_module_runtime<B: Backend>(
diff --git a/crates/backend-uzu/src/inference/text_to_speech/mod.rs b/crates/backend-uzu/src/inference/text_to_speech/mod.rs
index c28518346..f46d3a466 100644
--- a/crates/backend-uzu/src/inference/text_to_speech/mod.rs
+++ b/crates/backend-uzu/src/inference/text_to_speech/mod.rs
@@ -126,11 +126,12 @@ fn run(
};
let seed = rand::rng().random::<u64>();
let config = TtsRunConfig::default();
- session.synthesize_with_seed_and_config(input, seed, &config)
- };
- let result = match result {
- Ok(pcm) => Ok(build_pcm_batch(&pcm)),
- Err(error) => Err(Box::new(Error::from(error)) as BackendError),
+ let chunk_sender = sender.clone();
+ session.synthesize_streaming_with_seed_and_config(input, seed, &config, |pcm| {
+ let _ = chunk_sender.unbounded_send(Ok(build_pcm_batch(pcm)));
+ })
};
- let _ = sender.unbounded_send(result);
+ if let Err(error) = result {
+ let _ = sender.unbounded_send(Err(Box::new(Error::from(error)) as BackendError));
+ }
}
diff --git a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
index 915816913..f2c0796d8 100644
--- a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
+++ b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
@@ -69,6 +69,7 @@ struct TokenDecoderContext<B: Backend> {
scratch_buffers: ScratchBuffers<B>,
model_shape: ModelShape,
decoder_config: Rc<crate::config::DecoderConfig>,
+ runtime_config: TextDecoderRuntimeConfig,
executables: Decoder<B>,
sampler: GpuSampling<B>,
kv_cache_update: KVCacheUpdate<B>,
@@ -78,6 +79,7 @@ struct TokenDecoderContext<B: Backend> {
async_chain_seeds: Rc<RefCell<B::Buffer>>,
async_chain_results: Rc<RefCell<B::Buffer>>,
async_chain_capacity: usize,
+ current_max_prefix_length: usize,
}
impl<B: Backend> TokenDecoderContext<B> {
@@ -95,8 +97,8 @@ impl<B: Backend> TokenDecoderContext<B> {
runtime_config: &TextDecoderRuntimeConfig,
) -> Result<(Self, DataType), Error> {
let model_shape = ModelShape::from_decoder_config(&decoder_config);
- let max_prefix_length = decoder_config.context_length;
let max_suffix_length = text_decoder_prefill_step_size(runtime_config, decoder_config.context_length).max(32);
+ let max_prefix_length = max_suffix_length;
let activation_data_type = model_shape.activation_data_type();
let loaded_model = TokenDecoderLoadedModel::<B>::load(
&context,
@@ -129,6 +131,7 @@ impl<B: Backend> TokenDecoderContext<B> {
scratch_buffers: loaded_model.scratch_buffers,
model_shape,
decoder_config,
+ runtime_config: runtime_config.clone(),
executables: loaded_model.executables,
sampler: loaded_model.sampler,
kv_cache_update,
@@ -138,6 +141,7 @@ impl<B: Backend> TokenDecoderContext<B> {
async_chain_seeds,
async_chain_results,
async_chain_capacity,
+ current_max_prefix_length: max_prefix_length,
},
activation_data_type,
))
@@ -251,6 +255,25 @@ impl<B: Backend> TokenDecoderRunner<B> {
self.next_position = 0;
}
+ pub(super) fn prepare_for_generation(
+ &mut self,
+ max_prefix_length: usize,
+ ) -> Result<(), Error> {
+ let max_prefix_length = max_prefix_length.max(1).min(self.ctx.decoder_config.context_length);
+ let max_suffix_length = text_decoder_prefill_step_size(&self.ctx.runtime_config, max_prefix_length).max(32);
+ if self.ctx.current_max_prefix_length == max_prefix_length {
+ return Ok(());
+ }
+ let context = self.ctx.context.as_ref();
+ *self.ctx.cache_layers.borrow_mut() =
+ CacheLayers::new(context, &self.ctx.model_shape, max_prefix_length, max_suffix_length);
+ let intermediate_data_type: DataType = self.ctx.decoder_config.output_norm_config.scale_precision.into();
+ self.ctx.kv_cache_update =
+ KVCacheUpdate::new(context, intermediate_data_type, max_prefix_length).map_err(unable_to_create_context)?;
+ self.ctx.current_max_prefix_length = max_prefix_length;
+ Ok(())
+ }
+
pub(super) fn prefill_without_sampling(
&mut self,
token_ids: &[u64],
diff --git a/crates/backend-uzu/src/session/tts_session/decoder_support.rs b/crates/backend-uzu/src/session/tts_session/decoder_support.rs
index 827fe299c..8b708f6da 100644
--- a/crates/backend-uzu/src/session/tts_session/decoder_support.rs
+++ b/crates/backend-uzu/src/session/tts_session/decoder_support.rs
@@ -335,7 +335,9 @@ impl<'a, F: FnMut(&AudioPcmBatch)> StreamingSynthesisState<'a, F> {
partial_pcm,
resolve_decode_duration,
) = if force {
- let pending = self.pending_chunk.take().ok_or(Error::GenerateFailed)?;
+ let Some(pending) = self.pending_chunk.take() else {
+ return Ok(());
+ };
let step_stats = pending.chunk.step_stats();
let ready_frames = pending.ready_frames;
let next_chunk_frames = pending.next_chunk_frames;
diff --git a/crates/backend-uzu/src/session/tts_session/fishaudio.rs b/crates/backend-uzu/src/session/tts_session/fishaudio.rs
index 681c0b15a..0e4cbd902 100644
--- a/crates/backend-uzu/src/session/tts_session/fishaudio.rs
+++ b/crates/backend-uzu/src/session/tts_session/fishaudio.rs
@@ -379,18 +379,21 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
self.reset_generation_state();
let mut sampling = TextSamplingState::from_config(seed, &self.runtime_config.sampling);
- let mut current_semantic_token = self.decode_initial_semantic_token(text_tokens, &mut sampling)?;
- let post_scale = if self.scale_codebook_embeddings {
- Some(1.0 / ((self.num_codebooks + 1) as f32).sqrt())
- } else {
- None
- };
let mut max_new_tokens = self.max_seq_len.saturating_sub(text_tokens.len());
max_new_tokens = max_new_tokens.min(max_semantic_frames.max(1));
if let Some(limit) = self.runtime_config.max_new_tokens_override {
max_new_tokens = max_new_tokens.min(limit);
}
+ self.slow_runner.prepare_for_generation(text_tokens.len() + max_new_tokens)?;
+ self.fast_runner.prepare_for_generation(self.num_codebooks + 1)?;
+
+ let mut current_semantic_token = self.decode_initial_semantic_token(text_tokens, &mut sampling)?;
+ let post_scale = if self.scale_codebook_embeddings {
+ Some(1.0 / ((self.num_codebooks + 1) as f32).sqrt())
+ } else {
+ None
+ };
let mut by_codebook =
(0..self.num_codebooks).map(|_| Vec::<u32>::with_capacity(max_new_tokens)).collect::<Vec<_>>();
if self.current_codes_scratch.len() != self.num_codebooks {
diff --git a/crates/nagare/src/text_to_speech/mod.rs b/crates/nagare/src/text_to_speech/mod.rs
index d92fbcca7..9922a7592 100644
--- a/crates/nagare/src/text_to_speech/mod.rs
+++ b/crates/nagare/src/text_to_speech/mod.rs
@@ -120,21 +120,23 @@ impl TextToSpeechSession {
match event {
TextToSpeechSessionStreamChunk::PcmBatch {
batch,
- } => batches.push(batch.clone()),
+ } => batches.push(batch),
TextToSpeechSessionStreamChunk::Error {
error,
} => return Err(error),
}
}
- if let Some(batch) = batches.last() {
- return Ok(batch.clone());
- }
- Err(TextToSpeechSessionError::NoResponse {})
+ let first = batches.first().ok_or(TextToSpeechSessionError::NoResponse {})?;
+ Ok(PcmBatch {
+ sample_rate: first.sample_rate,
+ channels: first.channels,
+ lengths: vec![batches.iter().flat_map(|batch| batch.lengths.iter().copied()).sum()],
+ samples: batches.iter().flat_map(|batch| batch.samples.iter().copied()).collect(),
+ })
}
-}
-impl TextToSpeechSession {
- async fn synthesize_stream(
+ #[bindings::export(Method)]
+ pub async fn synthesize_stream(
&self,
input: String,
) -> TextToSpeechSessionStream {