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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/// General MIDI Level 1 types.
use num;
use num_derive;
use num_derive::FromPrimitive;
use std::ops::{Add, Sub};

use crate::elements::Program;
use redact_composer_core::{derive::Element, IntoCompositionSegment};
use redact_composer_core::{
    elements::PlayNote,
    render::{AdhocRenderer, RenderEngine, Renderer, Result},
    Segment,
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Default renderers used for GM [`Element`]s
/// ([`Instrument`] and [`DrumHit`]).
pub fn renderers() -> RenderEngine {
    RenderEngine::new() + Instrument::renderer() + DrumHit::renderer()
}

/// Types implementing [`Element`].
pub mod elements {
    pub use super::{DrumHit, Instrument};
}

/// Instruments defined according to
/// [GM1 Sound Set](https://www.midi.org/specifications-old/item/gm-level-1-sound-set)
#[derive(Element, Debug, Hash, FromPrimitive, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[allow(missing_docs)]
pub enum Instrument {
    // Piano (0..=7)
    AcousticGrandPiano,
    BrightAcousticPiano,
    ElectricGrandPiano,
    HonkyTonkPiano,
    ElectricPiano1,
    ElectricPiano2,
    Harpsichord,
    Clavi,

    // Chromatic Percussion (8..=15)
    Celesta,
    Glockenspiel,
    MusicBox,
    Vibraphone,
    Marimba,
    Xylophone,
    TubularBells,
    Dulcimer,

    // Organ (16..=23)
    DrawbarOrgan,
    PercussiveOrgan,
    RockOrgan,
    ChurchOrgan,
    ReedOrgan,
    Accordion,
    Harmonica,
    TangoAccordion,

    // Guitar (24..=31)
    AcousticGuitarNylon,
    AcousticGuitarSteel,
    ElectricGuitarJazz,
    ElectricGuitarClean,
    ElectricGuitarMuted,
    OverdrivenGuitar,
    DistortionGuitar,
    GuitarHarmonics,

    // Bass (32..=39)
    AcousticBass,
    ElectricBassFinger,
    ElectricBassPick,
    FretlessBass,
    SlapBass1,
    SlapBass2,
    SynthBass1,
    SynthBass2,

    // Strings (40..=47)
    Violin,
    Viola,
    Cello,
    Contrabass,
    TremoloStrings,
    PizzicatoStrings,
    OrchestralHarp,
    Timpani,

    // Ensemble (48..=55)
    StringEnsemble1,
    StringEnsemble2,
    SynthStrings1,
    SynthStrings2,
    ChoirAahs,
    ChoirOohs,
    SynthVoice,
    OrchestraHit,

    // Brass (56..=63)
    Trumpet,
    Trombone,
    Tuba,
    MutedTrumpet,
    FrenchHorn,
    BrassSection,
    SynthBrass1,
    SynthBrass2,

    // Reed (64..=71)
    SopranoSax,
    AltoSax,
    TenorSax,
    BaritoneSax,
    Oboe,
    EnglishHorn,
    Bassoon,
    Clarinet,

    // Pipe (72..=79)
    Piccolo,
    Flute,
    Recorder,
    PanFlute,
    BlownBottle,
    Shakuhachi,
    Whistle,
    Ocarina,

    // Synth Lead (80..=87)
    LeadSquare,
    LeadSawtooth,
    LeadCalliope,
    LeadChiff,
    LeadCharang,
    LeadVoice,
    LeadFifths,
    LeadBassPlusLead,

    // Synth Pad (88..=95)
    PadNewAge,
    PadWarm,
    PadPolySynth,
    PadChoir,
    PadBowed,
    PadMetallic,
    PadHalo,
    PadSweep,

    // Synth Effects (96..=103)
    FXRain,
    FXSoundtrack,
    FXCrystal,
    FXAtmosphere,
    FXBrightness,
    FXGoblins,
    FXEchoes,
    FXSciFi,

    // Ethnic (104..=111)
    Sitar,
    Banjo,
    Shamisen,
    Koto,
    Kalimba,
    BagPipe,
    Fiddle,
    Shanai,

    // Percussive (112..=119)
    TinkleBell,
    Agogo,
    SteelDrums,
    Woodblock,
    TaikoDrum,
    MelodicTom,
    SynthDrum,
    ReverseCymbal,

    // Sound Effects (120..127)
    GuitarFretNoise,
    BreathNoise,
    Seashore,
    BirdTweet,
    TelephoneRing,
    Helicopter,
    Applause,
    Gunshot,
}

impl From<Instrument> for Program {
    fn from(value: Instrument) -> Program {
        Program(value as u8)
    }
}

impl Instrument {
    /// Renderer that render an [`Instrument`] segment as a [`Program`] with the same timing.
    pub fn renderer() -> impl Renderer<Element = Self> {
        AdhocRenderer::<Self>::new(|segment, _| {
            Result::Ok(vec![
                Program::from(*segment.element).into_segment(segment.timing)
            ])
        })
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// # use redact_composer_midi::gm::Instruments;
/// #
/// let pianos = Instrument::AcousticGrandPiano + Instrument::BrightAcousticPiano;
/// assert_eq!(pianos, Instruments { instruments: vec![Instrument::AcousticGrandPiano, Instrument::BrightAcousticPiano] });
/// ```
impl Add for Instrument {
    type Output = Instruments;

    fn add(self, rhs: Self) -> Self::Output {
        Instruments {
            instruments: vec![self, rhs],
        }
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// # use redact_composer_midi::gm::Instruments;
/// #
/// let pianos = Instrument::AcousticGrandPiano
///                 + Instruments { instruments: vec![Instrument::BrightAcousticPiano] };
/// assert_eq!(pianos, Instruments { instruments: vec![Instrument::AcousticGrandPiano, Instrument::BrightAcousticPiano] });
/// ```
impl Add<Instruments> for Instrument {
    type Output = Instruments;

    fn add(self, rhs: Instruments) -> Self::Output {
        Instruments {
            instruments: vec![self],
        } + rhs
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// #
/// assert_eq!(Instrument::from(0u8), Instrument::AcousticGrandPiano);
/// ```
impl From<u8> for Instrument {
    fn from(value: u8) -> Self {
        num::FromPrimitive::from_u8(value).unwrap()
    }
}

impl From<Instrument> for u8 {
    fn from(value: Instrument) -> Self {
        value as u8
    }
}

/// A thin wrapper around a [`Vec<Instrument>`] with Add/Subtract operations.
#[derive(Debug, Clone, PartialEq)]
pub struct Instruments {
    /// A list of instruments.
    pub instruments: Vec<Instrument>,
}

impl Instruments {
    /// All instruments.
    pub fn all() -> Instruments {
        Instruments {
            instruments: (0..128).map(Instrument::from).collect(),
        }
    }

    /// GM1 piano instruments.
    pub fn piano() -> Instruments {
        Instruments {
            instruments: (0..8).map(Instrument::from).collect(),
        }
    }

    /// GM1 tonal percussive instruments.
    pub fn tonal_percussive() -> Instruments {
        Instruments {
            instruments: (8..16).map(Instrument::from).collect(),
        }
    }

    /// GM1 organ instruments.
    pub fn organ() -> Instruments {
        Instruments {
            instruments: (16..24).map(Instrument::from).collect(),
        }
    }

    /// GM1 guitar instruments.
    pub fn guitar() -> Instruments {
        Instruments {
            instruments: (24..32).map(Instrument::from).collect(),
        }
    }

    /// GM1 bass instruments.
    pub fn bass() -> Instruments {
        Instruments {
            instruments: (32..40).map(Instrument::from).collect(),
        }
    }

    /// GM1 string instruments.
    pub fn strings() -> Instruments {
        Instruments {
            instruments: (40..48).map(Instrument::from).collect(),
        }
    }

    /// GM1 ensemble instruments.
    pub fn ensemble() -> Instruments {
        Instruments {
            instruments: (48..56).map(Instrument::from).collect(),
        }
    }

    /// GM1 brass instruments.
    pub fn brass() -> Instruments {
        Instruments {
            instruments: (56..64).map(Instrument::from).collect(),
        }
    }

    /// GM1 reed instruments.
    pub fn reed() -> Instruments {
        Instruments {
            instruments: (64..72).map(Instrument::from).collect(),
        }
    }

    /// GM1 pipe instruments.
    pub fn pipe() -> Instruments {
        Instruments {
            instruments: (72..80).map(Instrument::from).collect(),
        }
    }

    /// GM1 synth lead instruments.
    pub fn synth_lead() -> Instruments {
        Instruments {
            instruments: (80..88).map(Instrument::from).collect(),
        }
    }

    /// GM1 synth pad instruments.
    pub fn synth_pad() -> Instruments {
        Instruments {
            instruments: (88..96).map(Instrument::from).collect(),
        }
    }

    /// GM1 synth FX instruments.
    pub fn synth_fx() -> Instruments {
        Instruments {
            instruments: (96..104).map(Instrument::from).collect(),
        }
    }

    /// GM1 ethnic instruments.
    pub fn ethnic() -> Instruments {
        Instruments {
            instruments: (104..112).map(Instrument::from).collect(),
        }
    }

    /// GM1 percussive instruments.
    pub fn percussive() -> Instruments {
        Instruments {
            instruments: (112..120).map(Instrument::from).collect(),
        }
    }

    /// GM1 sound FX instruments.
    pub fn sound_fx() -> Instruments {
        Instruments {
            instruments: (120..128).map(Instrument::from).collect(),
        }
    }

    /// Returns "melodic" instruments which have a clear tone, and are not overly percussive.
    pub fn melodic() -> Instruments {
        Self::all()
            - Self::percussive()
            - Self::sound_fx()
            - Self::synth_fx()
            - Instrument::Timpani
            - Instrument::TubularBells
            - Instrument::PadBowed
            - Instrument::LeadFifths
            - Instrument::OrchestraHit
            - Instrument::Kalimba
            - Instrument::GuitarHarmonics
    }
}

impl IntoIterator for Instruments {
    type Item = Instrument;

    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.instruments.into_iter()
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// # use redact_composer_midi::gm::Instruments;
/// #
/// let pianos = Instruments { instruments: vec![Instrument::AcousticGrandPiano] }
///                         + Instruments { instruments: vec![Instrument::BrightAcousticPiano] };
/// assert_eq!(pianos, Instruments { instruments: vec![Instrument::AcousticGrandPiano, Instrument::BrightAcousticPiano] });
/// ```
impl Add for Instruments {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Instruments {
            instruments: self.into_iter().chain(rhs).collect(),
        }
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// # use redact_composer_midi::gm::Instruments;
/// #
/// let pianos = Instruments { instruments: vec![Instrument::AcousticGrandPiano] }
///                         + Instrument::BrightAcousticPiano;
/// assert_eq!(pianos, Instruments { instruments: vec![Instrument::AcousticGrandPiano, Instrument::BrightAcousticPiano] });
/// ```
impl Add<Instrument> for Instruments {
    type Output = Self;

    fn add(self, rhs: Instrument) -> Self::Output {
        Instruments {
            instruments: self.into_iter().chain(vec![rhs]).collect(),
        }
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// # use redact_composer_midi::gm::Instruments;
/// #
/// let no_violins = Instruments { instruments: vec![Instrument::Violin, Instrument::Cello] }
///                         - Instruments { instruments: vec![Instrument::Violin] };
/// assert_eq!(no_violins, Instruments { instruments: vec![Instrument::Cello] });
/// ```
impl Sub for Instruments {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Instruments {
            instruments: self
                .into_iter()
                .filter(|i| !rhs.instruments.contains(i))
                .collect(),
        }
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// # use redact_composer_midi::gm::Instruments;
/// #
/// let no_violins = Instruments { instruments: vec![Instrument::Violin, Instrument::Cello] }
///                         - Instrument::Violin;
/// assert_eq!(no_violins, Instruments { instruments: vec![Instrument::Cello] });
///
/// let instruments = Instruments { instruments: vec![Instrument::AcousticGrandPiano, Instrument::BrightAcousticPiano] };
/// ```
impl Sub<Instrument> for Instruments {
    type Output = Self;

    fn sub(self, rhs: Instrument) -> Self::Output {
        Instruments {
            instruments: self.into_iter().filter(|i| *i != rhs).collect(),
        }
    }
}

/// ##Example
/// ```rust
/// # use redact_composer_midi::gm::elements::Instrument;
/// # use redact_composer_midi::gm::Instruments;
/// #
/// let instruments = Instruments { instruments: vec![Instrument::AcousticGrandPiano, Instrument::BrightAcousticPiano] };
/// let vec_instruments: Vec<Instrument> = instruments.into();
/// assert_eq!(
///     vec_instruments,
///     vec![Instrument::AcousticGrandPiano, Instrument::BrightAcousticPiano]
/// );
/// ```
impl From<Instruments> for Vec<Instrument> {
    fn from(value: Instruments) -> Self {
        value.instruments
    }
}

/// Represents a drum hit. (Similar to [`PlayNote`]).
#[derive(Element, Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DrumHit {
    /// The drum hit sound type.
    pub hit: DrumHitType,
    /// The strength of attack.
    pub velocity: u8,
}

impl DrumHit {
    /// Renderer that renders a [`DrumHit`] as a [`PlayNote`] over the same timing.
    pub fn renderer() -> impl Renderer<Element = Self> {
        AdhocRenderer::<Self>::new(|segment, _| {
            Result::Ok(vec![Segment::new(
                PlayNote {
                    note: segment.element.hit.into(),
                    velocity: segment.element.velocity,
                },
                segment.timing,
            )])
        })
    }
}

/// Percussion key map defined according to
/// [GM1 Sound Set](https://www.midi.org/specifications-old/item/gm-level-1-sound-set)
#[derive(Debug, Hash, FromPrimitive, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[allow(missing_docs)]
pub enum DrumHitType {
    AcousticBassDrum = 35,
    BassDrum,
    SideStick,
    AcousticSnare,
    HandClap,
    ElectricSnare,
    LowFloorTom,
    ClosedHiHat,
    HighFloorTom,
    PedalHiHat,
    LowTom,
    OpenHiHat,
    LowMidTom,
    HighMidTom,
    CrashCymbal1,
    HighTom,
    RideCymbal1,
    ChineseCymbal,
    RideBell,
    Tambourine,
    SplashCymbal,
    Cowbell,
    CrashCymbal2,
    Vibraslap,
    RideCymbal2,
    HighBongo,
    LowBongo,
    MuteHighConga,
    OpenHighConga,
    LowConga,
    HighTimbale,
    LowTimbale,
    HighAgogo,
    LowAgogo,
    Cabasa,
    Maracas,
    ShortWhistle,
    LongWhistle,
    ShortGuiro,
    LongGuiro,
    Claves,
    HighWoodblock,
    LowWoodblock,
    MuteCuica,
    OpenCuica,
    MuteTriangle,
    OpenTriangle,
}

impl From<u8> for DrumHitType {
    fn from(value: u8) -> Self {
        num::FromPrimitive::from_u8(value).unwrap()
    }
}

impl From<DrumHitType> for u8 {
    fn from(value: DrumHitType) -> Self {
        value as u8
    }
}