From 5b84ec90968f3d22353759a3ccde25021e2cead1 Mon Sep 17 00:00:00 2001 From: Carolina <79524656+carochacs@users.noreply.github.com> Date: Tue, 22 Sep 2026 20:10:41 -0600 Subject: [PATCH 1/9] feat: generate keys and guitar arrangements --- CHANGELOG.md | 7 ++ README.md | 31 +++++ chordr/plugin.json | 4 +- chordr/screen.js | 186 +++++++++++++++++++++++++++++ tests/generate_arrangement.test.js | 94 +++++++++++++++ 5 files changed, 320 insertions(+), 2 deletions(-) create mode 100644 tests/generate_arrangement.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index dd1090b..9c0abfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.5.0 + +- Add keys-first chord arrangement generation with two-hand MIDI voicings, + slash-bass support, durations, and voice leading. +- Add guitar arrangement generation with tuning-aware playable fret shapes. +- Accept both audio detector `{t, name}` events and chart chord/template pairs. + All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), diff --git a/README.md b/README.md index dc81c0e..976856f 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,15 @@ window.chordr.identifyChord(chordNotes, { isBass, }); window.chordr.identifyPianoChord(midiNotes); +window.chordr.generateChordArrangement(chords, { + instrument: "keys", // default; or "guitar" + duration: 180, + chordTemplates, +}); +await window.chordr.generateArrangementFromAudio(audioUrl, { + instrument: "keys", + duration: 180, +}); window.chordr.identifyFromHighway(chordNotes, highway); window.chordr.generateChordTemplates(chords, existingTemplates, { tuning, @@ -60,6 +69,27 @@ tolerates `{ string, fret }` objects. It returns `null` when the pitch-class set does not match a supported chord quality. See `CHORD_QUALITIES` in `chordr/screen.js`. +`generateChordArrangement(chords, options)` turns named harmony events such as +`[{t: 0, name: "C"}, {t: 2, name: "G/B"}]` into a playable arrangement. Keys +is the default and primary output: each note is `{t, midi, sus, hand}` with a +compact right-hand voicing, a left-hand root/slash bass, and voice leading +between changes. `{instrument: "guitar"}` instead returns `{t, s, f, sus}` +notes plus the selected fret shapes. Chart chords without an inline `name` can +use `options.chordTemplates` (their `id` indexes that array), so the API works +with authored charts and the audio detector's named events alike. The function +does not mutate its inputs. + +The result is deliberately an arrangement payload rather than an automatic +`chart-transform`: the host transform contract can replace notes but cannot +change instrument type or create a new arrangement. An editor/importer should +materialize this payload as a separate Keys or Guitar arrangement, leaving the +song's original part intact. + +`generateArrangementFromAudio(audioUrl, options)` is the end-to-end fallback +for a song with no authored piano part: it runs Chordr's existing audio chord +detection and feeds those harmony events into the same keys-first generator. +It returns `null` if audio detection fails. + `generateChordTemplates(chords, existingTemplates, ctx)` takes the wire-shape `chords` array (`[{ id, notes: [{s,f}, ...] }, ...]`) and the current `chord_templates` array, and returns a **new** array with any entry that @@ -104,6 +134,7 @@ neighbors) into chord segments. ```bash node tests/chord_analysis.test.js node tests/generate_chord_templates.test.js +node tests/generate_arrangement.test.js node tests/build_lyric_lines.test.js node tests/chord_lyrics_view.test.js python3 -m unittest tests/test_audio_chords.py diff --git a/chordr/plugin.json b/chordr/plugin.json index b9dcb85..323b853 100644 --- a/chordr/plugin.json +++ b/chordr/plugin.json @@ -1,8 +1,8 @@ { "id": "chordr", "name": "Chordr", - "version": "0.4.0", - "description": "Derives chord names and shapes from chart data for guitar and piano arrangements โ€” a shared capability other plugins consume rather than duplicating chord logic themselves.", + "version": "0.5.0", + "description": "Derives chords and generates playable keys-first or guitar arrangements from chart data and audio analysis.", "category": "tools", "type": "utility", "icon": "๐ŸŽผ", diff --git a/chordr/screen.js b/chordr/screen.js index a113f47..0bcc803 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -162,6 +162,178 @@ if (!window[`__${PLUGIN_ID}_installed`]) { return identifyFromMidis(midiNotes, opts); } + // โ”€โ”€ Chord-to-arrangement generation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + // Chord detection tells us the harmony, but a playable keys/guitar part + // still needs concrete pitches, octaves, durations and (for guitar) + // string/fret choices. Keep that policy here as pure functions so an + // editor/importer can materialise a NEW arrangement; chart-transform is + // intentionally not used because it cannot change an arrangement's + // instrument kind. + + const CHORD_INTERVALS_BY_SUFFIX = new Map( + CHORD_QUALITIES.map((q) => [q.suffix.toLowerCase(), q.intervals]) + ); + + function parseChordName(value) { + const text = String(value || "").trim(); + if (!text || /^(n\.?c\.?|no\s*chord)$/i.test(text)) return null; + const match = text.match(/^([A-Ga-g])([#b]?)([^/]*)?(?:\/([A-Ga-g])([#b]?))?$/); + if (!match) return null; + const pitchClass = (letter, accidental) => { + const natural = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }[letter.toUpperCase()]; + return (natural + (accidental === "#" ? 1 : accidental === "b" ? -1 : 0) + 12) % 12; + }; + let suffix = (match[3] || "").trim(); + const aliases = { + min: "m", minor: "m", maj: "", major: "", M: "", + "ฮ”": "maj7", "ฮ”7": "maj7", min7: "m7", "m7โ™ญ5": "m7b5", + "ยฐ": "dim", "ยฐ7": "dim7", "+": "aug", + }; + suffix = Object.prototype.hasOwnProperty.call(aliases, suffix) ? aliases[suffix] : suffix; + const intervals = CHORD_INTERVALS_BY_SUFFIX.get(suffix.toLowerCase()); + if (!intervals) return null; + const root = pitchClass(match[1], match[2]); + return { + name: text, + root, + bass: match[4] ? pitchClass(match[4], match[5]) : root, + quality: suffix, + intervals: intervals.slice(), + pitchClasses: intervals.map((iv) => (root + iv) % 12), + }; + } + + function _normaliseHarmonyEvents(chords, templates) { + const out = []; + for (const event of chords || []) { + if (!event || !Number.isFinite(Number(event.t))) continue; + const id = Number(event.id); + const template = Array.isArray(templates) && Number.isInteger(id) ? templates[id] : null; + const parsed = parseChordName(event.name || (template && template.name)); + if (parsed) out.push({ t: Math.max(0, Number(event.t)), chord: parsed }); + } + out.sort((a, b) => a.t - b.t); + // Multiple analysis frames can land at the same rounded onset. The last + // one is the most recent decision and avoids zero-length generated notes. + return out.filter((event, i) => i === out.length - 1 || event.t !== out[i + 1].t); + } + + function _eventDuration(events, index, options) { + const start = events[index].t; + const next = events[index + 1]; + const requestedEnd = Number(options.duration); + const fallback = Math.max(0.1, Number(options.defaultDuration) || 2); + const end = next ? next.t : (Number.isFinite(requestedEnd) && requestedEnd > start ? requestedEnd : start + fallback); + return Math.max(0.1, end - start); + } + + function _midiCandidates(pc, low, high) { + const result = []; + for (let midi = low; midi <= high; midi++) if (midi % 12 === pc) result.push(midi); + return result; + } + + function _bestRightHandVoicing(chord, previous, low, high) { + const pcs = chord.pitchClasses; + const candidates = pcs.map((pc) => _midiCandidates(pc, low, high)); + let best = null; + const visit = (i, chosen) => { + if (i === candidates.length) { + const sorted = chosen.slice().sort((a, b) => a - b); + if (new Set(sorted).size !== sorted.length || sorted.at(-1) - sorted[0] > 12) return; + let score = sorted.reduce((sum, midi) => sum + Math.abs(midi - 64), 0) * 0.05; + if (previous && previous.length) { + score += sorted.reduce((sum, midi, idx) => sum + Math.abs(midi - previous[Math.min(idx, previous.length - 1)]), 0); + } + if (!best || score < best.score) best = { notes: sorted, score }; + return; + } + for (const midi of candidates[i]) visit(i + 1, [...chosen, midi]); + }; + visit(0, []); + return best ? best.notes : pcs.map((pc) => _midiCandidates(pc, low, high)[0]).filter(Number.isFinite); + } + + function generateKeysArrangement(chords, options) { + const opts = options || {}; + const events = _normaliseHarmonyEvents(chords, opts.chordTemplates); + const low = Math.max(36, Math.min(67, Number(opts.rightHandLow) || 55)); + const high = Math.max(low + 12, Math.min(96, Number(opts.rightHandHigh) || 79)); + const leftLow = Math.max(21, Math.min(low - 1, Number(opts.leftHandLow) || 36)); + const leftHigh = Math.max(leftLow, Math.min(low - 1, Number(opts.leftHandHigh) || 52)); + const notes = []; + let previous = null; + for (let i = 0; i < events.length; i++) { + const event = events[i]; + const sus = _eventDuration(events, i, opts); + const right = _bestRightHandVoicing(event.chord, previous, low, high); + const bassChoices = _midiCandidates(event.chord.bass, leftLow, leftHigh); + const bass = bassChoices.length ? bassChoices.at(-1) : null; + if (bass !== null) notes.push({ t: event.t, midi: bass, sus, hand: "lh" }); + for (const midi of right) notes.push({ t: event.t, midi, sus, hand: "rh" }); + previous = right; + } + return { instrument: "keys", notes, sourceChords: events.map((e) => ({ t: e.t, name: e.chord.name })) }; + } + + function _bestGuitarShape(chord, options) { + const stringCount = Number(options.stringCount) || 6; + const tuning = options.tuning && options.tuning.length ? options.tuning : new Array(stringCount).fill(0); + const base = baseOpenStringMidis(stringCount, false); + const maxFret = Math.max(3, Math.min(15, Number(options.maxFret) || 8)); + const wanted = new Set(chord.pitchClasses); + const choices = []; + for (let s = 0; s < stringCount; s++) { + const open = (base[s] ?? base.at(-1)) + Number(tuning[s] || 0); + const frets = [-1]; + for (let f = 0; f <= maxFret; f++) if (wanted.has((open + f) % 12)) frets.push(f); + choices.push(frets); + } + let best = null; + const visit = (s, frets) => { + if (s === choices.length) { + const sounding = frets.map((f, idx) => f < 0 ? null : (base[idx] ?? base.at(-1)) + Number(tuning[idx] || 0) + f).filter(Number.isFinite); + if (sounding.length < Math.min(3, chord.pitchClasses.length)) return; + const covered = new Set(sounding.map((m) => m % 12)); + if (!chord.pitchClasses.every((pc) => covered.has(pc))) return; + const pressed = frets.filter((f) => f > 0); + const span = pressed.length ? Math.max(...pressed) - Math.min(...pressed) : 0; + if (span > 4) return; + const bassPenalty = sounding[0] % 12 === chord.bass ? 0 : 8; + const score = bassPenalty + span * 3 + frets.filter((f) => f < 0).length * 1.5 + frets.reduce((n, f) => n + Math.max(0, f), 0) * 0.08; + if (!best || score < best.score) best = { frets: frets.slice(), score }; + return; + } + for (const fret of choices[s]) visit(s + 1, [...frets, fret]); + }; + visit(0, []); + return best && best.frets; + } + + function generateGuitarArrangement(chords, options) { + const opts = options || {}; + const events = _normaliseHarmonyEvents(chords, opts.chordTemplates); + const notes = []; + const shapes = []; + for (let i = 0; i < events.length; i++) { + const event = events[i]; + const frets = _bestGuitarShape(event.chord, opts); + if (!frets) continue; + const sus = _eventDuration(events, i, opts); + frets.forEach((f, s) => { if (f >= 0) notes.push({ t: event.t, s, f, sus }); }); + shapes.push({ t: event.t, name: event.chord.name, frets }); + } + return { instrument: "guitar", notes, shapes, sourceChords: events.map((e) => ({ t: e.t, name: e.chord.name })) }; + } + + function generateChordArrangement(chords, options) { + const opts = options || {}; + const instrument = String(opts.instrument || "keys").toLowerCase(); + return /^(guitar|acoustic|electric)$/.test(instrument) + ? generateGuitarArrangement(chords, opts) + : generateKeysArrangement(chords, opts); + } + function identifyFromHighway(chordNotes, highway) { const hw = highway || window.highway; if (!hw || typeof hw.getSongInfo !== "function") { @@ -555,6 +727,15 @@ if (!window[`__${PLUGIN_ID}_installed`]) { } }; + // One-call path for the core use case: a song has audio but no authored + // piano/keys part. Detection failures remain soft (matching + // detectChordsFromAudio); a successful empty detection yields an empty but + // well-formed arrangement. + const generateArrangementFromAudio = async (audioUrl, options) => { + const chords = await detectChordsFromAudio(audioUrl); + return chords ? generateChordArrangement(chords, options) : null; + }; + // Cache keyed by song audio_url (song_info carries no `filename` field โ€” // see the WebSocket protocol reference; audio_url is the identity every // format resolves to): always holds the detection Promise โ€” in flight, @@ -744,6 +925,11 @@ if (!window[`__${PLUGIN_ID}_installed`]) { window.chordr = { identifyChord, identifyPianoChord, + parseChordName, + generateChordArrangement, + generateKeysArrangement, + generateGuitarArrangement, + generateArrangementFromAudio, identifyFromHighway, generateChordTemplates, buildLyricLines, diff --git a/tests/generate_arrangement.test.js b/tests/generate_arrangement.test.js new file mode 100644 index 0000000..8b54326 --- /dev/null +++ b/tests/generate_arrangement.test.js @@ -0,0 +1,94 @@ +'use strict'; +// Chord-symbol to playable keys/guitar arrangement generation. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); + +function freshPlugin() { + global.window = {}; + const file = path.join(__dirname, '..', 'chordr', 'screen.js'); + delete require.cache[require.resolve(file)]; + require(file); + return global.window.chordr; +} + +test('defaults to a two-hand keys arrangement', () => { + const chordr = freshPlugin(); + const result = chordr.generateChordArrangement([ + { t: 0, name: 'C' }, + { t: 2, name: 'G/B' }, + ], { duration: 5 }); + + assert.equal(result.instrument, 'keys'); + assert.deepEqual(result.sourceChords, [{ t: 0, name: 'C' }, { t: 2, name: 'G/B' }]); + assert.equal(result.notes.filter((n) => n.t === 0 && n.hand === 'rh').length, 3); + assert.equal(result.notes.find((n) => n.t === 0 && n.hand === 'lh').midi % 12, 0); + assert.equal(result.notes.find((n) => n.t === 2 && n.hand === 'lh').midi % 12, 11); + assert.ok(result.notes.filter((n) => n.t === 0).every((n) => n.sus === 2)); + assert.ok(result.notes.filter((n) => n.t === 2).every((n) => n.sus === 3)); +}); + +test('keys voicings stay in the configured ranges and use smooth voice leading', () => { + const chordr = freshPlugin(); + const result = chordr.generateKeysArrangement([ + { t: 0, name: 'Cmaj7' }, + { t: 1, name: 'Am7' }, + ], { rightHandLow: 60, rightHandHigh: 76 }); + const right = result.notes.filter((n) => n.hand === 'rh'); + + assert.ok(right.every((n) => n.midi >= 60 && n.midi <= 76)); + assert.deepEqual(new Set(right.filter((n) => n.t === 0).map((n) => n.midi % 12)), new Set([0, 4, 7, 11])); + assert.deepEqual(new Set(right.filter((n) => n.t === 1).map((n) => n.midi % 12)), new Set([9, 0, 4, 7])); +}); + +test('uses template names when chart chords do not carry a name', () => { + const chordr = freshPlugin(); + const result = chordr.generateKeysArrangement( + [{ t: 1, id: 0 }], + { chordTemplates: [{ name: 'Dm7' }] }, + ); + + assert.equal(result.sourceChords[0].name, 'Dm7'); + assert.deepEqual(new Set(result.notes.map((n) => n.midi % 12)), new Set([2, 5, 9, 0])); +}); + +test('guitar generation returns playable string/fret notes covering the chord', () => { + const chordr = freshPlugin(); + const result = chordr.generateChordArrangement( + [{ t: 0, name: 'C' }, { t: 2, name: 'Am' }], + { instrument: 'guitar', duration: 4 }, + ); + + assert.equal(result.instrument, 'guitar'); + assert.equal(result.shapes.length, 2); + for (const shape of result.shapes) { + assert.equal(shape.frets.length, 6); + assert.ok(shape.frets.every((f) => f >= -1 && f <= 8)); + } + const cPitches = result.notes.filter((n) => n.t === 0).map((n) => (40 + [0, 5, 10, 15, 19, 24][n.s] + n.f) % 12); + assert.deepEqual(new Set(cPitches), new Set([0, 4, 7])); +}); + +test('ignores unsupported chord symbols without throwing', () => { + const chordr = freshPlugin(); + const result = chordr.generateChordArrangement([{ t: 0, name: 'C13alt' }]); + assert.deepEqual(result.notes, []); + assert.deepEqual(result.sourceChords, []); +}); + +test('generateArrangementFromAudio connects audio detection to keys generation', async () => { + const originalFetch = global.fetch; + global.fetch = async (url) => { + if (url === '/song.ogg') return { ok: true, blob: async () => ({ type: 'audio/ogg' }) }; + return { ok: true, json: async () => ({ chords: [{ t: 0, name: 'F' }] }) }; + }; + try { + const chordr = freshPlugin(); + const result = await chordr.generateArrangementFromAudio('/song.ogg', { duration: 2 }); + assert.equal(result.instrument, 'keys'); + assert.deepEqual(result.sourceChords, [{ t: 0, name: 'F' }]); + assert.ok(result.notes.length >= 4); + } finally { + global.fetch = originalFetch; + } +}); From b2c0e5388b4d59c4bff489a18bc66dc7d59fbce4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 22:07:38 +0000 Subject: [PATCH 2/9] feat(generate): harmonize sung melody into an accompaniment via lyrics_karaoke MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a third arrangement-generation path alongside chart chords and audio chord detection: generateAccompanimentFromLyrics(filename, options) fetches lyrics_karaoke's canonical /playback payload, takes the primary voice's pitched tokens, and harmonizes the melody into a chord sequence โ€” a Krumhansl-Schmuckler-style key estimate from the melody's pitch-class durations, then a windowed best-fit diatonic triad per chord change โ€” which feeds into the existing generateChordArrangement (keys or guitar). Covers a song whose only harmonic information is its vocal line: no chord chart, no full-mix audio worth running chord detection on. Returns null when there's nothing to harmonize from (route unavailable, lyrics-only track, unrecognized schema_version). Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01XMb6KvcVj8KxYytezviPkJ --- CHANGELOG.md | 8 + README.md | 27 +++ chordr/screen.js | 158 ++++++++++++++++++ ...generate_accompaniment_from_lyrics.test.js | 143 ++++++++++++++++ 4 files changed, 336 insertions(+) create mode 100644 tests/generate_accompaniment_from_lyrics.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c0abfa..f11876b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ slash-bass support, durations, and voice leading. - Add guitar arrangement generation with tuning-aware playable fret shapes. - Accept both audio detector `{t, name}` events and chart chord/template pairs. +- Add `generateAccompanimentFromLyrics(filename, options)`: a third + arrangement-generation path that harmonizes a song's sung melody (read + from lyrics_karaoke's canonical `/playback` payload) into a backing chord + sequence โ€” key estimation via a Krumhansl-Schmuckler-style pitch-class + correlation, then a windowed best-fit diatonic triad per chord change โ€” + and feeds it into the existing keys/guitar generator. Covers a song whose + only harmonic information is its vocal line: no chord chart, no full-mix + audio worth chord-detecting. All notable changes to this project will be documented in this file. diff --git a/README.md b/README.md index 976856f..d4a9a9f 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,11 @@ await window.chordr.generateArrangementFromAudio(audioUrl, { instrument: "keys", duration: 180, }); +await window.chordr.generateAccompanimentFromLyrics(filename, { + instrument: "keys", // default; or "guitar" + arrangementIndex, // optional โ€” forwarded to lyrics_karaoke's /playback + windowSeconds: 2, // chord-change grid; smaller = more frequent changes +}); window.chordr.identifyFromHighway(chordNotes, highway); window.chordr.generateChordTemplates(chords, existingTemplates, { tuning, @@ -90,6 +95,27 @@ for a song with no authored piano part: it runs Chordr's existing audio chord detection and feeds those harmony events into the same keys-first generator. It returns `null` if audio detection fails. +`generateAccompanimentFromLyrics(filename, options)` is a third generation +path for a song whose only harmonic signal is its sung melody โ€” a Vocals +arrangement with synced lyrics and pitch, but no chord chart and no full-mix +audio worth running chord detection on. It fetches +[lyrics_karaoke's canonical `/playback` payload](https://github.com/get-flashbacks/feedback-plugin-lyrics-karaoke/blob/main/docs/architecture/vocals-playback-contract.md) +for `filename` (`options.arrangementIndex` is forwarded as that endpoint's +`arrangement` query param), takes the primary voice's pitched tokens, and +*harmonizes* them: it estimates a key center from the melody's duration-weighted +pitch-class distribution (a Krumhansl-Schmuckler-style correlation against +major/minor key profiles), then buckets the melody into `options.windowSeconds` +windows (default 2) and picks whichever diatonic triad of that key best +covers each window's notes. The resulting chord sequence is fed straight into +`generateChordArrangement`, so the same `instrument`/voicing options apply, +and the returned arrangement carries an extra `key: {root, mode}` field +describing what was detected. This is melody harmonization, not chord +detection โ€” it invents a plausible backing, it does not recover a chord +progression that was actually played. Returns `null` when there is nothing +to harmonize from: the lyrics_karaoke route is unavailable or 404s, the +track is lyrics-only (no `midi` on any token), or the response's +`schema_version` isn't the one this function understands. + `generateChordTemplates(chords, existingTemplates, ctx)` takes the wire-shape `chords` array (`[{ id, notes: [{s,f}, ...] }, ...]`) and the current `chord_templates` array, and returns a **new** array with any entry that @@ -135,6 +161,7 @@ neighbors) into chord segments. node tests/chord_analysis.test.js node tests/generate_chord_templates.test.js node tests/generate_arrangement.test.js +node tests/generate_accompaniment_from_lyrics.test.js node tests/build_lyric_lines.test.js node tests/chord_lyrics_view.test.js python3 -m unittest tests/test_audio_chords.py diff --git a/chordr/screen.js b/chordr/screen.js index 0bcc803..e700427 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -736,6 +736,163 @@ if (!window[`__${PLUGIN_ID}_installed`]) { return chords ? generateChordArrangement(chords, options) : null; }; + // โ”€โ”€ Melody-to-accompaniment (via lyrics_karaoke) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + // A third generation path alongside chart chords and audio chord + // detection: for a song whose only harmonic information is its sung + // melody (a Vocals arrangement with synced lyrics + pitch, no chord + // chart and no full-mix audio worth running chord detection on), derive + // a backing accompaniment straight from the melody notes lyrics_karaoke + // already extracted. This is a monophonic-melody harmonization problem, + // not a chord-detection one: we pick diatonic chords that best support + // the sung notes, not chords already sounding in a recording. + + // Krumhansl-Kessler key profiles (rotated per candidate tonic), used only + // to pick a plausible key center from the melody's own pitch-class + // durations โ€” this is a coarse heuristic, not music-theoretic ground + // truth, and is expected to misfire on melodies that modulate or that + // are modal/pentatonic enough to fit multiple keys equally well. + const KK_MAJOR_PROFILE = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]; + const KK_MINOR_PROFILE = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]; + + // Diatonic triads by scale degree (root offset in semitones from tonic, + // quality suffix matching CHORD_QUALITIES). Degree seven is the + // half-diminished/diminished triad in both modes' natural form. + const MAJOR_DEGREE_TRIADS = [ + { offset: 0, suffix: "" }, { offset: 2, suffix: "m" }, { offset: 4, suffix: "m" }, + { offset: 5, suffix: "" }, { offset: 7, suffix: "" }, { offset: 9, suffix: "m" }, + { offset: 11, suffix: "dim" }, + ]; + const MINOR_DEGREE_TRIADS = [ + { offset: 0, suffix: "m" }, { offset: 2, suffix: "dim" }, { offset: 3, suffix: "" }, + { offset: 5, suffix: "m" }, { offset: 7, suffix: "m" }, { offset: 8, suffix: "" }, + { offset: 10, suffix: "" }, + ]; + + function _pitchClassDurations(tokens) { + const weights = new Array(12).fill(0); + for (const tok of tokens) { + const pc = ((Math.round(tok.midi) % 12) + 12) % 12; + weights[pc] += Math.max(0.05, Number(tok.duration) || 0.05); + } + return weights; + } + + function _correlate(a, b) { + const meanA = a.reduce((s, v) => s + v, 0) / a.length; + const meanB = b.reduce((s, v) => s + v, 0) / b.length; + let num = 0, denomA = 0, denomB = 0; + for (let i = 0; i < a.length; i++) { + const da = a[i] - meanA, db = b[i] - meanB; + num += da * db; denomA += da * da; denomB += db * db; + } + const denom = Math.sqrt(denomA * denomB); + return denom > 0 ? num / denom : 0; + } + + function _estimateKey(tokens) { + const weights = _pitchClassDurations(tokens); + let best = { root: 0, mode: "major", score: -Infinity }; + for (let root = 0; root < 12; root++) { + const rotated = weights.slice(root).concat(weights.slice(0, root)); + const majorScore = _correlate(rotated, KK_MAJOR_PROFILE); + const minorScore = _correlate(rotated, KK_MINOR_PROFILE); + if (majorScore > best.score) best = { root, mode: "major", score: majorScore }; + if (minorScore > best.score) best = { root, mode: "minor", score: minorScore }; + } + return { root: best.root, mode: best.mode }; + } + + function _diatonicChords(key) { + const degrees = key.mode === "minor" ? MINOR_DEGREE_TRIADS : MAJOR_DEGREE_TRIADS; + return degrees.map((d) => { + const root = (key.root + d.offset) % 12; + const intervals = CHORD_INTERVALS_BY_SUFFIX.get(d.suffix.toLowerCase()); + return { + root, suffix: d.suffix, + pitchClasses: intervals.map((iv) => (root + iv) % 12), + }; + }); + } + + // Groups melody tokens into fixed windows and, per window, scores every + // diatonic triad by how much of the window's (duration-weighted) melody + // content it covers โ€” the sung notes are treated as the thing the + // accompaniment must support, not literal chord tones to reproduce. + // Ties favor the tonic triad, giving unclear windows (a single repeated + // note, a rest) a harmonically neutral default instead of an arbitrary one. + function _harmonizeMelody(tokens, windowSeconds, key) { + const triads = _diatonicChords(key); + const tonicIndex = 0; + const lastEnd = tokens.reduce((max, t) => Math.max(max, t.start + t.duration), 0); + const windowCount = Math.max(1, Math.ceil(lastEnd / windowSeconds)); + const chords = []; + let lastChosen = -1; + for (let w = 0; w < windowCount; w++) { + const winStart = w * windowSeconds; + const winEnd = winStart + windowSeconds; + const weights = new Array(12).fill(0); + let any = false; + for (const tok of tokens) { + const overlap = Math.min(tok.start + tok.duration, winEnd) - Math.max(tok.start, winStart); + if (overlap <= 0) continue; + const pc = ((Math.round(tok.midi) % 12) + 12) % 12; + weights[pc] += overlap; + any = true; + } + if (!any) continue; + let bestIdx = tonicIndex, bestScore = -Infinity; + triads.forEach((triad, idx) => { + let score = triad.pitchClasses.reduce((s, pc) => s + weights[pc], 0); + if (idx === lastChosen) score += 0.001; // gentle stickiness, avoids chord-per-window churn on ties + if (score > bestScore) { bestScore = score; bestIdx = idx; } + }); + const chosen = triads[bestIdx]; + const name = (NOTE_NAMES_SHARP[chosen.root] || "C") + chosen.suffix; + chords.push({ t: winStart, name }); + lastChosen = bestIdx; + } + return chords; + } + + // Fetches the canonical vocal playback payload + // (docs/architecture/vocals-playback-contract.md in lyrics_karaoke) for + // `filename`, harmonizes the primary voice's pitched tokens into a + // diatonic chord sequence, and generates a keys/guitar accompaniment from + // it via the same generateChordArrangement path chart chords and audio + // detection already use. Returns null wherever there is nothing to + // harmonize: no lyrics_karaoke route, no prepared song, an unpitched + // (lyrics-only) track, or a track too short to estimate a key from. + async function generateAccompanimentFromLyrics(filename, options) { + const opts = options || {}; + if (!filename) return null; + const params = new URLSearchParams({ filename }); + if (Number.isInteger(opts.arrangementIndex)) { + params.set("arrangement", String(opts.arrangementIndex)); + } + let payload; + try { + const res = await fetch(`/api/plugins/lyrics_karaoke/playback?${params}`); + if (!res.ok) return null; + payload = await res.json(); + } catch (_) { + return null; // network error, decoding failure, host without lyrics_karaoke, etc. + } + if (!payload || payload.schema_version !== 1 || !Array.isArray(payload.voices)) return null; + const voice = payload.voices.find((v) => v && v.primary) || payload.voices[0]; + const tokens = (voice && Array.isArray(voice.tokens) ? voice.tokens : []) + .filter((t) => Number.isFinite(t.midi) && Number.isFinite(t.start) && Number.isFinite(t.duration) && t.duration >= 0) + .sort((a, b) => a.start - b.start); + if (!tokens.length) return null; // lyrics-only track: nothing to harmonize from + + const windowSeconds = Math.max(0.5, Number(opts.windowSeconds) || 2); + const key = _estimateKey(tokens); + const chords = _harmonizeMelody(tokens, windowSeconds, key); + if (!chords.length) return null; + const arrangement = generateChordArrangement(chords, opts); + arrangement.key = { root: NOTE_NAMES_SHARP[key.root], mode: key.mode }; + return arrangement; + } + // Cache keyed by song audio_url (song_info carries no `filename` field โ€” // see the WebSocket protocol reference; audio_url is the identity every // format resolves to): always holds the detection Promise โ€” in flight, @@ -930,6 +1087,7 @@ if (!window[`__${PLUGIN_ID}_installed`]) { generateKeysArrangement, generateGuitarArrangement, generateArrangementFromAudio, + generateAccompanimentFromLyrics, identifyFromHighway, generateChordTemplates, buildLyricLines, diff --git a/tests/generate_accompaniment_from_lyrics.test.js b/tests/generate_accompaniment_from_lyrics.test.js new file mode 100644 index 0000000..be0ad8e --- /dev/null +++ b/tests/generate_accompaniment_from_lyrics.test.js @@ -0,0 +1,143 @@ +'use strict'; +// Melody-to-accompaniment generation, sourced from lyrics_karaoke's +// canonical /playback payload (docs/architecture/vocals-playback-contract.md +// in that plugin). Covers the harmonization path this PR adds on top of the +// existing chart-chord / audio-chord-detection generation paths. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); + +function freshPlugin() { + global.window = {}; + const file = path.join(__dirname, '..', 'chordr', 'screen.js'); + delete require.cache[require.resolve(file)]; + require(file); + return global.window.chordr; +} + +function withFetch(handler, fn) { + const original = global.fetch; + global.fetch = handler; + return Promise.resolve(fn()).finally(() => { global.fetch = original; }); +} + +function tokensFor(pitchClasses, opts) { + const startAt = (opts && opts.startAt) || 0; + const dur = (opts && opts.duration) || 0.5; + return pitchClasses.map((midi, i) => ({ + start: startAt + i * dur, duration: dur, text: 'la', midi, + })); +} + +test('returns null when the lyrics_karaoke route is unavailable', async () => { + const chordr = freshPlugin(); + await withFetch(async () => ({ ok: false }), async () => { + const result = await chordr.generateAccompanimentFromLyrics('song.sloppak'); + assert.equal(result, null); + }); +}); + +test('returns null on a network/decode failure without throwing', async () => { + const chordr = freshPlugin(); + await withFetch(async () => { throw new Error('offline'); }, async () => { + const result = await chordr.generateAccompanimentFromLyrics('song.sloppak'); + assert.equal(result, null); + }); +}); + +test('returns null for a lyrics-only track (no pitched tokens)', async () => { + const chordr = freshPlugin(); + const payload = { + schema_version: 1, + voices: [{ id: 'primary', primary: true, tokens: [ + { start: 0, duration: 0.5, text: 'la' }, + { start: 0.5, duration: 0.5, text: 'la' }, + ] }], + }; + await withFetch(async () => ({ ok: true, json: async () => payload }), async () => { + const result = await chordr.generateAccompanimentFromLyrics('song.sloppak'); + assert.equal(result, null); + }); +}); + +test('returns null for an unrecognized schema_version', async () => { + const chordr = freshPlugin(); + const payload = { schema_version: 2, voices: [] }; + await withFetch(async () => ({ ok: true, json: async () => payload }), async () => { + const result = await chordr.generateAccompanimentFromLyrics('song.sloppak'); + assert.equal(result, null); + }); +}); + +test('requests the primary voice for the given filename and arrangement index', async () => { + const chordr = freshPlugin(); + let requestedUrl = null; + const payload = { schema_version: 1, voices: [{ id: 'primary', primary: true, tokens: [] }] }; + await withFetch(async (url) => { requestedUrl = url; return { ok: true, json: async () => payload }; }, async () => { + await chordr.generateAccompanimentFromLyrics('Song Name.sloppak', { arrangementIndex: 1 }); + }); + assert.ok(requestedUrl.startsWith('/api/plugins/lyrics_karaoke/playback?')); + const params = new URLSearchParams(requestedUrl.split('?')[1]); + assert.equal(params.get('filename'), 'Song Name.sloppak'); + assert.equal(params.get('arrangement'), '1'); +}); + +test('harmonizes a C major melody into a diatonic keys accompaniment', async () => { + const chordr = freshPlugin(); + // Six 1s windows of a C major (I) arpeggio establish an unambiguous + // tonic for the key-estimation step, then one window each of F-A (IV) + // and G-B (V) โ€” those two windows carry too little total duration to + // sway the global key estimate away from C, but should still be enough + // local pitch-class weight to win their own window's chord choice, + // demonstrating the per-window harmonization actually varies with the + // melody instead of only ever reproducing the global key's tonic triad. + const tokens = [ + ...tokensFor([60, 64, 67, 60, 64, 67], { startAt: 0, duration: 0.5 }), // windows 0-2: C E G x2 + ...tokensFor([65, 69, 60], { startAt: 6, duration: 0.333 }), // window 6: F A C + ...tokensFor([67, 71, 62], { startAt: 7, duration: 0.333 }), // window 7: G B D + ]; + const payload = { schema_version: 1, voices: [{ id: 'primary', primary: true, tokens }] }; + + const result = await withFetch( + async () => ({ ok: true, json: async () => payload }), + () => chordr.generateAccompanimentFromLyrics('song.sloppak', { windowSeconds: 1 }), + ); + + assert.ok(result); + assert.equal(result.instrument, 'keys'); + assert.deepEqual(result.key, { root: 'C', mode: 'major' }); + assert.deepEqual( + result.sourceChords.map((c) => c.name), + ['C', 'C', 'C', 'F', 'G'], + ); + assert.ok(result.notes.length > 0); +}); + +test('falls back to the first voice when no voice is marked primary', async () => { + const chordr = freshPlugin(); + const tokens = tokensFor([60, 64, 67], { startAt: 0, duration: 0.5 }); + const payload = { schema_version: 1, voices: [{ id: 'solo', tokens }] }; + + const result = await withFetch( + async () => ({ ok: true, json: async () => payload }), + () => chordr.generateAccompanimentFromLyrics('song.sloppak'), + ); + + assert.ok(result); + assert.equal(result.sourceChords[0].name, 'C'); +}); + +test('instrument option is honored end to end (guitar accompaniment)', async () => { + const chordr = freshPlugin(); + const tokens = tokensFor([60, 64, 67, 60], { startAt: 0, duration: 0.5 }); + const payload = { schema_version: 1, voices: [{ id: 'primary', primary: true, tokens }] }; + + const result = await withFetch( + async () => ({ ok: true, json: async () => payload }), + () => chordr.generateAccompanimentFromLyrics('song.sloppak', { instrument: 'guitar' }), + ); + + assert.ok(result); + assert.equal(result.instrument, 'guitar'); + assert.ok(Array.isArray(result.shapes) && result.shapes.length > 0); +}); From 743ea6319d41304fb938b052516fd05234503314 Mon Sep 17 00:00:00 2001 From: "pullfrog[bot]" <226033991+pullfrog[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:35:01 +0000 Subject: [PATCH 3/9] fix(chordr): address review of the arrangement generators - plugin.json: fold the merge's duplicate version/description keys into one pair, and bump to 0.6.0 (0.5.0 was a downgrade from main's 0.5.4, and the shadowed key meant the host never saw either edit) - _eventDuration: rename the absolute-end `duration` to `lengthSeconds`, the arrangement's total length, floored by `defaultDuration` so a value below the last onset extends nothing instead of vanishing - _bestGuitarShape: search against the base the host decodes with, so isBass shapes read back as the requested chord rather than a transposition of it; memoize shapes per generation call and prune the fret-product search on the partial score (5.2s -> 0.9ms per chord at 8 strings x 15 frets, with the winning shape unchanged) - README: document the keys payload's MIDI-bucket conversion to the wire note format, what becomes of `hand`, and the three new exports - tests: pin right-hand motion, bass shape decoding and the search cost; assert an exact note count --- CHANGELOG.md | 32 ++++++----- CLAUDE.md | 4 +- README.md | 62 ++++++++++++++------ chordr/plugin.json | 6 +- chordr/screen.js | 51 +++++++++++++---- tests/generate_arrangement.test.js | 92 ++++++++++++++++++++++++++++-- 6 files changed, 196 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69090af..c730fc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,24 @@ # Changelog -## 0.5.0 +All notable changes to this project will be documented in this file. -- Add keys-first chord arrangement generation with two-hand MIDI voicings, - slash-bass support, durations, and voice leading. -- Add guitar arrangement generation with tuning-aware playable fret shapes. -- Accept both audio detector `{t, name}` events and chart chord/template pairs. +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Keys-first chord arrangement generation: `window.chordr.generateChordArrangement()` + turns named harmony events into a playable two-hand keys part (`generateKeysArrangement`), + with slash-bass support, note durations (`lengthSeconds` for the arrangement's + total length, `defaultDuration` for the trailing chord), register clamps and + voice leading between changes. `{instrument: "guitar"}` instead generates + tuning-aware guitar shapes (`generateGuitarArrangement`), honouring `tuning`, + `stringCount`, `maxFret` and `isBass`. +- Accept both audio detector `{t, name}` events and chart chord/template pairs + (`chordTemplates`, indexed by the event's `id`), so the generators work with + authored charts and the audio detector's events alike. - Add `generateAccompanimentFromLyrics(filename, options)`: a third arrangement-generation path that harmonizes a song's sung melody (read from lyrics_karaoke's canonical `/playback` payload) into a backing chord @@ -15,15 +28,6 @@ only harmonic information is its vocal line: no chord chart, no full-mix audio worth chord-detecting. -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Added - - `window.chordr.getChartTransformStatus()` reports whether the `chart-transform` provider is registered and currently selected on this host (`"pending"` / `"active"` / `"registered"` / `"unavailable"`). diff --git a/CLAUDE.md b/CLAUDE.md index f058fca..f2235ee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ capability's presence at call time (`getattr(app.state, handle its absence: `difficulty_ladder` returns HTTP 503 (see above), `feedpakr` degrades to a warning and no-ops rather than failing the build. This plugin's `plugin.json` is -currently at `0.5.4`; the chart-transform block has been declared in its +currently at `0.6.0`; the chart-transform block has been declared in its current canonical shape since `0.2.0` (commit `084e1b2`). If you change what `chart-transform`/`analyze_chart_chords_v1` returns or how it's registered, both of those repos' consuming code needs to be checked, not @@ -128,7 +128,7 @@ before assuming a given host can run it. ## Testing ```bash -node --test tests/*.test.js # 81 pass +node --test tests/*.test.js # 99 pass python3 -m pip install -r tests/requirements.txt python3 -m unittest discover -s tests -p 'test_*.py' # 18 pass ``` diff --git a/README.md b/README.md index 7fc0795..c653e5f 100644 --- a/README.md +++ b/README.md @@ -45,14 +45,19 @@ window.chordr.identifyChord(chordNotes, { isBass, }); window.chordr.identifyPianoChord(midiNotes); +window.chordr.parseChordName("Cmin7/E"); // { root, bass, quality, intervals, pitchClasses } | null window.chordr.generateChordArrangement(chords, { - instrument: "keys", // default; or "guitar" - duration: 180, - chordTemplates, + instrument: "keys", // default; or "guitar" / "acoustic" / "electric" + lengthSeconds: 180, // total arrangement length; the trailing chord fills the remainder + defaultDuration: 2, // seconds the trailing chord lasts without a lengthSeconds + chordTemplates, // names for chart events that carry only an id + tuning, capo, stringCount, maxFret, isBass, // guitar shapes }); +window.chordr.generateKeysArrangement(chords, options); // keys-only entry point +window.chordr.generateGuitarArrangement(chords, options); // guitar-only entry point await window.chordr.generateArrangementFromAudio(audioUrl, { instrument: "keys", - duration: 180, + lengthSeconds: 180, }); await window.chordr.generateAccompanimentFromLyrics(filename, { instrument: "keys", // default; or "guitar" @@ -80,16 +85,48 @@ set does not match a supported chord quality. See `CHORD_QUALITIES` in is the default and primary output: each note is `{t, midi, sus, hand}` with a compact right-hand voicing, a left-hand root/slash bass, and voice leading between changes. `{instrument: "guitar"}` instead returns `{t, s, f, sus}` -notes plus the selected fret shapes. Chart chords without an inline `name` can -use `options.chordTemplates` (their `id` indexes that array), so the API works -with authored charts and the audio detector's named events alike. The function -does not mutate its inputs. +notes plus the selected fret shapes in `shapes`, searched against the open +strings that `tuning`/`stringCount`/`isBass` describe โ€” `isBass: true` searches +a 4/5-string bass's fifths rather than the low six guitar strings, so its frets +decode back to the chord that was asked for. Chart chords without an inline +`name` can use `options.chordTemplates` (their `id` indexes that array), so the +API works with authored charts and the audio detector's named events alike. The +function does not mutate its inputs. + +Every note lasts until the next onset, so nothing has to be tuned for the +voicing to be musical; the only length options concern the trailing chord. +`lengthSeconds` is the arrangement's *total* length, so a final chord that +starts early is held until then โ€” that is what fills out a track whose last +detected chord is short. `defaultDuration` (2s by default) is that trailing +chord's own length and its floor, so a `lengthSeconds` below the last onset +extends nothing rather than collapsing the final note. The result is deliberately an arrangement payload rather than an automatic `chart-transform`: the host transform contract can replace notes but cannot change instrument type or create a new arrangement. An editor/importer should materialize this payload as a separate Keys or Guitar arrangement, leaving the -song's original part intact. +song's original part intact โ€” and note that the two payloads are not the same +thing on the wire. The guitar notes are *already* wire notes (`{t, s, f, sus}`, +feedpak-spec ยง6.2); the keys notes are not. `{t, midi, sus, hand}` has to be +converted first, because a keys/keys arrangement reuses `s`/`f` for a 24-semitone +MIDI bucket (`midi = s * 24 + f`) rather than a string index and fret: + +```js +const wireNotes = notes.map((n) => ({ + t: n.t, + s: Math.floor(n.midi / 24), + f: n.midi % 24, + sus: n.sus, +})); +``` + +Write the payload verbatim and every note decodes as `null`, leaving a +silently unidentifiable part โ€” the chordr#19 failure mode, in reverse. +`hand` has no wire field at all: it is a rendering hint (which hand plays the +note), so keep it in your own copy or drop it. The generator's register clamps +keep `f` under 24. Chordr reads that encoded form back through +`identifyChord(notes, { isPiano: true })` and `identifyPianoChord`, and +feedBack-plugin-piano claims keys arrangements by the same pattern. `generateArrangementFromAudio(audioUrl, options)` is the end-to-end fallback for a song with no authored piano part: it runs Chordr's existing audio chord @@ -221,13 +258,6 @@ neighbors) into chord segments. ## Tests ```bash -node tests/chord_analysis.test.js -node tests/generate_chord_templates.test.js -node tests/generate_arrangement.test.js -node tests/generate_accompaniment_from_lyrics.test.js -node tests/build_lyric_lines.test.js -node tests/chord_lyrics_view.test.js -python3 -m unittest tests/test_audio_chords.py node --test tests/*.test.js python3 -m pip install -r tests/requirements.txt python3 -m unittest discover -s tests -p 'test_*.py' diff --git a/chordr/plugin.json b/chordr/plugin.json index cf12b96..69c378f 100644 --- a/chordr/plugin.json +++ b/chordr/plugin.json @@ -1,10 +1,8 @@ { "id": "chordr", "name": "Chordr", - "version": "0.5.0", - "description": "Derives chords and generates playable keys-first or guitar arrangements from chart data and audio analysis.", - "version": "0.5.4", - "description": "Derives chord names and shapes from chart data for guitar and piano arrangements โ€” a shared capability other plugins consume rather than duplicating chord logic themselves.", + "version": "0.6.0", + "description": "Derives chords and generates playable keys/guitar arrangements from chart data, audio analysis, or a sung melody โ€” a shared capability other plugins consume rather than duplicating chord logic themselves.", "category": "tools", "type": "utility", "icon": "๐ŸŽผ", diff --git a/chordr/screen.js b/chordr/screen.js index cd6a48f..b4125c6 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -286,12 +286,18 @@ if (!window[`__${PLUGIN_ID}_installed`]) { return out.filter((event, i) => i === out.length - 1 || event.t !== out[i + 1].t); } + // Every chord lasts until the next onset; the trailing one lasts until + // `lengthSeconds` (the arrangement's total length, so an audio path whose + // last detected chord is short still fills its track). `defaultDuration` is + // that trailing chord's own length, and is also the floor for it: a + // `lengthSeconds` below the last onset extends nothing rather than + // collapsing the final note to a sliver. function _eventDuration(events, index, options) { const start = events[index].t; const next = events[index + 1]; - const requestedEnd = Number(options.duration); const fallback = Math.max(0.1, Number(options.defaultDuration) || 2); - const end = next ? next.t : (Number.isFinite(requestedEnd) && requestedEnd > start ? requestedEnd : start + fallback); + const length = Number(options.lengthSeconds); + const end = next ? next.t : Math.max(start + fallback, Number.isFinite(length) ? length : 0); return Math.max(0.1, end - start); } @@ -344,12 +350,25 @@ if (!window[`__${PLUGIN_ID}_installed`]) { return { instrument: "keys", notes, sourceChords: events.map((e) => ({ t: e.t, name: e.chord.name })) }; } - function _bestGuitarShape(chord, options) { + // Brute-forces the per-string fret combinations that sound the chord, scored + // on bass note, span, muted strings and fret distance. `shapeCache` (a Map, + // owned by the caller so it lives exactly as long as one generation call) + // memoizes the winner per chord + instrument setup: this search dominates + // the guitar path's cost, and a song repeats each chord symbol many times. + function _bestGuitarShape(chord, options, shapeCache) { const stringCount = Number(options.stringCount) || 6; const tuning = options.tuning && options.tuning.length ? options.tuning : new Array(stringCount).fill(0); - const base = baseOpenStringMidis(stringCount, false); + const isBass = !!options.isBass; + // Search against the base the HOST decodes with (see + // baseOpenStringMidis): a 4/5-string bass reads fifths, not the low six + // guitar strings, so frets chosen against the guitar base sound a + // different chord for a bass part. `capo` is added by the host on top of + // base+tuning+fret, so the search stays capo-relative. + const base = baseOpenStringMidis(stringCount, isBass); const maxFret = Math.max(3, Math.min(15, Number(options.maxFret) || 8)); const wanted = new Set(chord.pitchClasses); + const cacheKey = `${chord.pitchClasses.join(",")}/${chord.bass}/${stringCount}/${isBass}/${maxFret}/${tuning.join(",")}`; + if (shapeCache && shapeCache.has(cacheKey)) return shapeCache.get(cacheKey); const choices = []; for (let s = 0; s < stringCount; s++) { const open = (base[s] ?? base.at(-1)) + Number(tuning[s] || 0); @@ -359,23 +378,34 @@ if (!window[`__${PLUGIN_ID}_installed`]) { } let best = null; const visit = (s, frets) => { + const pressed = frets.filter((f) => f > 0); + const span = pressed.length ? Math.max(...pressed) - Math.min(...pressed) : 0; + if (span > 4) return; + // Span, muted strings and fret distance never shrink as strings are + // added, so their total is a lower bound on any shape reachable from + // here (the leaf's bass penalty is >= 0). A prefix already scoring at or + // above the incumbent best cannot beat it, so pruning it leaves the + // winning shape unchanged while cutting the search from seconds to + // milliseconds on wide tunings. + const floor = span * 3 + frets.filter((f) => f < 0).length * 1.5 + + frets.reduce((n, f) => n + Math.max(0, f), 0) * 0.08; + if (best && floor >= best.score) return; if (s === choices.length) { const sounding = frets.map((f, idx) => f < 0 ? null : (base[idx] ?? base.at(-1)) + Number(tuning[idx] || 0) + f).filter(Number.isFinite); if (sounding.length < Math.min(3, chord.pitchClasses.length)) return; const covered = new Set(sounding.map((m) => m % 12)); if (!chord.pitchClasses.every((pc) => covered.has(pc))) return; - const pressed = frets.filter((f) => f > 0); - const span = pressed.length ? Math.max(...pressed) - Math.min(...pressed) : 0; - if (span > 4) return; const bassPenalty = sounding[0] % 12 === chord.bass ? 0 : 8; - const score = bassPenalty + span * 3 + frets.filter((f) => f < 0).length * 1.5 + frets.reduce((n, f) => n + Math.max(0, f), 0) * 0.08; + const score = bassPenalty + floor; if (!best || score < best.score) best = { frets: frets.slice(), score }; return; } for (const fret of choices[s]) visit(s + 1, [...frets, fret]); }; visit(0, []); - return best && best.frets; + const frets = best && best.frets; + if (shapeCache) shapeCache.set(cacheKey, frets); + return frets; } function generateGuitarArrangement(chords, options) { @@ -383,9 +413,10 @@ if (!window[`__${PLUGIN_ID}_installed`]) { const events = _normaliseHarmonyEvents(chords, opts.chordTemplates); const notes = []; const shapes = []; + const shapeCache = new Map(); for (let i = 0; i < events.length; i++) { const event = events[i]; - const frets = _bestGuitarShape(event.chord, opts); + const frets = _bestGuitarShape(event.chord, opts, shapeCache); if (!frets) continue; const sus = _eventDuration(events, i, opts); frets.forEach((f, s) => { if (f >= 0) notes.push({ t: event.t, s, f, sus }); }); diff --git a/tests/generate_arrangement.test.js b/tests/generate_arrangement.test.js index 8b54326..817db14 100644 --- a/tests/generate_arrangement.test.js +++ b/tests/generate_arrangement.test.js @@ -17,7 +17,7 @@ test('defaults to a two-hand keys arrangement', () => { const result = chordr.generateChordArrangement([ { t: 0, name: 'C' }, { t: 2, name: 'G/B' }, - ], { duration: 5 }); + ], { lengthSeconds: 5 }); assert.equal(result.instrument, 'keys'); assert.deepEqual(result.sourceChords, [{ t: 0, name: 'C' }, { t: 2, name: 'G/B' }]); @@ -28,7 +28,7 @@ test('defaults to a two-hand keys arrangement', () => { assert.ok(result.notes.filter((n) => n.t === 2).every((n) => n.sus === 3)); }); -test('keys voicings stay in the configured ranges and use smooth voice leading', () => { +test('keys voicings stay in the configured ranges and cover the chord', () => { const chordr = freshPlugin(); const result = chordr.generateKeysArrangement([ { t: 0, name: 'Cmaj7' }, @@ -41,6 +41,27 @@ test('keys voicings stay in the configured ranges and use smooth voice leading', assert.deepEqual(new Set(right.filter((n) => n.t === 1).map((n) => n.midi % 12)), new Set([9, 0, 4, 7])); }); +test('the right hand moves minimally into the next chord', () => { + const chordr = freshPlugin(); + const result = chordr.generateKeysArrangement([ + { t: 0, name: 'Em' }, + { t: 1, name: 'C' }, + ], { rightHandLow: 60, rightHandHigh: 76 }); + const right = result.notes.filter((n) => n.hand === 'rh'); + const first = right.filter((n) => n.t === 0).map((n) => n.midi).sort((a, b) => a - b); + const second = right.filter((n) => n.t === 1).map((n) => n.midi).sort((a, b) => a - b); + + // Both metrics are the ones _bestRightHandVoicing scores a voicing by: + // nearest-by-index semitone movement from the previous chord, and the tones + // carried over. Without the movement term the C drops an octave to + // [60, 64, 67] โ€” 11 semitones of movement โ€” while still satisfying every + // range and pitch-class assertion, so pin the motion itself. + const movement = second.reduce((sum, midi, i) => sum + Math.abs(midi - first[Math.min(i, first.length - 1)]), 0); + const held = first.filter((midi) => second.includes(midi)).length; + assert.ok(movement <= 3, `right hand moved ${movement} semitones into the C`); + assert.ok(held >= 2, `only ${held} tones held over into the C`); +}); + test('uses template names when chart chords do not carry a name', () => { const chordr = freshPlugin(); const result = chordr.generateKeysArrangement( @@ -56,7 +77,7 @@ test('guitar generation returns playable string/fret notes covering the chord', const chordr = freshPlugin(); const result = chordr.generateChordArrangement( [{ t: 0, name: 'C' }, { t: 2, name: 'Am' }], - { instrument: 'guitar', duration: 4 }, + { instrument: 'guitar', lengthSeconds: 4 }, ); assert.equal(result.instrument, 'guitar'); @@ -69,6 +90,47 @@ test('guitar generation returns playable string/fret notes covering the chord', assert.deepEqual(new Set(cPitches), new Set([0, 4, 7])); }); +test('guitar shapes decode back to the requested chord for a bass part', () => { + const chordr = freshPlugin(); + // A 4/5-string bass reads fifths (B-E-A-D-G), not the low six guitar + // strings, so frets chosen against the guitar base decode to a different + // chord once the host reads them back with `isBass` โ€” C came back as + // unidentifiable, A as Esus4, G as Dsus4. + for (const stringCount of [4, 5]) { + for (const name of ['C', 'Am', 'Dm7', 'G']) { + const label = `${name} on ${stringCount} strings`; + const result = chordr.generateGuitarArrangement( + [{ t: 0, name }], + { instrument: 'guitar', stringCount, isBass: true }, + ); + assert.equal(result.shapes.length, 1, `${label} produced a shape`); + + const identified = chordr.identifyChord(result.notes, { + stringCount, isBass: true, tuning: new Array(stringCount).fill(0), + }); + const wanted = chordr.parseChordName(name); + assert.ok(identified, `${label} decoded`); + assert.deepEqual(new Set(identified.pitchClasses), new Set(wanted.pitchClasses), `${label} pitch classes`); + assert.ok(identified.pitchClasses.includes(wanted.bass), `${label} kept its bass note`); + } + } +}); + +test('a song of wide-tuning guitar chords does not block on the shape search', () => { + const chordr = freshPlugin(); + const progression = ['C', 'Am', 'F', 'G', 'Cmaj9', 'Dm7']; + const chords = Array.from({ length: 24 }, (_, i) => ({ t: i * 2, name: progression[i % progression.length] })); + const started = process.hrtime.bigint(); + const result = chordr.generateGuitarArrangement(chords, { instrument: 'guitar', stringCount: 8, maxFret: 15 }); + const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6; + + assert.equal(result.shapes.length, 24); + // The unpruned, uncached search cost seconds per chord at this size (~two + // minutes for this song). The pruned search plus the per-call shape cache + // finishes in single-digit milliseconds, so the bound is loose on purpose. + assert.ok(elapsedMs < 2000, `24 chords at 8 strings x 15 frets took ${elapsedMs}ms`); +}); + test('ignores unsupported chord symbols without throwing', () => { const chordr = freshPlugin(); const result = chordr.generateChordArrangement([{ t: 0, name: 'C13alt' }]); @@ -84,11 +146,31 @@ test('generateArrangementFromAudio connects audio detection to keys generation', }; try { const chordr = freshPlugin(); - const result = await chordr.generateArrangementFromAudio('/song.ogg', { duration: 2 }); + const result = await chordr.generateArrangementFromAudio('/song.ogg', { lengthSeconds: 2 }); assert.equal(result.instrument, 'keys'); assert.deepEqual(result.sourceChords, [{ t: 0, name: 'F' }]); - assert.ok(result.notes.length >= 4); + // A keys triad is exactly one left-hand bass note plus three right-hand + // chord tones โ€” an exact count, so a stray extra note fails here. + assert.equal(result.notes.length, 4); } finally { global.fetch = originalFetch; } }); + +test('lengthSeconds holds the trailing chord out to the arrangement length', () => { + const chordr = freshPlugin(); + const chords = [{ t: 0, name: 'C' }, { t: 10, name: 'F' }, { t: 100, name: 'G' }]; + const trailing = (options) => chordr.generateKeysArrangement(chords, options) + .notes.filter((n) => n.hand === 'rh' && n.t === 100) + .map((n) => n.sus)[0]; + + // The last chord is held until lengthSeconds โ€” that is how an audio path + // whose final detected chord is short still fills its track. + assert.equal(trailing({ lengthSeconds: 180 }), 80); + assert.equal(trailing({ lengthSeconds: 120 }), 20); + // A length below the last onset can't shorten the final note below + // defaultDuration, so it extends nothing rather than vanishing. + assert.equal(trailing({ lengthSeconds: 4 }), 2); + assert.equal(trailing({}), 2); + assert.equal(trailing({ defaultDuration: 6 }), 6); +}); From a3764f8732aea0b19e63f06d14869c94b2a3549f Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:15:44 +0000 Subject: [PATCH 4/9] fix(review): add M7/M9/M6 aliases to parseChordName --- chordr/screen.js | 1 + 1 file changed, 1 insertion(+) diff --git a/chordr/screen.js b/chordr/screen.js index b4125c6..e81db08 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -254,6 +254,7 @@ if (!window[`__${PLUGIN_ID}_installed`]) { let suffix = (match[3] || "").trim(); const aliases = { min: "m", minor: "m", maj: "", major: "", M: "", + M7: "maj7", M9: "maj9", M6: "6", "ฮ”": "maj7", "ฮ”7": "maj7", min7: "m7", "m7โ™ญ5": "m7b5", "ยฐ": "dim", "ยฐ7": "dim7", "+": "aug", }; From 22c7de50ee36388a69258c966bea42b486ee4ff5 Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:17:20 +0000 Subject: [PATCH 5/9] fix(review): add capo support to _bestGuitarShape search and cache --- chordr/screen.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/chordr/screen.js b/chordr/screen.js index e81db08..4d29a33 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -357,22 +357,24 @@ if (!window[`__${PLUGIN_ID}_installed`]) { // memoizes the winner per chord + instrument setup: this search dominates // the guitar path's cost, and a song repeats each chord symbol many times. function _bestGuitarShape(chord, options, shapeCache) { - const stringCount = Number(options.stringCount) || 6; + const stringCount = Number(options.stringCount) || (options.tuning && options.tuning.length) || 6; const tuning = options.tuning && options.tuning.length ? options.tuning : new Array(stringCount).fill(0); const isBass = !!options.isBass; + const capo = Number(options.capo) || 0; // Search against the base the HOST decodes with (see // baseOpenStringMidis): a 4/5-string bass reads fifths, not the low six // guitar strings, so frets chosen against the guitar base sound a - // different chord for a bass part. `capo` is added by the host on top of - // base+tuning+fret, so the search stays capo-relative. + // different chord for a bass part. `capo` shifts all strings uniformly + // (base + tuning + capo + fret), so fold it into the search to match + // the decode path exactly. const base = baseOpenStringMidis(stringCount, isBass); const maxFret = Math.max(3, Math.min(15, Number(options.maxFret) || 8)); const wanted = new Set(chord.pitchClasses); - const cacheKey = `${chord.pitchClasses.join(",")}/${chord.bass}/${stringCount}/${isBass}/${maxFret}/${tuning.join(",")}`; + const cacheKey = `${chord.pitchClasses.join(",")}/${chord.bass}/${stringCount}/${isBass}/${maxFret}/${capo}/${tuning.join(",")}`; if (shapeCache && shapeCache.has(cacheKey)) return shapeCache.get(cacheKey); const choices = []; for (let s = 0; s < stringCount; s++) { - const open = (base[s] ?? base.at(-1)) + Number(tuning[s] || 0); + const open = (base[s] ?? base.at(-1)) + Number(tuning[s] || 0) + capo; const frets = [-1]; for (let f = 0; f <= maxFret; f++) if (wanted.has((open + f) % 12)) frets.push(f); choices.push(frets); From eba53cdfca704c438e7a5a88526d113cd8c6dcf5 Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:18:28 +0000 Subject: [PATCH 6/9] fix(review): correct minor mode degree 7 comment --- chordr/screen.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/chordr/screen.js b/chordr/screen.js index 4d29a33..81c0a73 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -995,8 +995,9 @@ if (!window[`__${PLUGIN_ID}_installed`]) { const KK_MINOR_PROFILE = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]; // Diatonic triads by scale degree (root offset in semitones from tonic, - // quality suffix matching CHORD_QUALITIES). Degree seven is the - // half-diminished/diminished triad in both modes' natural form. + // quality suffix matching CHORD_QUALITIES). Major degree 7 is the + // diminished triad; minor degree 7 is the major triad on the flattened + // seventh (VII), and the natural-minor diminished triad is on degree 2. const MAJOR_DEGREE_TRIADS = [ { offset: 0, suffix: "" }, { offset: 2, suffix: "m" }, { offset: 4, suffix: "m" }, { offset: 5, suffix: "" }, { offset: 7, suffix: "" }, { offset: 9, suffix: "m" }, From 3ae2101668b3c34af1e8efa75f5abcb4e8627615 Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:19:09 +0000 Subject: [PATCH 7/9] fix(review): add truthy guard to token filter in generateAccompanimentFromLyrics --- chordr/screen.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chordr/screen.js b/chordr/screen.js index 81c0a73..8b79d53 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -1121,7 +1121,7 @@ if (!window[`__${PLUGIN_ID}_installed`]) { if (!payload || payload.schema_version !== 1 || !Array.isArray(payload.voices)) return null; const voice = payload.voices.find((v) => v && v.primary) || payload.voices[0]; const tokens = (voice && Array.isArray(voice.tokens) ? voice.tokens : []) - .filter((t) => Number.isFinite(t.midi) && Number.isFinite(t.start) && Number.isFinite(t.duration) && t.duration >= 0) + .filter((t) => t && Number.isFinite(t.midi) && Number.isFinite(t.start) && Number.isFinite(t.duration) && t.duration >= 0) .sort((a, b) => a.start - b.start); if (!tokens.length) return null; // lyrics-only track: nothing to harmonize from From e82a3319878e82045bb4a54b7f57e60b2bee1f23 Mon Sep 17 00:00:00 2001 From: carochacs <79524656+carochacs@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:19:33 +0000 Subject: [PATCH 8/9] fix(review): add blank line between paragraphs in README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c653e5f..b0a85a1 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ progression that was actually played. Returns `null` when there is nothing to harmonize from: the lyrics_karaoke route is unavailable or 404s, the track is lyrics-only (no `midi` on any token), or the response's `schema_version` isn't the one this function understands. + `groupChordEvents` returns a `{ parentIndex, continuation }` entry for every chord event. A nonempty event whose played `{s,f}` notes are a subset of the active preceding full chord retains that full chord's parent index, including From 9d032a0d69dd458046858970cbfce17f3bf30171 Mon Sep 17 00:00:00 2001 From: "pullfrog[bot]" <226033991+pullfrog[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:30:10 +0000 Subject: [PATCH 9/9] fix(review): validate guitar shapes against the capo-shifted pitch The shape search folded `capo` into each string's open pitch but the leaf that validates a candidate recomputed `base + tuning + f` without it, so every non-multiple-of-12 capo made the coverage check reject the shapes the candidate list had just built and `generateGuitarArrangement` returned `{notes: [], shapes: []}` silently. Both sites now read one `opens` array, so the shift cannot be applied in one and forgotten in the other. --- chordr/screen.js | 8 +++++++- tests/generate_arrangement.test.js | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/chordr/screen.js b/chordr/screen.js index 8b79d53..61b9f8c 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -372,9 +372,15 @@ if (!window[`__${PLUGIN_ID}_installed`]) { const wanted = new Set(chord.pitchClasses); const cacheKey = `${chord.pitchClasses.join(",")}/${chord.bass}/${stringCount}/${isBass}/${maxFret}/${capo}/${tuning.join(",")}`; if (shapeCache && shapeCache.has(cacheKey)) return shapeCache.get(cacheKey); + // Open-string sounding pitch per string (base + tuning + capo) โ€” the same + // expression `pitchFromBase` decodes with. The candidate list and the + // leaf's `sounding` below both read it from here, so a shift the search + // applies can't be left out of the coverage check that validates it. + const opens = []; const choices = []; for (let s = 0; s < stringCount; s++) { const open = (base[s] ?? base.at(-1)) + Number(tuning[s] || 0) + capo; + opens.push(open); const frets = [-1]; for (let f = 0; f <= maxFret; f++) if (wanted.has((open + f) % 12)) frets.push(f); choices.push(frets); @@ -394,7 +400,7 @@ if (!window[`__${PLUGIN_ID}_installed`]) { frets.reduce((n, f) => n + Math.max(0, f), 0) * 0.08; if (best && floor >= best.score) return; if (s === choices.length) { - const sounding = frets.map((f, idx) => f < 0 ? null : (base[idx] ?? base.at(-1)) + Number(tuning[idx] || 0) + f).filter(Number.isFinite); + const sounding = frets.map((f, idx) => f < 0 ? null : opens[idx] + f).filter(Number.isFinite); if (sounding.length < Math.min(3, chord.pitchClasses.length)) return; const covered = new Set(sounding.map((m) => m % 12)); if (!chord.pitchClasses.every((pc) => covered.has(pc))) return; diff --git a/tests/generate_arrangement.test.js b/tests/generate_arrangement.test.js index 817db14..944adaa 100644 --- a/tests/generate_arrangement.test.js +++ b/tests/generate_arrangement.test.js @@ -116,6 +116,29 @@ test('guitar shapes decode back to the requested chord for a bass part', () => { } }); +test('guitar shapes decode back to the requested chord under a capo', () => { + const chordr = freshPlugin(); + // `capo` shifts every string's sounding pitch, so the shape search has to + // search and validate against the same shifted pitch. Validating against the + // unshifted one left every non-multiple-of-12 capo producing no shape at all: + // the candidate list built frets the coverage check then rejected, and the + // empty result was silent because `sourceChords` stayed populated. + for (const capo of [0, 1, 2, 3, 5, 7, 12]) { + for (const name of ['C', 'Am', 'G', 'Dm7']) { + const label = `${name} at capo ${capo}`; + const result = chordr.generateGuitarArrangement([{ t: 0, name }], { instrument: 'guitar', capo }); + assert.equal(result.shapes.length, 1, `${label} produced a shape`); + + const identified = chordr.identifyChord(result.notes, { + capo, stringCount: 6, isBass: false, tuning: new Array(6).fill(0), + }); + const wanted = chordr.parseChordName(name); + assert.ok(identified, `${label} decoded`); + assert.deepEqual(new Set(identified.pitchClasses), new Set(wanted.pitchClasses), `${label} pitch classes`); + } + } +}); + test('a song of wide-tuning guitar chords does not block on the shape search', () => { const chordr = freshPlugin(); const progression = ['C', 'Am', 'F', 'G', 'Cmaj9', 'Dm7'];