rumpl 0.3.0

Sample-free General MIDI player and renderer
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
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Idiomatic demo phrases for auditioning a single GM instrument.
//!
//! Rather than playing one universal phrase for every program, each of the 16
//! GM families gets a phrase that suits the kind of music it is usually used
//! for — pianos arpeggiate a chord progression, basses walk a groove, strings
//! sing a legato line, brass stabs a fanfare, pads sustain, and so on. The
//! phrase is written out as a Standard MIDI File carrying the program change,
//! so it can be rendered or played like any other `.mid`.

use anyhow::{Context, Result};
use midly::num::{u4, u7, u15, u24, u28};
use midly::{
  Format, Header, MetaMessage, MidiMessage, Smf, Timing, TrackEvent,
  TrackEventKind,
};

use crate::synth::drums::gm_drum_name;
use crate::synth::patches::gm_program_name;

/// Ticks per quarter note for the generated files.
const TPQ: u32 = 480;

#[derive(Clone, Copy)]
struct Note {
  /// Onset in beats (quarter notes).
  start: f64,
  /// Duration in beats.
  dur: f64,
  key: u8,
  vel: u8,
}

/// Append a sequential melody: `keys` spaced `step` beats apart from `start`.
fn melody(
  out: &mut Vec<Note>,
  start: f64,
  step: f64,
  dur: f64,
  vel: u8,
  keys: &[u8],
) {
  for (i, &key) in keys.iter().enumerate() {
    out.push(Note {
      start: start + step * i as f64,
      dur,
      key,
      vel,
    });
  }
}

/// Append a simultaneous chord.
fn chord(out: &mut Vec<Note>, start: f64, dur: f64, vel: u8, keys: &[u8]) {
  for &key in keys {
    out.push(Note {
      start,
      dur,
      key,
      vel,
    });
  }
}

