Microtonality: how it works

This page is for programmers who want to read, maintain or extend the code that plays notes of microtonal scales. A scale is selected in a score with _scale(name,blockkey), and its notes must then sound at frequencies that do not belong to the 12-tone equal temperament. The page describes how scales are loaded, and how their frequencies reach a Csound score, real-time MIDI and MIDI files.

The two kinds of output follow very different paths:

  • in Csound, each note is a line of the score with its own pitch field. The console simply calculates the frequency of the note and writes it in Hertz (note 4);
  • in MIDI, a note only has a key number (0 to 127) and the pitch can only be changed with a pitchbend message, which applies to a whole channel. The console therefore gives each sounding note a channel of its own, and sends on this channel the pitchbend that corrects the pitch of the key. This mimics MIDI Polyphonic Expression (MPE). The channel is chosen by AssignUniqueChannel() (notes 5 to 9).

The code lives mainly in Tonality.c (scales and frequencies) and MIDIstuff.c (SendToDriver() and AssignUniqueChannel()). A few lines in SaveLoads1.c, CompileProcs.c, CsoundScoreMake.c, MakeSound.c, MIDIdriver.c and Inits.c connect it to the rest of the program.

Comments of the form // note 6 have been placed in Tonality.c and MIDIstuff.c. Each one points to the numbered note of this page that explains the code below it. In the other files, which may contain notes of other pages, the comments have the form // note 6 (microtonality). Searching for // note 6 finds every place that note 6 describes. Line numbers are not given because they change with every revision.

The principle

A microtonal scale is a list of frequency ratios, one for each grade, with a base frequency, a base key and an interval of repetition (most often 2, the octave). These are the arguments of a Csound GEN51 function table:

f2 0 128 -51 numgrades interval basefrequency basekey ratio0 ratio1 ... ratioN

Each scale also has the names of its notes (for instance sa r1 r2 ... in a scale of 22 shruti), and possibly the key numbers of its grades. Scales are stored in tonality resource files (-to), which are read when the project names one (note 1).

When the scale is loaded, the console computes for every key from 0 to 127 a correction in cents: how far the frequency of this key in the scale is from the frequency of the same key in an equal-tempered scale with the same base frequency (note 2). The same table of corrections is used by Csound and by MIDI, so that both outputs give the same pitches.

Loading scales

Note 1 — Reading a tonality file

LoadTonality() (SaveLoads1.c) reads the tonality file named in the project. In the JSON format, LoadTonalityJSON() rebuilds, for each scale, the GEN51 line and the strings of the former format (note names between slashes, key numbers between k, fractions between brackets). The former format is read by LoadTonalityOldFormat(). Both call CreateMicrotonalScale() (Tonality.c), which fills an entry of the array Scale (type t_scale): numgrades, interval, basefreq, basekey, baseoctave, tuningratio, notenames, keys, keyclass and numnotes.

A scale may have more grades than notes: names written • are grades without a note. The array keyclass gives the grade of each note. Ratios are read as decimal numbers, then replaced with the exact fractions when they are given. A line with another GEN number is not a scale and is ignored. A table that does not contain numgrades + 1 ratios is rejected with an error.

Scales are numbered from 1 in the order in which they are read (NumberScales). Scale 0 stands for the equal-tempered scale. In the score, the argument of _scale() is not the number of the scale but the index of its name in the string constants of the grammar; FindScale() (MIDIstuff.c) converts it by comparing the names.

Note 2 — The table of corrections

At the end of CreateMicrotonalScale(), two tables of MAXKEY (128) values in cents are filled for the scale:

  • deviation[key] is the difference between the frequency of the key in the scale, basefreq × ratio × intervaloctave − baseoctave, and the frequency of the same key in an equal-tempered scale built on basefreq and basekey;
  • blockkey_shift[key] is the difference between the ratio of the grade of this key and the nearest equal-tempered semitone.

The correction applied to a key is deviation[key] + blockkey_shift[blockkey]. The block key, the second argument of _scale() (DefaultBlockKey = 60 by default, in the settings), is the note whose frequency stays fixed when scales are changed: the second term shifts the whole scale so that this key keeps its equal-tempered pitch.

The values are stored as integers (short), which gives a precision of one cent. The option “Trace microtonality” of the settings (TraceMicrotonality) displays the table, key by key.

Note 3 — Microtonality in MIDI

