playr-app 0.20.0

What playr's Rust frontends share: actions, : commands, key bindings, settings and dispatch
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! The tape as kept between runs, when `persist` names `tape`: every voice's
//! settings and what it reads, by reference. A write loop that was printed
//! into is kept as its shape alone, and resumes silent. Design in
//! `docs/dev/tape-machine-v2-design.md`, section 7.

use std::fmt::Write as _;
use std::path::PathBuf;

use playr_looper::{Window, VOICES, WRITER};

use super::{
    model_name, Division, FxState, Layout, Shape, Source, Speed, TapeState, DELAY_MODELS, LFOS,
    REVERB_MODELS, SLOTS,
};

/// The longest write loop a saved shape may ask for, in seconds: bounds what
/// a damaged row can make playr allocate.
const LONGEST: usize = 3600;

/// What a voice reads, as kept.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Reads {
    #[default]
    Empty,
    /// The write loop; for voice 4, a silent one of [`SavedTape::shape`].
    Write,
    /// A loop read from a file.
    File(Source),
}

/// The tape's settings, and what each voice reads.
#[derive(Debug, Clone, PartialEq)]
pub struct SavedTape {
    /// The tape's rate, which the windows count frames at.
    pub(super) rate: u32,
    /// Writing is kept off: a resumed tape that wrote at once would print
    /// over the write loop before it was heard.
    pub(super) state: TapeState,
    pub(super) reads: [Reads; VOICES],
    /// The silent write loop's frames, range and channels.
    pub(super) shape: Option<(usize, Window, u16)>,
    pub(super) layout: Layout,
}

impl SavedTape {
    /// How many voices read a loop from a file.
    pub fn files(&self) -> usize {
        self.reads
            .iter()
            .filter(|r| matches!(r, Reads::File(_)))
            .count()
    }

    /// The settings kept.
    pub fn state(&self) -> &TapeState {
        &self.state
    }

    /// What each voice reads.
    pub fn reads(&self) -> &[Reads; VOICES] {
        &self.reads
    }

    /// Whether the tape was playing when kept.
    pub fn playing(&self) -> bool {
        self.state.playing
    }

    /// As text, a row a line.
    pub fn encode(&self) -> String {
        let s = &self.state;
        let mut text = format!("rate {}\nplaying {}\n", self.rate, bit(s.playing));
        let w = s.write_window;
        let _ = writeln!(
            text,
            "write {} {} {} {} {}",
            s.feedback, s.wear, s.thin, w.start, w.end
        );
        if let Some((frames, range, channels)) = self.shape {
            let _ = writeln!(
                text,
                "shape {frames} {} {} {channels}",
                range.start, range.end
            );
        }
        for (i, v) in s.voices.iter().enumerate() {
            let _ = writeln!(
                text,
                "voice {i} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}",
                bit(v.on),
                v.rate,
                v.window.start,
                v.window.end,
                v.level,
                v.pan,
                v.send,
                v.wear,
                v.fade,
                bit(v.ping),
                v.slew,
                v.drive,
                v.high_pass,
                v.low_pass,
                v.bell_hz,
                v.bell_gain,
                v.bell_q,
                bit(v.solo),
                bit(v.mute),
                v.delay,
                v.reverb,
            );
        }
        let fx = &s.fx;
        let _ = writeln!(
            text,
            "fx {} {} {} {} {} {} {} {} {} {} {} {} {}",
            model_name(&DELAY_MODELS, fx.delay_model),
            fx.time,
            fx.sync.map_or("-", Division::name),
            fx.feedback,
            fx.tone,
            fx.wow,
            fx.delay_return,
            model_name(&REVERB_MODELS, fx.reverb_model),
            fx.size,
            fx.decay,
            fx.damp,
            fx.reverb_return,
            fx.print,
        );
        // Each LFO's shape and speed; each routed slot's LFO, destination,
        // voice or "-", and depth.
        for (k, (shape, speed)) in s.lfos.iter().enumerate() {
            let _ = match speed {
                Speed::Hz(hz) => writeln!(text, "lfo {k} {} hz {hz}", shape.name()),
                Speed::Sync(part) => writeln!(text, "lfo {k} {} sync {part}", shape.name()),
            };
        }
        for (k, r) in s.routes.iter().enumerate() {
            if let Some(r) = r {
                let (dest, voice) = super::dest_name(r.dest);
                let voice = voice.map_or("-".into(), |v| v.to_string());
                let _ = writeln!(text, "route {k} {} {dest} {voice} {}", r.lfo, r.depth);
            }
        }
        // A lane folded or unfolded by hand, else "-"; then whose drawers are open.
        let folded = self
            .layout
            .folded
            .map(|f| f.map_or("-", |f| if f { "1" } else { "0" }));
        let drawer = self.layout.drawer.map(|d| bit(d).to_string());
        let _ = writeln!(
            text,
            "lanes {} {} {}",
            folded.join(" "),
            drawer.join(" "),
            bit(self.layout.fx)
        );
        for (i, r) in self.reads.iter().enumerate() {
            let _ = match r {
                Reads::Empty => writeln!(text, "reads {i} empty"),
                Reads::Write => writeln!(text, "reads {i} write"),
                // The path is last, as it may hold spaces.
                Reads::File(src) => writeln!(
                    text,
                    "reads {i} file {} {} {} {} {} {}",
                    bit(src.circular),
                    src.rate,
                    src.span.0,
                    src.span.1,
                    src.beats.map_or("-".into(), |b| b.to_string()),
                    src.path.to_string_lossy(),
                ),
            };
        }
        text
    }

