Skip to main content

rustysynth_ext/
synthesizer_settings.rs

1use crate::error::SynthesizerError;
2
3/// Specifies a set of parameters for synthesis.
4#[derive(Debug)]
5#[non_exhaustive]
6pub struct SynthesizerSettings {
7    /// The sample rate for synthesis.
8    pub sample_rate: i32,
9    /// The block size for rendering waveform.
10    pub block_size: usize,
11    /// The number of maximum polyphony.
12    pub maximum_polyphony: usize,
13    /// The value indicating whether reverb and chorus are enabled.
14    pub enable_reverb_and_chorus: bool,
15}
16
17impl SynthesizerSettings {
18    const DEFAULT_BLOCK_SIZE: usize = 64;
19    const DEFAULT_MAXIMUM_POLYPHONY: usize = 64;
20    const DEFAULT_ENABLE_REVERB_AND_CHORUS: bool = true;
21
22    /// Initializes a new instance of synthesizer settings.
23    ///
24    /// # Arguments
25    ///
26    /// * `sample_rate` - The sample rate for synthesis.
27    pub fn new(sample_rate: i32) -> Self {
28        Self {
29            sample_rate,
30            block_size: SynthesizerSettings::DEFAULT_BLOCK_SIZE,
31            maximum_polyphony: SynthesizerSettings::DEFAULT_MAXIMUM_POLYPHONY,
32            enable_reverb_and_chorus: SynthesizerSettings::DEFAULT_ENABLE_REVERB_AND_CHORUS,
33        }
34    }
35
36    pub(crate) fn validate(&self) -> Result<(), SynthesizerError> {
37        SynthesizerSettings::check_sample_rate(self.sample_rate)?;
38        SynthesizerSettings::check_block_size(self.block_size)?;
39        SynthesizerSettings::check_maximum_polyphony(self.maximum_polyphony)?;
40
41        Ok(())
42    }
43
44    fn check_sample_rate(value: i32) -> Result<(), SynthesizerError> {
45        if !(16_000..=192_000).contains(&value) {
46            return Err(SynthesizerError::SampleRateOutOfRange(value));
47        }
48
49        Ok(())
50    }
51
52    fn check_block_size(value: usize) -> Result<(), SynthesizerError> {
53        if !(8..=1024).contains(&value) {
54            return Err(SynthesizerError::BlockSizeOutOfRange(value));
55        }
56
57        Ok(())
58    }
59
60    fn check_maximum_polyphony(value: usize) -> Result<(), SynthesizerError> {
61        if !(8..=256).contains(&value) {
62            return Err(SynthesizerError::MaximumPolyphonyOutOfRange(value));
63        }
64
65        Ok(())
66    }
67}