Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Evolution and analysis

Two parts of the engine work on whole songs at once. Evolution (evolve.rs) searches for a better song by editing blueprints the way a producer revises a track and keeping what the critic prefers. Analysis (analysis/) reads a song from audio, so that a new one can be written on its skeleton.

Mutation

evolve::mutate(blueprint, genre, library, issues, rng) returns a changed copy and a sentence saying what changed. It picks one of 36 operators, applies it, and keeps the result if the blueprint actually changed; otherwise it tries another, up to 12 times, and as a last resort writes every part again with new seeds (rewrote every part).

leveloperatorswhat one does, in the words it logs
harmonyharmony_sub, harmony_newharmony A: chord 2: VI -> iv (third relation); a new progression from a style of the key’s family
drumsdrum_edit, drum_regen, drum_sound, drum_kit, drum_trigdrums (main): added a hat hit at beat 2.75, removed, nudged by a sixteenth, or re-accented; a new pattern from the lane’s template; a one-shot from the library or a nudge of one synth parameter; every lane onto another kit; a step’s trig (below)
partspart_seed, part_style, part_preset, patch_tweak, part_register, part_density, rack_layerbass: rewrote the part; chords: style stabs -> charleston; a preset from the genre’s list; cutoff, resonance, release, drive or detune of a synth patch; the register moved by 3, 5 or 12 semitones; a lead’s density; a stacked sound’s layer 2.5 dB louder or quieter at most, or a crossover between its layers moved a third of an octave, both layers that meet there with it
instrumentstrack_add, track_removepad in, on synth patch 'warm_pad': a part its genre writes that the song left out, playing where the genre’s forms play it, or one layer of those a more layered song plays (compose/layers.rs: a pad, a counter-melody, an arpeggio, a double of a part, a clap, a shaker or a percussion line), kept only if a section plays it; shaker out of the song: a part or drum lane that only colours it, never one every song of its genre has
mixmix_level, mix_send, mix_duck, mix_pan, spacemix: bass -1.3 dB (now -1.3); a reverb or delay send; a part’s sidechain depth; the pan of anything but kick, bass, snare and clap; the reverb’s decay or the delay’s time
effectsfx_tweak, fx_add, fx_remove, fx_eqkeys: filter cutoff 2400 Hz, one setting of an insert effect moved a little (a cutoff, a rate or a decay by up to a third, a mix or a feedback by a tenth); an insert effect the track takes, set as the genres set theirs (drive on the kick and bass, drive or a sharper attack on the other drums, a chorus, phaser, tremolo or tape on harmony, a delay, chorus or drive on a lead); one of those taken off again; pad: -2.1 dB at 400 Hz, the band a band issue names, cut or lifted on a track that lives in it
formform_layer, form_bars, form_flags, form_variant, form_change, form_buildform: lead out of break; a section 4 or 8 bars longer or shorter (4 to 48); a fill, gap, impact or filter sweep switched; a section’s drum variant; form: verse2 and chorus2 again after chorus2, form: intro left out, form: drop2 on progression B, unlike drop (below); form: build builds classic -> drop_out, or harder or gentler
feeltempo, key, swingtempo 128 -> 126 BPM within the genre’s range; key A minor -> C minor (tonal loops follow); swing nudged
samplesloop_swap, loop_chopanother Apple Loop for a loop part; break: slice 6 plays slice 3, a sampled break or phrase re-chopped as the sampler chops one (half-beat slices, every fourth where it was), in a genre that chops them, or a slice back in its own place

Every operator stays inside what the genre allows: styles and presets from the genre’s lists, tempo within its range, levels within −12 to +9 dB, pans within ±0.7. Nothing widens the low end: the kick and the bass take drive, never a chorus, a widener or a delay.

drum_trig programs one step of a lane as a drum machine’s trig, never the kick’s: a hat, shaker, ride or percussion hit that is not an accent plays by chance (50 to 90 % of the time), a hat rolls in two to four strokes only in a genre whose hats roll, a snare or clap is flammed (12 to 30 ms) or laid back (by up to 0.15 of a sixteenth), a percussion hit is tuned, and any hit is made brighter, darker, shorter or longer; a quarter of the time a step that has a trig plays plainly again.

drum_kit moves every drum lane onto another installed kit: the genre’s kits first, then tr909, tr808, tr707, muldjord and uzu, never the kit the song is already on. When the song is on a kit, one time in four it goes back to the synthesized voices instead. It logs drums: played on the tr808 kit or drums: back to the synthesized voices.

Issues steer the choice. All operators start with weight 1. For each of the verdict’s four worst issues, the operators that address its target are multiplied by 1 + 4 × severity: a band:sub+ issue of severity 0.5 makes the level, drum sound, kit, patch, space, pan, equalizer and effect-setting operators three times as likely. mix_level goes further and, three times in four, turns the track the band issue points at the right way (too much sub turns the kick or bass down), and fx_eq works only on a band issue; the part operators pick a part an issue names seven times in ten. A width- issue has fx_add widen harmony (a chorus, an auto-pan or a widener), a width+ one has fx_remove take a widening effect off, a sound:<part> issue brings in the rack and effect operators too, and a genre issue the instrument and trig operators.

The form is revised toward its issue. form_change makes one change of form::change, aimed at the verdict’s worst issue with the form, or at anything when it has none (the critic’s form checks say what each issue means):

