8000 Mode-agnostic loop on the composed timeline + reconcile/strip fixes by johannboehme · Pull Request #29 · 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
160 changes: 160 additions & 0 deletions frontend/src/editor/arrangement-loop.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { describe, expect, test } from "vitest";
import { nextLoopWrapMasterT, clampLoopToBounds } from "./arrangement-loop";
import type { Segment } from "./types";

describe("nextLoopWrapMasterT", () => {
test("single synthetic segment (direct-mode equivalent) — arr-time == master-time", () => {
const segs: Segment[] = [{ in: 0, out: 10 }];
expect(nextLoopWrapMasterT({ start: 1, end: 5 }, segs)).toEqual({
wrapAtMasterT: 5,
wrapTargetMasterT: 1,
wrapInSegIdx: 0,
targetSegIdx: 0,
});
});

test("synthetic segment with non-zero in (trim region) — projects through trim", () => {
// Direct-mode after Phase 3 will use {in: trim.in, out: trim.out}.
// Loop in arr-time {start: 0, end: 4} should map to master {6.4, 10.4}.
const segs: Segment[] = [{ in: 6.4, out: 12 }];
expect(nextLoopWrapMasterT({ start: 0, end: 4 }, segs)).toEqual({
wrapAtMasterT: 10.4,
wrapTargetMasterT: 6.4,
wrapInSegIdx: 0,
targetSegIdx: 0,
});
});

test("multi-segment, loop fully within one segment", () => {
const segs: Segment[] = [
{ in: 10, out: 15 },
{ in: 20, out: 25 },
];
// arr-times: seg0 = [0..5], seg1 = [5..10]. loop = {1, 4} → master {11, 14}.
expect(nextLoopWrapMasterT({ start: 1, end: 4 }, segs)).toEqual({
wrapAtMasterT: 14,
wrapTargetMasterT: 11,
wrapInSegIdx: 0,
targetSegIdx: 0,
});
});

test("multi-segment, loop spans segment boundary", () => {
const segs: Segment[] = [
{ in: 10, out: 15 },
{ in: 20, out: 25 },
];
// arr=2 → seg0 master 12. arr=8 → seg1 master 23.
expect(nextLoopWrapMasterT({ start: 2, end: 8 }, segs)).toEqual({
wrapAtMasterT: 23,
wrapTargetMasterT: 12,
wrapInSegIdx: 1,
targetSegIdx: 0,
});
});

test("loop start exactly at segment boundary (half-open: arr=5 → seg1)", () => {
const segs: Segment[] = [
{ in: 10, out: 15 },
{ in: 20, out: 25 },
];
// arr=5 starts seg1, master 20. arr=8 → master 23.
expect(nextLoopWrapMasterT({ start: 5, end: 8 }, segs)).toEqual({
wrapAtMasterT: 23,
wrapTargetMasterT: 20,
wrapInSegIdx: 1,
targetSegIdx: 1,
});
});< 10000 /td>

test("loop end exactly at total arr duration → clamps to last segment", () => {
const segs: Segment[] = [
{ in: 10, out: 15 },
{ in: 20, out: 25 },
];
// totalArr = 10. loop.end = 10 hits half-open boundary; clamp to last seg.
expect(nextLoopWrapMasterT({ start: 0, end: 10 }, segs)).toEqual({
wrapAtMasterT: 25,
wrapTargetMasterT: 10,
wrapInSegIdx: 1,
targetSegIdx: 0,
});
});

test("duplicate chunks — wrap target tied to user's chosen output position, not first occurrence", () => {
// Same master-range used twice in the arrangement.
const segs: Segment[] = [
{ in: 5, out: 8 },
{ in: 5, out: 8 },
];
// arr-times: seg0 = [0..3], seg1 = [3..6]. loop = {1, 5}: arr=1 → seg0
// master 6, arr=5 → seg1 master 7. The walker must wrap at master=7
// *while in seg1*, NOT also at master=7 in seg0.
expect(nextLoopWrapMasterT({ start: 1, end: 5 }, segs)).toEqual({
wrapAtMasterT: 7,
wrapTargetMasterT: 6,
wrapInSegIdx: 1,
targetSegIdx: 0,
});
});

test("empty segments → null (defensive — walker should never call with empty)", () => {
expect(nextLoopWrapMasterT({ start: 0, end: 1 }, [])).toBeNull();
});

test("null loop → null", () => {
const segs: Segment[] = [{ in: 0, out: 10 }];
expect(nextLoopWrapMasterT(null, segs)).toBeNull();
});
});

