Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: GIF generation + copy changes

Richie McIlroy2008c06491ac
diff --git a/apps/web/app/tools/convert/[conversionPath]/page.tsx b/apps/web/app/tools/convert/[conversionPath]/page.tsx
index f4969ae98..a2d651692 100644
--- a/apps/web/app/tools/convert/[conversionPath]/page.tsx
+++ b/apps/web/app/tools/convert/[conversionPath]/page.tsx
@@ -89,13 +89,13 @@ export default function ConversionPage({ params }: ConversionPageProps) {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to ensure high-quality conversion results.",
+ "We use browser technology to ensure high-quality and fast conversion results.",
},
],
faqs: [
{
question: `How does the ${sourceFormat.toUpperCase()} to ${targetFormat.toUpperCase()} converter work?`,
- answer: `Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload a ${sourceFormat.toUpperCase()} file, it gets processed locally on your device and converted to ${targetFormat.toUpperCase()} format without ever being sent to a server.`,
+ answer: `Our converter uses Remotion (remotion.dev) directly in your browser. When you upload a ${sourceFormat.toUpperCase()} file, it gets processed locally on your device and converted to ${targetFormat.toUpperCase()} format without ever being sent to a server.`,
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/convert/avi-to-mp4/page.tsx b/apps/web/app/tools/convert/avi-to-mp4/page.tsx
index 19a8600b0..f60890727 100644
--- a/apps/web/app/tools/convert/avi-to-mp4/page.tsx
+++ b/apps/web/app/tools/convert/avi-to-mp4/page.tsx
@@ -50,14 +50,14 @@ export default function AVIToMP4Page() {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to ensure high-quality conversion results.",
+ "We use browser technology to ensure high-quality and fast conversion results.",
},
],
faqs: [
{
question: "How does the AVI to MP4 converter work?",
answer:
- "Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload an AVI file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
+ "Our converter uses Remotion (remotion.dev) directly in your browser. When you upload an AVI file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/convert/mkv-to-mp4/page.tsx b/apps/web/app/tools/convert/mkv-to-mp4/page.tsx
index 7aa2d39ad..6af26e66c 100644
--- a/apps/web/app/tools/convert/mkv-to-mp4/page.tsx
+++ b/apps/web/app/tools/convert/mkv-to-mp4/page.tsx
@@ -50,14 +50,14 @@ export default function MKVToMP4Page() {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to ensure high-quality conversion results.",
+ "We use browser technology to ensure high-quality and fast conversion results.",
},
],
faqs: [
{
question: "How does the MKV to MP4 converter work?",
answer:
- "Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload an MKV file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
+ "Our converter uses Remotion (remotion.dev) directly in your browser. When you upload an MKV file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/convert/mov-to-mp4/page.tsx b/apps/web/app/tools/convert/mov-to-mp4/page.tsx
index 0df1961a1..5ddd03e31 100644
--- a/apps/web/app/tools/convert/mov-to-mp4/page.tsx
+++ b/apps/web/app/tools/convert/mov-to-mp4/page.tsx
@@ -50,14 +50,14 @@ export default function MOVToMP4Page() {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to ensure high-quality conversion results.",
+ "We use browser technology to ensure high-quality and fast conversion results.",
},
],
faqs: [
{
question: "How does the MOV to MP4 converter work?",
answer:
- "Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload a MOV file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
+ "Our converter uses Remotion (remotion.dev) directly in your browser. When you upload a MOV file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/convert/mp4-to-gif/page.tsx b/apps/web/app/tools/convert/mp4-to-gif/page.tsx
index e478f2431..5a8f0040b 100644
--- a/apps/web/app/tools/convert/mp4-to-gif/page.tsx
+++ b/apps/web/app/tools/convert/mp4-to-gif/page.tsx
@@ -51,14 +51,14 @@ export default function MP4ToGIFPage() {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to create optimized GIFs from your videos.",
+ "We use Remotion technology to create optimized GIFs from your videos.",
},
],
faqs: [
{
question: "How does the MP4 to GIF converter work?",
answer:
- "Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload an MP4 file, it gets processed locally on your device and converted to an animated GIF without ever being sent to a server.",
+ "Our converter uses Remotion (remotion.dev) directly in your browser. When you upload an MP4 file, it gets processed locally on your device and converted to an animated GIF without ever being sent to a server.",
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/convert/mp4-to-mp3/page.tsx b/apps/web/app/tools/convert/mp4-to-mp3/page.tsx
index 645c9fc8e..c49ae71af 100644
--- a/apps/web/app/tools/convert/mp4-to-mp3/page.tsx
+++ b/apps/web/app/tools/convert/mp4-to-mp3/page.tsx
@@ -50,14 +50,14 @@ export default function MP4ToMP3Page() {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to ensure high-quality audio extraction.",
+ "We use Remotion technology to ensure high-quality audio extraction.",
},
],
faqs: [
{
question: "How does the MP4 to MP3 converter work?",
answer:
- "Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload an MP4 file, it extracts the audio track locally on your device and saves it as an MP3 file without ever being sent to a server.",
+ "Our converter uses Remotion (remotion.dev) directly in your browser. When you upload an MP4 file, it extracts the audio track locally on your device and saves it as an MP3 file without ever being sent to a server.",
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/convert/mp4-to-webm/page.tsx b/apps/web/app/tools/convert/mp4-to-webm/page.tsx
index 1b717f074..44ab1b0f2 100644
--- a/apps/web/app/tools/convert/mp4-to-webm/page.tsx
+++ b/apps/web/app/tools/convert/mp4-to-webm/page.tsx
@@ -50,14 +50,14 @@ export default function MP4ToWebMPage() {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to ensure high-quality conversion results.",
+ "We use browser technology to ensure high-quality and fast conversion results.",
},
],
faqs: [
{
question: "How does the MP4 to WebM converter work?",
answer:
- "Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload an MP4 file, it gets processed locally on your device and converted to WebM format without ever being sent to a server.",
+ "Our converter uses Remotion (remotion.dev) directly in your browser. When you upload an MP4 file, it gets processed locally on your device and converted to WebM format without ever being sent to a server.",
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/convert/webm-to-mp4/page.tsx b/apps/web/app/tools/convert/webm-to-mp4/page.tsx
index 9293e23f9..fb41ef09e 100644
--- a/apps/web/app/tools/convert/webm-to-mp4/page.tsx
+++ b/apps/web/app/tools/convert/webm-to-mp4/page.tsx
@@ -50,14 +50,14 @@ export default function WebmToMp4Page() {
{
title: "High Quality Conversion",
description:
- "We use industry-standard FFmpeg technology to ensure high-quality conversion results.",
+ "We use browser technology to ensure high-quality and fast conversion results.",
},
],
faqs: [
{
question: "How does the WebM to MP4 converter work?",
answer:
- "Our converter uses WebAssembly to run FFmpeg directly in your browser. When you upload a WebM file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
+ "Our converter uses Remotion (remotion.dev) directly in your browser. When you upload a WebM file, it gets processed locally on your device and converted to MP4 format without ever being sent to a server.",
},
{
question: "Is there a file size limit?",
diff --git a/apps/web/app/tools/video-speed-controller/page.tsx b/apps/web/app/tools/video-speed-controller/page.tsx
index 2dcdc5191..e6c9d1ccb 100644
--- a/apps/web/app/tools/video-speed-controller/page.tsx
+++ b/apps/web/app/tools/video-speed-controller/page.tsx
@@ -7,7 +7,7 @@ const content = {
"Instantly speed up or slow down any MP4, WebM or MOV in your browser. No uploads, no quality loss.",
featuresTitle: "Why Use Our Online Video Speed Controller?",
featuresDescription:
- "Powered by WebCodecs + WebAssembly, Cap processes every frame locally for near-instant results—while keeping your files 100% private.",
+ "Powered by WebCodecs + Remotion, Cap processes every frame locally for near-instant results—while keeping your files 100% private.",
features: [
{
title: "WebCodecs-Level Speed",
@@ -43,7 +43,7 @@ const content = {
{
question: "Why is processing still slow on my laptop?",
answer:
- "WebCodecs relies on your device’s hardware. Older CPUs/GPUs or throttled mobiles will take longer.",
+ "WebCodecs relies on your device's hardware. Older CPUs/GPUs or throttled mobiles will take longer.",
},
{
question: "Can I use this on iOS / Android?",
diff --git a/apps/web/components/tools/MediaFormatConverter.tsx b/apps/web/components/tools/MediaFormatConverter.tsx
index af58ae437..27f46d61c 100644
--- a/apps/web/components/tools/MediaFormatConverter.tsx
+++ b/apps/web/components/tools/MediaFormatConverter.tsx
@@ -5,6 +5,8 @@ import { Button } from "@cap/ui";
import { trackEvent } from "@/app/utils/analytics";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
+import * as MediaParser from "@remotion/media-parser";
+import type { WebCodecsController } from "@remotion/webcodecs";
export const SUPPORTED_FORMATS = {
video: ["mp4", "webm", "mov", "avi", "mkv"],
@@ -167,13 +169,17 @@ export const MediaFormatConverter = ({
const [isSafari, setIsSafari] = useState(false);
const [isFirefox, setIsFirefox] = useState(false);
+ const [gifQuality, setGifQuality] = useState(18);
+ const [gifFps, setGifFps] = useState(15);
+ const [gifMaxWidth, setGifMaxWidth] = useState(1280);
+ const [gifDithering, setGifDithering] = useState(false);
+
const conversionPath = `${currentSourceFormat}-to-${currentTargetFormat}`;
const config = CONVERSION_CONFIGS[conversionPath];
const fileInputRef = useRef<HTMLInputElement>(null);
- const videoRef = useRef<HTMLVideoElement | null>(null);
- const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const recordedChunksRef = useRef<Blob[]>([]);
+ const parserControllerRef = useRef<{ abort: () => void } | null>(null);
useEffect(() => {
if (
@@ -219,6 +225,23 @@ export const MediaFormatConverter = ({
setIsFirefox(isFirefoxBrowser);
}, []);
+ useEffect(() => {
+ const loadRemotionModules = async () => {
+ try {
+ const parser = await import("@remotion/media-parser");
+ setMediaEngineLoaded(true);
+ } catch (error) {
+ console.error("Failed to load Remotion modules:", error);
+ setMediaEngineLoaded(false);
+ setError(
+ "Failed to load media conversion engine. Please try again later."
+ );
+ }
+ };
+
+ loadRemotionModules();
+ }, []);
+
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];
if (selectedFile) {
@@ -304,6 +327,11 @@ export const MediaFormatConverter = ({
setError(null);
setProgress(0);
+ if (parserControllerRef.current) {
+ parserControllerRef.current.abort();
+ }
+ parserControllerRef.current = { abort: () => {} };
+
trackEvent(`${conversionPath}_conversion_started`, {
fileSize: file.size,
fileName: file.name,
@@ -313,252 +341,346 @@ export const MediaFormatConverter = ({
console.log(`Starting conversion: ${conversionPath}`);
console.log(`Input file: ${file.name}, size: ${file.size} bytes`);
- const fileUrl = URL.createObjectURL(file);
-
if (currentTargetFormat === "mp3" && currentSourceFormat === "mp4") {
- await extractAudioFromVideo(fileUrl);
+ await extractAudioFromVideo(file);
} else if (
currentTargetFormat === "gif" &&
currentSourceFormat === "mp4"
) {
- await convertVideoToGif(fileUrl);
+ await convertVideoToGif(file);
} else {
- await convertVideoFormat(fileUrl);
+ await convertVideoFormat(file);
}
-
- URL.revokeObjectURL(fileUrl);
} catch (err: any) {
console.error("Detailed conversion error:", err);
- let errorMessage = "Conversion failed: ";
- if (err.message) {
- errorMessage += err.message;
- } else if (typeof err === "string") {
- errorMessage += err;
+ if (MediaParser.hasBeenAborted && MediaParser.hasBeenAborted(err)) {
+ setError("Conversion was cancelled");
} else {
- errorMessage += "Unknown error occurred during conversion";
- }
+ let errorMessage = "Conversion failed: ";
+ if (err.message) {
+ errorMessage += err.message;
+ } else if (typeof err === "string") {
+ errorMessage += err;
+ } else {
+ errorMessage += "Unknown error occurred during conversion";
+ }
- setError(errorMessage);
+ setError(errorMessage);
- trackEvent(`${conversionPath}_conversion_failed`, {
- fileSize: file.size,
- fileName: file.name,
- error: err.message || "Unknown error",
- });
+ trackEvent(`${conversionPath}_conversion_failed`, {
+ fileSize: file.size,
+ fileName: file.name,
+ error: err.message || "Unknown error",
+ });
+ }
} finally {
setIsConverting(false);
+ parserControllerRef.current = null;
}
};
- const extractAudioFromVideo = async (fileUrl: string): Promise<void> => {
- return new Promise((resolve, reject) => {
- const audio = new Audio();
- audio.src = fileUrl;
- audio.muted = false;
+ const extractAudioFromVideo = async (inputFile: File): Promise<void> => {
+ try {
+ const parser = await import("@remotion/media-parser");
+ const webcodecs = await import("@remotion/webcodecs");
+
+ const handleProgress = (progressEvent: { progress: number }) => {
+ setProgress(Math.min(Math.round(progressEvent.progress * 100), 99));
+ };
- const audioContext = new AudioContext();
- const mediaSource = audioContext.createMediaElementSource(audio);
- const destination = audioContext.createMediaStreamDestination();
- mediaSource.connect(destination);
+ const controller = parser.mediaParserController
+ ? parser.mediaParserController()
+ : null;
+ parserControllerRef.current = controller;
+
+ const result = await webcodecs.convertMedia({
+ src: inputFile,
+ container: "wav",
+ onProgress: ({ overallProgress }) => {
+ if (overallProgress !== null) {
+ setProgress(Math.min(Math.round(overallProgress * 100), 99));
+ }
+ },
+ controller: controller as unknown as WebCodecsController,
+ });
- const recorder = new MediaRecorder(destination.stream);
- const chunks: BlobPart[] = [];
+ const blob = await result.save();
+ const url = URL.createObjectURL(blob);
+ setOutputUrl(url);
+ setProgress(100);
- recorder.ondataavailable = (e) => {
- if (e.data.size > 0) {
- chunks.push(e.data);
+ trackEvent(`${conversionPath}_conversion_completed`, {
+ fileSize: file!.size,
+ fileName: file!.name,
+ outputSize: blob.size,
+ });
+ } catch (error) {
+ console.error("Error extracting audio:", error);
+ throw error;
+ }
+ };
+
+ const convertVideoToGif = async (inputFile: File): Promise<void> => {
+ try {
+ const parser = await import("@remotion/media-parser");
+ const webcodecs = await import("@remotion/webcodecs");
+
+ const onProgress = ({
+ overallProgress,
+ }: {
+ overallProgress: number | null;
+ }) => {
+ if (overallProgress !== null) {
+ setProgress(Math.min(Math.round(overallProgress * 100), 99));
}
};
- recorder.onstop = () => {
- const blob = new Blob(chunks, { type: "audio/mp3" });
- const url = URL.createObjectURL(blob);
- setOutputUrl(url);
+ const controller = parser.mediaParserController
+ ? parser.mediaParserController()
+ : null;
+ parserControllerRef.current = controller;
+
+ console.log(`Starting video to GIF conversion`);
+ console.log(
+ `Input file: ${inputFile.name}, size: ${inputFile.size} bytes`
+ );
+
+ const isCanvasSupported = !!document
+ .createElement("canvas")
+ .getContext("2d");
+ if (!isCanvasSupported) {
+ throw new Error(
+ "Your browser doesn't support canvas operations required for GIF conversion"
+ );
+ }
- trackEvent(`${conversionPath}_conversion_completed`, {
- fileSize: file!.size,
- fileName: file!.name,
- outputSize: blob.size,
- });
+ const metadata = await parser.parseMedia({
+ src: inputFile,
+ fields: {
+ durationInSeconds: true,
+ dimensions: true,
+ videoCodec: true,
+ },
+ });
- resolve();
- };
+ console.log("Video metadata for GIF conversion:", metadata);
- recorder.onerror = (e) => {
- reject(new Error("Error recording audio"));
- };
+ const originalWidth = metadata.dimensions?.width || 1920;
+ const originalHeight = metadata.dimensions?.height || 1080;
+ const maxWidth = gifMaxWidth;
+ const scale = originalWidth > maxWidth ? maxWidth / originalWidth : 1;
+ const targetWidth = Math.floor(originalWidth * scale);
+ const targetHeight = Math.floor(originalHeight * scale);
- audio.oncanplaythrough = () => {
- recorder.start();
- audio.play();
+ const GifModule = await import("gif.js");
+ const GIF = GifModule.default;
- const interval = setInterval(() => {
- if (audio.duration) {
- const currentProgress = (audio.currentTime / audio.duration) * 100;
- setProgress(Math.min(Math.round(currentProgress), 99));
- }
- }, 500);
+ const videoElement = document.createElement("video");
+ videoElement.muted = true;
+ videoElement.playsInline = true;
+ videoElement.src = URL.createObjectURL(inputFile);
- audio.onended = () => {
- clearInterval(interval);
- recorder.stop();
- setProgress(100);
- };
- };
+ await new Promise((resolve) => {
+ videoElement.onloadedmetadata = () => resolve(null);
+ });
+
+ const videoDuration = videoElement.duration;
+ const fps = gifFps;
+ const frameCount = Math.min(Math.floor(videoDuration * fps), gifFps * 15);
+ const frameDelay = 1000 / fps;
+
+ const canvas = document.createElement("canvas");
+ canvas.width = targetWidth;
+ canvas.height = targetHeight;
+ const ctx = canvas.getContext("2d");
- audio.onerror = () => {
- reject(new Error("Error loading audio from video"));
+ if (!ctx) {
+ throw new Error("Failed to get canvas context");
+ }
+
+ const gifEncoder = new GIF({
+ workers: 2,
+ quality: gifQuality,
+ width: targetWidth,
+ height: targetHeight,
+ workerScript: "/gif.worker.js",
+ dither: gifDithering,
+ });
+
+ const captureFrame = async (time: number): Promise<void> => {
+ return new Promise((resolve) => {
+ videoElement.currentTime = time;
+ videoElement.onseeked = () => {
+ ctx.drawImage(videoElement, 0, 0, targetWidth, targetHeight);
+ gifEncoder.addFrame(canvas, { delay: frameDelay, copy: true });
+ resolve();
+ };
+ });
};
- });
- };
- const convertVideoToGif = async (fileUrl: string): Promise<void> => {
- setError(
- "Converting video to GIF is currently not fully supported in the browser version. Please try using Google Chrome."
- );
- setProgress(100);
- return Promise.resolve();
- };
+ gifEncoder.on("progress", (progress: number) => {
+ setProgress(Math.min(Math.round(progress * 90 + 5), 95));
+ });
- const convertVideoFormat = async (fileUrl: string): Promise<void> => {
- return new Promise((resolve, reject) => {
- const video = document.createElement("video");
- videoRef.current = video;
- video.src = fileUrl;
- video.muted = false;
-
- video.oncanplay = async () => {
- try {
- const canvas = document.createElement("canvas");
- canvas.width = video.videoWidth;
- canvas.height = video.videoHeight;
- const ctx = canvas.getContext("2d");
-
- if (!ctx) {
- throw new Error("Failed to create canvas context");
- }
+ await videoElement.play();
+ videoElement.pause();
- const targetMimeType = getMimeType(currentTargetFormat);
-
- const mimeTypes =
- isFirefox && currentTargetFormat === "mp4"
- ? [
- "video/webm;codecs=vp8,opus",
- "video/webm;codecs=vp8",
- "video/webm",
- ]
- : [
- targetMimeType,
- "video/webm;codecs=vp9",
- "video/webm;codecs=vp8",
- "video/webm",
- "video/mp4",
- ];
-
- let selectedMimeType = "";
- for (const type of mimeTypes) {
- if (MediaRecorder.isTypeSupported(type)) {
- selectedMimeType = type;
- break;
- }
- }
+ setProgress(5);
- if (!selectedMimeType) {
- throw new Error(
- "None of the media formats are supported by this browser"
- );
- }
+ const frameInterval = videoDuration / frameCount;
+ for (let i = 0; i < frameCount; i++) {
+ const frameTime = i * frameInterval;
+ await captureFrame(frameTime);
- if (
- isFirefox &&
- currentSourceFormat === "webm" &&
- currentTargetFormat === "mp4"
- ) {
- console.warn(
- "Firefox has limited support for MP4 encoding. Using WebM container instead."
- );
- }
+ const captureProgress = (i / frameCount) * 45;
+ setProgress(Math.min(Math.round(5 + captureProgress), 50));
+ }
- const stream = canvas.captureStream(30);
-
- video.muted = true;
- try {
- const audioContext = new AudioContext();
- const source = audioContext.createMediaElementSource(video);
- const destination = audioContext.createMediaStreamDestination();
- source.connect(destination);
-
- destination.stream.getAudioTracks().forEach((track) => {
- stream.addTrack(track);
- });
- } catch (audioErr) {
- console.warn(
- "Could not add audio track, continuing without audio",
- audioErr
- );
- }
+ setProgress(50);
- const recorder = new MediaRecorder(stream, {
- mimeType: selectedMimeType,
- });
- mediaRecorderRef.current = recorder;
- recordedChunksRef.current = [];
+ const gifBlob = await new Promise<Blob>((resolve) => {
+ gifEncoder.on("finished", (blob: Blob) => {
+ resolve(blob);
+ });
+ gifEncoder.render();
+ });
- recorder.ondataavailable = (e) => {
- if (e.data.size > 0) {
- recordedChunksRef.current.push(e.data);
- }
- };
+ URL.revokeObjectURL(videoElement.src);
+
+ const gifUrl = URL.createObjectURL(gifBlob);
+ setOutputUrl(gifUrl);
+ setProgress(100);
- recorder.onstop = () => {
- const chunks = recordedChunksRef.current;
- const outputMimeType = selectedMimeType.split(";")[0];
- const blob = new Blob(chunks, { type: outputMimeType });
- const url = URL.createObjectURL(blob);
+ recordedChunksRef.current = [gifBlob];
- setOutputUrl(url);
+ trackEvent(`${conversionPath}_conversion_completed`, {
+ fileSize: file!.size,
+ fileName: file!.name,
+ outputSize: gifBlob.size,
+ });
+ } catch (error) {
+ console.error("Error converting video to GIF:", error);
- trackEvent(`${conversionPath}_conversion_completed`, {
- fileSize: file!.size,
- fileName: file!.name,
- outputSize: blob.size,
- });
+ if (MediaParser.hasBeenAborted && MediaParser.hasBeenAborted(error)) {
+ setError("Conversion was cancelled");
+ } else {
+ let errorMessage = "GIF conversion failed: ";
+
+ if (error instanceof Error) {
+ errorMessage += error.message;
+ } else if (typeof error === "string") {
+ errorMessage += error;
+ } else {
+ errorMessage += "Unknown error occurred during conversion";
+ }
- videoRef.current = null;
- mediaRecorderRef.current = null;
- resolve();
- };
+ setError(errorMessage);
+ }
- recorder.start(1000);
- video.play();
-
- const interval = setInterval(() => {
- if (video.duration) {
- const currentProgress =
- (video.currentTime / video.duration) * 100;
- setProgress(Math.min(Math.round(currentProgress), 99));
-
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
- }
- }, 30);
-
- video.onended = () => {
- clearInterval(interval);
- setTimeout(() => {
- recorder.stop();
- setProgress(100);
- }, 500);
- };
- } catch (err) {
- reject(err);
+ throw error;
+ }
+ };
+
+ const convertVideoFormat = async (inputFile: File): Promise<void> => {
+ try {
+ const parser = await import("@remotion/media-parser");
+ const webcodecs = await import("@remotion/webcodecs");
+
+ const onProgress = ({
+ overallProgress,
+ }: {
+ overallProgress: number | null;
+ }) => {
+ if (overallProgress !== null) {
+ setProgress(Math.min(Math.round(overallProgress * 100), 99));
}
};
- video.onerror = () => {
- reject(new Error("Error loading video"));
- };
- });
+ const controller = parser.mediaParserController
+ ? parser.mediaParserController()
+ : null;
+ parserControllerRef.current = controller;
+
+ console.log(`Starting conversion with Remotion: ${conversionPath}`);
+ console.log(
+ `Input file: ${inputFile.name}, size: ${inputFile.size} bytes`
+ );
+
+ const canUseWebCodecs =
+ typeof VideoDecoder !== "undefined" &&
+ typeof AudioDecoder !== "undefined" &&
+ typeof ArrayBuffer.prototype.resize === "function";
+
+ if (!canUseWebCodecs) {
+ throw new Error(
+ "Your browser doesn't support WebCodecs. Try using Chrome or Edge."
+ );
+ }
+
+ const metadata = await parser.parseMedia({
+ src: inputFile,
+ fields: {
+ durationInSeconds: true,
+ dimensions: true,
+ videoCodec: true,
+ },
+ });
+
+ console.log("Video metadata:", metadata);
+
+ const outputContainer = currentTargetFormat === "webm" ? "webm" : "mp4";
+
+ let videoCodec;
+ if (outputContainer === "webm") {
+ videoCodec = "vp8";
+ } else {
+ videoCodec = "h264";
+ }
+
+ const result = await webcodecs.convertMedia({
+ src: inputFile,
+ container: outputContainer as any,
+ videoCodec: videoCodec as any,
+ onProgress,
+ controller: controller as unknown as WebCodecsController,
+ expectedDurationInSeconds: metadata.durationInSeconds || undefined,
+ });
+
+ const blob = await result.save();
+ const url = URL.createObjectURL(blob);
+
+ setOutputUrl(url);
+ setProgress(100);
+
+ recordedChunksRef.current = [blob];
+
+ trackEvent(`${conversionPath}_conversion_completed`, {
+ fileSize: file!.size,
+ fileName: file!.name,
+ outputSize: blob.size,
+ });
+ } catch (error) {
+ console.error("Error converting video format:", error);
+
+ if (MediaParser.hasBeenAborted && MediaParser.hasBeenAborted(error)) {
+ setError("Conversion was cancelled");
+ } else {
+ let errorMessage = "Conversion failed: ";
+
+ if (error instanceof Error) {
+ errorMessage += error.message;
+ } else if (typeof error === "string") {
+ errorMessage += error;
+ } else {
+ errorMessage += "Unknown error occurred during conversion";
+ }
+
+ setError(errorMessage);
+ }
+
+ throw error;
+ }
};
const handleDownload = () => {
@@ -605,16 +727,9 @@ export const MediaFormatConverter = ({
URL.revokeObjectURL(outputUrl);
}
- if (
- mediaRecorderRef.current &&
- mediaRecorderRef.current.state !== "inactive"
- ) {
- mediaRecorderRef.current.stop();
- }
-
- if (videoRef.current) {
- videoRef.current.pause();
- videoRef.current.src = "";
+ if (parserControllerRef.current) {
+ parserControllerRef.current.abort();
+ parserControllerRef.current = null;
}
setFile(null);
@@ -755,6 +870,90 @@ export const MediaFormatConverter = ({
</div>
</div>
+ {currentTargetFormat === "gif" && (
+ <div className="mb-6 border border-gray-200 rounded-lg p-4">
+ <h3 className="text-lg font-medium mb-3">GIF Settings</h3>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm font-medium text-gray-700 mb-1">
+ Quality (Lower is better)
+ </label>
+ <div className="flex items-center">
+ <input
+ type="range"
+ min="1"
+ max="20"
+ value={gifQuality}
+ onChange={(e) => setGifQuality(parseInt(e.target.value))}
+ className="w-full"
+ />
+ <span className="ml-2 text-sm w-8 text-gray-600">
+ {gifQuality}
+ </span>
+ </div>
+ <p className="text-xs text-gray-500 mt-1">
+ Lower values produce higher quality GIFs but larger file sizes
+ </p>
+ </div>
+ <div>
+ <label className="block text-sm font-medium text-gray-700 mb-1">
+ Frames Per Second
+ </label>
+ <div className="flex items-center">
+ <input
+ type="range"
+ min="5"
+ max="30"
+ value={gifFps}
+ onChange={(e) => setGifFps(parseInt(e.target.value))}
+ className="w-full"
+ />
+ <span className="ml-2 text-sm w-8 text-gray-600">{gifFps}</span>
+ </div>
+ <p className="text-xs text-gray-500 mt-1">
+ Higher values create smoother animations but larger files
+ </p>
+ </div>
+ <div>
+ <label className="block text-sm font-medium text-gray-700 mb-1">
+ Max Width (px)
+ </label>
+ <div className="flex items-center">
+ <input
+ type="range"
+ min="240"
+ max="1280"
+ step="80"
+ value={gifMaxWidth}
+ onChange={(e) => setGifMaxWidth(parseInt(e.target.value))}
+ className="w-full"
+ />
+ <span className="ml-2 text-sm w-10 text-gray-600">
+ {gifMaxWidth}
+ </span>
+ </div>
+ <p className="text-xs text-gray-500 mt-1">
+ Larger sizes give higher resolution but increase file size
+ </p>
+ </div>
+ <div>
+ <label className="flex items-center text-sm font-medium text-gray-700 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={gifDithering}
+ onChange={(e) => setGifDithering(e.target.checked)}
+ className="rounded mr-2"
+ />
+ Enable Dithering
+ </label>
+ <p className="text-xs text-gray-500 mt-1">
+ Dithering can improve color appearance but may introduce noise
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+
<div
className={`border-2 border-dashed rounded-lg p-8 mb-6 flex flex-col items-center justify-center cursor-pointer transition-colors ${
isDragging
@@ -911,10 +1110,6 @@ export const MediaFormatConverter = ({
This converter works entirely in your browser. Your files are never
uploaded to any server.
</p>
- <p className="mt-1">
- Powered by modern browser APIs like MediaRecorder and WebAudio for
- fast and efficient conversion.
- </p>
{isSafari && (
<div className="mt-3 p-3 bg-yellow-50 border border-yellow-200 rounded-md text-yellow-700">
<p>
@@ -935,6 +1130,16 @@ export const MediaFormatConverter = ({
</p>
</div>
)}
+ {currentTargetFormat === "gif" && (
+ <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-md text-blue-700">
+ <p>
+ <strong>GIF Conversion:</strong> Converting to GIF format may take
+ some time and result in larger file sizes. For high-quality
+ results with smaller files, consider using the WebM or MP4 format
+ instead.
+ </p>
+ </div>
+ )}
</div>
</div>
);
diff --git a/apps/web/components/tools/SpeedController.tsx b/apps/web/components/tools/SpeedController.tsx
index 26324f7d9..ed4272b30 100644
--- a/apps/web/components/tools/SpeedController.tsx
+++ b/apps/web/components/tools/SpeedController.tsx
@@ -22,7 +22,6 @@ export const SpeedController = () => {
const [progress, setProgress] = useState(0);
const [outputUrl, setOutputUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
- const [mediaEngineLoaded, setMediaEngineLoaded] = useState(true);
const [isDragging, setIsDragging] = useState(false);
const [selectedSpeed, setSelectedSpeed] = useState<number>(1.5);
const [videoInfo, setVideoInfo] = useState<{
@@ -112,7 +111,7 @@ export const SpeedController = () => {
};
const processVideo = async () => {
- if (!file || !mediaEngineLoaded) return;
+ if (!file) return;
setIsProcessing(true);
setError(null);
@@ -636,7 +635,7 @@ export const SpeedController = () => {
<Button
variant="primary"
onClick={processVideo}
- disabled={!mediaEngineLoaded || isProcessing}
+ disabled={isProcessing}
className="w-full"
>
{selectedSpeed < 1 ? "Slow Down" : "Speed Up"} Video (
diff --git a/apps/web/package.json b/apps/web/package.json
index 8ed69012f..944f9b34d 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -55,6 +55,7 @@
"file-saver": "^2.0.5",
"framer-motion": "^11.13.1",
"geist": "^1.3.1",
+ "gif.js": "0.2.0",
"hls.js": "^1.5.3",
"hono": "^4.7.1",
"jszip": "^3.10.1",
diff --git a/apps/web/public/gif.worker.js b/apps/web/public/gif.worker.js
new file mode 100644
index 000000000..269624e61
--- /dev/null
+++ b/apps/web/public/gif.worker.js
@@ -0,0 +1,3 @@
+// gif.worker.js 0.2.0 - https://github.com/jnordberg/gif.js
+(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){var NeuQuant=require("./TypedNeuQuant.js");var LZWEncoder=require("./LZWEncoder.js");function ByteArray(){this.page=-1;this.pages=[];this.newPage()}ByteArray.pageSize=4096;ByteArray.charMap={};for(var i=0;i<256;i++)ByteArray.charMap[i]=String.fromCharCode(i);ByteArray.prototype.newPage=function(){this.pages[++this.page]=new Uint8Array(ByteArray.pageSize);this.cursor=0};ByteArray.prototype.getData=function(){var rv="";for(var p=0;p<this.pages.length;p++){for(var i=0;i<ByteArray.pageSize;i++){rv+=ByteArray.charMap[this.pages[p][i]]}}return rv};ByteArray.prototype.writeByte=function(val){if(this.cursor>=ByteArray.pageSize)this.newPage();this.pages[this.page][this.cursor++]=val};ByteArray.prototype.writeUTFBytes=function(string){for(var l=string.length,i=0;i<l;i++)this.writeByte(string.charCodeAt(i))};ByteArray.prototype.writeBytes=function(array,offset,length){for(var l=length||array.length,i=offset||0;i<l;i++)this.writeByte(array[i])};function GIFEncoder(width,height){this.width=~~width;this.height=~~height;this.transparent=null;this.transIndex=0;this.repeat=-1;this.delay=0;this.image=null;this.pixels=null;this.indexedPixels=null;this.colorDepth=null;this.colorTab=null;this.neuQuant=null;this.usedEntry=new Array;this.palSize=7;this.dispose=-1;this.firstFrame=true;this.sample=10;this.dither=false;this.globalPalette=false;this.out=new ByteArray}GIFEncoder.prototype.setDelay=function(milliseconds){this.delay=Math.round(milliseconds/10)};GIFEncoder.prototype.setFrameRate=function(fps){this.delay=Math.round(100/fps)};GIFEncoder.prototype.setDispose=function(disposalCode){if(disposalCode>=0)this.dispose=disposalCode};GIFEncoder.prototype.setRepeat=function(repeat){this.repeat=repeat};GIFEncoder.prototype.setTransparent=function(color){this.transparent=color};GIFEncoder.prototype.addFrame=function(imageData){this.image=imageData;this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null;this.getImagePixels();this.analyzePixels();if(this.globalPalette===true)this.globalPalette=this.colorTab;if(this.firstFrame){this.writeLSD();this.writePalette();if(this.repeat>=0){this.writeNetscapeExt()}}this.writeGraphicCtrlExt();this.writeImageDesc();if(!this.firstFrame&&!this.globalPalette)this.writePalette();this.writePixels();this.firstFrame=false};GIFEncoder.prototype.finish=function(){this.out.writeByte(59)};GIFEncoder.prototype.setQuality=function(quality){if(quality<1)quality=1;this.sample=quality};GIFEncoder.prototype.setDither=function(dither){if(dither===true)dither="FloydSteinberg";this.dither=dither};GIFEncoder.prototype.setGlobalPalette=function(palette){this.globalPalette=palette};GIFEncoder.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette};GIFEncoder.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")};GIFEncoder.prototype.analyzePixels=function(){if(!this.colorTab){this.neuQuant=new NeuQuant(this.pixels,this.sample);this.neuQuant.buildColormap();this.colorTab=this.neuQuant.getColormap()}if(this.dither){this.ditherPixels(this.dither.replace("-serpentine",""),this.dither.match(/-serpentine/)!==null)}else{this.indexPixels()}this.pixels=null;this.colorDepth=8;this.palSize=7;if(this.transparent!==null){this.transIndex=this.findClosest(this.transparent,true)}};GIFEncoder.prototype.indexPixels=function(imgq){var nPix=this.pixels.length/3;this.indexedPixels=new Uint8Array(nPix);var k=0;for(var j=0;j<nPix;j++){var index=this.findClosestRGB(this.pixels[k++]&255,this.pixels[k++]&255,this.pixels[k++]&255);this.usedEntry[index]=true;this.indexedPixels[j]=index}};GIFEncoder.prototype.ditherPixels=function(kernel,serpentine){var kernels={FalseFloydSteinberg:[[3/8,1,0],[3/8,0,1],[2/8,1,1]],FloydSteinberg:[[7/16,1,0],[3/16,-1,1],[5/16,0,1],[1/16,1,1]],Stucki:[[8/42,1,0],[4/42,2,0],[2/42,-2,1],[4/42,-1,1],[8/42,0,1],[4/42,1,1],[2/42,2,1],[1/42,-2,2],[2/42,-1,2],[4/42,0,2],[2/42,1,2],[1/42,2,2]],Atkinson:[[1/8,1,0],[1/8,2,0],[1/8,-1,1],[1/8,0,1],[1/8,1,1],[1/8,0,2]]};if(!kernel||!kernels[kernel]){throw"Unknown dithering kernel: "+kernel}var ds=kernels[kernel];var index=0,height=this.height,width=this.width,data=this.pixels;var direction=serpentine?-1:1;this.indexedPixels=new Uint8Array(this.pixels.length/3);for(var y=0;y<height;y++){if(serpentine)direction=direction*-1;for(var x=direction==1?0:width-1,xend=direction==1?width:0;x!==xend;x+=direction){index=y*width+x;var idx=index*3;var r1=data[idx];var g1=data[idx+1];var b1=data[idx+2];idx=this.findClosestRGB(r1,g1,b1);this.usedEntry[idx]=true;this.indexedPixels[index]=idx;idx*=3;var r2=this.colorTab[idx];var g2=this.colorTab[idx+1];var b2=this.colorTab[idx+2];var er=r1-r2;var eg=g1-g2;var eb=b1-b2;for(var i=direction==1?0:ds.length-1,end=direction==1?ds.length:0;i!==end;i+=direction){var x1=ds[i][1];var y1=ds[i][2];if(x1+x>=0&&x1+x<width&&y1+y>=0&&y1+y<height){var d=ds[i][0];idx=index+x1+y1*width;idx*=3;data[idx]=Math.max(0,Math.min(255,data[idx]+er*d));data[idx+1]=Math.max(0,Math.min(255,data[idx+1]+eg*d));data[idx+2]=Math.max(0,Math.min(255,data[idx+2]+eb*d))}}}}};GIFEncoder.prototype.findClosest=function(c,used){return this.findClosestRGB((c&16711680)>>16,(c&65280)>>8,c&255,used)};GIFEncoder.prototype.findClosestRGB=function(r,g,b,used){if(this.colorTab===null)return-1;if(this.neuQuant&&!used){return this.neuQuant.lookupRGB(r,g,b)}var c=b|g<<8|r<<16;var minpos=0;var dmin=256*256*256;var len=this.colorTab.length;for(var i=0,index=0;i<len;index++){var dr=r-(this.colorTab[i++]&255);var dg=g-(this.colorTab[i++]&255);var db=b-(this.colorTab[i++]&255);var d=dr*dr+dg*dg+db*db;if((!used||this.usedEntry[index])&&d<dmin){dmin=d;minpos=index}}return minpos};GIFEncoder.prototype.getImagePixels=function(){var w=this.width;var h=this.height;this.pixels=new Uint8Array(w*h*3);var data=this.image;var srcPos=0;var count=0;for(var i=0;i<h;i++){for(var j=0;j<w;j++){this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];this.pixels[count++]=data[srcPos++];srcPos++}}};GIFEncoder.prototype.writeGraphicCtrlExt=function(){this.out.writeByte(33);this.out.writeByte(249);this.out.writeByte(4);var transp,disp;if(this.transparent===null){transp=0;disp=0}else{transp=1;disp=2}if(this.dispose>=0){disp=dispose&7}disp<<=2;this.out.writeByte(0|disp|0|transp);this.writeShort(this.delay);this.out.writeByte(this.transIndex);this.out.writeByte(0)};GIFEncoder.prototype.writeImageDesc=function(){this.out.writeByte(44);this.writeShort(0);this.writeShort(0);this.writeShort(this.width);this.writeShort(this.height);if(this.firstFrame||this.globalPalette){this.out.writeByte(0)}else{this.out.writeByte(128|0|0|0|this.palSize)}};GIFEncoder.prototype.writeLSD=function(){this.writeShort(this.width);this.writeShort(this.height);this.out.writeByte(128|112|0|this.palSize);this.out.writeByte(0);this.out.writeByte(0)};GIFEncoder.prototype.writeNetscapeExt=function(){this.out.writeByte(33);this.out.writeByte(255);this.out.writeByte(11);this.out.writeUTFBytes("NETSCAPE2.0");this.out.writeByte(3);this.out.writeByte(1);this.writeShort(this.repeat);this.out.writeByte(0)};GIFEncoder.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var n=3*256-this.colorTab.length;for(var i=0;i<n;i++)this.out.writeByte(0)};GIFEncoder.prototype.writeShort=function(pValue){this.out.writeByte(pValue&255);this.out.writeByte(pValue>>8&255)};GIFEncoder.prototype.writePixels=function(){var enc=new LZWEncoder(this.width,this.height,this.indexedPixels,this.colorDepth);enc.encode(this.out)};GIFEncoder.prototype.stream=function(){return this.out};module.exports=GIFEncoder},{"./LZWEncoder.js":2,"./TypedNeuQuant.js":3}],2:[function(require,module,exports){var EOF=-1;var BITS=12;var HSIZE=5003;var masks=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];function LZWEncoder(width,height,pixels,colorDepth){var initCodeSize=Math.max(2,colorDepth);var accum=new Uint8Array(256);var htab=new Int32Array(HSIZE);var codetab=new Int32Array(HSIZE);var cur_accum,cur_bits=0;var a_count;var free_ent=0;var maxcode;var clear_flg=false;var g_init_bits,ClearCode,EOFCode;function char_out(c,outs){accum[a_count++]=c;if(a_count>=254)flush_char(outs)}function cl_block(outs){cl_hash(HSIZE);free_ent=ClearCode+2;clear_flg=true;output(ClearCode,outs)}function cl_hash(hsize){for(var i=0;i<hsize;++i)htab[i]=-1}function compress(init_bits,outs){var fcode,c,i,ent,disp,hsize_reg,hshift;g_init_bits=init_bits;clear_flg=false;n_bits=g_init_bits;maxcode=MAXCODE(n_bits);ClearCode=1<<init_bits-1;EOFCode=ClearCode+1;free_ent=ClearCode+2;a_count=0;ent=nextPixel();hshift=0;for(fcode=HSIZE;fcode<65536;fcode*=2)++hshift;hshift=8-hshift;hsize_reg=HSIZE;cl_hash(hsize_reg);output(ClearCode,outs);outer_loop:while((c=nextPixel())!=EOF){fcode=(c<<BITS)+ent;i=c<<hshift^ent;if(htab[i]===fcode){ent=codetab[i];continue}else if(htab[i]>=0){disp=hsize_reg-i;if(i===0)disp=1;do{if((i-=disp)<0)i+=hsize_reg;if(htab[i]===fcode){ent=codetab[i];continue outer_loop}}while(htab[i]>=0)}output(ent,outs);ent=c;if(free_ent<1<<BITS){codetab[i]=free_ent++;htab[i]=fcode}else{cl_block(outs)}}output(ent,outs);output(EOFCode,outs)}function encode(outs){outs.writeByte(initCodeSize);remaining=width*height;curPixel=0;compress(initCodeSize+1,outs);outs.writeByte(0)}function flush_char(outs){if(a_count>0){outs.writeByte(a_count);outs.writeBytes(accum,0,a_count);a_count=0}}function MAXCODE(n_bits){return(1<<n_bits)-1}function nextPixel(){if(remaining===0)return EOF;--remaining;var pix=pixels[curPixel++];return pix&255}function output(code,outs){cur_accum&=masks[cur_bits];if(cur_bits>0)cur_accum|=code<<cur_bits;else cur_accum=code;cur_bits+=n_bits;while(cur_bits>=8){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}if(free_ent>maxcode||clear_flg){if(clear_flg){maxcode=MAXCODE(n_bits=g_init_bits);clear_flg=false}else{++n_bits;if(n_bits==BITS)maxcode=1<<BITS;else maxcode=MAXCODE(n_bits)}}if(code==EOFCode){while(cur_bits>0){char_out(cur_accum&255,outs);cur_accum>>=8;cur_bits-=8}flush_char(outs)}}this.encode=encode}module.exports=LZWEncoder},{}],3:[function(require,module,exports){var ncycles=100;var netsize=256;var maxnetpos=netsize-1;var netbiasshift=4;var intbiasshift=16;var intbias=1<<intbiasshift;var gammashift=10;var gamma=1<<gammashift;var betashift=10;var beta=intbias>>betashift;var betagamma=intbias<<gammashift-betashift;var initrad=netsize>>3;var radiusbiasshift=6;var radiusbias=1<<radiusbiasshift;var initradius=initrad*radiusbias;var radiusdec=30;var alphabiasshift=10;var initalpha=1<<alphabiasshift;var alphadec;var radbiasshift=8;var radbias=1<<radbiasshift;var alpharadbshift=alphabiasshift+radbiasshift;var alpharadbias=1<<alpharadbshift;var prime1=499;var prime2=491;var prime3=487;var prime4=503;var minpicturebytes=3*prime4;function NeuQuant(pixels,samplefac){var network;var netindex;var bias;var freq;var radpower;function init(){network=[];netindex=new Int32Array(256);bias=new Int32Array(netsize);freq=new Int32Array(netsize);radpower=new Int32Array(netsize>>3);var i,v;for(i=0;i<netsize;i++){v=(i<<netbiasshift+8)/netsize;network[i]=new Float64Array([v,v,v,0]);freq[i]=intbias/netsize;bias[i]=0}}function unbiasnet(){for(var i=0;i<netsize;i++){network[i][0]>>=netbiasshift;network[i][1]>>=netbiasshift;network[i][2]>>=netbiasshift;network[i][3]=i}}function altersingle(alpha,i,b,g,r){network[i][0]-=alpha*(network[i][0]-b)/initalpha;network[i][1]-=alpha*(network[i][1]-g)/initalpha;network[i][2]-=alpha*(network[i][2]-r)/initalpha}function alterneigh(radius,i,b,g,r){var lo=Math.abs(i-radius);var hi=Math.min(i+radius,netsize);var j=i+1;var k=i-1;var m=1;var p,a;while(j<hi||k>lo){a=radpower[m++];if(j<hi){p=network[j++];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}if(k>lo){p=network[k--];p[0]-=a*(p[0]-b)/alpharadbias;p[1]-=a*(p[1]-g)/alpharadbias;p[2]-=a*(p[2]-r)/alpharadbias}}}function contest(b,g,r){var bestd=~(1<<31);var bestbiasd=bestd;var bestpos=-1;var bestbiaspos=bestpos;var i,n,dist,biasdist,betafreq;for(i=0;i<netsize;i++){n=network[i];dist=Math.abs(n[0]-b)+Math.abs(n[1]-g)+Math.abs(n[2]-r);if(dist<bestd){bestd=dist;bestpos=i}biasdist=dist-(bias[i]>>intbiasshift-netbiasshift);if(biasdist<bestbiasd){bestbiasd=biasdist;bestbiaspos=i}betafreq=freq[i]>>betashift;freq[i]-=betafreq;bias[i]+=betafreq<<gammashift}freq[bestpos]+=beta;bias[bestpos]-=betagamma;return bestbiaspos}function inxbuild(){var i,j,p,q,smallpos,smallval,previouscol=0,startpos=0;for(i=0;i<netsize;i++){p=network[i];smallpos=i;smallval=p[1];for(j=i+1;j<netsize;j++){q=network[j];if(q[1]<smallval){smallpos=j;smallval=q[1]}}q=network[smallpos];if(i!=smallpos){j=q[0];q[0]=p[0];p[0]=j;j=q[1];q[1]=p[1];p[1]=j;j=q[2];q[2]=p[2];p[2]=j;j=q[3];q[3]=p[3];p[3]=j}if(smallval!=previouscol){netindex[previouscol]=startpos+i>>1;for(j=previouscol+1;j<smallval;j++)netindex[j]=i;previouscol=smallval;startpos=i}}netindex[previouscol]=startpos+maxnetpos>>1;for(j=previouscol+1;j<256;j++)netindex[j]=maxnetpos}function inxsearch(b,g,r){var a,p,dist;var bestd=1e3;var best=-1;var i=netindex[g];var j=i-1;while(i<netsize||j>=0){if(i<netsize){p=network[i];dist=p[1]-g;if(dist>=bestd)i=netsize;else{i++;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}if(j>=0){p=network[j];dist=g-p[1];if(dist>=bestd)j=-1;else{j--;if(dist<0)dist=-dist;a=p[0]-b;if(a<0)a=-a;dist+=a;if(dist<bestd){a=p[2]-r;if(a<0)a=-a;dist+=a;if(dist<bestd){bestd=dist;best=p[3]}}}}}return best}function learn(){var i;var lengthcount=pixels.length;var alphadec=30+(samplefac-1)/3;var samplepixels=lengthcount/(3*samplefac);var delta=~~(samplepixels/ncycles);var alpha=initalpha;var radius=initradius;var rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(i=0;i<rad;i++)radpower[i]=alpha*((rad*rad-i*i)*radbias/(rad*rad));var step;if(lengthcount<minpicturebytes){samplefac=1;step=3}else if(lengthcount%prime1!==0){step=3*prime1}else if(lengthcount%prime2!==0){step=3*prime2}else if(lengthcount%prime3!==0){step=3*prime3}else{step=3*prime4}var b,g,r,j;var pix=0;i=0;while(i<samplepixels){b=(pixels[pix]&255)<<netbiasshift;g=(pixels[pix+1]&255)<<netbiasshift;r=(pixels[pix+2]&255)<<netbiasshift;j=contest(b,g,r);altersingle(alpha,j,b,g,r);if(rad!==0)alterneigh(rad,j,b,g,r);pix+=step;if(pix>=lengthcount)pix-=lengthcount;i++;if(delta===0)delta=1;if(i%delta===0){alpha-=alpha/alphadec;radius-=radius/radiusdec;rad=radius>>radiusbiasshift;if(rad<=1)rad=0;for(j=0;j<rad;j++)radpower[j]=alpha*((rad*rad-j*j)*radbias/(rad*rad))}}}function buildColormap(){init();learn();unbiasnet();inxbuild()}this.buildColormap=buildColormap;function getColormap(){var map=[];var index=[];for(var i=0;i<netsize;i++)index[network[i][3]]=i;var k=0;for(var l=0;l<netsize;l++){var j=index[l];map[k++]=network[j][0];map[k++]=network[j][1];map[k++]=network[j][2]}return map}this.getColormap=getColormap;this.lookupRGB=inxsearch}module.exports=NeuQuant},{}],4:[function(require,module,exports){var GIFEncoder,renderFrame;GIFEncoder=require("./GIFEncoder.js");renderFrame=function(frame){var encoder,page,stream,transfer;encoder=new GIFEncoder(frame.width,frame.height);if(frame.index===0){encoder.writeHeader()}else{encoder.firstFrame=false}encoder.setTransparent(frame.transparent);encoder.setRepeat(frame.repeat);encoder.setDelay(frame.delay);encoder.setQuality(frame.quality);encoder.setDither(frame.dither);encoder.setGlobalPalette(frame.globalPalette);encoder.addFrame(frame.data);if(frame.last){encoder.finish()}if(frame.globalPalette===true){frame.globalPalette=encoder.getGlobalPalette()}stream=encoder.stream();frame.data=stream.pages;frame.cursor=stream.cursor;frame.pageSize=stream.constructor.pageSize;if(frame.canTransfer){transfer=function(){var i,len,ref,results;ref=frame.data;results=[];for(i=0,len=ref.length;i<len;i++){page=ref[i];results.push(page.buffer)}return results}();return self.postMessage(frame,transfer)}else{return self.postMessage(frame)}};self.onmessage=function(event){return renderFrame(event.data)}},{"./GIFEncoder.js":1}]},{},[4]);
+//# sourceMappingURL=gif.worker.js.map
diff --git a/apps/web/types/gif.js.d.ts b/apps/web/types/gif.js.d.ts
new file mode 100644
index 000000000..90b0f24c6
--- /dev/null
+++ b/apps/web/types/gif.js.d.ts
@@ -0,0 +1,34 @@
+/* This file is required to use gif.js in the browser.
+ It's quite an antiquated library so doesn't have built in types, but it's reliable for GIF generation.
+ This is not an AI comment just an observation by me on the need for this file :D
+*/
+
+declare module 'gif.js' {
+ interface GIFOptions {
+ workers?: number;
+ quality?: number;
+ width?: number;
+ height?: number;
+ workerScript?: string;
+ repeat?: number;
+ transparent?: string | number[];
+ background?: string | number[];
+ dither?: boolean;
+ }
+
+ interface GIFFrameOptions {
+ delay?: number;
+ copy?: boolean;
+ dispose?: number;
+ }
+
+ export default class GIF {
+ constructor(options: GIFOptions);
+ addFrame(imageElement: CanvasImageSource | HTMLCanvasElement, options?: GIFFrameOptions): void;
+ on(event: 'finished', callback: (blob: Blob) => void): void;
+ on(event: 'progress', callback: (progress: number) => void): void;
+ on(event: string, callback: (...args: any[]) => void): void;
+ render(): void;
+ abort(): void;
+ }
+}
\ No newline at end of file
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d617658bd..c1d2ab395 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -434,12 +434,6 @@ importers:
'@deepgram/sdk':
specifier: ^3.3.4
version: 3.7.0([email protected])
- '@ffmpeg/ffmpeg':
- specifier: ^0.12.10
- version: 0.12.10
- '@ffmpeg/util':
- specifier: ^0.12.1
- version: 0.12.1
'@fortawesome/free-brands-svg-icons':
specifier: ^6.7.2
version: 6.7.2
@@ -542,6 +536,9 @@ importers:
geist:
specifier: ^1.3.1
+ gif.js:
+ specifier: ^0.2.0
+ version: 0.2.0
hls.js:
specifier: ^1.5.3
version: 1.5.15
@@ -3115,18 +3112,6 @@ packages:
resolution: {integrity: sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==}
engines: {node: '>=14'}
- '@ffmpeg/[email protected]':
- resolution: {integrity: sha512-lVtk8PW8e+NUzGZhPTWj2P1J4/NyuCrbDD3O9IGpSeLYtUZKBqZO8CNj1WYGghep/MXoM8e1qVY1GztTkf8YYQ==}
- engines: {node: '>=18.x'}
-
- '@ffmpeg/[email protected]':
- resolution: {integrity: sha512-NJtxwPoLb60/z1Klv0ueshguWQ/7mNm106qdHkB4HL49LXszjhjCCiL+ldHJGQ9ai2Igx0s4F24ghigy//ERdA==}
- engines: {node: '>=16.x'}
-
- '@ffmpeg/[email protected]':
- resolution: {integrity: sha512-10jjfAKWaDyb8+nAkijcsi9wgz/y26LOc1NKJradNMyCIl6usQcBbhkjX5qhALrSBcOy6TOeksunTYa+a03qNQ==}
- engines: {node: '>=18.x'}
-
'@floating-ui/[email protected]':
resolution: {integrity: sha512-7XJ9cPU+yI2QeLS+FCSlqNFZJq8arvswefkZrYI1yQBbftw6FyrZOxYSh+9S7z7TpeWlRt9zJ5IhM1WIL334jA==}
@@ -9012,6 +8997,9 @@ packages:
resolution: {integrity: sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg==}
+ resolution: {integrity: sha512-bYxCoT8OZKmbxY8RN4qDiYuj4nrQDTzgLRcFVovyona1PTWNePzI4nzOmotnlOFIzTk/ZxAHtv+TfVLiBWj/hw==}
+
resolution: {integrity: sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==}
hasBin: true
@@ -15759,14 +15747,6 @@ snapshots:
'@fastify/[email protected]': {}
- '@ffmpeg/[email protected]':
- dependencies:
- '@ffmpeg/types': 0.12.2
-
- '@ffmpeg/[email protected]': {}
-
- '@ffmpeg/[email protected]': {}
-
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.8
@@ -22869,6 +22849,8 @@ snapshots:
dependencies:
resolve-pkg-maps: 1.0.0
+
dependencies:
citty: 0.1.6