8000 fix(editor): correct long-form loop placement (arr-time anchoring) by johannboehme · Pull Request #48 · 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
31 changes: 30 additions & 1 deletion frontend/src/editor/arrangement-loop.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,36 @@
import { describe, expect, test } from "vitest";
import { nextLoopWrapMasterT, clampLoopToBounds } from "./arrangement-loop";
import {
nextLoopWrapMasterT,
clampLoopToBounds,
loopAroundPlayhead,
} from "./arrangement-loop";
import type { Segment } from "./types";

describe("loopAroundPlayhead", () => {
test("centers the window on the arr-time playhead", () => {
// A 2 s window around arr-time 5 is [4, 6].
expect(loopAroundPlayhead(5, 2, 10)).toEqual({ start: 4, end: 6 });
});

test("anchors on the arr-time playhead, not a master-time value", () => {
// The caller passes the AUTHORITATIVE arr-playhead (timelineT). For a
// repeated chunk's 2nd occurrence the playhead is arr 12 (even though
// its master-time also appears earlier); the loop must center at 12 →
// [10, 14], never on the first occurrence's arr-position.
expect(loopAroundPlayhead(12, 4, 20)).toEqual({ start: 10, end: 14 });
});

test("clamps to the playable arr-window at the end of the song", () => {
// Playhead at arr 19, total 20; a 4 s window would overrun → clamp so
// the window ends at 20 and keeps its full length: [16, 20].
expect(loopAroundPlayhead(19, 4, 20)).toEqual({ start: 16, end: 20 });
});

test("clamps to 0 at the start of the song", () => {
expect(loopAroundPlayhead(0.5, 4, 10)).toEqual({ start: 0, end: 4 });
});
});

