Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): preserve playback timing in long GIF conversions

Akshar Patel476d082e3d5c
diff --git a/apps/web/__tests__/fixtures/gif-24s.mp4 b/apps/web/__tests__/fixtures/gif-24s.mp4
new file mode 100644
index 000000000..bbe697d08
Binary files /dev/null and b/apps/web/__tests__/fixtures/gif-24s.mp4 differ
diff --git a/apps/web/__tests__/fixtures/gif-6s.mp4 b/apps/web/__tests__/fixtures/gif-6s.mp4
new file mode 100644
index 000000000..3741e0450
Binary files /dev/null and b/apps/web/__tests__/fixtures/gif-6s.mp4 differ
diff --git a/apps/web/__tests__/unit/media-format-converter.test.ts b/apps/web/__tests__/unit/media-format-converter.test.ts
index 720d504e9..8f19dbe90 100644
--- a/apps/web/__tests__/unit/media-format-converter.test.ts
+++ b/apps/web/__tests__/unit/media-format-converter.test.ts
@@ -26,6 +26,22 @@ vi.mock("next/navigation", () => ({
}));
vi.mock("@/app/utils/analytics", () => ({ trackEvent: vi.fn() }));
+const frameDelays = vi.hoisted(() => [] as number[]);
+vi.mock("gif.js", () => ({
+ default: class {
+ private finish?: (blob: Blob) => void;
+ addFrame(_canvas: HTMLCanvasElement, options: { delay: number }) {
+ frameDelays.push(options.delay);
+ }
+ on(event: string, callback: (blob: Blob) => void) {
+ if (event === "finished") this.finish = callback;
+ }
+ render() {
+ this.finish?.(new Blob(["encoded GIF"], { type: "image/gif" }));
+ }
+ },
+}));
+
let root: Root;
let container: HTMLDivElement;
let output: Parameters<typeof URL.createObjectURL>[0] | undefined;
@@ -41,6 +57,7 @@ beforeEach(() => {
vi.stubGlobal("MediaRecorder", { isTypeSupported: () => false });
vi.spyOn(console, "log").mockImplementation(() => {});
output = undefined;
+ frameDelays.length = 0;
originalCreate = URL.createObjectURL;
originalRevoke = URL.revokeObjectURL;
URL.createObjectURL = (blob) => {
@@ -98,3 +115,84 @@ it("converts a MOV to a downloadable MP4 using Remotion", async () => {
expect(metadata.durationInSeconds).toBeGreaterThan(0);
expect(container.textContent).toContain("Download MP4");
});
+
+it.each([
+ { duration: 24, frames: 150 },
+ { duration: 6, frames: 60 },
+])(
+ "preserves a $duration-second video's GIF duration",
+ async ({ duration, frames }) => {
+ vi.stubGlobal("MediaRecorder", { isTypeSupported: () => true });
+ vi.spyOn(HTMLMediaElement.prototype, "duration", "get").mockReturnValue(
+ duration,
+ );
+ vi.spyOn(HTMLMediaElement.prototype, "src", "set").mockImplementation(
+ function () {
+ queueMicrotask(() => this.dispatchEvent(new Event("loadedmetadata")));
+ },
+ );
+ vi.spyOn(
+ HTMLMediaElement.prototype,
+ "currentTime",
+ "set",
+ ).mockImplementation(function () {
+ queueMicrotask(() => this.dispatchEvent(new Event("seeked")));
+ });
+ vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue();
+ vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
+ drawImage: vi.fn(),
+ } as unknown as CanvasRenderingContext2D);
+ const bytes = await readFile(
+ join(__dirname, `../fixtures/gif-${duration}s.mp4`),
+ );
+ root.render(
+ createElement(MediaFormatConverter, {
+ initialConversionPath: "mp4-to-gif",
+ }),
+ );
+ await vi.waitFor(() =>
+ expect(container.querySelector("input[type=file]")).not.toBeNull(),
+ );
+ const fpsInput = Array.from(container.querySelectorAll("label"))
+ .find((label) => label.textContent === "Frames Per Second")
+ ?.parentElement?.querySelector("input");
+ if (!(fpsInput instanceof HTMLInputElement))
+ throw new Error("Missing FPS slider");
+ const setValue = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ "value",
+ )?.set;
+ setValue?.call(fpsInput, "10");
+ fpsInput.dispatchEvent(new Event("input", { bubbles: true }));
+ const input = container.querySelector(
+ "input[type=file]",
+ ) as HTMLInputElement;
+ Object.defineProperty(input, "files", {
+ value: [
+ new File([bytes], `clip-${duration}s.mp4`, { type: "video/mp4" }),
+ ],
+ });
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ await vi.waitFor(() =>
+ expect(container.textContent).toContain(`clip-${duration}s.mp4`),
+ );
+ const convert = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Convert to GIF",
+ );
+ if (!convert) throw new Error("Missing GIF conversion action");
+ convert.click();
+ await vi.waitFor(() =>
+ expect(container.textContent).toContain("Conversion complete!"),
+ );
+ expect(frameDelays).toHaveLength(frames);
+ expect(frameDelays.reduce((total, delay) => total + delay, 0)).toBeCloseTo(
+ duration * 1000,
+ );
+ if (!(output instanceof globalThis.Blob)) {
+ throw new Error("No converted GIF was saved");
+ }
+ expect(output.type).toBe("image/gif");
+ expect(container.textContent).toContain("Download GIF");
+ },
+);
diff --git a/apps/web/components/tools/MediaFormatConverter.tsx b/apps/web/components/tools/MediaFormatConverter.tsx
index fd184a168..942a30802 100644
--- a/apps/web/components/tools/MediaFormatConverter.tsx
+++ b/apps/web/components/tools/MediaFormatConverter.tsx
@@ -492,7 +492,7 @@ export const MediaFormatConverter = ({
const videoDuration = videoElement.duration;
const fps = gifFps;
const frameCount = Math.min(Math.floor(videoDuration * fps), gifFps * 15);
- const frameDelay = 1000 / fps;
+ const frameDelay = (videoDuration * 1000) / frameCount;
const canvas = document.createElement("canvas");
canvas.width = targetWidth;