Skip to main content

music21/
lib.rs

1//! Music theory analysis in Rust, ported from Python's
2//! [music21](https://github.com/cuthbertLab/music21).
3//!
4//! The crate covers the analysis side of music21: pitches, intervals, chords,
5//! keys, scales, roman numerals, chord symbols, figured bass, durations,
6//! meters, tone rows, sieves, tempo marks and voice leading. It keeps
7//! music21's data model and gives music21's answers, so a chord is named, a
8//! numeral realized and a scale spelled the way music21 does it. Beyond
9//! music21, it has tuning systems, regular temperaments and polyrhythms.
10//!
11//! ```
12//! use music21::Chord;
13//!
14//! let chord: Chord = "C E- G B-".parse()?;
15//! assert_eq!(chord.pitched_common_name(), "C-minor seventh chord");
16//! assert_eq!(chord.forte_class().as_deref(), Some("4-26"));
17//! assert_eq!(chord.chord_symbol().as_deref(), Some("Cm7"));
18//! # Ok::<(), music21::Error>(())
19//! ```
20//!
21//! The main types are re-exported at the crate root; each module holds the
22//! rest of its area. Every fallible call returns the crate-wide [`Result`].
23//! Coming from music21's Python, start with the [`guide`].
24//!
25//! # Features
26//!
27//! No features are on by default.
28//!
29//! - `serde` derives `Serialize` and `Deserialize` for the public types.
30//! - `scala-archive` bundles the Scala scale archive (about 4,000 `.scl`
31//!   files, roughly 1 MB) and enables `ScalaArchive::bundled()`.
32//! - `language-detection` bundles music21's excerpts in seven languages
33//!   (about 1.9 MB) and enables `features::language`'s detector, which reads
34//!   a text against them, and music21's language feature, `TX1`, among the
35//!   native extractors. Its `Trigram` needs no excerpt and is always there.
36//! - `musicxml` reads and writes MusicXML (`musicxml::from_musicxml`,
37//!   `musicxml::to_musicxml`).
38//! - `musescore` runs an installed MuseScore to read and write the formats it
39//!   opens and saves; it turns on `musicxml`. MuseScore's own `.mscx` is
40//!   read without it, by `musescore::from_mscx`.
41#![cfg_attr(docsrs, feature(doc_cfg))]
42#![deny(missing_docs)]
43#![deny(missing_debug_implementations)]
44#![forbid(unsafe_code)]
45
46/// The README's examples, run as doctests so they cannot go stale.
47#[cfg(doctest)]
48#[doc = include_str!("../README.md")]
49mod readme {}
50// #![feature(inline_const_pat)]
51// #![feature(negative_impls)]
52// #![feature(specialization)]
53// #![feature(lazy_get)]
54/// ABC notation export helpers.
55pub mod abc;
56/// music21's experimental modules: notes hashed and streams aligned by them.
57pub mod alpha;
58/// Key-finding and compact analysis helpers.
59pub mod analysis;
60/// Articulations: how a note is played.
61pub mod articulations;
62/// Finding the notes in a recording: music21's `audioSearch`.
63pub mod audiosearch;
64/// Barlines and repeat signs.
65pub mod bar;
66pub mod braille;
67pub mod capella;
68/// Chord construction, common-name analysis and chord input conversion traits.
69pub mod chord;
70/// Lead-sheet chord-symbol parsing.
71pub mod chordsymbol;
72/// Clefs: which line a note is written on.
73pub mod clef;
74/// music21's `common`: the plumbing its modules share, which knows no
75/// music.
76pub mod common;
77pub(crate) mod defaults;
78pub(crate) mod display;
79/// Rhythmic duration primitives.
80pub mod duration;
81/// Dynamic marks and the loudness each stands for.
82pub mod dynamics;
83/// music21's user environment: preferences, the settings file and
84/// temporary files.
85pub mod environment;
86/// Error and result types used by the crate.
87pub mod error;
88/// Ornaments and what they play.
89pub mod expressions;
90/// Features of a piece for machine learning: music21's `features`.
91pub mod features;
92
93/// Figured bass: the numbers written under a bass note.
94pub mod figuredbass;
95#[doc = include_str!("guide.md")]
96pub mod guide {}
97/// Humdrum `**kern` scores.
98pub mod humdrum;
99/// Instruments: music21's `instrument` module.
100pub mod instrument;
101
102/// Public interval parsing, naming and transposition helpers.
103pub mod interval;
104/// Public key and key-signature helpers.
105pub mod key;
106/// How a score is laid out on the page: music21's `layout` objects.
107pub mod layout;
108/// LilyPond, written as music21 writes it.
109pub mod lily;
110/// Measures, ties, rests, voices, beams and stems worked out for a score
111/// that does not say them.
112pub mod makenotation;
113/// MEI scores.
114pub mod mei;
115/// A score's title, composer and the rest of what is said about it.
116pub mod metadata;
117/// Time signatures: bar length, beat count, beat length and beat division.
118pub mod meter;
119/// MIDI files read into scores and scores written as MIDI: [`midi::from_midi`]
120/// and [`midi::to_midi`].
121pub mod midi;
122pub mod musedata;
123pub mod musescore;
124/// MusicXML import and export: music21's `musicxml.xmlToM21` and
125/// `musicxml.m21ToXml`.
126#[cfg(feature = "musicxml")]
127pub mod musicxml;
128/// Ties, noteheads, stem direction, colour, lyrics and beams.
129pub mod notation;
130/// Note construction and pitch access helpers.
131pub mod note;
132pub mod noteworthy;
133pub mod omr;
134/// Notes with no pitch, and chords of them.
135pub mod percussion;
136/// Pitch construction, spelling and pitch-space helpers.
137pub mod pitch;
138/// Polyrhythm timing and pitch-set helpers.
139pub mod polyrhythm;
140/// Words and signs telling a player where to go next.
141pub mod repeat;
142/// Rests: silence with a written length.
143pub mod rest;
144/// Roman numeral parsing and compact harmonic analysis.
145pub mod roman;
146/// RomanText, a harmonic analysis written as roman numerals.
147pub mod romantext;
148/// Public scale helpers.
149pub mod scale;
150/// Finding music in streams: lyrics as text.
151pub mod search;
152/// Tone rows, twelve-tone matrices and serial transformations.
153pub mod serial;
154pub mod sieve;
155/// Marks joining several notes: slurs.
156pub mod spanner;
157pub(crate) mod statistics;
158pub(crate) mod stepname;
159/// Streams: notes, chords and other events placed on a timeline, nested as
160/// scores, parts and measures.
161pub mod stream;
162/// How an object is drawn: music21's `style` objects.
163pub mod style;
164/// Notes on the strings and frets of a fretted instrument.
165pub mod tablature;
166/// Metronome marks and tempo-word conventions.
167pub mod tempo;
168/// Lyrics joined into words and lines, and the articles of titles.
169pub mod text;
170/// TinyNotation, a line of notes written as letters and numbers.
171pub mod tinynotation;
172/// A stream's elements as spans of time, and the moments where what sounds
173/// changes.
174pub mod tree;
175/// Tuning-system ratios, labels and frequency helpers.
176pub mod tuningsystem;
177pub mod variant;
178/// Two-voice voice-leading classification and parallel-interval checks.
179pub mod voiceleading;
180pub mod volpiano;
181pub mod volume;
182mod xml;
183// #[macro_use]
184// pub(crate) mod macros;
185
186pub use abc::{
187    abc_chord, abc_duration, abc_note, abc_rest, from_abc, from_abc_number,
188    pitch_name_from_abc_note, pitch_names_from_abc_chord, to_abc,
189};
190pub use analysis::{
191    KeyEstimate, KeyProfile, estimate_key_from_chords, estimate_key_from_chords_with,
192    estimate_key_from_pitches, estimate_key_from_pitches_with,
193};
194pub use analysis::{tonal_certainty, tonal_certainty_from_scores};
195pub use articulations::{Articulation, ArticulationKind};
196pub use bar::{Barline, BarlineType, Ending, RepeatDirection};
197pub use chord::{
198    Chord, ChordResolutionSuggestion, ChordTableAddress, GuitarFingering, GuitarStringFingering,
199    GuitarTuning, GuitarTuningString, IntoNotes, KnownChordType, TriadQuality,
200    format_vector_string,
201};
202pub use chordsymbol::{
203    ChordAlteration, ChordQuality, ChordStepModification, ChordStepModificationType, ChordSymbol,
204    Music21ChordType, chord_symbol_figure_from_chord, chord_symbol_from_chord,
205    known_chord_symbol_types, realize_chord_symbol_durations,
206};
207pub use clef::{Clef, ClefKind};
208pub use defaults::{FloatType, FractionType, IntegerType, Octave, UnsignedIntegerType};
209pub use duration::{
210    Duration, DurationTuple, DurationType, Grace, Tuplet, TupletBracket, TupletShow, TupletType,
211    quarter_length_to_closest_type,
212};
213pub use dynamics::Dynamic;
214pub use error::{Error, Result};
215pub use instrument::{Instrument, SearchLanguage, ensemble_name_by_size};
216pub use interval::{
217    ChromaticInterval, DiatonicInterval, GenericInterval, Interval, IntervalDirection, Specifier,
218    absolute_higher_pitch, absolute_lower_pitch, convert_diatonic_number_to_step, convert_generic,
219    convert_semitone_to_specifier_generic, convert_semitone_to_specifier_generic_microtone,
220    intervals_to_diatonic, notes_to_chromatic, notes_to_generic, parse_specifier,
221    staff_distance_to_generic_number, written_higher_pitch, written_lower_pitch,
222};
223pub use key::{Key, KeySignature, convert_key_string_to_music21_key_string};
224pub use metadata::{Metadata, MetadataContent, MetadataValue};
225pub use meter::{BeamedNote, BeatDivision, MeterTerminal, OffsetAlign, TimeSignature};
226pub use midi::{DEFAULT_TICKS_PER_QUARTER, MidiNote, from_midi, to_midi};
227pub use notation::{
228    Beam, BeamDirection, BeamType, Beams, Justification, Lyric, NoteSize, Notehead, Placement,
229    StemDirection, Syllabic, Tie, TieStyle, TieType,
230};
231pub use note::{IntoNote, Note};
232pub use percussion::{PercussionChord, PercussionNote, Unpitched};
233pub use pitch::{
234    Accidental, AccidentalAttribute, AccidentalDisplayOptions, AccidentalSpecifier,
235    CHROMATIC_PITCH_CLASS_NAMES, Microtone, MicrotoneSpecifier, Pitch, PitchClass,
236    PitchClassSpecifier, PitchName, PitchOptions, convert_pitch_class_to_str, dissonance_score,
237    pitch_class_name, simplify_multiple_enharmonics,
238};
239pub use polyrhythm::{Polyrhythm, PolyrhythmAnalysis, PolyrhythmEvent, PolyrhythmRatioTone};
240pub use repeat::{RepeatExpression, RepeatExpressionKind};
241pub use rest::{FullMeasure, Rest};
242pub use roman::roman_numeral_from_chord;
243pub use roman::{
244    ImpliedQuality, Minor67Default, NumeralAlone, RomanNumeral, analyze_chord,
245    analyze_chord_with_root, identify_as_tonic_or_dominant, roman_inversion_name,
246};
247pub use scale::{
248    BluesForm, DegreeComparison, Scale, ScaleType, Simplification, SolfegVariant, StepScale,
249    WeightedHexatonicBlues,
250};
251pub use serial::{
252    HISTORICAL_ROWS, HistoricalRow, IndexedTransformation, LinkClassification, ToneRow,
253    Transformation, TransformationConvention, TwelveToneMatrix, historical_row_by_name,
254    row_to_matrix,
255};
256pub use sieve::Sieve;
257pub use spanner::{
258    Glissando, LineEnd, LineEnds, MultiRest, OctaveShift, Pedal, PedalForm, PedalObject,
259    PedalObjectKind, PedalType, SlideType, Spanner, SpannerKind,
260};
261pub use stream::{BarTogether, StaffGroup, Stream, StreamElement, StreamEvent, StreamKind};
262pub use tempo::{
263    DEFAULT_TEMPO_VALUES, MetricModulation, MetronomeMark, ModulationSide, TempoText,
264    convert_tempo_by_referent, interpolate_elements,
265};
266pub use tuningsystem::{
267    ALL_TUNING_SYSTEMS, COMMON_EQUAL_TEMPERAMENTS, COMMON_TWELVE_TONE_TUNING_SYSTEMS,
268    EqualDivision, HISTORICAL_TEMPERAMENTS, Monzo, Mos, MosScale, OCTAVE_CENTS, Ratio,
269    TRITAVE_CENTS, Temperament, TuningSystem, Val, moment_of_symmetry_sizes,
270    scala::{ScalaArchive, ScalaDegree, ScalaScale},
271};
272pub use voiceleading::{
273    MotionType, QuartetOptions, VoiceLeadingQuartet, iterate_all_voice_leading_quartets,
274    verticality_at,
275};
276pub use volume::{DynamicContext, Volume, realize_volume};
277
278/// Reads note events from a Standard MIDI File, dropping everything else.
279#[deprecated(
280    since = "0.15.0",
281    note = "use `from_midi` for a score, or `midi::read_midi_bytes` for bare note events"
282)]
283pub fn read_midi_bytes(bytes: &[u8]) -> Result<Vec<MidiNote>> {
284    midi::read_midi_bytes(bytes)
285}
286
287/// Reads note events and the first tempo from a Standard MIDI File.
288#[deprecated(
289    since = "0.15.0",
290    note = "use `from_midi` for a score, or `midi::read_midi_bytes_with_tempo` for bare note events"
291)]
292pub fn read_midi_bytes_with_tempo(bytes: &[u8]) -> Result<(Vec<MidiNote>, Option<FloatType>)> {
293    midi::read_midi_bytes_with_tempo(bytes)
294}
295
296/// Writes note events as a minimal format-0 Standard MIDI File.
297#[deprecated(
298    since = "0.15.0",
299    note = "use `to_midi` for a score, or `midi::write_midi_bytes` for bare note events"
300)]
301pub fn write_midi_bytes(notes: &[MidiNote], tempo_bpm: FloatType) -> Result<Vec<u8>> {
302    midi::write_midi_bytes(notes, tempo_bpm)
303}
304
305/// A stream's notes and chords as MIDI note events, everything else dropped.
306#[deprecated(
307    since = "0.15.0",
308    note = "use `to_midi` for a score, or `midi::midi_notes_from_stream` for bare note events"
309)]
310pub fn midi_notes_from_stream(stream: &Stream) -> Result<Vec<MidiNote>> {
311    midi::midi_notes_from_stream(stream)
312}
313
314/// A stream of notes built from MIDI note events.
315#[deprecated(
316    since = "0.15.0",
317    note = "use `from_midi` for a score, or `midi::stream_from_midi_notes` for bare note events"
318)]
319pub fn stream_from_midi_notes(notes: &[MidiNote]) -> Result<Stream> {
320    midi::stream_from_midi_notes(notes)
321}