issuechanges tried
form:shorta section to the next length its kind takes; the last verse and its hook played again where a third would go, or in a drop genre the last drop with the break and build into it; the last peak twice; a bridge
form:longa section to the next shorter length; the intro or the outro shorter or left out; a section heard earlier left out again, with the build into it
form:introthe intro shorter, or left out
form:sameof two neighbours alike, the second without one of its parts, with one of the next peak’s, or on the other progression; a bridge, or a lift into a hook
form:sectionthe longest section shorter
form:peaks-, form:peaks+the peak and its way in again, or the last peak twice; a later peak left out

A revised form keeps three sections at least, a peak, builds that lead into peaks, sections that rest on a track sure to play, names of their own (a second verse2 becomes verse3) and the section a take starts from. A length issue also turns form_bars the way the song should go.

Every mutation appends its sentence to the blueprint’s lineage, so a song carries its own history.

Crossover

evolve::crossover(a, b) makes a child from two parents in one of two ways, half the time each: the drums and form of one with the harmony and parts of the other, or the drums of one with everything else of the other. Both keep a coherent song, because the harmony and the parts written over it travel together.

evolve::run is a (μ + λ) search: every candidate ever judged stays in the pool, and each generation’s parents are the best population of all of them.

initial songs ──judge──▶ pool
                          │  each generation:
                          │    parents = best `population` of the pool
                          │    children: pick a parent (biased to the better ones),
                          │              crossover with another parent (20 %),
                          │              then 1 or 2 mutations steered by the parent's issues;
                          │              skip any blueprint already seen
                          │    judge every child in parallel (rayon) and add it to the pool
                          ▼
                     every candidate, best first
  • Previews. A candidate is heard on its build-up and first drop, not the whole song: preview_window takes the first drop or hook and up to 16 bars before it, preview_bars (32) in all, and the rest of the song is cut away with Project::slice. A whole song takes seconds to render; a preview a fraction of that, so a generation of eight children takes 10 to 40 s with the ears. The mix, the arc, the time and the ears are the preview’s, and the notes and the form the whole song’s (judge::judge_whole), so a section added, left out or lengthened outside the preview counts all the same.
  • Duplicates are skipped by hashing each blueprint’s JSON, so the search never judges the same song twice.
  • Parents are drawn with min(random(n), random(n)), which favours the better half without ignoring the rest.
  • Stopping. A cancel flag is checked before each generation.

Each candidate records its id (g2-1: generation 2, child 1), its parent, what changed and its score. The command line writes them all to evolution.json and renders the best in full; the session keeps the best only if it beats the song it started from.

The studio’s Variations (the mutate command and MCP tool) is a single generation without crossover: count children of the current song, one or two mutations each, steered by the current song’s issues, judged on the same 32-bar previews, and the best kept if it beats the current song’s preview score.

Reading a song

analysis::song::analyze(audio, tempo_range) reads a whole mixed song the way a producer does before remaking it: tempo, downbeat, key, the chord of every bar, sections with their energy and what plays in them, drum habits per sixteenth, swing and a bass style. It uses no models: everything is signal processing in analysis/.

filewhat it does
onsets.rsonset strength as log-compressed spectral flux, optionally in a frequency band; peaks above a moving median; onsets refined to where the energy starts rising: the first millisecond above a tenth of the loudest, from a hop before the peak frame’s window to a hop after it (log flux peaks when an attack first comes into the window, at its end)
beats.rstempo from the onset envelope’s autocorrelation, its grid’s fit to the onsets and the kit’s backbeat, beats by dynamic programming (Ellis 2007), then a constant-tempo grid, or the beats a band plays when they drift off it, and the downbeat
chroma.rspitch-class energy, keys by Krumhansl-Kessler profiles, chords by template matching
melody.rsa take’s melody as notes, read by voice/ (below)
structure.rsthe sections, as the song’s own: where each starts, which play the same music, what each is, where a build resolves
song.rsthe rest: each section’s energy and what plays in it, the phrases sung, progressions, drum steps, swing, and to_blueprint
groove.rsthe groove of a recording’s drums (below)
drums.rsa beat’s hits, played or beatboxed, named kick, snare or hat and folded into lanes (below)

