bliplib 0.2.5

The Bizarre Language for Intermodulation Programming (BLIP)
Documentation
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#![allow(dead_code)]

use std::{
    error::Error,
    fmt::Debug,
    fs::File,
    io::{self, Cursor, Read, stdin},
    ops::Not,
    str::FromStr,
};

use anyhow::anyhow;
use bliplib::compiler::Expression;
use clap::Parser;
use derive_wrapper::AsRef;
use getset::Getters;
use hound::SampleFormat;
use mp3lame_encoder::{Bitrate, Quality};
use nom::{
    Finish, Parser as P,
    branch::alt,
    bytes::complete::tag,
    character::complete::{char, u16, usize},
    combinator::{rest, success, value},
    error::ErrorKind,
    sequence::preceded,
};
use nom_locate::{LocatedSpan, position};
use strum::{EnumDiscriminants, EnumIter, EnumString, IntoDiscriminant, IntoStaticStr};
use thiserror::Error;

const DEFAULT_INSTRUMENT: &str = "sin(2*pi()*(442*2^((n+1)/N))*t)";
const DEFAULT_LENGTH: &str = "2^(2-log(2, l))*(60/T)";

#[derive(Debug, Parser)]
#[command(version, author, about)]
pub(super) enum Cli {
    /// Play a song
    Play(PlayOpts),
    /// Check for typos
    Check(PlayOpts),
    /// Export a song to an audio file or stdout
    Export(ExportOpts),
    /// Memo menu for examples and general help about syntax and supported audio formats
    #[command(subcommand)]
    Memo(MemoKind),
}

#[derive(Debug, Parser, Clone, Getters)]
#[getset(get = "pub(super)")]
pub(super) struct PlayOpts {
    /// Use this sheet music [default: stdin]
    #[command(flatten)]
    input: InputGroup<false>,
    /// Set available notes ("a,b,c" for example)
    #[arg(short, long, value_delimiter = ',')]
    notes: Vec<String>,
    /// Set the signal expression (instrument) used to generate music samples
    #[arg(short, long, default_value = DEFAULT_INSTRUMENT)]
    instrument: Expression,
    /// Set the expression used to generate note lengths in seconds
    #[arg(short, long, default_value = DEFAULT_LENGTH)]
    length: Expression,
    /// Add a variable named VARIABLE (a single letter) and set its initial value to VALUE
    #[arg(short, long = "variable", value_name = "VARIABLE=VALUE", value_parser = parse_key_val::<'=', Letter, f64>)]
    #[getset(skip)]
    variables: Vec<(Letter, f64)>,
    /// Add a macro named NAME (single character, not alphanumeric) which expands to EXPANSION when called in sheet music
    #[arg(short, long = "macro", value_name = "NAME:EXPANSION", value_parser = parse_key_val::<':', NotALetter, String>)]
    #[getset(skip)]
    macros: Vec<(NotALetter, String)>,
    /// Add a slope expression named NAME which mutates the VARIABLE with the result of EXPR each frame
    #[arg(short, long = "slope", value_name = "NAME:VARIABLE=EXPR", value_parser = parse_key_tuple::<LetterString, Letter, Expression>)]
    #[getset(skip)]
    slopes: Vec<(LetterString, (Letter, Expression))>,
}

impl PlayOpts {
    pub(super) fn variables(&self) -> impl Iterator<Item = (&char, &f64)> {
        self.variables.iter().map(|(c, f)| (c.as_ref(), f))
    }

    pub(super) fn macros(&self) -> impl Iterator<Item = (&char, &String)> {
        self.macros.iter().map(|(c, s)| (c.as_ref(), s))
    }

    pub(super) fn slopes(&self) -> impl Iterator<Item = (&String, (&char, &Expression))> {
        self.slopes
            .iter()
            .map(|(name, (v, e))| (name.as_ref(), (v.as_ref(), e)))
    }
}

