Struct musical_note::Octave

source ·
pub struct Octave { /* private fields */ }

Implementations§

octave number should be raw: like

let middle_c = 60u8;
let octave = Octave::new(middle_c/12);
Examples found in repository?
src/lib.rs (line 169)
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
    pub fn from_str(name: &str) -> Option<ResolvedNote> {
        lazy_static! {
            static ref RESOLVED_NOTE_RE: Regex = Regex::new(r"(\w*)(-?\d)").unwrap();
        }
        for cap in RESOLVED_NOTE_RE.captures_iter(name) {
            let tonic = note_from_str(&cap[1])?;
            let (note, accidental) = tonic;
            let mut octave = Octave::from(&cap[2]);
            if note == NoteName::B
                && (accidental == Accidental::Sharp || accidental == Accidental::DoubleSharp)
            {
                octave = Octave::new(octave.raw() + 1);
            } else if note == NoteName::C
                && (accidental == Accidental::Flat || accidental == Accidental::DoubleFlat)
            {
                octave = Octave::new(octave.raw() - 1);
            }
            return Some(Self {
                note,
                accidental,
                octave,
                midi: octave.apply_to_midi_note(NotesMap::get().get_by_note(note, accidental)),
            });
        }
        None
    }
Examples found in repository?
src/lib.rs (line 169)
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
    pub fn from_str(name: &str) -> Option<ResolvedNote> {
        lazy_static! {
            static ref RESOLVED_NOTE_RE: Regex = Regex::new(r"(\w*)(-?\d)").unwrap();
        }
        for cap in RESOLVED_NOTE_RE.captures_iter(name) {
            let tonic = note_from_str(&cap[1])?;
            let (note, accidental) = tonic;
            let mut octave = Octave::from(&cap[2]);
            if note == NoteName::B
                && (accidental == Accidental::Sharp || accidental == Accidental::DoubleSharp)
            {
                octave = Octave::new(octave.raw() + 1);
            } else if note == NoteName::C
                && (accidental == Accidental::Flat || accidental == Accidental::DoubleFlat)
            {
                octave = Octave::new(octave.raw() - 1);
            }
            return Some(Self {
                note,
                accidental,
                octave,
                midi: octave.apply_to_midi_note(NotesMap::get().get_by_note(note, accidental)),
            });
        }
        None
    }

can be negative. Here middle-c considered as C3. So, function return would be in range of -2..9

Examples found in repository?
src/lib.rs (line 213)
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
    pub fn split_midi(midi: u8) -> (u8, Self) {
        (midi % 12, Self::from_midi(midi))
    }
    /// Return raw midi byte.
    pub fn apply_to_midi_note(&self, note_idx: u8) -> u8 {
        self.octave * 12 + (note_idx % 12)
    }
}
impl From<&str> for Octave {
    fn from(value: &str) -> Self {
        let nr = value.parse::<i8>().unwrap();
        return Self {
            octave: (nr + 2) as u8,
        };
    }
}

/// Main function to convert midi to ResolvedNote.
///
/// If accidental is given — it tries to return note with this accidental.
/// Otherwise — it uses Key (and, mainly, Scale) rules for alteration.
pub fn midi_to_note(midi: u8, key: Key, accidental: Option<Accidental>) -> ResolvedNote {
    Note::from_midi(midi, accidental).resolve(key)
}