Tempo. The onset envelope adds the full-band flux to twice the kick-band flux (30 to 160 Hz), because in dance music the kick marks the beat. The peaks of its autocorrelation (helped by the autocorrelation at twice the lag), from 55 to 200 BPM, are the tempos it might be, each also at twice and half its tempo. A syncopated kick or a dotted rhythm repeats at four thirds or two thirds of the beat about as strongly as at the beat, so a peak alone is no answer: of each tempo the tracker asks how well its grid lies on the onsets, its beats, eighths and sixteenths at the phase that suits each stretch of 16 beats, weighted 1, ½ and ¼, against the envelope’s mean (salience). A tempo a third or a quarter off the music’s puts most of its grid between the onsets; one at twice or half of it lies on them nearly as well as the music’s own. Of the tempos whose grid lies within 5 % of the best one’s (25 % when the drums are heard apart from the rest), it keeps the one nearest the tempos songs are played at, a prior centred on 110 BPM (or on the middle of the range a genre gives) with a spread of 0.6 octave, whose kit plays a backbeat (backbeat): in a cycle of two beats, the snares on the second and the kicks on the first, less the snares on the first and the kicks on the second, from the drum hits heard (below). A kick on one and a snare on two and four give most; at twice the tempo the snare falls with the kick, at half of it between the beats. With the drums apart (the ears’ stems), the backbeat counts for much (e^(3·backbeat)), and it is what keeps a slow song from being heard at twice its tempo; in a whole mix, where a chord or a bass note is heard as a hit as often as a drum, for little (e^(0.5·backbeat)). On claudius’s own renders of 14 genres from R&B at 62 BPM to drum and bass at 175, three songs each, the whole mix is heard at its tempo 34 times in 42 where it was 21, and the drums apart 38 times; on 20 other genres, two songs each, 31 in 40 against 26 for the mix, with three tempos a third or more off rather than seven, and 31 for the drums apart as before. What it still hears at twice or half are the songs listeners differ on too: R&B and reggae under 80 BPM at twice, the trap and drill family at 70, where their snare on the third beat is a backbeat. In a whole mix the dynamic programming lets a beat last 0.9 to 1.1 of the tempo’s: a band strays a few percent from its tempo and comes back, which fits, while the looser range a kit heard apart still has (half to twice) followed a syncopated riff or bass line struck harder than the beat for a few bars and slipped a beat into the count, sliding every bar line after it across the beat (five times in Men at Work’s “Down Under”). Beats tracked by dynamic programming jitter by a frame and insert or skip beats through breakdowns, but music made in a DAW keeps one tempo, so the tracker then fits a constant grid around the slope of a line through the tracked beats (finer than the median gap between them, which is a whole number of 5.3 ms frames: 117 or 118 at 96 BPM, nearly 1 % apart), trying every tempo within 0.5 % in steps of 0.005 BPM and every phase, and keeps the one that lands on the most onset energy.

A band’s tempo. A band speeds up and slows down, and a grid of one tempo drifts off it: a band that goes from 92 to 98 BPM over 80 bars is several beats away from any one tempo by the end. So the tracker also keeps the beats as it played them: the tracked beats with a skipped one put back and one slipped in left out, each moved onto the line through it and the eight beats on either side (which takes out the jitter and keeps the drift). When somewhere 16 of them in a row sit more than an eighth of a beat off the grid, all one way, and they land on 5 % more onset energy than the grid does, those are the beats (Grid::steady false) and the tempo is their middle one. The bars (Analysis::bar_starts) are every fourth beat from the downbeat, back to the start of the recording at the first bar’s length; everything measured bar by bar (the chords, the loudness, the drum steps, the swing) is measured over each bar as the band played it, and every piece cut from a recording is cut on those bars and made one tempo (Analysis::cut, warp::flatten): each of its bars stretched to the recording’s mean bar, in one stream through Signalsmith Stretch, so that the renderer’s warp to the song’s tempo lands every bar on the song’s. A recording that keeps one tempo is cut as it was.

Downbeat. Of the four beat phases, the downbeat is the one with the best mix of its cues, each scaled to its best phase: a change of harmony across the beat (chroma a bar before against a bar after, weight 1.5), the biggest level jumps (sections start on downbeats, 0.75), and kick strength (0.5); in a whole mix also the kit’s backbeat (1.5), the kicks on the bar’s first and third beats and the snares on its second and fourth, less the other way round. Harmony leads because level jumps also come from pre-drop gaps and risers, and kick strength from rolling basses. The backbeat tells a bar’s one and three from its two and four where the chords change a push ahead of the bar, as pop, rock and reggae often do (a phase and the one two beats on score alike: the other cues tell one from three). On the beat benchmark’s held-out half (557 songs of MTG-Jamendo against librosa’s beats, 668 of people’s loops from the Freesound Loop Dataset against their own grid), the narrower range and the backbeat together keep more of a song’s bars in step (+0.015 of them, +0.058 when it is played drifting as a band does) and put more of a loop’s bar lines on its downbeats (from 0.185 to 0.267), with no measure worse.

Key and chords. Chroma comes from FFT bins close to an equal-tempered pitch, so drums and noise smear less into it. The key is chosen among the four best Krumhansl-Kessler fits of the loudness-weighted average chroma, by its fit plus how many bar chords it explains diatonically, how often its tonic chord appears, and how much bass sits on its tonic. Each bar’s chord is matched against triad and seventh templates, with a pull towards the key’s diatonic chords, using a bass chroma read in the second half of each of the first three beats, where the kick has decayed and a sidechained bass has swelled back.

Sections (structure.rs, design record 0022). Each bar is heard as its harmony (the pitch classes of each of its four beats), its timbre (twelve cepstral coefficients of its spectrum), how loud and how bright it is, its kit (its drums apart, else how strongly its hits strike over the bar), its bass, and how much of it a voice sings (the words cuts hears in the vocals, over the bars round each so that a breath between lines is no change). A section starts where how the bars sound stops being like it was (Foote’s checkerboard novelty over the similarity of every pair of bars, at 4 bars and at 2), where the chords a passage plays change (whatever their order), where a run of bars that comes back 8 bars or more later starts or ends (a diagonal stripe in the harmony’s similarity, which marks both verses’ starts however unlike the bars within each are), and where the voice, the kit or the loudness comes in or goes. Each change is scaled to the song’s clearest but never by more than a real change measures, so that a loop’s noise is no boundary. Of every way to cut the song, dynamic programming keeps the one whose boundaries are most novel, less a cost for each, under a preference for sections of 8 and 16 bars that never forbids another length (17 bars stays 17 where the boundary is clear), the bars counted as a phrase’s: a bar over 3.2 s (a slow song, or one heard at half its tempo) as two, one under 1.6 s as half. Sections that rise together, bar by bar, into a louder one are one build. With the stems apart, what the voice sings, beat by beat, counts as much as the chords in the stripes and in the letters of two sections both sung: a song on one loop of chords tells its verse from its chorus by the tune. Sections whose chords, tune and sound go on alike (the chords moved up to two semitones, as a last chorus may be) share a letter, by average linkage.