impl<const CREATE_IF_NOT_EXISTS: bool> InputGroup<CREATE_IF_NOT_EXISTS>
where
    Self: Clone,
{
    pub(super) fn get(&self) -> Box<dyn Read> {
        self.input
            .as_ref()
            .map(|i| Box::new(i.clone().0) as Box<dyn Read>)
            .or(self
                .sheet_music_string
                .as_ref()
                .map(|s| Box::new(Cursor::new(s.clone())) as Box<dyn Read>))
            .unwrap_or(Box::new(stdin()))
    }
}

#[derive(Debug, Clone, Copy, AsRef)]
struct Letter(char);

#[derive(Debug, Error)]
enum LetterError {
    #[error("the character '{0}' should be a letter")]
    Char(char),
    #[error("no characters found")]
    Empty,
}

impl FromStr for Letter {
    type Err = LetterError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let c = s.chars().next().ok_or(Self::Err::Empty)?;
        c.is_alphabetic()
            .then_some(c)
            .map(Self)
            .ok_or(Self::Err::Char(c))
    }
}

#[derive(Debug, Clone, Copy, AsRef)]
struct NotALetter(char);

#[derive(Debug, Error)]
enum NotALetterError {
    #[error("the character '{0}' should not be a letter")]
    Char(char),
    #[error("no characters found")]
    Empty,
}

impl FromStr for NotALetter {
    type Err = NotALetterError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let c = s.chars().next().ok_or(Self::Err::Empty)?;
        c.is_alphabetic()
            .not()
            .then_some(c)
            .map(Self)
            .ok_or(Self::Err::Char(c))
    }
}

#[derive(Debug, Clone, AsRef)]
struct LetterString(String);

#[derive(Debug, Error)]
enum LetterStringError {
    #[error("the string \"{0}\" should be only letters")]
    String(String),
    #[error("no characters found")]
    Empty,
}

impl FromStr for LetterString {
    type Err = LetterStringError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.is_empty()
            .not()
            .then_some(
                s.chars()
                    .all(|c| c.is_alphabetic())
                    .then_some(s)
                    .map(str::to_string)
                    .map(Self)
                    .ok_or(Self::Err::String(s.to_string())),
            )
            .ok_or(Self::Err::Empty)?
    }
}

/// Parse a single key-value pair
///
/// From https://github.com/clap-rs/clap/blob/6b12a81bafe7b9d013b06981f520ab4c70da5510/examples/typed-derive.rs
fn parse_key_val<const SEP: char, T, U>(
    s: &str,
) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
where
    T: std::str::FromStr,
    T::Err: Error + Send + Sync + 'static,
    U: std::str::FromStr,
    U::Err: Error + Send + Sync + 'static,
{
    let pos = s
        .find(SEP)
        .ok_or_else(|| format!("invalid KEY{SEP}value: no `{SEP}` found in `{s}`"))?;
    Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}

fn parse_key_tuple<T, U1, U2>(
    s: &str,
) -> Result<(T, (U1, U2)), Box<dyn Error + Send + Sync + 'static>>
where
    T: std::str::FromStr,
    T::Err: Error + Send + Sync + 'static,
    U1: std::str::FromStr,
    U1::Err: Error + Send + Sync + 'static,
    U2: std::str::FromStr,
    U2::Err: Error + Send + Sync + 'static,
{
    let pos = s
        .find(':')
        .ok_or_else(|| format!("invalid KEY:value, no `:` found in `{s}`"))?;
    Ok((
        s[..pos].parse()?,
        parse_key_val::<'=', _, _>(&s[pos + 1..])?,
    ))
}

#[derive(Debug, Parser, Clone)]
#[group(required = false, multiple = false)]
pub(super) struct InputGroup<const CREATE_IF_NOT_EXISTS: bool> {
    /// Set the path to your sheet music file [default: stdin]
    input: Option<ClonableFile<CREATE_IF_NOT_EXISTS>>,
    /// Use this sheet music instead of reading from a file or stdin
    #[arg(short = 'c')]
    sheet_music_string: Option<String>,
}

