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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Generate audio data.
//!
//! Normally you only need to use the high level RomBuilder methods:
//! RomBuilder::add_audio_data and RomBuilder::add_audio_player.
//! So check those out first.
//!
//! The audio player that plays the generated audio can be found at:
//! [audio_player.asm](https://github.com/rukai/ggbasm/blob/master/src/audio_player.asm)

use anyhow::{Error, bail};
use crate::ast::{Instruction, Expr};

/// Processes `Vec<AudioLine>` into `Vec<Instruction>` that can be played by the audio player
/// Despite returning Instruction, the only variants used are Db* and Label.
pub fn generate_audio_data(lines: Vec<AudioLine>) -> Result<Vec<Instruction>, Error> {
    // Bail if a clean exit is impossible
    let mut bad_label  = None;
    let mut clean_exit = false;
    for line in &lines {
        match line {
            AudioLine::Disable       => { clean_exit = true }
            AudioLine::PlayFrom (_)  => { clean_exit = true }
            AudioLine::Label (label) => {
                clean_exit = false;
                bad_label = Some(label.clone());
            }
            _ => { }
        }
    }
    if !clean_exit {
        if let Some(bad_label) = bad_label {
            bail!("It is impossible to cleanly exit from label \"{}\". Please ensure `disable` or `playfrom song_label` is used at least once after this label.", bad_label);
        }
        else {
            bail!("Audio has no labels so there is no way to use it.");
        }
    }

    let mut result = vec!();
    for line in lines {
        match line {
            AudioLine::SetRegisters { rest, ch1, ch2, .. } => {
                let mut bytes = vec!();
                if let Some(state) = ch1 {
                    // validate values
                    if state.length > 0x3f {
                        bail!("Length of {} is > 0x3F", state.length);
                    }
                    if state.duty > 3 {
                        bail!("Duty of {} is > 3", state.duty);
                    }
                    if state.envelope_initial_volume > 0x0F {
                        bail!("envelope initial volume of {} is > 0x0F", state.envelope_initial_volume);
                    }
                    if state.envelope_argument > 7 {
                        bail!("envelope initial volume of {} is > 7", state.envelope_argument);
                    }
                    // TODO: Validate ff10 inputs

                    // generate register values
                    let frequency = note_to_frequency(state.octave, &state.note, state.sharp)?;
                    let length = 0x3f - state.length; // make length start at 0 and higher values mean longer length.

                    let ff10 = 0;
                    let ff11 = ((state.duty << 6 & 0b11000000))
                               | length          & 0b00111111;
                    let ff12 = (state.envelope_initial_volume << 4)
                        | (if state.envelope_increase { 1 } else { 0 } << 3)
                        | (state.envelope_argument & 0b00000111);
                    let ff13 = (frequency & 0xFF) as u8;
                    let ff14 = ((frequency >> 8) as u8 & 0b00000111)
                        | if state.enable_length { 1 } else { 0 } << 6
                        | if state.initial       { 1 } else { 0 } << 7;

                    // insert command/argument pairs
                    bytes.push(0x10);
                    bytes.push(ff10);

                    bytes.push(0x11);
                    bytes.push(ff11);

                    bytes.push(0x12);
                    bytes.push(ff12);

                    bytes.push(0x13);
                    bytes.push(ff13);

                    bytes.push(0x14);
                    bytes.push(ff14);
                }
                if let Some(state) = ch2 {
                    // validate values
                    if state.length > 0x3f {
                        bail!("Length of {} is > 0x3F", state.length);
                    }
                    if state.duty > 3 {
                        bail!("Duty of {} is > 3", state.duty);
                    }
                    if state.envelope_initial_volume > 0x0F {
                        bail!("envelope initial volume of {} is > 0x0F", state.envelope_initial_volume);
                    }
                    if state.envelope_argument > 7 {
                        bail!("envelope initial volume of {} is > 7", state.envelope_argument);
                    }

                    // generate register values
                    let frequency = note_to_frequency(state.octave, &state.note, state.sharp)?;
                    let length = 0x3f - state.length; // make length start at 0 and higher values mean longer length.

                    let ff16 = ((state.duty << 6 & 0b11000000))
                               | length          & 0b00111111;
                    let ff17 = (state.envelope_initial_volume << 4)
                        | (if state.envelope_increase { 1 } else { 0 } << 3)
                        | (state.envelope_argument & 0b00000111);
                    let ff18 = (frequency & 0xFF) as u8;
                    let ff19 = ((frequency >> 8) as u8 & 0b00000111)
                        | if state.enable_length { 1 } else { 0 } << 6
                        | if state.initial       { 1 } else { 0 } << 7;

                    // insert command/argument pairs
                    bytes.push(0x16);
                    bytes.push(ff16);

                    bytes.push(0x17);
                    bytes.push(ff17);

                    bytes.push(0x18);
                    bytes.push(ff18);

                    bytes.push(0x19);
                    bytes.push(ff19);
                }

                bytes.push(0xFF);
                bytes.push(rest);

                result.push(Instruction::Db(bytes));
            }
            AudioLine::Rest (rest) => result.push(Instruction::Db (vec!(0xFF, rest))),
            AudioLine::Disable     => result.push(Instruction::Db (vec!(0xFC))),
            AudioLine::PlayFrom (label) => {
                result.push(Instruction::Db (vec!(0xFE)));
                result.push(Instruction::DbExpr16 (Expr::Ident (label)));
            }
            AudioLine::Label (label) => result.push(Instruction::Label (label)),
        }
    }

    Ok(result)
}

