Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(schema): never force-bake 'native' before the source is probed

Etienne Lescot71a4e2cd1702
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index ce21ac464..eab949305 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -183,10 +183,9 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
// so the sizes shown match what the export produces. Read through `getEditorSettings` — the
// same typed façade the ratio dropdown writes through and `buildSceneDescription` reads — so
// this dialog can't drift from the compositor if the storage ever moves. `resolveAspectRatioValue`
- // is the single funnel preview and export agree on; the v5→v6 upgrader retires the legacy
- // "native" AspectRatio so no document-context argument is needed here.
+ // owns the legacy "native" case (uncropped reference asset), previously hand-rolled here.
const EXPORT_ASPECT = useMemo(
- () => resolveAspectRatioValue(getEditorSettings(document).aspectRatio),
+ () => resolveAspectRatioValue(document, getEditorSettings(document).aspectRatio),
[document],
);
// Output dimensions the export will produce for a given tier, from the (crop-aware)
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index 80abde6aa..63e7347d2 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -185,12 +185,12 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
// exactly what the frame is styled to (`width: frameSize.width` a few lines below), so it's
// used directly everywhere `canvasSize` used to be — one source of truth, no separate
// observer that can desync from it.
- // `resolveAspectRatioValue`, not bare `getAspectRatioValue`: keeps preview and export
- // routing through the same funnel — the v5→v6 upgrader rewrites the legacy "native"
- // selection to a concrete `"W:H"` token, so both paths agree on the resolved shape
- // without an extra document argument.
+ // `resolveAspectRatioValue`, not bare `getAspectRatioValue`: the latter has no document to
+ // resolve the legacy "native" selection against and answers 16/9 for it, so a project saved
+ // with "native" over portrait footage framed the preview 16:9 while `pickOutputDims` handed
+ // the compositor a portrait `output` — preview and export disagreed on the frame's shape.
const frameSize = useMemo(() => {
- const ratio = resolveAspectRatioValue(settings.aspectRatio);
+ const ratio = resolveAspectRatioValue(document, settings.aspectRatio);
const { width: containerWidth, height: containerHeight } = containerSize;
if (containerWidth <= 0 || containerHeight <= 0)
return { width: containerWidth, height: containerHeight };
@@ -200,7 +200,7 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
}
const width = containerWidth;
return { width: Math.round(width), height: Math.round(width / ratio) };
- }, [containerSize, settings.aspectRatio]);
+ }, [containerSize, settings.aspectRatio, document]);
// Crop is per-clip (see clipSchema.cropRegion) — resolve it from whichever
// clip the playhead is currently inside, the same lookup VirtualPreview
diff --git a/src/lib/ai-edition/document/outputFormat.test.ts b/src/lib/ai-edition/document/outputFormat.test.ts
index c3490e8ee..9c16552c6 100644
--- a/src/lib/ai-edition/document/outputFormat.test.ts
+++ b/src/lib/ai-edition/document/outputFormat.test.ts
@@ -225,7 +225,13 @@ describe("pickOutputDims", () => {
[asset("a1", 1366, 768), asset("a2", 3840, 2160)],
[clip("c1", "a1"), clip("c2", "a2")],
);
- const tokens: AspectRatio[] = [...ASPECT_RATIO_PRESETS, "683:384", "64:27", "1023:767"];
+ const tokens: AspectRatio[] = [
+ ...ASPECT_RATIO_PRESETS,
+ "683:384",
+ "64:27",
+ "1023:767",
+ "native",
+ ];
for (const token of tokens) {
const out = pickOutputDims(d, token);
expect(out.width % 2, `width for ${token}`).toBe(0);
@@ -250,6 +256,14 @@ describe("pickOutputDims", () => {
expect(pickOutputDims(after, "16:9")).toEqual({ width: 3840, height: 2160 });
});
+ it('legacy "native" still resolves to the reference clip, drift included', () => {
+ const portraitWins = doc(
+ [asset("a1", 1920, 1080), asset("a2", 2160, 3840)],
+ [clip("c1", "a1"), clip("c2", "a2")],
+ );
+ expect(pickOutputDims(portraitWins, "native")).toEqual({ width: 2160, height: 3840 });
+ });
+
it("sizes the output off the cropped footprint, not the raw 4K asset", () => {
// A single 4K clip cropped to a 16:9 half-width strip: the output must rasterise at the
// crop's real size (1920x1080), not the asset's 3840x2160. Before the reference went
@@ -263,13 +277,18 @@ describe("pickOutputDims", () => {
});
describe("resolveAspectRatioValue", () => {
- // The legacy `"native"` AspectRatio is retired — the v5→v6 upgrader (see
- // `src/lib/ai-edition/schema/index.test.ts` — "v5 -> v6 native AspectRatio
- // migration") rewrites every stored "native" to a concrete `"W:H"` token at load
- // time, so by the time this function runs there is no document context to thread
- // through. What remains is a thin wrapper around `getAspectRatioValue`.
+ it('resolves legacy "native" against the document instead of the 16/9 fallback', () => {
+ const d = doc([asset("a1", 1080, 1920)], [clip("c1", "a1")]);
+ expect(resolveAspectRatioValue(d, "native")).toBeCloseTo(1080 / 1920, 6);
+ });
+
+ it('falls back to 16/9 for "native" with no document (preview before load)', () => {
+ expect(resolveAspectRatioValue(null, "native")).toBeCloseTo(16 / 9, 6);
+ });
+
it("passes concrete tokens straight through", () => {
- expect(resolveAspectRatioValue("4:5")).toBeCloseTo(0.8, 6);
- expect(resolveAspectRatioValue("64:27")).toBeCloseTo(64 / 27, 6);
+ const d = doc([asset("a1", 1080, 1920)], [clip("c1", "a1")]);
+ expect(resolveAspectRatioValue(d, "4:5")).toBeCloseTo(0.8, 6);
+ expect(resolveAspectRatioValue(d, "64:27")).toBeCloseTo(64 / 27, 6);
});
});
diff --git a/src/lib/ai-edition/document/outputFormat.ts b/src/lib/ai-edition/document/outputFormat.ts
index faa598ef3..602db3aa5 100644
--- a/src/lib/ai-edition/document/outputFormat.ts
+++ b/src/lib/ai-edition/document/outputFormat.ts
@@ -18,6 +18,7 @@ import { calculateEffectiveSourceDimensions } from "@/lib/exporter/mp4ExportSett
import {
type AspectRatio,
getAspectRatioValue,
+ getNativeAspectRatioValue,
toAspectRatioToken,
} from "@/utils/aspectRatioUtils";
import type { AxcutAsset, AxcutClip, AxcutDocument } from "../schema";
@@ -224,13 +225,19 @@ export function collectNativeFormats(
}
/**
- * Numeric ratio for a stored selection. v6 documents never carry the legacy `"native"`
- * AspectRatio (the v5→v6 upgrader rewrites it to a concrete `"W:H"` token), so resolution
- * is a single token lookup. Kept as a function so the preview / export path still has a
- * single funnel — if storage ever moves, this is the one place to update.
+ * Numeric ratio for a stored selection, with the document available to resolve the legacy
+ * `"native"` value. Every consumer that frames or sizes the output must go through this rather
+ * than bare `getAspectRatioValue`, which has no document and falls back to 16/9.
*/
-export function resolveAspectRatioValue(aspectRatio: AspectRatio): number {
- return getAspectRatioValue(aspectRatio);
+export function resolveAspectRatioValue(
+ document: AxcutDocument | null | undefined,
+ aspectRatio: AspectRatio,
+ probedAssetDims: Record<string, Dims> = {},
+): number {
+ if (aspectRatio !== "native") return getAspectRatioValue(aspectRatio);
+ if (!document) return getAspectRatioValue("native");
+ const reference = referenceClipDims(document, probedAssetDims);
+ return getNativeAspectRatioValue(reference.width, reference.height);
}
/**
@@ -254,7 +261,7 @@ export function pickOutputDims(
probedAssetDims: Record<string, Dims> = {},
): Dims {
const reference = referenceClipDims(document, probedAssetDims);
- const ratio = resolveAspectRatioValue(aspectRatio);
+ const ratio = resolveAspectRatioValue(document, aspectRatio, probedAssetDims);
const longSide = toEvenPx(Math.max(reference.width, reference.height));
if (ratio >= 1) {
return { width: longSide, height: toEvenPx(longSide / ratio) };
diff --git a/src/lib/ai-edition/schema/index.test.ts b/src/lib/ai-edition/schema/index.test.ts
index fdbd76ae2..9b3767c6e 100644
--- a/src/lib/ai-edition/schema/index.test.ts
+++ b/src/lib/ai-edition/schema/index.test.ts
@@ -590,10 +590,13 @@ describe("v5 -> v6 native AspectRatio migration", () => {
expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("9:16");
});
- it("falls back to 16:9 when the timeline has no clips with known dimensions", () => {
+ it("leaves 'native' alone when the timeline has no clips with known dimensions", () => {
+ // Deliberately NOT a 16:9 fallback: an empty/unprobed timeline gives no basis
+ // for a concrete token, and guessing one persists a wrong frame. See the v1.7
+ // import case below.
const doc = documentSchema.parse(makeV5Doc({ legacyEditor: { aspectRatio: "native" } }));
expect(doc.schemaVersion).toBe(6);
- expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("16:9");
+ expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("native");
});
it("passes through a concrete aspectRatio unchanged", () => {
@@ -623,6 +626,90 @@ describe("v5 -> v6 native AspectRatio migration", () => {
expect(twice).toEqual(once);
});
+ it("keeps 'native' when the source dimensions are not known yet (v1.7 import)", () => {
+ // The v1.7 -> v1.8 path: `{version:2, media, editor}` carries only file paths,
+ // so `migrateProjectDataToAxcutDocument` produces assets with no `video` block.
+ // Baking here would stamp a hardcoded 16:9 and persist it — permanently
+ // reframing every portrait v1.7 project saved with "Native". Leave the
+ // sentinel; it resolves dynamically at runtime and converts on a later load,
+ // once useTimeline's probe has written `asset.video` back.
+ const doc = documentSchema.parse({
+ schemaVersion: 5,
+ project: {
+ id: "p1",
+ title: "from v1.7",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-01-01T00:00:00.000Z",
+ },
+ assets: [
+ {
+ id: "asset_u",
+ kind: "video",
+ label: "A",
+ originalPath: "/a.mp4",
+ cameraTrack: null,
+ // no `video` — exactly what the v2 import produces
+ },
+ ],
+ timeline: {
+ clips: [
+ {
+ id: "clip_a",
+ assetId: "asset_u",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ origin: "user",
+ },
+ ],
+ },
+ legacyEditor: { aspectRatio: "native" },
+ });
+ expect(doc.schemaVersion).toBe(6);
+ expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("native");
+ });
+
+ it("converts 'native' once the probe has persisted dimensions", () => {
+ // Second load of the same project, after useTimeline probed a PORTRAIT source.
+ // This is the case that must not become 16:9.
+ const doc = documentSchema.parse({
+ schemaVersion: 5,
+ project: {
+ id: "p1",
+ title: "from v1.7, probed",
+ createdAt: "2024-01-01T00:00:00.000Z",
+ updatedAt: "2024-01-01T00:00:00.000Z",
+ },
+ assets: [
+ {
+ id: "asset_u",
+ kind: "video",
+ label: "A",
+ originalPath: "/a.mp4",
+ cameraTrack: null,
+ video: { width: 1080, height: 1920 },
+ },
+ ],
+ timeline: {
+ clips: [
+ {
+ id: "clip_a",
+ assetId: "asset_u",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ origin: "user",
+ },
+ ],
+ },
+ legacyEditor: { aspectRatio: "native" },
+ });
+ expect(doc.schemaVersion).toBe(6);
+ expect((doc.legacyEditor as Record<string, unknown>).aspectRatio).toBe("9:16");
+ });
+
it("bakes the CROPPED dimensions, not the raw ones", () => {
// "native" resolved to the cropped clip at runtime. A 3840x2160 asset cropped
// to its left half is effectively 1920x2160 → 8:9. Reading the raw dims would
diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts
index 177d0929a..a10b718ab 100644
--- a/src/lib/ai-edition/schema/index.ts
+++ b/src/lib/ai-edition/schema/index.ts
@@ -612,12 +612,26 @@ function upgradeV5DocumentToV6(raw: unknown): unknown {
return { ...doc, schemaVersion: 6 };
}
+ // OPPORTUNISTIC, never forced. Baking requires real source dimensions, and a
+ // project imported from v1.7 has none yet: `migrateProjectDataToAxcutDocument`
+ // builds its asset from `{version:2, media, editor}`, which carries only file
+ // paths — dimensions arrive later, when `useTimeline`'s probe effect writes
+ // `asset.video` back to disk.
+ //
+ // So when dimensions are unknown we leave `"native"` in place rather than
+ // stamping a hardcoded ratio. `"native"` keeps resolving dynamically at runtime
+ // (`resolveAspectRatioValue`), which IS the v1.7 behaviour, and the next load
+ // after the probe has persisted dimensions converts it for real. Forcing
+ // `"16:9"` here would permanently reframe every portrait v1.7 project that used
+ // "Native", on its first open in v1.8, with no way back.
const dims = largestClipDims(doc);
- const token = dims ? toAspectRatioToken(dims.width, dims.height) : null;
+ if (!dims) {
+ return { ...doc, schemaVersion: 6 };
+ }
return {
...doc,
schemaVersion: 6,
- legacyEditor: { ...legacy, aspectRatio: token ?? "16:9" },
+ legacyEditor: { ...legacy, aspectRatio: toAspectRatioToken(dims.width, dims.height) },
};
}
diff --git a/src/utils/aspectRatioUtils.ts b/src/utils/aspectRatioUtils.ts
index 451f43fff..07d98a207 100644
--- a/src/utils/aspectRatioUtils.ts
+++ b/src/utils/aspectRatioUtils.ts
@@ -15,12 +15,17 @@ export type AspectRatioPreset = (typeof ASPECT_RATIO_PRESETS)[number];
* A concrete `"W:H"` shape. The presets are just the well-known members — the picker also
* offers the clips' own native shapes ("Original"), which are stored the same way and can be
* anything (`"64:27"` for an ultrawide, `"683:384"` for an odd capture size).
+ *
+ * `"native"` is a LEGACY value kept only so projects saved before the shapes were enumerated
+ * still open. It resolves to the timeline's reference asset (largest pixel area), which is
+ * exactly the silent, drifting behaviour the enumeration replaced — nothing writes it any
+ * more, so it can be dropped once old projects are assumed migrated.
*/
-export type AspectRatio = AspectRatioPreset | `${number}:${number}`;
+export type AspectRatio = AspectRatioPreset | `${number}:${number}` | "native";
-const ASPECT_RATIO_FALLBACK = 16 / 9;
+const NATIVE_ASPECT_RATIO_FALLBACK = 16 / 9;
-/** Split a `"W:H"` token. Returns null for anything malformed. */
+/** Split a `"W:H"` token. Returns null for `"native"` and for anything malformed. */
export function parseAspectRatio(value: string): { width: number; height: number } | null {
const match = /^\s*(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)\s*$/.exec(value);
if (!match) return null;
@@ -35,7 +40,7 @@ export function parseAspectRatio(value: string): { width: number; height: number
/** Validation gate for anything read back from disk (project files, user prefs). */
export function isAspectRatio(value: unknown): value is AspectRatio {
if (typeof value !== "string") return false;
- return parseAspectRatio(value) !== null;
+ return value === "native" || parseAspectRatio(value) !== null;
}
function greatestCommonDivisor(a: number, b: number): number {
@@ -66,12 +71,15 @@ export function toAspectRatioToken(width: number, height: number): AspectRatio |
}
/**
- * Numeric value of an aspect ratio. Returns the 16/9 fallback for any value that doesn't
- * parse as a `"W:H"` token.
+ * Numeric value of an aspect ratio. Legacy `"native"` has no document context here so it
+ * returns the 16/9 fallback — callers holding a document must resolve it through
+ * `resolveAspectRatioValue` (lib/ai-edition/document/outputFormat) instead, or preview and
+ * output silently disagree on old projects.
*/
export function getAspectRatioValue(aspectRatio: AspectRatio): number {
+ if (aspectRatio === "native") return NATIVE_ASPECT_RATIO_FALLBACK;
const parsed = parseAspectRatio(aspectRatio);
- return parsed ? parsed.width / parsed.height : ASPECT_RATIO_FALLBACK;
+ return parsed ? parsed.width / parsed.height : NATIVE_ASPECT_RATIO_FALLBACK;
}
export function getNativeAspectRatioValue(
@@ -91,11 +99,11 @@ export function getNativeAspectRatioValue(
cropW <= 0 ||
cropH <= 0
) {
- return ASPECT_RATIO_FALLBACK;
+ return NATIVE_ASPECT_RATIO_FALLBACK;
}
const ratio = (videoWidth * cropW) / (videoHeight * cropH);
- return Number.isFinite(ratio) && ratio > 0 ? ratio : ASPECT_RATIO_FALLBACK;
+ return Number.isFinite(ratio) && ratio > 0 ? ratio : NATIVE_ASPECT_RATIO_FALLBACK;
}
export function getAspectRatioDimensions(
@@ -110,6 +118,7 @@ export function getAspectRatioDimensions(
}
export function getAspectRatioLabel(aspectRatio: AspectRatio): string {
+ if (aspectRatio === "native") return "Original";
return aspectRatio;
}
@@ -117,6 +126,7 @@ export function isPortraitAspectRatio(aspectRatio: AspectRatio): boolean {
return getAspectRatioValue(aspectRatio) < 1;
}
-export function formatAspectRatioForCSS(aspectRatio: AspectRatio): string {
+export function formatAspectRatioForCSS(aspectRatio: AspectRatio, nativeRatio?: number): string {
+ if (aspectRatio === "native") return String(nativeRatio ?? NATIVE_ASPECT_RATIO_FALLBACK);
return aspectRatio.replace(":", "/");
}