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: add consistent opt-in Music Video render grades (#9302)

[._.]/ Adam Eivy7288ae2dbbcb
diff --git a/client/src/components/musicVideo/GradePanel.jsx b/client/src/components/musicVideo/GradePanel.jsx
new file mode 100644
index 0000000000..c818e047c3
--- /dev/null
+++ b/client/src/components/musicVideo/GradePanel.jsx
@@ -0,0 +1,56 @@
+import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_DEFAULT_GRAIN } from '../../lib/musicVideoGrade.js';
+import { compositionDraft } from './compositionDraft.js';
+
+const LABELS = { neutral: 'Neutral (no effect)', 'teal-night': 'Teal night', 'golden-hour': 'Golden hour', monochrome: 'Monochrome' };
+const inputCls = 'min-h-[44px] w-full rounded border border-port-border bg-port-bg px-2 py-1 text-sm';
+const options = MUSIC_VIDEO_GRADE_PRESETS.map((preset) => <option key={preset} value={preset}>{LABELS[preset]}</option>);
+
+/** Explicit render-time looks; no provider calls or changes to generated assets. */
+export default function GradePanel({ project, onSave }) {
+ const composition = compositionDraft(project);
+ if (!['composed', 'document'].includes(composition.mode)) return null;
+ const grade = composition.grade || { preset: 'neutral', grain: MUSIC_VIDEO_GRADE_DEFAULT_GRAIN, sections: [] };
+ const save = (patch) => {
+ const update = { composition: { ...composition, grade: { ...grade, ...patch } } };
+ onSave(update);
+ };
+ const setSection = (sceneId, preset) => save({ sections: [
+ ...(grade.sections || []).filter((section) => section.sceneId !== sceneId),
+ ...(preset ? [{ sceneId, preset }] : []),
+ ] });
+ return (
+ <section aria-label="Render grade" className="space-y-2 border-t border-port-border pt-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h3 className="text-sm font-medium">Render grade</h3>
+ <button type="button" className="min-h-[44px] text-xs text-port-accent"
+ onClick={() => save({ preset: 'neutral', sections: [] })}>Reset grades to neutral</button>
+ </div>
+ <p className="text-xs text-port-text-muted">Opt-in color curves and repeatable grain on composed and document exports. Source footage stays unchanged. Render an excerpt to review the grade; the live document preview is ungraded.</p>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
+ <div>
+ <label htmlFor="mv-grade-preset" className="text-xs text-port-text-muted">Default section look</label>
+ <select id="mv-grade-preset" className={inputCls} value={grade.preset || 'neutral'} onChange={(event) => save({ preset: event.target.value })}>{options}</select>
+ </div>
+ <div>
+ <label htmlFor="mv-grade-grain" className="text-xs text-port-text-muted">Grain</label>
+ <select id="mv-grade-grain" className={inputCls} value={grade.grain ?? MUSIC_VIDEO_GRADE_DEFAULT_GRAIN} onChange={(event) => save({ grain: Number(event.target.value) })}>
+ <option value={0}>None</option><option value={MUSIC_VIDEO_GRADE_DEFAULT_GRAIN}>Fine</option><option value={0.03}>Strong</option>
+ {grade.grain != null && ![0, MUSIC_VIDEO_GRADE_DEFAULT_GRAIN, 0.03].includes(grade.grain) && <option value={grade.grain}>Custom</option>}
+ </select>
+ </div>
+ </div>
+ <div className="max-h-60 space-y-2 overflow-y-auto">
+ {(project.scenes || []).map((scene) => (
+ <div key={scene.sceneId}>
+ <label htmlFor={`mv-grade-${scene.sceneId}`} className="text-xs text-port-text-muted">{scene.label || scene.sectionLabel || 'Untitled section'}</label>
+ <select id={`mv-grade-${scene.sceneId}`} className={inputCls}
+ value={(grade.sections || []).find((section) => section.sceneId === scene.sceneId)?.preset ?? ''}
+ onChange={(event) => setSection(scene.sceneId, event.target.value)}>
+ <option value="">Default section look</option>{options}
+ </select>
+ </div>
+ ))}
+ </div>
+ </section>
+ );
+}
diff --git a/client/src/components/musicVideo/GradePanel.test.jsx b/client/src/components/musicVideo/GradePanel.test.jsx
new file mode 100644
index 0000000000..2f5090bd55
--- /dev/null
+++ b/client/src/components/musicVideo/GradePanel.test.jsx
@@ -0,0 +1,26 @@
+import { useState } from 'react';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import GradePanel from './GradePanel.jsx';
+
+describe('composition grade controls', () => {
+ it('persists explicit presets and section overrides, then resets every section without changing other composition settings', () => {
+ const onSave = vi.fn();
+ const initial = { id: 'mv-example', scenes: [{ sceneId: 'verse', label: 'Verse' }], composition: { mode: 'document', posterSec: 3 } };
+ function Editor() {
+ const [project, setProject] = useState(initial);
+ return <GradePanel project={project} onSave={(patch) => { onSave(patch); setProject((current) => ({ ...current, ...patch })); }} />;
+ }
+ render(<Editor />);
+ expect(screen.getByLabelText('Default section look').value).toBe('neutral');
+ expect(onSave).not.toHaveBeenCalled();
+ fireEvent.change(screen.getByLabelText('Default section look'), { target: { value: 'teal-night' } });
+ fireEvent.change(screen.getByLabelText('Verse'), { target: { value: 'golden-hour' } });
+ expect(onSave).toHaveBeenLastCalledWith({ composition: expect.objectContaining({ mode: 'document', posterSec: 3,
+ grade: { preset: 'teal-night', grain: 0.012, sections: [{ sceneId: 'verse', preset: 'golden-hour' }] },
+ }) });
+ fireEvent.click(screen.getByRole('button', { name: 'Reset grades to neutral' }));
+ expect(screen.getByLabelText('Verse').value).toBe('');
+ expect(onSave).toHaveBeenLastCalledWith({ composition: expect.objectContaining({ grade: { preset: 'neutral', grain: 0.012, sections: [] } }) });
+ });
+});
diff --git a/client/src/components/musicVideo/stages/ComposeStage.jsx b/client/src/components/musicVideo/stages/ComposeStage.jsx
index 7ea6e9f01e..9a1edbaedc 100644
--- a/client/src/components/musicVideo/stages/ComposeStage.jsx
+++ b/client/src/components/musicVideo/stages/ComposeStage.jsx
@@ -1,3 +1,4 @@
+import GradePanel from '../GradePanel.jsx';
import TypographyPanel from '../TypographyPanel.jsx';
import CodeVideoPanel from '../CodeVideoPanel.jsx';
import DocumentCompositionPanel from '../DocumentCompositionPanel.jsx';
@@ -18,6 +19,7 @@ export default function ComposeStage({ board }) {
<span className="text-xs text-port-text-muted" aria-hidden="true">Render style</span>
<RenderStyleSelect project={project} onRenderStyle={board.onRenderStyle} />
</div>
+ <GradePanel project={project} onSave={board.saveCompositionGrade} />
<TypographyPanel project={project} onEditLocal={board.editProjectLocal} onSave={board.saveProjectFields} />
{mode === 'code' && (
<CodeVideoPanel project={project} audioUrl={audioUrl} onProject={board.replaceProject} />
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 0ff212fc38..8e6ac9f4c1 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -299,3 +299,5 @@ grep -i "what you want to do" client/src/lib/README.md
| `layoutRoutes.js` | `isFullWidthRoute(pathname)` classifies routes that own their scrolling layout. |
| `navPresentation.js` | Sidebar icon presentation and section ordering, separate from the Layout React refresh boundary. |
+
+| `musicVideoGrade.js` | Shared Music Video grade preset and grain bounds for the composition controls. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index ac7b1975df..71f4b35efa 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -259,3 +259,5 @@ export * from './navPresentation.js';
export * from './squarifyTreemap.js';
export * from './styleSourceChoice.js';
export * from './trackProvenance.js';
+
+export * from './musicVideoGrade.js';
diff --git a/client/src/lib/musicVideoGrade.js b/client/src/lib/musicVideoGrade.js
new file mode 100644
index 0000000000..b5dbaa546d
--- /dev/null
+++ b/client/src/lib/musicVideoGrade.js
@@ -0,0 +1,5 @@
+export {
+ MUSIC_VIDEO_GRADE_PRESETS,
+ MUSIC_VIDEO_GRADE_DEFAULT_GRAIN,
+ MUSIC_VIDEO_GRADE_MAX_GRAIN,
+} from '../../../server/lib/musicVideoGrade.js';
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 71e4cd12f0..e0dd55fe74 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -120,6 +120,7 @@ export default function MusicVideo() {
const [arranging, setArranging] = useState(false);
const [creativeSetupPending, setCreativeSetupPending] = useState(false);
const [styleReferencesPending, setStyleReferencesPending] = useState(false);
+ const [compositionSavePending, setCompositionSavePending] = useState(0);
useEffect(() => { setStyleReferencesPending(false); }, [selectedId]);
const [planning, setPlanning] = useState(false);
const [cloning, setCloning] = useState(false);
@@ -519,11 +520,17 @@ export default function MusicVideo() {
// older snapshot of the list overwrite a newer one.
const timedTextSaveChain = useRef(Promise.resolve());
const editProjectLocal = (patch) => patchProject(selected.id, patch);
- const saveProjectFields = (patch) => {
+ const saveProjectFields = (patch, { applyComposition = false } = {}) => {
const projectId = selected.id;
+ setCompositionSavePending((count) => count + 1);
timedTextSaveChain.current = timedTextSaveChain.current
.then(() => updateMusicVideoProject(projectId, patch, { silent: true }))
- .catch((err) => toast.error(err?.message || 'Failed to save changes'));
+ .then((saved) => {
+ if (applyComposition) patchProject(projectId, { composition: saved.composition });
+ })
+ .catch((err) => toast.error(err?.message || 'Failed to save changes'))
+ .finally(() => setCompositionSavePending((count) => count - 1));
+ return timedTextSaveChain.current;
};
const handleImportLyrics = (body, onDone) => {
const projectId = selected.id;
@@ -743,7 +750,7 @@ export default function MusicVideo() {
analyzing,
}) : null;
const runNextAction = () => {
- if (!selected || !nextAction || nextAction.disabled) return;
+ if (!selected || !nextAction || nextAction.disabled || compositionSavePending > 0) return;
if (nextAction.kind === 'goto') { goToStage(nextAction.stage, nextAction.anchor); return; }
switch (nextAction.id) {
case 'kickoff': handleKickoff(); break;
@@ -762,7 +769,7 @@ export default function MusicVideo() {
// use, so a panel moving between tabs never changes a signature here.
const board = selected ? {
project: selected,
- locked: creativeSetupPending || styleReferencesPending,
+ locked: creativeSetupPending || styleReferencesPending || compositionSavePending > 0,
busy: { analyzing, planning, arranging, cloning },
tracks,
trackName,
@@ -798,6 +805,7 @@ export default function MusicVideo() {
replaceProject,
editProjectLocal,
saveProjectFields,
+ saveCompositionGrade: (patch) => saveProjectFields(patch, { applyComposition: true }),
saveVisualSpec,
saveAutomation,
saveCreativeSetup: (patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {
@@ -988,7 +996,7 @@ export default function MusicVideo() {
stage={activeStage}
onStageChange={(stage) => goToStage(stage)}
progress={progress}
- nextAction={nextAction}
+ nextAction={compositionSavePending > 0 && nextAction ? { ...nextAction, disabled: true, reason: 'Saving composition…' } : nextAction}
onNextAction={runNextAction}
spend={projectSpend(selected)}
dock={resolvePreviewSource(selected) ? (
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 9971937742..041c99745f 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -2188,3 +2188,28 @@ describe('MusicVideo stage tabs (#9243)', () => {
});
});
});
+
+it('waits for a grade save before rendering and keeps the saved look when a later save fails', async () => {
+ const project = { ...PROJECT_WITH_CLIP, composition: { mode: 'composed', textCues: [], style: { color: '#ffffff', font: 'sans' } } };
+ let finishSave;
+ updateMusicVideoProject.mockImplementationOnce((_id, patch) => new Promise((resolve) => {
+ finishSave = () => resolve({ ...project, ...patch });
+ }));
+ await openProject(project, 'compose');
+ fireEvent.change(screen.getByLabelText('Default section look'), { target: { value: 'teal-night' } });
+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith(project.id,
+ { composition: expect.objectContaining({ grade: expect.objectContaining({ preset: 'teal-night' }) }) }, { silent: true }));
+ expect(screen.getByLabelText('Default section look')).toBeDisabled();
+ expect(screen.getByLabelText('Default section look').value).toBe('neutral');
+ await openStage('review');
+ expect(screen.getByRole('button', { name: /^Render final$/ })).toBeDisabled();
+ expect(renderMusicVideoProject).not.toHaveBeenCalled();
+ await act(async () => { finishSave(); });
+ expect(screen.getByRole('button', { name: /^Render final$/ })).not.toBeDisabled();
+ await openStage('compose');
+ expect(screen.getByLabelText('Default section look').value).toBe('teal-night');
+ updateMusicVideoProject.mockRejectedValueOnce(new Error('Grade save unavailable'));
+ fireEvent.change(screen.getByLabelText('Default section look'), { target: { value: 'golden-hour' } });
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Grade save unavailable'));
+ expect(screen.getByLabelText('Default section look').value).toBe('teal-night');
+});
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
index fc1f8ac96f..7d2b0f6be2 100644
--- a/docs/HTML_COMPOSITIONS.md
+++ b/docs/HTML_COMPOSITIONS.md
@@ -228,6 +228,28 @@ project's video backend has a source-audio lip-sync lane (fal.ai today).
The treatment's proof checklist treats readable text and audio alignment as
judgeable only in the final render.
+## Music-video render grades
+
+In **Compose → Render grade**, explicitly choose Neutral, Teal night, Golden
+hour, or Monochrome, with an optional per-section override and bounded grain.
+The selection is stored in `composition.grade`; clones remap section overrides
+to their new scene IDs. Neutral is the default and a true filter bypass. A
+neutral section override disables the default look for that section; resetting
+to neutral clears every override. Grades affect composed and document exports,
+not plain footage or code-rendered mode. The live document preview is ungraded;
+render an excerpt to judge the selected look.
+
+Both encoders use the same bounded RGB curves and deterministic, song-time
+frame-addressed grain. Composed footage is graded before typography, and
+excerpt trimming happens after grading. Document captures receive the same
+filter before encoding, with the excerpt offset and document frame rate, so
+section changes and grain stay on the song clock. Black/white endpoints are
+preserved to keep document lettering readable. Source assets are unchanged;
+selecting a grade does not infer a look from references or invoke a provider.
+Saving the selection gates rendering until the server has accepted it.
+
+See the [synthetic visual validation and remaining acceptance](validation/9302-music-video-grade.md).
+
## Music-video composition documents
A Music Video project can own its whole edit as a composition document: set
diff --git a/docs/README.md b/docs/README.md
index c00c3aae89..6df650b1c6 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -64,6 +64,8 @@ Comms & voice: [beeper](./features/beeper.md) · [openclaw-operator-chat](./feat
## Point-in-time records
+- [Music Video render-grade validation](validation/9302-music-video-grade.md) — synthetic encoder parity, visual references, and remaining generated-shot acceptance.
+
- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs. See [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md) for stable executable routes, migration and management flows.
- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md), [Privacy Center storage](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md), [Eidoverse guest chat](./decisions/2026-09-05-eidoverse-guest-chat.md), [numeric PortOS quality federation](./decisions/2026-09-10-portos-quality-federation.md), [federated Eidoverse foundations](./decisions/2026-09-18-federated-eidoverse-foundations.md)), why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md), and why closed-set decisions run on a [local entailment model that abstains](./decisions/2026-09-18-local-jev-decision-service.md).
- **research/** — investigation tools and incident write-ups (e.g. the [H3 scene-continuity comparison](./research/minimax-h3-continuity.md), [H3 vision precision investigation](./research/minimax-h3-vision-precision.md), [mflux GPU-watchdog panic](./research/2026-06-13-mflux-training-watchdog-panic.md) and [local LLM performance audit](./research/2026-08-22-local-llm-performance-audit.md)).
diff --git a/docs/validation/9302-music-video-grade.md b/docs/validation/9302-music-video-grade.md
new file mode 100644
index 0000000000..e3dc529298
--- /dev/null
+++ b/docs/validation/9302-music-video-grade.md
@@ -0,0 +1,57 @@
+# Music Video render-grade validation
+
+Issue: #9302. Synthetic visual review performed 2026-10-01.
+
+## Reproduce
+
+With Chrome and FFmpeg available, run:
+
+```sh
+PORTOS_GRADE_PROOF_DIR="$(mktemp -d)" npm test --prefix server -- --run services/musicVideo/documentRender.browser.test.js -t 'matches bounded grades'
+```
+
+The fixture creates RGB and grey ramps, encodes a lossless source clip, and
+renders three timed looks through both the composed-footage graph and the real
+sandboxed Chrome document capture: teal night, golden hour, monochrome. The
+1280×720 document explicitly uses 12 fps, exercising a document rate different
+from the 24 fps planning default. Every image and record is synthetic.
+
+## Visual observations
+
+Reference:
+
+![Ungraded synthetic color and grey ramps](assets/9302/reference.png)
+
+Composed output, left to right: teal night, golden hour, monochrome:
+
+![Composed graded ramp frames](assets/9302/composed.png)
+
+Document output at the same song times:
+
+![Document graded ramp frames](assets/9302/document.png)
+
+The grey ramp moves toward cool shadows in teal night and warm midtones in
+golden hour; the monochrome section removes chroma. The same color bands stay
+in the same palette across the two output paths. Fine grain is visible without
+clipping black and white endpoints. Composed typography is downstream of the
+grade; document text is captured before the grade, whose curves and tapered
+grain preserve black and white for contrast. This is a controlled review of
+actual encoded synthetic imagery, not a claim based only on filter strings.
+
+Measured mean absolute RGB error (0–255 channel units): composed versus document
+**1.47**; the document excerpt versus corresponding full-render frames **1.01**.
+The 0.5–1.5 second excerpt crosses the look change at song second 1. Both
+composed and document excerpts are bounded below 2 units of error against their
+full renders. A repeated document excerpt decodes byte-for-byte identically,
+including grain. Tolerances account for RGB/YUV conversion and independent H.264
+prediction; encoded lossy frames are not claimed to be byte-identical between
+architectures. The test also checks endpoint protection and monochrome chroma.
+
+## Remaining acceptance
+
+The reference sheet above does **not** establish palette/grain consistency on a
+representative set of independently AI-generated shots, skin tones, and practical
+lighting. That part of #9302 remains open: use an explicitly approved synthetic
+or redistributable generated-shot set with reference images, render the selected
+presets in both modes, and record a controlled side-by-side visual judgment.
+No live project images were accessed and no generation-provider calls were made.
diff --git a/docs/validation/assets/9302/composed.png b/docs/validation/assets/9302/composed.png
new file mode 100644
index 0000000000..f5aec1fc6f
Binary files /dev/null and b/docs/validation/assets/9302/composed.png differ
diff --git a/docs/validation/assets/9302/document.png b/docs/validation/assets/9302/document.png
new file mode 100644
index 0000000000..fd9be7c63e
Binary files /dev/null and b/docs/validation/assets/9302/document.png differ
diff --git a/docs/validation/assets/9302/reference.png b/docs/validation/assets/9302/reference.png
new file mode 100644
index 0000000000..6606ce6b52
Binary files /dev/null and b/docs/validation/assets/9302/reference.png differ
diff --git a/server/lib/README.md b/server/lib/README.md
index 6433f35c5c..39dd29a122 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -811,3 +811,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `musicVideoActionContract.js` | Versioned shot intent shape/timing validation and clip-relative frame/motion prompt compilation, shared by treatment and the board. |
| `sheetPointers.js` | Browser-safe persisted character-sheet layout: `LEGACY_SHEET_VARIANT_ID`, `readSheetPointer`, `listSheetPointers`, identity-preserving `applySheetPointerToCharacter`, and default-variant browser adapter `applySheetPointer`. |
+| `musicVideoGrade.js` | Opt-in Music Video grade presets, bounded normalization, and shared song-timed RGB curves with deterministic grain for composed and document encodes. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 044bb5ca31..8401af69b9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -795,3 +795,4 @@ export * from './musicVideoMediumPlan.js';
export * from './imageLimits.js';
export * from './musicVideoActionContract.js';
+export * from './musicVideoGrade.js';
diff --git a/server/lib/musicVideoGrade.js b/server/lib/musicVideoGrade.js
new file mode 100644
index 0000000000..c442609050
--- /dev/null
+++ b/server/lib/musicVideoGrade.js
@@ -0,0 +1,65 @@
+/** LUT-free, opt-in Music Video grades shared by footage and document encoders. */
+export const MUSIC_VIDEO_GRADE_PRESETS = ['neutral', 'teal-night', 'golden-hour', 'monochrome'];
+export const MUSIC_VIDEO_GRADE_MAX_GRAIN = 0.03;
+export const MUSIC_VIDEO_GRADE_DEFAULT_GRAIN = 0.012;
+
+export function normalizeMusicVideoGrade(input) {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
+ const preset = (value) => MUSIC_VIDEO_GRADE_PRESETS.includes(value) ? value : 'neutral';
+ const seen = new Set();
+ const sections = (Array.isArray(input.sections) ? input.sections : []).filter((section) => {
+ if (typeof section?.sceneId !== 'string' || !section.sceneId || section.sceneId.length > 120 || seen.has(section.sceneId)) return false;
+ seen.add(section.sceneId);
+ return true;
+ }).slice(0, 1000).map((section) => ({ sceneId: section.sceneId, preset: preset(section.preset) }));
+ return {
+ preset: preset(input.preset),
+ grain: Number.isFinite(input.grain) ? Math.max(0, Math.min(MUSIC_VIDEO_GRADE_MAX_GRAIN, input.grain)) : MUSIC_VIDEO_GRADE_DEFAULT_GRAIN,
+ sections,
+ };
+}
+
+// Curves preserve black and white. Maximum channel displacement stays below 8% and
+// grain tapers to zero at both endpoints, so document text remains readable.
+const CURVES = {
+ 'teal-night': [-0.22, 0.05, 0.2],
+ 'golden-hour': [0.22, 0.07, -0.18],
+ monochrome: [0, 0, 0],
+};
+
+/**
+ * One shared RGB filter chain. Sections are half-open SONG-time intervals.
+ * Frame-addressed grain never uses RNG state, so an excerpt, a second render,
+ * and different ffmpeg thread counts produce the same grain at the same time.
+ * No selected effect means no colorspace round trip, preserving legacy output.
+ */
+export function musicVideoGradeFilter(grade, sections, { fps = 24, offsetSec = 0 } = {}) {
+ const settings = normalizeMusicVideoGrade(grade);
+ if (!settings) return null;
+ const overrides = new Map(settings.sections.map((section) => [section.sceneId, section.preset]));
+ const windows = new Map();
+ for (const section of sections || []) {
+ const preset = overrides.get(section.sceneId) ?? settings.preset;
+ if (preset === 'neutral' || !Number.isFinite(section.startSec) || !Number.isFinite(section.endSec) || section.endSec <= section.startSec) continue;
+ const start = Math.max(0, section.startSec - offsetSec);
+ const end = section.endSec - offsetSec;
+ if (end <= start) continue;
+ const ranges = windows.get(preset) || [];
+ ranges.push(`gte(t,${start})*lt(t,${end})`);
+ windows.set(preset, ranges);
+ }
+ if (!windows.size) return null;
+ const frame = `floor((T+${offsetSec})*${fps}+0.5)`;
+ // Integer modular hash: portable, cheap, spatially and temporally repeatable.
+ const noise = `(mod(pow(mod(X*73+Y*151+(${frame})*199,4093),2)*157,4093)/4093-0.5)`;
+ const filters = ['format=gbrp'];
+ for (const [preset, ranges] of windows) {
+ const channels = ['r', 'g', 'b'].map((channel, i) => {
+ const value = preset === 'monochrome' ? '(0.2126*r(X,Y)+0.7152*g(X,Y)+0.0722*b(X,Y))/255' : `${channel}(X,Y)/255`;
+ const curve = CURVES[preset][i];
+ return `${channel}='st(0,${value});255*clip(ld(0)+${curve}*ld(0)*(1-ld(0))+0.16*ld(0)*(1-ld(0))*(2*ld(0)-1)+${settings.grain}*${noise}*4*ld(0)*(1-ld(0)),0,1)'`;
+ });
+ filters.push(`geq=${channels.join(':')}:enable='${ranges.join('+')}'`);
+ }
+ return filters.join(',');
+}
diff --git a/server/lib/musicVideoGrade.test.js b/server/lib/musicVideoGrade.test.js
new file mode 100644
index 0000000000..2f18783641
--- /dev/null
+++ b/server/lib/musicVideoGrade.test.js
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+import { musicVideoCompositionSchema } from './musicVideoValidation.js';
+import { normalizeComposition } from '../services/musicVideo/composition.js';
+import { musicVideoGradeFilter } from './musicVideoGrade.js';
+
+// Serialization/validation boundary: no unbounded filter values from peers or PATCH.
+describe('Music Video grade contract', () => {
+ it('keeps legacy and explicit neutral manifests a true bypass and rejects invalid settings', () => {
+ const sections = [{ sceneId: 'a', startSec: 0, endSec: 2 }];
+ expect(normalizeComposition({ mode: 'composed' })).not.toHaveProperty('grade');
+ expect(musicVideoGradeFilter(null, sections)).toBeNull();
+ expect(musicVideoGradeFilter({ preset: 'neutral' }, sections)).toBeNull();
+ for (const grade of [{ preset: 'injected-filter' }, { grain: 0.031 }, { grain: -1 }, { grain: Infinity }]) {
+ expect(musicVideoCompositionSchema.safeParse({ grade }).success).toBe(false);
+ }
+ expect(normalizeComposition({ grade: { preset: 'unknown', grain: 100 } }).grade).toEqual({ preset: 'neutral', grain: 0.03, sections: [] });
+ expect(musicVideoCompositionSchema.parse({ grade: { preset: 'teal-night', grain: 0.02 } }).grade.preset).toBe('teal-night');
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index b4576626c4..dfa4eb445c 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1,3 +1,4 @@
+import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVideoGrade.js';
/**
* Music Video production mode — Zod schemas + shared enums (issue #1760, Phase 1).
*
@@ -363,6 +364,14 @@ export const musicVideoCompositionSchema = z.object({
version: z.literal(1).optional(),
mode: z.enum(MUSIC_VIDEO_COMPOSITION_MODES).optional(),
cutting: z.enum(MUSIC_VIDEO_CUTTING_MODES).optional(),
+ grade: z.object({
+ preset: z.enum(MUSIC_VIDEO_GRADE_PRESETS).optional(),
+ grain: z.number().min(0).max(MUSIC_VIDEO_GRADE_MAX_GRAIN).optional(),
+ sections: z.array(z.object({
+ sceneId: z.string().min(1).max(120),
+ preset: z.enum(MUSIC_VIDEO_GRADE_PRESETS),
+ }).strict()).max(1000).optional(),
+ }).strict().nullable().optional(),
textCues: z.array(musicVideoTextCueSchema).max(1000).optional(),
style: z.object({
color: z.string().regex(/^#[0-9a-f]{6}$/i, 'color is #rrggbb').optional(),
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
index 5d2de43213..3abb0c3f7e 100644
--- a/server/services/htmlComposition/encode.js
+++ b/server/services/htmlComposition/encode.js
@@ -37,7 +37,7 @@ const SCREENSHOT = Object.freeze({ format: 'png', optimizeForSpeed: true, fromSu
// the terminal race releases a pending write on exit, disconnect or cancel.
// `offsetSec` seeks a window of a longer timeline: frame n is drawn at
// `offsetSec + n / fps` (a music-video excerpt stays on song time).
-export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress, offsetSec = 0, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {
+export async function encodeComposition(page, contract, outputPath, { musicPath, audio, signal, onProgress, offsetSec = 0, videoFilter = null, spawnProcess = spawn, locateFfmpeg = findFfmpeg, tagFilter = bt709TagFilter } = {}) {
const ffmpeg = await locateFfmpeg();
if (!ffmpeg) throw new Error('ffmpeg not found on PATH');
const tag = await tagFilter();
@@ -62,7 +62,7 @@ export async function encodeComposition(page, contract, outputPath, { musicPath,
const args = ['-hide_banner', '-loglevel', 'error', ...input, '-framerate', String(fps * sub), '-i', 'pipe:0'];
if (exactAudio) args.push('-ss', String(exactAudio.startSec ?? 0), '-t', String(durationSec), '-i', exactAudio.path);
else if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);
- args.push('-map', '0:v', '-vf', [motionBlurFilter, 'scale=in_range=pc:out_range=tv:out_color_matrix=bt709', tag].filter(Boolean).join(','), ...H264_ENCODE_ARGS, ...BT709_CONTAINER_ARGS);
+ args.push('-map', '0:v', '-vf', [motionBlurFilter, videoFilter, 'scale=in_range=pc:out_range=tv:out_color_matrix=bt709', tag].filter(Boolean).join(','), ...H264_ENCODE_ARGS, ...BT709_CONTAINER_ARGS);
if (exactAudio) args.push('-map', '1:a', ...AAC_ENCODE_ARGS);
else if (musicPath) args.push('-map', '1:a', '-af', `atrim=duration=${durationSec},asetpts=PTS-STARTPTS,afade=t=out:st=${durationSec - 0.5}:d=0.5`, ...AAC_ENCODE_ARGS);
args.push('-frames:v', String(numFrames), '-t', String(durationSec), '-movflags', '+faststart', '-y', outputPath);
diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.js
index 1cfd5a366e..e3be8b5531 100644
--- a/server/services/musicVideo/composition.js
+++ b/server/services/musicVideo/composition.js
@@ -1,3 +1,4 @@
+import { normalizeMusicVideoGrade } from '../../lib/musicVideoGrade.js';
/**
* Music Video — composition manifest + deterministic typography (#8984, part of #8966).
*
@@ -145,6 +146,7 @@ export function normalizeComposition(input) {
const documentRef = normalizeCompositionDocument(input.document);
const documentDraft = normalizeCompositionDocument(input.documentDraft);
const overlay = normalizeCompositionOverlay(input.overlay);
+ const grade = normalizeMusicVideoGrade(input.grade);
return {
version: COMPOSITION_VERSION,
mode: pick(input.mode, COMPOSITION_MODES, 'concat'),
@@ -155,6 +157,7 @@ export function normalizeComposition(input) {
...(typeof style.accentColor === 'string' && /^#[0-9a-f]{6}$/i.test(style.accentColor) ? { accentColor: style.accentColor.toLowerCase() } : {}),
},
posterSec: toTime(input.posterSec),
+ ...(grade ? { grade } : {}),
// Absent until chosen (#9290): the autopilot plan picks 'intercut' for an undecided project.
...(CUTTING_MODES.includes(input.cutting) ? { cutting: input.cutting } : {}),
// Absent unless a code video was actually stored, so a composed manifest
diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.js
index d553e29fbe..a3bc8c73b4 100644
--- a/server/services/musicVideo/documentRender.browser.test.js
+++ b/server/services/musicVideo/documentRender.browser.test.js
@@ -7,10 +7,11 @@
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { existsSync } from 'node:fs';
-import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { execFileSync, spawn } from 'node:child_process';
import { chromium } from 'playwright-core';
+import sharp from 'sharp';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
const author = vi.hoisted(() => ({ calls: 0, response: null }));
@@ -33,6 +34,7 @@ vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await imp
const { PATHS } = await import('../../lib/paths.js');
const { findFfmpeg } = await import('../../lib/ffmpeg.js');
+const { buildMusicVideoFfmpegArgs } = await import('./render.js');
const { encodeDocumentComposition, prepareDocumentRender } = await import('./documentRender.js');
const { importDocumentTemplate } = await import('./compositionDocument.js');
const { generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument } = await import('./documentGeneration.js');
@@ -118,6 +120,86 @@ describe.skipIf(!chrome || !ffmpeg)('layered template with real Chrome and ffmpe
await rm(second.outputPath, { force: true });
}, 120000);
+ it('matches bounded grades across real composed/document ramps and song-time excerpts', async () => {
+ // Synthetic reference: horizontal RGB/grey ramps plus hard black/white
+ // endpoints. No install data, provider calls, or network images.
+ const width = 1280;
+ const height = 720;
+ const fps = 12;
+ const bytes = Buffer.alloc(width * height * 3);
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
+ const v = Math.round(255 * x / (width - 1));
+ const band = Math.floor(y / 180);
+ const rgb = band === 0 ? [v, v, v] : band === 1 ? [v, 72, 104] : band === 2 ? [104, v, 72] : [72, 104, v];
+ bytes.set(rgb, (y * width + x) * 3);
+ }
+ const directory = 'music-video/mv-grade/composition/doc-grade';
+ const dir = join(PATHS.data, directory);
+ await mkdir(dir, { recursive: true });
+ await mkdir(PATHS.music, { recursive: true });
+ await mkdir(PATHS.videos, { recursive: true });
+ const reference = join(dir, 'reference.png');
+ await sharp(bytes, { raw: { width, height, channels: 3 } }).png().toFile(reference);
+ await writeFile(join(dir, 'index.html'), `<!doctype html><style>html,body{margin:0}img{width:${width}px;height:${height}px;display:block}</style>
+ <img id="reference" src="reference.png"><script>window.portosComposition={durationSec:2,fps:${fps},width:${width},height:${height},seek:async()=>{await document.getElementById('reference').decode()}};</script>`);
+ const master = join(PATHS.music, 'grade.wav');
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=2', master]);
+ const source = join(PATHS.videos, 'grade-source.mkv');
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-loop', '1', '-i', reference, '-t', '1', '-r', String(fps), '-c:v', 'ffv1', '-pix_fmt', 'yuv420p', source]);
+ const scenes = [{ sceneId: 'a', startSec: 0, endSec: 1 }, { sceneId: 'b', startSec: 1, endSec: 1.5 }, { sceneId: 'c', startSec: 1.5, endSec: 2 }];
+ const grade = { preset: 'teal-night', grain: 0.03, sections: [{ sceneId: 'b', preset: 'golden-hour' }, { sceneId: 'c', preset: 'monochrome' }] };
+ const project = { id: 'mv-grade', name: 'Synthetic grade reference', scenes,
+ audioAnalysis: { durationSec: 2, sections: [] }, composition: { mode: 'document', grade, document: { directory } } };
+ const plan = await prepareDocumentRender(project);
+ const document = join(PATHS.videos, 'grade-document.mp4');
+ await encodeDocumentComposition({ project, plan, jobId: 'grade-document', audioPath: master, outputPath: document });
+ const clips = scenes.map((scene) => ({ sceneId: scene.sceneId, videoPath: source, inSec: 0, outSec: scene.endSec - scene.startSec, width, height, fps }));
+ const composed = join(PATHS.videos, 'grade-composed.mp4');
+ const composedArgs = buildMusicVideoFfmpegArgs(clips, master, composed, { grade, frameGrid: true }).args;
+ execFileSync(ffmpeg, ['-v', 'error', ...composedArgs], { stdio: 'pipe' });
+ const decode = (path, filters = []) => execFileSync(ffmpeg, ['-v', 'error', '-i', path, ...filters, '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: 1 << 28 });
+ const frameSize = width * height * 3;
+ const documentRgb = decode(document);
+ const composedRgb = decode(composed);
+ expect(documentRgb.length).toBe(frameSize * fps * 2);
+ expect(composedRgb.length).toBe(documentRgb.length);
+ const mae = (a, b) => a.reduce((sum, v, i) => sum + Math.abs(v - b[i]), 0) / a.length;
+ // Browser RGB and video YUV420 differ by conversion/subsampling and H.264
+ // quantization; palette parity is bounded rather than falsely byte-exact.
+ expect(mae(documentRgb, composedRgb)).toBeLessThan(5);
+ const excerpt = join(PATHS.videos, 'grade-excerpt.mp4');
+ await encodeDocumentComposition({ project, plan, jobId: 'grade-excerpt', audioPath: master, outputPath: excerpt, windowStart: 0.5, windowEnd: 1.5 });
+ const excerptRgb = decode(excerpt);
+ expect(mae(excerptRgb, documentRgb.subarray(6 * frameSize, 18 * frameSize))).toBeLessThan(2);
+ const repeat = join(PATHS.videos, 'grade-repeat.mp4');
+ await encodeDocumentComposition({ project, plan, jobId: 'grade-repeat', audioPath: master, outputPath: repeat, windowStart: 0.5, windowEnd: 1.5 });
+ expect(decode(repeat).equals(excerptRgb)).toBe(true);
+ const composedExcerpt = join(PATHS.videos, 'grade-composed-excerpt.mp4');
+ execFileSync(ffmpeg, ['-v', 'error', ...buildMusicVideoFfmpegArgs(clips, master, composedExcerpt, {
+ grade, frameGrid: true, excerpt: { startSec: 0.5, endSec: 1.5 },
+ }).args], { stdio: 'pipe' });
+ expect(mae(decode(composedExcerpt), composedRgb.subarray(6 * frameSize, 18 * frameSize))).toBeLessThan(2);
+ const pixel = (rgb, frame, x, y) => [...rgb.subarray(frame * frameSize + (y * width + x) * 3, frame * frameSize + (y * width + x) * 3 + 3)];
+ const cool = pixel(documentRgb, 6, 640, 90);
+ const warm = pixel(documentRgb, 12, 640, 90);
+ const monochrome = pixel(documentRgb, 20, 640, 270);
+ expect(Math.max(...monochrome) - Math.min(...monochrome)).toBeLessThan(4);
+ expect(cool[2]).toBeGreaterThan(cool[0] + 15);
+ expect(warm[0]).toBeGreaterThan(warm[2] + 15);
+ expect(Math.max(...pixel(documentRgb, 6, 0, 90))).toBeLessThan(5);
+ expect(Math.min(...pixel(documentRgb, 6, width - 1, 90))).toBeGreaterThan(248);
+ // Optional local proof export: only synthetic fixtures, never live records.
+ if (process.env.PORTOS_GRADE_PROOF_DIR) {
+ const proof = process.env.PORTOS_GRADE_PROOF_DIR;
+ await mkdir(proof, { recursive: true });
+ await copyFile(reference, join(proof, 'reference.png'));
+ for (const [label, path] of [['document', document], ['composed', composed], ['excerpt', excerpt]]) {
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-i', path, '-vf', "select='eq(n,6)+eq(n,12)+eq(n,20)',scale=480:270,tile=3x1", '-frames:v', '1', join(proof, `${label}.png`)]);
+ }
+ await writeFile(join(proof, 'metrics.json'), JSON.stringify({ paletteMeanAbsoluteError: mae(documentRgb, composedRgb), excerptMeanAbsoluteError: mae(excerptRgb, documentRgb.subarray(6 * frameSize, 18 * frameSize)), repeatIdentical: true }, null, 2));
+ }
+ }, 120000);
+
it('renders a generated 30-second card/still/clip document with the selected performance in-point', async () => {
await mkdir(PATHS.videos, { recursive: true });
await mkdir(PATHS.images, { recursive: true });
diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.js
index 6cdf852ec5..9e2915924a 100644
--- a/server/services/musicVideo/documentRender.js
+++ b/server/services/musicVideo/documentRender.js
@@ -1,3 +1,4 @@
+import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';
/**
* Music Video — render a project's composition document over the song.
*
@@ -345,6 +346,7 @@ export async function encodeDocumentComposition({
const target = documentTargetFrame({ ...parsed.data, motionBlur: 1 }, project);
const window = documentRenderWindow(target, { windowStart, windowEnd });
await encodeComposition(page, { ...target, durationSec: window.durationSec }, silent, {
+ videoFilter: musicVideoGradeFilter(project.composition?.grade, data.scenes, { fps: target.fps, offsetSec: window.startSec }),
signal, offsetSec: window.startSec, onProgress: (fraction) => onProgress?.(fraction * 0.95),
});
page.check();
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index c4e25f198e..bca29b1ef8 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -414,7 +414,7 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =
};
if (!composition) {
- const { args } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, excerpt: { startSec, endSec: endClamped }, soundBed });
+ const { args } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, excerpt: { startSec, endSec: endClamped }, soundBed, grade: composed ? project.composition?.grade : null });
startEncode(args);
return { jobId, excerptId };
}
@@ -433,7 +433,7 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =
}).then((overlays) => {
signal.throwIfAborted();
job.overlayAbort = null;
- const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, excerpt: { startSec, endSec: endClamped }, soundBed });
+ const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, excerpt: { startSec, endSec: endClamped }, soundBed, grade: composed ? project.composition?.grade : null });
startEncode(layered.args, 0.5);
}).catch(async (err) => {
const canceled = signal.aborted;
diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.js
index 6ff1a619a2..9a06ac0d17 100644
--- a/server/services/musicVideo/projectsFile.test.js
+++ b/server/services/musicVideo/projectsFile.test.js
@@ -212,6 +212,7 @@ describe('projectsFile federation (#1770)', () => {
await file.updateProject(p.id, { composition: {
mode: 'composed',
+ grade: { preset: 'teal-night', grain: 0.012, sections: [{ sceneId: 'chorus', preset: 'golden-hour' }] },
textCues: [
{ text: ' Hook line ', startSec: 1, endSec: 3, template: 'rise', placement: 'center', emphasis: 'hero' },
{ text: 'Tail', startSec: 4, endSec: 2 },
@@ -223,6 +224,7 @@ describe('projectsFile federation (#1770)', () => {
expect(saved.composition).toEqual({
version: 1,
mode: 'composed',
+ grade: { preset: 'teal-night', grain: 0.012, sections: [{ sceneId: 'chorus', preset: 'golden-hour' }] },
textCues: [
{ id: expect.stringMatching(/^mtc-/), text: 'Hook line', startSec: 1, endSec: 3, template: 'rise', placement: 'center', emphasis: 'hero' },
{ id: expect.stringMatching(/^mtc-/), text: 'Tail', startSec: 4, endSec: null, template: 'fade', placement: 'lower', emphasis: 'subtitle' },
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 2eeddddb4c..39203feb43 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -215,6 +215,12 @@ export function cloneProjectRecord(source, {
createdAt: now,
updatedAt: now,
scenes,
+ ...(source.composition?.grade ? { composition: {
+ ...source.composition,
+ grade: { ...source.composition.grade, sections: (source.composition.grade.sections || []).map((section) => ({
+ ...section, sceneId: sceneIdMap.get(section.sceneId) ?? section.sceneId,
+ })) },
+ } } : {}),
// #8980 — the treatment's shot directions and proofs follow the scenes to
// their new ids; proof evidence the clone can't back is dropped.
treatment: source.treatment ? remapTreatmentForClone(source.treatment, sceneIdMap, {
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index a7442ffb58..bd355e3924 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -73,6 +73,7 @@ describe('cloneProjectRecord', () => {
...baseProject(),
status: 'complete',
renderHistoryId: 'final-1',
+ composition: { mode: 'composed', grade: { preset: 'neutral', sections: [{ sceneId: 'scene-old', preset: 'teal-night' }] } },
audioAnalysis: {
bpm: 120, beats: [0], downbeats: [0],
sections: [{ label: 'S', startSec: 0, endSec: 5 }],
@@ -109,6 +110,8 @@ describe('cloneProjectRecord', () => {
videoHistoryId: 'clip-1',
});
expect(clone.scenes[0].sceneId).not.toBe('scene-old');
+ expect(clone.composition.grade.sections).toEqual([{ sceneId: clone.scenes[0].sceneId, preset: 'teal-night' }]);
+ expect(source.composition.grade.sections[0].sceneId).toBe('scene-old');
expect(source.scenes[0].sceneId).toBe('scene-old');
// A pre-#8965 scene's selections become takes on the clone, so the new
// version's candidate list is never missing what it already shows.
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index b52864a41f..4c42032651 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -1,3 +1,4 @@
+import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';
/**
* Music Video — render pipeline (#1760, Phase 2).
*
@@ -419,7 +420,7 @@ function sectionChain(c, input, { canonW, canonH, fps, frames, frameGrid }) {
// overlap the window, clipped to it and re-based to the excerpt's own timeline
// (0 = `startSec`) so a contact sheet built from the excerpt file can sample
// cut boundaries directly. `totalDuration` becomes the excerpt's own length.
-export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [], frameGrid: gridOption = false, excerpt = null, soundBed = null } = {}) {
+export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec = null, overlays = [], frameGrid: gridOption = false, excerpt = null, soundBed = null, grade = null } = {}) {
if (!Array.isArray(clips) || clips.length === 0) throw new Error('buildMusicVideoFfmpegArgs: empty clips');
const frameGrid = gridOption || clips.some((c) => c.layer);
// Stills and cards have no dimensions of their own: the first footage clip
@@ -470,8 +471,10 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
for (const overlay of overlays) inputs.push('-itsoffset', String(overlay.startSec), '-i', overlay.path);
const filters = plan.map(({ c, frames }, i) => `${sectionChain(c, inputOf[i], { canonW, canonH, fps, frames, frameGrid })}[v${i}]`);
+ const gradeFilter = musicVideoGradeFilter(grade, plan.map(({ c, startSec, endSec }) => ({ sceneId: c.sceneId, startSec, endSec })), { fps });
const cutLabel = overlays.length > 0 ? 'cut0' : 'outv';
- filters.push(`${plan.map((_, i) => `[v${i}]`).join('')}concat=n=${plan.length}:v=1:a=0[${cutLabel}]`);
+ filters.push(`${plan.map((_, i) => `[v${i}]`).join('')}concat=n=${plan.length}:v=1:a=0[${gradeFilter ? 'ungraded' : cutLabel}]`);
+ if (gradeFilter) filters.push(`[ungraded]${gradeFilter}[${cutLabel}]`);
overlays.forEach((_, k) => {
const out = k === overlays.length - 1 ? 'outv' : `cut${k + 1}`;
filters.push(`[cut${k}][${audioIdx + 1 + k}:v]overlay=eof_action=pass:format=auto[${out}]`);
@@ -788,7 +791,7 @@ export async function renderMusicVideo(projectId, options = {}) {
const jobId = randomUUID();
const filename = `music-video-${projectId.slice(0, 8)}-${Date.now()}.mp4`;
const outputPath = join(PATHS.videos, filename);
- const { args, totalDuration, canonW, canonH, fps, sections } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, soundBed });
+ const { args, totalDuration, canonW, canonH, fps, sections } = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, frameGrid: composed, soundBed, grade: composed ? project.composition?.grade : null });
// #8984: a composed project lays its timed text cues over the cut, and a
// title card's text (#8985) joins them over its own section. No renderable
// cue (plain mode, or nothing timed) skips the overlay capture entirely.
@@ -970,7 +973,7 @@ export async function renderMusicVideo(projectId, options = {}) {
signal.throwIfAborted();
// Capture is over: from here a cancel kills the encode (job.process).
job.overlayAbort = null;
- const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, soundBed });
+ const layered = buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioDurationSec, overlays, frameGrid: true, soundBed, grade: project.composition?.grade });
startEncode(layered.args, 0.5);
}).catch(async (err) => {
const canceled = signal.aborted;
diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.js
index 4194fbc406..a15c10e5be 100644
--- a/server/services/musicVideo/render.test.js
+++ b/server/services/musicVideo/render.test.js
@@ -61,6 +61,19 @@ describe('buildMusicVideoFfmpegArgs', () => {
expect(r2.totalDuration).toBe(10); // audio (10) < video (20)
});
+ it('grades the song before typography and excerpt trimming, with neutral output unchanged', () => {
+ const clips = [clip({ sceneId: 'a' })];
+ const plain = buildMusicVideoFfmpegArgs(clips, '/a.wav', '/o.mp4');
+ expect(buildMusicVideoFfmpegArgs(clips, '/a.wav', '/o.mp4', { grade: { preset: 'neutral' } }).args).toEqual(plain.args);
+ const result = buildMusicVideoFfmpegArgs(clips, '/a.wav', '/o.mp4', {
+ grade: { preset: 'teal-night' }, overlays: [{ path: '/overlay.mov', startSec: 0 }], excerpt: { startSec: 1, endSec: 2 },
+ });
+ const graph = result.args[result.args.indexOf('-filter_complex') + 1];
+ expect(graph.indexOf('geq=')).toBeLessThan(graph.indexOf('overlay='));
+ expect(graph.indexOf('overlay=')).toBeLessThan(graph.indexOf('[outv]trim='));
+ expect(graph).toContain("enable='gte(t,0)*lt(t,2)'");
+ });
+
it('throws on empty clips', () => {
expect(() => buildMusicVideoFfmpegArgs([], '/a.wav', '/o.mp4')).toThrow(/empty clips/);
});