-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
226 lines (195 loc) · 6.37 KB
/
lib.rs
File metadata and controls
226 lines (195 loc) · 6.37 KB
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
pub mod audio_processing;
pub mod file;
mod live_audio;
pub mod project;
pub mod sample;
use std::{
fmt::Debug,
num::{NonZero, NonZeroU16},
ops::Deref,
time::Duration,
};
use simple_left_right::{WriteGuard, Writer};
use crate::{
audio_processing::{Interpolation, playback::PlaybackStatus},
live_audio::LiveAudio,
project::{
note_event::NoteEvent,
song::{Song, SongOperation, ValidOperation},
},
sample::Sample,
};
#[derive(Debug, Clone, Copy)]
pub enum ToWorkerMsg {
Playback(PlaybackSettings),
StopPlayback,
PlayEvent(NoteEvent),
StopLiveNote,
SetInterpolation(Interpolation),
}
// don't leak the dependency types
pub struct StatusRecv<StreamData>(rt_write_lock::Reader<(Option<PlaybackStatus>, StreamData)>);
// don't leak the dependency types
pub struct StatusRead<'a, StreamData>(
rt_write_lock::ReadGuard<'a, (Option<PlaybackStatus>, StreamData)>,
);
impl<S> Deref for StatusRead<'_, S> {
type Target = (Option<PlaybackStatus>, S);
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<S> StatusRecv<S> {
pub fn try_get(&mut self) -> Option<StatusRead<'_, S>> {
self.0.try_read().map(|r| StatusRead(r))
}
}
pub struct StreamSend(rtrb::Producer<ToWorkerMsg>);
impl StreamSend {
#[expect(clippy::result_unit_err)]
pub fn try_msg_worker(&mut self, msg: ToWorkerMsg) -> Result<(), ()> {
match self.0.push(msg) {
Ok(_) => Ok(()),
Err(_) => Err(()),
}
}
}
#[derive(Debug, Default)]
pub(crate) struct Collector {
samples: Vec<Sample>,
}
impl Collector {
pub fn add_sample(&mut self, sample: Sample) {
self.samples.push(sample);
}
fn collect(&mut self) {
self.samples.retain(|s| {
// only look at strong count as weak pointers are not used
s.strongcount() != 1
});
}
}
pub struct AudioManager {
song: Writer<Song, ValidOperation>,
gc: Collector,
buffer_time: Duration,
}
impl AudioManager {
pub fn new(song: Song) -> Self {
let mut gc = Collector::default();
for (_, sample) in song.samples.iter().flatten() {
gc.add_sample(sample.clone());
}
let left_right = simple_left_right::Writer::new(song);
Self {
song: left_right,
gc,
buffer_time: Duration::ZERO,
}
}
/// If this returns None, waiting buffer_time should (weird threading issues aside) always be enough time
/// and it should return Some after that.
pub fn try_edit_song(&mut self) -> Option<SongEdit<'_>> {
self.song.try_lock().map(|song| SongEdit {
song,
gc: &mut self.gc,
})
}
pub fn get_song(&self) -> &Song {
self.song.read()
}
pub fn collect_garbage(&mut self) {
self.gc.collect();
}
/// If the config specifies more than two channels only the first two will be filled with audio.
/// The rest get silence.
///
/// The callback in for example Cpal provides an additional arguement, where a timestamp is give.
/// That should ba handled by wrapping this function in another callback, where this argument could
/// then be ignored or send somewhere for processing. This Sending needs to happen wait-free!! There are
/// a couple of libaries that can do this, i would recommend triple_buffer or rtrb.
///
/// The OutputConfig has to match the config of the AudioStream that will call this. If for example the
/// buffer size is different Panics may occur.
///
/// In my testing i noticed that when using Cpal with non-standard buffer sizes Cpal would just give
/// another buffer size. This may also lead to panics.
///
/// ## Panics
///
/// Will panic if there is an active stream.
pub fn get_callback<
Sample: dasp::sample::Sample + dasp::sample::FromSample<f32>,
StreamData: Clone,
>(
&mut self,
config: OutputConfig,
initial_stream_data: StreamData,
) -> (
impl FnMut(&mut [Sample], StreamData) + use<Sample, StreamData>,
Duration,
StatusRecv<StreamData>,
StreamSend,
) {
const SEND_SIZE: usize = 10;
let mut from_worker = rt_write_lock::Reader::new((None, initial_stream_data));
// let from_worker = triple_buffer::triple_buffer(&(None, initial_stream_data));
let to_worker = rtrb::RingBuffer::new(SEND_SIZE);
let reader = self.song.build_reader().expect("another stream is active");
let audio_worker = LiveAudio::<StreamData>::new(
reader,
to_worker.1,
// doesn't panic because i just created the reader
from_worker.get_writer().unwrap(),
config,
);
let buffer_time =
Duration::from_millis((config.buffer_size * 1000 / config.sample_rate).into());
self.buffer_time = buffer_time;
(
audio_worker.get_typed_callback(),
buffer_time,
StatusRecv(from_worker),
StreamSend(to_worker.0),
)
}
/// Buffer time of the last created callback.
pub fn last_buffer_time(&self) -> Duration {
self.buffer_time
}
}
/// the changes made to the song will be made available to the playing live audio as soon as
/// this struct is dropped.
///
/// With this you can load the full song without ever playing a half initialised state
/// when doing mulitple operations this object should be kept as it is
#[derive(Debug)]
pub struct SongEdit<'a> {
song: WriteGuard<'a, Song, ValidOperation>,
gc: &'a mut Collector,
}
impl SongEdit<'_> {
pub fn apply_operation(&mut self, op: SongOperation) -> Result<(), SongOperation> {
let valid_operation = ValidOperation::new(op, self.gc, self.song.read())?;
self.song.apply_op(valid_operation);
Ok(())
}
pub fn song(&self) -> &Song {
self.song.read()
}
/// Finish the changes and publish them to the live playing song.
/// Equivalent to std::mem::drop(SongEdit)
pub fn finish(self) {}
}
#[derive(Debug, Clone, Copy)]
pub struct OutputConfig {
pub buffer_size: u32,
pub channel_count: NonZeroU16,
pub sample_rate: NonZero<u32>,
pub interpolation: Interpolation,
}
#[derive(Debug, Clone, Copy)]
pub enum PlaybackSettings {
Pattern { idx: u8, should_loop: bool },
Order { idx: u16, should_loop: bool },
}