The compilation of _scale() (GetPerformanceControl(), CompileProcs.c) sets the global MIDImicrotonality when the output is real-time MIDI, a MIDI file or an event list, and not Csound. It displays “Microtonality mimics MIDI Polyphonic Expression”. Everything specific to MIDI on this page depends on this flag. Csound does not need it.

Csound: calculating the frequency

Note 4 — GetPitchWithScale()

In Csound, there is no channel to manage. Each note is a line of the score, and the instrument receives its pitch in one of its fields. When a note belongs to a scale, CscoreWrite() (CsoundScoreMake.c) calls GetPitchWithScale() (Tonality.c), which returns the frequency in Hertz:

frequency = basefreq × 2^(temp_note / 12) × 2^(temp_octave − baseoctave)   (equal-tempered key)
          × ratio0                                                     (ratio of the base key)
          × A4freq / 440                                               (diapason)
          × 2^(cents / 1200)                                           (pitchbend of the note)
          × 2^(correction / 1200)                                      (deviation of the scale, note 2)

The pitchbend of the note, cents, is the value of _pitchbend() converted to cents with the pitchbend range of the Csound instrument. CscoreWrite() then sets pitch_format to IGNORER: the frequency is written as it is, whatever the pitch format of the instrument (octave point pitch class, octave point decimal or cps) declared in the Csound resource file. The instrument of the orchestra must therefore accept a frequency in Hertz when scales are used. The comment of the score line shows the deviation from the equal-tempered pitch of the same key.

Since each note gets its own frequency, any number of notes of any scales can sound at the same time, and the precision is that of the frequency (3 decimals in the score).

MIDI: one channel for each note

MIDI has no way of giving a note an arbitrary frequency. The console sends the key nearest to the frequency, and a pitchbend message that raises or lowers it by the correction. A pitchbend message applies to all notes of its channel, so two notes with different corrections cannot share a channel. MPE solves the same problem for expressive controllers: the instrument uses a zone of channels, here channels 2 to 16 (the member channels), and each note gets a member channel of its own while it sounds. Channel 1 is the manager channel of the zone and receives no notes. Synthesisers that accept MPE, such as Pianoteq, play these notes correctly. Others work as well, provided they apply the pitchbend of each channel to its notes, which multi-timbral General MIDI synthesisers do.

Up to 15 notes of scales can sound at the same time.

Note 5 — SendToDriver()

Every MIDI event goes through SendToDriver() (MIDIstuff.c), which sends it to real-time MIDI (SendToStack()) or writes it to the MIDI file. With MIDImicrotonality, a NoteOn or NoteOff whose scale is a microtonal scale (i_scale > 0) is processed as follows:

  1. FindScale() gives the number of the scale (note 1).
  2. pitchbend_master is the pitchbend of the sound-object instance at its start (PitchbendStart(), set by _pitchbend()), relative to the centre value 8192. It is added to the correction of the scale (note 9).
  3. AssignUniqueChannel() chooses the channel of the note (notes 6 and 7). The channel of the item, set by _chan(), is ignored.
  4. The status of the event is set to this channel.
  5. For a NoteOn, the correction of the key is computed (note 2), the key may be moved (note 8), and a pitchbend message is sent on the channel before the NoteOn, at the same date (note 9).

Other events (control changes, program changes, pressure…) and notes of the equal-tempered scale (_scale(0,0), or no scale) keep the channel of the item.

Note 6 — AssignUniqueChannel(): NoteOff

The state of channels 2 to 16 is kept in global arrays indexed by the channel number minus 1 (ch = 1 to 15):

  • MPEnote[ch]: the key sounding on the channel, 0 if it is free;
  • MPEscale[ch]: its scale, −1 if the channel is free;
  • MPEpitch[ch]: its pitchbend_master;
  • MPEold_note[ch] and MPEnew_note[ch]: the key requested and the key sent, when they differ (note 8);
  • MPEreleased[ch]: the value of a counter (MPEreleaseCount) when the channel was last released.

They are reset by Inits.c when the console starts.

A NoteOff (or a NoteOn with velocity 0) must be sent on the channel of its NoteOn. AssignUniqueChannel() looks for it in three passes, and stops at the first channel found:

  1. a channel whose MPEold_note is the key, with the same scale and pitch: the NoteOn had been moved to another key (note 8);
  2. a channel whose MPEnote is the key, with the same scale and pitch;
  3. a channel whose MPEnote is the key, with the same scale, whatever the pitch. This pass, added on 2026-10-13, finds notes whose pitchbend has changed between the NoteOn and the NoteOff.