describe("nextLoopWrapMasterT", () => {
test("single synthetic segment (direct-mode equivalent) — arr-time == master-time", () => {
const segs: Segment[] = [{ in: 0, out: 10 }];
Expand Down
26 changes: 26 additions & 0 deletions frontend/src/editor/arrangement-loop.ts
37 changes: 24 additions & 13 deletions frontend/src/editor/components/SyncTuner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,32 @@ export function nextLoopWrapMasterT(
};
}

/** Build a loop region of `seconds` length centered on the playhead.
*
* Works purely in arr-time. The caller MUST pass the AUTHORITATIVE arr-time
* playhead (`playback.timelineT`), NOT `masterToArr(currentTime)` — the
* latter scans for the first segment whose master range contains the
* playhead and snaps onto the FIRST occurrence when a chunk is repeated in
* the arrangement, so the loop would land on the wrong occurrence (the
* same first-match trap the walker avoids by tracking `currentSegmentIdx`).
* Clamps the window to `[0, totalArrS]`, preserving its full length where
* possible. Callers still pass the result through `setLoop`, which narrows
* it to the master-trim window. */
export function loopAroundPlayhead(
playheadArrT: number,
seconds: number,
totalArrS: number,
): LoopRegion {
const half = seconds / 2;
let start = Math.max(0, playheadArrT - half);
let end = start + seconds;
if (end > totalArrS) {
end = totalArrS;
start = Math.max(0, end - seconds);
}
return { start, end };
}

/** 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
// 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 { segmentIndexAtArr, totalArrDuration } from "../arrangement-time";
import { loopAroundPlayhead } from "../arrangement-loop";
import { isVideoClip, MASTER_AUDIO_ID } from "../types";
import { ChunkyButton } from "./ChunkyButton";
import { Knob } from "./Knob";
Expand Down Expand Up @@ -71,7 +72,6 @@ export function SyncTuner({ lastSyncOverrideMs }: Props) {
const setAbBypass = useEditorStore((s) => s.setAbBypass);
// currentTime read imperatively in the loop-around-playhead handler
// — subscribing would re-render this whole panel 60×/sec for nothing.
const trim = useEditorStore((s) => s.trim);
const setLoop = useEditorStore((s) => s.setLoop);
const loop = useEditorStore((s) => s.playback.loop);
const hasBpm = useEditorStore((s) => Boolean(s.jobMeta?.bpm));
Expand Down Expand Up @@ -106,11 +106,17 @@ export function SyncTuner({ lastSyncOverrideMs }: Props) {
const totalMs = abBypass ? algoMs : algoMs + userOverrideMs;

function setLoopAroundPlayhead(seconds: number) {
const t = useEditorStore.getState().playback.currentTime;
const half = seconds / 2;
const start = Math.max(trim.in, t - half);
const end = Math.min(trim.out, start + seconds);
setLoop({ start, end });
const s = useEditorStore.getState();
// Anchor on the AUTHORITATIVE arr-time playhead (`timelineT`), not on
// master-time — in long-form with a repeated chunk a master-time scan
// snaps onto the wrong occurrence. `setLoop` then narrows to the trim.
setLoop(
loopAroundPlayhead(
s.playback.timelineT,
seconds,
totalArrDuration(s.arrangementSegments),
),
);
}

function nudgeWithHaptic(delta: number) {
Expand Down Expand Up @@ -439,18 +445,23 @@ function MasterAudioBranch() {
const setAudioStartNudgeS = useEditorStore((s) => s.setAudioStartNudgeS);
const nudgeAudioStartMs = useEditorStore((s) => s.nudgeAudioStartMs);
// currentTime read imperatively in setLoopAroundPlayhead.
const trim = useEditorStore((s) => s.trim);
const setLoop = useEditorStore((s) => s.setLoop);
const loop = useEditorStore((s) => s.playback.loop);

const audioNudgeMs = audioNudgeS * 1000;

function setLoopAroundPlayhead(seconds: number) {
const t = useEditorStore.getState().playback.currentTime;
const half = seconds / 2;
const start = Math.max(trim.in, t - half);
const end = Math.min(trim.out, start + seconds);
setLoop({ start, end });
const s = useEditorStore.getState();
// Anchor on the AUTHORITATIVE arr-time playhead (`timelineT`), not on
// master-time — in long-form with a repeated chunk a master-time scan
// snaps onto the wrong occurrence. `setLoop` then narrows to the trim.
setLoop(
loopAroundPlayhead(
s.playback.timelineT,
seconds,
totalArrDuration(s.arrangementSegments),
),
);
}

function nudgeWithHaptic(deltaMs: number) {
Expand Down
15 changes: 11 additions & 4 deletions frontend/src/editor/components/Timeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1276,10 +1276,17 @@ export function Timeline({
setSelectedPillId(p.id);
setSelectedClipId(p.camId);
if (lanesLocked) {
// Lock on → no drag setup. Fall back to a normal scrub
// click so the playhead still follows the user's pointer.
seekFromX(x, snapped(tRaw, e));
dragRef.current = { kind: "playhead" };
// Lock on → no drag setup. A locked pill click normally also
// scrubs so the playhead follows the pointer — but NOT while a
// loop is engaged. A scrub onto a pill outside the loop lands
// out of the loop region, and the audio walker's immediate-wrap
// (useAudioMaster) yanks playback straight back to loop.start,
// so the picked pill could never be auditioned. With a loop
// active, select only and leave the loop running untouched.
if (!loop) {
seekFromX(x, snapped(tRaw, e));
dragRef.current = { kind: "playhead" };
}
return;
}
if (pillHit.zone === "left") {
Expand Down
29 changes: 15 additions & 14 deletions frontend/src/editor/components/TransportBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,11 @@ export function TransportBar() {
});
switch (target.kind) {
case "loop": {
// Loop lives in arr-time on the composed timeline; project the
// playhead's master-time through `arrSegments` (Identity for
// single-take's whole-master segment).
const t_arr = masterToArr(t, arrSegments);
const newStart = t_arr;
// Loop lives in arr-time on the composed timeline. Anchor on the
// AUTHORITATIVE arr-playhead (`timelineT`), NOT `masterToArr(t)` —
// a master-time scan snaps onto the first occurrence of a repeated
// chunk, so the loop edge would jump to the wrong occurrence.
const newStart = s.playback.timelineT;
const newEnd = Math.max(loop!.end, newStart + 1 / fps);
setLoop({ start: newStart, end: newEnd });
return;
Expand Down Expand Up @@ -182,8 +182,8 @@ export function TransportBar() {
});
switch (target.kind) {
case "loop": {
const t_arr = masterToArr(t, arrSegments);
const newEnd = t_arr;
// Authoritative arr-playhead — see setInPointAtPlayhead's loop case.
const newEnd = s.playback.timelineT;
const newStart = Math.min(loop!.start, newEnd - 1 / fps);
setLoop({ start: newStart, end: newEnd });
return;
Expand All @@ -209,13 +209,14 @@ export function TransportBar() {
setLoop(null);
return;
}
// Anchor on the COMPOSED timeline (the user's tape). Loop bounds
// are arr-time; clamp to the playable arr-window so a fresh-open
// playhead at t=0 doesn't propose a region outside the active
// range — `setLoop` would clamp it to null and the toggle would
// appear to do nothing.
const t = useEditorStore.getState().playback.currentTime;
const t_arr = masterToArr(t, arrSegments);
// Anchor on the COMPOSED timeline (the user's tape) at the AUTHORITATIVE
// arr-playhead (`timelineT`). Using `masterToArr(currentTime)` would scan
// for the first segment whose master range contains the playhead and snap
// onto the FIRST occurrence of a repeated chunk — so in long-form the loop
// would land on the wrong occurrence (markers + audio jump away from where
// the user pressed). Clamp to the playable arr-window so a fresh-open
// playhead doesn't propose a region `setLoop` would clamp to null.
const t_arr = useEditorStore.getState().playback.timelineT;
const hi = totalArrDuration(arrSegments);
const start = Math.max(0, Math.min(hi - 1 / fps, t_arr));
const end = Math.min(hi, start + 2);
Expand Down
18 changes: 16 additions & 2 deletions frontend/src/editor/useAudioMaster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useEditorStore } from "./store";
import { nextLoopWrapMasterT } from "./arrangement-loop";
import { segmentArrStarts, segmentIndexAtArr } from "./arrangement-time";
import {
arrToMaster,
segmentArrStarts,
segmentIndexAtArr,
} from "./arrangement-time";
import { attachLoopGlitchProbe, isProbeEnabled } from "./audio-glitch-probe";

export interface AudioMasterHandle {
Expand Down Expand Up @@ -352,8 +356,18 @@ export function useAudioMaster(
? refsStable.b.current
: refsStable.a.current;
if (!idleEl) return;
// `loop.start` is arr-time on the composed tape; the <audio> clock is
// master-time. Project before parking — Identity for single-take, but
// off by the segment offset in long-form (the tick re-parks at the
// correct wrapTargetMasterT before any crossfade, so this was masked,
// but parking the right master-time up front avoids a cold-decoder
// attack if a wrap fires immediately after the loop is set).
const parkMasterT = arrToMaster(
loop.start,
useEditorStore.getState().arrangementSegments,
);
try {
idleEl.currentTime = clampSeek(loop.start, idleEl.duration);
idleEl.currentTime = clampSeek(parkMasterT, idleEl.duration);
} catch {
/* not ready yet — next tick will catch up */
}
Expand Down
Loading
0