#[derive(Debug)]
pub(super) struct ClonableFile<const CREATE_IF_NOT_EXISTS: bool>(File);

impl<const CREATE_IF_NOT_EXISTS: bool> Clone for ClonableFile<CREATE_IF_NOT_EXISTS> {
    fn clone(&self) -> Self {
        Self(self.0.try_clone().expect("cloning file handle"))
    }
}

impl<const CREATE_IF_NOT_EXISTS: bool> FromStr for ClonableFile<CREATE_IF_NOT_EXISTS> {
    type Err = io::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match CREATE_IF_NOT_EXISTS {
            true => File::create(s),
            false => File::open(s),
        }
        .map(Self)
    }
}

impl<const CREATE_IF_NOT_EXISTS: bool> From<ClonableFile<CREATE_IF_NOT_EXISTS>> for File {
    fn from(value: ClonableFile<CREATE_IF_NOT_EXISTS>) -> Self {
        value.0
    }
}

#[derive(Debug, Parser, Clone)]
pub(super) struct ExportOpts {
    #[command(flatten)]
    pub(super) playopts: PlayOpts,
    /// Audio format to use
    #[cfg_attr(
        feature = "mp3",
        arg(default_value = "mp3 --bitrate 128 --quality best")
    )]
    #[cfg_attr(
        not(feature = "mp3"),
        cfg_attr(feature = "raw", arg(default_value = "raw mulaw"))
    )]
    #[arg(short, long, value_parser = audio_format_parser)]
    pub(super) format: AudioFormat,
    /// Output file [default: stdout]
    #[arg(short, long)]
    pub(super) output: Option<ClonableFile<true>>,
}

#[derive(Clone, EnumDiscriminants)]
#[strum_discriminants(
    derive(EnumString, IntoStaticStr, EnumIter),
    strum(serialize_all = "lowercase")
)]
pub(super) enum AudioFormat {
    Mp3 {
        bitrate: Bitrate,
        quality: Quality,
    },
    Wav {
        bps: u16,
        sample_format: SampleFormat,
    },
    Flac {
        bps: usize,
    },
    Raw(RawAudioFormat),
}

impl Debug for AudioFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Raw(r) => f.debug_tuple("Raw").field(r).finish(),
            _ => self.discriminant().fmt(f),
        }
    }
}

impl Default for AudioFormat {
    fn default() -> Self {
        AudioFormat::Raw(Default::default())
    }
}

