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 mod corpus;
78pub(crate) mod defaults;
79pub(crate) mod display;
80/// Rhythmic duration primitives.
81pub mod duration;
82/// Dynamic marks and the loudness each stands for.
83pub mod dynamics;
84/// music21's user environment: preferences, the settings file and
85/// temporary files.
86pub mod environment;
87/// Error and result types used by the crate.
88pub mod error;
89/// Ornaments and what they play.
90pub mod expressions;
91/// Features of a piece for machine learning: music21's `features`.
92pub mod features;
93
94/// Figured bass: the numbers written under a bass note.
95pub mod figuredbass;
96#[doc = include_str!("guide.md")]
97pub mod guide {}
98/// Graphs of a score's data: what music21's `graph` plots.
99pub mod graph;
100/// Humdrum `**kern` scores.
101pub mod humdrum;
102/// Instruments: music21's `instrument` module.
103pub mod instrument;
104
105/// Public interval parsing, naming and transposition helpers.
106pub mod interval;
107/// Public key and key-signature helpers.
108pub mod key;
109/// How a score is laid out on the page: music21's `layout` objects.
110pub mod layout;
111/// LilyPond, written as music21 writes it.
112pub mod lily;
113/// Measures, ties, rests, voices, beams and stems worked out for a score
114/// that does not say them.
115pub mod makenotation;
116/// MEI scores.
117pub mod mei;
118/// A score's title, composer and the rest of what is said about it.
119pub mod metadata;
120/// Time signatures: bar length, beat count, beat length and beat division.
121pub mod meter;
122/// MIDI files read into scores and scores written as MIDI: [`midi::from_midi`]
123/// and [`midi::to_midi`].
124pub mod midi;
125pub mod musedata;
126pub mod musescore;
127/// MusicXML import and export: music21's `musicxml.xmlToM21` and
128/// `musicxml.m21ToXml`.
129#[cfg(feature = "musicxml")]
130pub mod musicxml;
131/// Ties, noteheads, stem direction, colour, lyrics and beams.
132pub mod notation;
133/// Note construction and pitch access helpers.
134pub mod note;
135pub mod noteworthy;
136pub mod omr;
137/// Notes with no pitch, and chords of them.
138pub mod percussion;
139/// Pitch construction, spelling and pitch-space helpers.
140pub mod pitch;
141/// Polyrhythm timing and pitch-set helpers.
142pub mod polyrhythm;
143/// Words and signs telling a player where to go next.
144pub mod repeat;
145/// Rests: silence with a written length.
146pub mod rest;
147/// Roman numeral parsing and compact harmonic analysis.
148pub mod roman;
149/// RomanText, a harmonic analysis written as roman numerals.
150pub mod romantext;
151/// Public scale helpers.
152pub mod scale;
153/// Finding music in streams: lyrics as text.
154pub mod search;
155/// Tone rows, twelve-tone matrices and serial transformations.
156pub mod serial;
157pub mod sieve;
158/// What decides which of two things comes first in a stream: music21's
159/// `sorting`.
160pub mod sorting;
161/// Marks joining several notes: slurs.
162pub mod spanner;
163pub(crate) mod statistics;
164pub(crate) mod stepname;
165/// Streams: notes, chords and other events placed on a timeline, nested as
166/// scores, parts and measures.
167pub mod stream;
168/// How an object is drawn: music21's `style` objects.
169pub mod style;
170/// Notes on the strings and frets of a fretted instrument.
171pub mod tablature;
172/// Metronome marks and tempo-word conventions.
173pub mod tempo;
174/// Lyrics joined into words and lines, and the articles of titles.
175pub mod text;
176/// TinyNotation, a line of notes written as letters and numbers.
177pub mod tinynotation;
178/// A stream's elements as spans of time, and the moments where what sounds
179/// changes.
180pub mod tree;
181/// Tuning-system ratios, labels and frequency helpers.
182pub mod tuningsystem;
183pub mod variant;
184/// Two-voice voice-leading classification and parallel-interval checks.
185pub mod voiceleading;
186pub mod volpiano;
187pub mod volume;
188mod xml;
189// #[macro_use]
190// pub(crate) mod macros;
191
192pub use abc::{
193    abc_chord, abc_duration, abc_note, abc_rest, from_abc, from_abc_number,
194    pitch_name_from_abc_note, pitch_names_from_abc_chord, to_abc,
195};
196pub use analysis::{
197    KeyEstimate, KeyProfile, estimate_key_from_chords, estimate_key_from_chords_with,
198    estimate_key_from_pitches, estimate_key_from_pitches_with,
199};
200pub use analysis::{tonal_certainty, tonal_certainty_from_scores};
201pub use articulations::{Articulation, ArticulationKind};
202pub use bar::{Barline, BarlineType, BracketPlace, Ending, RepeatDirection};
203pub use chord::{
204    Chord, ChordResolutionSuggestion, ChordTableAddress, GuitarFingering, GuitarStringFingering,
205    GuitarTuning, GuitarTuningString, IntoNotes, KnownChordType, TriadQuality,
206    format_vector_string,
207};
208pub use chordsymbol::{
209    ChordAlteration, ChordQuality, ChordStepModification, ChordStepModificationType, ChordSymbol,
210    Music21ChordType, chord_symbol_figure_from_chord, chord_symbol_from_chord,
211    known_chord_symbol_types, realize_chord_symbol_durations,
212};
213pub use clef::{Clef, ClefKind};
214pub use defaults::{FloatType, FractionType, IntegerType, Octave, UnsignedIntegerType};
215pub use duration::{
216    Duration, DurationTuple, DurationType, Grace, Tuplet, TupletBracket, TupletShow, TupletType,
217    quarter_length_to_closest_type,
218};
219pub use dynamics::Dynamic;
220pub use error::{Error, Result};
221pub use instrument::{Instrument, SearchLanguage, ensemble_name_by_size};
222pub use interval::{
223    ChromaticInterval, DiatonicInterval, GenericInterval, Interval, IntervalDirection, Specifier,
224    absolute_higher_pitch, absolute_lower_pitch, convert_diatonic_number_to_step, convert_generic,
225    convert_semitone_to_specifier_generic, convert_semitone_to_specifier_generic_microtone,
226    intervals_to_diatonic, notes_to_chromatic, notes_to_generic, parse_specifier,
227    staff_distance_to_generic_number, written_higher_pitch, written_lower_pitch,
228};
229pub use key::{Key, KeySignature, convert_key_string_to_music21_key_string};
230pub use metadata::{Metadata, MetadataContent, MetadataValue};
231pub use meter::{BeamedNote, BeatDivision, MeterTerminal, OffsetAlign, TimeSignature};
232pub use midi::{DEFAULT_TICKS_PER_QUARTER, MidiNote, from_midi, to_midi};
233pub use notation::{
234    Beam, BeamDirection, BeamType, Beams, Justification, Lyric, NoteSize, Notehead, Placement,
235    StemDirection, Syllabic, Tie, TieStyle, TieType,
236};
237pub use note::{IntoNote, Note};
238pub use percussion::{PercussionChord, PercussionNote, Unpitched};
239pub use pitch::{
240    Accidental, AccidentalAttribute, AccidentalDisplayOptions, AccidentalSpecifier,
241    CHROMATIC_PITCH_CLASS_NAMES, Microtone, MicrotoneSpecifier, Pitch, PitchClass,
242    PitchClassSpecifier, PitchName, PitchOptions, convert_pitch_class_to_str, dissonance_score,
243    pitch_class_name, simplify_multiple_enharmonics,
244};
245pub use polyrhythm::{Polyrhythm, PolyrhythmAnalysis, PolyrhythmEvent, PolyrhythmRatioTone};
246pub use repeat::{RepeatExpression, RepeatExpressionKind};
247pub use rest::{FullMeasure, Rest};
248pub use roman::roman_numeral_from_chord;
249pub use roman::{
250    ImpliedQuality, Minor67Default, NumeralAlone, RomanNumeral, analyze_chord,
251    analyze_chord_with_root, identify_as_tonic_or_dominant, roman_inversion_name,
252};
253pub use scale::{
254    BluesForm, DegreeComparison, Scale, ScaleType, Simplification, SolfegVariant, StepScale,
255    WeightedHexatonicBlues,
256};
257pub use serial::{
258    HISTORICAL_ROWS, HistoricalRow, IndexedTransformation, LinkClassification, ToneRow,
259    Transformation, TransformationConvention, TwelveToneMatrix, historical_row_by_name,
260    row_to_matrix,
261};
262pub use sieve::Sieve;
263pub use spanner::{
264    Glissando, LineEnd, LineEnds, MultiRest, OctaveShift, Pedal, PedalForm, PedalObject,
265    PedalObjectKind, PedalType, SlideType, Spanner, SpannerKind,
266};
267pub use stream::{BarTogether, StaffGroup, Stream, StreamElement, StreamEvent, StreamKind};
268pub use tempo::{
269    DEFAULT_TEMPO_VALUES, MetricModulation, MetronomeMark, ModulationSide, TempoText,
270    convert_tempo_by_referent, interpolate_elements,
271};
272pub use tuningsystem::{
273    ALL_TUNING_SYSTEMS, COMMON_EQUAL_TEMPERAMENTS, COMMON_TWELVE_TONE_TUNING_SYSTEMS,
274    EqualDivision, HISTORICAL_TEMPERAMENTS, Monzo, Mos, MosScale, OCTAVE_CENTS, Ratio,
275    TRITAVE_CENTS, Temperament, TuningSystem, Val, moment_of_symmetry_sizes,
276    scala::{ScalaArchive, ScalaDegree, ScalaScale},
277};
278pub use voiceleading::{
279    MotionType, QuartetOptions, VoiceLeadingQuartet, iterate_all_voice_leading_quartets,
280    verticality_at,
281};
282pub use volume::{DynamicContext, Volume, realize_volume};
283
284/// Reads note events from a Standard MIDI File, dropping everything else.
285#[deprecated(
286    since = "0.15.0",
287    note = "use `from_midi` for a score, or `midi::read_midi_bytes` for bare note events"
288)]
289pub fn read_midi_bytes(bytes: &[u8]) -> Result<Vec<MidiNote>> {
290    midi::read_midi_bytes(bytes)
291}
292
293/// Reads note events and the first tempo from a Standard MIDI File.
294#[deprecated(
295    since = "0.15.0",
296    note = "use `from_midi` for a score, or `midi::read_midi_bytes_with_tempo` for bare note events"
297)]
298pub fn read_midi_bytes_with_tempo(bytes: &[u8]) -> Result<(Vec<MidiNote>, Option<FloatType>)> {
299    midi::read_midi_bytes_with_tempo(bytes)
300}
301
302/// Writes note events as a minimal format-0 Standard MIDI File.
303#[deprecated(
304    since = "0.15.0",
305    note = "use `to_midi` for a score, or `midi::write_midi_bytes` for bare note events"
306)]
307pub fn write_midi_bytes(notes: &[MidiNote], tempo_bpm: FloatType) -> Result<Vec<u8>> {
308    midi::write_midi_bytes(notes, tempo_bpm)
309}
310
311/// A stream's notes and chords as MIDI note events, everything else dropped.
312#[deprecated(
313    since = "0.15.0",
314    note = "use `to_midi` for a score, or `midi::midi_notes_from_stream` for bare note events"
315)]
316pub fn midi_notes_from_stream(stream: &Stream) -> Result<Vec<MidiNote>> {
317    midi::midi_notes_from_stream(stream)
318}
319
320/// A stream of notes built from MIDI note events.
321#[deprecated(
322    since = "0.15.0",
323    note = "use `from_midi` for a score, or `midi::stream_from_midi_notes` for bare note events"
324)]
325pub fn stream_from_midi_notes(notes: &[MidiNote]) -> Result<Stream> {
326    midi::stream_from_midi_notes(notes)
327}