1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use std::{
    fmt::{self, Debug, Formatter},
    convert::TryFrom,
    fs::File,
    io::Read,
    path::Path,
    time::Duration,
};
use anyhow::{Context, Error};
use hound::{WavReader, WavSpec};
use hotg_rune_core::{Value};
use hotg_rune_runtime::ParameterError;

use crate::run::multi::{Builder, SourceBackedCapability};

#[derive(Clone, PartialEq)]
pub struct AudioClip {
    spec: WavSpec,
    samples: Vec<i16>,
}

impl AudioClip {
    pub fn from_wav_file(filename: impl AsRef<Path>) -> Result<Self, Error> {
        let filename = filename.as_ref();
        let f = File::open(filename).with_context(|| {
            format!("Unable to open \"{}\" for reading", filename.display())
        })?;
        let wav = WavReader::new(f)?;

        AudioClip::load(wav)
    }

    pub fn load(reader: WavReader<impl Read>) -> Result<Self, Error> {
        let spec = reader.spec();
        let samples = reader
            .into_samples()
            .collect::<Result<Vec<i16>, hound::Error>>()
            .context("Unable to parse the WAV file")?;
        Ok(AudioClip { spec, samples })
    }
}

impl Debug for AudioClip {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let AudioClip { spec, samples } = self;
        f.debug_struct("AudioClip")
            .field("spec", spec)
            .field("samples", &format_args!("({} samples)", samples.len()))
            .finish()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Sound {
    pcm_samples: Vec<i16>,
}

impl SourceBackedCapability for Sound {
    type Builder = SoundSettings;
    type Source = AudioClip;

    fn generate(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
        let chunk_size = std::mem::size_of::<i16>();
        let mut bytes_written = 0;

        for (chunk, sample) in
            buffer.chunks_mut(chunk_size).zip(&self.pcm_samples)
        {
            let sample = sample.to_ne_bytes();
            chunk.copy_from_slice(&sample);

            bytes_written += sample.len();
        }

        Ok(bytes_written)
    }

    fn from_builder(
        builder: SoundSettings,
        source: &AudioClip,
    ) -> Result<Self, Error> {
        // TODO: Resample to match the desired sample rate instead of just using
        // frequency and duration to calculate the number of samples.
        let total_samples = builder.total_samples(source.samples.len())?;

        Ok(Sound {
            pcm_samples: source.samples[..total_samples].to_vec(),
        })
    }
}

#[derive(Debug, Default, Clone, PartialEq)]
pub struct SoundSettings {
    frequency: Option<u32>,
    duration: Option<Duration>,
}

impl SoundSettings {
    fn total_samples(&self, max_samples: usize) -> Result<usize, Error> {
        match *self {
            SoundSettings {
                frequency: None,
                duration: None,
            } => Ok(max_samples),
            SoundSettings {
                frequency: Some(frequency),
                duration: Some(duration),
            } => {
                let total_samples = usize::try_from(
                    (frequency as u128) * duration.as_micros() / 1_000_000,
                )?;

                if total_samples > max_samples {
                    anyhow::bail!(
                        "{} samples were requested but only {} are available",
                        total_samples,
                        max_samples
                    );
                }

                Ok(total_samples)
            },

            SoundSettings { duration: None, .. } => {
                anyhow::bail!("The \"sample_duration\" parameter wasn't set")
            },
            SoundSettings {
                frequency: None, ..
            } => anyhow::bail!("The \"frequency\" parameter wasn't set"),
        }
    }
}

impl Builder for SoundSettings {
    fn set_parameter(
        &mut self,
        key: &str,
        value: Value,
    ) -> Result<(), ParameterError> {
        let SoundSettings {
            frequency,
            duration,
        } = self;

        match key {
            "hz" | "frequency" => super::try_from_int_value(frequency, value),
            "sample_duration_ms" => {
                super::try_from_int_value_and_then(value, |ms| {
                    *duration = Some(Duration::from_millis(ms))
                })
            },
            "sample_duration" => {
                super::try_from_int_value_and_then(value, |secs| {
                    *duration = Some(Duration::from_secs(secs))
                })
            },

            _ => Err(ParameterError::UnsupportedParameter),
        }
    }
}