use std::{
ffi::CString,
os::raw::{c_int, c_uint},
};
use piper1_rs_sys::{
piper_audio_chunk,
piper_synthesize_next,
piper_synthesize_options,
piper_synthesize_start,
};
use crate::{
Piper,
PiperError,
PiperResult,
consts::{PIPER_DONE, PIPER_ERR_GENERIC, PIPER_OK},
};
pub struct PiperSynthesisHandle<'a> {
inner: &'a mut Piper,
synthesis_text: *mut i8,
options: piper_synthesize_options,
}
impl<'handle> PiperSynthesisHandle<'handle> {
pub(crate) fn new(
inner: &'handle mut Piper,
synthesis_text: *mut i8,
options: impl Into<piper_synthesize_options>,
) -> Self {
Self {
inner,
synthesis_text,
options: options.into(),
}
}
pub(crate) fn start_synthesis(&mut self) -> PiperResult<()> {
let option_ptr = &self.options as *const piper_synthesize_options;
let res =
unsafe { piper_synthesize_start(self.inner.ptr, self.synthesis_text, option_ptr) };
match res {
PIPER_OK => Ok(()),
PIPER_ERR_GENERIC => Err(PiperError::GenericError),
n => Err(PiperError::UnknownError(n)),
}
}
pub fn get_next_chunk<'chunk>(
&'chunk mut self,
) -> PiperResult<Option<PiperAudioChunk<'chunk, 'handle>>> {
let mut maybe_chunk = std::mem::MaybeUninit::uninit();
let ret = unsafe { piper_synthesize_next(self.inner.ptr, maybe_chunk.as_mut_ptr()) };
let chunk = match ret {
PIPER_OK => unsafe { maybe_chunk.assume_init() },
PIPER_DONE => return Ok(None),
PIPER_ERR_GENERIC => return Err(PiperError::GenericError),
n => return Err(PiperError::UnknownError(n)),
};
Ok(Some(PiperAudioChunk {
_synth_handle: self,
inner: chunk,
}))
}
}
impl Drop for PiperSynthesisHandle<'_> {
fn drop(&mut self) {
assert!(!self.synthesis_text.is_null());
let _synthesis_text = unsafe { CString::from_raw(self.synthesis_text) };
}
}
pub struct PiperAudioChunk<'a, 'b> {
_synth_handle: &'a mut PiperSynthesisHandle<'b>,
inner: piper_audio_chunk,
}
impl PiperAudioChunk<'_, '_> {
pub fn samples(&self) -> &[f32] {
assert!(!self.inner.samples.is_null());
unsafe { core::slice::from_raw_parts(self.inner.samples, self.num_samples()) }
}
pub fn num_samples(&self) -> usize {
self.inner.num_samples
}
pub fn sample_rate(&self) -> u32 {
self.inner.sample_rate as u32
}
pub fn is_last(&self) -> bool {
self.inner.is_last
}
pub fn phonemes(&self) -> &[c_uint] {
assert!(!self.inner.phonemes.is_null());
unsafe { core::slice::from_raw_parts(self.inner.phonemes, self.num_phonemes()) }
}
pub fn num_phonemes(&self) -> usize {
self.inner.num_phonemes
}
pub fn phoneme_ids(&self) -> &[c_int] {
assert!(!self.inner.phoneme_ids.is_null());
unsafe { core::slice::from_raw_parts(self.inner.phoneme_ids, self.num_phoneme_ids()) }
}
pub fn num_phoneme_ids(&self) -> usize {
self.inner.num_phoneme_ids
}
pub fn alignments(&self) -> &[c_int] {
assert!(!self.inner.alignments.is_null());
unsafe { core::slice::from_raw_parts(self.inner.alignments, self.num_alignments()) }
}
pub fn num_alignments(&self) -> usize {
self.inner.num_alignments
}
}