diff --git a/src/components/canvas/players/luma-player.ts b/src/components/canvas/players/luma-player.ts index 02564373..c10f479a 100644 --- a/src/components/canvas/players/luma-player.ts +++ b/src/components/canvas/players/luma-player.ts @@ -62,13 +62,14 @@ export class LumaPlayer extends Player { return; } - const playbackTime = this.getPlaybackTime(); + // The matte's trim is its in-point, as for the render + const sourceTime = this.getSourceTime(); const shouldClipPlay = this.edit.isPlaying && this.isActive(); if (shouldClipPlay) { if (!this.isPlaying) { this.isPlaying = true; - this.texture.source.resource.currentTime = playbackTime; + this.texture.source.resource.currentTime = sourceTime; this.texture.source.resource.play().catch(console.error); } @@ -77,10 +78,10 @@ export class LumaPlayer extends Player { } const desyncThreshold = 0.1; - const shouldSync = Math.abs(this.texture.source.resource.currentTime - playbackTime) > desyncThreshold; + const shouldSync = Math.abs(this.texture.source.resource.currentTime - sourceTime) > desyncThreshold; if (shouldSync) { - this.texture.source.resource.currentTime = playbackTime; + this.texture.source.resource.currentTime = sourceTime; } } @@ -90,7 +91,7 @@ export class LumaPlayer extends Player { } if (!this.edit.isPlaying && this.isActive()) { - this.texture.source.resource.currentTime = playbackTime; + this.texture.source.resource.currentTime = sourceTime; } } diff --git a/src/components/canvas/players/player.ts b/src/components/canvas/players/player.ts index 88e87b96..d2802c82 100644 --- a/src/components/canvas/players/player.ts +++ b/src/components/canvas/players/player.ts @@ -6,6 +6,7 @@ import { type Edit } from "@core/edit-session"; import { InternalEvent } from "@core/events/edit-events"; import { calculateContainerScale, calculateFitScale, calculateSpriteTransform, type FitMode } from "@core/layout/fit-system"; import { type PlaybackReadiness } from "@core/pending-captures"; +import { inferAssetTypeFromUrl } from "@core/shared/asset-utils"; import { type AliasReference, type ResolvedTiming, @@ -26,6 +27,9 @@ import { Entity } from "../../../core/shared/entity"; import { type BuiltClipFilter, buildClipFilters, CLIP_BLUR_STRENGTH } from "./clip-filters"; import { COLOR_FILTERS, ColorFilter } from "./color-filter"; +/** Asset types whose schema has a `trim` in-point; a luma has one only when its source is a video. */ +const IN_POINT_ASSET_TYPES = new Set(["video", "audio", "caption", "text-to-speech"]); + /** * Tracks a merge field binding for a specific property path. * Used to restore placeholders on export for properties that haven't changed. @@ -581,6 +585,19 @@ export abstract class Player extends Entity { return Math.max(0.1, duration / speed - trim); } + /** + * Moving the start by `delta` seconds with the end fixed: the delta clamped to the source before the in-point, + * and the trim that keeps every remaining frame where it was. Null when the asset has no in-point. + */ + public getStartTrim(delta: number): { delta: number; trim: number } | null { + const { type, src = "", trim = 0 } = this.clipConfiguration.asset as { type: string; src?: string; trim?: number }; + if (!IN_POINT_ASSET_TYPES.has(type) && !(type === "luma" && inferAssetTypeFromUrl(src) === "video")) return null; + + // A constant speed scales trim as well as playback, so trim moves 1:1 with the start + const clamped = Math.max(delta, -trim); + return { delta: clamped, trim: trim + clamped }; + } + public abstract getSize(): Size; /** diff --git a/src/components/canvas/players/video-player.ts b/src/components/canvas/players/video-player.ts index f5346fc2..daacefa5 100644 --- a/src/components/canvas/players/video-player.ts +++ b/src/components/canvas/players/video-player.ts @@ -55,6 +55,14 @@ export function createAnimatedSpeed(tweens: VideoAsset["speed"], length: number) return { curve, sourceOffsets }; } +/** Source seconds the speed curve covers over the first `time` seconds of the clip. */ +function sourceOffsetAt({ sourceOffsets }: AnimatedSpeed, time: number): number { + const position = Math.min(time / SPEED_STEP_SECONDS, sourceOffsets.length - 1); + const index = Math.floor(position); + const next = Math.min(index + 1, sourceOffsets.length - 1); + return sourceOffsets[index] + (sourceOffsets[next] - sourceOffsets[index]) * (position - index); +} + export class VideoPlayer extends Player { private texture: pixi.Texture | null; private sprite: pixi.Sprite | null; @@ -352,11 +360,18 @@ export class VideoPlayer extends Player { public override getSourceTime(): number { if (!this.animatedSpeed) return super.getSourceTime(); const { trim = 0 } = this.clipConfiguration.asset as VideoAsset; - const { sourceOffsets } = this.animatedSpeed; - const position = Math.min(this.getPlaybackTime() / SPEED_STEP_SECONDS, sourceOffsets.length - 1); - const index = Math.floor(position); - const next = Math.min(index + 1, sourceOffsets.length - 1); - return trim + sourceOffsets[index] + (sourceOffsets[next] - sourceOffsets[index]) * (position - index); + return trim + sourceOffsetAt(this.animatedSpeed, this.getPlaybackTime()); + } + + public override getStartTrim(delta: number): { delta: number; trim: number } | null { + if (!this.animatedSpeed) return super.getStartTrim(delta); + const { trim = 0 } = this.clipConfiguration.asset as VideoAsset; + if (delta >= 0) return { delta, trim: Math.max(0, trim + sourceOffsetAt(this.animatedSpeed, delta)) }; + + // Before the clip the curve holds its first speed + const speed = this.animatedSpeed.curve.getValue(0); + const clamped = speed > 0 ? Math.max(delta, -trim / speed) : delta; + return { delta: clamped, trim: Math.max(0, trim + clamped * speed) }; } public override getMaxLength(): number | null { diff --git a/src/components/timeline/interaction/interaction-controller.ts b/src/components/timeline/interaction/interaction-controller.ts index 161bc531..e4e500c6 100644 --- a/src/components/timeline/interaction/interaction-controller.ts +++ b/src/components/timeline/interaction/interaction-controller.ts @@ -4,6 +4,7 @@ import { MoveAndAttachLumaCommand } from "@core/commands/move-and-attach-luma-co import { MoveClipCommand } from "@core/commands/move-clip-command"; import { MoveClipWithPushCommand } from "@core/commands/move-clip-with-push-command"; import { ResizeClipCommand } from "@core/commands/resize-clip-command"; +import { type StartTrimTarget, TrimClipStartCommand } from "@core/commands/trim-clip-start-command"; import type { Edit } from "@core/edit-session"; import { inferAssetTypeFromUrl } from "@core/shared/asset-utils"; import { type Seconds, sec } from "@core/timing/types"; @@ -491,20 +492,18 @@ export class InteractionController implements TimelineInteractionRegistration { // Calculate new dimensions based on edge const { edge, originalStart, originalLength, clipElement } = state; - const maxLength = this.getResizeMaxLength(state.clipRef, originalLength); if (edge === "left") { // Resize from left edge (keep end fixed, change start and length) - const originalEnd = originalStart + originalLength; - const minStart = maxLength !== null ? Math.max(0, originalEnd - maxLength) : 0; - const newStart = sec(Math.max(minStart, Math.min(time, originalEnd - 0.1))); - const newLength = sec(originalEnd - newStart); + const { start: newStart } = this.resolveStartEdge(state.clipRef, originalStart, originalLength, time); + const newLength = sec(originalStart + originalLength - newStart); clipElement.style.setProperty("--clip-start", String(newStart)); clipElement.style.setProperty("--clip-length", String(newLength)); this.feedbackElements.dragTimeTooltip = showDragTimeTooltip(this.feedbackElements, newStart, e.clientX - rect.left, e.clientY - rect.top); } else { // Resize from right edge + const maxLength = this.getResizeMaxLength(state.clipRef, originalLength); const newLength = sec(Math.max(0.1, Math.min(time - originalStart, maxLength ?? Infinity))); clipElement.style.setProperty("--clip-length", String(newLength)); @@ -775,45 +774,22 @@ export class InteractionController implements TimelineInteractionRegistration { // Get attached luma Player reference BEFORE changes (stable across index changes) const lumaPlayer = this.stateManager.getAttachedLumaPlayer(clipRef.trackIndex, clipRef.clipIndex); - const maxLength = this.getResizeMaxLength(clipRef, originalLength); - if (edge === "left") { // Resize from left edge (keep end fixed, change start and length) - const originalEnd = originalStart + originalLength; - const minStart = maxLength !== null ? Math.max(0, originalEnd - maxLength) : 0; - const newStart = Math.max(minStart, Math.min(time, originalEnd - 0.1)); - const newLength = originalEnd - newStart; - - if (newStart !== originalStart || newLength !== originalLength) { - // Move clip to new start position - if (newStart !== originalStart) { - const moveCommand = new MoveClipCommand(clipRef.trackIndex, clipRef.clipIndex, clipRef.trackIndex, sec(newStart)); - this.edit.executeEditCommand(moveCommand); - } + const { start: newStart, trim } = this.resolveStartEdge(clipRef, originalStart, originalLength, time); - // Resize clip to new length - if (newLength !== originalLength) { - const resizeCommand = new ResizeClipCommand(clipRef.trackIndex, clipRef.clipIndex, sec(newLength)); - this.edit.executeEditCommand(resizeCommand); - } + if (newStart !== originalStart) { + const targets: StartTrimTarget[] = [{ ...clipRef, trim }]; - // Also update attached luma clip - if (lumaPlayer) { - const lumaIndices = this.edit.findClipIndices(lumaPlayer); - if (lumaIndices) { - if (newStart !== originalStart) { - const lumaMoveCommand = new MoveClipCommand(lumaIndices.trackIndex, lumaIndices.clipIndex, lumaIndices.trackIndex, sec(newStart)); - this.edit.executeEditCommand(lumaMoveCommand); - } - if (newLength !== originalLength) { - const lumaResizeCommand = new ResizeClipCommand(lumaIndices.trackIndex, lumaIndices.clipIndex, sec(newLength)); - this.edit.executeEditCommand(lumaResizeCommand); - } - } - } + // Also trim attached luma clip + const lumaIndices = lumaPlayer ? this.edit.findClipIndices(lumaPlayer) : null; + if (lumaPlayer && lumaIndices) targets.push({ ...lumaIndices, trim: lumaPlayer.getStartTrim(newStart - originalStart)?.trim }); + + this.edit.executeEditCommand(new TrimClipStartCommand(targets, newStart, sec(originalStart + originalLength - newStart))); } } else { // Resize from right edge (keep start fixed, change length) + const maxLength = this.getResizeMaxLength(clipRef, originalLength); const newLength = Math.max(0.1, Math.min(time - originalStart, maxLength ?? Infinity)); if (newLength !== originalLength) { @@ -851,6 +827,20 @@ export class InteractionController implements TimelineInteractionRegistration { return viewXToTime(e.clientX - rect.left + this.tracksContainer.scrollLeft, this.stateManager.getViewport().pixelsPerSecond); } + /** + * Start edge for a left resize, clamped to the minimum length and to the source before the asset's in-point, + * with the trim that cuts the footage to match. No trim when the asset has no in-point. + */ + private resolveStartEdge(clipRef: ClipRef, originalStart: number, originalLength: number, time: number): { start: Seconds; trim?: number } { + const start = Math.max(0, Math.min(time, originalStart + originalLength - 0.1)); + const delta = start - originalStart; + const startTrim = this.edit.getPlayerClip(clipRef.trackIndex, clipRef.clipIndex)?.getStartTrim(delta); + if (!startTrim) return { start: sec(start) }; + + // Rebuilding an unclamped start from its delta would add float error to a snapped time + return { start: sec(startTrim.delta === delta ? start : originalStart + startTrim.delta), trim: startTrim.trim }; + } + /** * Longest length a resize may grow the clip to, or null when unbounded. */ diff --git a/src/core/commands/resize-clip-command.ts b/src/core/commands/resize-clip-command.ts index 03ef15f9..a13cf540 100644 --- a/src/core/commands/resize-clip-command.ts +++ b/src/core/commands/resize-clip-command.ts @@ -6,19 +6,21 @@ import type { Clip } from "@schemas"; import { type EditCommand, type CommandContext, type CommandResult, CommandSuccess, CommandNoop } from "./types"; /** - * Document-only command to resize a clip's length. + * Document-only command to resize a clip's length, optionally setting its asset's trim. */ export class ResizeClipCommand implements EditCommand { readonly name = "resizeClip"; /** Document-layer value for undo (may be "auto", "end", or numeric) */ private originalLength?: Clip["length"]; + private originalAsset?: Clip["asset"]; private clipId?: string; constructor( private trackIndex: number, private clipIndex: number, - private newLength: Seconds + private newLength: Seconds, + private newTrim?: number ) {} execute(context?: CommandContext): CommandResult { @@ -46,9 +48,16 @@ export class ResizeClipCommand implements EditCommand { // Capture document clip BEFORE mutation const previousDocClip = structuredClone(docClip); + this.originalAsset = previousDocClip.asset; // Document-only mutation - doc.updateClip(this.trackIndex, this.clipIndex, { length: this.newLength }); + doc.updateClip( + this.trackIndex, + this.clipIndex, + this.newTrim === undefined + ? { length: this.newLength } + : { length: this.newLength, asset: { ...docClip.asset, trim: this.newTrim } as Clip["asset"] } + ); // Single-clip resolution (O(1) instead of O(n) full resolve) if (this.clipId) { @@ -88,7 +97,11 @@ export class ResizeClipCommand implements EditCommand { const currentDocClip = structuredClone(context.getDocumentClip(this.trackIndex, this.clipIndex)); // Document-only mutation - restore original length (may be "auto", "end", or numeric) - doc.updateClip(this.trackIndex, this.clipIndex, { length: this.originalLength }); + doc.updateClip( + this.trackIndex, + this.clipIndex, + this.newTrim === undefined ? { length: this.originalLength } : { length: this.originalLength, asset: this.originalAsset } + ); // Single-clip resolution (O(1) instead of O(n) full resolve) if (this.clipId) { diff --git a/src/core/commands/trim-clip-start-command.ts b/src/core/commands/trim-clip-start-command.ts new file mode 100644 index 00000000..1a4baa8c --- /dev/null +++ b/src/core/commands/trim-clip-start-command.ts @@ -0,0 +1,88 @@ +import type { Player } from "@canvas/players/player"; +import type { Seconds } from "@core/timing/types"; + +import { MoveClipCommand } from "./move-clip-command"; +import { ResizeClipCommand } from "./resize-clip-command"; +import { type EditCommand, type CommandContext, type CommandResult, CommandSuccess, CommandNoop } from "./types"; + +const errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error)); + +export interface StartTrimTarget { + trackIndex: number; + clipIndex: number; + /** Asset trim to set, omitted for assets without an in-point */ + trim?: number; +} + +/** + * Compound command that moves the start of clips with their ends fixed, setting each in-point, as one undo step. + */ +export class TrimClipStartCommand implements EditCommand { + readonly name = "trimClipStart"; + + private steps: EditCommand[] = []; + /** Undo can reorder clips whose starts tie, so a redo finds them by id */ + private clipIds: (string | null)[] = []; + + constructor( + private readonly targets: StartTrimTarget[], + private readonly newStart: Seconds, + private readonly newLength: Seconds + ) {} + + async execute(context?: CommandContext): Promise { + if (!context) throw new Error("TrimClipStartCommand.execute: context is required"); + + // Players are stable while moves reorder clip indices + const players = this.targets.map(({ trackIndex, clipIndex }, i) => { + const clipId = this.clipIds[i]; + return clipId ? context.getPlayerByClipId(clipId) : context.getClipAt(trackIndex, clipIndex); + }); + if (!players.every((player): player is Player => player !== null)) return CommandNoop("Clips not found"); + this.clipIds = players.map(player => player.clipId); + + this.dispose(); + try { + for (const [i, player] of players.entries()) { + const from = this.indicesOf(context, player); + await this.run(context, new MoveClipCommand(from.trackIndex, from.clipIndex, from.trackIndex, this.newStart)); + const at = this.indicesOf(context, player); + await this.run(context, new ResizeClipCommand(at.trackIndex, at.clipIndex, this.newLength, this.targets[i].trim)); + } + } catch (executeError) { + try { + await this.undo(context); + } catch (undoError) { + throw new Error( + `TrimClipStartCommand: execute failed (${errorMessage(executeError)}) and rollback also failed (${errorMessage(undoError)}). State may be corrupted.` + ); + } + throw executeError; + } + + return this.steps.length > 0 ? CommandSuccess() : CommandNoop("No clip changed"); + } + + async undo(context?: CommandContext): Promise { + if (!context) throw new Error("TrimClipStartCommand.undo: context is required"); + + for (const step of [...this.steps].reverse()) await step.undo?.(context); + return CommandSuccess(); + } + + private async run(context: CommandContext, step: EditCommand): Promise { + const result = await step.execute(context); + if (result.status === "success") this.steps.push(step); + } + + private indicesOf(context: CommandContext, player: Player): { trackIndex: number; clipIndex: number } { + const indices = context.findClipIndices(player); + if (!indices) throw new Error("TrimClipStartCommand: clip not found"); + return indices; + } + + dispose(): void { + for (const step of this.steps) step.dispose?.(); + this.steps = []; + } +} diff --git a/tests/edit-commands.test.ts b/tests/edit-commands.test.ts index 09d06dff..97efadd2 100644 --- a/tests/edit-commands.test.ts +++ b/tests/edit-commands.test.ts @@ -9,7 +9,7 @@ * before imports/declarations. To share mock classes between mocks (e.g., MockImageSource for instanceof * checks), we must use require() at runtime inside the factory. This is the standard Jest pattern. */ import { Edit } from "@core/edit-session"; -import { type EditCommand, type CommandContext, type CommandResult, CommandSuccess } from "@core/commands/types"; +import { type EditCommand, type CommandContext, type CommandResult, CommandNoop, CommandSuccess } from "@core/commands/types"; import type { EventEmitter } from "@core/events/event-emitter"; import { InternalEvent } from "@core/events/edit-events"; import { sec } from "@core/timing/types"; @@ -1894,7 +1894,6 @@ describe("Keyboard movement keyframe safety", () => { }); }); - describe("commitClipUpdate validation", () => { let edit: Edit; let warnSpy: jest.SpyInstance; @@ -1938,10 +1937,7 @@ describe("commitClipUpdate validation", () => { const { history, index } = getCommandState(edit); expect(history).toHaveLength(0); expect(index).toBe(-1); - expect(warnSpy).toHaveBeenCalledWith( - expect.stringContaining("skipping invalid clip"), - expect.anything() - ); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("skipping invalid clip"), expect.anything()); }); it("commits valid fit updates to history", () => { @@ -1959,3 +1955,112 @@ describe("commitClipUpdate validation", () => { expect(index).toBe(0); }); }); + +describe("TrimClipStartCommand", () => { + let edit: Edit; + + beforeEach(async () => { + edit = new Edit({ + timeline: { + tracks: [ + { + clips: [ + { asset: { type: "video", src: "https://example.com/video.mp4", trim: 0.5 }, start: 1, length: 4 }, + { asset: { type: "luma", src: "https://example.com/luma.mp4" }, start: 1, length: 4 } + ] + }, + { clips: [{ asset: { type: "image", src: "https://example.com/image.jpg" }, start: 1, length: 4 }] } + ] + }, + output: { size: { width: 1920, height: 1080 }, format: "mp4" } + }); + await edit.load(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + edit.dispose(); + }); + + // Equal starts leave the content/luma order on the track unspecified + const clipOfType = (type: string) => [0, 1].map(i => edit.getClip(0, i)).find(clip => clip?.asset?.type === type); + + it("cuts the clip and its luma as one undo step", async () => { + const { TrimClipStartCommand } = await import("@core/commands/trim-clip-start-command"); + const historyBefore = getCommandState(edit).history.length; + + await edit.executeEditCommand( + new TrimClipStartCommand( + [ + { trackIndex: 0, clipIndex: 0, trim: 1.5 }, + { trackIndex: 0, clipIndex: 1, trim: 1 } + ], + sec(2), + sec(3) + ) + ); + + expect(getCommandState(edit).history).toHaveLength(historyBefore + 1); + expect(clipOfType("video")).toMatchObject({ start: 2, length: 3, asset: { trim: 1.5 } }); + expect(clipOfType("luma")).toMatchObject({ start: 2, length: 3, asset: { trim: 1 } }); + + await edit.undo(); + expect(clipOfType("video")).toMatchObject({ start: 1, length: 4, asset: { trim: 0.5 } }); + expect(clipOfType("luma")).toMatchObject({ start: 1, length: 4 }); + expect(clipOfType("luma")?.asset).not.toHaveProperty("trim"); + + await edit.redo(); + expect(clipOfType("video")).toMatchObject({ start: 2, length: 3, asset: { trim: 1.5 } }); + expect(clipOfType("luma")).toMatchObject({ start: 2, length: 3, asset: { trim: 1 } }); + }); + + it("leaves an image without a trim", async () => { + const { TrimClipStartCommand } = await import("@core/commands/trim-clip-start-command"); + expect(edit.getPlayerClip(1, 0)?.getStartTrim(1)).toBeNull(); + + await edit.executeEditCommand(new TrimClipStartCommand([{ trackIndex: 1, clipIndex: 0 }], sec(2), sec(3))); + + expect(edit.getClip(1, 0)).toMatchObject({ start: 2, length: 3 }); + expect(edit.getClip(1, 0)?.asset).not.toHaveProperty("trim"); + }); + + it("reports both errors when a failed trim can't be rolled back", async () => { + const { TrimClipStartCommand } = await import("@core/commands/trim-clip-start-command"); + const { MoveClipCommand } = await import("@core/commands/move-clip-command"); + const { ResizeClipCommand } = await import("@core/commands/resize-clip-command"); + jest.spyOn(ResizeClipCommand.prototype, "execute").mockImplementation(() => { + throw new Error("resize failed"); + }); + jest.spyOn(MoveClipCommand.prototype, "undo").mockRejectedValue(new Error("undo failed")); + + const trim = edit.executeEditCommand(new TrimClipStartCommand([{ trackIndex: 1, clipIndex: 0 }], sec(2), sec(3))); + + await expect(trim).rejects.toThrow(/resize failed.*undo failed/); + }); + + it("records nothing when no step applies", async () => { + const { TrimClipStartCommand } = await import("@core/commands/trim-clip-start-command"); + const { MoveClipCommand } = await import("@core/commands/move-clip-command"); + const { ResizeClipCommand } = await import("@core/commands/resize-clip-command"); + jest.spyOn(MoveClipCommand.prototype, "execute").mockReturnValue(CommandNoop("unchanged")); + jest.spyOn(ResizeClipCommand.prototype, "execute").mockReturnValue(CommandNoop("unchanged")); + const historyBefore = getCommandState(edit).history.length; + + const result = await edit.executeEditCommand(new TrimClipStartCommand([{ trackIndex: 1, clipIndex: 0 }], sec(2), sec(3))); + + expect(result.status).toBe("noop"); + expect(getCommandState(edit).history).toHaveLength(historyBefore); + }); + + it("disposes its steps", async () => { + const { TrimClipStartCommand } = await import("@core/commands/trim-clip-start-command"); + const { MoveClipCommand } = await import("@core/commands/move-clip-command"); + const dispose = jest.spyOn(MoveClipCommand.prototype, "dispose"); + const command = new TrimClipStartCommand([{ trackIndex: 1, clipIndex: 0 }], sec(2), sec(3)); + await edit.executeEditCommand(command); + + command.dispose(); + + expect(dispose).toHaveBeenCalled(); + }); +}); diff --git a/tests/interaction-controller.test.ts b/tests/interaction-controller.test.ts index d7ca7f24..30facc2f 100644 --- a/tests/interaction-controller.test.ts +++ b/tests/interaction-controller.test.ts @@ -67,6 +67,15 @@ jest.mock("../src/core/commands/resize-clip-command", () => ({ })) })); +jest.mock("../src/core/commands/trim-clip-start-command", () => ({ + TrimClipStartCommand: jest.fn().mockImplementation((targets, newStart, newLength) => ({ + type: "TrimClipStartCommand", + targets, + newStart, + newLength + })) +})); + // ─── Mock Types ────────────────────────────────────────────────────────────── interface MockClipConfig { @@ -140,7 +149,7 @@ function createMockEdit() { executeEditCommand: jest.fn((cmd: unknown) => { executedCommands.push(cmd); }), - getPlayerClip: jest.fn(() => ({ id: "player-1", getMaxLength: () => null })), + getPlayerClip: jest.fn(() => ({ id: "player-1", getMaxLength: () => null, getStartTrim: (): unknown => null })), findClipIndices: jest.fn((player: unknown) => { if (!player) return null; return { trackIndex: 0, clipIndex: 0 }; @@ -687,7 +696,7 @@ describe("InteractionController", () => { expect(mockEdit.executeEditCommand).toHaveBeenCalled(); }); - it("executes both MoveClipCommand and ResizeClipCommand when resizing left edge", () => { + it("executes a start trim when resizing left edge", () => { controller = new InteractionController( mockEdit as never, mockStateManager as never, @@ -1079,7 +1088,7 @@ describe("InteractionController", () => { const clipElement = () => mockDOM.tracksContainer.querySelector(".ss-clip") as HTMLElement; const lastCommand = (type: string) => mockEdit.executeEditCommand.mock.calls - .map(([cmd]) => cmd as Record & { type: string }) + .map(([cmd]) => cmd as Record & { type: string }) .filter(cmd => cmd.type === type) .pop(); @@ -1111,7 +1120,7 @@ describe("InteractionController", () => { document.dispatchEvent(createPointerEvent("pointermove", { clientX: 350, clientY: 20 })); document.dispatchEvent(createPointerEvent("pointerup", { clientX: 350, clientY: 20 })); - expect(lastCommand("MoveClipCommand")?.["newTime"]).toBeCloseTo(3); + expect(lastCommand("MoveClipCommand")?.["newTime"] as number).toBeCloseTo(3); }); it("moves a right edge grabbed inside the clip by the pointer's displacement", () => { @@ -1122,7 +1131,7 @@ describe("InteractionController", () => { expect(Number(clipElement().style.getPropertyValue("--clip-length"))).toBeCloseTo(3); document.dispatchEvent(createPointerEvent("pointerup", { clientX: 411, clientY: 20 })); - expect(lastCommand("ResizeClipCommand")?.["length"]).toBeCloseTo(3); + expect(lastCommand("ResizeClipCommand")?.["length"] as number).toBeCloseTo(3); }); it("measures the grab offset in the scrolled timeline", () => { @@ -1162,8 +1171,80 @@ describe("InteractionController", () => { expect(Number(clipElement().style.getPropertyValue("--clip-start"))).toBeCloseTo(1.5); document.dispatchEvent(createPointerEvent("pointerup", { clientX: 171, clientY: 20 })); - expect(lastCommand("MoveClipCommand")?.["newTime"]).toBeCloseTo(1.5); - expect(lastCommand("ResizeClipCommand")?.["length"]).toBeCloseTo(1.5); + expect(lastCommand("TrimClipStartCommand")?.["newStart"] as number).toBeCloseTo(1.5); + expect(lastCommand("TrimClipStartCommand")?.["newLength"] as number).toBeCloseTo(1.5); + }); + + describe("start trim", () => { + // Trim 0.5 at speed 1: the start can move 0.5 s left before the source runs out + const videoPlayer = { + getMaxLength: () => null, + getStartTrim: (delta: number) => ({ delta: Math.max(delta, -0.5), trim: Math.max(0, 0.5 + delta) }) + }; + const dragLeftEdge = (toX: number) => { + const handle = clipElement().querySelector(".ss-clip-resize-handle.left") as HTMLElement; + handle.dispatchEvent(createPointerEvent("pointerdown", { clientX: 116, clientY: 20 })); + document.dispatchEvent(createPointerEvent("pointermove", { clientX: toX, clientY: 20 })); + document.dispatchEvent(createPointerEvent("pointerup", { clientX: toX, clientY: 20 })); + }; + + beforeEach(() => { + mockEdit.getPlayerClip.mockReturnValue(videoPlayer as never); + }); + + it("cuts the source with the start as a single command", () => { + dragLeftEdge(216); + + expect(mockEdit.executeEditCommand).toHaveBeenCalledTimes(1); + expect(lastCommand("TrimClipStartCommand")).toEqual({ + type: "TrimClipStartCommand", + targets: [{ trackIndex: 0, clipIndex: 0, trim: 1.5 }], + newStart: 2, + newLength: 1 + }); + }); + + it("stops the start edge where the source runs out", () => { + const handle = clipElement().querySelector(".ss-clip-resize-handle.left") as HTMLElement; + handle.dispatchEvent(createPointerEvent("pointerdown", { clientX: 116, clientY: 20 })); + document.dispatchEvent(createPointerEvent("pointermove", { clientX: 16, clientY: 20 })); + expect(Number(clipElement().style.getPropertyValue("--clip-start"))).toBeCloseTo(0.5); + document.dispatchEvent(createPointerEvent("pointerup", { clientX: 16, clientY: 20 })); + + expect(lastCommand("TrimClipStartCommand")).toMatchObject({ + targets: [{ trackIndex: 0, clipIndex: 0, trim: 0 }], + newStart: 0.5, + newLength: 2.5 + }); + }); + + it("gives an attached luma the same in-point change", () => { + const lumaPlayer = { getStartTrim: (delta: number) => ({ delta, trim: delta }) }; + mockStateManager.getAttachedLumaPlayer.mockReturnValue(lumaPlayer as never); + mockEdit.findClipIndices.mockReturnValue({ trackIndex: 0, clipIndex: 1 }); + + dragLeftEdge(216); + + expect(mockEdit.executeEditCommand).toHaveBeenCalledTimes(1); + expect(lastCommand("TrimClipStartCommand")?.["targets"]).toEqual([ + { trackIndex: 0, clipIndex: 0, trim: 1.5 }, + { trackIndex: 0, clipIndex: 1, trim: 1 } + ]); + }); + + it("keeps an unclamped start exactly where it snapped", () => { + // Left edge at view x 86; the playhead at 0.1 s is a snap point + mockStateManager.setTestTracks([createMockTrack(0, [{ start: 0.7, length: 2 }])] as MockTrack[]); + mockStateManager.getPlayback.mockReturnValue({ time: 0.1, isPlaying: false }); + mockEdit.getPlayerClip.mockReturnValue({ getMaxLength: () => null, getStartTrim: (delta: number) => ({ delta, trim: 1 + delta }) } as never); + const handle = clipElement().querySelector(".ss-clip-resize-handle.left") as HTMLElement; + + handle.dispatchEvent(createPointerEvent("pointerdown", { clientX: 86, clientY: 20 })); + document.dispatchEvent(createPointerEvent("pointermove", { clientX: 28, clientY: 20 })); + document.dispatchEvent(createPointerEvent("pointerup", { clientX: 28, clientY: 20 })); + + expect(lastCommand("TrimClipStartCommand")?.["newStart"]).toBe(0.1); + }); }); }); diff --git a/tests/player-sync.test.ts b/tests/player-sync.test.ts index e859b945..987d722f 100644 --- a/tests/player-sync.test.ts +++ b/tests/player-sync.test.ts @@ -14,6 +14,7 @@ import { VideoPlayer } from "@canvas/players/video-player"; import { AudioPlayer } from "@canvas/players/audio-player"; import { LumaPlayer } from "@canvas/players/luma-player"; import { CaptionPlayer } from "@canvas/players/caption-player"; +import { Player } from "@canvas/players/player"; import type { Edit } from "@core/edit-session"; import { sec, type Seconds } from "@core/timing/types"; import type { ResolvedClip, VideoAsset, AudioAsset, LumaAsset, CaptionAsset, Tween } from "@schemas"; @@ -502,6 +503,37 @@ describe("AudioPlayer", () => { }); }); +describe("getStartTrim", () => { + it("keeps the frame under the new start at a constant speed", () => { + // At 2×, a 1 s start trim moves the source in-point 2 s: trim is scaled by speed + const before = new VideoPlayer(createMockEdit(1), createVideoClipConfig(0.5, 0, 2)); + const result = before.getStartTrim(1); + expect(result).toEqual({ delta: 1, trim: 1.5 }); + + const after = new VideoPlayer(createMockEdit(1), createVideoClipConfig(result?.trim, 1, 2)); + expect(after.getSourceTime()).toBeCloseTo(before.getSourceTime()); + expect(new AudioPlayer(createMockEdit(0), createAudioClipConfig(0)).getStartTrim(1)).toEqual({ delta: 1, trim: 1 }); + }); + + it("keeps the frame under the new start through a speed curve", () => { + const before = new VideoPlayer(createMockEdit(1), createAnimatedSpeedClipConfig([{ from: 1, to: 3, start: 0, length: 2 }], 1)); + expect(before.getStartTrim(1)?.trim).toBeCloseTo(before.getSourceTime(), 3); + }); + + it("stops the start where the trim reaches 0", () => { + expect(new VideoPlayer(createMockEdit(0), createVideoClipConfig(0.5)).getStartTrim(-1)).toEqual({ delta: -0.5, trim: 0 }); + // The curve holds 2× before the clip, so 1 s of source covers 0.5 s of timeline + const animated = new VideoPlayer(createMockEdit(0), createAnimatedSpeedClipConfig([{ from: 2, to: 2, start: 0, length: 2 }], 1)); + expect(animated.getStartTrim(-1)).toEqual({ delta: -0.5, trim: 0 }); + }); + + it("trims video lumas and leaves image lumas without an in-point", () => { + expect(new LumaPlayer(createMockEdit(0), createLumaClipConfig()).getStartTrim(1)).toEqual({ delta: 1, trim: 1 }); + const imageLuma = { asset: { type: "luma", src: "luma.png" }, start: 0, length: 10 } as ResolvedClip; + expect(new LumaPlayer(createMockEdit(0), imageLuma).getStartTrim(1)).toBeNull(); + }); +}); + // ───────────────────────────────────────────────────────────────────────────── // LumaPlayer Tests // ───────────────────────────────────────────────────────────────────────────── @@ -516,6 +548,20 @@ describe("LumaPlayer", () => { expect(player.getPlaybackTime()).toBe(6); }); }); + + it("plays a video matte from its trim", () => { + const player = new LumaPlayer(createMockEdit(3), { asset: { type: "luma", src: "luma.mp4", trim: 2 }, start: 0, length: 10 } as ResolvedClip); + const video = createMockVideoElement(); + // @ts-expect-error - accessing private property for testing + player.texture = { source: new pixi.VideoSource({ resource: video }) }; + // The base update needs a loaded scene; only the matte's seek is under test + const baseUpdate = jest.spyOn(Player.prototype, "update").mockImplementation(() => {}); + + player.update(0, 0); + baseUpdate.mockRestore(); + + expect(video.currentTime).toBe(5); + }); }); // ─────────────────────────────────────────────────────────────────────────────