    /// From [`SavedTape::encode`]'s text. A row that does not read is left at
    /// its default; text with no rate, or nothing read from a file and no
    /// write loop, is `None`.
    pub fn decode(text: &str) -> Option<SavedTape> {
        let mut rate = None;
        let mut state = TapeState::new(Window::new(0, 0));
        state.voices[0].on = false;
        let mut reads: [Reads; VOICES] = Default::default();
        let mut shape = None;
        let mut layout = Layout::default();
        for line in text.lines() {
            let words: Vec<&str> = line.split(' ').collect();
            match words.as_slice() {
                ["rate", r] => rate = r.parse::<u32>().ok().filter(|r| *r > 0),
                ["playing", b] => state.playing = flag(b).unwrap_or(false),
                ["write", fb, wear, thin, a, b] => {
                    if let (Some(fb), Some(wear), Some(thin), Some(w)) =
                        (num(fb), num(wear), num(thin), window(a, b))
                    {
                        (state.feedback, state.wear, state.thin) = (fb, wear, thin);
                        state.write_window = w;
                    }
                }
                ["shape", frames, a, b, c] => {
                    let frames = frames.parse::<usize>().ok();
                    let channels = c.parse::<u16>().ok().filter(|c| (1..=2).contains(c));
                    if let (Some(f), Some(w), Some(c)) = (frames, window(a, b), channels) {
                        shape = (w.end <= f).then_some((f, w, c));
                    }
                }
                ["voice", i, rest @ ..] => {
                    if let (Some(i), Some(v)) = (index(i), voice(rest)) {
                        state.voices[i] = v;
                    }
                }
                ["fx", rest @ ..] => {
                    if let Some(fx) = fx(rest) {
                        state.fx = fx;
                    }
                }
                // Before the FX lane, rows had no word for it.
                ["lanes", rest @ ..] if [2 * VOICES, 2 * VOICES + 1].contains(&rest.len()) => {
                    let folded: Option<Vec<Option<bool>>> = rest[..VOICES]
                        .iter()
                        .map(|w| match *w {
                            "-" => Some(None),
                            w => flag(w).map(Some),
                        })
                        .collect();
                    let drawer: Option<Vec<bool>> =
                        rest[VOICES..2 * VOICES].iter().map(|w| flag(w)).collect();
                    let fx = rest.get(2 * VOICES).map_or(Some(false), |w| flag(w));
                    if let (Some(f), Some(d), Some(x)) = (folded, drawer, fx) {
                        layout.folded.copy_from_slice(&f);
                        layout.drawer.copy_from_slice(&d);
                        layout.fx = x;
                    }
                }
                ["lfo", k, shape, kind, v] => {
                    let k = k.parse::<usize>().ok().filter(|k| *k < LFOS);
                    let shape = Shape::ALL.into_iter().find(|s| s.name() == *shape);
                    let speed = match (*kind, num(v)) {
                        ("hz", Some(hz)) => Some(Speed::Hz(hz)),
                        ("sync", Some(part)) if part > 0.0 => Some(Speed::Sync(part)),
                        _ => None,
                    };
                    if let (Some(k), Some(shape), Some(speed)) = (k, shape, speed) {
                        state.lfos[k] = (shape, speed);
                    }
                }
                ["route", k, lfo, dest, voice, depth] => {
                    let k = k.parse::<usize>().ok().filter(|k| *k < SLOTS);
                    let lfo = lfo.parse::<usize>().ok().filter(|l| *l < LFOS);
                    let voice = match *voice {
                        "-" => Some(None),
                        v => v.parse::<u8>().ok().map(Some),
                    };
                    let dest = voice.and_then(|v| super::dest_named(dest, v));
                    let depth = num(depth).filter(|d| (-1.0..=1.0).contains(d));
                    if let (Some(k), Some(lfo), Some(dest), Some(depth)) = (k, lfo, dest, depth) {
                        state.routes[k] = Some(super::Route { lfo, dest, depth });
                    }
                }
                ["reads", i, "empty"] => {
                    if let Some(i) = index(i) {
                        reads[i] = Reads::Empty;
                    }
                }
                ["reads", i, "write"] => {
                    if let Some(i) = index(i) {
                        reads[i] = Reads::Write;
                    }
                }
                ["reads", i, "file", circular, r, a, b, beats, path @ ..] => {
                    let path = path.join(" ");
                    let src = (|| {
                        let (start, end) = (a.parse::<u64>().ok()?, b.parse::<u64>().ok()?);
                        let beats = match *beats {
                            "-" => None,
                            b => Some(b.parse::<u32>().ok()?),
                        };
                        let path = PathBuf::from(path);
                        if start >= end || path.as_os_str().is_empty() {
                            return None;
                        }
                        Some(Source {
                            name: playr_core::samples::name_for(&path),
                            path,
                            rate: r.parse::<u32>().ok().filter(|r| *r > 0)?,
                            span: (start, end),
                            circular: flag(circular)?,
                            voice: None,
                            beats,
                        })
                    })();
                    if let (Some(i), Some(src)) = (index(i), src) {
                        reads[i] = Reads::File(src);
                    }
                }
                _ => {}
            }
        }
        let rate = rate?;
        let shape = shape.filter(|(f, ..)| *f <= LONGEST * rate as usize);
        // Voice 4 reads the write loop alone, and a silent one needs a shape.
        if matches!(reads[WRITER], Reads::Write) && shape.is_none() {
            reads[WRITER] = Reads::Empty;
        }
        let write = !matches!(reads[WRITER], Reads::Empty);
        for (i, r) in reads.iter_mut().enumerate() {
            if i != WRITER && *r == Reads::Write && !write {
                *r = Reads::Empty;
            }
        }
        for (i, r) in reads.iter().enumerate() {
            state.own[i] = i != WRITER && matches!(r, Reads::File(_));
            state.empty[i] = *r == Reads::Empty;
        }
        state.write = false;
        let shape = shape.filter(|_| reads[WRITER] == Reads::Write);
        let saved = SavedTape {
            rate,
            state,
            reads,
            shape,
            layout,
        };
        (saved.files() > 0 || saved.shape.is_some()).then_some(saved)
    }
}