/// Parses `&str` into `Vec<AudioLine>`
/// Returns `Err` if the text does not conform to the audio text format.
///
/// Documentation on the input format is given for RomBuilder::add_audio_data.
/// Each AudioLine cooresponds to a line in the input file. Empty lines are skipped.
pub fn parse_audio_text(text: &str) -> Result<Vec<AudioLine>, Error> {
    let mut result = vec!();
    for (i, line) in text.lines().enumerate() {
        let tokens: Vec<&str> = line.split_whitespace().collect();
        // empty lines for formatting are ok
        if tokens.len() == 0 {
            continue;
        }
        let line = match parse_audio_line(line) {
            Ok(line) => line,
            Err(error) => {
                bail!("Invalid command or values on line {}: {}", i + 1, error);
            }
        };
        result.push(line);
    }
    Ok(result)
}

fn parse_audio_line(line: &str) -> Result<AudioLine, Error> {
    let tokens: Vec<&str> = line.split_whitespace().collect();
    if tokens[0].to_lowercase() == "rest" {
        if let Some(value) = tokens.get(1) {
            if let Ok(value) = u8::from_str_radix(value, 16) {
                Ok(AudioLine::Rest (value))
            } else {
                bail!("rest instruction argument is not a hexadecimal integer");
            }
        } else {
            bail!("rest instruction needs an argument");
        }
    } else if tokens[0].to_lowercase() == "playfrom" {
        if tokens.len() == 2 {
            Ok(AudioLine::PlayFrom (tokens[1].to_string()))
        } else {
            bail!("Expected 1 argument for playfrom, however there is {} arguments", tokens.len());
        }
    } else if tokens[0].to_lowercase() == "label" {
        if tokens.len() == 2 {
            Ok(AudioLine::Label (tokens[1].to_string()))
        } else {
            bail!("Expected 1 argument for label, however there is {} arguments", tokens.len());
        }
    } else if tokens[0].to_lowercase() == "disable" {
        Ok(AudioLine::Disable)
    }
    else {
        let line: Vec<char> = line.chars().collect();

        let rest = match u8::from_str_radix(line[0..2].iter().cloned().collect::<String>().as_ref(), 16) {
            Ok(value) => value,
            Err(_)    => bail!("Invalid character for rest"),
        };

        let ch1 = if line.len() < 23 || line[4..23].iter().all(|x| x.is_whitespace()) {
            None
        } else {
            let line = &line;

            // these are the only values unique to channel 1
            let sweep_time = 0;
            let sweep_increase = true;
            let sweep_number = 0;

            // use channel 2 logic as a base for channel 1
            let channel2 = read_channel2(&line[4..])?;
            Some(Channel1State {
                note:                       channel2.note,
                sharp:                      channel2.sharp,
                octave:                     channel2.octave,
                duty:                       channel2.duty,
                length:                     channel2.length,
                envelope_initial_volume:    channel2.envelope_initial_volume,
                envelope_argument:          channel2.envelope_argument,
                envelope_increase:          channel2.envelope_increase,
                enable_length:              channel2.enable_length,
                initial:                    channel2.initial,
                sweep_time, sweep_increase, sweep_number,
            })
        };

        let ch2 = if line.len() < 40 || line[25..40].iter().all(|x| x.is_whitespace()) {
            None
        } else {
            Some(read_channel2(&line[25..])?)
        };

        let ch3 = if line.len() < 41 {
            None
        } else {
            unimplemented!("Channel 3 and 4 are unimplemented");
        };

        let ch4 = None;

        Ok(AudioLine::SetRegisters { rest, ch1, ch2, ch3, ch4 })
    }
}