fn audio_format_parser(input: &str) -> Result<AudioFormat, anyhow::Error> {
    fn mp3<'a>() -> impl P<
        LocatedSpan<&'a str>,
        Output = AudioFormat,
        Error = nom::error::Error<LocatedSpan<&'a str>>,
    > {
        preceded(
            tag::<&'a str, LocatedSpan<&'a str>, nom::error::Error<LocatedSpan<&'a str>>>(
                AudioFormatDiscriminants::Mp3.into(),
            ),
            u16.or(success(320))
                .and(
                    alt((
                        value(Quality::Best, tag("b")),
                        value(Quality::SecondBest, tag("sb")),
                        value(Quality::NearBest, tag("nb")),
                        value(Quality::VeryNice, tag("v")),
                        value(Quality::Nice, tag("n")),
                        value(Quality::Good, tag("g")),
                        value(Quality::Decent, tag("d")),
                        value(Quality::Ok, tag("o")),
                        value(Quality::SecondWorst, tag("sw")),
                        value(Quality::Worst, tag("w")),
                    ))
                    .or(success(Quality::Good)),
                )
                .and(position)
                .map_res(|((b, q), p)| {
                    Ok(AudioFormat::Mp3 {
                        bitrate: match b {
                            8 => Bitrate::Kbps8,
                            16 => Bitrate::Kbps16,
                            24 => Bitrate::Kbps24,
                            32 => Bitrate::Kbps32,
                            40 => Bitrate::Kbps40,
                            48 => Bitrate::Kbps48,
                            64 => Bitrate::Kbps64,
                            80 => Bitrate::Kbps80,
                            96 => Bitrate::Kbps96,
                            112 => Bitrate::Kbps112,
                            128 => Bitrate::Kbps128,
                            160 => Bitrate::Kbps160,
                            192 => Bitrate::Kbps192,
                            224 => Bitrate::Kbps224,
                            256 => Bitrate::Kbps256,
                            320 => Bitrate::Kbps320,
                            _ => return Err(nom::error::Error::new(p, ErrorKind::Verify)),
                        },
                        quality: q,
                    })
                }),
        )
    }
    fn wav<'a>() -> impl P<
        LocatedSpan<&'a str>,
        Output = AudioFormat,
        Error = nom::error::Error<LocatedSpan<&'a str>>,
    > {
        preceded(
            tag::<&'a str, LocatedSpan<&'a str>, nom::error::Error<LocatedSpan<&'a str>>>(
                AudioFormatDiscriminants::Wav.into(),
            ),
            u16.or(success(32))
                .and(value(SampleFormat::Int, char('i')).or(success(SampleFormat::Float)))
                .map(|(bps, sample_format)| AudioFormat::Wav { bps, sample_format }),
        )
    }
    fn flac<'a>() -> impl P<
        LocatedSpan<&'a str>,
        Output = AudioFormat,
        Error = nom::error::Error<LocatedSpan<&'a str>>,
    > {
        preceded(
            tag::<&'a str, LocatedSpan<&'a str>, nom::error::Error<LocatedSpan<&'a str>>>(
                AudioFormatDiscriminants::Flac.into(),
            ),
            usize.or(success(16)).map(|bps| AudioFormat::Flac { bps }),
        )
    }
    fn parser<'a>() -> impl P<
        LocatedSpan<&'a str>,
        Output = AudioFormat,
        Error = nom::error::Error<LocatedSpan<&'a str>>,
    > {
        alt((
            mp3::<'a>(),
            wav::<'a>(),
            flac::<'a>(),
            rest.map_res(|r: LocatedSpan<&'a str>| {
                Ok::<AudioFormat, nom::error::Error<LocatedSpan<&'a str>>>(AudioFormat::Raw(
                    (*r == "raw")
                        .then_some(Default::default())
                        .ok_or(nom::error::Error::new(r, ErrorKind::Verify))
                        .or(RawAudioFormat::try_from(*r)
                            .map_err(|_| nom::error::Error::new(r, ErrorKind::Verify)))?,
                ))
            }),
        ))
    }
    parser()
        .parse_complete(LocatedSpan::new(input))
        .finish()
        .map(|(_, o)| o)
        .map_err(|e| anyhow!("{e:?}"))
}

#[derive(Debug, Parser, Clone, EnumString, Default, EnumIter, IntoStaticStr)]
#[strum(ascii_case_insensitive)]
pub(super) enum RawAudioFormat {
    ALaw,
    F32Be,
    F32Le,
    F64Be,
    F64Le,
    #[default]
    MuLaw,
    S8,
    S16Be,
    S16Le,
    S24Be,
    S24Le,
    S32Be,
    S32Le,
    U8,
    U16Be,
    U16Le,
    U24Be,
    U24Le,
    U32Be,
    U32Le,
}

#[derive(Debug, Parser, Clone)]
pub(super) enum MemoKind {
    #[command(flatten)]
    Syntax(SyntaxTarget),
    /// Show a list of examples or a specific example from the list
    Examples { n: Option<u8> },
    /// Print all available formats
    Formats,
}

#[derive(Debug, Parser, Clone)]
pub(super) enum SyntaxTarget {
    /// Print BLIP's grammar
    Blip,
    #[command(flatten)]
    Expressions(FastEvalSyntaxSection),
}

#[derive(Debug, Parser, Clone)]
pub(super) enum FastEvalSyntaxSection {
    /// Print available functions and constants for expressions
    Functions,
    /// Print available operators for expressions
    Ops,
    /// Print available literals for expressions
    Literals,
}