fn bit(b: bool) -> u8 {
    u8::from(b)
}

fn flag(word: &str) -> Option<bool> {
    match word {
        "0" => Some(false),
        "1" => Some(true),
        _ => None,
    }
}

fn num(word: &str) -> Option<f32> {
    word.parse::<f32>().ok().filter(|v| v.is_finite())
}

fn index(word: &str) -> Option<usize> {
    word.parse::<usize>().ok().filter(|i| *i < VOICES)
}

fn window(a: &str, b: &str) -> Option<Window> {
    let (a, b) = (a.parse::<usize>().ok()?, b.parse::<usize>().ok()?);
    (a <= b).then(|| Window::new(a, b))
}

/// A voice's settings, from the words after its index.
fn voice(words: &[&str]) -> Option<super::VoiceState> {
    // Before the effects, rows ended at mute: their sends are 0.
    let (words, sends) = match words.len() {
        19 => (words, ["0", "0"]),
        21 => (&words[..19], [words[19], words[20]]),
        _ => return None,
    };
    let [on, rate, a, b, level, pan, send, wear, fade, ping, slew, drive, hp, lp, bell, gain, q, solo, mute] =
        words
    else {
        return None;
    };
    let [delay, reverb] = sends;
    Some(super::VoiceState {
        on: flag(on)?,
        rate: num(rate)?,
        window: window(a, b)?,
        level: num(level)?,
        pan: num(pan)?,
        send: num(send)?,
        wear: num(wear)?,
        fade: num(fade)?,
        ping: flag(ping)?,
        slew: num(slew)?,
        drive: num(drive)?,
        high_pass: num(hp)?,
        low_pass: num(lp)?,
        bell_hz: num(bell)?,
        bell_gain: num(gain)?,
        bell_q: num(q)?,
        solo: flag(solo)?,
        mute: flag(mute)?,
        delay: num(delay)?,
        reverb: num(reverb)?,
    })
}

/// The model `table` names `word`.
fn named<M: Copy>(table: &[(&str, M)], word: &str) -> Option<M> {
    table.iter().find(|m| m.0 == word).map(|m| m.1)
}

/// The effects' settings, from the words after `fx`.
fn fx(words: &[&str]) -> Option<FxState> {
    let [dm, time, sync, fb, tone, wow, dr, rm, size, decay, damp, rr, print] = words else {
        return None;
    };
    Some(FxState {
        delay_model: named(&DELAY_MODELS, dm)?,
        time: num(time)?,
        sync: match *sync {
            "-" => None,
            w => Some(*Division::ALL.iter().find(|d| d.name() == w)?),
        },
        feedback: num(fb)?,
        tone: num(tone)?,
        wow: num(wow)?,
        delay_return: num(dr)?,
        reverb_model: named(&REVERB_MODELS, rm)?,
        size: num(size)?,
        decay: num(decay)?,
        damp: num(damp)?,
        reverb_return: num(rr)?,
        print: num(print)?,
    })
}