What each is. In a song a voice sings a quarter of at least, the chorus is the music it sings again and again that is loudest and sung most, ends the singing and does not start it; the verse is the other music it sings again and that leads to the chorus; a pre-chorus comes between; a post-chorus is loud music no one sings right after a chorus; a bridge is sung once, after two choruses or after one and 8 bars long; the intro and the outro play before the voice and after it, and an instrumental or a break between. Without the stems the voice is not heard, and a song is taken as sung wherever it plays fully. A track no one sings in (the stems apart and the vocals all but silent) is named by loudness: drops are the loudest sections with the kit and the music they play, a build comes before a drop, the intro before the first and the outro after the last, a break is quiet or has no kit, a groove the rest. Each section’s energy is its loudness scaled between the quietest and loudest sections, from 0.3 to 1, a groove’s 0.72 for all of them when they are within 1.5 dB of each other. A section builds over its last bars where they rise, bar by bar, into a louder section, which resolves the build where it starts, and a piece of a section is cut at its first bar’s line, or before it in the quiet before its first phrase where that is sung before the bar.

On JamendoLyrics, 78 songs whose lyrics are timed line by line and written in stanzas (examples/eval_structure.rs), 60% of the stanzas that start other music are heard within a bar of a section’s start, against 14% for the 4-bar blocks this replaced, and on 60 recordings of SALAMI the boundaries within 3 seconds of the annotated ones score an F-measure of 0.49 against 0.36; naming the chorus is the weak part (53% of the choruses heard as such from the mix, 51% with the stems apart, and 38% and 32% of the other stanzas taken for one). The record has the numbers in full.

Progressions. In the loudest drop, the chords are tested for repeating every 2, 4 or 8 bars, and the cycle that agrees most becomes progression A; when the chords come in pairs, it becomes one chord per two bars. Progression B is read the same way from the longest break or intro.

Drums, swing and bass. The kick, snare and hat onset envelopes (by band) are sampled at every sixteenth of every bar in the sections with a kick and energy of at least 0.6, averaged, and turned into lane templates: a step that hits in almost every bar becomes certain, weaker steps become probabilities. Swing is the median position of hat onsets in the second half of each eighth. The bass style is guessed from the kick’s step profile: rolling when ten or more sixteenths are busy, offbeat when the off-beat eighths carry more than 55 % of the on-beat weight, sustain when at most two are busy, syncopated otherwise.

Hearing a groove

analysis::groove::hear(audio, bpm) measures where each sixteenth of a recording’s bar lands and how hard. Everything rests on the grid, and a groove measured against the wrong sixteenths means nothing, so a tempo that is known (given, an Apple Loop’s in GarageBand’s catalogue, or 92bpm in the file’s name) is only tuned, within 3 %. Otherwise the song analysis guesses one, which on a short loop is often off by 3:4 or 4:3 or a few percent (on twelve of Apple’s drum loops it was right for four), and the drums’ onsets choose:

  • The tempos tried. The guess and its octaves, and for a recording of 40 seconds or less the whole bars it lasts (half a bar, 1, 2, 4, 8 or 16), which give a loop’s tempo exactly. Less likely, and winning only when they fit clearly better: 3:4, 4:3, 2:3 and 3:2 of the guess, and 3, 6 or 12 bars. Over a bar or two a guess tuned freely fits anything near, so in a recording of 12 seconds or less one within 3 % of an octave of the length is dropped.
  • How well each fits. Each is tuned in steps of 0.01 % to where the onsets sit nearest its sixteenths: the mean squared distance, in sixteenths, weighted by loudness, with the grid’s phase where the distances balance. The on-beat and the off-beat sixteenths are measured each from where they land on average, so a swing costs nothing; otherwise a loop swung at 62 % fits the grid of triplets half as fast again better than its own.
  • The tempo. The slowest that fits about as well as the best (a grid twice as fine always fits at least as well).
  • The downbeat. The beats are the sixteenths of four that the loud onsets fall on, and the downbeat is the beat with the most energy under 120 Hz.

On fourteen of those loops this finds the tempo of nine of the thirteen it can read (one has too few hits). Three of the others come out an octave off, which is where the drums sit on sixteenths either way. Telling which octave a drummer counts takes knowing a snare from a kick, which the onsets alone don’t. With the catalogue’s tempo, all thirteen are right.

Each onset is then set against the sixteenth nearest it. Each of the sixteen positions takes the median of its onsets’ distances from the grid (a position with fewer than two keeps no timing), clamped to 0.12 beats, and their mean loudness against the recording’s, clamped to 0.4 to 1.3, as its accent. The beats are put back on the grid by the mean of their timings, so a downbeat found a little early or late doesn’t move the whole groove.

