MIDI, Sequencers and the DAW
How does a few pages of 1983 specification carry music between machines, and what must an engine do to play it in real time?
In January 1983 a Prophet-600 and a Jupiter-6 were joined by a five-pin cable; MIDI 1.0 has run the industry since. An ear question hears a twelve-note chord as the cable delivers it, the last note 7.0 ms after the first, against all at once. Machines that play: the Banu Musa's pinned cylinder, the music box (heard), player-piano rolls (forty notes a second, heard), Nancarrow's tempo canons and their arithmetic. MUSIC N's orchestra and score from unit generators (heard), and real time arriving. MIDI byte by byte: ten bits a byte at 31,250 baud (320 microseconds), status and data bytes, running status (42 bytes to 29 for the Tune's first phrase), a chord's smear against its size (16 notes: 15.4 ms plain, 10.6 running). Seven-bit controllers zip (31-cent steps; an ear question); one bend per channel; MPE (2018) and MIDI 2.0 (2020). A Standard MIDI File of the whole Tune: 423 bytes against 6.9 MB of audio, read back exactly; variable-length times and the tempo map. Step sequencers (a sixteen-step line, heard), piano rolls and trackers; a pattern language parsed into a tree (heard) and live coding. An engine of stateful voices, limiters and delays renders bit-identically in blocks of 32 to 2048; small blocks cost more (11 per cent load at 32, 2 at 2048); missed deadlines click (heard); notes snapped to blocks land up to 21 ms early (an ear question) where sample-accurate scheduling is exact; a lock-free queue; the processing graph, plug-ins, and delay compensation, whose absence combs a parallel path (5 ms late: notches every 200 Hz from 100, heard). The Tune as a tracker module and a tempo canon at 3 : 4 : 5 : 6 meeting after 30.7 s.
What you need. Part 10 for notation and the piano roll; Part 11 for meter; Part 44 for chip music; Part 48 for sampling; Parts 51 and 52 for the voices. Serial communication, binary and hexadecimal, graphs and topological order, threads and queues.
- Ideas, mathematics and history
- player pianos and Nancarrow, MUSIC N, the 1983 handshake, the protocol byte by byte, real-time audio, the audio graph, plug-ins, live coding
- What we build, compute and hear
- a sequencer and audio graph with a measured real-time budget; a tempo canon
What you will be able to do
Foundations
- Hear a chord smeared by the cable, a music box, a player-piano roll and a MUSIC-style orchestra.
- Hear zipper noise from a 7-bit controller, a sixteen-step bass line and a two-line pattern.
- Hear missed deadlines, notes snapped to blocks, and a parallel path combing without delay compensation.
Full course
- Encode and decode MIDI 1.0 with running status, and time a message on the wire.
- Write and read a Standard MIDI File with variable-length times and a tempo; parse a pattern language.
- Build an engine that renders identically in any block size, schedules to the sample and compensates latency.
Research
- Find the best-sounding neural effect that is guaranteed never to miss an audio deadline.
Practice
- Choose a block size, use delay compensation and MPE, and keep the audio thread free of locks and allocation.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Foundations 23 min · Full course 35 min · Research 37 min · Practice 35 min.
- 0A five-pin cableFoundations2 min
- 1Machines that playFoundations3 min
- 2MUSIC N and unit generatorsFoundations3 min
- 3MIDI, byte by byteFoundations4 min
- 4MIDI's limits, MPE and MIDI 2.0Foundations3 min
- 5MIDI filesPractice3 min
- 6Sequencers: steps, rolls and trackersFoundations2 min
- 7A pattern language and live codingFoundations2 min
- 8The audio callbackPractice4 min
- 9Timing inside a blockPractice3 min
- 10The graph, plug-ins and delay compensationPractice3 min
- 11Frontier: learning in the audio thread; networked performanceResearch3 min
- Variation 53, recap and problemsAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
A five-pin cableFoundations2 min
In January 1983, at a trade show, a key pressed on one synthesizer sounded another. Listen before the history. A twelve-note chord, struck four times, twice over. Once, every note starts together. Once, the notes arrive as MIDI sends them, one after another down a cable. Which was the cable?
The first was the cable. MIDI sends one byte every three hundred and twenty microseconds, and each note takes two or three bytes, so the twelve notes arrive one after another, the last milliseconds after the first. That is too short to hear as an arpeggio; it is heard, if at all, as a softer, slightly smeared attack. Forty years of music have been played down this cable, and dense traffic can produce much larger queueing delays.
The cable has a story. In 1981 Dave Smith of Sequential Circuits proposed a universal interface between synthesizers. Roland's Ikutaro Kakehashi and the Japanese makers joined, and rivals agreed on a five-pin cable and a few pages of rules. In January 1983, at a trade show, a Prophet-600 and a Jupiter-6 were joined, and a key pressed on one sounded the other. MIDI 1.0 is still spoken by nearly every electronic instrument, and in 2013 Smith and Kakehashi shared a technical Grammy for it. This part reads it byte by byte, then builds what sits on top.
Here is the plan. Machines that play: cylinders, rolls and Nancarrow. MUSIC N and the unit generator. MIDI byte by byte, its limits, MPE, MIDI 2.0 and files. Sequencers, trackers and a small pattern language. The audio callback, its deadline and its timing. And the processing graph, plug-ins and delay compensation.
1Machines that playFoundations3 min
How old is the idea of music stored as instructions?
Music stored as instructions is old. Around 850 in Baghdad the Banū Mūsā brothers described a flute played by a turning cylinder of pins. A pin is an instruction, open this hole now, and the cylinder is a program. Barrel organs, carillons and clocks played pinned cylinders for centuries. In 1796 in Geneva, Antoine Favre made the music box: pins pluck the teeth of a steel comb. Swap the cylinder and the machine plays another tune: the music is data.
Here is a music box, computed: the Tune's first two phrases on steel tines clamped at one end, whose overtones lie at six and seventeen and a half times the note, which is why a music box sounds glassy rather than like a piano.
The next machines read paper. Around 1900 the player piano read a roll: a hole is a key held down, and air does the rest. In 1904 the Welte-Mignon reproducing piano recorded a pianist's dynamics and pedalling too. By the 1920s player pianos outsold ordinary ones in America, until the radio and the gramophone ended them. A roll is a piano roll in the modern sense, time across and pitch up, as Part 10 drew it. And a roll can hold what no hands can play.
Here is what a roll can do: arpeggios at forty notes a second, then fifteen keys at once over five octaves.
One composer took the roll seriously. Conlon Nancarrow, in Mexico City from the late 1940s, punched player-piano rolls by hand for fifty years. His Studies for Player Piano use speeds and densities no pianist could reach, and tempo canons: the same line in several voices at different speeds, such as Study number 36, at seventeen to eighteen to nineteen to twenty. The voices are started so that they meet at one moment, the convergence point. Variation 53 builds one, with the Tune at three, four, five and six.
The arithmetic of a tempo canon is one line. Voice v plays at r v beats a second, and note k falls on beat b k, so it sounds at the voice's start plus b k over r v. To make every voice reach note K at the same moment T, start voice v at T minus b K over r v, with T set by the slowest voice, which starts at zero. Before the meeting the voices drift apart in time; after it they would drift the other way. Nancarrow worked this out by hand, with a ruler and a punch.
2MUSIC N and unit generatorsFoundations3 min
How did a computer first make music?
The computer made music before it made anything playable. In 1957 at Bell Labs, Max Mathews's program MUSIC computed a sound sample by sample on an IBM 704. It was not real time: seconds of sound could take hours, then be played back from tape. In 1961 a computer sang Daisy Bell, from John Kelly, Carol Lochbaum and Mathews, remembered from a film seven years later. And in 1960 MUSIC III introduced the unit generator: small blocks, an oscillator, an envelope, an adder, patched together. This modular software approach preceded Moog's commercially influential 1964 modular synthesizer.
MUSIC split music into two files. The orchestra says how each instrument is wired from unit generators: here an envelope generator feeding an oscillator's amplitude, the oscillator reading a stored table, a sine with two harmonics. The score is a list of notes, one line each: which instrument, when it starts, how long it lasts, and its frequency. That split, instruments and notes, is still a useful division in many synthesizers and sequencers, and MIDI is its score.
The orchestra plays the score: the Tune's first phrase, as a 1960s computer would have computed it.
MUSIC has many descendants. MUSIC IV and V in the 1960s, then Csound, from Barry Vercoe in 1986, keep the orchestra and the score. Max, from Miller Puckette in the 1980s, and Pure Data in 1996, draw unit generators as boxes and wires. SuperCollider, from James McCartney in 1996, makes and destroys them while the music runs. What changed was speed: by the 1990s a personal computer could run them in real time. And real time brings a deadline, which is chapter eight.
Real time arrived in stages. In the 1970s special hardware made synthesis live, from Giuseppe Di Giugno's 4X at IRCAM, finished in 1981, to the Synclavier. In the 1980s digital chips put FM and samples in every keyboard, as Part 52 told. In the 1990s general-purpose processors caught up, and the studio moved into software. The cost of a voice fell from a cabinet to a few microseconds. But the instruments still had to talk to each other: hence MIDI.
3MIDI, byte by byteFoundations4 min
What exactly goes down the cable?
Start with the wire. MIDI is a serial line: each byte is sent as a start bit, eight data bits lowest first, and a stop bit. At thirty-one thousand two hundred and fifty bits a second, a speed chosen because it is a one-megahertz clock divided by thirty-two, a byte takes three hundred and twenty microseconds. The signal is a current loop through an opto-isolator, reducing ground-loop paths through the data connection; other connections can still create hum; and each cable carries one direction, out, in, or thru to chain the next instrument.
A note is three bytes. Hexadecimal nine zero: note on, channel one. Three C: key sixty, middle C. Six four: velocity one hundred, how hard. The rule that makes the stream readable: a status byte has its top bit set, a data byte does not, so data has seven bits and a hundred and twenty-eight values. The status byte's high half is the kind of message, nine for note on, eight for off, B for a controller, E for pitch bend; its low half is the channel, so sixteen logical channels share one cable; channels need not map one-to-one to instruments. And notice what is missing: MIDI says which key and how hard, never what it sounds like. It is a score, not a sound.
Where do the three bytes come from? A common velocity-sensitive keyboard design uses two contacts per key, one early in its travel and one at the bottom. The time between them measures how fast the key moved: a few milliseconds is loud, tens of milliseconds soft. The keyboard's processor scans its keys repeatedly, at a design-dependent rate and turns that time into a velocity from one to a hundred and twenty-seven, and three bytes leave the socket. The velocity is a measurement of a gesture; what the receiving instrument does with it is up to the instrument.
The Tune's first phrase is messages, a note on and a note off for each note. Sent plainly that is bytes. But a receiver can remember the last status: if the next message has the same one, it is left out, running status. And a note off can be sent as a note on with velocity zero to keep the status the same. The phrase shrinks to bytes, per cent less, and our decoder reads it back exactly.
So how long does a chord take? Each note adds three bytes plainly, two with running status: sixteen notes take milliseconds plainly and with running status. For comparison, sound travels three and a half metres in ten milliseconds: a drummer and a bassist a few metres apart live with that every night. This idealized chord spread may be tolerable, but a dense passage with controllers moving on several channels can fill the cable, and then everything waits.
A few more messages complete the language. Controllers: B, the controller number, the value. The modulation wheel is one, volume seven, the sustain pedal sixty-four. Pitch bend uses two data bytes for fourteen bits, sixteen thousand three hundred and eighty-four steps, with eight thousand one hundred and ninety-two at rest. Program change chooses one of a hundred and twenty-eight sounds, and General MIDI, in 1991, fixed which: one is a piano, forty-one a violin. System messages send a clock twenty-four times per quarter note to keep machines in step, and system exclusive carries anything else. In all, a handful of message types; the rest is convention.
4MIDI's limits, MPE and MIDI 2.0Foundations3 min
What can't a 1983 protocol say?
The first limit is seven bits. A controller has a hundred and twenty-eight values. Sweep a filter's cutoff from two hundred hertz to two kilohertz with one, and it moves in a staircase of a hundred and twenty-seven steps, each cents, a third of a semitone, where the smooth sweep glides.
Your turn. A resonant filter, Part 51's ladder, swept from two hundred hertz to two kilohertz, twice. Once its cutoff follows a MIDI controller, a hundred and twenty-eight values; once it moves smoothly. Which was the controller?
The first. It clicks its way up: the resonant whistle jumps from step to step, a sound engineers call zipper noise. Synthesizers learned to smooth incoming controllers; MIDI 1.0 had in fact allowed fourteen-bit controllers from the start, two paired together, but few devices used them.
Pitch is better served. A bend has fourteen bits. Over two semitones each step is of a cent, a very fine pitch increment in ordinary listening conditions; over forty-eight semitones it is still of a cent. The real limit is that there is one bend per channel: bend one note of a chord and every note on that channel bends with it. A guitarist bends one string; a violinist slides one finger; ordinary channel-wide bend cannot express that on a shared channel; separate channels or MPE can.
The first answer was a workaround. MIDI Polyphonic Expression, MPE, adopted in 2018, gives every sounding note a channel of its own. Then each note can carry its own bend, its own pressure and its own controller: a slide, a swell, a vibrato. That allows fifteen notes at once, with one channel left for messages to all of them. It was made for instruments that sense each finger's pressure, sideways slide and forward glide. And it lives inside the old protocol: no new cable was needed.
Then came a new version. MIDI 2.0, adopted in 2020, uses Universal MIDI Packets built from thirty-two-bit words, with message-dependent lengths, the Universal MIDI Packet, rather than a byte stream. Velocity gets sixteen bits and controllers thirty-two: much finer quantization, though values are still discrete. Per-note controllers and per-note pitch are built in rather than borrowed from channels. Devices describe themselves to each other, and fall back to MIDI 1.0 when they must. The five-pin cable remains for MIDI 1.0; the new packets travel over USB and networks.
Despite its limits, MIDI got a great deal right. It describes gestures, not sounds, so any instrument can obey any controller. It was small enough for an eight-bit processor of 1983 to read in real time. It was free to use, with no licence fee, which helped broad adoption. And it stayed backward compatible for forty years: a 1983 keyboard still plays a modern plug-in. Few standards have lasted as long with so little change.
5MIDI filesPractice3 min
How do you store a performance, not a sound?
A performance can be stored. The Standard MIDI File of 1988 is a series of chunks, each a four-letter tag and a length. Here are the first twenty-two bytes of our file of the Tune. The header, M T h d, length six: format one, two tracks, four hundred and eighty ticks to a beat. Then the first track, M T r k. Inside a track, every event is preceded by the time since the last one, and the events are the cable's messages, plus a few that only files need: the tempo, names, the end of the track.
The times use a clever code, the variable-length quantity. Each byte carries seven bits of the number; the top bit says whether another byte follows. Zero is one byte; a hundred and twenty-seven is one byte; a hundred and twenty-eight needs two, eight one, zero zero; four hundred and eighty, one beat, is eight three, six zero. Most waits in music are short, so most cost one byte: the same idea as Morse's code, short signs for what is common.
A file counts in ticks, not seconds. The header says how many ticks make a beat, the division; a tempo event says how many microseconds a beat lasts. Seconds are ticks times tempo, over the division times a million. Four hundred and eighty ticks, at five hundred thousand microseconds a beat, is half a second: a hundred and twenty beats a minute. Change the tempo event and every note moves, while the score itself stays the same.
Our writer stores the whole Tune, notes, in bytes. Our reader reads it back, every note at the right key and the right time. The same seconds as twenty-four-bit stereo audio take million bytes, about times as many, because the file says what to play, not what it sounds like.
MIDI files travelled far. They carried ringtones, karaoke, game music and whole songs across the early internet, and with General MIDI's fixed sounds a file played back roughly right on any machine. They are also data: corpora of MIDI files train the composition models of Part 65. But a file keeps no sound, and the same file sounds different on every synthesizer. What plays the file is the sequencer.
6Sequencers: steps, rolls and trackersFoundations2 min
How do you write music for a machine to play?
The simplest sequencer is a row of steps. Sixteen steps a bar; each holds a note or a rest, may be accented, and may slide into the next. The analogue sequencers of the 1960s had a knob per step; the bass machine of 1981 that defined acid house stored patterns exactly like this one. A step sequencer thinks in a grid, not in time: the loop repeats until you change it.
Hear it, four bars, through Part 51's ladder: accents open the filter further; slides glide into the next note.
Computers brought a second way. The piano roll: time across, pitch up, a bar for each note, as Part 10 drew it and the player piano punched it. Notes are drawn, dragged and stretched with a mouse, with velocity as a lane beneath. Quantizing pulls every note to the nearest grid line; swing pulls every other one late, as Part 38 measured. A performance can be recorded and edited like a document. The idea has held from 1983 to now: notes as editable objects, not marks on paper.
A third way came from home computers. In 1987 Karsten Obarski's Soundtracker, for the Amiga's four sample channels, turned the score on its side: time runs down the screen, one row at a time, and each column is a channel. Each cell holds a note, an instrument number and an effect, typed in hexadecimal by people who were also programmers. Here is the Tune's first phrase as Variation 53 will play it. The demoscene and a generation of game music lived in trackers, Part 44's chip music among them.
Today one program holds all of these. The digital audio workstation lays tracks of audio and of MIDI side by side on one timeline, with mixing, effects and synthesizers inside, all as software. Some arrange clips in a grid to be launched live, the step sequencer's loop come back. Under every one of them is an engine computing audio in blocks, against a clock. Before the engine, one more way to write: as text.
7A pattern language and live codingFoundations2 min
Can music be typed while it plays?
Our pattern language has five rules, after the mini-notation of Alex McLean's TidalCycles. Spaces split one cycle into equal steps. Square brackets split a step again. A tilde is a rest. A star repeats something inside its step. And angle brackets take one item per cycle, in turn, so a pattern can change from one cycle to the next.
Two lines of it, expanded over four cycles of two seconds. The melody: C, E, two Gs in the time of one, and then, from the angle brackets, A in the first cycle, C in the second, B in the third, E in the fourth. The drums: a kick, a half-step rest and a kick, a snare, then a kick and a hat sharing a step. The parser turns each line into a list of timed events, which the engine of the next chapter plays.
How is a pattern read? The parser builds a tree. The cycle, two seconds, is the root; its four steps are its children, half a second each. A bracket is a subtree that divides its half second again, two Gs of a quarter second each. An angle bracket is a node that picks one child per cycle, in turn. Playing a cycle walks the tree, dividing time at every level: a recursive program of a few dozen lines, which is why such languages are easy to extend.
And heard: four cycles of the two lines, the melody on the engine's sawtooth voice, the drums from Part 51's circuits.
Text can be performed. In live coding the musician edits the code while it plays, and the screen is shown to the audience. SuperCollider in 1996, ChucK from Ge Wang in 2003, TidalCycles in 2009 and Sonic Pi from Sam Aaron in 2012 made it possible, and since 2012 algoraves have been dance nights where the instrument is a text editor. Changes must be scheduled safely; when they take effect depends on the environment and performer: the engine never stops. That is the engine's hardest rule.
8The audio callbackPractice4 min
What does real time actually demand?
Real time means a deadline. The sound card plays from a buffer, a block of samples at a time, and while one block plays, the computer must compute the next. Every few milliseconds the operating system calls the engine, the audio callback, and asks for exactly one block. The engine has until that block is due: the block size over the sample rate. A hundred and twenty-eight samples at forty-eight kilohertz gives two point six seven milliseconds, every time, forever.
The first rule of an engine: the block size must not change the music. Our engine plays notes on three tracks, one through a look-ahead limiter, in blocks from thirty-two samples to two thousand and forty-eight, and compares each result with the whole four seconds computed in one go. Every one is identical, to the last bit, because every voice, filter and delay carries its state from block to block, and every note starts on its own sample, wherever the block boundaries fall.
How hard is the deadline? Here is the median work per block, measured in this implementation on this computer. With blocks of two thousand and forty-eight samples the engine uses per cent of the time it has. With thirty-two it uses per cent: small blocks cost more than their share, because each block carries a fixed overhead, the call, the bookkeeping, the start of every loop. Small blocks mean low latency and a heavier load; large blocks the reverse. Every studio chooses its block size between the two.
What happens when a block is late? The sound card cannot wait: it plays whatever is in the buffer, silence, repeated samples or another fallback depending on the driver; this example inserts silence. Here is the same passage clean, then with of its blocks late, each a gap of under three milliseconds.
Each gap is a click: a few milliseconds of silence cut into a waveform. One every second is enough to ruin a recording, which is why audio engineers count these, xruns, and why an engine is written to be predictable before it is written to be fast.
So the audio thread has rules. In the callback: no waiting on locks, no memory allocation, no files, no network, because any of these can take an unknown time and the deadline cannot. Messages cross from the interface to the engine through lock-free queues. Ross Bencina's well-known essay on the subject is called, simply, Time waits for nothing. And timing must be exact inside the block too.
How does a message reach the audio thread without a lock? Through a ring of slots shared by two threads. The interface writes each message at the write index and then advances it; the audio thread reads at the read index and advances that. With a suitable single-producer, single-consumer design, atomic publication, correct memory ordering, preallocated storage and explicit full/empty handling, each operation can have bounded cost: a design goal that this diagram illustrates rather than a production queue implemented here.
9Timing inside a blockPractice3 min
Where in the block does a note begin?
A lazy engine starts each note at the beginning of the block it falls in. With blocks of a thousand and twenty-four samples, milliseconds, sixteenth-note hi-hats at a hundred and twenty beats a minute land up to milliseconds early, by a different amount each time, because the beat and the blocks do not line up. Our engine instead starts every note on its own sample, inside the block.
Your turn. Sixteenth-note hi-hats over a kick, twice. Once every hit is placed to the sample; once every hit is moved to the start of its block. Which was moved?
The second. Snapped to blocks, the hats limp: some pairs too close, some too far, a groove that stumbles. Placed to the sample they are even. Ensemble players align within a few tens of milliseconds and hear far less than that in a steady pulse; an engine has no excuse to add its own.
Timing has a second side: latency. It adds up along the chain: the controller, the cable or USB, the input buffer, the engine's block, the output buffer, the converter. Latency sensitivity varies with player, instrument and task; roughly ten milliseconds is a useful design target, not a universal threshold between the key and the sound. Sound in air takes about three milliseconds a metre, so a pianist hears the piano a few milliseconds late anyway. The budget is spent mostly on the block size: small blocks, low latency, heavy load. And every plug-in that looks ahead adds its own latency.
The cure for block timing is simple. At the start of each block, take the events due before its end. For each, compute its offset inside the block: a note due at sample seventeen hundred falls six hundred and seventy-six samples into the second block of a thousand and twenty-four. Then run that voice from that sample, not from the block's start. For notes played live, the engine needs to know when each message was sent, so incoming MIDI needs timestamps; the host can timestamp arrivals; timestamp support depends on the transport and protocol, and ordinary USB MIDI 1.0 packets do not carry a per-note timestamp.
10The graph, plug-ins and delay compensationPractice3 min
What happens when one path is late?
Inside the engine, a session is a graph. Sources, the tracks; effects on each; buses that gather them; the mix; the output. This simplified routing graph has no cycles; feedback systems require explicit delays and special scheduling, so every node can run once per block after everything that feeds it: the engine sorts the nodes, a topological order, and runs them in that order, every block.
Many nodes come from elsewhere. A plug-in is a node written by someone else and loaded into the host's graph. Steinberg's VST came in 1996, then Apple's Audio Units, Avid's AAX and, in 2022, the open CLAP. The contract is the same: process a block before its deadline, with buffers and scheduling specified by the plug-in API, and report your latency. A look-ahead limiter, from Part 50, must see the future, so it delays its output by its look-ahead. And a delayed path in a graph of parallel paths is a problem.
Here is the problem in its commonest form. Parallel compression: the dry drums plus a heavily squashed copy, for weight without losing the hits. The squashing is done by a look-ahead limiter whose output arrives milliseconds late. Unless the host delays the dry path by the same samples, the two copies meet misaligned. Hosts can do this when latency is correctly reported and compensation is enabled, plug-in delay compensation, delaying every path to match the slowest.
Hear it: the loop with the dry path not delayed, then compensated. Misaligned, every hit has a flam, a doubled attack, and the sustained parts sound hollow and phasey. Aligned, the two copies fuse into one heavier drum.
Why hollow? A sound plus a copy five milliseconds late is Part 49's comb filter: wherever the delay is half a period the two cancel, at a hundred hertz, three hundred, five hundred, every two hundred hertz up the spectrum. Delay compensation removes the comb by removing the delay. One sample of bookkeeping in the engine is the difference between a mix and a mess.
One more trick makes heavy sessions possible. When the graph is too heavy for the deadline, the workstation renders a track offline, freezing it into audio. Offline there is no deadline: the same engine runs as fast or as slow as it needs. Our deterministic engine gives bit-identical offline and block output; real plug-ins can change quality modes or use randomness, so exact equality is not universal. Bouncing renders the whole mix to a file the same way. Real time is a promise about when; offline rendering keeps the promise about what.
11Frontier: learning in the audio thread; networked performanceResearch3 min
Can a network meet a deadline, or a band play across a continent?
Two frontiers meet this part's engine. Neural instruments and effects now run inside plug-ins; RAVE, from Antoine Caillon and Philippe Esling in 2021, runs in real time on a laptop. A fixed network can have a regular operation count, but execution time still depends on hardware and runtime conditions, and it must fit every block's deadline, every time. Many need look-ahead or long blocks, so they add latency the graph must compensate. Learning while playing is harder still: training must happen outside the audio thread. The open question is the best model that never misses a deadline.
The second frontier is distance. In networked performance, musicians in different cities play one piece. Light in fibre travels about two hundred kilometres a millisecond, so a thousand kilometres costs five milliseconds each way before any buffering. Chris Chafe's JackTrip, from Stanford, sends uncompressed audio with the smallest buffers it dares. In clapping experiments, duos keep a steady tempo up to about twenty to twenty-five milliseconds of delay, and beyond it they slow down. Propagation delay is a lower bound; tolerable distance also depends on buffering, routing, repertoire and adaptation.
The engine has also left the studio. The Web Audio API, from 2011, put an audio graph in every browser, and AudioWorklet, from 2018, lets a page run its own nodes in the audio thread. Web MIDI lets a page talk to a keyboard on the desk. This course's interactives use the same graph: a small workstation in a page. Collaborative sessions now share one project from several places, if not one moment. The engine is everywhere, and the deadline comes with it.
A research problem to end on. Take a neural effect and the engine of this part, and measure its cost per block across a thousand runs. Measure tail latency and observed maxima, rather than only averages; a thousand runs cannot establish a guaranteed worst case, because the deadline is set by the slowest block. Trade model size against block size and look-ahead, and judge each by blind listening. The question: what is the best-sounding model that is meeting a specified deadline under explicit platform assumptions? An answer would tell plug-in makers how much learning fits in two milliseconds.
Variation 53, recap and problemsAll tracks2 min
Every part ends by doing something to the Tune with what it built. Here it is first as a four-channel tracker module, lead, bass, arpeggio and drums, played by the engine. Then the whole Tune as a tempo canon, Nancarrow's form: four voices at speeds three, four, five and six, the slowest starting first, each started so that all four arrive together on the last note.
Row fifty-three of the ledger: tracker rows; four voices meeting on the last note after seconds; and the canon rendered in blocks identical, to the last bit, to the canon rendered at once.
What did we find? Music as instructions is old: pinned cylinders, paper rolls, Nancarrow's canons. MUSIC N split instruments from notes, and MIDI is the notes. MIDI 1.0 sends a byte every three hundred and twenty microseconds, with seven-bit data and running status; MPE and MIDI 2.0 go further. A MIDI file stores a performance thousands of times smaller than its sound. An engine must give the same music in any block size, meet every deadline, and time notes to the sample. And parallel paths must be delayed to the slowest, or they comb.
Five problems. One to compute, one to prove, one for your ears, one to build, and a research problem, marked with a star. Solutions are in this part's notes. Pause here.
Where does this come back? In microphones and loudspeakers, the two ends of the chain. In recording and mixing, the session inside the workstation. In live sound, where latency meets a stage. In transcription, from audio back to MIDI. And in machines that compose, trained on MIDI corpora.
And in practice. Producers record with small blocks and mix with large ones. Engineers trust delay compensation and still check parallel paths by ear. Plug-in developers never allocate or lock in the audio thread. And performers use MPE for the slides and swells ordinary shared-channel pitch bend does not express.
The books and papers this part follows. The full list, with notes, is in the README.
Where it goes next. Microphones and loudspeakers in Part 54; the session in Part 56; latency on stage in Part 59; transcription back to MIDI in Part 61; MIDI corpora for composing machines in Part 65.
Key results
The part's results in one place, for revision.
Try it
Lab 53 · MIDI and the engine, computed
Send a chord down a simulated MIDI cable, write and read a MIDI file, render a pattern in blocks of any size and check that nothing changes, and build a tempo canon.
python -m videos.music.labs 53
needs numpy, scipy, matplotlib · download lab53.py ·
source on GitHuba 12-note chord, running status on 25 bytes, 8.00 ms on the wire
a two-note MIDI file 63 bytes; read back 4 events; first bytes 4d 54 68 64 00 00 00 06
pattern in blocks of 256: identical to one block? yes
tempo canon: voices start at (s) 0.00, 0.67, 1.00; they meet at 2.00 s
ear problem: the last three are snapped to blocks or exact (listen first) exact, snapped, snapped
MIDI 1.0 sends a byte every 320 microseconds; running status saves the repeated status byte. A MIDI file counts in ticks. An engine that keeps its state between blocks and places notes to the sample gives the same music in any block size. A tempo canon starts each voice so that all meet on one note.
The code (75 lines; it asserts its own result)
"""Lab 53: MIDI and the engine, computed: bytes on the wire, a file written and read, an engine in blocks, a tempo canon."""
import numpy as np
from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat
from explainer.music.monochord import daw as W
TITLE = "MIDI and the engine, computed"
GOAL = ("Send a chord down a simulated MIDI cable, write and read a MIDI file, render a pattern in blocks of any size and "
"check that nothing changes, and build a tempo canon.")
TASKS = [
"Change CHORD (how many notes) and RUNNING. How long does the chord take on the wire, and how many bytes does it cost?",
"Change PATTERN and BLOCK. Does any block size change the sound? Now set QUANTIZE = True: what moves, and by how much?",
"Change RATIOS. When do the canon's voices meet, and which voice starts first?",
]
CHORD, RUNNING = 12, True
PATTERN = "c4 e4 [g4 g4] <a4 c5>"
BLOCK, QUANTIZE = 256, False
RATIOS = (2.0, 3.0, 4.0)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
keys = list(range(48, 48 + CHORD))
stream = W.encode([W.note_on(0, k, 100) for k in keys], running=RUNNING)
lab.row(f"a {CHORD}-note chord, running status {'on' if RUNNING else 'off'}", f"{len(stream)} bytes, {1000 * W.wire_times(stream)[-1]:.2f} ms on the wire")
tr = [(0, W.note_on(0, 60, 90)), (480, W.note_off(0, 60)), (480, W.note_on(0, 64, 90)), (960, W.note_off(0, 64))]
data = W.write_smf([tr])
back = W.read_smf(data)
lab.row("a two-note MIDI file", f"{len(data)} bytes; read back {len(back['events'])} events; first bytes {data[:8].hex(' ')}")
ev = [(int(a * SR), W.note_number(s), 0.8, int(0.9 * d * SR), "main") for a, d, s in W.pattern_events(PATTERN, 2, 2.0)]
n = int(4.5 * SR)
ref = W.Engine(ev).render(n)
y = W.Engine(ev, quantize=QUANTIZE).render(n, BLOCK)
same = bool(np.array_equal(y, ref))
lab.row(f"pattern in blocks of {BLOCK}{' (snapped)' if QUANTIZE else ''}: identical to one block?", "yes" if same else f"no: largest difference {np.max(np.abs(y - ref)):.3g}")
notes = [(60, 0.0, 1.0), (62, 1.0, 1.0), (64, 2.0, 1.0), (65, 3.0, 1.0), (67, 4.0, 2.0)]
canon, T = W.tempo_canon(notes, list(RATIOS), len(notes) - 1)
starts = sorted({round(a, 3) for v, k, a, d in canon if k == 60})
lab.row("tempo canon: voices start at (s)", ", ".join(f"{s:.2f}" for s in starts) + f"; they meet at {T:.2f} s")
assert (not QUANTIZE and same) or QUANTIZE
# sound: the pattern and the canon; ear problem: snapped or exact, at random
cev = [(int(a * SR), k + 12 * (v - 1), 0.7, int(0.85 * d * SR), "main") for v, k, a, d in canon]
can = W.Engine(cev).render(int((T + 2.0) * SR), 512)
clips = [Clip(0.5 * ref / np.max(np.abs(ref)), SR), Clip(0.5 * can / np.max(np.abs(can)), SR)]
answers = []
hats = [(int((i * 0.125 + 0.013) * SR), 84, 0.6, int(0.05 * SR), "main") for i in range(24)]
for i in range(3):
q = bool(rng.random() < 0.5)
h = W.Engine(hats, quantize=q).render(int(3.4 * SR), 1024)
clips.append(Clip(0.5 * h / np.max(np.abs(h)), SR))
answers.append("snapped" if q else "exact")
lab.audio = concat(clips, gap=0.6)
lab.row("ear problem: the last three are snapped to blocks or exact (listen first)", ", ".join(answers))
fig, (ax1, ax2) = labs.figure(2)
nn = list(range(1, 17))
for run_, col, name in ((False, "C3", "plain"), (True, labs.GOLD, "running status")):
ax1.plot(nn, [1000 * W.wire_times(W.encode([W.note_on(0, 48 + j, 100) for j in range(k)], running=run_))[-1] for k in nn], "o-", color=col, label=name)
ax1.set_xlabel("notes in the chord")
ax1.set_ylabel("ms on the wire")
ax1.legend(fontsize=7)
for v, k, a, d in canon:
ax2.plot([a, a + d], [v + 0.05 * (k - 60)] * 2, color=f"C{v}", lw=3)
ax2.axvline(T, color="k", lw=1)
ax2.set_xlabel("s")
ax2.set_ylabel("voice")
lab.fig = fig
lab.note = ("MIDI 1.0 sends a byte every 320 microseconds; running status saves the repeated status byte. A MIDI file "
"counts in ticks. An engine that keeps its state between blocks and places notes to the sample gives the same "
"music in any block size. A tempo canon starts each voice so that all meet on one note.")
return lab
Now change it
- Change CHORD (how many notes) and RUNNING. How long does the chord take on the wire, and how many bytes does it cost?
- Change PATTERN and BLOCK. Does any block size change the sound? Now set QUANTIZE = True: what moves, and by how much?
- Change RATIOS. When do the canon's voices meet, and which voice starts first?
Problems, with solutions
Try each problem before opening its solution.
-
Compute. With running status, how long does a 10-note chord take to arrive, and how long without?
Solution
With running status: 3 + 9 × 2 = 21 bytes, 21 × 320 µs = 6.72 ms. Without: 30 bytes, 9.6 ms.
-
Prove. Prove that a variable-length quantity of n bytes holds every number below 2^{7n}, and that the code is prefix-free (no code is the start of another).
Solution
Each byte carries seven bits, so n bytes carry 7n bits: every number below 2^{7n} has such a code (with leading zero groups dropped, the shortest one). The top bit is set on every byte but the last, so a reader knows a code has ended exactly when it meets a byte with the top bit clear; no proper prefix of a code ends that way, so no code is the start of another, and a stream of codes needs no separators.
-
Ear. The lab plays a groove with notes snapped to blocks or placed exactly, at random; say which.
Solution
The lab prints them. Snapped grooves limp: the gaps between hats vary by up to a block (21 ms at 1024 samples), so some pairs crowd and some drag.
-
Build. Add a tempo change to the MIDI writer (a second tempo event) and make the reader honour it.
Where to look. Write a meta event FF 51 03 tt tt tt at its tick in the tempo track; in
read_smf, keep a sorted list of (tick, tempo) and convert each event's tick to seconds by summing over the tempo segments before it. -
★ What is the best-sounding model that is meeting a specified deadline under explicit platform assumptions?
Where the frontier is. Measure observed maxima and tail latency per block; finite trials do not prove a worst-case bound. State platform and scheduling assumptions when arguing a guarantee. Measure the cost of neural effects inside a real-time engine; trade model size against block size and look-ahead (whose latency the graph must compensate); judge each by blind listening; and look for architectures whose cost is constant by construction.
Notes and sources
Sources
- MIDI Manufacturers Association, The Complete MIDI 1.0 Detailed Specification (1983–96), Standard MIDI Files 1.0 (1988), MIDI Polyphonic Expression (2018), MIDI 2.0 (2020); D. Smith and C. Wood, "The 'USI', or Universal Synthesizer Interface", AES (1981).
- M. V. Mathews, The Technology of Computer Music (1969); C. Roads, The Computer Music Tutorial (2nd ed., 2023); M. Puckette, The Theory and Technique of Electronic Music (2007); J. McCartney, "Rethinking the computer music language: SuperCollider", CMJ (2002); B. Vercoe, Csound (1986).
- K. Gann, The Music of Conlon Nancarrow (1995); T. Koetsier, "On the prehistory of programmable machines: musical automata, looms, calculators", Mechanism and Machine Theory (2001).
- A. McLean, "Making programming languages to dance to: live coding with Tidal", FARM (2014); S. Aaron and A. Blackwell, "From Sonic Pi to Overtone" (2013); G. Wang, The ChucK Audio Programming Language (2008).
- R. Bencina, "Real-time audio programming 101: time waits for nothing" (2011); Steinberg, VST (1996); CLAP (2022).
- C. Chafe, M. Gurevich, G. Leslie and S. Tyan, "Effect of time delay on ensemble accuracy", ISMA (2004); J.-P. Cáceres and C. Chafe, "JackTrip" (2010); A. Caillon and P. Esling, "RAVE: a variational autoencoder for fast and high-quality neural audio synthesis" (2021).
About this partfrom its README
Part 53 of a sixty-eight-part course in music (see the series plan and
the syllabus), the last part of Act IX, Electric Sound. In January 1983, on a trade-show floor, two
synthesizers from rival firms were joined by a five-pin cable, and a key pressed on one sounded the other. The
specification fitted on a few pages and has run the industry for forty years. This part reads it byte by byte, then
builds what sits on top: files, sequencers, a pattern language, and an audio engine with its hard real-time deadline.
The tools are Monochord's (explainer/music/monochord/daw.py); the cable, the deadlines and the dropouts are simulated.
- A five-pin cable. An ear question (a twelve-note chord, all at once and as MIDI delivers it: which was the cable?); the arrivals (the last note 7.0 ms after the first); Dave Smith, Ikutaro Kakehashi and the 1983 handshake; the plan.
- 1. Machines that play. Music as instructions (the Banū Mūsā's cylinder, about 850; the music box, 1796); a computed music box, heard; paper rolls; forty notes a second on Part 7's piano, heard; Nancarrow; the arithmetic of a tempo canon.
- 2. MUSIC N and unit generators. Max Mathews's MUSIC (1957) and MUSIC III's unit generators (1960); an orchestra and a score; the score played, heard; MUSIC's descendants (Csound, Max, Pure Data, SuperCollider); real time arrives.
- 3. MIDI, byte by byte. One byte on the wire (31,250 baud, 320 µs); one note in three bytes; inside a keyboard (velocity from two contacts); running status (the Tune's first phrase: 42 bytes to 29); how long a chord takes (16 notes: 15.4 ms plainly, 10.6 with running status); the other messages.
- 4. MIDI's limits, MPE and MIDI 2.0. Seven bits (a sweep in 31-cent steps); an ear question (a resonant sweep by a 7-bit controller or smoothly: which was the controller?); one bend per channel (0.024 cents a step over ±2 semitones); MPE (2018); MIDI 2.0 (2020); what MIDI got right.
- 5. MIDI files. Chunks (the first 22 bytes of the Tune's file); variable-length times; from ticks to seconds; the whole Tune in 423 bytes against 6.9 MB of audio, read back exactly; MIDI files at work.
- 6. Sequencers: steps, rolls and trackers. A sixteen-step line with accents and slides, heard; the piano roll; the Tune's first phrase in a tracker (Soundtracker, 1987); the workstation.
- 7. A pattern language and live coding. Five rules (after TidalCycles); two lines expanded over four cycles; how the pattern is read (a tree); the two lines heard; live coding.
- 8. The audio callback. A block at a time against a clock (128 samples at 48 kHz: 2.67 ms); blocks must not change the music (identical to the last bit in blocks of 32 to 2048); what a block costs (measured: small blocks cost more than their share); a missed deadline heard (5 of 1,500 blocks late, simulated); the rules of the audio thread; a lock-free queue.
- 9. Timing inside a block. A sequencer that looks at the clock once a block (hi-hats up to 21 ms early with 1024-sample blocks); an ear question (placed to the sample or snapped: which was snapped?); the latency budget; sample-accurate scheduling.
- 10. The graph, plug-ins and delay compensation. The processing graph; plug-ins (VST to CLAP); two paths, one late (a 5 ms look-ahead limiter in parallel); delay compensation heard; why it sounded hollow (notches every 200 Hz from 100); freezing and bouncing.
- 11. Frontier: learning in the audio thread; networked performance. Neural effects under a deadline (RAVE); networked performance (5 ms per 1000 km of fibre; ensembles hold tempo up to about 20–25 ms); the browser as a studio; ★ research problem: what is the best-sounding model meeting a specified deadline under explicit platform assumptions?
- Variation 53, recap and problems. The Tune as a four-channel tracker module, then as a tempo canon at 3 : 4 : 5 : 6 meeting on the last note; the ledger (32 tracker rows; meeting after 30.7 s; block and offline renders identical); what we found; five problems; where it comes back; in practice; references; Part 54.
What is computed and built
python -m videos.music.music53.compute (under a minute) fills .cache/music53/.
| Item | What it computes | Checked against |
|---|---|---|
hook, bytes |
a chord's arrival on the wire; the Tune's first phrase as bytes, with and without running status | the byte timing (tests) |
musicbox, pianola, musicn |
a music box, a roll on Part 7's piano, a MUSIC-style orchestra | — |
zipper |
a 7-bit controller sweep against a smooth one | the step size (tests) |
smf |
the whole Tune written as a MIDI file and read back | the notes and times (tests) |
steps, pattern |
a sixteen-step line; two lines of the pattern language | the pattern's expansion (tests) |
callback, timing |
the engine in seven block sizes, its cost and dropouts; block-snapped timing | bit-identical renders (tests) |
pdc |
parallel compression with and without delay compensation | the comb's notches (tests) |
tune53 |
Variation 53: a tracker module and a tempo canon | convergence; identical renders (tests) |
Monochord's tools are held in tests/music/test_daw.py; this part's claims and clips in tests/music/test_music53.py.
Sounds. The engine's sawtooth voice, Part 51's ladder and drum circuits, Part 52's Karplus–Strong strings, Part 7's piano and a computed music box. The cable's timing is computed from the specification; the dropouts are simulated.
What the models are, and are not. The cable is ideal: no other traffic, no jitter in the sender. The costs are this part's Python and numba on one computer. The dropouts come from a model of a heavy session (60 per cent load and rare stalls), not from a real audio interface. The pattern language is a small subset of TidalCycles' mini-notation.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: an ear question (a chord down the cable or all at once?); the arrivals; Smith, Kakehashi and 1983; the plan.
- Machines that play: cylinders and the music box, heard; rolls; forty notes a second, heard; Nancarrow; a tempo canon's arithmetic.
- MUSIC N and unit generators: Mathews; an orchestra and a score; the score heard; descendants; real time arrives.
- MIDI byte by byte: the wire; one note; inside a keyboard; running status; a chord's smear; the other messages.
- MIDI's limits: seven bits; an ear question (which sweep was the controller?); one bend per channel; MPE; MIDI 2.0; what MIDI got right.
- MIDI files: chunks; variable-length times; ticks to seconds; the Tune in 423 bytes; files at work.
- Sequencers: a sixteen-step line, heard; the piano roll; the tracker; the workstation.
- A pattern language: five rules; two lines expanded; the parse tree; the lines heard; live coding.
- The audio callback: the deadline; identical in every block size; cost per block; dropouts heard; the rules; a lock-free queue.
- Timing inside a block: snapped to blocks; an ear question (which was snapped?); the latency budget; sample-accurate scheduling.
- The graph and delay compensation: the graph; plug-ins; two paths, one late; compensation heard; the comb; freezing.
- Frontier: learning in the audio thread; networked performance; the browser as a studio; the research problem.
- Variation 53: the Tune as a tracker module and a tempo canon. Outro: problems, payoffs.
Covers: automata, music boxes and player pianos; Nancarrow; MUSIC N and unit generators; the MIDI protocol and
its limits; MPE (2018) and MIDI 2.0 (2020); step sequencers, piano rolls and trackers; the audio callback;
latency; the processing graph and delay compensation; plug-ins; dataflow and live-coding languages.
Built and computed: monochord/daw.py: MIDI 1.0 with running status, its timing at 31,250 baud (a twelve-note chord
spread over 7.0 ms); variable-length quantities and Standard MIDI Files written and read (the Tune in 423 bytes); an
engine of stateful voices, limiters and delays that renders bit-identically in blocks of 32 to 2048 samples, with its
per-block cost measured on this machine; sample-accurate and block-snapped scheduling (up to 21 ms early at 1024);
delay compensation (a 5 ms path combing at 100 Hz and every 200 Hz above); a small pattern language; tracker events;
tempo canons.
Variation 53: the Tune as a tracker module and as a tempo canon at 3 : 4 : 5 : 6 meeting on the last note.
Frontier: learning in the audio thread; networked performance (open: the best model that never misses a deadline).
Reading: the MIDI 1.0 specification; Mathews, The Technology of Computer Music; Puckette; McCartney (2002).
Build the film
python -m videos.music.music53.compute # the part's numbers, into .cache/music53
python tools/build.py music53 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music53 Hook # one chapter, silent, with a contact sheet
Scenes: videos/music/music53. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.music.music53.compute # numbers and sounds (under a minute)
EXPLAINER_TTS=silent python tools/build.py music53 -q l --fps 15 # a silent-narration preview, with the sounds
python tools/qa_sound.py music53 --sync # the sound gates
python tools/dead_air.py renders/music53_480p.mp4 --sound music53 # no empty screen; no sound over a still one
python tools/lecture_length.py music53 # 30 to 60 minutes, listening included
python tools/build.py music53 # 1080p30, narrated
python -m pytest -q tests/music # Monochord against its references; this part's claims and clips
python -m videos.music.labs 53 # the lab (writes a figure and a short WAV)