Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
does) now decode `midi = s*24 + f` directly, and auto-generated chord
templates for them no longer write a nonsense guitar fret diagram. Fixes
a bug where an unnamed C major piano voicing was auto-named "D". (#19)
- Generated accompaniments no longer sustain a chord across a detected
rest. Audio chord detection now carries each segment's own end
(`{"t", "name", "end"}`) and lyric harmonization carries each window's
end, and `generateChordArrangement` honors an event's explicit `end`
instead of always holding the chord until the next onset. Internal and
trailing silence in a detected run or a silent harmonization window
therefore stays a rest rather than being filled; authored chart chords
without an `end` keep the next-onset behavior. (#29)

<!-- Add entries under Added, Changed, Deprecated, Removed, Fixed, or Security as changes land. -->
6 changes: 3 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.6.0`; the chart-transform block has been declared in its
currently at `0.6.1`; 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
Expand Down Expand Up @@ -128,9 +128,9 @@ before assuming a given host can run it.
## Testing

```bash
node --test tests/*.test.js # 99 pass
node --test tests/*.test.js # 107 pass
python3 -m pip install -r tests/requirements.txt
python3 -m unittest discover -s tests -p 'test_*.py' # 18 pass
python3 -m unittest discover -s tests -p 'test_*.py' # 20 pass
```

The JS suite has no third-party dependencies. `test_chart_bridge.py`
Expand Down
32 changes: 24 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,23 @@ decode back to the chord that was asked for. Chart chords without an inline
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.
Every note lasts until the next onset (or its own explicit `end`), 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.

An event may carry its own `end` (seconds), as the detection paths below
emit for every segment they produce. When present it wins over the
next-onset rule — the chord stops there, so a silent stretch before the next
chord (or after the last one) survives as a rest instead of being sustained
over. It is still capped at the next onset and at `lengthSeconds`, so a
detected end can't overlap the next chord or outlive the arrangement.
Authored chart chords without an `end` keep the next-onset behavior.

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
Expand Down Expand Up @@ -131,7 +140,10 @@ 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
detection and feeds those harmony events into the same keys-first generator.
It returns `null` if audio detection fails.
Each detected segment carries its own `end`, so internal and trailing
silence become rests rather than being filled by sustained chords; a
`lengthSeconds` no longer stretches the last detection to the end of the
track. 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
Expand All @@ -147,7 +159,9 @@ 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
describing what was detected. Each harmonized window carries its own `end`,
so a window with no sung note is a rest rather than being filled, and the
final window stops where the melody ends. 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
Expand Down Expand Up @@ -189,9 +203,11 @@ the same parsing.

`detectChordsFromAudio(audioUrl)` fetches the audio at `audioUrl` and
POSTs it to this plugin's own `/api/plugins/chordr/detect_chords` route
for chroma-based detection, returning `[{ t, name }, ...]` or `null` on
for chroma-based detection, returning `[{ t, name, end }, ...]` or `null` on
any failure (network error, no audio, detection failed — the caller just
has no chords for that song, same as a chart with none). The chord/lyrics
has no chords for that song, same as a chart with none). `end` is the
detected segment's own end time, so a caller can preserve the rest before
the next chord rather than sustaining over it. The chord/lyrics
view calls it automatically as a fallback; exposed for any other
lyrics/chord-consuming plugin that wants the same source.

Expand Down Expand Up @@ -244,8 +260,8 @@ guarding on the nonexistent `songInfo.filename`) is fixed — see CHANGELOG's

`POST /api/plugins/chordr/detect_chords` — body is the raw audio bytes
(any format `librosa`/`soundfile` can decode: mp3, ogg, wav, flac).
Returns `{"chords": [{"t": <seconds>, "name": <chord name>}, ...]}`, or
a 4xx/5xx with `{"error": "..."}` on a bad/oversized body, missing
Returns `{"chords": [{"t": <seconds>, "name": <chord name>, "end": <seconds>}, ...]}`,
or a 4xx/5xx with `{"error": "..."}` on a bad/oversized body, missing
`librosa`, or a decode/analysis failure. Detection
(`chordr/audio_chords.py`): `librosa.feature.chroma_cqt` per ~0.2s
analysis frame, each frame matched against a binary chord-quality
Expand Down
21 changes: 15 additions & 6 deletions chordr/audio_chords.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,14 @@ def detect_chords_from_chroma(chroma, times, min_run_seconds=0.5):
frame, time-ordered. times: parallel list of frame onset times in
seconds (same length as chroma).

Returns [{"t": float, "name": str}, ...] — one entry per detected
chord segment. Silence/unidentified stretches are omitted entirely,
the same convention the chart's own `chords` array uses (it only
lists actual chord events).
Returns [{"t": float, "name": str, "end": float}, ...] — one entry per
detected chord segment. `end` is the run's own end time (the next
frame's onset, so the last frame of the run is still covered, or one
frame past the last onset for a run that reaches the end of the
analysis), so a silent stretch before the next chord survives as a
rest instead of being sustained over. Silence/unidentified stretches
are still omitted entirely, the same convention the chart's own
`chords` array uses (it only lists actual chord events).
"""
if not chroma or len(chroma) != len(times):
return []
Expand All @@ -177,10 +181,15 @@ def detect_chords_from_chroma(chroma, times, min_run_seconds=0.5):
runs = _smooth_labels(labels, min_run_frames)

events = []
for label, start_idx, _end_idx in runs:
for label, start_idx, end_idx in runs:
if label is None:
continue
events.append({"t": times[start_idx], "name": label})
# end_idx is exclusive: the first frame of the next run (i.e. where
# this one stopped sounding). At the very end of the analysis there
# is no such frame, so extend one average frame past the last onset
# rather than dropping the final frame's worth of duration.
run_end = times[end_idx] if end_idx < len(times) else times[-1] + avg_frame_dur
events.append({"t": times[start_idx], "name": label, "end": run_end})
return events


Expand Down
2 changes: 1 addition & 1 deletion chordr/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "chordr",
"name": "Chordr",
"version": "0.6.0",
"version": "0.6.1",
"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",
Expand Down
45 changes: 40 additions & 5 deletions chordr/screen.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,15 @@ if (!window[`__${PLUGIN_ID}_installed`]) {
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 });
if (parsed) {
const norm = { t: Math.max(0, Number(event.t)), chord: parsed };
// Detection paths (audio runs, harmonized windows) carry the segment's
// own end so a rest before the next onset survives generation; authored
// chart chords have no `end` and keep the next-onset behavior.
const end = Number(event.end);
if (Number.isFinite(end)) norm.end = Math.max(norm.t, end);
out.push(norm);
}
}
out.sort((a, b) => a.t - b.t);
// Multiple analysis frames can land at the same rounded onset. The last
Expand All @@ -293,11 +301,31 @@ if (!window[`__${PLUGIN_ID}_installed`]) {
// 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.
//
// An event carrying an explicit `end` (a detected run or harmonized
// window) instead stops there — that is what preserves an internal or
// trailing rest instead of sustaining the chord across it. It is still
// clamped to the next onset and to `lengthSeconds`, so a detected end
// can't overlap the next chord or outlive the arrangement, but the 100 ms
// floor does not apply: a measured 20 ms run is 20 ms, not 100, or the
// chord would spill back into the rest the end exists to mark.
function _eventDuration(events, index, options) {
const start = events[index].t;
const event = events[index];
const start = event.t;
const next = events[index + 1];
const fallback = Math.max(0.1, Number(options.defaultDuration) || 2);
const length = Number(options.lengthSeconds);
const explicitEnd = Number(event.end);
if (Number.isFinite(explicitEnd) && explicitEnd > start) {
let end = explicitEnd;
// Never past the next onset (a caller could hand us an overlapping
// end) nor past `lengthSeconds` (the arrangement's own length).
if (next && next.t < end) end = next.t;
if (Number.isFinite(length) && length > start) end = Math.min(end, length);
// Honor the measured end exactly; flooring the duration up to 100 ms
// here would push a short segment back over the rest that follows it.
return end - start;
}
const end = next ? next.t : Math.max(start + fallback, Number.isFinite(length) ? length : 0);
return Math.max(0.1, end - start);
}
Expand Down Expand Up @@ -950,8 +978,10 @@ if (!window[`__${PLUGIN_ID}_installed`]) {
// unnamed). Fetches the song's audio (same-origin regardless of source
// format — sloppak/loose-folder/archive all resolve to a playable URL
// via songInfo.audio_url) and uploads it to the backend's chroma-CQT +
// template-matching detector. Returns [{ t, name }, ...] or null on any
// failure — the view just has no chords for this song, same as today.
// template-matching detector. Returns [{ t, name, end }, ...] or null on
// any failure — the view just has no chords for this song, same as today.
// `end` is the detected run's own end, so a rest before the next chord is
// preserved rather than sustained over.
const detectChordsFromAudio = async (audioUrl) => {
if (!audioUrl || typeof fetch === "undefined") return null;
try {
Expand Down Expand Up @@ -1095,7 +1125,12 @@ if (!window[`__${PLUGIN_ID}_installed`]) {
});
const chosen = triads[bestIdx];
const name = (NOTE_NAMES_SHARP[chosen.root] || "C") + chosen.suffix;
chords.push({ t: winStart, name });
// Carry the window's end so a silent window between two sung windows
// stays a rest: the chord stops at its own window boundary rather than
// being sustained to the next chord's onset. The final window is capped
// at `lastEnd` so the accompaniment stops where the melody does instead
// of filling the trailing silence out to the window edge.
chords.push({ t: winStart, name, end: Math.min(winEnd, lastEnd) });
lastChosen = bestIdx;
}
return chords;
Expand Down
39 changes: 39 additions & 0 deletions tests/generate_accompaniment_from_lyrics.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,45 @@ test('harmonizes a C major melody into a diatonic keys accompaniment', async ()
assert.ok(result.notes.length > 0);
});

test('does not sustain a chord across silent windows', async () => {
const chordr = freshPlugin();
// The issue's repro: two short pitched notes ten seconds apart. Every
// window between them is empty, so the first chord must stop at its own
// window boundary rather than being held until the next onset.
const tokens = [
{ start: 0, duration: 1, text: 'la', midi: 60 },
{ start: 10, duration: 1, text: 'la', midi: 60 },
];
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: 2 }),
);

assert.ok(result);
assert.deepEqual(result.sourceChords.map((c) => c.t), [0, 10]);
const firstSus = [...new Set(result.notes.filter((n) => n.t === 0).map((n) => n.sus))];
assert.deepEqual(firstSus, [2]); // one window long, not 10
assert.deepEqual(result.notes.filter((n) => n.t > 0 && n.t < 10), []);
});

test('stops the accompaniment where the melody ends (trailing silence)', async () => {
const chordr = freshPlugin();
const tokens = [{ start: 0, duration: 1, text: 'la', midi: 60 }];
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: 2 }),
);

assert.ok(result);
// The melody ends at t=1, inside the 2s window — the chord stops there
// instead of filling the window's trailing silence.
assert.deepEqual([...new Set(result.notes.map((n) => n.sus))], [1]);
});

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 });
Expand Down
71 changes: 71 additions & 0 deletions tests/generate_arrangement.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,74 @@ test('lengthSeconds holds the trailing chord out to the arrangement length', ()
assert.equal(trailing({}), 2);
assert.equal(trailing({ defaultDuration: 6 }), 6);
});

test('an explicit event end stops a chord before the next onset', () => {
const chordr = freshPlugin();
const result = chordr.generateKeysArrangement([
{ t: 0, name: 'C', end: 1 },
{ t: 10, name: 'F', end: 11 },
]);
const sus = (t) => result.notes.filter((n) => n.t === t).map((n) => n.sus);

// Each chord stops at its own detected end, so the silent stretch between
// them (t=1..10) is a rest rather than being sustained over.
assert.deepEqual([...new Set(sus(0))], [1]);
assert.deepEqual([...new Set(sus(10))], [1]);
});

test('an explicit event end shorter than 100 ms is honored, not floored', () => {
const chordr = freshPlugin();
const result = chordr.generateKeysArrangement([
{ t: 0, name: 'C', end: 0.02 },
{ t: 5, name: 'F', end: 5.02 },
]);
const sus = (t) => [...new Set(result.notes.filter((n) => n.t === t).map((n) => n.sus))];

// A measured 20 ms run stays 20 ms: flooring it up to 100 ms would spill the
// chord into the rest that follows it.
assert.deepEqual(sus(0), [0.02]);
assert.ok(Math.abs(sus(5)[0] - 0.02) < 1e-9);
});

test('an explicit event end is not extended by lengthSeconds', () => {
const chordr = freshPlugin();
// No next onset and a lengthSeconds past the end: without honoring `end`
// the final note would be stretched to 60 to fill the arrangement.
const result = chordr.generateKeysArrangement([{ t: 0, name: 'C', end: 1 }], { lengthSeconds: 60 });
assert.deepEqual([...new Set(result.notes.map((n) => n.sus))], [1]);
});

test('an explicit event end is capped at lengthSeconds and the next onset', () => {
const chordr = freshPlugin();
const sus = (result, t) => [...new Set(result.notes.filter((n) => n.t === t).map((n) => n.sus))];

// end past lengthSeconds: capped to the arrangement's length.
const cappedByLength = chordr.generateKeysArrangement([{ t: 0, name: 'C', end: 100 }], { lengthSeconds: 5 });
assert.deepEqual(sus(cappedByLength, 0), [5]);

// A caller-supplied end that overlaps the next onset can't produce an
// overlapping sustain — it stops at the next chord.
const overlapping = chordr.generateKeysArrangement([
{ t: 0, name: 'C', end: 10 },
{ t: 4, name: 'F', end: 8 },
]);
assert.deepEqual(sus(overlapping, 0), [4]);
assert.deepEqual(sus(overlapping, 4), [4]);
});

test('generateArrangementFromAudio honors detected run ends', 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', end: 1 }, { t: 10, name: 'C', end: 11 }] }) };
};
try {
const chordr = freshPlugin();
const result = await chordr.generateArrangementFromAudio('/song.ogg', { lengthSeconds: 180 });
const sus = (t) => [...new Set(result.notes.filter((n) => n.t === t).map((n) => n.sus))];
assert.deepEqual(sus(0), [1]);
assert.deepEqual(sus(10), [1]);
} finally {
global.fetch = originalFetch;
}
});
Loading
Loading