/// return (Note, sharp, octave)
fn read_note(line: &[char]) -> Result<(Note, bool, u8), Error> {
    let note = match line[0] {
        'a' | 'A' => Note::A,
        'b' | 'B' => Note::B,
        'c' | 'C' => Note::C,
        'd' | 'D' => Note::D,
        'e' | 'E' => Note::E,
        'f' | 'F' => Note::F,
        'g' | 'G' => Note::G,
        _   => bail!("Invalid character for note"),
    };

    let sharp = line[0].is_lowercase();

    let octave = match line[1].to_string().parse() {
        Ok(value) => value,
        Err(_)    => bail!("Invalid character for octave"),
    };

    Ok((note, sharp, octave))
}

/// return channel 2 data
fn read_channel2(line: &[char]) -> Result<Channel2State, Error> {
    let (note, sharp, octave) = read_note(line)?;

    let duty = match line[3].to_string().parse() {
        Ok(value) => value,
        Err(_)    => bail!("Invalid character for duty"),
    };
    if duty > 3 {
        bail!("Duty of {} is > 3", duty);
    }

    let length = match u8::from_str_radix(line[5..7].iter().cloned().collect::<String>().as_ref(), 16) {
        Ok(value) => value,
        Err(_)    => bail!("Invalid character for length"),
    };
    if length > 0x3f {
        bail!("Length of {} is > 0x3F", length);
    }

    let envelope_initial_volume = match u8::from_str_radix(line[8].to_string().as_ref(), 16) {
        Ok(value) => value,
        Err(_)    => bail!("Invalid character for envelope initial volume"),
    };
    if envelope_initial_volume > 0x0F {
        bail!("envelope initial volume of {} is > 0x0F", envelope_initial_volume);
    }

    let envelope_argument = match line[10].to_string().parse() {
        Ok(value) => value,
        Err(_)    => bail!("Invalid character for envelope argument"),
    };
    if envelope_argument > 7 {
        bail!("envelope initial volume of {} is > 7", envelope_argument);
    }

    let envelope_increase = match line[11] {
        'Y' => true,
        'N' => false,
        _   => bail!("Invalid character for envelope increase"),
    };

    let enable_length = match line[13] {
        'Y' => true,
        'N' => false,
        _   => bail!("Invalid character for enable length"),
    };

    let initial = match line[14] {
        'Y' => true,
        'N' => false,
        _   => bail!("Invalid character for initial"),
    };

    Ok(Channel2State {
        note, sharp, octave, duty, length,
        envelope_initial_volume,
        envelope_argument,
        envelope_increase,
        enable_length,
        initial,
    })
}

/// Represents a line from the audio file
pub enum AudioLine {
    SetRegisters {
        rest: u8,
        ch1:  Option<Channel1State>,
        ch2:  Option<Channel2State>,
        ch3:  Option<Channel3State>,
        ch4:  Option<Channel4State>,
    },
    Label (String),
    PlayFrom (String),
    Rest (u8),
    Disable,
}

/// Represents a Note to be played by a channel
pub enum Note {
    A,
    B,
    C,
    D,
    E,
    F,
    G,
}

impl Note {
    pub fn to_string(&self) -> String {
        match self {
            Note::A => String::from("A"),
            Note::B => String::from("B"),
            Note::C => String::from("C"),
            Note::D => String::from("D"),
            Note::E => String::from("E"),
            Note::F => String::from("F"),
            Note::G => String::from("G"),
        }
    }
}

/// Represents the state of channel 1
pub struct Channel1State {
    pub note:                    Note,
    pub sharp:                   bool,
    pub octave:                  u8,
    pub duty:                    u8,
    pub length:                  u8,
    pub envelope_initial_volume: u8,
    pub envelope_argument:       u8,
    pub envelope_increase:       bool,
    pub enable_length:           bool,
    pub initial:                 bool,
    pub sweep_time:              u8,
    pub sweep_increase:          bool,
    pub sweep_number:            u8,
}