The channel found is released: MPEnote = 0, MPEscale = MPEpitch = −1, and MPEreleased takes the next value of the counter. If no channel is found, the function returns 0, and SendToDriver() displays “No channel available” (at most 5 times) and sends the NoteOff on channel 1. This message reveals a NoteOff without a NoteOn. Such a case was fixed in MakeSound() on 2026-11-13, where a NoteOn merged with the previous one was counted as sounding (see note 28 of the page about MakeSound()).

Note 7 — AssignUniqueChannel(): NoteOn

A NoteOn takes a free channel (MPEnote = 0 and MPEscale = −1), and records its key, scale and pitch. Among the free channels, the one chosen is:

  • the channel released longest ago (smallest MPEreleased). A channel that has just been released still plays the release of its note: the sound continues after the NoteOff, often for a long time with a piano. The pitchbend of the next note would shift the pitch of this release, which makes a click on some synthesisers (heard with Pianoteq). Taking the channel released longest ago leaves the most time to the release. Before 2026-11-16, the first free channel was taken, so that the same channels were used over and over;
  • not channel 10, unless no other channel is free. Channel 10 (ch = 9) is the percussion channel of General MIDI: a player of MIDI files, or a General MIDI synthesiser, plays its notes as drum sounds, whatever the program selected. An MPE synthesiser does not make this distinction, which is why channel 10 is still used as a last resort rather than losing a note. With 14 other channels, this only happens when more than 14 notes of scales sound at the same time.

If all 15 channels are busy, the function returns 0, and SendToDriver() displays “No channel available” and sends the note on channel 1. Its pitchbend then applies to every note sent on channel 1.

Note 8 — Moving the key

The pitchbend corrects a key by less than a semitone in each direction. When the correction of the key is less than −100 cents or at least 100 cents, the note is sent on another key: new_note = note + floor(correction / 100), and the correction is reduced by the same number of semitones, which brings it between 0 and 99 cents. The key requested is stored in MPEold_note[ch] and the key sent in MPEnew_note[ch] and MPEnote[ch].

The NoteOff, which still carries the key requested, finds the channel by MPEold_note (note 6, first pass). SendToDriver() then replaces its key with MPEnew_note, so that the synthesiser releases the key that it plays, and resets both values to −1.

If the new key is out of the range 0 to 127, the error “Microtonality pitchbender out of range” is displayed and the note is sent without correction.

Note 9 — The pitchbend message

The pitchbend value is a 14-bit number, from 0 to 16383, with 8192 (DEFTPITCHBEND) for no bend. The console assumes that the synthesiser has a pitchbend sensitivity of ±2 semitones, the default value of General MIDI. The range ±200 cents then corresponds to ±8192, so one cent is 8192 / 200 = 40.96 units:

pitchBendValue = 8192 + pitchbend_master + correction × 8192 / 200

The value is limited to 0…16383, with an error message (“Pitchbender out of range”) displayed at most 4 times. It is split into two bytes of 7 bits (LSB first), and sent as PitchBend + channel at the date of the NoteOn: to the stack of real-time events with SendToStack(), or to the MIDI file with WriteMIDIbyte(). Since it is sent before the NoteOn, the note starts at the right pitch.

The resolution of the pitchbend is finer than a cent, so the precision of MIDI is the precision of the table of corrections, one cent. With “Trace microtonality”, each note is displayed with its key, name, channel, scale, correction and frequency, in the form § key K: "name" channel C, scale #S (block key B) -> key K2 corr N cents, freq F Hz, where -> key K2 only appears when the key has been moved (note 8).

Note 10 — Volume in MIDI MPE

The volume of a note (_volume()) is normally sent as control change 7 (CC7) on the channel of the item, at the start of the sound-object (SendInitialControls(), MakeSound.c). With microtonality, the notes are no longer on the channel of the item, which is often channel 1, the manager channel of the MPE zone. A synthesiser in MPE mode, such as Pianoteq, applies a control change of the manager channel to all notes of the zone. With -gr.tryShruti, the drone and the melody have different volumes: the volume jumped at each note of either part, changing the loudness of the other one.

