Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: auto-arrange music-video scenes across song sections by energy (#1915)

[._.]/ Adam Eivy5990fe003b2b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3513cc821d..50f5ed0f88 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,8 @@
- **[issue-1854] Beat-quantized timeline arranger: drag-snap scenes to the beat grid.** The director board's scene list now sits above an interactive **beat-grid timeline** (built from the project's cached audio analysis) showing section bands, beats, and downbeats. Drag a scene's left/right edge to trim its in/out point — or drag its body to reposition it — and it snaps to the nearest beat, downbeat, or section boundary within a small tolerance; an unsnapped drop is left exactly where you placed it. Confirmed (snapped) scenes are marked **beat-aligned** and now render *exactly* as arranged: the render's beat-snap step (`beatSnapClips`) honors a beat-aligned scene's saved `startSec`/`endSec` outright instead of re-deriving the cut from whichever beats happen to be nearby at render time. Auto-arranging scenes across the song's sections by energy is filed as a follow-up (#1915). (Closes #1854)
+- **[issue-1915] Auto-arrange scenes across song sections by energy.** A one-click **Auto-arrange** button on the Music Video scene board distributes every scene across the analyzed song's sections weighted by each section's energy — louder sections get more (shorter) cuts, calmer sections get fewer (longer) ones — and writes the same persisted `startSec`/`endSec`/`beatAligned` fields the manual drag-snap arranger (#1854) writes, so the result is a director-tunable starting point honored exactly at render time. The offline audio analysis now records a normalized 0..1 `energy` per section (additive/optional — older cached analyses fall back to an even spread; re-run **Analyze** to populate it). The distribution is a pure, isolated helper — `autoArrangeScenes(scenes, audioAnalysis)` in `client/src/lib/beatGrid.js` (largest-remainder allocation by energy weight, interior cuts snapped to the beat grid) — unit-tested independently of the UI. (Closes #1915)
+
## Security
- **`safeUrlFetch` SSRF guard now pins the vetted IP at connect time, closing a DNS-rebinding TOCTOU** — `isPublicHttpUrlSafe` resolved a hostname's DNS to validate it was public, but the subsequent `fetch` re-resolved the same hostname at connect time, so a rebinding host could answer a public address for the check and a loopback/link-local/cloud-metadata address for the actual connection, slipping past the guard. The guard now resolves once and the connection is pinned to that exact validated address via a per-request undici `Agent` whose `connect.lookup` always returns the vetted IP — while Host header and TLS SNI stay the original hostname, so cert validation is unaffected. Every redirect hop is still independently re-validated and re-pinned. (Low real-world exploitability — PortOS is single-user on a private network and URL sources are user-pasted Pinterest boards / stored feeds — but the connect-time re-resolution is now eliminated.) (#1859)
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 7bf0b4b3bb..91deda005c 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -35,7 +35,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |
| `universeRunTag.js` | `buildUniverseSectionRenderTag(universe, kindKey, entry)` — the durable `universeRun` job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to `generateImage` so the server auto-files the render into the universe collection AND appends it to the entry's `imageRefs[]` (no client follow-up PATCH). |
| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. |
-| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback. Used by `components/musicVideo/BeatTimeline.jsx`. |
+| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |
| `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. |
| `catalogTypes.js` | Client mirror of `server/lib/catalogTypes.js` — catalog ingredient type registry (label, badge color, primary-content key/label, snippet fallback chain, per-type editor field list) for the Catalog list/picker/editor. |
| `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |
diff --git a/client/src/lib/beatGrid.js b/client/src/lib/beatGrid.js
index 730503dcb2..9f4427767b 100644
--- a/client/src/lib/beatGrid.js
+++ b/client/src/lib/beatGrid.js
@@ -77,3 +77,124 @@ export function computeSceneSpans(scenes, durationSec) {
return { sceneId: scene.sceneId, startSec, endSec, persisted: false };
});
}
+
+const DEFAULT_MIN_SCENE_SEC = 0.5;
+const round3 = (n) => Number(n.toFixed(3));
+
+// Allocate `total` whole items across `weights` (non-negative) using the
+// largest-remainder method, so the per-bucket counts sum to EXACTLY `total`
+// and a heavier weight gets proportionally more. All-zero weights fall back to
+// an even split. Returns an integer array the same length as `weights`.
+function allocateByWeight(weights, total) {
+ const positive = weights.map((w) => (typeof w === 'number' && w > 0 ? w : 0));
+ const sum = positive.reduce((a, b) => a + b, 0);
+ // No usable weight signal → split evenly across the buckets.
+ const eff = sum > 0 ? positive : weights.map(() => 1);
+ const effSum = sum > 0 ? sum : weights.length;
+ const raw = eff.map((w) => (w / effSum) * total);
+ const counts = raw.map((r) => Math.floor(r));
+ let remaining = total - counts.reduce((a, b) => a + b, 0);
+ // Hand out the leftover units to the buckets with the largest fractional part.
+ const byFrac = raw
+ .map((r, i) => ({ i, frac: r - Math.floor(r) }))
+ .sort((a, b) => b.frac - a.frac);
+ for (let k = 0; remaining > 0 && k < byFrac.length; k++) {
+ counts[byFrac[k].i] += 1;
+ remaining -= 1;
+ }
+ return counts;
+}
+
+// Split one section's [startSec, endSec] span into `count` contiguous cut
+// boundaries (length `count + 1`). Interior cuts snap to the nearest grid point
+// when one keeps the run monotonic AND leaves both adjacent spans at least
+// `minSceneSec` long; otherwise the raw even-division time is kept. The
+// section's own outer edges are never moved (they're already section grid lines).
+function sectionCutBoundaries(startSec, endSec, count, gridPoints, minSceneSec) {
+ const boundaries = [startSec];
+ for (let k = 1; k < count; k++) {
+ const raw = startSec + ((endSec - startSec) * k) / count;
+ const snap = snapTimeToGrid(raw, gridPoints, Infinity);
+ let b = snap ? snap.t : raw;
+ const prev = boundaries[boundaries.length - 1];
+ if (b < prev + minSceneSec || b > endSec - minSceneSec) b = raw;
+ if (b < prev) b = prev; // keep strictly non-decreasing on a tiny section
+ boundaries.push(b);
+ }
+ boundaries.push(endSec);
+ return boundaries;
+}
+
+// Auto-arrange a project's scenes across the analyzed song sections, weighted by
+// each section's energy (#1915). Higher-energy sections receive MORE scenes
+// (hence shorter, snappier cuts); lower-energy sections receive fewer, longer
+// ones. Within each section the allotted scenes tile its time span contiguously,
+// with interior cuts snapped to the beat grid. Returns a proposed arrangement —
+// `[{ sceneId, startSec, endSec, beatAligned }]` in scene order — written with
+// the SAME persisted fields the manual drag-snap arranger (#1854) writes, so the
+// result is a director-tunable starting point honored exactly at render time by
+// the server's `beatSnapClips`.
+//
+// Pure + side-effect-free, so it's unit-tested in isolation before the UI button.
+// Edge cases return a sensible no-op:
+// - no scenes → []
+// - no usable `sections` AND no `durationSec` → [] (nothing to arrange against)
+// - no `sections` but a `durationSec` → treat the whole track as one section
+// - missing per-section `energy` (older analyses) → equal weights (even spread)
+export function autoArrangeScenes(scenes, audioAnalysis, { minSceneSec = DEFAULT_MIN_SCENE_SEC } = {}) {
+ const ordered = (Array.isArray(scenes) ? scenes : [])
+ .filter((s) => s && typeof s.sceneId === 'string')
+ .slice()
+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
+ if (ordered.length === 0) return [];
+
+ const durationSec = typeof audioAnalysis?.durationSec === 'number' && audioAnalysis.durationSec > 0
+ ? audioAnalysis.durationSec
+ : null;
+
+ let sections = (Array.isArray(audioAnalysis?.sections) ? audioAnalysis.sections : [])
+ .filter((s) => typeof s?.startSec === 'number' && typeof s?.endSec === 'number' && s.endSec > s.startSec)
+ .map((s) => ({
+ startSec: s.startSec,
+ endSec: s.endSec,
+ energy: typeof s.energy === 'number' && s.energy > 0 ? s.energy : null,
+ }));
+
+ if (sections.length === 0) {
+ if (!durationSec) return [];
+ sections = [{ startSec: 0, endSec: durationSec, energy: null }];
+ }
+
+ // Energy is the cut-density weight. When no section carries energy (legacy
+ // analyses, or the single synthetic fallback section), weigh every section
+ // equally so scenes still spread across the whole track.
+ const haveEnergy = sections.some((s) => s.energy != null);
+ const weights = sections.map((s) => (haveEnergy ? (s.energy ?? 0) : 1));
+ const counts = allocateByWeight(weights, ordered.length);
+
+ const gridPoints = buildBeatGridPoints(audioAnalysis);
+ // A grid (beats/downbeats/section edges) means the cuts are genuinely
+ // beat-aligned; mark every produced span aligned so the render honors these
+ // computed durations exactly (the director can then drag to fine-tune). With
+ // no grid at all the spans are still intentional, but not beat-locked.
+ const beatAligned = gridPoints.length > 0;
+
+ const result = [];
+ let sceneIdx = 0;
+ for (let si = 0; si < sections.length; si++) {
+ const count = counts[si];
+ if (count <= 0) continue;
+ const boundaries = sectionCutBoundaries(sections[si].startSec, sections[si].endSec, count, gridPoints, minSceneSec);
+ for (let k = 0; k < count; k++) {
+ const scene = ordered[sceneIdx];
+ sceneIdx += 1;
+ result.push({
+ sceneId: scene.sceneId,
+ startSec: round3(boundaries[k]),
+ endSec: round3(boundaries[k + 1]),
+ beatAligned,
+ });
+ }
+ }
+ return result;
+}
diff --git a/client/src/lib/beatGrid.test.js b/client/src/lib/beatGrid.test.js
index 6fdcef5a98..9d8381a22c 100644
--- a/client/src/lib/beatGrid.test.js
+++ b/client/src/lib/beatGrid.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { buildBeatGridPoints, snapTimeToGrid, computeSceneSpans } from './beatGrid.js';
+import { buildBeatGridPoints, snapTimeToGrid, computeSceneSpans, autoArrangeScenes } from './beatGrid.js';
describe('buildBeatGridPoints', () => {
it('returns an empty list with no analysis', () => {
@@ -94,3 +94,113 @@ describe('computeSceneSpans', () => {
expect(spans[0]).toEqual({ sceneId: 's1', startSec: 0, endSec: 3, persisted: false });
});
});
+
+describe('autoArrangeScenes', () => {
+ const scenes = (n) => Array.from({ length: n }, (_, i) => ({ sceneId: `s${i + 1}`, order: i }));
+
+ it('returns an empty arrangement with no scenes', () => {
+ expect(autoArrangeScenes([], { sections: [{ startSec: 0, endSec: 10 }], durationSec: 10 })).toEqual([]);
+ expect(autoArrangeScenes(null, null)).toEqual([]);
+ });
+
+ it('returns [] when there is nothing to arrange against (no sections, no duration)', () => {
+ expect(autoArrangeScenes(scenes(3), { sections: [] })).toEqual([]);
+ expect(autoArrangeScenes(scenes(3), null)).toEqual([]);
+ });
+
+ it('covers a single section contiguously, in scene order, with no gaps', () => {
+ const out = autoArrangeScenes(scenes(3), { sections: [{ startSec: 0, endSec: 9, energy: 1 }], durationSec: 9 });
+ expect(out.map((a) => a.sceneId)).toEqual(['s1', 's2', 's3']);
+ expect(out[0].startSec).toBe(0);
+ expect(out[out.length - 1].endSec).toBe(9);
+ for (let i = 1; i < out.length; i++) expect(out[i].startSec).toBeCloseTo(out[i - 1].endSec, 3);
+ });
+
+ it('falls back to a single track-spanning section when sections are absent', () => {
+ const out = autoArrangeScenes(scenes(2), { durationSec: 8 });
+ expect(out).toHaveLength(2);
+ expect(out[0].startSec).toBe(0);
+ expect(out[1].endSec).toBe(8);
+ });
+
+ it('gives the higher-energy section more (shorter) cuts than the lower-energy one', () => {
+ const analysis = {
+ durationSec: 20,
+ sections: [
+ { startSec: 0, endSec: 10, energy: 0.2 }, // calm
+ { startSec: 10, endSec: 20, energy: 1.0 }, // loud
+ ],
+ };
+ const out = autoArrangeScenes(scenes(6), analysis);
+ const loud = out.filter((a) => a.startSec >= 10);
+ const calm = out.filter((a) => a.endSec <= 10);
+ expect(loud.length).toBeGreaterThan(calm.length);
+ // Loud-section cuts are on average shorter than calm-section cuts.
+ const avg = (arr) => arr.reduce((s, a) => s + (a.endSec - a.startSec), 0) / arr.length;
+ expect(avg(loud)).toBeLessThan(avg(calm));
+ });
+
+ it('spreads scenes evenly when no section carries energy (legacy analysis)', () => {
+ const analysis = {
+ durationSec: 20,
+ sections: [
+ { startSec: 0, endSec: 10 },
+ { startSec: 10, endSec: 20 },
+ ],
+ };
+ const out = autoArrangeScenes(scenes(4), analysis);
+ expect(out.filter((a) => a.endSec <= 10)).toHaveLength(2);
+ expect(out.filter((a) => a.startSec >= 10)).toHaveLength(2);
+ });
+
+ it('assigns exactly one span per scene even with more sections than scenes', () => {
+ const analysis = {
+ durationSec: 30,
+ sections: [
+ { startSec: 0, endSec: 10, energy: 1 },
+ { startSec: 10, endSec: 20, energy: 0.1 },
+ { startSec: 20, endSec: 30, energy: 0.1 },
+ ],
+ };
+ const out = autoArrangeScenes(scenes(2), analysis);
+ expect(out).toHaveLength(2);
+ expect(new Set(out.map((a) => a.sceneId)).size).toBe(2);
+ });
+
+ it('snaps interior cuts to the beat grid and marks them beatAligned', () => {
+ const analysis = {
+ durationSec: 8,
+ beats: [0, 2, 4, 6, 8],
+ sections: [{ startSec: 0, endSec: 8, energy: 1 }],
+ };
+ const out = autoArrangeScenes(scenes(2), analysis);
+ expect(out.every((a) => a.beatAligned)).toBe(true);
+ // The single interior cut (raw 4.0) lands on the beat at 4.
+ expect(out[0].endSec).toBe(4);
+ expect(out[1].startSec).toBe(4);
+ });
+
+ it('marks spans not beatAligned when there is no grid at all', () => {
+ const out = autoArrangeScenes(scenes(2), { durationSec: 6 });
+ expect(out.every((a) => a.beatAligned === false)).toBe(true);
+ });
+
+ it('keeps every span at least minSceneSec long rather than snapping them away', () => {
+ const analysis = {
+ durationSec: 6,
+ beats: [0, 0.1, 5.9, 6], // a beat clings to each section edge
+ sections: [{ startSec: 0, endSec: 6, energy: 1 }],
+ };
+ const out = autoArrangeScenes(scenes(2), analysis, { minSceneSec: 1 });
+ for (const a of out) expect(a.endSec - a.startSec).toBeGreaterThanOrEqual(1);
+ });
+
+ it('orders the arrangement by scene order, not input order', () => {
+ const unordered = [
+ { sceneId: 's2', order: 1 },
+ { sceneId: 's1', order: 0 },
+ ];
+ const out = autoArrangeScenes(unordered, { sections: [{ startSec: 0, endSec: 4, energy: 1 }], durationSec: 4 });
+ expect(out.map((a) => a.sceneId)).toEqual(['s1', 's2']);
+ });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index ccc0ff74fe..2c04b9a6e1 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -1,5 +1,5 @@
import { useEffect, useState, useCallback } from 'react';
-import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video } from 'lucide-react';
+import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Wand2 } from 'lucide-react';
import toast from '../components/ui/Toast';
import PageHeader from '../components/PageHeader';
import {
@@ -19,6 +19,7 @@ import { generateImage } from '../services/apiSystem.js';
import { generateVideo } from '../services/apiImageVideo.js';
import { listTracks } from '../services/apiTracks.js';
import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';
+import { autoArrangeScenes } from '../lib/beatGrid.js';
import useSceneRenderLifecycle from '../hooks/useSceneRenderLifecycle.js';
import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress.js';
import { formatDurationSec } from '../utils/formatters.js';
@@ -43,6 +44,7 @@ export default function MusicVideo() {
const [selectedId, setSelectedId] = useState(null);
const [loading, setLoading] = useState(true);
const [analyzing, setAnalyzing] = useState(false);
+ const [arranging, setArranging] = useState(false);
const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });
const selected = projects.find((p) => p.id === selectedId) || null;
const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));
@@ -127,6 +129,45 @@ export default function MusicVideo() {
.finally(() => setAnalyzing(false));
};
+ // Auto-arrange (#1915): distribute every scene across the analyzed song
+ // sections weighted by each section's energy, writing the same persisted
+ // startSec/endSec/beatAligned fields the manual drag-snap arranger (#1854)
+ // writes — a director-tunable starting point honored exactly at render time.
+ // Optimistically applies the whole arrangement to the local board, then
+ // persists each scene sequentially (the per-project load-modify-save can't
+ // drop a write that way). Silent PATCHes — the catch owns the only error toast.
+ const handleAutoArrange = () => {
+ if (!selected?.audioAnalysis) return;
+ const scenes = selected.scenes || [];
+ const arrangement = autoArrangeScenes(scenes, selected.audioAnalysis);
+ if (arrangement.length === 0) {
+ toast.error('Nothing to arrange — analyze the track and add scenes first');
+ return;
+ }
+ const byId = new Map(arrangement.map((a) => [a.sceneId, a]));
+ replaceProject({
+ ...selected,
+ scenes: scenes.map((s) => {
+ const a = byId.get(s.sceneId);
+ return a ? { ...s, startSec: a.startSec, endSec: a.endSec, beatAligned: a.beatAligned } : s;
+ }),
+ });
+ setArranging(true);
+ (async () => {
+ for (const a of arrangement) {
+ // Sequential by design — see the comment above (avoids a load-modify-save race).
+ await updateMusicVideoScene(
+ selected.id, a.sceneId,
+ { startSec: a.startSec, endSec: a.endSec, beatAligned: a.beatAligned },
+ { silent: true },
+ );
+ }
+ })()
+ .then(() => toast.success(`Auto-arranged ${arrangement.length} scene${arrangement.length === 1 ? '' : 's'} by energy`))
+ .catch((err) => toast.error(err?.message || 'Auto-arrange failed'))
+ .finally(() => setArranging(false));
+ };
+
// --- Render (#1760, Phase 2): assemble scene clips over the master audio bed.
// The kickoff returns a jobId; progress streams over SSE via useSseProgress.
const [render, setRender] = useState(null); // { jobId, projectId } while in flight
@@ -369,6 +410,16 @@ export default function MusicVideo() {
className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">
<Activity size={15} /> {analyzing ? 'Analyzing…' : 'Analyze'}
</button>
+ <button onClick={handleAutoArrange}
+ disabled={arranging || !selected.audioAnalysis || (selected.scenes || []).length === 0}
+ title={!selected.audioAnalysis
+ ? 'Analyze the track first'
+ : (selected.scenes || []).length === 0
+ ? 'Add scenes first'
+ : 'Distribute scenes across song sections by energy'}
+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">
+ <Wand2 size={15} /> {arranging ? 'Arranging…' : 'Auto-arrange'}
+ </button>
{render ? (
<button onClick={handleCancelRender} title="Cancel render"
className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index b69e1352f5..433e0dd102 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -95,6 +95,9 @@ export const musicVideoAudioAnalysisSchema = z.object({
label: z.string(),
startSec: z.number(),
endSec: z.number(),
+ // Normalized 0..1 section loudness used by the energy-weighted auto-arranger
+ // (#1915). Additive + optional so older cached analyses still validate.
+ energy: z.number().min(0).optional(),
})),
durationSec: z.number(),
}).strict();
diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.js
index 0c06a4ee97..fa84fedc92 100644
--- a/server/services/musicVideo/audioAnalysis.js
+++ b/server/services/musicVideo/audioAnalysis.js
@@ -300,7 +300,8 @@ function pickDownbeats(beats, onset, fps) {
*/
function segmentSections(energy, fps, durationSec) {
if (durationSec <= 0) return [];
- const single = [{ label: 'Section 1', startSec: 0, endSec: Number(durationSec.toFixed(3)) }];
+ // A lone section carries the full (normalized) energy by definition.
+ const single = [{ label: 'Section 1', startSec: 0, endSec: Number(durationSec.toFixed(3)), energy: 1 }];
if (durationSec < MIN_SECTION_SEC * 2) return single;
const winFrames = Math.max(1, Math.round(SECTION_WINDOW_SEC * fps));
@@ -343,12 +344,32 @@ function segmentSections(energy, fps, durationSec) {
const cutTimes = boundaries.map((w) => (w * winFrames) / fps);
const edges = [0, ...cutTimes, durationSec];
+
+ // Per-section loudness: the mean windowed energy over each section's span,
+ // normalized to the loudest section (0..1). This drives the energy-weighted
+ // auto-arranger (#1915) — louder sections earn more, shorter scene cuts. It is
+ // an ADDITIVE field on the section shape; older cached analyses simply omit it
+ // and the arranger falls back to an even spread.
+ const winSec = winFrames / fps;
+ const sectionMeans = [];
+ for (let i = 0; i < edges.length - 1; i++) {
+ let sum = 0;
+ let n = 0;
+ for (let w = 0; w < winCount; w++) {
+ const tw = w * winSec; // window start time
+ if (tw >= edges[i] && tw < edges[i + 1]) { sum += profile[w]; n += 1; }
+ }
+ sectionMeans.push(n > 0 ? sum / n : 0);
+ }
+ const maxMean = Math.max(0, ...sectionMeans);
+
const sections = [];
for (let i = 0; i < edges.length - 1; i++) {
sections.push({
label: `Section ${i + 1}`,
startSec: Number(edges[i].toFixed(3)),
endSec: Number(edges[i + 1].toFixed(3)),
+ energy: maxMean > 0 ? Number((sectionMeans[i] / maxMean).toFixed(3)) : 1,
});
}
return sections;
@@ -362,7 +383,7 @@ function segmentSections(energy, fps, durationSec) {
* @param {number} sampleRate
* @param {{ hop?: number }} [opts]
* @returns {{ bpm: number|null, beats: number[], downbeats: number[],
- * sections: Array<{label:string,startSec:number,endSec:number}>,
+ * sections: Array<{label:string,startSec:number,endSec:number,energy:number}>,
* durationSec: number }}
*/
export function analyzePcm(samples, sampleRate, { hop = ONSET_HOP } = {}) {
diff --git a/server/services/musicVideo/audioAnalysis.test.js b/server/services/musicVideo/audioAnalysis.test.js
index 65612c42e2..eb16da5018 100644
--- a/server/services/musicVideo/audioAnalysis.test.js
+++ b/server/services/musicVideo/audioAnalysis.test.js
@@ -141,6 +141,32 @@ describe('analyzePcm', () => {
expect(sections[i].startSec).toBeCloseTo(sections[i - 1].endSec, 3);
expect(sections[i].label).toBeTruthy();
}
+ // Every section carries a normalized 0..1 energy (#1915), and the loudest is 1.
+ for (const s of sections) {
+ expect(typeof s.energy).toBe('number');
+ expect(s.energy).toBeGreaterThan(0);
+ expect(s.energy).toBeLessThanOrEqual(1);
+ }
+ expect(Math.max(...sections.map((s) => s.energy))).toBe(1);
+ });
+
+ it('assigns higher energy to a louder section than a quiet one (#1915)', () => {
+ // A quiet first half and a loud second half: the energy jump forces a
+ // section boundary, and the loud section must read a higher energy.
+ const samples = clickTrack({ bpm: 120, durationSec: 40 });
+ const half = Math.round(samples.length / 2);
+ for (let i = 0; i < half; i++) samples[i] *= 0.15;
+ const { sections } = analyzePcm(samples, ANALYSIS_SAMPLE_RATE);
+ expect(sections.length).toBeGreaterThanOrEqual(2);
+ const quiet = sections[0];
+ const loud = sections[sections.length - 1];
+ expect(loud.energy).toBeGreaterThan(quiet.energy);
+ });
+
+ it('reports energy 1 for the single fallback section of a short track', () => {
+ const { sections } = analyzePcm(clickTrack({ bpm: 120, durationSec: 4 }), ANALYSIS_SAMPLE_RATE);
+ expect(sections).toHaveLength(1);
+ expect(sections[0].energy).toBe(1);
});
it('reports no tempo and one section for a sustained pure tone', () => {