/// Not yet resolved Note, constructed by MIDI.
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Serialize, Deserialize)]
pub struct Note {
    midi: u8,
    accidental: Option<Accidental>,
    octave: Octave,
}
impl Note {
    pub fn from_midi(midi: u8, accidental: Option<Accidental>) -> Self {
        Self {
            midi,
            accidental,
            octave: Octave::from_midi(midi),
        }
    }

Get note index (C=0, D=2, D#=3, B=11) and octave.

Examples found in repository?
src/lib.rs (line 253)
252
253
254
255
256
257
258
259
260
261
262
263
    pub fn resolve(&self, key: Key) -> ResolvedNote {
        let (midi_note, octave) = Octave::split_midi(self.midi);
        // let midi_note = self.midi % 12;
        let notes_map = NotesMap::get();
        let res = self.resolve_by_accident(&notes_map, midi_note, octave);
        if res.is_some() {
            return res.unwrap();
        }
        let scale = key.resolve_scale(&notes_map);

        scale.resolve_pitch(notes_map, midi_note, octave)
    }

Return raw midi byte.

Examples found in repository?
src/lib.rs (line 179)
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
    pub fn from_str(name: &str) -> Option<ResolvedNote> {
        lazy_static! {
            static ref RESOLVED_NOTE_RE: Regex = Regex::new(r"(\w*)(-?\d)").unwrap();
        }
        for cap in RESOLVED_NOTE_RE.captures_iter(name) {
            let tonic = note_from_str(&cap[1])?;
            let (note, accidental) = tonic;
            let mut octave = Octave::from(&cap[2]);
            if note == NoteName::B
                && (accidental == Accidental::Sharp || accidental == Accidental::DoubleSharp)
            {
                octave = Octave::new(octave.raw() + 1);
            } else if note == NoteName::C
                && (accidental == Accidental::Flat || accidental == Accidental::DoubleFlat)
            {
                octave = Octave::new(octave.raw() - 1);
            }
            return Some(Self {
                note,
                accidental,
                octave,
                midi: octave.apply_to_midi_note(NotesMap::get().get_by_note(note, accidental)),
            });
        }
        None
    }
}

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Serialize, Deserialize)]
pub struct Octave {
    octave: u8,
}
impl Octave {
    /// octave number should be raw: like
    /// ```
    /// # use musical_note::Octave;
    /// let middle_c = 60u8;
    /// let octave = Octave::new(middle_c/12);
    /// ```
    pub fn new(octave: u8) -> Self {
        Self { octave }
    }
    pub fn raw(&self) -> u8 {
        self.octave
    }
    /// can be negative. Here middle-c considered as C3.
    /// So, function return would be in range of -2..9
    pub fn as_midi(&self) -> i8 {
        self.octave as i8 - 2
    }
    pub fn from_midi(midi: u8) -> Self {
        Self { octave: midi / 12 }
    }
    /// Get note index `(C=0, D=2, D#=3, B=11)` and octave.
    pub fn split_midi(midi: u8) -> (u8, Self) {
        (midi % 12, Self::from_midi(midi))
    }
    /// Return raw midi byte.
    pub fn apply_to_midi_note(&self, note_idx: u8) -> u8 {
        self.octave * 12 + (note_idx % 12)
    }
}
impl From<&str> for Octave {
    fn from(value: &str) -> Self {
        let nr = value.parse::<i8>().unwrap();
        return Self {
            octave: (nr + 2) as u8,
        };
    }
}

/// Main function to convert midi to ResolvedNote.
///
/// If accidental is given — it tries to return note with this accidental.
/// Otherwise — it uses Key (and, mainly, Scale) rules for alteration.
pub fn midi_to_note(midi: u8, key: Key, accidental: Option<Accidental>) -> ResolvedNote {
    Note::from_midi(midi, accidental).resolve(key)
}

/// Not yet resolved Note, constructed by MIDI.
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Serialize, Deserialize)]
pub struct Note {
    midi: u8,
    accidental: Option<Accidental>,
    octave: Octave,
}
impl Note {
    pub fn from_midi(midi: u8, accidental: Option<Accidental>) -> Self {
        Self {
            midi,
            accidental,
            octave: Octave::from_midi(midi),
        }
    }
    pub fn resolve(&self, key: Key) -> ResolvedNote {
        let (midi_note, octave) = Octave::split_midi(self.midi);
        // let midi_note = self.midi % 12;
        let notes_map = NotesMap::get();
        let res = self.resolve_by_accident(&notes_map, midi_note, octave);
        if res.is_some() {
            return res.unwrap();
        }
        let scale = key.resolve_scale(&notes_map);

        scale.resolve_pitch(notes_map, midi_note, octave)
    }
    fn resolve_by_accident(
        &self,
        notes_map: &NotesMap,
        midi_note: u8,
        octave: Octave,
    ) -> Option<ResolvedNote> {
        if self.accidental.is_some() {
            let acc = self.accidental.as_ref().unwrap();
            let note = notes_map.get_by_midi(&midi_note).get(&acc);
            if note.is_some() {
                return Some(ResolvedNote::new(
                    note.unwrap().clone(),
                    acc.clone(),
                    octave,
                    octave.apply_to_midi_note(midi_note),
                ));
            }
        }
        None
    }
    pub fn midi(&self) -> u8 {
        self.midi
    }
    pub fn set_midi(&mut self, midi: u8) {
        self.midi = midi;
    }
    pub fn accidental(&self) -> Option<Accidental> {
        self.accidental.clone()
    }
    pub fn set_accidental(&mut self, accidental: Option<Accidental>) {
        self.accidental = accidental;
    }
}
impl From<u8> for Note {
    /// from midi, but without boilerplate.
    fn from(midi: u8) -> Self {
        Self::from_midi(midi, None)
    }
}
impl From<ResolvedNote> for Note {
    fn from(value: ResolvedNote) -> Self {
        Self {
            midi: value.midi,
            accidental: Some(value.accidental),
            octave: value.octave,
        }
    }
}

