Skip to main content

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