/// Tempo (BPM) and notes for a program's demo, chosen by GM family.
fn phrase(program: u8) -> (u32, Vec<Note>) {
  let mut n = Vec::new();
  let family = program / 8;
  let bpm = match family {
    0 => {
      // Piano — arpeggiated I–vi–IV–V progression with a sustained tonic.
      for (i, (bass, arp)) in [
        (48u8, [60u8, 64, 67, 72]),
        (45, [57, 60, 64, 69]),
        (41, [53, 57, 60, 65]),
        (43, [55, 59, 62, 67]),
      ]
      .iter()
      .enumerate()
      {
        let s = i as f64 * 2.0;
        chord(&mut n, s, 2.0, 70, &[*bass]);
        melody(&mut n, s, 0.5, 0.5, 88, arp);
      }
      chord(&mut n, 8.0, 2.5, 80, &[48, 60, 64, 67, 72]);
      104
    }
    1 => {
      // Chromatic percussion — a sparkly descending run and a turn.
      melody(
        &mut n,
        0.0,
        0.5,
        0.45,
        96,
        &[84, 83, 81, 79, 77, 76, 74, 72],
      );
      melody(&mut n, 4.0, 0.5, 0.45, 90, &[72, 76, 79, 84]);
      chord(&mut n, 6.0, 1.5, 88, &[72, 76, 79]);
      132
    }
    2 => {
      // Organ — sustained block chords I–IV–V–I with a top line.
      for (i, ch) in [
        [48u8, 55, 60, 64],
        [53, 57, 60, 65],
        [55, 59, 62, 67],
        [48, 55, 60, 64],
      ]
      .iter()
      .enumerate()
      {
        chord(&mut n, i as f64 * 2.0, 2.0, 82, ch);
      }
      melody(&mut n, 0.0, 1.0, 0.9, 96, &[72, 76, 77, 74, 79, 83, 79, 76]);
      96
    }
    3 => {
      // Guitar — fingerpicked arpeggios over a folk progression.
      for (i, (bass, arp)) in [
        (40u8, [52u8, 55, 59, 55]),
        (43, [52, 55, 60, 55]),
        (43, [50, 55, 59, 55]),
        (50, [57, 62, 66, 62]),
      ]
      .iter()
      .enumerate()
      {
        let s = i as f64 * 2.0;
        chord(&mut n, s, 2.0, 78, &[*bass]);
        melody(&mut n, s, 0.5, 0.5, 90, arp);
      }
      100
    }
    4 => {
      // Bass — a syncopated octave-and-fifth groove down low.
      melody(&mut n, 0.0, 0.5, 0.4, 96, &[36, 36, 43, 48, 36, 46, 43, 38]);
      melody(&mut n, 4.0, 0.5, 0.4, 96, &[41, 41, 48, 53, 41, 51, 48, 43]);
      112
    }
    5 => {
      // Strings — a singing, legato solo line.
      melody(&mut n, 0.0, 1.0, 1.1, 84, &[69, 72, 76, 74]);
      melody(&mut n, 4.0, 1.0, 1.1, 84, &[72, 69, 67, 69]);
      chord(&mut n, 8.0, 2.5, 80, &[72]);
      80
    }
    6 => {
      // Ensemble (strings/choir) — lush sustained four-part chords.
      for (i, ch) in [
        [48u8, 55, 64, 67],
        [45, 57, 64, 69],
        [41, 57, 60, 65],
        [43, 55, 59, 67],
      ]
      .iter()
      .enumerate()
      {
        chord(&mut n, i as f64 * 2.0, 2.0, 78, ch);
      }
      chord(&mut n, 8.0, 3.0, 78, &[48, 55, 64, 67]);
      72
    }
    7 => {
      // Brass — punchy fanfare stabs into a rising triad.
      chord(&mut n, 0.0, 0.4, 104, &[60, 64, 67]);
      chord(&mut n, 0.5, 0.4, 100, &[60, 64, 67]);
      chord(&mut n, 1.0, 0.4, 104, &[60, 64, 67]);
      melody(&mut n, 2.0, 0.5, 0.45, 104, &[67, 72, 76, 79]);
      chord(&mut n, 4.0, 2.0, 104, &[60, 64, 67, 72]);
      120
    }
    8 => {
      // Reed — a smooth, swung solo line.
      melody(
        &mut n,
        0.0,
        0.5,
        0.45,
        92,
        &[67, 69, 71, 72, 74, 72, 71, 67],
      );
      melody(
        &mut n,
        4.0,
        0.5,
        0.45,
        92,
        &[65, 67, 69, 71, 72, 69, 67, 65],
      );
      chord(&mut n, 8.0, 1.5, 88, &[64]);
      100
    }
    9 => {
      // Pipe — a light, airy melody up high.
      melody(
        &mut n,
        0.0,
        0.5,
        0.45,
        88,
        &[79, 81, 83, 84, 83, 81, 79, 76],
      );
      melody(&mut n, 4.0, 0.5, 0.45, 88, &[77, 79, 81, 79, 76, 72]);
      112
    }
    10 => {
      // Synth lead — a syncopated, repeated riff.
      melody(
        &mut n,
        0.0,
        0.5,
        0.4,
        100,
        &[72, 75, 79, 75, 72, 75, 79, 84],
      );
      melody(
        &mut n,
        4.0,
        0.5,
        0.4,
        100,
        &[82, 79, 75, 79, 75, 72, 75, 72],
      );
      124
    }
    11 => {
      // Synth pad — slow, sustained maj7 swells.
      chord(&mut n, 0.0, 4.0, 72, &[48, 55, 59, 64]);
      chord(&mut n, 4.0, 4.5, 72, &[41, 57, 60, 65]);
      60
    }
    12 => {
      // Synth effects — a low drone under scattered atmospheric tones.
      chord(&mut n, 0.0, 8.0, 64, &[36]);
      melody(&mut n, 0.0, 2.0, 1.8, 80, &[84, 79, 88, 83]);
      70
    }
    13 => {
      // Ethnic — a modal melody over a sustained drone.
      chord(&mut n, 0.0, 8.0, 70, &[50]);
      melody(
        &mut n,
        0.0,
        0.5,
        0.45,
        90,
        &[62, 64, 65, 67, 69, 67, 65, 64],
      );
      melody(&mut n, 4.0, 0.5, 0.45, 90, &[62, 64, 65, 64, 62, 62]);
      100
    }
    14 => {
      // Percussive (steel drum, bells, …) — a bright repeated riff.
      melody(
        &mut n,
        0.0,
        0.25,
        0.22,
        96,
        &[60, 60, 67, 60, 64, 60, 67, 64],
      );
      melody(
        &mut n,
        2.0,
        0.25,
        0.22,
        96,
        &[60, 60, 67, 72, 67, 64, 67, 60],
      );
      120
    }
    _ => {
      // Sound effects — non-pitched; just trigger the sound a few times.
      chord(&mut n, 0.0, 2.0, 100, &[60]);
      chord(&mut n, 2.0, 2.0, 100, &[67]);
      chord(&mut n, 4.0, 2.0, 100, &[72]);
      90
    }
  };
  (bpm, n)
}

