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
11 changes: 6 additions & 5 deletions src/components/canvas/players/luma-player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand All @@ -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;
}
}

Expand All @@ -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;
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/components/canvas/players/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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;

/**
Expand Down
25 changes: 20 additions & 5 deletions src/components/canvas/players/video-player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<pixi.VideoSource> | null;
private sprite: pixi.Sprite | null;
Expand Down Expand Up @@ -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 {
Expand Down
64 changes: 27 additions & 37 deletions src/components/timeline/interaction/interaction-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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.
*/
Expand Down
21 changes: 17 additions & 4 deletions src/core/commands/resize-clip-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
88 changes: 88 additions & 0 deletions src/core/commands/trim-clip-start-command.ts
Original file line number Diff line number Diff line change
@@ -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<CommandResult> {
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<CommandResult> {
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<void> {
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 = [];
}
}
Loading
Loading