8000 feat(editor): conform bar-grid to selected pill's audio onset by johannboehme · Pull Request #36 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions frontend/src/editor/components/SyncTuner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// offset instead of the whole cam — so a single chunk can be tuned without
// disturbing the rest of the take.
import { useEditorStore } from "../store";
import { segmentIndexAtArr } from "../arrangement-time";
import { isVideoClip, MASTER_AUDIO_ID } from "../types";
import { ChunkyButton } from "./ChunkyButton";
import { Knob } from "./Knob";
Expand Down Expand Up @@ -48,6 +49,24 @@ export function SyncTuner({ lastSyncOverrideMs }: Props) {
(s) => s.setPillSourceOffsetMs,
);
const resetPill = useEditorStore((s) => s.resetPill);
const conformAudioStartToPill = useEditorStore(
(s) => s.conformAudioStartToPill,
);
// Subscribe to anything that changes whether CONFORM is meaningful so
// the disabled state stays correct as pills, segments, and the nudge
// shift around.
const pillAudioStartMs = useEditorStore((s) => {
if (!selectedPillId) return null;
const p = s.pills.find((pp) => pp.id === selectedPillId);
if (!p) return null;
const idx = segmentIndexAtArr(p.originalArrStartS, s.arrangementSegments);
if (idx < 0) return null;
return s.arrangementSegments[idx]?.audioStartMs ?? null;
});
const audioStartNudgeS = useEditorStore(
(s) => s.jobMeta?.audioStartNudgeS ?? 0,
);
const bpmPhaseS = useEditorStore((s) => s.jobMeta?.bpm?.phase ?? null);
const abBypass = useEditorStore((s) => s.offset.abBypass);
const setAbBypass = useEditorStore((s) => s.setAbBypass);
// currentTime read imperatively in the loop-around-playhead handler
Expand Down Expand Up @@ -128,6 +147,21 @@ export function SyncTuner({ lastSyncOverrideMs }: Props) {
selectedClip !== null &&
lastSyncOverrideMs !== userOverrideMs;

// CONFORM is meaningful when a pill is selected AND the source segment
// has a detected onset to anchor on. Disabled when the resulting nudge
// would equal the current one — the action is idempotent.
const conformDelta =
pillMode && pillAudioStartMs !== null && bpmPhaseS !== null
? Math.round(
(pillAudioStartMs / 1000 - bpmPhaseS - audioStartNudgeS) * 1e6,
) / 1e3
: null;
const conformEnabled =
pillMode &&
pillAudioStartMs !== null &&
bpmPhaseS !== null &&
Math.abs(conformDelta ?? 0) > 1e-3;

return (
<div className="flex flex-col gap-5">
{/* On narrow phones the title and the A/B segmented control don't
Expand Down Expand Up @@ -266,6 +300,30 @@ export function SyncTuner({ lastSyncOverrideMs }: Props) {
</div>
</div>

{/* Bar-grid conform — re-anchor the master beat phase to this
pill's source onset. Only shown in pill-mode; the action
shifts the global `audioStartNudgeS`, but the trigger is
the selected pill so it lives next to the pill controls. */}
{pillMode && (
<div className="flex flex-col gap-1.5">
<span className="label">Bar Grid</span>
<ChunkyButton
variant="secondary"
size="sm"
=> {
if (selectedPillId) conformAudioStartToPill(selectedPillId);
}}
disabled={!conformEnabled}
>
{pillAudioStartMs === null
? "CONFORM TO PILL · NO ONSET"
: conformDelta !== null && conformEnabled
? `CONFORM TO PILL (${formatMs(conformDelta).trim()})`
: "CONFORM TO PILL"}
</ChunkyButton>
</div>
)}

{/* Resets */}
<div className="grid grid-cols-2 gap-1.5">
<ChunkyButton
Expand Down
181 changes: 181 additions & 0 deletions frontend/src/editor/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,187 @@ describe("useEditorStore", () => {
});
});

