piper1-rs 0.1.0

Safe Rust bindings to Piper, the TTS library
Documentation
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},
};

/// A handle to an active transcription session.
///
/// Internally contains a mutable pointer to the Piper synthesizer.
/// This means you can only have one of these running per synthesizer at a time.
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)),
		}
	}

	/// Get the next chunk of audio from synthesis.
	///
	/// You must drop any prior [`PiperAudioChunk`] obtained from this function before
	/// calling this again.
	/// The Rust compiler will statically guarantee this, typically you needn't do anything special.
	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) };
	}
}

/// A single chunk of audio returned when synthesizing.
pub struct PiperAudioChunk<'a, 'b> {
	// we keep this reference around just to ensure `PiperSynthesisHandle::get_next_chunk`
	// can only be called after this object is dropped
	// for reasoning on why, see docs on `piper_synthesize_next`:
	// > Each call to piper_synthesize_next will fill the audio chunk, invalidating
	// > the memory of the previous chunk
	// a cautious assumption is that the data pointers are reused over and over
	_synth_handle: &'a mut PiperSynthesisHandle<'b>,
	inner:         piper_audio_chunk,
}

impl PiperAudioChunk<'_, '_> {
	/// Raw samples returned from the voice model.
	pub fn samples(&self) -> &[f32] {
		assert!(!self.inner.samples.is_null());
		unsafe { core::slice::from_raw_parts(self.inner.samples, self.num_samples()) }
	}

	/// Number of samples in the audio chunk.
	pub fn num_samples(&self) -> usize {
		self.inner.num_samples
	}

	/// Sample rate in Hertz.
	pub fn sample_rate(&self) -> u32 {
		// cast safely because the sample rate should never be negative
		self.inner.sample_rate as u32
	}

	/// True if this is the last audio chunk.
	///
	/// In other words, calling [`PiperSynthesisHandle::get_next_chunk`] will return `None` forever now,
	/// until another synthesis session is started.
	pub fn is_last(&self) -> bool {
		self.inner.is_last
	}

	/// Phoneme codepoints that produced this audio chunk, aligned with IDs.
	///
	/// Phonemes will look like `[p1, p1, 0, p2, p2, 0, ...]` where the same phoneme
	/// codepoint is repeated for each ID from that phoneme (usually just one ID
	/// plus pad).
	///
	/// Groups of repeated codepoints are separated by a 0 so that alignments can
	/// be attributed to the correct phoneme. This is accomplished by:
	///
	/// 1. Read N (repeated) codepoints from phonemes until a 0 is reached (or end)
	/// 2. The next N phoneme IDs correspond to that phoneme
	/// 3. The next N alignments (sample counts) correspond to that phoneme
	/// 4. Advance your iterators in the phoneme id and alignment arrays by N
	/// 5. Repeat
	pub fn phonemes(&self) -> &[c_uint] {
		assert!(!self.inner.phonemes.is_null());
		unsafe { core::slice::from_raw_parts(self.inner.phonemes, self.num_phonemes()) }
	}

	/// Number of codepoints in [`Self::phonemes`].
	pub fn num_phonemes(&self) -> usize {
		self.inner.num_phonemes
	}

	/// Phoneme IDs that produced this audio chunk.
	///
	/// IDs will look like `[1, 0, id1, 0, id2, 0, ..., 2]` where:
	///
	/// * 0 = pad
	/// * 1 = beginning of sentence
	/// * 2 = end of sentence
	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()) }
	}

	/// Number of IDs in [`Self::phoneme_ids`].
	pub fn num_phoneme_ids(&self) -> usize {
		self.inner.num_phoneme_ids
	}

	/// Audio sample count for each phoneme ID.
	///
	/// This includes the meta IDs:
	///
	/// * 0 = pad
	/// * 1 = beginning of sentence
	/// * 2 = end of sentence
	///
	/// Use [`Self::phonemes`] to align these sample counts with actual phonemes.
	pub fn alignments(&self) -> &[c_int] {
		assert!(!self.inner.alignments.is_null());
		unsafe { core::slice::from_raw_parts(self.inner.alignments, self.num_alignments()) }
	}

	/// Number of alignments.
	///
	/// This should be the same as [`Self::num_phoneme_ids`].
	pub fn num_alignments(&self) -> usize {
		self.inner.num_alignments
	}
}