describe("clampLoopToBounds", () => {
test("no segments + trim → behaves like legacy clampLoopRegion", () => {
expect(
clampLoopToBounds({ start: 1, end: 2 }, [], { in: 0, out: 5 }),
).toEqual({ start: 1, end: 2 });
expect(
clampLoopToBounds({ start: 4, end: 7 }, [], { in: 0, out: 5 }),
).toEqual({ start: 4, end: 5 });
expect(
clampLoopToBounds({ start: 10, end: 12 }, [], { in: 0, out: 5 }),
).toBeNull();
});

test("with segments → clamps to [0, totalArrDuration] (arr-time domain)", () => {
const segs: Segment[] = [
{ in: 10, out: 15 },
{ in: 20, out: 25 },
];
// totalArr = 10. trim is irrelevant in arr-mode.
expect(
clampLoopToBounds({ start: 1, end: 5 }, segs, { in: 0, out: 100 }),
).toEqual({ start: 1, end: 5 });
expect(
clampLoopToBounds({ start: 8, end: 15 }, segs, { in: 0, out: 100 }),
).toEqual({ start: 8, end: 10 });
expect(
clampLoopToBounds({ start: -2, end: 3 }, segs, { in: 0, out: 100 }),
).toEqual({ start: 0, end: 3 });
});

test("with segments + null loop → null", () => {
const segs: Segment[] = [{ in: 10, out: 15 }];
expect(clampLoopToBounds(null, segs, { in: 0, out: 5 })).toBeNull();
});

test("with segments + loop entirely outside arr range → null", () => {
const segs: Segment[] = [{ in: 10, out: 15 }];
// totalArr = 5. loop [10, 20] is past it.
expect(
clampLoopToBounds({ start: 10, end: 20 }, segs, { in: 0, out: 100 }),
).toBeNull();
});

test("with segments + degenerate loop after clamp → null", () => {
const segs: Segment[] = [{ in: 10, out: 15 }];
expect(
clampLoopToBounds({ start: 5, end: 6 }, segs, { in: 0, out: 100 }),
).toBeNull();
});
});
84 changes: 84 additions & 0 deletions frontend/src/editor/arrangement-loop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* Loop-region helpers that work uniformly in direct-mode (single track,
* arr-time == master-time passthrough) and arrangement-mode (composed
* timeline of N segments). The user thinks of the loop as in/out markers
* on the composed "tape" — these helpers project that intent down to the
* master-time clock the audio walker runs on.
*
* Pure, no IO. The walker calls `nextLoopWrapMasterT` per tick to know
* where the next wrap fires; the store calls `clampLoopToBounds` so the
* user can't drag a loop outside the playable region.
*/
import type { Segment } from "./types";
import type { LoopRegion, TrimRegion } from "./OffsetScheduler";
import { clampLoopRegion } from "./OffsetScheduler";
import {
arrToMaster,
segmentIndexAtArr,
totalArrDuration,
} from "./arrangement-time";

export interface LoopWrapGeometry {
/** Master-time at which the wrap fires (= arr-time of `loop.end`
* projected into its containing segment). */
wrapAtMasterT: number;
/** Master-time the idle <audio> should be parked at — where the loop
* re-enters playback. */
wrapTargetMasterT: number;
/** Index of the segment in which the wrap fires. The walker uses this
* to skip wrap-arming while the playhead is still in an earlier
* segment (segment-hop comes first). */
wrapInSegIdx: number;
/** Index of the segment that contains `loop.start` — used as the
* authoritative `nextSegmentIdx` after the crossfade swaps so the
* walker doesn't re-derive from master-time and pick a duplicate. */
targetSegIdx: number;
}

/** Project an arr-time loop into master-time wrap geometry, given the
* current arrangement segments. Returns null when there's no loop or
* no segments to walk. Loop is assumed already clamped to
* `[0, totalArrDuration]` by `clampLoopToBounds`. */
export function nextLoopWrapMasterT(
loop: LoopRegion | null,
segments: readonly Segment[],
): LoopWrapGeometry | null {
if (!loop) return null;
if (segments.length === 0) return null;

// Half-open intervals: arr-time exactly == totalArrDuration falls past
// the last segment in `segmentIndexAtArr`. The wrap MUST fire inside
// a real segment, so clamp to the last index. arrToMaster handles the
// value side correctly (clamps to `last.out`).
let wrapInSegIdx = segmentIndexAtArr(loop.end, segments);
if (wrapInSegIdx === -1) wrapInSegIdx = segments.length - 1;

let targetSegIdx = segmentIndexAtArr(loop.start, segments);
// Symmetric guard — loop.start clamped to 0 should map to seg 0; this
// is only here so a caller passing an unclamped loop doesn't crash.
if (targetSegIdx === -1) targetSegIdx = 0;

return {
wrapAtMasterT: arrToMaster(loop.end, segments),
wrapTargetMasterT: arrToMaster(loop.start, segments),
wrapInSegIdx,
targetSegIdx,
};
}