/// GM channel 10 (index 9), where note numbers select percussion sounds.
const DRUM_CHANNEL: u8 = 9;

/// Lowest and highest GM percussion keys (Acoustic Bass Drum … Open Triangle).
const GM_DRUM_KEYS: std::ops::RangeInclusive<u8> = 35..=81;

/// Tempo (BPM) and notes for the drum-kit demo: two bars of a rock groove, a
/// tom fill into a crash, then every GM percussion key in turn.
fn drum_phrase() -> (u32, Vec<Note>) {
  const KICK: u8 = 36;
  const SNARE: u8 = 38;
  const CLOSED_HAT: u8 = 42;
  const OPEN_HAT: u8 = 46;
  const CRASH: u8 = 49;
  // Short gates, as drum parts in real MIDI files usually have.
  const HIT: f64 = 0.1;

  let mut n = Vec::new();
  chord(&mut n, 0.0, HIT, 110, &[CRASH, KICK]);
  for bar in 0..2 {
    let s = bar as f64 * 4.0;
    for eighth in 0..8 {
      let t = s + eighth as f64 * 0.5;
      let last = bar == 1 && eighth == 7;
      let hat = if last { OPEN_HAT } else { CLOSED_HAT };
      let vel = if eighth % 2 == 0 { 96 } else { 72 };
      chord(&mut n, t, HIT, vel, &[hat]);
    }
    chord(&mut n, s + 1.0, HIT, 104, &[SNARE]);
    chord(&mut n, s + 3.0, HIT, 104, &[SNARE]);
    // Kicks on 1 (bar 2; bar 1 already has one with the crash), the "and"
    // of 2, and 3.
    if bar == 1 {
      chord(&mut n, s, HIT, 110, &[KICK]);
    }
    chord(&mut n, s + 1.5, HIT, 96, &[KICK]);
    chord(&mut n, s + 2.0, HIT, 110, &[KICK]);
  }
  // Tom fill down the kit (high tom → low floor tom), landing on a crash.
  melody(
    &mut n,
    8.0,
    0.25,
    HIT,
    100,
    &[50, 50, 48, 48, 47, 47, 43, 41],
  );
  chord(&mut n, 10.0, HIT, 115, &[CRASH, KICK]);

  // Every GM percussion key, one per beat, so each sound can ring out.
  let keys: Vec<u8> = GM_DRUM_KEYS.collect();
  melody(&mut n, 12.0, 1.0, HIT, 100, &keys);
  (120, n)
}

/// Build the demo phrase for `program` as a Standard MIDI File and write it.
pub fn write_demo_midi(program: u8, path: &std::path::Path) -> Result<()> {
  let (bpm, notes) = phrase(program);
  write_midi(bpm, 0, Some(program), &notes, path)
}

