Skip to content

Commit 2d695a8

Browse files
feat(studio): support GIF export with loop count (#5593)
* feat(studio): support GIF export with loop count * fix(studio): cap GIF exports at 30 fps * fix(studio): complete GIF export review follow-ups
1 parent 64cb655 commit 2d695a8

25 files changed

Lines changed: 762 additions & 178 deletions

‎docs/guides/rendering.mdx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ The whole loop: the project, the render command, progress, and the finished file
1717
playing. The flags shown are the ones people actually reach for — format,
1818
resolution, frame rate, quality.
1919

20+
## Export a GIF from Studio
21+
22+
Open the **Renders** panel, choose **GIF**, set the loop count, and click **Export**.
23+
Use `0` to loop forever or an integer from `1` to `65535` for a finite loop count.
24+
GIF exports have no audio and are capped at 30 fps; the 60 fps option is disabled
25+
while GIF is selected. Finished GIFs preview in the render list and can be
26+
opened, downloaded, or deleted there.
27+
2028
## Render a normal video
2129

2230
From the project folder:

‎packages/cli/src/server/studioRenderTelemetry.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,10 @@ import type { RenderCpuTelemetryPayload } from "../telemetry/renderCpu.js";
2121
export interface StudioRenderOpts {
2222
fps: Fps;
2323
quality: string;
24-
/** Output container format; Studio requests are constrained to these three. */
25-
format?: "mp4" | "webm" | "mov";
24+
format?: "mp4" | "webm" | "mov" | "gif";
2625
/** Named canvas preset the Studio request asked for; undefined renders at the composition's native dimensions. */
2726
outputResolution?: CanvasResolution;
2827
useGpu?: boolean;
29-
// gif_fps_capped/hdr_mode/video_frame_format are deliberately absent: Studio
30-
// has no gif/png-sequence option and createRenderJob never receives an
31-
// hdrMode or videoFrameFormat from the Studio request type, so there is no
32-
// per-request value: see the PR description for the full reasoning.
3328
// Telemetry id of the browser user who triggered the render, so the render
3429
// outcome joins their studio_session_start / studio_render_start events.
3530
// Undefined for older studio clients → falls back to the install anonymousId.

‎packages/cli/src/server/studioServer.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import {
2+
waitForRenderCancellation,
3+
cancelAndVerifyArtifacts,
4+
} from "../../../../test-utils/renderCancellation";
15
import { EventEmitter } from "node:events";
26
import { afterEach, describe, expect, it, vi } from "vitest";
37
import {
@@ -408,6 +412,46 @@ describe("createStudioServer shutdown", () => {
408412
rmSync(outDir, { recursive: true, force: true });
409413
});
410414

415+
it("forwards GIF loop count and writes a metadata sidecar without overwriting output", async () => {
416+
producerState.executeRenderJob = async (job, _dir, outputPath) => {
417+
expect(job).toMatchObject({ format: "gif", gifLoop: 3 });
418+
writeFileSync(outputPath, "GIF89a");
419+
};
420+
const projectDir = tmpProject();
421+
const outputPath = join(projectDir, "out.gif");
422+
server = createStudioServer({ projectDir });
423+
const state = server.adapter.startRender({
424+
...startRenderOpts("gif-job", outputPath),
425+
format: "gif",
426+
gifLoop: 3,
427+
});
428+
await vi.waitFor(() => expect(state.status, state.error).toBe("complete"));
429+
expect(readFileSync(outputPath, "utf8")).toBe("GIF89a");
430+
expect(JSON.parse(readFileSync(join(projectDir, "out.meta.json"), "utf8"))).toMatchObject({
431+
status: "complete",
432+
});
433+
});
434+
435+
it.each([false, true])(
436+
"removes cancelled GIF output and sidecar (late completion: %s)",
437+
async (lateCompletion) => {
438+
const projectDir = tmpProject();
439+
const outputPath = join(projectDir, "out.gif");
440+
const metaPath = join(projectDir, "out.meta.json");
441+
producerState.executeRenderJob = async (_job, _dir, output, _progress, signal) => {
442+
writeFileSync(output, "partial-gif");
443+
writeFileSync(metaPath, "{}");
444+
await waitForRenderCancellation(signal, lateCompletion);
445+
};
446+
server = createStudioServer({ projectDir });
447+
const state = server.adapter.startRender({
448+
...startRenderOpts("gif-job", outputPath),
449+
format: "gif",
450+
});
451+
await cancelAndVerifyArtifacts(state, outputPath, metaPath);
452+
},
453+
);
454+
411455
it("cancels an in-flight render's signal and waits for it before draining the browser pool", async () => {
412456
const events: string[] = [];
413457
let started!: () => void;

‎packages/cli/src/server/studioServer.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
646646
state.status = "cancelled";
647647
for (const suffix of ["", ".meta.json"]) {
648648
const fp = suffix
649-
? opts.outputPath.replace(/\.(mp4|webm|mov)$/, suffix)
649+
? opts.outputPath.replace(/\.(mp4|webm|mov|gif)$/, suffix)
650650
: opts.outputPath;
651651
try {
652652
if (existsSync(fp)) unlinkSync(fp);
@@ -670,6 +670,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
670670
fps: opts.fps,
671671
quality: opts.quality as "draft" | "standard" | "high",
672672
format: opts.format,
673+
...(opts.gifLoop !== undefined ? { gifLoop: opts.gifLoop } : {}),
673674
outputResolution: opts.outputResolution,
674675
...(manualEditsRenderScript ? { renderBodyScripts: [manualEditsRenderScript] } : {}),
675676
...(opts.composition ? { entryFile: opts.composition } : {}),
@@ -702,7 +703,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
702703
if (job.audioLoweredDb !== undefined) state.audioLoweredDb = job.audioLoweredDb;
703704
state.status = "complete";
704705
state.progress = 100;
705-
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov)$/, ".meta.json");
706+
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov|gif)$/, ".meta.json");
706707
writeFileSync(
707708
metaPath,
708709
JSON.stringify({
@@ -736,7 +737,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
736737
cpu.stop(),
737738
);
738739
try {
739-
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov)$/, ".meta.json");
740+
const metaPath = opts.outputPath.replace(/\.(mp4|webm|mov|gif)$/, ".meta.json");
740741
writeFileSync(metaPath, JSON.stringify({ status: "failed" }));
741742
} catch {
742743
/* ignore */

‎packages/studio-server/src/helpers/encoderOptions.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ const VIDEO_FRAME_FORMATS = ["auto", "jpg", "png"] as const;
44
const HDR_MODES = ["auto", "force-hdr", "force-sdr"] as const;
55

66
interface EncoderOptions {
7+
gifLoop?: number;
78
crf?: number;
89
videoBitrate?: string;
910
videoFrameFormat?: (typeof VIDEO_FRAME_FORMATS)[number];
1011
hdrMode?: (typeof HDR_MODES)[number];
1112
}
1213

1314
export interface EncoderOptionsBody {
15+
gifLoop?: unknown;
1416
crf?: unknown;
1517
videoBitrate?: unknown;
1618
videoFrameFormat?: unknown;
@@ -55,6 +57,17 @@ export function parseEncoderOptions(body: EncoderOptionsBody, format: string): P
5557
const rate = parseRateControl(body, format);
5658
if (!rate.ok) return rate;
5759
const options: EncoderOptions = { ...rate.options };
60+
if (isSet(body.gifLoop)) {
61+
if (
62+
typeof body.gifLoop !== "number" ||
63+
!Number.isInteger(body.gifLoop) ||
64+
body.gifLoop < 0 ||
65+
body.gifLoop > 65535
66+
) {
67+
return { ok: false, error: "gifLoop must be an integer from 0 to 65535" };
68+
}
69+
if (format === "gif") options.gifLoop = body.gifLoop;
70+
}
5871
if (isSet(body.videoFrameFormat)) {
5972
if (!oneOf(body.videoFrameFormat, VIDEO_FRAME_FORMATS)) {
6073
return {

‎packages/studio-server/src/history/uncopied.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,17 @@ describe("project history and media files", () => {
7171
expect(blobBytes(historyRoot, history)).toBeLessThan(1024);
7272
});
7373

74+
it("leaves GIF render outputs out of project history", async () => {
75+
const { history, historyRoot, projectDir, write } = await project({ "index.html": "A" });
76+
const render = await history.beginWindow(you, "Export GIF");
77+
write("renders/export.gif", Buffer.alloc(2 * MiB, 7));
78+
const entry = await render.close();
79+
expect(entry?.files ?? []).toEqual([]);
80+
expect(history.peek("start")).not.toHaveProperty(["renders/export.gif"]);
81+
expect(statSync(join(projectDir, "renders/export.gif")).size).toBe(2 * MiB);
82+
expect(blobBytes(historyRoot, history)).toBeLessThan(1024);
83+
});
84+
7485
it("copies no bytes of media written or replaced while history is open", async () => {
7586
const { history, historyRoot, write } = await project({ "index.html": "A" });
7687
const window = await history.beginWindow(you, "Render");

‎packages/studio-server/src/routes/render.test.ts‎

Lines changed: 124 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { afterEach, describe, expect, it, vi } from "vitest";
22
import { Hono } from "hono";
3-
import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from "node:fs";
3+
import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, existsSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { join } from "node:path";
66
import { VALID_CANVAS_RESOLUTIONS } from "@hyperframes/parsers";
@@ -1044,3 +1044,126 @@ describe("audioLoweredDb — the limiter's attenuation reaches the host", () =>
10441044
}
10451045
});
10461046
});
1047+
1048+
describe("Studio GIF renders", () => {
1049+
it.each([undefined, null, 0, 1, 65535])("accepts GIF with gifLoop %j", async (gifLoop) => {
1050+
const spy = vi.fn();
1051+
const { app, cleanup } = buildApp(spy);
1052+
try {
1053+
const res = await app.request("/projects/demo/render", {
1054+
method: "POST",
1055+
headers: { "content-type": "application/json" },
1056+
body: JSON.stringify({ format: "gif", gifLoop, gpu: true }),
1057+
});
1058+
expect(res.status).toBe(200);
1059+
expect(spy).toHaveBeenCalledWith(
1060+
expect.objectContaining({
1061+
format: "gif",
1062+
outputPath: expect.stringMatching(/\.gif$/),
1063+
useGpu: false,
1064+
...(typeof gifLoop === "number" ? { gifLoop } : {}),
1065+
}),
1066+
);
1067+
if (gifLoop == null) expect(spy.mock.calls[0][0]).not.toHaveProperty("gifLoop");
1068+
} finally {
1069+
cleanup();
1070+
}
1071+
});
1072+
1073+
it.each([-1, 65536, 1.5, "2", true, {}, []])(
1074+
"rejects invalid gifLoop %j before starting",
1075+
async (gifLoop) => {
1076+
const spy = vi.fn();
1077+
const { app, cleanup } = buildApp(spy);
1078+
try {
1079+
const res = await app.request("/projects/demo/render", {
1080+
method: "POST",
1081+
headers: { "content-type": "application/json" },
1082+
body: JSON.stringify({ format: "gif", gifLoop }),
1083+
});
1084+
expect(res.status).toBe(400);
1085+
expect(await res.json()).toEqual({ error: "gifLoop must be an integer from 0 to 65535" });
1086+
expect(spy).not.toHaveBeenCalled();
1087+
} finally {
1088+
cleanup();
1089+
}
1090+
},
1091+
);
1092+
1093+
it("leaves video exports unchanged when a valid GIF loop option is supplied", async () => {
1094+
const spy = vi.fn();
1095+
const { app, cleanup } = buildApp(spy);
1096+
try {
1097+
const res = await app.request("/projects/demo/render", {
1098+
method: "POST",
1099+
headers: { "content-type": "application/json" },
1100+
body: JSON.stringify({ format: "mp4", gifLoop: 3 }),
1101+
});
1102+
expect(res.status).toBe(200);
1103+
expect(spy.mock.calls[0][0]).not.toHaveProperty("gifLoop");
1104+
} finally {
1105+
cleanup();
1106+
}
1107+
});
1108+
1109+
it("lists a saved GIF after restart, serves image bytes, and deletes its sidecar", async () => {
1110+
const { app, rendersDir, cleanup } = buildApp(vi.fn());
1111+
try {
1112+
const output = join(rendersDir, "saved.gif");
1113+
const meta = join(rendersDir, "saved.meta.json");
1114+
writeFileSync(output, "GIF89a");
1115+
writeFileSync(meta, JSON.stringify({ status: "complete", durationMs: 42 }));
1116+
const list = await app.request("/projects/demo/renders");
1117+
expect(await list.json()).toMatchObject({
1118+
renders: [{ id: "saved", filename: "saved.gif", durationMs: 42 }],
1119+
});
1120+
for (const url of [
1121+
"/projects/demo/renders/file/saved.gif",
1122+
"/render/saved/view",
1123+
"/render/saved/download",
1124+
]) {
1125+
const res = await app.request(url);
1126+
expect(res.status).toBe(200);
1127+
expect(res.headers.get("content-type")).toBe("image/gif");
1128+
expect(await res.text()).toBe("GIF89a");
1129+
expect(res.headers.get("content-disposition")).toContain(
1130+
url.endsWith("download") ? "attachment" : "inline",
1131+
);
1132+
}
1133+
expect((await app.request("/render/saved", { method: "DELETE" })).status).toBe(200);
1134+
expect(existsSync(output)).toBe(false);
1135+
expect(existsSync(meta)).toBe(false);
1136+
expect(await (await app.request("/projects/demo/renders")).json()).toEqual({ renders: [] });
1137+
} finally {
1138+
cleanup();
1139+
}
1140+
});
1141+
});
1142+
1143+
describe("Studio GIF frame-rate cap", () => {
1144+
it.each([
1145+
{ format: "gif", fps: 60, expected: { num: 30, den: 1 } },
1146+
{ format: "gif", fps: "60000/1001", expected: { num: 30, den: 1 } },
1147+
{ format: "gif", fps: "30001/1000", expected: { num: 30, den: 1 } },
1148+
{ format: "gif", fps: "30000/1001", expected: { num: 30000, den: 1001 } },
1149+
{ format: "gif", fps: 30, expected: { num: 30, den: 1 } },
1150+
{ format: "gif", fps: 24, expected: { num: 24, den: 1 } },
1151+
{ format: "mp4", fps: 60, expected: { num: 60, den: 1 } },
1152+
{ format: "webm", fps: 60, expected: { num: 60, den: 1 } },
1153+
{ format: "mov", fps: 60, expected: { num: 60, den: 1 } },
1154+
])("forwards $format at $fps fps as $expected", async ({ format, fps, expected }) => {
1155+
const spy = vi.fn();
1156+
const { app, cleanup } = buildApp(spy);
1157+
try {
1158+
const res = await app.request("/projects/demo/render", {
1159+
method: "POST",
1160+
headers: { "content-type": "application/json" },
1161+
body: JSON.stringify({ format, fps }),
1162+
});
1163+
expect(res.status).toBe(200);
1164+
expect(spy).toHaveBeenCalledWith(expect.objectContaining({ format, fps: expected }));
1165+
} finally {
1166+
cleanup();
1167+
}
1168+
});
1169+
});

‎packages/studio-server/src/routes/render.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { existsSync, lstatSync, readFileSync, unlinkSync, readdirSync, statSync
44
import { dirname, join } from "node:path";
55
import type { StudioApiAdapter, RenderJobState } from "../types.js";
66
import { VALID_CANVAS_RESOLUTIONS, type CanvasResolution } from "@hyperframes/parsers";
7-
import { formatRenderOutputTimestamp, parseFps } from "@hyperframes/core";
7+
import { formatRenderOutputTimestamp, parseFps, fpsToNumber } from "@hyperframes/core";
88
import {
99
folderGone,
1010
isPrivateProjectFile,
@@ -20,6 +20,7 @@ const RENDER_MIME: Record<string, string> = {
2020
".mp4": "video/mp4",
2121
".webm": "video/webm",
2222
".mov": "video/quicktime",
23+
".gif": "image/gif",
2324
};
2425
const RENDER_EXTENSIONS = Object.keys(RENDER_MIME);
2526
const RENDER_ARTIFACT_EXTENSIONS = [...RENDER_EXTENSIONS, ".meta.json"];
@@ -111,16 +112,23 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
111112
previewMotionBlur?: boolean;
112113
pageMotionBlur?: unknown;
113114
};
114-
const VALID_FORMATS = new Set(["mp4", "webm", "mov"]);
115-
const FORMAT_EXT: Record<string, string> = { mp4: ".mp4", webm: ".webm", mov: ".mov" };
116-
const format = VALID_FORMATS.has(body.format ?? "") ? (body.format as string) : "mp4";
115+
const VALID_FORMATS = ["mp4", "webm", "mov", "gif"] as const;
116+
const FORMAT_EXT: Record<string, string> = {
117+
mp4: ".mp4",
118+
webm: ".webm",
119+
mov: ".mov",
120+
gif: ".gif",
121+
};
122+
const format = VALID_FORMATS.find((value) => value === body.format) ?? "mp4";
117123

118124
// Default to 30 fps when unset or unparseable. The route stays lenient on
119125
// invalid fps values (matching the lenient handling of `resolution` and
120126
// `quality` already in this file) — the producer surfaces a clearer error
121127
// message if the caller really did mean to fail loudly.
122128
const fpsParse = body.fps === undefined ? null : parseFps(body.fps);
123-
const fps = fpsParse && fpsParse.ok ? fpsParse.value : { num: 30, den: 1 };
129+
const requestedFps = fpsParse && fpsParse.ok ? fpsParse.value : { num: 30, den: 1 };
130+
const fps =
131+
format === "gif" && fpsToNumber(requestedFps) > 30 ? { num: 30, den: 1 } : requestedFps;
124132
const quality = ["draft", "standard", "high"].includes(body.quality ?? "")
125133
? (body.quality as string)
126134
: "standard";
@@ -171,7 +179,7 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
171179
const jobState = adapter.startRender({
172180
project,
173181
outputPath,
174-
format: format as "mp4" | "webm" | "mov",
182+
format,
175183
fps,
176184
quality,
177185
jobId,
@@ -346,14 +354,14 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
346354
const rendersDir = adapter.rendersDir(project);
347355
if (!existsSync(rendersDir)) return c.json({ renders: [] });
348356
const files = readdirSync(rendersDir)
349-
.filter((f) => f.endsWith(".mp4") || f.endsWith(".webm") || f.endsWith(".mov"))
357+
.filter((f) => RENDER_EXTENSIONS.some((extension) => f.endsWith(extension)))
350358
.flatMap((f) => {
351359
const fp = resolveWithinProject(rendersDir, f);
352360
return fp && !isPrivateProjectFile(project.dir, fp) ? [{ f, fp }] : [];
353361
})
354362
.map(({ f, fp }) => {
355363
const stat = statSync(fp);
356-
const rid = f.replace(/\.(mp4|webm|mov)$/, "");
364+
const rid = f.replace(/\.(mp4|webm|mov|gif)$/, "");
357365
const metaPath = join(rendersDir, `${rid}.meta.json`);
358366
let status: "complete" | "failed" = "complete";
359367
let durationMs: number | undefined;

‎packages/studio-server/src/types.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ export interface StudioApiAdapter {
165165
startRender(opts: {
166166
project: ResolvedProject;
167167
outputPath: string;
168-
format: "mp4" | "webm" | "mov";
168+
format: "mp4" | "webm" | "mov" | "gif";
169169
/**
170170
* Frame rate as an exact rational. The HTTP layer (POST
171171
* `/projects/:id/render`) accepts either a JSON number (integer fps,
@@ -175,6 +175,7 @@ export interface StudioApiAdapter {
175175
*/
176176
fps: import("@hyperframes/core").Fps;
177177
quality: string;
178+
gifLoop?: number;
178179
crf?: number;
179180
videoBitrate?: string;
180181
videoFrameFormat?: "auto" | "jpg" | "png";

0 commit comments

Comments
 (0)