diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d5f153..acd315c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/CLAUDE.md b/CLAUDE.md index 8efb97c..66b9f28 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.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 @@ -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 ``` diff --git a/README.md b/README.md index 91af7bf..786932a 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/chordr/plugin.json b/chordr/plugin.json index 546f9cc..308665c 100644 --- a/chordr/plugin.json +++ b/chordr/plugin.json @@ -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", diff --git a/chordr/screen.js b/chordr/screen.js index 7399db0..2a1feb2 100644 --- a/chordr/screen.js +++ b/chordr/screen.js @@ -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 @@ -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++) { diff --git a/tests/generate_accompaniment_from_lyrics.test.js b/tests/generate_accompaniment_from_lyrics.test.js index 599316f..e2953c7 100644 --- a/tests/generate_accompaniment_from_lyrics.test.js +++ b/tests/generate_accompaniment_from_lyrics.test.js @@ -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]); +});