/// Represents the state of channel 2
pub struct Channel2State {
    pub note:                    Note,
    pub sharp:                   bool,
    pub octave:                  u8,
    pub duty:                    u8,
    pub length:                  u8,
    pub envelope_initial_volume: u8,
    pub envelope_argument:       u8,
    pub envelope_increase:       bool,
    pub enable_length:           bool,
    pub initial:                 bool,
}

/// Represents the state of channel 3
pub struct Channel3State {
}

/// Represents the state of channel 4
pub struct Channel4State {
}

/// Converts an octave, note and sharp into the 16 bit value the gameboy uses for frequency.
fn note_to_frequency(octave: u8, note: &Note, sharp: bool) -> Result<u16, Error> {
    Ok(match (octave, note, sharp) {
        (3, Note::C, false)  => 44,
        (3, Note::C, true)   => 156,
        (3, Note::D, false)  => 262,
        (3, Note::D, true)   => 363,
        (3, Note::E, false)  => 457,
        (3, Note::F, false)  => 547,
        (3, Note::F, true)   => 631,
        (3, Note::G, false)  => 710,
        (3, Note::G, true)   => 786,
        (3, Note::A, false)  => 854,
        (3, Note::A, true)   => 923,
        (3, Note::B, false)  => 986,
        (4, Note::C, false)  => 1046,
        (4, Note::C, true)   => 1102,
        (4, Note::D, false)  => 1155,
        (4, Note::D, true)   => 1205,
        (4, Note::E, false)  => 1253,
        (4, Note::F, false)  => 1297,
        (4, Note::F, true)   => 1339,
        (4, Note::G, false)  => 1379,
        (4, Note::G, true)   => 1417,
        (4, Note::A, false)  => 1452,
        (4, Note::A, true)   => 1486,
        (4, Note::B, false)  => 1517,
        (5, Note::C, false)  => 1546,
        (5, Note::C, true)   => 1575,
        (5, Note::D, false)  => 1602,
        (5, Note::D, true)   => 1627,
        (5, Note::E, false)  => 1650,
        (5, Note::F, false)  => 1673,
        (5, Note::F, true)   => 1694,
        (5, Note::G, false)  => 1714,
        (5, Note::G, true)   => 1732,
        (5, Note::A, false)  => 1750,
        (5, Note::A, true)   => 1767,
        (5, Note::B, false)  => 1783,
        (6, Note::C, false)  => 1798,
        (6, Note::C, true)   => 1812,
        (6, Note::D, false)  => 1825,
        (6, Note::D, true)   => 1837,
        (6, Note::E, false)  => 1849,
        (6, Note::F, false)  => 1860,
        (6, Note::F, true)   => 1871,
        (6, Note::G, false)  => 1881,
        (6, Note::G, true)   => 1890,
        (6, Note::A, false)  => 1899,
        (6, Note::A, true)   => 1907,
        (6, Note::B, false)  => 1915,
        (7, Note::C, false)  => 1923,
        (7, Note::C, true)   => 1930,
        (7, Note::D, false)  => 1936,
        (7, Note::D, true)   => 1943,
        (7, Note::E, false)  => 1949,
        (7, Note::F, false)  => 1954,
        (7, Note::F, true)   => 1959,
        (7, Note::G, false)  => 1964,
        (7, Note::G, true)   => 1969,
        (7, Note::A, false)  => 1974,
        (7, Note::A, true)   => 1978,
        (7, Note::B, false)  => 1982,
        (8, Note::C, false)  => 1985,
        (8, Note::C, true)   => 1988,
        (8, Note::D, false)  => 1992,
        (8, Note::D, true)   => 1995,
        (8, Note::E, false)  => 1998,
        (8, Note::F, false)  => 2001,
        (8, Note::F, true)   => 2004,
        (8, Note::G, false)  => 2006,
        (8, Note::G, true)   => 2009,
        (8, Note::A, false)  => 2011,
        (8, Note::A, true)   => 2013,
        (8, Note::B, false)  => 2015,
        (octave, note, false) => bail!("Invalid note: {}{}", note.to_string().to_uppercase(), octave),
        (octave, note, true)  => bail!("Invalid note: {}{}", note.to_string().to_lowercase(), octave)
    })
}