/** 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. */
export function clampLoopToBounds(
loop: LoopRegion | null,
segments: readonly Segment[],
trim: TrimRegion,
): LoopRegion | null {
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);
if (end <= start) return null;
return { start, end };
}
90 changes: 88 additions & 2 deletions frontend/src/editor/arrangement-pills.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ describe("reconcilePills", () => {
];

it("preserves user-edited arr/source on stored pills, refreshes originals", () => {
const userEdited: Pill[] = [
const userEditedPills: Pill[] = [
{
id: "c::a0",
camId: "c",
Expand All @@ -156,9 +156,10 @@ describe("reconcilePills", () => {
originalSourceInS: 99,
originalSourceOutS: 99,
fromArrangementItemId: "a0",
userEdited: true,
},
];
const reconciled = reconcilePills(arr, chunks, cams, userEdited);
const reconciled = reconcilePills(arr, chunks, cams, userEditedPills);
expect(reconciled.length).toBe(2);
// First pill: user-edited values stay.
expect(reconciled[0].arrStartS).toBe(0.5);
Expand All @@ -173,6 +174,91 @@ describe("reconcilePills", () => {
expect(reconciled[1].arrStartS).toBe(2);
});

it("regenerates pills without the userEdited flag (legacy / sync-stale)", () => {
// Mode-agnostic rule: stored arr/source override fresh ONLY when the
// user-edited flag is true. Pre-flag pills (or pills written before
// sync resolved) are auto-derived and must follow the current
// baseline.
const stored: Pill[] = [
{
id: "c::a0",
camId: "c",
// Pre-sync stored values that no longer match clipRangeS.
arrStartS: 99,
arrEndS: 99,
sourceInS: 99,
sourceOutS: 99,
originalArrStartS: 0,
originalArrEndS: 2,
originalSourceInS: 0,
originalSourceOutS: 2,
fromArrangementItemId: "a0",
// No userEdited flag → treated as auto-generated.
},
];
const reconciled = reconcilePills(arr, chunks, cams, stored);
// Fresh values win.
expect(reconciled[0].arrStartS).toBe(0);
expect(reconciled[0].arrEndS).toBe(2);
});

it("regenerates an unedited stored pill when sync changes its baseline", () => {
// Pre-existing bug: a single-take pill saved before sync completed
// (arrStartS=0, originalArrStartS=0). Sync resolves later to a non-zero
// 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.
const cam: Clip[] = [makeVideoClip("c", -2896, 100)];
const stored: Pill[] = [
{
id: "c::__default__",
camId: "c",
arrStartS: 0,
arrEndS: 100,
sourceInS: 0,
sourceOutS: 100,
originalArrStartS: 0,
originalArrEndS: 100,
originalSourceInS: 0,
originalSourceOutS: 100,
fromArrangementItemId: "__default__",
},
];
const reconciled = reconcilePills([], [], cam, stored);
expect(reconciled.length).toBe(1);
expect(reconciled[0].arrStartS).toBeCloseTo(2.896, 3);
expect(reconciled[0].arrEndS).toBeCloseTo(2.896 + 100, 3);
});

it("ignores polluted stored pills in direct-mode (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.
const cam: Clip[] = [makeVideoClip("c", -2896, 100)];
const stored: Pill[] = [
{
id: "c::__default__",
camId: "c",
arrStartS: 0,
arrEndS: 100,
sourceInS: 0,
sourceOutS: 100,
// Originals diverged from arr by a previous reconcile run.
originalArrStartS: 2.896,
originalArrEndS: 2.896 + 100,
originalSourceInS: 0,
originalSourceOutS: 100,
fromArrangementItemId: "__default__",
},
];
const reconciled = reconcilePills([], [], cam, stored);
expect(reconciled.length).toBe(1);
expect(reconciled[0].arrStartS).toBeCloseTo(2.896, 3);
});

it("drops stored pills whose arrangement-item disappeared", () => {
const stored: Pill[] = [
{
Expand Down
15 changes: 12 additions & 3 deletions frontend/src/editor/arrangement-pills.ts B1B5
Original file line number Diff line number Diff line change
Expand Up @@ -210,11 +210,20 @@ export function reconcilePills(
const storedById = new Map(storedPills.map((p) => [p.id, p]));
return fresh.map((freshP) => {
const stored = storedById.get(freshP.id);
if (!stored) return freshP;
// Mode-agnostic rule: stored values override fresh ONLY when the
// user explicitly edited this pill (`userEdited === true`). Without
// that flag, the pill is auto-derived from clips + sync + chunks —
// any baseline shift (sync resolving, trim change, audio nudge) must
// flow through to the pill, which means using fresh values.
//
// Pre-flag pills (no `userEdited`) are conservatively treated as
// auto-generated. This drops any user edits made before the flag
// was added, but those were already broken across reloads in many
// cases (the previous heuristic mis-flagged unedited pills as edited
// whenever a previous reconcile cycle had refreshed the originals).
if (!stored || !stored.userEdited) return freshP;
return {
...stored,
// Refresh originals to current auto-derived values so RESET
// takes the user back to "what the editor would generate now".
originalArrStartS: freshP.originalArrStartS,
originalArrEndS: freshP.originalArrEndS,
originalSourceInS: freshP.originalSourceInS,
Expand Down
Loading
Loading
0