#[derive(Debug, PartialEq, PartialOrd, Hash, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum Accidental {
    White,
    Sharp,
    DoubleSharp,
    Flat,
    DoubleFlat,
}
impl Accidental {
    pub fn to_string_by_note(&self, note: NoteName) -> String {
        match self {
            Self::DoubleFlat | Self::Flat => {
                if note.need_trunk() {
                    self.to_string().remove(0).to_string()
                } else {
                    self.to_string()
                }
            }
            _ => self.to_string(),
        }
    }
    /// "es" is Flat, "is" is Sharp, "white" is White.
    pub fn from_str(name: &str) -> Option<Self> {
        match name.to_lowercase().as_str() {
            "s" | "es" => Some(Self::Flat),
            "eses" => Some(Self::DoubleFlat),
            "is" => Some(Self::Sharp),
            "isis" => Some(Self::DoubleSharp),
            "white" => Some(Self::White),
            _ => None,
        }
    }
}
impl Default for Accidental {
    fn default() -> Self {
        Self::White
    }
}
impl ToString for Accidental {
    fn to_string(&self) -> String {
        match self {
            Accidental::White => "white".to_string(),
            Accidental::Sharp => "is".to_string(),
            Accidental::DoubleSharp => "isis".to_string(),
            Accidental::Flat => "es".to_string(),
            Accidental::DoubleFlat => "eses".to_string(),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Serialize, Deserialize)]
pub struct Key {
    pub tonic: (NoteName, Accidental),
    pub scale: Scale,
}
impl Key {
    pub fn new(note: NoteName, accidental: Accidental, scale: Scale) -> Self {
        Self {
            tonic: (note, accidental),
            scale,
        }
    }
    /// `[root_midi, root_index]`
    ///
    /// `root_midi` is `u8` in rage 0..12, based on note name and accidental.
    /// `root_index` is `u8` in rage 0..7, based only on note name.
    pub fn get_root(&self) -> [u8; 2] {
        let (tonic_note, tonic_acc) = self.tonic.clone();
        let root_midi = NotesMap::get().get_by_note(tonic_note.clone(), tonic_acc);
        let root_idx = tonic_note.index();
        [root_midi, root_idx]
    }
    /// Returns concrete Scale representation (grades) for the key.
    fn resolve_scale(&self, notes_map: &NotesMap) -> ResolvedScale {
        self.scale.resolve_for_key(notes_map, self)
    }
    /// "as" or "eis" — without octave.
    pub fn from_str(name: &str, scale: Scale) -> Option<Self> {
        Some(Self {
            tonic: note_from_str(name)?,
            scale,
        })
    }
}
impl Default for Key {
    fn default() -> Self {
        Self::new(Default::default(), Default::default(), Default::default())
    }
}
impl From<(&String, Scale)> for Key {
    fn from(value: (&String, Scale)) -> Self {
        let (name, scale) = value;
        Self {
            tonic: note_from_str(name).unwrap(),
            scale,
        }
    }
}

fn note_from_str(name: &str) -> Option<(NoteName, Accidental)> {
    let note = &name[0..1];
    match NoteName::from_str(note) {
        Some(note) => {
            if name.len() <= 1 {
                return Some((note, Accidental::White));
            } else {
                match Accidental::from_str(&name[1..]) {
                    Some(acc) => Some((note, acc)),
                    None => None,
                }
            }
        }
        None => None,
    }
}

#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, PartialOrd, Serialize, Deserialize)]
pub enum NoteName {
    C,
    D,
    E,
    F,
    G,
    A,
    B,
}
impl NoteName {
    fn need_trunk(&self) -> bool {
        match self {
            Self::A | Self::E => true,
            _ => false,
        }
    }
    fn index(self) -> u8 {
        match self {
            Self::C => 0,
            Self::D => 1,
            Self::E => 2,
            Self::F => 3,
            Self::G => 4,
            Self::A => 5,
            Self::B => 6,
        }
    }
    pub fn from_str(name: &str) -> Option<Self> {
        match name.to_uppercase().as_str() {
            "C" => Some(Self::C),
            "D" => Some(Self::D),
            "E" => Some(Self::E),
            "F" => Some(Self::F),
            "G" => Some(Self::G),
            "A" => Some(Self::A),
            "B" => Some(Self::B),
            _ => None,
        }
    }
    fn by_index(mut index: u8) -> Self {
        let names = [
            Self::C,
            Self::D,
            Self::E,
            Self::F,
            Self::G,
            Self::A,
            Self::B,
        ];
        if index > 6 {
            index -= 7;
        }
        names[index as usize].clone()
    }
}
impl Default for NoteName {
    fn default() -> Self {
        Self::C
    }
}
impl ToString for NoteName {
    fn to_string(&self) -> String {
        match self {
            Self::C => String::from("c"),
            Self::D => String::from("d"),
            Self::E => String::from("e"),
            Self::F => String::from("f"),
            Self::G => String::from("g"),
            Self::A => String::from("a"),
            Self::B => String::from("b"),
        }
    }
}

/// Concrete Scale representation, based on the given root note.
///
/// Used to estimate alteration for notes, can be alterated by scale rules.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolvedScale {
    pub key: Key,
    /// 0..12 midi bytes, representing every grade of the scale.
    /// E.g. for C-Dur it would be: `[0, 2, 4, 5, 7, 9, 11]`,
    /// and for A-moll: `[9, 11, 0, 2, 4, 5, 7]`
    pub degree_midi: [u8; 7],
    /// the same, but, holding Tuples of note names and accidentals.
    pub degree_notes: [(NoteName, Accidental); 7],
    /// Collects accidentals, used for degrees to estimate, which
    /// alteration of non-degree notes is preferable.
    /// TODO: think on using this as weight.
    pub used_accidentals: Vec<Accidental>,
}
impl ResolvedScale {
    pub fn resolve_pitch(
        &self,
        notes_map: &NotesMap,
        midi_note: u8,
        octave: Octave,
    ) -> ResolvedNote {
        let note: (NoteName, Accidental);
        let key_root_midi = self.key.get_root()[0];
        match self.degree_midi.binary_search(&midi_note) {
            Ok(note_index) => {
                note = self.degree_notes[note_index];
                // println!("found note from scale {:?} at index {:?}", note, note_index);
            }
            Err(_err) => {
                if midi_note == key_root_midi + 1 && self.key.scale == Scale::Minor {
                    // println!("that is minor II♭");
                    note = notes_map
                        .resolve_note_for_midi(self.degree_notes[1 as usize], midi_note)
                        .unwrap();
                } else if midi_note == (key_root_midi + 8) % 12 && self.key.scale == Scale::Major {
                    // println!("that is major VI♭");
                    let candidate_note = self.degree_notes[5 as usize];
                    note = notes_map
                        .resolve_note_for_midi(candidate_note, midi_note)
                        .unwrap();
                } else {
                    // println!("just search for anything for midi: {:?}", midi_note);
                    note = notes_map
                        .resolve_enharmonic(self.used_accidentals.last().copied(), midi_note);
                }
            }
        }
        ResolvedNote::new(note.0, note.1, octave, octave.apply_to_midi_note(midi_note))
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Deserialize this value from the given Serde deserializer. Read more
Converts to this type from the input type.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.