describe("conformAudioStartToPill", () => {
// The bar grid anchors at `bpm.phase + audioStartNudgeS` (master-time).
// Conforming to a pill picks that pill's source segment audioStartMs as
// the new anchor — the nudge becomes whatever shifts `bpm.phase` onto
// it. Lets the user re-snap drift between FX/cut grid and a specific
// chunk's onset when many pills accumulated small accumulated offsets
// (e.g. arrangement-mode jobs from triage).
function loadArrangementWithAudioStarts() {
useEditorStore.getState().loadJob(
{
...baseJobMeta,
duration: 180,
bpm: { value: 120, phase: 1.0, manualOverride: false },
},
{
clips: [
{
id: "cam-1",
filename: "a.mp4",
color: "#fff",
sourceDurationS: 200,
syncOffsetMs: 0,
},
],
arrangementSegments: [
{ in: 0, out: 60, audioStartMs: 1500, chunkId: "c0" },
{ in: 60, out: 120, audioStartMs: 60_321, chunkId: "c1" },
],
arrangement: [
{ id: "item-0", chunkId: "c0" },
{ id: "item-1", chunkId: "c1" },
],
chunks: [
{
id: "c0",
startMs: 0,
endMs: 60_000,
audioStartMs: 1500,
bpmOctaveShift: 0,
effectiveBpm: 120,
beatsPerBar: 4,
accepted: true,
trimMode: "free",
},
{
id: "c1",
startMs: 60_000,
endMs: 120_000,
audioStartMs: 60_321,
bpmOctaveShift: 0,
effectiveBpm: 120,
beatsPerBar: 4,
accepted: true,
trimMode: "free",
},
],
},
);
}

test("aligns audioStartNudgeS so beat-phase lands on the pill's segment audioStartMs", () => {
loadArrangementWithAudioStarts();
const pills = useEditorStore.getState().pills;
const pillItem1 = pills.find((p) => p.fromArrangementItemId === "item-1");
expect(pillItem1).toBeTruthy();
const result = useEditorStore
.getState()
.conformAudioStartToPill(pillItem1!.id);
expect(result).toBe("ok");
// segment.audioStartMs = 60321 ms = 60.321 s; bpm.phase = 1.0 s.
// newNudgeS = 60.321 - 1.0 = 59.321
const nudge = useEditorStore.getState().jobMeta?.audioStartNudgeS;
expect(nudge).toBeCloseTo(59.321, 6);
});

test("returns 'unchanged' when nudge already matches the pill's audio-start", () => {
loadArrangementWithAudioStarts();
// First conform sets the nudge; running it again is a no-op.
const pills = useEditorStore.getState().pills;
const pillItem0 = pills.find((p) => p.fromArrangementItemId === "item-0");
expect(pillItem0).toBeTruthy();
expect(
useEditorStore.getState().conformAudioStartToPill(pillItem0!.id),
).toBe("ok");
// segment.audioStartMs = 1500 ms = 1.5 s; bpm.phase = 1.0 s → nudge = 0.5
expect(useEditorStore.getState().jobMeta?.audioStartNudgeS).toBeCloseTo(
0.5,
6,
);
expect(
useEditorStore.getState().conformAudioStartToPill(pillItem0!.id),
).toBe("unchanged");
});

test("returns 'no-pill' for an unknown pill id", () => {
loadArrangementWithAudioStarts();
expect(
useEditorStore.getState().conformAudioStartToPill("does-not-exist"),
).toBe("no-pill");
});

test("returns 'no-bpm' when bpm is not set", () => {
// Same arrangement but no bpm on jobMeta.
useEditorStore.getState().loadJob(
{ ...baseJobMeta, duration: 180 },
{
clips: [
{
id: "cam-1",
filename: "a.mp4",
color: "#fff",
sourceDurationS: 200,
syncOffsetMs: 0,
},
],
arrangementSegments: [
{ in: 0, out: 60, audioStartMs: 1500, chunkId: "c0" },
],
arrangement: [{ id: "item-0", chunkId: "c0" }],
chunks: [
{
id: "c0",
startMs: 0,
endMs: 60_000,
audioStartMs: 1500,
bpmOctaveShift: 0,
effectiveBpm: 0,
beatsPerBar: 4,
accepted: true,
trimMode: "free",
},
],
},
);
const pill = useEditorStore.getState().pills[0];
expect(useEditorStore.getState().conformAudioStartToPill(pill.id)).toBe(
"no-bpm",
);
});

test("returns 'no-audio-start' when the pill's segment has no audioStartMs", () => {
useEditorStore.getState().loadJob(
{
...baseJobMeta,
duration: 60,
bpm: { value: 120, phase: 1.0, manualOverride: false },
},
{
clips: [
{
id: "cam-1",
filename: "a.mp4",
color: "#fff",
sourceDurationS: 200,
syncOffsetMs: 0,
},
],
// Bare single-segment arrangement (no audioStartMs).
arrangementSegments: [{ in: 0, out: 60 }],
arrangement: [{ id: "item-0", chunkId: "c0" }],
chunks: [
{
id: "c0",
startMs: 0,
endMs: 60_000,
bpmOctaveShift: 0,
effectiveBpm: 120,
beatsPerBar: 4,
accepted: true,
trimMode: "free",
},
],
},
);
const pill = useEditorStore.getState().pills[0];
expect(useEditorStore.getState().conformAudioStartToPill(pill.id)).toBe(
"no-audio-start",
);
});
});