/// Write the GM drum-kit demo (channel 10) as a Standard MIDI File.
pub fn write_drum_demo_midi(path: &std::path::Path) -> Result<()> {
  let (bpm, notes) = drum_phrase();
  write_midi(bpm, DRUM_CHANNEL, None, &notes, path)
}

/// File name of the drum-kit demo. Numbered 128 so it sorts after the 128
/// program demos; it is not a GM program.
pub const DRUM_DEMO_FILENAME: &str = "128-drum-kit.mid";

/// Tempo (BPM) and notes for auditioning one percussion sound: four isolated
/// hits from soft to hard, each with room to decay, then a run of eight
/// sixteenths to show how it retriggers.
fn drum_sound_phrase(key: u8) -> (u32, Vec<Note>) {
  const HIT: f64 = 0.1;
  let mut n = Vec::new();
  for (i, vel) in [40u8, 70, 100, 127].into_iter().enumerate() {
    chord(&mut n, i as f64 * 2.0, HIT, vel, &[key]);
  }
  melody(&mut n, 8.0, 0.25, HIT, 100, &[key; 8]);
  (90, n)
}

/// Write the demo of the single percussion sound on `key` (channel 10).
pub fn write_drum_sound_demo_midi(
  key: u8,
  path: &std::path::Path,
) -> Result<()> {
  let (bpm, notes) = drum_sound_phrase(key);
  write_midi(bpm, DRUM_CHANNEL, None, &notes, path)
}

/// Slugged file name for a percussion sound's demo, e.g.
/// `038-acoustic-snare.mid`. `key` must be in `DRUM_KEYS`.
pub fn drum_sound_demo_filename(key: u8) -> String {
  let name = gm_drum_name(key).expect("key outside the GM2 percussion map");
  format!("{key:03}-{}.mid", slug(name))
}

fn write_midi(
  bpm: u32,
  channel: u8,
  program: Option<u8>,
  notes: &[Note],
  path: &std::path::Path,
) -> Result<()> {
  let us_per_quarter = (60_000_000.0 / bpm as f64).round() as u32;
  let ch = u4::from(channel);

  // Collect absolute-tick events, then convert to delta-time track events.
  // Sort key second component orders simultaneous events: setup (0) before
  // note-offs (1) before note-ons (2) before end-of-track (3).
  let mut evs: Vec<(u64, u8, TrackEventKind)> = vec![(
    0,
    0,
    TrackEventKind::Meta(MetaMessage::Tempo(u24::from(us_per_quarter))),
  )];
  if let Some(program) = program {
    evs.push((
      0,
      0,
      TrackEventKind::Midi {
        channel: ch,
        message: MidiMessage::ProgramChange {
          program: u7::from(program),
        },
      },
    ));
  }

  for note in notes {
    let on = (note.start * TPQ as f64).round() as u64;
    let off = ((note.start + note.dur) * TPQ as f64).round() as u64;
    evs.push((
      on,
      2,
      TrackEventKind::Midi {
        channel: ch,
        message: MidiMessage::NoteOn {
          key: u7::from(note.key),
          vel: u7::from(note.vel),
        },
      },
    ));
    evs.push((
      off,
      1,
      TrackEventKind::Midi {
        channel: ch,
        message: MidiMessage::NoteOff {
          key: u7::from(note.key),
          vel: u7::from(0),
        },
      },
    ));
  }

  let end = evs.iter().map(|e| e.0).max().unwrap_or(0) + TPQ as u64;
  evs.push((end, 3, TrackEventKind::Meta(MetaMessage::EndOfTrack)));
  evs.sort_by_key(|e| (e.0, e.1));

  let mut prev = 0u64;
  let mut track = Vec::with_capacity(evs.len());
  for (tick, _, kind) in evs {
    track.push(TrackEvent {
      delta: u28::from((tick - prev) as u32),
      kind,
    });
    prev = tick;
  }

  let smf = Smf {
    header: Header::new(
      Format::SingleTrack,
      Timing::Metrical(u15::from(TPQ as u16)),
    ),
    tracks: vec![track],
  };
  smf
    .save(path)
    .with_context(|| format!("writing {}", path.display()))
}