Hearing drums

analysis::drums::hear(audio) names the hits of a beat, played on a kit or beatboxed, and fold sets them on a grid (a take’s, from its first beat at the song’s tempo; a file’s, from groove::beat) and folds the times round into a pattern of 1, 2 or 4 bars.

  • The onsets. Those of the whole sound and of its top over 5 kHz, which finds a quiet hat under a kick’s tail, merged within 25 ms (a kick’s body arriving after its click is the same hit).
  • What each adds. Every band at its strongest in the 50 ms after the onset, in 20 ms windows (a period of the lowest kick), less its level in the 20 ms before: the tail of the hit before is not part of this one. Of that, the shares under 150 Hz, in a drum’s body (150 to 800 Hz) and over 5 kHz. An onset that doubles none of the whole sound, its low band or its high band is a ripple inside a sound, and one 30 dB under the loudest hit is breath or the room.
  • Naming. Three clusters of those shares, started amid the quarter of hits that lie most low, most in the middle and most high, so a stray sound can’t take one. Each is named by where its middle lies, and kept only if that is near its kind: a kick’s 0.12 under 150 Hz, a hat’s 0.2 over 5 kHz with next to nothing in the body, a snare’s 40 % between. Otherwise the recording lacks that kind (a loop of kicks alone still makes three clusters), and its hits are named alone: a quarter under 150 Hz is a kick, a half over 5 kHz (or a fifth, with nothing in the body) a hat, the rest a snare. Those thresholds come from the shares of about 2,400 hits in GarageBand’s single-drum loops. A snare whose noise lies over 5 kHz more than from 800 Hz to 5 kHz is a hat: an open hat, which a snare’s and a clap’s noise lies the other way round from.
  • A second sound. A hit that adds to another kind’s band far more than hits of its own kind do there (a quarter of them add less) is that kind too: half what that kind’s own hits add, or, when every one of them lies under other hits (open hats on the kicks), three times what its own kind adds. A kick that adds from 800 Hz to 5 kHz half what the louder snares (the loudest quarter) add there, beyond what kicks usually do, has a snare or a clap on it, as house claps on the kick’s two and four; a rim on the kick adds about a third of that.
  • Folding. A step hit in at least three quarters of the times round is a hit; one hit in a quarter to three quarters plays with that chance (a trig’s prob). Its velocity is its median level against the loudest of its kind, to the power 0.6.

Measured on kits, against 15 mixes of a kick, a snare and a hat loop from GarageBand at one tempo (each loop’s own onsets the truth): kicks 89 % precision and 95 % recall, snares 68 % and 56 %, hats 91 % and 59 %. The hits missed are mostly quiet hats under other hits and snares layered with a sub, which add as much under 150 Hz as a kick does. On beatboxing, against 20 four-bar beats built from the recordings of a published beatbox dataset (Mehta and others, 2022; maxardito/beatbox on Hugging Face), one performer’s kick, snare and hat each, hits are found nearly all the time (98 to 100 % recall). The kicks are the weak kind, at 49 % precision: a beatboxed snare’s release, 12 to 27 dB under it and a sixteenth later, is heard as a kick, and telling it from a ghost note a sixteenth after a hit would take more than level. Snares are at 65 %, hats at 87 %.

Writing a new song on it

analysis::song::to_blueprint(analysis, genre, seed, ...) generates a song in the genre at the analysed tempo and key, then replaces its skeleton with the analysis: progressions A and B and their chord length, the swing, and the form, one section per analysed section with its length rounded to whole 4-bar phrases, its energy, and layers chosen from what was heard (the kick when there was a kick, hat-like lanes with hats, bass and chords by energy, the lead in drops and breaks). Intros filter in, sections before a drop build with a gap, drops after something else get an impact, quiet sections use the sparse drum variant. The kick, snare, clap and hat lanes get new patterns drawn from the analysed templates, and the bass takes the analysed style when the genre has it. The sounds and the mix come from the genre. claudius remake --skeleton and the remake command with sampled: false do exactly this, and the song’s history begins with remade from <file>: <tempo> BPM, <key>, <n> sections, progression <numerals>.

Its stems

With the ears, a remake first separates the recording into its vocals, its drums, its bass and the rest (crate::stems, Spleeter’s four nets through earshot::separate): about 8 s for a four-minute song, once, kept in memory and in the cache folder (stems/, the three recordings separated last, as 24-bit FLAC) by what the recording is. The nets come down the first time they are needed once the ears have been asked for (Ears::load); without them, or without the ears, nothing is separated and everything below hears the mix as before. The analysis then hears each thing in its own stem (analyze_with): the beats and the drum habits in the drums when a kit plays (a recording whose drums hold under a twentieth of its power has none, and its sections no kick or hats), the chords in the bass and the rest without the voice’s melody over them, the bass under each chord in the bass, and where the voice and the kit come and go among the cues for its sections.

Reworking it

