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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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)
- Lyric harmonization (`generateAccompanimentFromLyrics` →
`_harmonizeMelody`) no longer hangs the page on malformed vocal playback
timestamps. Each token field was already required to be finite, but the SUM
of two finite values can overflow to Infinity (`{start: 1e308, duration:
1e308}`), and a large finite span still implied one synchronous window per
slice of it on the browser main thread. The summed endpoint is now validated
for finiteness and against the 15-minute song horizon (the same bound the
audio path applies, though out-of-horizon melodies are rejected rather than
truncated), and the window loop is hard-capped regardless of timestamps —
out-of-range melodies return the same `null` "nothing to harmonize" result
as a rest-only or lyrics-only track. (#28)

<!-- Add entries under Added, Changed, Deprecated, Removed, Fixed, or Security as changes land. -->
4 changes: 2 additions & 2 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.1`; the chart-transform block has been declared in its
currently at `0.6.2`; 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,7 +128,7 @@ before assuming a given host can run it.
## Testing

```bash
node --test tests/*.test.js # 107 pass
node --test tests/*.test.js # 110 pass
python3 -m pip install -r tests/requirements.txt
python3 -m unittest discover -s tests -p 'test_*.py' # 20 pass
```
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,14 @@ final window stops where the melody ends. This is melody harmonization, not chor
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.
track is lyrics-only (no `midi` on any token), the response's
`schema_version` isn't the one this function understands, or the melody's
timeline falls outside the supported song bounds — a summed endpoint
`start + duration` that overflows (both fields can be finite yet sum to
Infinity) or a span past the 15-minute song horizon (the same bound the
audio path applies). Out-of-bound melodies are rejected rather than
truncated, since either case would otherwise mean iterating one
synchronous window per slice of the whole span on the page's main thread.

`groupChordEvents` returns a `{ parentIndex, continuation }` entry for every
chord event. A nonempty event whose played `{s,f}` notes are a subset of the
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.1",
"version": "0.6.2",
"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
33 changes: 31 additions & 2 deletions chordr/screen.js
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,22 @@ if (!window[`__${PLUGIN_ID}_installed`]) {
});
}

// Supported song horizon for a melody to harmonize, sharing the 15-minute
// bound routes.py's MAX_AUDIO_DURATION_SECONDS applies to audio. Unlike
// that cap (which truncates the loaded audio), a melody past the horizon
// is rejected outright: the caller's "nothing to harmonize" null is more
// honest than silently dropping the tail, and anything longer is malformed
// or hostile — harmonizing it would iterate a window per slice of the whole
// span on the browser main thread.
const MAX_HARMONIZED_MELODY_SECONDS = 900.0;
// Hard cap on the number of windows per call, independent of the
// timestamps, so the main-thread loop can never iterate an impractical
// number of times even if the horizon or minimum windowSeconds ever change.
// It never binds today — the 900s horizon at the minimum 0.5s window is
// 1800 windows < 3000 — so it is defense-in-depth over the horizon check,
// not a second guard that can fire.
const MAX_HARMONY_WINDOWS = 3000;

// 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
Expand All @@ -1100,8 +1116,21 @@ if (!window[`__${PLUGIN_ID}_installed`]) {
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));
// The endpoint is a SUM of the tokens' start/duration, so validating
// each field for finiteness is not enough: two finite values can still
// sum to Infinity ({start: 1e308, duration: 1e308}), which would make
// the window loop below run forever, and a large finite span still
// implies a window per slice of it. Validate the summed endpoint and
// bail out with no chords — the caller returns null for a melody that
// cannot be harmonized, the same graceful result a rest- or lyrics-only
// track already produces.
let lastEnd = 0;
for (const t of tokens) {
const end = t.start + t.duration;
if (!Number.isFinite(end) || end > MAX_HARMONIZED_MELODY_SECONDS) return [];
if (end > lastEnd) lastEnd = end;
}
const windowCount = Math.min(MAX_HARMONY_WINDOWS, Math.max(1, Math.ceil(lastEnd / windowSeconds)));
const chords = [];
let lastChosen = -1;
for (let w = 0; w < windowCount; w++) {
Expand Down
69 changes: 69 additions & 0 deletions tests/generate_accompaniment_from_lyrics.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,72 @@ test('instrument option is honored end to end (guitar accompaniment)', async ()
assert.equal(result.instrument, 'guitar');
assert.ok(Array.isArray(result.shapes) && result.shapes.length > 0);
});

test('returns null for a melody endpoint that overflows to Infinity', { timeout: 2000 }, async () => {
const chordr = freshPlugin();
const payload = {
schema_version: 1,
voices: [{ id: 'primary', primary: true, tokens: [
// A normal token so that — without the finiteness check on the summed
// endpoint — a real chord would be produced and the null above it
// would not be attributable to an empty window grid.
{ start: 0, duration: 1, text: 'la', midi: 60 },
// The issue's repro: each field is finite, but start + duration
// overflows the summed endpoint to Infinity. The old window loop
// iterated `w < Math.ceil(Infinity / windowSeconds)` forever — this
// test would hang instead of completing against that code.
{ start: 1e308, duration: 1e308, text: 'la', midi: 60 },
] }],
};

const result = await withFetch(
async () => ({ ok: true, json: async () => payload }),
() => chordr.generateAccompanimentFromLyrics('song.sloppak'),
);

assert.equal(result, null);
});

test('returns null for a very large but finite melody beyond the song horizon', { timeout: 2000 }, async () => {
const chordr = freshPlugin();
const payload = {
schema_version: 1,
voices: [{ id: 'primary', primary: true, tokens: [
{ start: 0, duration: 1, text: 'la', midi: 60 },
// Finite, so no overflow — but ~317 years is no song. Without the
// horizon check the old code synchronously iterated a window per
// slice of the whole span on the browser main thread (≈5 billion
// iterations here) instead of returning null.
{ start: 1e10, duration: 1, text: 'la', midi: 60 },
] }],
};

const result = await withFetch(
async () => ({ ok: true, json: async () => payload }),
() => chordr.generateAccompanimentFromLyrics('song.sloppak'),
);

assert.equal(result, null);
});

test('still harmonizes a long melody inside the supported song horizon', { timeout: 2000 }, async () => {
const chordr = freshPlugin();
const payload = {
schema_version: 1,
voices: [{ id: 'primary', primary: true, tokens: [
{ start: 0, duration: 1, text: 'la', midi: 60 },
// Ends at 890s, inside the 900s horizon — must not be over-rejected
// as out-of-range by the same check that rejects the hostile spans
// above.
{ start: 889, duration: 1, text: 'la', midi: 60 },
] }],
};

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, 888]);
});
Loading