/// Slugged file name for a program's demo, e.g. `006-harpsichord.mid`.
pub fn demo_filename(program: u8) -> String {
  format!("{program:03}-{}.mid", slug(gm_program_name(program)))
}

/// Lower-case, hyphen-separated ASCII slug of `name`.
fn slug(name: &str) -> String {
  name
    .chars()
    .map(|c| {
      if c.is_ascii_alphanumeric() {
        c.to_ascii_lowercase()
      } else {
        ' '
      }
    })
    .collect::<String>()
    .split_whitespace()
    .collect::<Vec<_>>()
    .join("-")
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::midi;

  #[test]
  fn every_program_has_a_nonempty_phrase() {
    for program in 0..128u8 {
      let (bpm, notes) = phrase(program);
      assert!(bpm > 0);
      assert!(!notes.is_empty(), "program {program} has no notes");
      for note in &notes {
        assert!(note.dur > 0.0);
        assert!(note.key < 128 && note.vel < 128);
      }
    }
  }

  #[test]
  fn filenames_are_slugged_and_unique() {
    let mut names = std::collections::HashSet::new();
    for program in 0..128u8 {
      let name = demo_filename(program);
      assert!(name.ends_with(".mid"));
      assert!(!name.contains(' '));
      assert!(names.insert(name), "duplicate demo filename");
    }
    assert_eq!(demo_filename(6), "006-harpsichord.mid");
  }

  #[test]
  fn written_midi_parses_back_with_the_right_program() {
    let dir = std::env::temp_dir().join("rumpl-demo-test");
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("040.mid");
    write_demo_midi(40, &path).unwrap();

    let info = midi::info(&path).unwrap();
    assert!(info.duration > 0.0);
    assert!(info.note_count > 0);
    assert_eq!(info.channels[0].program, 40);
  }

  #[test]
  fn drum_demo_plays_every_gm_percussion_key_on_channel_10() {
    let (bpm, notes) = drum_phrase();
    assert!(bpm > 0);
    for key in GM_DRUM_KEYS {
      assert!(
        notes.iter().any(|n| n.key == key),
        "drum demo never plays key {key}"
      );
    }

    let dir = std::env::temp_dir().join("rumpl-demo-test");
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join(DRUM_DEMO_FILENAME);
    write_drum_demo_midi(&path).unwrap();

    let info = midi::info(&path).unwrap();
    assert_eq!(info.channels.len(), 1);
    assert!(info.channels[0].is_drums);
    assert_eq!(info.channels[0].note_count, notes.len());
  }

  #[test]
  fn every_drum_sound_has_a_demo_on_channel_10() {
    let dir = std::env::temp_dir().join("rumpl-demo-test");
    std::fs::create_dir_all(&dir).unwrap();
    let mut names = std::collections::HashSet::new();
    for key in crate::synth::drums::DRUM_KEYS {
      let name = drum_sound_demo_filename(key);
      assert!(!name.contains(' '));
      assert!(names.insert(name.clone()), "duplicate filename {name}");

      let path = dir.join(&name);
      write_drum_sound_demo_midi(key, &path).unwrap();
      let info = midi::info(&path).unwrap();
      assert_eq!(info.channels.len(), 1);
      assert!(info.channels[0].is_drums);
      assert!(info.note_count > 0);
    }
    assert_eq!(drum_sound_demo_filename(38), "038-acoustic-snare.mid");
    assert_eq!(drum_sound_demo_filename(42), "042-closed-hi-hat.mid");
  }
}