piper1-rs 0.1.0

Safe Rust bindings to Piper, the TTS library
Documentation
use std::{ffi::CString, io::ErrorKind};

use piper1_rs_sys::{
	piper_create,
	piper_default_synthesize_options,
	piper_free,
	piper_synthesizer,
};

use crate::{
	error::{PiperError, PiperResult},
	piper_synth_options::PiperSynthesisOptions,
	synthesis_handle::PiperSynthesisHandle,
};

/// A handle to a Piper synthesizer.
pub struct Piper {
	pub(crate) ptr: *mut piper_synthesizer,

	model_str_ptr:   *mut i8,
	config_str_ptr:  *mut i8,
	espeak_data_ptr: *mut i8,
}

impl Piper {
	/// Create a Piper synthesizer from a voice model.
	///
	/// All paths must be valid UTF-8.
	///
	/// # Arguments
	/// * `model_path`: path to ONNX voice model file
	/// * `config_path`: path to JSON voice config file.
	///   `None` defaults to `${model_path}.json`.
	/// * `espeak_data_path`: path to ESpeak-ng data directory
	pub fn new(
		model_path: impl Into<String>,
		config_path: Option<impl Into<String>>,
		espeak_data_path: impl Into<String>,
	) -> PiperResult<Self> {
		Self::new_inner(
			model_path.into(),
			config_path.map(|p| p.into()),
			espeak_data_path.into(),
		)
	}

	fn new_inner(
		model_path: String,
		config_path: Option<String>,
		espeak_data_path: String,
	) -> PiperResult<Self> {
		path_exists(&model_path)?;
		if let Some(ref config_path) = config_path {
			path_exists(config_path)?;
		}
		path_exists(&espeak_data_path)?;

		let model_path = CString::new(model_path.into_bytes())?.into_raw();
		let config_path = if let Some(s) = config_path {
			CString::new(s.into_bytes())?.into_raw()
		} else {
			std::ptr::null_mut()
		};
		let espeak_data_path = CString::new(espeak_data_path.into_bytes())?.into_raw();

		let ptr = unsafe { piper_create(model_path, config_path, espeak_data_path) };
		if ptr.is_null() {
			Err(PiperError::NullPointer)
		} else {
			Ok(Piper {
				ptr,
				model_str_ptr: model_path,
				config_str_ptr: config_path,
				espeak_data_ptr: espeak_data_path,
			})
		}
	}

	/// Get the default synthesis options for this TTS model.
	pub fn get_default_synthesis_options(&self) -> PiperSynthesisOptions {
		unsafe { piper_default_synthesize_options(self.ptr) }.into()
	}

	/// Call this function to begin synthesizing audio.
	pub fn start_synthesis(
		&'_ mut self,
		text: String,
		options: &PiperSynthesisOptions,
	) -> PiperResult<PiperSynthesisHandle<'_>> {
		let synthesis_text = CString::new(text)?.into_raw();

		let mut handle = PiperSynthesisHandle::new(self, synthesis_text, options);
		handle.start_synthesis()?;

		Ok(handle)
	}
}

impl Drop for Piper {
	fn drop(&mut self) {
		unsafe { piper_free(self.ptr) }

		if !self.model_str_ptr.is_null() {
			let _model_path = unsafe { CString::from_raw(self.model_str_ptr) };
		}
		if !self.config_str_ptr.is_null() {
			let _config = unsafe { CString::from_raw(self.config_str_ptr) };
		}
		if !self.espeak_data_ptr.is_null() {
			let _espeak_data = unsafe { CString::from_raw(self.espeak_data_ptr) };
		}
	}
}

fn path_exists(path: &str) -> PiperResult<()> {
	if std::fs::exists(path)? {
		Ok(())
	} else {
		Err(PiperError::Io(std::io::Error::new(
			ErrorKind::NotFound,
			path,
		)))
	}
}