8000 Editor: collapse direct-mode / arrangement-mode split by johannboehme · Pull Request #32 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ app/static/
.coverage
htmlcov/
uv.lock
frontend/pnpm-lock.yaml
30 changes: 28 additions & 2 deletions frontend/src/editor/arrangement-loop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,12 @@ describe("clampLoopToBounds", () => {
).toBeNull();
});

test("with segments → clamps to [0, totalArrDuration] (arr-time domain)", () => {
test("with segments + wide-open trim → clamps to [0, totalArrDuration]", () => {
const segs: Segment[] = [
{ in: 10, out: 15 },
{ in: 20, out: 25 },
];
// totalArr = 10. trim is irrelevant in arr-mode.
// totalArr = 10; trim covers all of it.
expect(
clampLoopToBounds({ start: 1, end: 5 }, segs, { in: 0, out: 100 }),
).toEqual({ start: 1, end: 5 });
Expand All @@ -138,6 +138,32 @@ describe("clampLoopToBounds", () => {
).toEqual({ start: 0, end: 3 });
});

test("with segments + narrow trim → trim wins over arr range (master-trim universal)", () => {
// Single-take after Phase A: arrangementSegments=[{in:0, out:60}].
// Master-trim={5, 50} narrows the playable region; the loop must
// clamp to the trim's arr-projection, not the full segment range.
const segs: Segment[] = [{ in: 0, out: 60 }];
expect(
clampLoopToBounds({ start: 1, end: 60 }, segs, { in: 5, out: 50 }),
).toEqual({ start: 5, end: 50 });
expect(
clampLoopToBounds({ start: 20, end: 25 }, segs, { in: 0, out: 10 }),
).toBeNull();
});

test("long-form + master-trim → clamp via masterToArr projection", () => {
// Long-form arrangement with two 5-second chunks (totalArr=10).
// Master-trim {12, 22} cuts: master 12 → arr-time 2 (mid-seg0);
// master 22 → arr-time 7 (mid-seg1). Loop must clamp to [2, 7].
const segs: Segment[] = [
{ in: 10, out: 15 },
{ in: 20, out: 25 },
];
expect(
clampLoopToBounds({ start: 0, end: 10 }, segs, { in: 12, out: 22 }),
).toEqual({ start: 2, end: 7 });
});

test("with segments + null loop → null", () => {
const segs: Segment[] = [{ in: 10, out: 15 }];
expect(clampLoopToBounds(null, segs, { in: 0, out: 5 })).toBeNull();
Expand Down
18 changes: 13 additions & 5 deletions frontend/src/editor/arrangement-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { LoopRegion, TrimRegion } from "./OffsetScheduler";
import { clampLoopRegion } from "./OffsetScheduler";
import {
arrToMaster,
masterToArr,
segmentIndexAtArr,
totalArrDuration,
} from "./arrangement-time";
Expand Down Expand Up @@ -66,9 +67,14 @@ export function nextLoopWrapMasterT(
};
}

/** Mode-aware clamp. With segments → clamp to `[0, totalArrDuration]`.
* Without → fall back to legacy trim-clamp. Returns null when the loop
* collapses to zero length. */
/** Clamp the loop to the playable arr-time window: the intersection of
* the segments' totalArrDuration and the master-trim's projection into
* arr-time. Master-trim universally narrows the loop in both single-take
* (where arr-time == master-time) and long-form (where trim cuts across
* chunks). Returns null when the loop collapses to zero length.
*
* Defensive: with empty segments falls back to legacy trim-clamp so a
* pre-load store snapshot doesn't crash. */
export function clampLoopToBounds(
loop: LoopRegion | null,
segments: readonly Segment[],
Expand All @@ -77,8 +83,10 @@ export function clampLoopToBounds(
if (!loop) return null;
if (segments.length === 0) return clampLoopRegion(loop, trim);
const total = totalArrDuration(segments);
const start = Math.max(0, loop.start);
const end = Math.min(total, loop.end);
const trimInArr = Math.max(0, Math.min(total, masterToArr(trim.in, segments)));
const trimOutArr = Math.max(trimInArr, Math.min(total, masterToArr(trim.out, segments)));
const start = Math.max(trimInArr, loop.start);
const end = Math.min(trimOutArr, loop.end);
if (end <= start) return null;
return { start, end };
}
54 changes: 40 additions & 14 deletions frontend/src/editor/arrangement-pills.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,45 @@ const makeVideoClip = (
selectedCandidateIdx: 0,
});

describe("generatePills (single-take = no arrangement)", () => {
it("emits one pill per cam covering its full master range", () => {
/** Synthetic single-take inputs — mirrors what `synthesizeJobLoadShape`
* feeds into `loadJob` for direct-mode jobs. The arrangement-item id is
* the legacy `__default__` sentinel so pill ids stay stable across the
* refactor. */
const makeSyntheticSingleTake = (durationS: number) => ({
arrangement: [{ id: "__default__", chunkId: "__default_chunk__" }],
chunks: [
{
id: "__default_chunk__",
startMs: 0,
endMs: durationS * 1000,
bpmOctaveShift: 0 as const,
effectiveBpm: 0,
beatsPerBar: 4,
accepted: true,
trimMode: "free" as const,
},
],
});

describe("generatePills (single-take via synthetic arrangement)", () => {
it("emits one pill per cam, ID anchored on the __default__ sentinel", () => {
const cams: Clip[] = [
makeVideoClip("cam-a", 0, 30),
makeVideoClip("cam-b", 0, 45),
];
const pills = generatePills([], [], cams);
// Single-take's synthetic chunk spans the WIDEST cam (max sourceDurationS)
// — this is what synthesizeJobLoadShape produces when fed master duration.
const { arrangement, chunks } = makeSyntheticSingleTake(45);
const pills = generatePills(arrangement, chunks, cams);
expect(pills.length).toBe(2);
// cam-a clipped at its own range (30s); cam-b uses its full 45s.
expect(pills[0]).toMatchObject({
id: "cam-a::__default__",
camId: "cam-a",
arrStartS: 0,
arrEndS: 30,
sourceInS: 0,
sourceOutS: 30,
originalArrStartS: 0,
originalArrEndS: 30,
originalSourceInS: 0,
originalSourceOutS: 30,
fromArrangementItemId: "__default__",
});
expect(pills[1].id).toBe("cam-b::__default__");
Expand Down Expand Up @@ -208,8 +228,10 @@ describe("reconcilePills", () => {
// offset → fresh generation puts the pill at e.g. arr=2.896. Reconcile
// would otherwise keep stored.arrStartS=0 and only refresh originals,
// so the pill renders at 0 while the cuts strip / clipRangeS expect
// 2.896. Direct-mode bypasses the stored pill entirely.
// 2.896. Single-take goes through the synthetic arrangement+chunk
// (mirroring synthesizeJobLoadShape).
const cam: Clip[] = [makeVideoClip("c", -2896, 100)];
const synth = makeSyntheticSingleTake(100);
const stored: Pill[] = [
{
id: "c::__default__",
Expand All @@ -225,19 +247,23 @@ describe("reconcilePills", () => {
fromArrangementItemId: "__default__",
},
];
const reconciled = reconcilePills([], [], cam, stored);
const reconciled = reconcilePills(synth.arrangement, synth.chunks, cam, stored);
expect(reconciled.length).toBe(1);
expect(reconciled[0].arrStartS).toBeCloseTo(2.896, 3);
expect(reconciled[0].arrEndS).toBeCloseTo(2.896 + 100, 3);
// Synthetic chunk spans [0, 100s]; cam-clip-vs-chunk intersection
// ends at 2.896+100=102.896s in master, but the chunk caps at 100s,
// so arrEndS = 100 (clipped by chunk bound).
expect(reconciled[0].arrEndS).toBeCloseTo(100, 3);
});

it("ignores polluted stored pills in direct-mode (originals diverged from arr by previous reconcile)", () => {
it("ignores polluted stored pills (originals diverged from arr by previous reconcile)", () => {
// Reload race: a previous reconcile cycle refreshed `originalArrStartS`
// to the post-sync fresh value (2.896) but left `arrStartS=0`. Then the
// pill got persisted in that polluted state. The unedited-heuristic
// can no longer recognize it because arr ≠ original. Direct-mode
// sidesteps this entirely: pill is always regenerated.
// can no longer recognize it because arr ≠ original. Without the
// userEdited flag, the pill is always regenerated.
const cam: Clip[] = [makeVideoClip("c", -2896, 100)];
const synth = makeSyntheticSingleTake(100);
const stored: Pill[] = [
{
id: "c::__default__",
Expand All @@ -254,7 +280,7 @@ describe("reconcilePills", () => {
fromArrangementItemId: "__default__",
},
];
const reconciled = reconcilePills([], [], cam, stored);
const reconciled = reconcilePills(synth.arrangement, synth.chunks, cam, stored);
expect(reconciled.length).toBe(1);
expect(reconciled[0].arrStartS).toBeCloseTo(2.896, 3);
});
Expand Down
78 changes: 14 additions & 64 deletions frontend/src/editor/arrangement-pills.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,30 @@
/**
* Pill auto-generation, reconciliation, and active-pill resolution.
*
* The editor is uniformly pill-based. Every job — long-form arrangement
* or single-take — renders through `pills[]`. The generator below
* produces one pill per editing slot:
* The editor is uniformly pill-based. Every job runs through the same
* `(arrangement × chunks × clips)` shape — long-form jobs feed their
* persisted arrangement, single-take jobs synthesize a single
* arrangement-item + chunk in `synthesizeJobLoadShape` so the pill
* generator stays mode-agnostic.
*
* - Long-form jobs (arrangement non-empty): one pill per
* (cam × arrangement-item) intersection. Pill ID
* `${camId}::${arrangementItemId}` round-trips user edits across
* editor mounts.
*
* - Single-take jobs (arrangement empty): one pill per cam covering
* the cam's full visible master-time range. Pill ID
* `${camId}::__default__`.
* Pill ID `${camId}::${arrangementItemId}` round-trips user edits across
* editor mounts; single-take jobs keep the legacy `__default__` item id
* so pre-refactor persisted pill edits stay matched.
*
* Pure helpers — no store, no IO, no React.
*/
import type { ArrangementItem, Chunk, Cut } from "../storage/jobs-db";
import { camSourceTimeS } from "../local/timing/cam-time";
import { masterToArr } from "./arrangement-time";
import {
clipRangeS,
isImageClip,
isVideoClip,
clipRangeS,
type Clip,
type Pill,
type Segment,
} from "./types";

/** Single-take pill id sentinel. Stable so reconcile keeps user edits
* across editor mounts even when the job has no arrangement. */
const DEFAULT_ITEM_ID = "__default__";

/** Tolerance for pill-dirtiness comparisons. Anything sub-millisecond
* is rounding noise, not a user edit. */
const DIRTY_EPS_S = 1e-3;
Expand All @@ -52,12 +45,11 @@ export function isPillDirty(p: Pill): boolean {
/**
* Build the editor's pill list from the persisted job state.
*
* Dispatches on whether the job carries an arrangement:
* - `arrangement.length > 0` → emit one pill per (cam × item)
* intersection in playback order.
* - empty / missing arrangement → emit one pill per cam, anchored
* at the cam's full master-time range. arr-time == master-time
* in this case (no segment-walker mapping).
* Emits one pill per (cam × arrangement-item) intersection in playback
* order. Single-take jobs come in with a synthetic single-item
* arrangement (see `synthesizeJobLoadShape`) so this function stays
* mode-agnostic — its only inputs are the same `(arrangement, chunks,
* clips)` triple regardless of the job's source.
*
* Originals are baked in so the per-pill RESET action restores the
* pill to the slot the editor would generate today.
Expand All @@ -66,48 +58,6 @@ export function generatePills(
arrangement: readonly ArrangementItem[],
chunks: readonly Chunk[],
clips: readonly Clip[],
): Pill[] {
if (arrangement.length === 0 || chunks.length === 0) {
return generateDefaultPills(clips);
}
return generateArrangementPills(arrangement, chunks, clips);
}

function generateDefaultPills(clips: readonly Clip[]): Pill[] {
const out: Pill[] = [];
for (const clip of clips) {
const range = clipRangeS(clip);
if (range.endS <= range.startS) continue;
if (isImageClip(clip)) {
out.push(makePill({
camId: clip.id,
itemId: DEFAULT_ITEM_ID,
arrStartS: range.startS,
arrEndS: range.endS,
sourceInS: 0,
sourceOutS: clip.durationS,
}));
continue;
}
if (!isVideoClip(clip)) continue;
const sourceInS = clip.trimInS ?? 0;
const sourceOutS = clip.trimOutS ?? clip.sourceDurationS;
out.push(makePill({
camId: clip.id,
itemId: DEFAULT_ITEM_ID,
arrStartS: range.startS,
arrEndS: range.endS,
sourceInS,
sourceOutS,
}));
}
return out;
}

function generateArrangementPills(
arrangement: readonly ArrangementItem[],
chunks: readonly Chunk[],
clips: readonly Clip[],
): Pill[] {
const chunkById = new Map(chunks.map((c) => [c.id, c]));
const out: Pill[] = [];
Expand Down
Loading
Loading
0