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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use crate::{audio::filter::Filter, NesResult};
use anyhow::anyhow;
#[cfg(not(target_arch = "wasm32"))]
use pix_engine::prelude::*;
use ringbuf::{Consumer, HeapRb, Producer, SharedRb};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;
use std::{fmt, mem::MaybeUninit, sync::Arc};

pub mod filter;
pub mod window_sinc;

type RbRef = Arc<SharedRb<f32, Vec<MaybeUninit<f32>>>>;

pub trait Audio {
    fn output(&self) -> f32;
}

pub struct NesAudioCallback {
    initialized: bool,
    buffer: Consumer<f32, RbRef>,
}

impl NesAudioCallback {
    const fn new(buffer: Consumer<f32, RbRef>) -> Self {
        Self {
            initialized: false,
            buffer,
        }
    }

    #[inline]
    pub fn clear(&mut self) {
        self.buffer.clear();
    }

    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    pub fn read(&mut self, out: &mut [f32]) {
        if !self.initialized && self.buffer.len() < out.len() {
            out.fill(0.0);
            return;
        }
        self.initialized = true;

        for val in out {
            if let Some(sample) = self.buffer.pop() {
                *val = sample;
            } else {
                *val = 0.0;
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl AudioCallback for NesAudioCallback {
    type Channel = f32;

    fn callback(&mut self, out: &mut [Self::Channel]) {
        self.read(out);
    }
}

impl fmt::Debug for NesAudioCallback {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NesAudioCallback")
            .field("initialized", &self.initialized)
            .field("buffer_len", &self.buffer.len())
            .field("buffer_capacity", &self.buffer.capacity())
            .finish()
    }
}

#[must_use]
pub struct AudioMixer {
    #[cfg(not(target_arch = "wasm32"))]
    device: Option<AudioDevice<NesAudioCallback>>,
    producer: Producer<f32, RbRef>,
    consumer: Option<Consumer<f32, RbRef>>,
    input_frequency: f32,
    output_frequency: f32,
    decim_ratio: f32,
    pitch_ratio: f32,
    fraction: f32,
    avg: f32,
    count: f32,
    filters: [Filter; 3],
}

impl AudioMixer {
    pub fn new(input_frequency: f32, output_frequency: f32, buffer_size: usize) -> Self {
        let buffer = HeapRb::<f32>::new(buffer_size);
        let (producer, consumer) = buffer.split();
        Self {
            #[cfg(not(target_arch = "wasm32"))]
            device: None,
            producer,
            consumer: Some(consumer),
            input_frequency,
            output_frequency,
            decim_ratio: input_frequency / output_frequency,
            pitch_ratio: 1.0,
            fraction: 0.0,
            avg: 0.0,
            count: 0.0,
            filters: [
                Filter::high_pass(output_frequency, 90.0, 1500.0),
                Filter::high_pass(output_frequency, 440.0, 1500.0),
                // Should be 14k, but this allows 2X speed within the Nyquist limit
                Filter::low_pass(output_frequency, 12_000.0, 1500.0),
            ],
        }
    }

    #[must_use]
    pub const fn output_frequency(&self) -> f32 {
        self.output_frequency
    }

    /// Opens audio callback device for playback
    ///
    /// # Errors
    ///
    /// This function will return an error if the audio device fails to be opened, or if
    /// `open_playback` is called more than once.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn open_playback(&mut self, s: &mut PixState) -> NesResult<()> {
        match self.consumer.take() {
            Some(consumer) => {
                let spec = AudioSpecDesired {
                    freq: Some(self.output_frequency as i32),
                    channels: Some(1),
                    samples: Some((self.capacity() / 2) as u16),
                };
                self.device =
                    Some(s.open_playback(None, &spec, |_| NesAudioCallback::new(consumer))?);
                Ok(())
            }
            None => Err(anyhow!("can only open_playback once")),
        }
    }

    /// Returns audio buffer device for consuming audio samples.
    ///
    /// # Errors
    ///
    /// This function will return an error if `open_buffer` is called more than once.
    pub fn open_callback(&mut self) -> NesResult<NesAudioCallback> {
        match self.consumer.take() {
            Some(consumer) => Ok(NesAudioCallback::new(consumer)),
            None => Err(anyhow!("can only open_buffer exactly once")),
        }
    }

    /// Resets the audio callback device.
    ///
    /// # Errors
    ///
    /// This function will return an error if the audio device fails to be opened.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn reset(&mut self, buffer_size: usize) {
        self.decim_ratio = self.input_frequency / self.output_frequency;
        self.pitch_ratio = 1.0;
        self.fraction = 0.0;
        let buffer = HeapRb::<f32>::new(buffer_size);
        let (producer, consumer) = buffer.split();
        self.producer = producer;
        self.consumer = Some(consumer);
    }

    #[inline]
    #[cfg(not(target_arch = "wasm32"))]
    pub fn resume(&mut self) {
        if let Some(ref mut device) = self.device {
            device.resume();
        }
    }

    #[inline]
    #[cfg(not(target_arch = "wasm32"))]
    pub fn pause(&mut self) {
        if let Some(ref mut device) = self.device {
            device.pause();
        }
    }

    #[inline]
    pub fn set_input_frequency(&mut self, input_frequency: f32) {
        self.input_frequency = input_frequency;
    }

    #[inline]
    pub fn set_output_frequency(&mut self, output_frequency: f32) {
        self.output_frequency = output_frequency;
    }

    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.producer.len()
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.producer.is_empty()
    }

    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.producer.capacity()
    }

    #[inline]
    #[must_use]
    pub const fn pitch_ratio(&self) -> f32 {
        self.pitch_ratio
    }

    /// Outputs audio using multi-rate-control re-sampling.
    ///
    /// Sources:
    /// - <https://near.sh/articles/audio/dynamic-rate-control>
    /// - <https://github.com/libretro/docs/blob/master/archive/ratecontrol.pdf>
    pub fn consume(
        &mut self,
        samples: &[f32],
        dynamic_rate_control: bool,
        max_delta: f32,
    ) -> usize {
        self.pitch_ratio = if dynamic_rate_control {
            let size = self.producer.len() as f32;
            let capacity = self.producer.capacity() as f32;
            ((capacity - 2.0 * size) / capacity).mul_add(max_delta, 1.0)
        } else {
            1.0
        };
        self.decim_ratio = self.input_frequency / (self.output_frequency * self.pitch_ratio);
        let mut sample_count = 0;
        for sample in samples {
            self.avg += *sample;
            self.count += 1.0;
            while self.fraction <= 0.0 {
                let sample = self
                    .filters
                    .iter_mut()
                    .fold(self.avg / self.count, |sample, filter| filter.apply(sample));
                if self.producer.push(sample).is_err() {
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        std::thread::sleep(Duration::from_micros(10));
                    }
                }
                self.avg = 0.0;
                self.count = 0.0;
                sample_count += 1;
                self.fraction += self.decim_ratio;
            }
            self.fraction -= 1.0;
        }
        sample_count
    }
}

impl fmt::Debug for AudioMixer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AudioMixer")
            .field("producer_len", &self.producer.len())
            .field("producer_capacity", &self.producer.capacity())
            .field("input_frequency", &self.input_frequency)
            .field("output_frequency", &self.output_frequency)
            .field("decim_ratio", &self.decim_ratio)
            .field("pitch_ratio", &self.pitch_ratio)
            .field("fraction", &self.fraction)
            .field("filters", &self.filters)
            .finish()
    }
}