A remake is a rework unless asked otherwise (remix::rework), which keeps the recording the song it is. With its stems apart, the rest of it above its bass, from its first downbeat to the end of its last bar, is a loop track, original, that plays once from the first section through all of them (a take’s from), through the genre’s treatment of a phrase it samples with a high-pass at 80 Hz; its drums and its bass are left to the genre’s. When it sings (its vocals hold a twentieth of its power, Stems::sung), its voice is another such track beside it, vocals, with the vocal role and a vocal’s mix (remix::voice_mix: high-passed at 100 Hz, compressed, with less reverb, delay and ducking than a sampled phrase, since its own room is in it, and 2 dB louder, the song’s own singer on the genre’s drums and bass), and original holds its voice only when it does not sing (and is left out when the rest holds under a fiftieth of its power, a voice over a beat). Without the stems the recording is split into what sustains and what strikes (fft::harmonic), and what sustains is the loop, with the high-pass at 150 Hz at least, which leaves the low end to the genre’s bass and kick. The song generated in the genre at the recording’s tempo (rework_tempo: from the length of its bars, doubled when that is nearer the genre’s range, two bars of the song to each of its own, or halved, one to two of its own, when that is nearer and the recording holds each chord two bars, three pairs in four, since a bar of the song plays one chord; so that the loop is not stretched) and in its key then takes the recording’s skeleton exactly: one section per analysed section, as long as it was heard, its kind and energy, the layers of the genre’s section most like it (of its kind, else the nearest in energy) that play under a recording (drum lanes, the bass, the break and the textures, not chords, keys, pads or leads, which would play against its own and against it where a chord was heard wrong), a progression per run of its bars’ chords at one chord a bar, and the recording’s swing. Parts the sections do not play are left out. The recording’s sections are brought halfway to the middle of their levels (sections_levelled: by 9 dB at most, the gain moving over the last beat before a section; a section 30 dB under the loudest is a rest and is left as it is), since the genre’s drums keep one level. The history says reworked from '<file>': all <n> bars of it, ....

Flipping it

With flip, a remake is a new song on the recording’s sound (remix::remix): the recording without its drums (its bass and the rest, with the stems apart, its voice left to the sampler’s phrases, unless the bass and the rest hold under 15 % of its power, remix::BACKING, when its vocals stay in; else what sustains of it, fft::harmonic) and its drums (its drum stem; else what strikes), cut into the pieces a producer would take from it, on the bars it plays. A hook a voice sings in (the recording sings, and its voice was not taken out) is offered at its own pitch only, and not re-chopped (remix::own_key: the genre’s pitch narrowed to none and its chop to 0), wherever a way of playing it so meets the genre’s tempo, unless the genre’s producers speed their singers up (speeds_voices, chipmunk soul’s). In a genre whose phrase says how far under its range it plays a record at the record’s own speed (under, trip hop’s 0.25), such a hook is stretched by a tenth at most (remix::SUNG_STRETCH, to the range’s nearest edge; where nothing stretches, as in the web studio, the song takes the nearest of the hook’s own tempo, half or twice it, just outside the range instead, which a sampler meets at the voice’s own pitch): further than that, the song plays at the hook’s own tempo, half or twice it, the fastest of them under reaches below the range (remix::sung_tempo: a pop record of 125 BPM as trip hop at 62.5), with the genre’s drums in place of the recording’s, which would play on at twice the song’s tempo. Its pieces are chosen by the scores the Sample window offers pieces by (kinds::cuts_of): its hook (remix::hook_of, a loop of the hook of eight bars, else four or two, from the hook’s sections), another passage as long (passage_of, from none of them) and its drums (break_of, a drum break of the lengths a break takes), each the best on take 0 and drawn among the near-best for any other seed, as another take is; where no loop of the hook can be cut (no chord rings in it), the hook falls back to the first bars of the section with chords that pulls most toward being one (hook_bars). The hook without its drums is offered to the sampling pipeline as the phrase a song is built on (sampling::apply, through a library that holds only the recording’s pieces and the libraries’ one-shots, loops and textures), with the other passage as the phrase’s second passage and the drums as the break where the genre samples one. So the song takes the hook’s key and chords and a tempo the genre plays, the recording’s own or a multiple of it (sampling::meets). A flip of it follows: as many bars as the hook of half beats, each from another bar of the recording on the hook’s chord at that place, each bar brought to the hook’s level (bar_gains, by 18 dB at most, a rest left as it is), in the intro, the breaks and the outro where the other passage does not play. Then the sampler brings in its sung phrases, from the recording as the remix heard it (sampler::sample_from: its stems and its analysis, not separated or analysed again). A recording with no section with chords long enough falls back to the skeleton, and the reply says so. The song’s history says what came from where: remixed from '<file>': its hook (bars 33-36) without its drums; ....

Rebuilding it

