huashu-motion 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +28 -1
- package/README.md +28 -1
- package/THIRD_PARTY.md +2 -0
- package/cli/lib/arrange.js +570 -0
- package/cli/lib/beats-report.js +180 -0
- package/cli/lib/beats.js +351 -22
- package/cli/lib/check.js +16 -0
- package/cli/lib/music.js +156 -0
- package/cli/lib/render-om.js +2 -1
- package/cli/lib/render.js +11 -1
- package/cli/lib/sound.js +81 -12
- package/cli/lib/track.js +342 -0
- package/cli/om.js +15 -0
- package/music/LICENSE.md +35 -0
- package/music/catalog.json +316 -0
- package/package.json +2 -2
- package/runtime/om.js +48 -1
- package/skills/huashu-motion/SKILL.md +9 -6
- package/skills/huashu-motion/references/about-author.md +1 -0
- package/skills/huashu-motion/references/director.md +2 -2
- package/skills/huashu-motion/references/music-sources.md +47 -0
- package/skills/huashu-motion/references/music.md +4 -0
- package/skills/huashu-motion/references/rhythm.md +2 -0
- package/skills/huashu-motion/references/sound.md +63 -1
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
// Arrange a track to a film the way a music editor does: a natural beginning (the track's own first bars, untouched), an elastic
|
|
2
|
+
// middle (whole bars or phrases dropped or repeated so the length fits), a natural ending. Joins go only inside stable stretches of
|
|
3
|
+
// the track, on bar lines, never across a lift or a segment change: a lift together with the fill bar before it and the bar after it
|
|
4
|
+
// stays as the track has it. Candidates are generated by several strategies and scored together:
|
|
5
|
+
//
|
|
6
|
+
// A elastic middle opening, then bars chosen by beam search (fit to the film's energy, harmony, loudness), then the ending
|
|
7
|
+
// B head and tail the first N bars, one join, the last M bars: the shortest way to a film
|
|
8
|
+
// C button ending when the track's own ending is a fade, a hard cut, or longer than the film allows: stop on a strong
|
|
9
|
+
// home-chord hit in the main section and let it ring out in a reverb tail
|
|
10
|
+
// (fade) the old way, only when nothing above works: the last bar, then a fade
|
|
11
|
+
// D film yields the film lengths at which a track needs one join or none (`fitDurations`), so the film can be
|
|
12
|
+
// cut to the music instead of the music to the film
|
|
13
|
+
// E micro stretch OM.music({ stretch: 'fit' }): up to 3 % to absorb the last fraction of a bar
|
|
14
|
+
//
|
|
15
|
+
// A join must keep both sides within 3 dB over one second, both bars on the same segment or energy grade, and a harmony smooth
|
|
16
|
+
// enough (score >= 0.55). The arrangement is a pure function of the track's map and the film's declarations.
|
|
17
|
+
import { chromaCosine } from './beats.js';
|
|
18
|
+
import { OmError } from './project.js';
|
|
19
|
+
|
|
20
|
+
const r3 = (x) => Math.round(x * 1000) / 1000;
|
|
21
|
+
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
|
|
22
|
+
export const JOIN_X = 0.04; // seconds of crossfade ahead of a join
|
|
23
|
+
export const GOOD_JOIN = 0.6, OK_JOIN = 0.4;
|
|
24
|
+
export const MIN_RANGE_DB = 4; // a track whose bars span less than this (10th to 98th percentile of bar loudness) is too flat to re-cut
|
|
25
|
+
const PROTECT_STEP = 0.2; // a change of segment energy this big is a lift (or a drop) that is never cut across
|
|
26
|
+
const JOIN_COST = 0.7; // a join is only worth it for what it buys: playing the track straight is the default
|
|
27
|
+
const TRIM_MAX = 2; // dB of static gain a join may add to level its two sides
|
|
28
|
+
export const STRETCH_MAX = 0.03; // OM.music({ stretch }) bends the track at most this far
|
|
29
|
+
|
|
30
|
+
// ---------- the film's side ----------
|
|
31
|
+
|
|
32
|
+
// A time given as seconds or as a scene label ('hero' or 'scene:hero'); null when it names nothing.
|
|
33
|
+
export function timeOf(v, labels = {}) {
|
|
34
|
+
if (v == null || v === false) return null;
|
|
35
|
+
if (typeof v === 'number' && isFinite(v)) return v;
|
|
36
|
+
if (typeof v === 'string') {
|
|
37
|
+
if (/^\d+(\.\d+)?$/.test(v)) return Number(v);
|
|
38
|
+
for (const k of [`scene:${v}`, v, `scene:${v.replace(/^scene:/, '')}`]) if (labels[k] != null) return Number(labels[k]);
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// What the film says about itself: OM.music({ burst, peak, stop, drop, energy }) and its scene labels.
|
|
44
|
+
export function filmStructure({ labels = {}, music = {}, duration }) {
|
|
45
|
+
const notes = [];
|
|
46
|
+
const ref = (k) => { const t = timeOf(music[k], labels); if (music[k] != null && t == null) notes.push(`OM.music({ ${k}: ${JSON.stringify(music[k])} }) names no scene or time`); return t; };
|
|
47
|
+
const burst = ref('burst') ?? ref('drop'), peak = ref('peak'), landing = ref('landing');
|
|
48
|
+
let stop = null;
|
|
49
|
+
if (Array.isArray(music.stop)) { const a = timeOf(music.stop[0], labels), b = timeOf(music.stop[1], labels); if (a != null && b != null && b > a) stop = [a, b]; else notes.push('OM.music({ stop }) wants [from, to]'); }
|
|
50
|
+
else if (music.stop != null) { const a = timeOf(music.stop, labels); if (a != null) stop = [a, burst != null && burst > a ? burst : a + 1]; else notes.push(`OM.music({ stop: ${JSON.stringify(music.stop)} }) names no scene or time`); }
|
|
51
|
+
const scenes = Object.entries(labels).filter(([k]) => k.startsWith('scene:')).map(([k, t]) => ({ name: k.slice(6), t: Number(t) })).sort((a, b) => a.t - b.t);
|
|
52
|
+
const energy = {};
|
|
53
|
+
for (const [k, v] of Object.entries(music.energy || {})) if (isFinite(Number(v))) energy[k.replace(/^scene:/, '')] = clamp(Number(v));
|
|
54
|
+
return { duration, burst, peak, landing, stop, scenes, energy, notes };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The energy the film wants from its music at time t, 0–1.
|
|
58
|
+
export function targetAt(st, t) {
|
|
59
|
+
const D = st.duration;
|
|
60
|
+
// base: the scenes climb from a low start to full; the last scene resolves
|
|
61
|
+
let base;
|
|
62
|
+
const n = st.scenes.length;
|
|
63
|
+
if (n >= 2) {
|
|
64
|
+
let idx = 0; for (let i = 0; i < n; i++) if (st.scenes[i].t <= t + 1e-6) idx = i;
|
|
65
|
+
const sc = st.scenes[idx];
|
|
66
|
+
base = st.energy[sc.name] ?? (idx === n - 1 && n >= 3 ? 0.5 : 0.35 + 0.65 * (idx / Math.max(1, n - 2)));
|
|
67
|
+
} else base = t < 0.75 * D ? 0.4 + 0.6 * (t / (0.75 * D)) : 0.6;
|
|
68
|
+
let e = clamp(base);
|
|
69
|
+
if (st.burst != null) e = t < st.burst - 1e-6 ? Math.min(e, 0.55) : Math.max(e, 0.85);
|
|
70
|
+
if (st.peak != null && t >= st.peak - 1e-6) e = 1;
|
|
71
|
+
if (st.stop && t >= st.stop[0] - 1e-6 && t < st.stop[1] - 1e-6) e = Math.min(e, 0.3);
|
|
72
|
+
if (t < 3) e = Math.min(e, 0.45); // the hook is a quiet start
|
|
73
|
+
return e;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---------- the track's side ----------
|
|
77
|
+
|
|
78
|
+
const phraseStarts = (map) => { const s = new Set(); for (const g of map.segments) for (let i = g.from; i < g.to; i += 4) s.add(i); return s; };
|
|
79
|
+
|
|
80
|
+
// How well bar a leads into bar b (a ≠ b − 1): the chroma of a's tail against b's head, and the step in energy. 1 = seamless.
|
|
81
|
+
export function joinScore(map, a, b) {
|
|
82
|
+
const A = map.bars[a], B = map.bars[b];
|
|
83
|
+
const cd = 1 - Math.max(0, chromaCosine(A.tail, B.head)), de = Math.abs(A.e - B.e);
|
|
84
|
+
return r3(clamp(1 - 1.5 * cd - 0.4 * de));
|
|
85
|
+
}
|
|
86
|
+
const chordStep = (map, a, b) => `${map.bars[a].chord}→${map.bars[b].chord}`;
|
|
87
|
+
|
|
88
|
+
// ---------- the search ----------
|
|
89
|
+
|
|
90
|
+
const GRID_SLACK = 0.06; // seconds: an event this close to a bar line is on it
|
|
91
|
+
const LOUD_LIMIT = 3.05; // dB over 1 s each side of a join
|
|
92
|
+
const MIN_SMOOTH = 0.55; // join smoothness below which a join is not allowed
|
|
93
|
+
const END_MAX = 0.45; // a natural ending may take this share of the film
|
|
94
|
+
const BUTTON_TAIL = [2.2, 4.2]; // seconds of ring after a button hit
|
|
95
|
+
|
|
96
|
+
const protectedBars = (map) => {
|
|
97
|
+
const P = new Set(), X = new Set();
|
|
98
|
+
map.segments.forEach((g, k) => { if (k > 0 && Math.abs(g.energy - map.segments[k - 1].energy) >= PROTECT_STEP) { for (const i of [g.from - 1, g.from, g.from + 1]) P.add(i); if (g.energy > map.segments[k - 1].energy) for (const i of [g.from - 1, g.from]) X.add(i); } }); // every real lift or drop, with its fill bar and the bar after: nothing joins into them, and the fill and the lift are not left before the next bar has played
|
|
99
|
+
P.out = X;
|
|
100
|
+
return P;
|
|
101
|
+
};
|
|
102
|
+
const segIndex = (map) => { const a = new Array(map.bars.length).fill(0); map.segments.forEach((g, k) => { for (let i = g.from; i < g.to; i++) a[i] = k; }); return a; };
|
|
103
|
+
|
|
104
|
+
// The ways bar p can lead into bar m (m != p + 1): at the bar line ('bar': p whole, then m) or on the fourth beat ('beat3': p's first three
|
|
105
|
+
// beats, then the last beat of bar m - 1, then m: the join sits at the same place of the progression on both sides). null when none is allowed.
|
|
106
|
+
function optionsOf(ctx, p, m) {
|
|
107
|
+
const al = !!(ctx.allow && ctx.allow.has(m)), key = (al ? -1 : 1) * (p * 4096 + m), hit = ctx.edges.get(key);
|
|
108
|
+
if (hit !== undefined) return hit;
|
|
109
|
+
const { map, P, seg, bars } = ctx, A = bars[p], out = [];
|
|
110
|
+
const pos = (i) => { const k = Math.min(i, bars.length - 1); return (k - map.segments[seg[k]].from) % 4; }, level = (x, y) => seg[x] === seg[y] || map.segments[seg[x]].grade === map.segments[seg[y]].grade || Math.abs(bars[x].e - bars[y].e) <= 0.12 || (Math.abs(map.segments[seg[x]].grade - map.segments[seg[y]].grade) <= 2 && Math.abs(bars[x].dbOut - bars[y].dbIn) <= 4.5); // or the same loudness within a trim
|
|
111
|
+
const blocked = (x) => P.has(x) && !(al && x === m && Math.abs(bars[p].e - bars[m].e) <= 0.15); // a lift-aligned join may enter the straight run to the lift even where that run touches a segment change, if the bar levels with where the join comes from
|
|
112
|
+
if (!P.out.has(p) && !blocked(m) && level(p, m)) {
|
|
113
|
+
const smooth = joinScore(map, p, m);
|
|
114
|
+
if (smooth >= MIN_SMOOTH) { const posMatch = pos(p + 1) === pos(m), phrase = ctx.phrase.has(p + 1) && ctx.phrase.has(m); out.push({ kind: 'bar', smooth, d0: r3(bars[m].dbIn - A.dbOut), posMatch, phrase, cos: r3(chromaCosine(A.tail, bars[m].head)), base: 0.35 + 1.5 * (1 - smooth) - (phrase ? 0.3 : 0) - (posMatch ? 0.2 : 0) }); }
|
|
115
|
+
}
|
|
116
|
+
if (m >= 1 && !P.out.has(p) && !P.has(m - 1) && !blocked(m) && level(p, m - 1) && pos(p) === pos(m - 1)) {
|
|
117
|
+
const Q = bars[m - 1], cos = chromaCosine(A.tail, Q.tail), smooth = r3(clamp(1 - 1.5 * (1 - Math.max(0, cos)) - 0.4 * Math.abs(A.e - Q.e)));
|
|
118
|
+
if (smooth >= MIN_SMOOTH) out.push({ kind: 'beat3', smooth, d0: r3(Q.dbOut - A.dbOut), posMatch: true, phrase: false, cos: r3(cos), base: 0.55 + 1.5 * (1 - smooth) - 0.2 });
|
|
119
|
+
}
|
|
120
|
+
ctx.edges.set(key, out);
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
// from a state (bar p, static gain g so far) into bar m: the cheapest allowed way, with the gain the new run gets (at most 2 dB of trim to level the join)
|
|
124
|
+
function stepOf(ctx, s, m) {
|
|
125
|
+
if (m === s.m + 1) return { cost: 0.1, kind: 'consec', g: s.g };
|
|
126
|
+
let best = null;
|
|
127
|
+
for (const o of optionsOf(ctx, s.m, m)) {
|
|
128
|
+
const d = o.d0, trim = clamp(d, -TRIM_MAX, TRIM_MAX), resid = d - trim; // the new run enters d dB louder; its static gain takes up to 2 dB of that
|
|
129
|
+
if (Math.abs(resid) > LOUD_LIMIT) continue;
|
|
130
|
+
const g2 = s.g - trim; if (Math.abs(g2) > 3) continue;
|
|
131
|
+
const cost = JOIN_COST + o.base + 0.12 * Math.abs(resid) + 0.1 * Math.abs(trim) + 0.04 * Math.abs(g2);
|
|
132
|
+
if (!best || cost < best.cost) best = { cost, kind: o.kind, g: g2, o, resid, trim };
|
|
133
|
+
}
|
|
134
|
+
return best;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// One arrangement: opening bars 0..a-1, a middle of n bars, then the ending. Returns null when no valid middle exists.
|
|
138
|
+
const fail = (ctx, why, info) => { ctx.why[why] = (ctx.why[why] || 0) + 1; if (process.env.OM_ARR_DEBUG === '2' && info) console.error(' fail', why, JSON.stringify(info)); return null; };
|
|
139
|
+
function build(ctx, o) {
|
|
140
|
+
const { map, bars, durs, B, D, st, beatLen } = ctx;
|
|
141
|
+
const { a, ts, end } = o, g0 = bars[0].start - ts;
|
|
142
|
+
const line = (j) => g0 + j * B;
|
|
143
|
+
// ending geometry
|
|
144
|
+
let Jend, endInfo;
|
|
145
|
+
if (end.kind === 'natural') {
|
|
146
|
+
const Tz = ctx.an.end - bars[end.z].start;
|
|
147
|
+
if (Tz < 1.5) return fail(ctx, 'ending too short');
|
|
148
|
+
Jend = Math.round((D - Tz - g0) / B);
|
|
149
|
+
endInfo = { kind: 'natural', bar: end.z, T: Tz, slack: D - Tz - line(Jend) };
|
|
150
|
+
} else if (end.kind === 'button') {
|
|
151
|
+
Jend = Math.floor((D - BUTTON_TAIL[0] - g0) / B);
|
|
152
|
+
const T = D - line(Jend);
|
|
153
|
+
if (T > BUTTON_TAIL[1]) return fail(ctx, 'button tail');
|
|
154
|
+
endInfo = { kind: 'button', bar: end.h, T, slack: 0 };
|
|
155
|
+
} else { // fade: the film's last bar, then a fade
|
|
156
|
+
const f = ctx.fade, lines = []; for (let j = 0; line(j) <= D - f + 1e-9; j++) lines.push(j);
|
|
157
|
+
const Jf = lines.at(-1); Jend = Jf + 1;
|
|
158
|
+
endInfo = { kind: 'fade', bar: null, T: 0, slack: 0, Jf };
|
|
159
|
+
}
|
|
160
|
+
const n = Jend - a;
|
|
161
|
+
if (n < 0 || a < 2 || a > ctx.M - 2) return fail(ctx, 'n<0');
|
|
162
|
+
if (o.mid === 'B' && n !== 0) return fail(ctx, 'B n!=0');
|
|
163
|
+
const lo = a, hi = end.kind === 'natural' ? end.z : end.kind === 'button' ? end.h : ctx.M;
|
|
164
|
+
const exitTo = end.kind === 'natural' ? end.z : end.kind === 'button' ? end.h : null;
|
|
165
|
+
const fit = (j, m) => {
|
|
166
|
+
const t0 = line(j), tt = t0 + B / 2;
|
|
167
|
+
let sc = ctx.flat ? 0 : -3 * Math.abs(targetAt(st, tt) - bars[m].e);
|
|
168
|
+
for (const L of ctx.lifts) if (L.bar === m) for (const [ev, w] of [[st.burst, 1.6], [st.peak, 0.8]]) if (ev != null) { const d = Math.abs(t0 - ev); if (d <= B + 1e-6) sc += w * Math.min(1, L.step / 0.3) * (d <= B / 4 + 1e-6 ? 1 : 0.35 * (1 - d / B)); }
|
|
169
|
+
if (st.peak != null && Math.abs(t0 - st.peak) <= B / 4 + 1e-6) sc += bars[m].e >= 0.85 ? 0.6 : -0.6;
|
|
170
|
+
return sc;
|
|
171
|
+
};
|
|
172
|
+
// lift-aligned: each forced {j, m} has the track's lift bar m play at film bar j, with its fill bar (m - 1) and the bar before that (m - 2) played straight into it
|
|
173
|
+
const force = o.force || [];
|
|
174
|
+
ctx.allow = new Set(); for (const f of force) for (let k = 0; k <= f.j - 2 - a; k++) ctx.allow.add(f.m - 2 - k); // the bars of the straight run into the lift's fill bar may be entered by a join even where they sit next to a segment change, if they level with where the join comes from
|
|
175
|
+
const reqAt = (j) => { let r = null; for (const f of force) { const k = f.j - j; if (k >= 0 && k <= 2) { if (r != null && r !== f.m - k) return NaN; r = f.m - k; } } return r; };
|
|
176
|
+
for (const f of force) if (f.j - 2 < a || f.j >= Jend || f.m - 2 < lo || f.m + 1 >= hi) return fail(ctx, 'lift out of reach', { a, Jend, lo, hi, force, end: end.z ?? end.h });
|
|
177
|
+
for (let j = a; j < Jend; j++) if (Number.isNaN(reqAt(j))) return fail(ctx, 'lifts overlap');
|
|
178
|
+
const chainAt = (j) => { const c = []; if (reqAt(j) == null) for (const f of force) if (j < f.j - 2) c.push(f.m - 2 - (f.j - 2 - j)); return c; }; // the bars a run heading for the lift's stable bar is on
|
|
179
|
+
const first = { m: a - 1, g: 0 };
|
|
180
|
+
let path = [], cost = 0, lastState = first;
|
|
181
|
+
if (n === 0) {
|
|
182
|
+
if (force.length) return fail(ctx, 'lift needs a middle');
|
|
183
|
+
if (exitTo == null) return fail(ctx, 'B fade');
|
|
184
|
+
const s = stepOf(ctx, first, exitTo); if (!s) return fail(ctx, 'B join not allowed');
|
|
185
|
+
cost += s.cost; path = []; lastState = { ...first, exit: s };
|
|
186
|
+
} else {
|
|
187
|
+
// bars that can lead into the ending: the search is steered towards them near its end (else the beam never arrives)
|
|
188
|
+
const exitSet = new Set();
|
|
189
|
+
if (exitTo != null) { for (let p = lo; p < hi; p++) if (stepOf(ctx, { m: p, g: 0 }, exitTo)) exitSet.add(p); }
|
|
190
|
+
let beam = [];
|
|
191
|
+
const req0 = reqAt(a);
|
|
192
|
+
for (let m = lo; m < hi; m++) { if (req0 != null && m !== req0) continue; const s = stepOf(ctx, first, m); if (s) beam.push({ m, g: s.g, kind: s.kind, o: s.o, sc: fit(a, m) - s.cost, ec: s.cost, prev: null, used: new Set([m]) }); }
|
|
193
|
+
beam.sort((x, y) => y.sc - x.sc);
|
|
194
|
+
{ const ch = chainAt(a), keep = beam.filter((q) => ch.includes(q.m)); beam = [...new Set([...beam.slice(0, 90), ...keep])]; }
|
|
195
|
+
for (let j = a + 1; j < Jend && beam.length; j++) {
|
|
196
|
+
const next = [], req = reqAt(j), chain = chainAt(j);
|
|
197
|
+
for (const s of beam) {
|
|
198
|
+
const cands = new Set(); if (s.m + 1 < hi) cands.add(s.m + 1);
|
|
199
|
+
if (req != null) { cands.clear(); cands.add(req); } else for (const c of chain) if (c !== s.m + 1 && c >= lo && c < hi) cands.add(c);
|
|
200
|
+
const jumps = [];
|
|
201
|
+
if (req == null) {
|
|
202
|
+
for (let m = lo; m < hi; m++) if (m !== s.m + 1 && optionsOf(ctx, s.m, m).length) jumps.push([m, fit(j, m) - (s.used.has(m) ? 0.6 : 0)]);
|
|
203
|
+
jumps.sort((x, y) => y[1] - x[1]); for (const [m] of jumps.slice(0, 6)) cands.add(m);
|
|
204
|
+
}
|
|
205
|
+
if (req == null && j >= Jend - 4) for (const m of exitSet) if (m !== s.m + 1 && (m === s.m + 1 || optionsOf(ctx, s.m, m).length)) cands.add(m);
|
|
206
|
+
for (const m of cands) { const st2 = stepOf(ctx, s, m); if (!st2) continue; const reuse = s.used.has(m) && m !== s.m + 1 ? 0.6 : s.used.has(m) ? 0.3 : 0; next.push({ m, g: st2.g, kind: st2.kind, o: st2.o, sc: s.sc + fit(j, m) - st2.cost - reuse + (j >= Jend - 3 && exitSet.has(m) ? 1.2 : 0), ec: s.ec + st2.cost + reuse, prev: s, used: new Set([...s.used, m]) }); }
|
|
207
|
+
}
|
|
208
|
+
next.sort((x, y) => y.sc - x.sc); beam = next.slice(0, 90);
|
|
209
|
+
if (chain.length) beam = [...new Set([...beam, ...next.filter((q) => chain.includes(q.m)).slice(0, 20)])];
|
|
210
|
+
if (j >= Jend - 3) { const keepE = next.filter((q) => exitSet.has(q.m)).slice(0, 20); beam = [...new Set([...beam, ...keepE])]; }
|
|
211
|
+
}
|
|
212
|
+
let best = null;
|
|
213
|
+
for (const s of beam) { if (exitTo != null) { const e = stepOf(ctx, s, exitTo); if (!e) continue; const sc = s.sc - e.cost; if (!best || sc > best.sc) best = { s, e, sc, ec: s.ec + e.cost }; } else if (!best || s.sc > best.sc) best = { s, e: null, sc: s.sc, ec: s.ec }; }
|
|
214
|
+
if (!best) return fail(ctx, 'no way into the ending', force.length ? { a, Jend, z: exitTo, force, beam: beam.length, exitSet: [...exitSet].join(',') } : null);
|
|
215
|
+
for (let q = best.s; q; q = q.prev) path.push(q); path.reverse();
|
|
216
|
+
cost = best.ec; lastState = { m: best.s.m, g: best.s.g, exit: best.e };
|
|
217
|
+
}
|
|
218
|
+
// the sequence of film bars with how each is entered
|
|
219
|
+
const seq = [];
|
|
220
|
+
for (let i = 0; i < a; i++) seq.push({ m: i, kind: 'consec', g: 0 });
|
|
221
|
+
for (const q of path) seq.push({ m: q.m, kind: q.kind, o: q.o, g: q.g });
|
|
222
|
+
if (end.kind === 'natural') { const ex = lastState.exit; seq.push({ m: end.z, kind: ex?.kind ?? 'consec', o: ex?.o, g: ex?.g ?? lastState.g }); for (let m = end.z + 1; m < ctx.M; m++) seq.push({ m, kind: 'consec', g: ex?.g ?? lastState.g }); }
|
|
223
|
+
else if (end.kind === 'button') { const ex = lastState.exit; seq.push({ m: end.h, kind: ex?.kind ?? 'consec', o: ex?.o, g: ex?.g ?? lastState.g }); }
|
|
224
|
+
// film pieces: a run follows the track; a bar join restarts on the film's bar line; a beat-3 join cuts the previous bar after three beats
|
|
225
|
+
const pieces = [];
|
|
226
|
+
seq.forEach((e, j) => {
|
|
227
|
+
const prev = pieces.at(-1), m = e.m;
|
|
228
|
+
if (j === 0) { pieces.push({ out: 0, from: ts, len: bars[0].end - ts, bar: m, join: null, gain: 0 }); return; }
|
|
229
|
+
if (e.kind === 'beat3') {
|
|
230
|
+
const pb = prev.bar, cut = 3 * beatLen;
|
|
231
|
+
prev.len = Math.min(prev.len, cut);
|
|
232
|
+
const at = line(j - 1) + cut, q = m - 1;
|
|
233
|
+
pieces.push({ out: at, from: bars[q].start + cut, len: durs[q] - cut, bar: q, partial: true, join: { p: pb, kind: 'beat3', o: e.o, m }, gain: e.g });
|
|
234
|
+
pieces.push({ out: at + durs[q] - cut, from: bars[m].start, len: durs[m], bar: m, join: null, gain: e.g });
|
|
235
|
+
} else if (e.kind === 'bar') pieces.push({ out: line(j), from: bars[m].start, len: durs[m], bar: m, join: { p: prev.bar, kind: 'bar', o: e.o, m }, gain: e.g });
|
|
236
|
+
else pieces.push({ out: prev.out + prev.len, from: bars[m].start, len: durs[m], bar: m, join: null, gain: e.g });
|
|
237
|
+
});
|
|
238
|
+
if (end.kind === 'natural') pieces.at(-1).len += ctx.an.end - bars[ctx.M - 1].end;
|
|
239
|
+
return { pieces, seq, a, n, ts, g: g0, line, Jend, endInfo, cost, mid: o.mid, endKind: end.kind, path, force };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// the lifts with the bar the hit lands on: the segment boundary can sit a bar early, on the riser that leads into the hit (that bar's loudness
|
|
243
|
+
// climbs inside it, and the next bar starts 3 dB or more louder than it did)
|
|
244
|
+
function trueLifts(map) {
|
|
245
|
+
const bars = map.bars;
|
|
246
|
+
return (map.lifts || []).map((L) => {
|
|
247
|
+
const b = L.bar, up = (i) => bars[i + 1].dbIn - bars[i].dbIn;
|
|
248
|
+
if (b + 2 < bars.length && b >= 1 && up(b) >= 3 && up(b) - (bars[b].dbIn - bars[b - 1].dbIn) >= 2.5) return { ...L, bar: b + 1, pickup: b, boundary: b };
|
|
249
|
+
return L;
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// how clear the fill bar before a lift is, 0-1: the bar before the lift differs from the one before it (energy, or a rise in the highs: a riser, a cymbal)
|
|
254
|
+
const fillOf = (ctx, L) => fillClarity(ctx.bars, L);
|
|
255
|
+
export function fillClarity(bars, L) {
|
|
256
|
+
const A = bars[L - 1], Z = bars[L - 2]; if (!A || !Z) return 0;
|
|
257
|
+
return r3(clamp(0.5 * clamp(Math.abs(A.e - Z.e) / 0.2) + 0.5 * clamp(((A.hf ?? 0) - (Z.hf ?? 0)) / 4)));
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function arrangeTrack(an, { duration, film = {}, fade = null, tail = 10, only = null, quick = false, noSuggest = false, pick = 0 } = {}) {
|
|
261
|
+
const map = an.map;
|
|
262
|
+
if (!map || map.bars.length < 4) return { ok: false, reason: 'the track has no bar map (too short, or no clear pulse)' };
|
|
263
|
+
if (an.confidence < 0.3 && !an.fit?.forcedBpm) return { ok: false, reason: `no clear pulse (confidence ${an.confidence}): bars are guesses` };
|
|
264
|
+
const bars = map.bars, M = bars.length, st = filmStructure({ labels: film.labels, music: film.music, duration });
|
|
265
|
+
const durs = bars.map((b) => b.end - b.start), B = [...durs].sort((x, y) => x - y)[M >> 1], beatLen = B / 4;
|
|
266
|
+
if (duration < 2 * B) return { ok: false, reason: 'the film is shorter than two bars' };
|
|
267
|
+
const flat = !!(map.dynamics && map.dynamics.rangeDb < MIN_RANGE_DB);
|
|
268
|
+
const f = fade > 0 ? Number(fade) : clamp(2 * beatLen, 1, 1.5);
|
|
269
|
+
const ctx = { flat, an, map, bars, durs, M, B, beatLen, D: duration, st, fade: f, edges: new Map(), why: {}, P: protectedBars(map), seg: segIndex(map), phrase: phraseStarts(map), lifts: trueLifts(map) };
|
|
270
|
+
const ts0 = [0];
|
|
271
|
+
const anchor = st.burst ?? st.peak;
|
|
272
|
+
if (anchor != null) { const sh = ((bars[0].start - anchor) % B + B) % B; if (sh > 0.02 && (sh <= bars[0].start + 0.02 || bars[0].e < 0.3)) ts0.push(r3(sh)); }
|
|
273
|
+
const op = map.opening.bars, aList = quick ? [op] : [...new Set([op, op + 2, op + 4].filter((x) => x >= 2 && x < M / 3))];
|
|
274
|
+
const E = map.ending, ends = [];
|
|
275
|
+
// a natural ending of any length: the last k bars (to the end of the music), k from two bars to the whole closing stretch; it must start at the level the music plays at
|
|
276
|
+
const body = E.bodyDb ?? -15, zs = [];
|
|
277
|
+
for (let z = M - 2; z >= Math.max(op + 1, M - 32); z--) if (bars[z].dbIn >= body - 8 || z >= M - 3) zs.push(z);
|
|
278
|
+
const zPick = quick ? zs.filter((_, i) => i % 3 === 0).slice(0, 5) : zs.filter((_, i) => i < 4 || i % 2 === 0).slice(0, 12);
|
|
279
|
+
for (const z of zPick) ends.push({ kind: 'natural', z });
|
|
280
|
+
const hits = bars.map((b, i) => i).filter((i) => i >= op + 2 && bars[i].tonic && bars[i].e >= 0.55 && bars[i].atk >= 2 && i < M - 2 && !ctx.P.has(i));
|
|
281
|
+
for (const h of hits.slice(0, quick ? 10 : 30)) ends.push({ kind: 'button', h });
|
|
282
|
+
ends.push({ kind: 'fade' });
|
|
283
|
+
const cands = [];
|
|
284
|
+
const hasNaturalEnd = (l) => l.length > 0;
|
|
285
|
+
for (const ts of ts0) for (const e of ends) {
|
|
286
|
+
for (const a of aList) { const r = build(ctx, { a, ts, end: e, mid: 'A' }); if (r) cands.push(r); }
|
|
287
|
+
if (e.kind !== 'fade' && !quick) for (let a = Math.max(2, op); a <= Math.min(M - 3, 16); a++) { const r = build(ctx, { a, ts, end: e, mid: 'B' }); if (r) cands.push(r); }
|
|
288
|
+
}
|
|
289
|
+
const endBonus = (c) => (c.endKind === 'natural' ? { cadence: 1.5, 'ring-out': 1.3, fade: 0.9, 'hard stop': 0.3 }[map.ending.type] ?? 1 : c.endKind === 'button' ? 0.6 : 0);
|
|
290
|
+
const gapOf = (c) => { let s = 0, k = 0; c.pieces.forEach((q) => { if (c.endKind === 'natural' && q.bar >= c.endInfo.bar && !q.partial) return; s += Math.abs(targetAt(st, q.out + B / 2) - bars[q.bar].e); k++; }); return s / Math.max(1, k); }; // the track's own ending is not held to the film's energy curve
|
|
291
|
+
const accentOf = (z) => { const top = Math.max(...bars.slice(z).map((x) => x.db)); let best = z; for (let i = z; i < M; i++) if (bars[i].db >= top - 8 && (bars[best].db < top - 8 || bars[i].atk > bars[best].atk + 0.5)) best = i; return best; }; // the strongest hit in the closing stretch
|
|
292
|
+
const finalChordOf = (z) => { let i = M - 1; while (i - 1 >= z && bars[i - 1].chord === bars[M - 1].chord) i--; return i; }; // the first bar of the closing chord's last run
|
|
293
|
+
const landingOf = (c) => { if (c.endKind === 'button') return c.pieces.at(-1).out; if (c.endKind !== 'natural') return null; const z = c.endInfo.bar, q = c.pieces.find((x) => x.bar === z && !x.partial), ls = accentOf(z), fc = finalChordOf(z); c.endInfo.accent = ls; c.endInfo.chordBar = fc; return q ? q.out + bars[ls].start - bars[z].start : null; };
|
|
294
|
+
const liftW = (L) => 1.5 + 0.5 * Math.min(1, L.step / 0.4) + 0.3 * fillOf(ctx, L.bar); // a real lift on the burst or peak is worth at least what the track's own ending is (1.5), more for a bigger step and a clearer fill
|
|
295
|
+
const scoreOf = (c) => {
|
|
296
|
+
c.gap = gapOf(c); c.joinCount = c.pieces.filter((q) => q.join).length;
|
|
297
|
+
c.score = (ctx.flat ? 0 : -3) * c.gap - c.cost - 0.5 * c.joinCount + endBonus(c) - Math.abs(c.endInfo.slack) / B * 0.6 - (c.ts > 0 ? 0.1 : 0) + (c.mid === 'B' ? 0.1 : 0);
|
|
298
|
+
const nl = (t) => c.pieces.filter((p) => !p.partial).reduce((q, p) => (Math.abs(p.out - t) < Math.abs(q.out - t) ? p : q), c.pieces[0]);
|
|
299
|
+
c.align = 0; c.landing = landingOf(c); c.liftOn = { burst: null, peak: null };
|
|
300
|
+
if (st.burst != null) {
|
|
301
|
+
const q = nl(st.burst), L = ctx.lifts.find((x) => x.bar === q.bar), q1 = nl(st.burst - B), L1 = ctx.lifts.find((x) => x.bar === q1.bar);
|
|
302
|
+
if (Math.abs(q.out - st.burst) <= GRID_SLACK) c.align += 0.8;
|
|
303
|
+
if (L && Math.abs(q.out - st.burst) <= GRID_SLACK) { c.align += liftW(L); c.liftOn.burst = L.step; }
|
|
304
|
+
else if (L1 && Math.abs(q1.out - (st.burst - B)) <= GRID_SLACK && Math.max(bars[L1.bar].e, bars[L1.bar + 1]?.e ?? 0) >= 0.7) { c.align += 0.8 * liftW(L1); c.liftOn.burst = L1.step; c.liftOn.burstEarly = true; } // the lift a bar before: the burst is its second bar
|
|
305
|
+
}
|
|
306
|
+
if (st.peak != null) {
|
|
307
|
+
const q = nl(st.peak); if (Math.abs(q.out - st.peak) <= GRID_SLACK) c.align += 0.4 + (bars[q.bar].e >= 0.85 ? 0.4 : 0);
|
|
308
|
+
const L = ctx.lifts.find((x) => x.bar === q.bar), q1 = nl(st.peak - B), L1 = ctx.lifts.find((x) => x.bar === q1.bar); // the lift lands on the peak, or a bar before it (the peak is then the lift's second bar)
|
|
309
|
+
if (L && Math.abs(q.out - st.peak) <= GRID_SLACK) { c.align += liftW(L); c.liftOn.peak = L.step; }
|
|
310
|
+
else if (L1 && Math.abs(q1.out - (st.peak - B)) <= GRID_SLACK && Math.max(bars[L1.bar].e, bars[L1.bar + 1]?.e ?? 0) >= 0.5) { c.align += 0.8 * liftW(L1); c.liftOn.peak = L1.step; c.liftOn.peakEarly = true; }
|
|
311
|
+
}
|
|
312
|
+
if (st.landing != null && c.landing != null) { const zq = c.pieces.find((x) => x.bar === c.endInfo.bar && !x.partial), fcT = zq && c.endInfo.chordBar != null ? zq.out + bars[c.endInfo.chordBar].start - bars[c.endInfo.bar].start : c.landing; const d = Math.min(Math.abs(c.landing - st.landing), Math.abs(fcT - st.landing)); c.align += d <= 0.25 ? 1.2 : d <= beatLen ? 0.7 : -0.3 * Math.min(2, d / B); }
|
|
313
|
+
c.align += 0.6 * ((c.liftOn.burst != null && c.force?.length ? 1 : 0) + (c.liftOn.peak != null && c.force?.length > 1 || c.liftOn.peak != null && c.force?.length === 1 && c.liftOn.burst == null ? 1 : 0)); // the join that brings a lift onto its event is paid for by the lift: a purposeful join, not a repair
|
|
314
|
+
c.score += c.align; return c;
|
|
315
|
+
};
|
|
316
|
+
// lift-aligned candidates: for the film's burst (and peak), every lift of the track that could land on it with a join at the stable bar two before it
|
|
317
|
+
// (the fill bar and the lift then play untouched). Opening of a few bars shorter or longer than the track's own, so the join can sit where it must.
|
|
318
|
+
const liftsFor = (t, minE, extra) => {
|
|
319
|
+
if (t == null) return [];
|
|
320
|
+
const out = [];
|
|
321
|
+
for (const L of ctx.lifts) {
|
|
322
|
+
if (L.bar < 4 || L.bar + 2 >= M) continue;
|
|
323
|
+
if (Math.max(bars[L.bar].e, bars[L.bar + 1].e) < minE) continue;
|
|
324
|
+
for (const back of extra ? [0, 1] : [0]) out.push({ ...L, back, rank: L.step + 0.4 * fillOf(ctx, L.bar) - 0.1 * back });
|
|
325
|
+
}
|
|
326
|
+
return out.sort((x, y) => y.rank - x.rank);
|
|
327
|
+
};
|
|
328
|
+
if (!only?.noForce) for (const ts of ts0) {
|
|
329
|
+
const g0 = bars[0].start - ts, jOf = (t, back = 0) => { const j = Math.round((t - g0) / B) - back; return Math.abs(g0 + (j + back) * B - t) <= GRID_SLACK ? j : null; };
|
|
330
|
+
const bl = st.burst != null && jOf(st.burst, 0) != null ? liftsFor(st.burst, 0.7, true).slice(0, quick ? 12 : 30) : [];
|
|
331
|
+
const pl = st.peak != null && jOf(st.peak) != null ? liftsFor(st.peak, 0.5, true).slice(0, quick ? 12 : 30) : [];
|
|
332
|
+
const combos = [];
|
|
333
|
+
for (const b of bl) combos.push([{ j: jOf(st.burst, b.back), m: b.bar }]);
|
|
334
|
+
for (const q of pl) combos.push([{ j: jOf(st.peak, q.back), m: q.bar }]);
|
|
335
|
+
const zOk = [...new Set(cands.filter((c) => c.endKind === 'natural').sort((x, y) => x.cost - y.cost).map((c) => c.endInfo.bar))].slice(0, quick ? 3 : 6);
|
|
336
|
+
const nat = zOk.map((z) => ({ kind: 'natural', z })), others = hasNaturalEnd(nat) ? [] : ends.filter((e) => e.kind !== 'natural').slice(0, quick ? 3 : 6);
|
|
337
|
+
const aF = [...new Set(quick ? [op - 2, op] : [op - 3, op - 2, op - 1, op, op + 2])].filter((x) => x >= 3 && x < M / 3);
|
|
338
|
+
const run = (force) => { const got = []; for (const e of [...nat, ...others]) for (const a of aF) { if (force.some((f) => f.j - 2 < a)) continue; const r = build(ctx, { a, ts, end: e, mid: 'A', force }); if (r) got.push(scoreOf(r)); } return got; };
|
|
339
|
+
const best = new Map(); // the best single-lift candidate per lift: the pairs are built from the lifts that work
|
|
340
|
+
for (const force of combos.filter((f) => f.length === 1)) { const got = run(force); cands.push(...got); if (got.length) best.set(`${force[0].j}:${force[0].m}`, Math.max(...got.map((x) => x.score))); }
|
|
341
|
+
const okB = bl.filter((x) => best.has(`${jOf(st.burst, x.back)}:${x.bar}`)).sort((x, y) => best.get(`${jOf(st.burst, y.back)}:${y.bar}`) - best.get(`${jOf(st.burst, x.back)}:${x.bar}`)).slice(0, 3);
|
|
342
|
+
const okP = pl.filter((x) => best.has(`${jOf(st.peak, x.back)}:${x.bar}`)).sort((x, y) => best.get(`${jOf(st.peak, y.back)}:${y.bar}`) - best.get(`${jOf(st.peak, x.back)}:${x.bar}`)).slice(0, 3);
|
|
343
|
+
for (const x of okB) for (const y of okP) cands.push(...run([{ j: jOf(st.burst, x.back), m: x.bar }, { j: jOf(st.peak, y.back), m: y.bar }]));
|
|
344
|
+
}
|
|
345
|
+
for (const c of cands) if (c.score == null) scoreOf(c);
|
|
346
|
+
if (only) { const keep = cands.filter((c) => (!only.mid || c.mid === only.mid) && (!only.endKind || c.endKind === only.endKind)); cands.length = 0; cands.push(...keep); }
|
|
347
|
+
// the ending's priority: the track's own > a button (only when its ending is a hard cut or none fits) > a fade
|
|
348
|
+
const hasNatural = cands.some((c) => c.endKind === 'natural');
|
|
349
|
+
const hasNatural0 = hasNatural;
|
|
350
|
+
if (process.env.OM_ARR_DEBUG) console.error('arrange candidates', cands.length, JSON.stringify(ctx.why));
|
|
351
|
+
if (!cands.length) return { ok: false, reason: 'no arrangement keeps the track\'s opening, a stable join and an ending within this film length' };
|
|
352
|
+
// priority: the track's own ending, then (only for a hard cut) a button, then a fade; within a class the score decides
|
|
353
|
+
const alts = cands.slice();
|
|
354
|
+
if (!only) {
|
|
355
|
+
const pick = hasNatural0 ? cands.filter((c) => c.endKind === 'natural' || (c.endKind === 'button' && map.ending.type === 'hard stop')) : cands.some((c) => c.endKind === 'button') ? cands.filter((c) => c.endKind === 'button') : cands;
|
|
356
|
+
const keep = pick.slice(); cands.length = 0; cands.push(...keep);
|
|
357
|
+
}
|
|
358
|
+
cands.sort((x, y) => y.score - x.score);
|
|
359
|
+
if (process.env.OM_ARR_DEBUG) for (const c of cands.slice(0, 12)) console.error(' cand', c.mid, c.endKind, c.endInfo.bar, 'a', c.a, 'ts', c.ts, 'score', c.score.toFixed(2), 'gap', c.gap.toFixed(2), 'cost', c.cost.toFixed(2), 'align', c.align.toFixed(2), 'slack', c.endInfo.slack.toFixed(2), 'joins', c.joinCount, 'force', JSON.stringify((c.force || []).map((f) => `${f.j}:${f.m}`)));
|
|
360
|
+
// a refused candidate (planTrack's loudness veto) falls through to the rest of the list: the other endings come after the preferred ones
|
|
361
|
+
const order = pick > 0 ? [...cands, ...alts.filter((c) => !cands.includes(c)).sort((x, y) => ({ natural: 0, button: 1, fade: 2 }[x.endKind] - { natural: 0, button: 1, fade: 2 }[y.endKind]) || y.score - x.score)] : cands;
|
|
362
|
+
if (pick >= order.length) return { ok: false, reason: 'no more candidates' };
|
|
363
|
+
const best = order[pick];
|
|
364
|
+
const res = finish(ctx, best, alts.sort((x, y) => (y.score ?? -9) - (x.score ?? -9)), { duration, tail });
|
|
365
|
+
res.candidates = cands.length;
|
|
366
|
+
if (!noSuggest && !only) res.suggestion = suggestFilm(an, { duration, film, fade, tail }, res, ctx);
|
|
367
|
+
return res;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// The film yields: the same track against a film that moves its burst, peak, landing (up to a bar) or its length (up to 4 s). Returns both
|
|
371
|
+
// plans side by side with their scores, and recommends the second when it buys fewer joins, a real ending, or a lift on the burst.
|
|
372
|
+
function suggestFilm(an, { duration, film, fade, tail }, asIs, ctx) {
|
|
373
|
+
const B = ctx.B, st = ctx.st, bars = ctx.bars, lifts = ctx.lifts;
|
|
374
|
+
const base = asIs.score - asIs.alignScore; // the score without the strict alignment terms: alignment is re-judged with the film moved
|
|
375
|
+
const variants = [];
|
|
376
|
+
for (let dD = -4; dD <= 4.01; dD += 1) {
|
|
377
|
+
const D2 = duration + dD; if (D2 < 2 * B + 2) continue;
|
|
378
|
+
const r = dD === 0 ? asIs : arrangeTrack(an, { duration: D2, film, fade, tail, quick: true, noSuggest: true });
|
|
379
|
+
if (!r.ok) continue;
|
|
380
|
+
// what the film would move to: the burst onto the lift nearest it, the peak onto the nearest main bar, the landing onto the ending's strong beat
|
|
381
|
+
const steps = r.steps, moved = {}, pen = { v: 0.12 * Math.abs(dD) };
|
|
382
|
+
if (st.burst != null) { const L = steps.filter((x) => lifts.some((l) => l.bar === x.bar && !x.partial)).sort((x, y) => Math.abs(x.film - st.burst) - Math.abs(y.film - st.burst))[0]; if (L && Math.abs(L.film - st.burst) <= B + 0.01) { moved.burst = r3(L.film); pen.v += 0.1 * Math.abs(L.film - st.burst) / (B / 4); } }
|
|
383
|
+
if (st.peak != null) { const L = steps.filter((x) => bars[x.bar].e >= 0.85 && !x.partial).sort((x, y) => Math.abs(x.film - st.peak) - Math.abs(y.film - st.peak))[0]; if (L && Math.abs(L.film - st.peak) <= B + 0.01) { moved.peak = r3(L.film); pen.v += 0.1 * Math.abs(L.film - st.peak) / (B / 4); } }
|
|
384
|
+
if (st.landing != null && r.ending.landing != null && Math.abs(r.ending.landing - st.landing) <= B + 0.01 + Math.abs(dD)) { moved.landing = r3(r.ending.landing); pen.v += 0.1 * Math.abs(r.ending.landing - st.landing) / (B / 4); }
|
|
385
|
+
const bonus = (moved.burst != null ? 2.0 : 0) + (moved.peak != null ? 0.8 : 0) + (moved.landing != null ? 1.2 : 0);
|
|
386
|
+
variants.push({ duration: r3(D2), moved, lift: r.liftOn, score: r3(r.score - r.alignScore + bonus - pen.v), joins: r.joins.length, endingKind: r.endingKind, endingSeconds: r.ending.kind === 'natural' ? r3(r.ending.musicEnds - r.ending.fromFilm) : 0, ending: r.ending, gap: r.meanGap, steps: r.steps.length });
|
|
387
|
+
}
|
|
388
|
+
const here = { duration, moved: {}, lift: asIs.liftOn, score: r3(asIs.score), joins: asIs.joins.length, endingKind: asIs.endingKind, endingSeconds: asIs.ending.kind === 'natural' ? r3(asIs.ending.musicEnds - asIs.ending.fromFilm) : 0 };
|
|
389
|
+
variants.sort((x, y) => y.score - x.score);
|
|
390
|
+
const top = variants.find((v) => v.duration !== duration || Object.keys(v.moved).length) || null;
|
|
391
|
+
if (!top) return { asIs: here, adjusted: null, recommend: false };
|
|
392
|
+
// what the adjusted film buys. A longer film is never recommended for its longer tail alone: only for fewer joins, a better kind of ending, or a lift that lands on the burst or the peak
|
|
393
|
+
const gain = [];
|
|
394
|
+
if (top.joins < here.joins) gain.push(`${here.joins - top.joins} fewer join${here.joins - top.joins === 1 ? '' : 's'}`);
|
|
395
|
+
if (top.endingKind !== here.endingKind && (top.endingKind === 'natural' || here.endingKind === 'fade')) gain.push(`${top.endingKind === 'natural' ? "the track's own ending" : top.endingKind} instead of ${here.endingKind === 'natural' ? "the track's own ending" : here.endingKind}`);
|
|
396
|
+
if (top.lift?.burst != null && here.lift?.burst == null) gain.push('a real lift of the track on the burst');
|
|
397
|
+
if (top.lift?.peak != null && here.lift?.peak == null) gain.push('a real lift of the track on the peak');
|
|
398
|
+
if (gain.length && top.endingKind === 'natural' && here.endingKind === 'natural' && top.endingSeconds < here.endingSeconds) gain.push(`a shorter tail (${top.endingSeconds.toFixed(1)} s)`);
|
|
399
|
+
return { asIs: here, adjusted: top, recommend: top.score >= here.score + 0.8 && gain.length > 0, gain };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function finish(ctx, c, cands, { duration, tail }) {
|
|
403
|
+
const { map, bars, B, D, st, an } = ctx;
|
|
404
|
+
const segs = [], joins = [], steps = [];
|
|
405
|
+
const pcs = c.pieces;
|
|
406
|
+
let cur = null;
|
|
407
|
+
pcs.forEach((q, k) => {
|
|
408
|
+
if (!cur || q.join) {
|
|
409
|
+
if (cur) cur.len = q.out - cur.out; // a run ends on the join
|
|
410
|
+
cur = { out: q.out, from: q.from, len: q.len, xin: 0, xout: 0, pin: q.join ? JOIN_X : 0, pout: 0, gain: q.gain || 0 };
|
|
411
|
+
if (q.join) segs.at(-1).pout = JOIN_X;
|
|
412
|
+
segs.push(cur);
|
|
413
|
+
} else cur.len += q.len;
|
|
414
|
+
steps.push({ film: r3(q.out), bar: q.bar, track: r3(q.from), label: map.segments[ctx.seg[q.bar]].label, e: bars[q.bar].e, target: r3(targetAt(st, q.out + B / 2)), partial: !!q.partial, gain: q.gain || 0 });
|
|
415
|
+
if (q.join) { const o = q.join.o, to = q.join.m; joins.push({ at: r3(q.out), from: q.join.p, to, kind: q.join.kind, score: o.smooth, chords: `${bars[q.join.p].chord}→${bars[q.partial ? q.bar : to].chord}`, step: r3(bars[to].e - bars[q.join.p].e), dLoud: o.d0, gain: r3(q.gain || 0), posMatch: o.posMatch, phrase: o.phrase, cos: o.cos, novelty: noveltyRank(ctx, q.join.p, q.partial ? q.bar : to) }); }
|
|
416
|
+
});
|
|
417
|
+
const end = c.endInfo, lastSeg = segs.at(-1), fileEnd = Math.min(an.end || an.duration, an.duration);
|
|
418
|
+
let ending, fadeFrom = D, button = null;
|
|
419
|
+
const lastStartFilm = pcs.at(-1).out;
|
|
420
|
+
if (c.endKind === 'natural') {
|
|
421
|
+
lastSeg.len = Math.min(fileEnd - lastSeg.from, lastSeg.len + 0.0);
|
|
422
|
+
const zq = pcs.find((q) => q.bar === end.bar && !q.partial), zStart = zq.out, lastStrong = end.accent ?? map.ending.lastStrong;
|
|
423
|
+
const landing = lastStrong >= end.bar ? r3(zStart + bars[lastStrong].start - bars[end.bar].start) : null;
|
|
424
|
+
const musicEnds = r3(zStart + end.T);
|
|
425
|
+
if (musicEnds > D + 0.02) fadeFrom = Math.max(0, D - Math.min(0.4, musicEnds - D + 0.2));
|
|
426
|
+
const fcBar = end.chordBar ?? ctx.M - 1, finalChord = r3(zStart + bars[fcBar].start - bars[end.bar].start);
|
|
427
|
+
ending = { kind: 'natural', type: map.ending.type, bar: end.bar, bars: ctx.M - end.bar, chord: bars[lastStrong].chord, tonic: bars[lastStrong].tonic, landing, finalChord, finalChordName: bars[fcBar].chord, accentBar: lastStrong, musicEnds, slack: r3(D - musicEnds), fromFilm: r3(zStart), decaySec: map.ending.decaySec };
|
|
428
|
+
} else if (c.endKind === 'button') {
|
|
429
|
+
const h = end.bar, hitLen = ctx.beatLen, at = lastStartFilm;
|
|
430
|
+
lastSeg.len = at - lastSeg.out + hitLen; lastSeg.pout = 0; lastSeg.xout = 0;
|
|
431
|
+
button = { at: r3(at), from: bars[h].start, hitLen: r3(hitLen), tail: r3(D - at), decay: r3(clamp(D - at - hitLen, 1.5, 3)), synthetic: true };
|
|
432
|
+
ending = { kind: 'button', type: 'button', synthetic: true, bar: h, chord: bars[h].chord, tonic: bars[h].tonic, landing: r3(at), musicEnds: r3(D), slack: 0, hitDb: bars[h].atk };
|
|
433
|
+
} else {
|
|
434
|
+
lastSeg.len = Math.max(lastSeg.len, Math.min(fileEnd - lastSeg.from, D + tail - lastSeg.out));
|
|
435
|
+
fadeFrom = r3(c.line(end.Jf));
|
|
436
|
+
const kb = pcs.reduce((q, p, j) => (p.out <= fadeFrom + 1e-6 ? j : q), 0), bb = pcs[kb].bar;
|
|
437
|
+
const E = map.ending, why = `the track's own ending (${E.type}, ${E.seconds.toFixed(1)} s) has no stable join leading into it at this length`;
|
|
438
|
+
ending = { kind: 'fade', type: 'fade', why, bar: bb, chord: bars[bb].chord, tonic: bars[bb].tonic, landing: null, fadeFrom, musicEnds: r3(D), slack: 0 };
|
|
439
|
+
}
|
|
440
|
+
// events and the burst / peak alignment: the film's lines are the music's lines
|
|
441
|
+
const lines = pcs.filter((q) => !q.partial).map((q) => q.out), nearest = (t) => lines.reduce((q, l) => (Math.abs(l - t) < Math.abs(q - t) ? l : q), lines[0]);
|
|
442
|
+
const events = [], suggest = [];
|
|
443
|
+
for (const [name, t] of [['burst', st.burst], ['peak', st.peak], ['stop', st.stop && st.stop[1] !== st.burst ? st.stop[1] : null]]) if (t != null) {
|
|
444
|
+
const nl = nearest(t), off = Math.round((t - nl) * 1000);
|
|
445
|
+
events.push({ name, t, offMs: off, before: r3(lines.filter((l) => l <= t).at(-1) ?? 0), after: r3(lines.find((l) => l >= t) ?? D) });
|
|
446
|
+
if (name !== 'stop' && Math.abs(off) > GRID_SLACK * 1000) suggest.push(`${name} ${t.toFixed(2)}s is ${Math.abs(off)} ms ${off > 0 ? 'after' : 'before'} a bar line: move it to ${r3(nl)}s (${(Math.abs(off) / 1000 / (B / 4)).toFixed(1)} beat${Math.abs(off) / 1000 / (B / 4) > 1.05 ? 's' : ''})`);
|
|
447
|
+
if (name === 'burst' || name === 'peak') {
|
|
448
|
+
const liftAt = (tt) => { const q = pcs.find((x) => !x.partial && Math.abs(x.out - tt) <= GRID_SLACK); return q ? ctx.lifts.find((L) => L.bar === q.bar) : null; };
|
|
449
|
+
const on = Math.abs(off) <= GRID_SLACK * 1000 ? liftAt(nl) : null, early = !on ? liftAt(nl - B) : null;
|
|
450
|
+
if (on) events.at(-1).lift = { at: r3(nl), step: on.step, how: 'on' };
|
|
451
|
+
else if (early) { events.at(-1).lift = { at: r3(nl - B), step: early.step, how: 'a bar before' }; suggest.push(`the track's lift lands at ${r3(nl - B).toFixed(2)}s, a bar before the ${name} (${t.toFixed(2)}s), which is its second bar: move the ${name} to ${r3(nl - B).toFixed(2)}s to put the hit on the lift`); }
|
|
452
|
+
else if (name === 'burst') { const L = pcs.filter((q) => !q.partial && ctx.lifts.some((l) => l.bar === q.bar)).map((q) => q.out).filter((t2) => t2 > 1).sort((x, y) => Math.abs(x - t) - Math.abs(y - t))[0]; if (L != null) suggest.push(`no lift of the track lands on the burst (${t.toFixed(2)}s); the nearest lift in this arrangement is at ${L.toFixed(2)}s: move the burst there (${((L - t) / (B / 4)).toFixed(1)} beats)`); }
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (st.landing != null) {
|
|
456
|
+
const near = [ending.landing, ending.finalChord].filter((v) => v != null).sort((x, y) => Math.abs(x - st.landing) - Math.abs(y - st.landing))[0], d = near != null ? r3(near - st.landing) : null;
|
|
457
|
+
events.push({ name: 'landing', t: st.landing, offMs: d == null ? null : Math.round(-d * 1000) });
|
|
458
|
+
if (d != null && Math.abs(d) > 0.25) suggest.push(`landing ${st.landing.toFixed(2)}s: the ending's strongest accent is at ${ending.landing.toFixed(2)}s${ending.finalChord != null && Math.abs(ending.finalChord - ending.landing) > 0.05 ? ` and its final chord (${ending.finalChordName}) starts at ${ending.finalChord.toFixed(2)}s` : ''} (${d > 0 ? 'later' : 'earlier'} by ${Math.abs(d).toFixed(2)} s than the film's landing): move the end card to the one you want it on`);
|
|
459
|
+
}
|
|
460
|
+
let duck = null;
|
|
461
|
+
if (st.stop) { const beat = B / 4, snap = (t) => r3(c.g + Math.round((t - c.g) / beat) * beat); duck = { from: snap(st.stop[0]), to: snap(st.stop[1]), db: -9, rampIn: 0.06, rampOut: 0.04 }; if (duck.to <= duck.from) duck = null; }
|
|
462
|
+
const worst = joins.reduce((a, j) => Math.min(a, j.score), 1);
|
|
463
|
+
const alternatives = [], seen = new Set();
|
|
464
|
+
for (const x of cands) { const key = `${x.mid}/${x.endKind}`; if (!seen.has(key)) { seen.add(key); alternatives.push({ strategy: x.mid === 'B' ? 'B head+tail' : 'A elastic middle', ending: x.endKind, score: r3(x.score), joins: x.joinCount, gap: r3(x.gap), slack: r3(x.endInfo.slack) }); } }
|
|
465
|
+
return {
|
|
466
|
+
ok: true, flat: ctx.flat, segs, joins, steps, pickup: c.ts, barLen: B, score: r3(c.score), alignScore: r3(c.align), meanGap: r3(c.gap), worstJoin: worst, notes: [...st.notes, ...(ctx.flat ? [`the track has no quiet section: its bars span only ${map.dynamics.rangeDb.toFixed(1)} dB, so the film's energy contour is not followed; the opening, the length and the ending are arranged`] : [])],
|
|
467
|
+
strategy: c.mid === 'B' ? 'B head+tail' : 'A elastic middle', endingKind: c.endKind, liftOn: c.liftOn, ending, button, fadeFrom, duck, events, suggest, alternatives,
|
|
468
|
+
opening: { bars: c.a, end: r3(pcs[c.a - 1].out + pcs[c.a - 1].len), from: r3(c.ts) },
|
|
469
|
+
slack: ending.slack, targets: pcs.filter((q) => !q.partial).map((q) => ({ t: r3(q.out), e: r3(targetAt(st, q.out + B / 2)) })), structure: { burst: st.burst, peak: st.peak, stop: st.stop, landing: st.landing }, grid: c.g,
|
|
470
|
+
fitDurations: fitDurations(an, D),
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// where the join's chroma change sits among the track's own bar-to-bar changes, 0-1 (1 = the biggest change the track makes on a bar line)
|
|
475
|
+
function noveltyRank(ctx, p, m) {
|
|
476
|
+
if (!ctx.own) { ctx.own = []; for (let i = 0; i + 1 < ctx.M; i++) ctx.own.push(1 - Math.max(0, chromaCosine(ctx.bars[i].tail, ctx.bars[i + 1].head))); ctx.own.sort((x, y) => x - y); }
|
|
477
|
+
const v = 1 - Math.max(0, chromaCosine(ctx.bars[p].tail, ctx.bars[m].head));
|
|
478
|
+
return r3(ctx.own.filter((x) => x <= v).length / ctx.own.length);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// D: film lengths at which the track needs one join (opening N bars, then its natural ending) or a button, so a film can be cut to the music
|
|
482
|
+
export function fitDurations(an, D) {
|
|
483
|
+
const map = an.map; if (!map) return [];
|
|
484
|
+
const bars = map.bars, M = bars.length, out = [], ctx = { map, bars, P: protectedBars(map), seg: segIndex(map), phrase: phraseStarts(map), edges: new Map() };
|
|
485
|
+
for (let z = Math.max(4, M - 20); z <= M - 2; z++) {
|
|
486
|
+
if (bars[z].dbIn < (map.ending.bodyDb ?? -15) - 6) continue;
|
|
487
|
+
for (let N = 3; N <= 16 && N < z; N++) {
|
|
488
|
+
const o = optionsOf(ctx, N - 1, z)[0], len = bars[N - 1].end + (an.end - bars[z].start);
|
|
489
|
+
if (o) out.push({ seconds: r3(len), openingBars: N, endingFrom: z, endingBars: M - z, join: o.smooth, ok: true, lifts: (map.lifts || []).filter((L) => L.bar < N).map((L) => r3(bars[L.bar].start)) });
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return out.sort((x, y) => Math.abs(x.seconds - D) - Math.abs(y.seconds - D)).slice(0, 4);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// ---------- measuring the rendered arrangement ----------
|
|
496
|
+
|
|
497
|
+
// 1 s of loudness each side of every join, and the 0.5 s loudness curve's jumps over 6 dB that the track does not have itself
|
|
498
|
+
export function measureArrangement(out, plan, rate = 48000) {
|
|
499
|
+
const a = plan.arrange; if (!a) return { joins: [], jumps: [] };
|
|
500
|
+
const rms = (t0, t1) => { const i0 = Math.max(0, Math.round(t0 * rate)), i1 = Math.min(out.L.length, Math.round(t1 * rate)); let s = 0; for (let i = i0; i < i1; i++) { const v = 0.5 * (out.L[i] + out.R[i]); s += v * v; } return 10 * Math.log10(s / Math.max(1, i1 - i0) + 1e-12); };
|
|
501
|
+
// the window after a join stops where a fade begins or where a button's hit has played (its ring is a decay by design)
|
|
502
|
+
const stopAt = (t) => Math.min(t + 1, a.endingKind === 'fade' ? a.fadeFrom : 1e9, a.button && t < a.button.at + 1e-6 && t > a.button.at - 0.1 ? a.button.at + a.button.hitLen : 1e9);
|
|
503
|
+
const joins = a.joins.map((j) => { const e = stopAt(j.at), ok = e - j.at >= 0.3, b = rms(j.at - 1, j.at), af = ok ? rms(j.at, e) : b; return { at: j.at, before: r3(b), after: r3(af), diff: r3(af - b) }; });
|
|
504
|
+
const jumps = [], skip = (t) => (a.duck && (Math.abs(t - a.duck.from) < 0.6 || Math.abs(t - a.duck.to) < 0.6)) || t > (a.fadeFrom || 1e9) - 0.05 && a.endingKind === 'fade';
|
|
505
|
+
const win = 0.5, n = Math.floor(plan.duration / win), lv = []; for (let k = 0; k < n; k++) lv.push(rms(k * win, (k + 1) * win));
|
|
506
|
+
for (let k = 1; k < n; k++) { const d = lv[k] - lv[k - 1], t = k * win; if (Math.abs(d) > 6 && !skip(t)) { const nearJoin = a.joins.some((j) => Math.abs(j.at - t) < 0.55); const inEnding = a.ending && a.ending.kind === 'natural' && t >= a.ending.musicEnds - 0.1, ring = a.button && t > a.button.at + 0.25; jumps.push({ at: r3(t), db: r3(d), atJoin: nearJoin, original: ring || (!nearJoin && (inEnding || !(a.button && t >= a.button.at - 0.1))) }); } }
|
|
507
|
+
return { joins, jumps: jumps.filter((j) => !j.original) };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// ---------- the table ----------
|
|
511
|
+
|
|
512
|
+
const mmss = (t) => `${t.toFixed(2)}`;
|
|
513
|
+
export function arrangeLines(an, plan, measured = null) {
|
|
514
|
+
const a = plan.arrange, map = an.map;
|
|
515
|
+
if (!a) return plan.arrangeNote ? [`arrange straight cut from ${plan.start.toFixed(2)}s${plan.looped ? ', looped on bar lines' : ''} — ${plan.arrangeNote}`] : [];
|
|
516
|
+
const out = [`arrange ${a.strategy}, ${a.endingKind === 'natural' ? "the track's own ending" : a.endingKind === 'button' ? 'a button ending (a home-chord hit that rings out)' : 'a fade (no usable ending)'} · ${a.joins.length} join${a.joins.length === 1 ? '' : 's'} · mean gap to the film's energy ${a.meanGap.toFixed(2)}${a.pickup > 0 ? ` · music starts ${Math.round(a.pickup * 1000)} ms into the track` : ''}`];
|
|
517
|
+
let k = 0;
|
|
518
|
+
while (k < a.steps.length) {
|
|
519
|
+
let e = k; while (e + 1 < a.steps.length && a.steps[e + 1].bar === a.steps[e].bar + 1) e++;
|
|
520
|
+
const t0 = a.steps[k].film, t1 = e + 1 < a.steps.length ? a.steps[e + 1].film : plan.duration;
|
|
521
|
+
const b0 = map.bars[a.steps[k].bar], b1 = map.bars[a.steps[e].bar], from = k === 0 ? a.pickup : b0.start;
|
|
522
|
+
const role = k === 0 ? 'opening' : e === a.steps.length - 1 && a.endingKind !== 'fade' ? (a.endingKind === 'button' ? 'hit' : 'ending') : 'middle';
|
|
523
|
+
out.push(` film ${mmss(t0)}–${mmss(Math.min(t1, plan.duration))} ← track ${mmss(from)}–${mmss(b1.end)} bars ${a.steps[k].bar}${e > k ? `–${a.steps[e].bar}` : ''} ${role} ${[...new Set(a.steps.slice(k, e + 1).map((q) => q.label))].join('/')} energy ${a.steps.slice(k, e + 1).map((q) => q.e.toFixed(2)).join(' ')} (film wants ${a.steps.slice(k, e + 1).map((q) => q.target.toFixed(2)).join(' ')})`);
|
|
524
|
+
k = e + 1;
|
|
525
|
+
}
|
|
526
|
+
a.joins.forEach((j, i) => {
|
|
527
|
+
const m = measured?.joins?.[i];
|
|
528
|
+
out.push(` join ${mmss(j.at)} ${j.kind === 'beat3' ? `beat 4 of bar ${j.from} → beat 4 of bar ${j.to - 1}` : `bar ${j.from}→${j.to}`} ${j.chords} smooth ${j.score.toFixed(2)} ${j.score >= GOOD_JOIN ? 'good' : j.score >= OK_JOIN ? 'ok' : 'rough — may be audible'} loudness ${m ? `${m.before.toFixed(1)}→${m.after.toFixed(1)} dB (${m.diff >= 0 ? '+' : ''}${m.diff.toFixed(1)}, measured over 1 s each side)` : `${j.dLoud >= 0 ? '+' : ''}${j.dLoud.toFixed(1)} dB`}${Math.abs(j.gain) >= 0.05 ? `, ${j.gain >= 0 ? '+' : ''}${j.gain.toFixed(1)} dB static gain on what follows` : ''} ${j.phrase ? 'phrase to phrase' : 'mid-phrase'}${j.posMatch ? ', same place in the progression' : ''}`);
|
|
529
|
+
});
|
|
530
|
+
const en = a.ending;
|
|
531
|
+
out.push(en.kind === 'natural' ? ` end the track's own ending: its last ${en.bars} bars (${(en.musicEnds - en.fromFilm).toFixed(1)} s, ${en.type}, ${en.decaySec.toFixed(1)} s of decay) play on to the end of the music at film ${mmss(en.musicEnds)}s${Math.abs(en.slack) > 0.05 ? ` (${en.slack > 0 ? `${en.slack.toFixed(2)} s of silence before the last frame` : `${(-en.slack).toFixed(2)} s clipped from its decay`})` : ''}${en.landing != null ? ` · strongest accent in the tail (${en.chord}${en.tonic ? ', home chord' : ''}) at film ${mmss(en.landing)}s${en.finalChord != null && Math.abs(en.finalChord - en.landing) > 0.05 ? `; the final chord (${en.finalChordName}) starts at film ${mmss(en.finalChord)}s` : ''}: land the end card on whichever you want` : ''}`
|
|
532
|
+
: en.kind === 'button' ? ` end button (synthetic: the ring is made, not the track's): a ${en.chord}${en.tonic ? ' (home chord)' : ''} hit at film ${mmss(en.landing)}s rings out in a reverb tail of ${a.button.tail.toFixed(1)} s to the last frame: land the end card at ${mmss(en.landing)}s`
|
|
533
|
+
: ` end no usable ending (${en.why}; no button hit fits either): the last bar rings from ${mmss(en.fadeFrom)}s into a fade`);
|
|
534
|
+
if (a.duck) out.push(` stop ${mmss(a.duck.from)}–${mmss(a.duck.to)}s ducked ${a.duck.db} dB on whole beats (declared)`);
|
|
535
|
+
for (const e of a.events) out.push(` ${e.name.padEnd(5)} ${mmss(e.t)}s ${Math.abs(e.offMs) <= GRID_SLACK * 1000 ? 'is on a bar line' : `is ${Math.abs(e.offMs)} ms ${e.offMs > 0 ? 'after' : 'before'} the nearest bar line`}${e.lift ? `; ${e.lift.how === 'on' ? 'a real lift of the track lands on it' : `a real lift of the track lands ${e.lift.how} (${mmss(e.lift.at)}s)`} (step ${e.lift.step.toFixed(2)})` : ''}`);
|
|
536
|
+
for (const t of a.suggest) out.push(` hint ${t}`);
|
|
537
|
+
const alt = a.alternatives.filter((x) => x.strategy !== a.strategy || x.ending !== a.endingKind).slice(0, 3);
|
|
538
|
+
if (alt.length) out.push(` also tried: ${alt.map((x) => `${x.strategy} + ${x.ending} (score ${x.score.toFixed(2)}, ${x.joins} join${x.joins === 1 ? '' : 's'})`).join(' · ')}`);
|
|
539
|
+
const sg = a.suggestion;
|
|
540
|
+
if (sg?.adjusted) {
|
|
541
|
+
const d = (v) => `${v.duration} s${v.moved.burst != null ? `, burst ${v.moved.burst}` : ''}${v.moved.peak != null ? `, peak ${v.moved.peak}` : ''}${v.moved.landing != null ? `, landing ${v.moved.landing}` : ''}`;
|
|
542
|
+
out.push(` film as written: ${plan.duration} s score ${sg.asIs.score.toFixed(2)} ${sg.asIs.joins} join${sg.asIs.joins === 1 ? '' : 's'}, ${sg.asIs.endingKind === 'natural' ? `the track's own ending (${sg.asIs.endingSeconds.toFixed(1)} s)` : sg.asIs.endingKind}`);
|
|
543
|
+
out.push(` film adjusted: ${d(sg.adjusted)} score ${sg.adjusted.score.toFixed(2)} ${sg.adjusted.joins} join${sg.adjusted.joins === 1 ? '' : 's'}, ${sg.adjusted.endingKind === 'natural' ? `the track's own ending (${sg.adjusted.endingSeconds.toFixed(1)} s)` : sg.adjusted.endingKind}`);
|
|
544
|
+
out.push(sg.recommend ? ` hint recommended: the adjusted film buys ${sg.gain.join(', ')}` : ' hint the adjusted film scores about the same: keep the film as written');
|
|
545
|
+
}
|
|
546
|
+
const fd = a.fitDurations?.[0];
|
|
547
|
+
if (fd && Math.abs(fd.seconds - plan.duration) > 0.05 && Math.abs(fd.seconds - plan.duration) <= a.barLen) out.push(` hint a film of ${fd.seconds.toFixed(1)} s needs one join only (first ${fd.openingBars} bars, then the ending from bar ${fd.endingFrom}${fd.lifts.length ? `; its lifts at ${fd.lifts.join(', ')} s` : ''}): ${plan.duration > fd.seconds ? 'cut' : 'extend'} the film by ${Math.abs(fd.seconds - plan.duration).toFixed(1)} s and the music needs no re-cut`);
|
|
548
|
+
for (const j of measured?.jumps || []) out.push(`warning loudness jumps ${j.db > 0 ? '+' : ''}${j.db.toFixed(1)} dB between the 0.5 s around film ${mmss(j.at)}s${j.atJoin ? ' (a join)' : ''} — not something the track does itself`);
|
|
549
|
+
for (const n of a.notes) out.push(`warning ${n}`);
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// A stretch (OM.music({ stretch: bpm })): the ratio to play the track at, or null with the reason.
|
|
554
|
+
export function stretchRatio(trackBpm, want) {
|
|
555
|
+
if (!(want > 0)) return { ratio: 1, note: null };
|
|
556
|
+
const r = want / trackBpm;
|
|
557
|
+
if (Math.abs(r - 1) > STRETCH_MAX + 1e-9) return { ratio: 1, note: `stretch ${want} bpm would bend the ${trackBpm.toFixed(2)} bpm track by ${((r - 1) * 100).toFixed(1)} % (the limit is ${STRETCH_MAX * 100} %): ignored` };
|
|
558
|
+
return { ratio: r, note: null };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// An analysis played at `ratio` times the speed: every time in it divides by ratio.
|
|
562
|
+
export function scaleAnalysis(an, ratio) {
|
|
563
|
+
if (ratio === 1) return an;
|
|
564
|
+
const t = (x) => r3(x / ratio), a = (xs) => xs.map(t);
|
|
565
|
+
const out = { ...an, bpm: Math.round(an.bpm * ratio * 100) / 100, beats: a(an.beats), downbeats: a(an.downbeats), end: t(an.end), duration: t(an.duration), sections: an.sections.map((s) => ({ ...s, start: t(s.start), end: t(s.end) })), drops: an.drops.map((d) => ({ ...d, t: t(d.t) })) };
|
|
566
|
+
if (an.map) out.map = { ...an.map, bars: an.map.bars.map((b) => ({ ...b, start: t(b.start), end: t(b.end) })), segments: an.map.segments.map((s) => ({ ...s, start: t(s.start), end: t(s.end) })) };
|
|
567
|
+
return out;
|
|
568
|
+
}
|
|
569
|
+
export { OmError };
|
|
570
|
+
export const _debug = { optionsOf, protectedBars, segIndex, phraseStarts };
|