describe("setClipViewportTransform / reset", () => {
function loadOneCam() {
useEditorStore.getState().loadJob(baseJobMeta, {
Expand Down
38 changes: 37 additions & 1 deletion frontend/src/editor/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ import {
activeCamAtArr,
reconcilePills,
} from "./arrangement-pills";
import { masterToArr, sliceByArrSegments } from "./arrangement-time";
import {
masterToArr,
segmentIndexAtArr,
sliceByArrSegments,
} from "./arrangement-time";
import type { ArrangementItem, Chunk } from "../storage/jobs-db";
import { classifyAspectRatio } from "./exportPresets";
import { DEFAULT_VIEWPORT_TRANSFORM } from "./render/element-transform";
Expand Down Expand Up @@ -501,6 +505,14 @@ interface EditorState {
setAudioStartNudgeS(s: number): void;
/** Increment the master-audio nudge by `deltaMs` (ms; signed). */
nudgeAudioStartMs(deltaMs: number): void;
/** Re-anchor the bar grid (= master `audioStartNudgeS`) so beat 0 lands
* on the audio onset of the given pill's source segment. Used to
* re-align the grid against a single chunk after small accumulated
* drift between FX/cut snap-times and the audio. Pass-through return
* codes mirror triage's `conformChunk` so the UI can disable / toast. */
conformAudioStartToPill(
pillId: string,
): "ok" | "no-pill" | "no-bpm" | "no-audio-start" | "unchanged";
/** Set the time-signature numerator (= beats per bar). Re-runs the
* whole-bar grid + bar-line ruler the next render. */
setBeatsPerBar(n: number): void;
Expand Down Expand Up @@ -1557,6 +1569,30 @@ export const useEditorStore = create<EditorState>()(
const cur = meta.audioStartNudgeS ?? 0;
get().setAudioStartNudgeS(cur + deltaMs / 1000);
},
conformAudioStartToPill(pillId) {
const s = get();
const pill = s.pills.find((p) => p.id === pillId);
if (!pill) return "no-pill";
const meta = s.jobMeta;
const phase = meta?.bpm?.phase;
if (!meta || typeof phase !== "number") return "no-bpm";
// Resolve the segment via the pill's auto-generated arr-position —
// immune to any post-load drag that moved arrStartS off its
// arrangement-item's segment range.
const segIdx = segmentIndexAtArr(
pill.originalArrStartS,
s.arrangementSegments,
);
if (segIdx < 0) return "no-audio-start";
const seg = s.arrangementSegments[segIdx];
if (typeof seg.audioStartMs !== "number") return "no-audio-start";
const targetPhaseS = seg.audioStartMs / 1000;
const newNudgeS = Math.round((targetPhaseS - phase) * 1000) / 1000;
const cur = meta.audioStartNudgeS ?? 0;
if (Math.abs(newNudgeS - cur) < 1e-6) return "unchanged";
set({ jobMeta: { ...meta, audioStartNudgeS: newNudgeS } });
return "ok";
},
setBeatsPerBar(n) {
const meta = get().jobMeta;
if (!meta) return;
Expand Down
Loading
0