With rebuild, a remake is the song itself made again on claudius’s sounds (rebuild::rebuild), so that each note can be changed. What it heard comes first (rebuild::played), and the song is written from that alone (rebuild_with, which the tests feed with what they say was heard):

  • The form is the recording’s sections, each its own kind, length and energy, its drum variant named after it, and on a progression of its own (A, B … one to a section, unlike a rework’s one to each run of chords), its bars’ chords at one a bar. A part’s written notes are kept per progression and tiled from a section’s start (arrange::tile), so a progression to each section is what lets every section play its own notes. The tempo is the recording’s own (Analysis::cut_bpm), its band’s speeding up and slowing down taken out: a time in it is a beat of the song through its bars (Analysis::bar_at, bar_start).
  • The drums are the hits analysis::drums::hear finds in its drum stem. Each section’s are folded into a pattern of its own (fold, four bars or as many as the section has), written into the genre’s kick, snare (or clap) and hat lanes as the section’s variant (script::put_hits), with a trig’s chance where a step plays only some of the times round, at sixteenths and in the recording’s swing (the genre lane’s own speed, length, swing and groove undone). Each lane is as late or early as its hits on the beats are on average, which no swing moves (late_ms, within 3 ms none, 40 ms at most). Without a drum stem, the drum habits of the busiest sections (kick_steps …) play wherever the kick is heard.
  • The bass and the rest are the notes of their stems as Basic Pitch hears them (transcribe::notes, through earshot::notes), the bass from 30 to 500 Hz with notes of 80 ms and more (a pickup a sixteenth long is under Basic Pitch’s own 128 ms at 120 BPM), the rest from 55 Hz to 4.2 kHz with 100 ms. A stem’s notes 18 dB under its loud ones (the tenth loudest) are another instrument’s bleeding into it, which the model hears as surely as the stem’s own (rebuild::own). A note an octave, a twelfth, two octaves or two and a third or a fifth over one it starts with, which the model is half as sure of again, is that note’s overtone. The bass plays one note at a time (of notes struck together the surest, or the lower of two nearly as sure, each cut where the next starts); the rest plays chords and all. Both are set on the sixteenths, their velocity from how sure the model is, and each section’s are written for its progression, the part in the sections it plays in, on the genre’s bass and keys (or chords) part’s sound and mix. Without the ears, the genre’s bass and chord parts write their own on the recording’s chords, where its bass and harmony are heard.
  • The voice, when it sings (Stems::sung), stays on vocals as a rework’s does, and its melody (analysis:: melody::transcribe, in its key on the sixteenths) is written out on a lead, melody, that plays in no section.

Its history says what it heard: rebuilt from '<file>': its 4 sections bar for bar, on its chords; its drums struck as it strikes them, each section's folded into a pattern of its own (113 on clap, 232 on hat, 243 on kick); its bass as 214 notes on bass; the rest of it as 866 notes on keys. Against a render whose notes are known (the cookbook’s house song), 99 % of the rebuilt kicks and 98 % of its hats land on sixteenths it strikes, missing none, and two thirds of its claps; the bass notes are 87 % right (pitch and sixteenth) and 93 % found, the rest’s 67 % and 71 %.

Where it goes wrong

Analysis is best on steady electronic music with a clear kick, and approximate everywhere. Reading claudius’ own D minor deep house song back:

118.0 BPM (pulse clarity 0.55), Bb major (confidence 0.43), swing 0.50, 52 bars from 0.00 s
  progression A: iii7 Imaj7 vi7 vii  |  B: Imaj7 Imaj7  (1 bar(s) per chord)

The tempo and the first downbeat are exact. The chords of A (Dm7, B♭maj7, Gm7, Am) are the song’s own (Dm7, B♭maj7, Gm7, Am7) in the right order, named in B♭ major, the key of the song’s sixth degree, with the seventh of the last one missed. Progression B, read from a 12-bar break, came out as two bars of B♭maj7, the first of the song’s four chords. The usual failures are these: half or double tempo (a genre’s tempo range fixes most), a relative or neighbouring key, a progression rotated when the first downbeat lands a beat or a bar off, and sections merged when their energy is close. CLAUDIUS_DEBUG=1 prints the downbeat cues per phase.

Hearing a melody