Since 2026-11-16, the volume of a note of a scale is applied to its velocity, which belongs to the note alone:

  • VolumeAsVelocity() tells whether a note is concerned: not Csound, MIDImicrotonality, and a microtonal scale;
  • in MakeSound(), before the NoteOn is sent, the velocity becomes velocity × volume / DeftVolume, limited to 1…127, where volume is the volume of the instance (InstanceVolume()) and DeftVolume the default volume of the settings (90). A note at the default volume keeps its velocity. This is not done for a sound-object whose prototype ignores the volume (OkVolume);
  • in SendInitialControls(), the CC7 is no longer sent for these notes.

The MPE specification recommends exactly this: the volume of a single note is expressed by its velocity, or by messages on its own channel (channel pressure, CC74), never by a control change of the manager channel.

Note 11 — MIDI input

When MIDI input is played through to the output (sendMIDIEvent() with direction == INmidi, MIDIdriver.c), the notes received are processed in the same way if a scale is current: the key is shifted by basekey − 60, a channel is assigned with AssignUniqueChannel(), and the correction is sent as a pitchbend. Events produced by the console go through SendToDriver() instead, and are not corrected a second time.

Note 12 — Channel filters

The filters of the MIDI outputs (MIDIchannelFilter, PassOutEvent()) are ignored with microtonality. Since the channel of a note is chosen by AssignUniqueChannel(), filtering channels would drop notes at random.

Note 13 — Event lists

An event list contains notes with their channels, but no pitchbend. When it is the output, the first note of each scale exports the scale as a Scala file (.scl) and a keyboard mapping (.kbm) to the output folder (ExportScale(), ExportSCL(), ExportKBM(), Tonality.c), so that the program reading the list can tune its notes.

Note 14 — Settings sent to the synthesiser

In real-time MIDI, when the diapason (A4freq) is not 440 Hz, TuneMIDIdevice() (MakeSound.c) sends the tuning to all channels (registered parameter 2), and the corrections of the scales do not include it. This is not done in MIDI files.

SetUpMPEreceiver() would configure the synthesiser for MPE (an MPE configuration message for a lower zone of 15 member channels, and a pitchbend sensitivity of ±2 semitones on each channel). It is not called: Pianoteq did not need it, and these messages made unwanted noises when improvising with -gr.Mozart. The synthesiser must therefore be set by hand.

Limitations

  • The pitchbend sensitivity of the synthesiser must be ±2 semitones. The MPE specification gives the member channels a default sensitivity of ±48 semitones: a synthesiser in MPE mode may need to be set accordingly, otherwise every correction is 24 times too large.
  • At most 15 notes of different scales can sound at the same time, 14 without using channel 10.
  • Notes without a scale, or in the equal-tempered scale, keep the channel of the item. If this channel is one of channels 2 to 16, a note of a scale may be assigned the same channel, and its pitchbend then changes their pitch. Such notes are best sent on channel 1.
  • Continuous variations of the volume (_volumecont), and other control changes, are still sent on the channel of the item, which applies them to all notes of an MPE zone (note 10).
  • The pitchbend of a note is fixed at its start. A continuous variation of the pitchbend is sent on the channel of the item, not on the channels of the notes.
  • In MIDI, the diapason is only applied in real time (note 14). In Csound, it is part of the frequency (note 4).

Debugging microtonality

  • The projects -gr.tryShruti, -gr.tryScales, -gr.tryRagas, -gr.tryTunings and -gr.tryOneScale of the sample set use scales. They can be run in a terminal, from the php folder, with the tonality file named in their header, for instance:

    ../bp produce -gr ../ctests_git/-gr.tryShruti -se ../ctests_git/-se.tryShruti -cs ../csound_resources/-cs.tryShruti -to ../tonality_resources/-to.tryShruti --seed 1 --midiout /tmp/shruti.mid

    with --csoundout /tmp/shruti.sco instead of --midiout for Csound.
  • The option “Trace microtonality” (TraceMicrotonality) of the settings displays the table of corrections of each scale (note 2) and every note sent (note 9). For Csound, the same lines are displayed by GetPitchWithScale(), which allows comparing the frequencies of both outputs.
  • In AssignUniqueChannel(), setting the local variable test to TRUE displays each NoteOn and NoteOff with the channel found, and the state of the channels examined.
  • In a MIDI file, each NoteOn of a scale must be preceded by a pitchbend on the same channel, at the same date, and its NoteOff must be on the same channel with the same key.

Note: This page was entirely composed by Claude Opus 5.5 on 16 November 2026.

Leave a Reply

Your email address will not be published. Required fields are marked *

« Translate