voice/ reads a voice, one note at a time: its pitch, the notes it means, and how its singer sings. analysis::melody::transcribe(audio, key, options) uses it to turn a take’s melody into notes for take::melody (the transcribe_take command), and voice::assess and take::assess (assess_voice) to say how it is sung.

  • Pitch (voice/pitch.rs). The take is mixed to mono, low-passed twice at 3 kHz and decimated to 8 kHz, which leaves a voice’s fundamental and its first harmonics. YIN (de Cheveigné and Kawahara 2002) reads a pitch from 50 Hz to 1 kHz every 10 ms, over a 50 ms window: the first dip of the cumulative mean normalised difference under 0.15, refined between samples by a parabola, and its depth is the frame’s clarity. A frame more than 35 dB under the take’s loudest is unvoiced, whatever its pitch, and a frame more than four semitones from the median of its five neighbours (an octave or a harmonic jumped to) takes the median. Each voiced frame’s period is then found again at 48 kHz, within 3 % of YIN’s, as the lag that differs least from itself over 20 ms, which reads a held pitch to a cent. pitch::rough skips that, for the sampler’s look at whole songs.
  • Where the notes are (voice/intent.rs). A hidden Markov model over the notes the take may be singing (pYIN’s note tracker in Tony, Mauch et al. 2015, works the same way): each note has an attack state, which reaches a semitone or so for scoops and slides and costs half its likelihood, and a hold state, read from the pitch’s median over 150 ms, which keeps a note’s edges and loses its vibrato; silence is a state of its own. A frame without a pitch is likelier in silence (0.9) than in a note (0.1), and a rise of more than 3 dB within 30 ms speaks for an attack. A hold is left at 2 % a frame, an attack settles at 20 %, and silence starts a note at 3 %. Viterbi gives the states; a note runs from where the path enters its attack to where it leaves the note or attacks it again, and notes under 70 ms are dropped. A note is settled from the first of three frames within 30 cents of its median, and its place is the median after that.
  • Which note each one is. A singer puts a note off by so much for the whole of it, so frames, which would make any small error certain, do not decide it. A chain over the notes does: each note is read once, from its place, as a normal around where this singer puts each candidate (Voice::bias_at) with their scatter (Voice::spread_at), and a note follows the one before by the song’s weights (1 for a tone of the key, 1.6 for a tone of the chord under the note, 0.12 for any other) and the step (0.8 for the same note, falling by e for every 5 semitones beyond the first); after a silence of more than a second the step counts for nothing. Viterbi names the notes and forward-backward gives each its sure. The wider the singer’s scatter, the further the song moves the line between two notes: in C major, from anyone’s 30 cents, a note is read as F up to about 70 cents above it.
  • The singer (voice/singer.rs). fit learns a Voice from notes heard against the notes meant. Notes 0.75 semitone or more off were another note, missed, and do not count. Where they sing is a least-squares fit of three values, at the bottom, the middle and the top of the range, interpolated between, each leaning on in-tune singing by a tenth of a note; how widely is the scatter left around that at each place, leaning on anyone’s 30 cents by half a note. The settling is the median, and the vibrato the median of the notes of 400 ms or more whose detrended pitch swings 4 to 8 times a second by 5 cents or more (an autocorrelation peak over 0.3). Voice::hit is the chance of a note within so many cents, from that normal.
  • Learning from the singing alone. voice::assess reads the notes with anyone’s voice, fits the singer to them, and reads them again with that voice, twice. A take is read with the song’s key and the chords under it from where it starts (intent::Scale::song).
  • The grid. Each note’s start and end go to the nearest sixteenth, measured from the middle of the frames’ windows. A note in the song’s key keeps its pitch; one outside it goes to the key’s tone nearest where it was sung (unless chromatic), and its velocity follows its loudness. Two notes on one sixteenth keep the longer, and a note ends where the next begins.

The notes go into the new parts’ notes, by the progression of each section the take covers. Written notes may run over several cycles of their progression, and arrange repeats them only after the last cycle they reach. On the way, take::styled can make them harmony, octaves, chords, a bass line, an arpeggio or a pad. It counts by the key’s scale steps (Key::step), so a third above or a triad under a note stays in the key.

Checking a voice

voice::check::Check is a pitch check: six phrases of four notes in a random major key between two notes, each a random walk on the scale, a step of one or two degrees seven times in ten and a leap of three or four otherwise, at 90 BPM, a beat a note. A phrase takes ten beats: its four notes, a beat’s rest, four beats to answer in, a beat’s rest. Check::hear reads each answer from 200 ms before its first beat to the next phrase, with anyone’s voice in no key (what was sung, not what should have been), and lines the notes up with the phrase’s by the least cost: a note sung for a note played costs how far off it was (a semitone and a half at most), a note not sung 1.2, a note that answers none 0.8. It tries the phrase two octaves down to one up and keeps the octave that costs least, and fits the voice (singer::fit) to the notes as meant in the singer’s octave. A note reached by three semitones or more is a leap.

Tuning a voice

voice::tune::tune moves a voice onto the notes it means, as the tune effect, claudius tune and the tune command do. It reads the notes (intent::decode with the singer given, or voice::learn from the voice itself) and works out a move for every frame, in semitones:

  • Towards the note. A frame’s centre is the mean pitch of the frames around it within 90 ms, inside its note, which takes out a vibrato; frames more than 1.5 semitones from where the note is held (a slide, an octave misheard) count for nothing and move as the frames around them. Of how far the centre is from the note, the singer’s bias goes whole; of the rest, a share humanize² / spread² stays (all of it when the singer scatters less than humanize), so the tuner moves a loose singer in and leaves a precise one.
  • When. The move comes in as 1 - e^(-t / speed_ms) from the note’s start, so a slow tuner leaves the scoop into a note, and strength (a Param, by beat) scales it.
  • The vibrato. vibrato below 1 takes that share of the swing around the centre out as well.
  • Between notes, the move goes in a straight line from one note’s to the next, and a three-frame mean smooths it.

The voiced stretches (voiced frames, with gaps of up to two) are then moved by TD-PSOLA (Moulines and Charpentier 1990, dsp/psola.rs). Marks go a period apart, each where the voice looks most like it did a period before (the best normalised correlation within a sixth of a period), so that every grain is cut at the same point of its period. Each output mark takes the grain at the input mark nearest it, two periods long with Hann halves as long as the periods either side, and the next output mark comes the input period on, over the ratio. Laid back where they were cut, the grains add up to the signal itself; moved, they are divided by how much of them overlaps. The first and the last period of a stretch are crossfaded from and back to the signal, and frames without a pitch pass as they are. The grains keep their spectra, so the voice keeps its formants. A move by the same grains, resampled, would shift the formants instead, which is how a voice can later sound larger or smaller.

The tests sing to it (voice::sing): three harmonics with a 5.5 Hz vibrato, breath noise, a 30 ms glide into each note and breaths where asked. Their melodies come back with every pitch and onset where it was sung, a singer 60 cents flat comes back as the notes meant once the voice is known, and a singer flat at the top only is learnt as flat there.