Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Tools page updates

Richie McIlroybf2769f040fc
diff --git a/apps/web/app/tools/video-speed-controller/page.tsx b/apps/web/app/tools/video-speed-controller/page.tsx
index d87e0fbdf..2dcdc5191 100644
--- a/apps/web/app/tools/video-speed-controller/page.tsx
+++ b/apps/web/app/tools/video-speed-controller/page.tsx
@@ -2,60 +2,60 @@ import { SpeedController } from "@/components/tools/SpeedController";
import { ToolsPageTemplate } from "@/components/tools/ToolsPageTemplate";
const content = {
- title: "Video Speed Controller",
- description: "Speed up or slow down your videos directly in your browser",
- featuresTitle: "Why Use Our Video Speed Controller",
+ title: "Video Speed Controller (0.25×-3×)",
+ description:
+ "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:
- "Our free video speed controller tool runs entirely in your browser, respecting your privacy while delivering professional results.",
+ "Powered by WebCodecs + WebAssembly, Cap processes every frame locally for near-instant results—while keeping your files 100% private.",
features: [
{
- title: "100% Private",
+ title: "WebCodecs-Level Speed",
description:
- "All processing happens locally in your browser. Your videos never leave your device.",
+ "Modern browser APIs crunch frames directly on your GPU/CPU, so even large clips render in seconds.",
},
{
- title: "Multiple Speed Options",
+ title: "100% Private",
description:
- "Choose from various speed settings from super slow (0.25x) to ultra fast (3x) to achieve the perfect timing.",
+ "Nothing ever touches a server. All encoding and decoding stays on-device.",
},
{
- title: "Preserves Audio Quality",
+ title: "Fine-Grained Control (0.25×-3×)",
description:
- "Unlike basic tools, we adjust audio pitch to sound natural at different speeds.",
+ "Dial in super-slow 0.25× for tutorials or crank up to 3× for snappy demos—audio pitch is auto-corrected.",
},
],
faqs: [
{
- question: "What video formats are supported?",
+ question: "What video formats can I adjust?",
answer:
- "Our tool supports most common video formats including MP4, WebM, MOV, AVI, and MKV.",
+ "MP4, WebM, MOV, AVI and MKV are all supported—basically anything modern browsers can decode. Chrome is recommended for best results.",
},
{
- question: "Is there a file size limit?",
- answer:
- "Yes, the maximum file size is 500MB. This limit ensures optimal performance in the browser.",
+ question: "Is there a file-size limit?",
+ answer: "Up to 500 MB for smooth in-browser performance.",
},
{
- question: "Will the video quality be reduced?",
+ question: "Will my video quality drop?",
answer:
- "No, our tool maintains the original resolution of your video while adjusting its speed.",
+ "No. We preserve your original resolution and bitrate; only playback speed changes.",
},
{
- question: "Why is video processing slow?",
+ question: "Why is processing still slow on my laptop?",
answer:
- "Processing happens completely in your browser, so speed depends on your device's performance. Larger videos will take longer to process.",
+ "WebCodecs relies on your device’s hardware. Older CPUs/GPUs or throttled mobiles will take longer.",
},
{
- question: "Can I use this on my phone?",
+ question: "Can I use this on iOS / Android?",
answer:
- "Yes, this tool works on modern mobile browsers, but processing may be faster on desktop devices.",
+ "Yes—modern Safari, Chrome and Firefox are supported, but Chrome is recommended.",
},
],
cta: {
- title: "Looking for more powerful video tools?",
+ title: "Need heavier-duty video tools?",
description:
- "Download Cap - the open source screen recorder with built-in editing capabilities",
- buttonText: "Get Cap for Free",
+ "Grab Cap — the open-source screen recorder & editor that lives on your machine.",
+ buttonText: "Download Cap Free",
},
};
@@ -66,7 +66,15 @@ export default function SpeedControllerPage() {
}
export const metadata = {
- title: "Video Speed Controller - Speed Up or Slow Down Videos Online",
+ title:
+ "Video Speed Controller Online – Speed Up or Slow Down Videos (0.25×-3×)",
description:
- "Free browser-based tool to adjust video playback speed. Speed up or slow down videos without losing quality, all processed locally for privacy.",
+ "Free WebCodecs-powered tool to change video speed online. Adjust playback from 0.25× to 3× without quality loss—processed locally for privacy.",
+ keywords: [
+ "video speed controller",
+ "speed up video online",
+ "slow down video online",
+ "change video playback speed",
+ "adjust video speed in browser",
+ ],
};
diff --git a/apps/web/components/Navbar.tsx b/apps/web/components/Navbar.tsx
index 75c810b21..30503d994 100644
--- a/apps/web/components/Navbar.tsx
+++ b/apps/web/components/Navbar.tsx
@@ -113,7 +113,7 @@ export const Navbar = ({ auth }: { auth: boolean }) => {
return (
<>
- <div className="fixed border-b border-b-zinc-100 inset-0 z-20 p-4 w-full backdrop-blur-md bg-white/70 h-[60px]">
+ <div className="fixed border-b border-b-zinc-100 inset-0 z-50 p-4 w-full backdrop-blur-md bg-white/70 h-[60px]">
<div className="flex justify-between items-center mx-auto max-w-4xl h-full transition-all">
<div className="flex items-center">
<Link passHref href="/home">
diff --git a/apps/web/components/tools/MediaFormatConverter.tsx b/apps/web/components/tools/MediaFormatConverter.tsx
index 8a31bf877..019942803 100644
--- a/apps/web/components/tools/MediaFormatConverter.tsx
+++ b/apps/web/components/tools/MediaFormatConverter.tsx
@@ -2,8 +2,6 @@
import { useState, useRef, useEffect } from "react";
import { Button } from "@cap/ui";
-import { FFmpeg } from "@ffmpeg/ffmpeg";
-import { fetchFile } from "@ffmpeg/util";
import { trackEvent } from "@/app/utils/analytics";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
@@ -24,7 +22,6 @@ export const CONVERSION_CONFIGS: Record<
string,
{
acceptType: string;
- command: (input: string, output: string) => string[];
outputType: string;
title: (source: string, target: string) => string;
description: (source: string, target: string) => string;
@@ -32,21 +29,6 @@ export const CONVERSION_CONFIGS: Record<
> = {
"webm-to-mp4": {
acceptType: "video/webm",
- command: (input, output) => [
- "-i",
- input,
- "-c:v",
- "libx264",
- "-preset",
- "medium",
- "-crf",
- "23",
- "-c:a",
- "aac",
- "-b:a",
- "128k",
- output,
- ],
outputType: "video/mp4",
title: (source, target) =>
`${source.toUpperCase()} to ${target.toUpperCase()} Converter`,
@@ -55,19 +37,6 @@ export const CONVERSION_CONFIGS: Record<
},
"mp4-to-webm": {
acceptType: "video/mp4",
- command: (input, output) => [
- "-i",
- input,
- "-c:v",
- "libvpx",
- "-crf",
- "30",
- "-b:v",
- "0",
- "-c:a",
- "libvorbis",
- output,
- ],
outputType: "video/webm",
title: (source, target) =>
`${source.toUpperCase()} to ${target.toUpperCase()} Converter`,
@@ -76,26 +45,6 @@ export const CONVERSION_CONFIGS: Record<
},
"mov-to-mp4": {
acceptType: "video/quicktime",
- command: (input, output) => [
- "-i",
- input,
- "-c:v",
- "libx264",
- "-preset",
- "fast",
- "-crf",
- "23",
- "-movflags",
- "+faststart",
- "-pix_fmt",
- "yuv420p",
- "-c:a",
- "aac",
- "-b:a",
- "128k",
- "-y",
- output,
- ],
outputType: "video/mp4",
title: (source, target) =>
`${source.toUpperCase()} to ${target.toUpperCase()} Converter`,
@@ -104,21 +53,6 @@ export const CONVERSION_CONFIGS: Record<
},
"avi-to-mp4": {
acceptType: "video/x-msvideo",
- command: (input, output) => [
- "-i",
- input,
- "-c:v",
- "libx264",
- "-preset",
- "medium",
- "-crf",
- "23",
- "-c:a",
- "aac",
- "-b:a",
- "128k",
- output,
- ],
outputType: "video/mp4",
title: (source, target) =>
`${source.toUpperCase()} to ${target.toUpperCase()} Converter`,
@@ -127,60 +61,22 @@ export const CONVERSION_CONFIGS: Record<
},
"mkv-to-mp4": {
acceptType: "video/x-matroska",
- command: (input, output) => [
- "-i",
- input,
- "-c:v",
- "libx264",
- "-preset",
- "medium",
- "-crf",
- "23",
- "-c:a",
- "aac",
- "-b:a",
- "128k",
- output,
- ],
outputType: "video/mp4",
title: (source, target) =>
`${source.toUpperCase()} to ${target.toUpperCase()} Converter`,
description: (source, target) =>
`Convert ${source.toUpperCase()} videos to ${target.toUpperCase()} format directly in your browser`,
},
-
"mp4-to-mp3": {
acceptType: "video/mp4",
- command: (input, output) => [
- "-i",
- input,
- "-vn",
- "-ar",
- "44100",
- "-ac",
- "2",
- "-b:a",
- "192k",
- output,
- ],
outputType: "audio/mp3",
title: (source, target) =>
`${source.toUpperCase()} to ${target.toUpperCase()} Converter`,
description: (source, target) =>
`Extract audio from ${source.toUpperCase()} videos and save as ${target.toUpperCase()} files`,
},
-
"mp4-to-gif": {
acceptType: "video/mp4",
- command: (input, output) => [
- "-i",
- input,
- "-vf",
- "fps=10,scale=320:-1:flags=lanczos",
- "-c:v",
- "gif",
- output,
- ],
outputType: "image/gif",
title: (source, target) =>
`${source.toUpperCase()} to ${target.toUpperCase()} Converter`,
@@ -260,16 +156,24 @@ export const MediaFormatConverter = ({
const [progress, setProgress] = useState(0);
const [outputUrl, setOutputUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
- const [ffmpegLoaded, setFfmpegLoaded] = useState(false);
+ const [mediaEngineLoaded, setMediaEngineLoaded] = useState(true);
const [isDragging, setIsDragging] = useState(false);
const [currentSourceFormat, setCurrentSourceFormat] = useState(sourceFormat);
const [currentTargetFormat, setCurrentTargetFormat] = useState(targetFormat);
+ const [supportedFormats, setSupportedFormats] = useState<string[]>([
+ "mp4",
+ "webm",
+ ]);
+ const [isSafari, setIsSafari] = useState(false);
+ const [isFirefox, setIsFirefox] = useState(false);
const conversionPath = `${currentSourceFormat}-to-${currentTargetFormat}`;
const config = CONVERSION_CONFIGS[conversionPath];
- const ffmpegRef = useRef<FFmpeg | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
+ const videoRef = useRef<HTMLVideoElement | null>(null);
+ const mediaRecorderRef = useRef<MediaRecorder | null>(null);
+ const recordedChunksRef = useRef<Blob[]>([]);
useEffect(() => {
if (
@@ -294,33 +198,27 @@ export const MediaFormatConverter = ({
]);
useEffect(() => {
- const loadFFmpeg = async () => {
- try {
- const ffmpegInstance = new FFmpeg();
- ffmpegRef.current = ffmpegInstance;
-
- ffmpegInstance.on("progress", ({ progress }: { progress: number }) => {
- setProgress(Math.round(progress * 100));
- });
-
- await ffmpegInstance.load();
- setFfmpegLoaded(true);
- trackEvent(`${conversionPath}_tool_loaded`);
- } catch (err) {
- setError("Failed to load FFmpeg. Please try again later.");
- console.error("FFmpeg loading error:", err);
+ const checkSupport = async () => {
+ if (MediaRecorder.isTypeSupported("video/webm")) {
+ setSupportedFormats((prev) => [...prev, "webm"]);
}
- };
- loadFFmpeg();
-
- return () => {
- if (outputUrl) {
- URL.revokeObjectURL(outputUrl);
- }
+ trackEvent(`${conversionPath}_tool_loaded`);
};
+
+ checkSupport();
}, [conversionPath]);
+ useEffect(() => {
+ const isSafariBrowser = /^((?!chrome|android).)*safari/i.test(
+ navigator.userAgent
+ );
+ setIsSafari(isSafariBrowser);
+
+ const isFirefoxBrowser = navigator.userAgent.indexOf("Firefox") !== -1;
+ setIsFirefox(isFirefoxBrowser);
+ }, []);
+
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];
if (selectedFile) {
@@ -400,7 +298,7 @@ export const MediaFormatConverter = ({
};
const convertFile = async () => {
- if (!file || !ffmpegLoaded || !ffmpegRef.current || !config) return;
+ if (!file || !mediaEngineLoaded || !config) return;
setIsConverting(true);
setError(null);
@@ -412,53 +310,23 @@ export const MediaFormatConverter = ({
});
try {
- const ffmpeg = ffmpegRef.current;
- const inputFileName = `input.${currentSourceFormat}`;
- const outputFileName = `output.${currentTargetFormat}`;
-
console.log(`Starting conversion: ${conversionPath}`);
console.log(`Input file: ${file.name}, size: ${file.size} bytes`);
- await ffmpeg.writeFile(inputFileName, await fetchFile(file));
- console.log("File written to FFmpeg virtual filesystem");
-
- const command = config.command(inputFileName, outputFileName);
- console.log("FFmpeg command:", command);
-
- await ffmpeg.exec(command);
- console.log("FFmpeg command executed");
-
- const data = await ffmpeg.readFile(outputFileName);
- console.log(`Output data received, type: ${typeof data}`);
-
- if (!data) {
- throw new Error(
- "Conversion resulted in an empty file. Please try again."
- );
- }
-
- const blob = new Blob([data], { type: config.outputType });
- console.log(`Output blob created, size: ${blob.size} bytes`);
+ const fileUrl = URL.createObjectURL(file);
- if (blob.size < 1024 && file.size > 10 * 1024) {
- throw new Error(
- "Conversion produced an unusually small file. It may be corrupted."
- );
+ if (currentTargetFormat === "mp3" && currentSourceFormat === "mp4") {
+ await extractAudioFromVideo(fileUrl);
+ } else if (
+ currentTargetFormat === "gif" &&
+ currentSourceFormat === "mp4"
+ ) {
+ await convertVideoToGif(fileUrl);
+ } else {
+ await convertVideoFormat(fileUrl);
}
- const url = URL.createObjectURL(blob);
-
- setOutputUrl(url);
-
- trackEvent(`${conversionPath}_conversion_completed`, {
- fileSize: file.size,
- fileName: file.name,
- outputSize: blob.size,
- conversionTime: Date.now(),
- });
-
- await ffmpeg.deleteFile(inputFileName);
- await ffmpeg.deleteFile(outputFileName);
+ URL.revokeObjectURL(fileUrl);
} catch (err: any) {
console.error("Detailed conversion error:", err);
@@ -483,11 +351,240 @@ export const MediaFormatConverter = ({
}
};
+ const extractAudioFromVideo = async (fileUrl: string): Promise<void> => {
+ return new Promise((resolve, reject) => {
+ const audio = new Audio();
+ audio.src = fileUrl;
+ audio.muted = true;
+
+ const audioContext = new AudioContext();
+ const mediaSource = audioContext.createMediaElementSource(audio);
+ const destination = audioContext.createMediaStreamDestination();
+ mediaSource.connect(destination);
+
+ const recorder = new MediaRecorder(destination.stream);
+ const chunks: BlobPart[] = [];
+
+ recorder.ondataavailable = (e) => {
+ if (e.data.size > 0) {
+ chunks.push(e.data);
+ }
+ };
+
+ recorder.onstop = () => {
+ const blob = new Blob(chunks, { type: "audio/mp3" });
+ const url = URL.createObjectURL(blob);
+ setOutputUrl(url);
+
+ trackEvent(`${conversionPath}_conversion_completed`, {
+ fileSize: file!.size,
+ fileName: file!.name,
+ outputSize: blob.size,
+ });
+
+ resolve();
+ };
+
+ recorder.onerror = (e) => {
+ reject(new Error("Error recording audio"));
+ };
+
+ audio.oncanplaythrough = () => {
+ recorder.start();
+ audio.play();
+
+ const interval = setInterval(() => {
+ if (audio.duration) {
+ const currentProgress = (audio.currentTime / audio.duration) * 100;
+ setProgress(Math.min(Math.round(currentProgress), 99));
+ }
+ }, 500);
+
+ audio.onended = () => {
+ clearInterval(interval);
+ recorder.stop();
+ setProgress(100);
+ };
+ };
+
+ audio.onerror = () => {
+ reject(new Error("Error loading audio from video"));
+ };
+ });
+ };
+
+ 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();
+ };
+
+ 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 = true;
+
+ 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");
+ }
+
+ 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;
+ }
+ }
+
+ if (!selectedMimeType) {
+ throw new Error(
+ "None of the media formats are supported by this browser"
+ );
+ }
+
+ if (
+ isFirefox &&
+ currentSourceFormat === "webm" &&
+ currentTargetFormat === "mp4"
+ ) {
+ console.warn(
+ "Firefox has limited support for MP4 encoding. Using WebM container instead."
+ );
+ }
+
+ 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
+ );
+ }
+
+ const recorder = new MediaRecorder(stream, {
+ mimeType: selectedMimeType,
+ });
+ mediaRecorderRef.current = recorder;
+ recordedChunksRef.current = [];
+
+ recorder.ondataavailable = (e) => {
+ if (e.data.size > 0) {
+ recordedChunksRef.current.push(e.data);
+ }
+ };
+
+ recorder.onstop = () => {
+ const chunks = recordedChunksRef.current;
+ const outputMimeType = selectedMimeType.split(";")[0];
+ const blob = new Blob(chunks, { type: outputMimeType });
+ const url = URL.createObjectURL(blob);
+
+ setOutputUrl(url);
+
+ trackEvent(`${conversionPath}_conversion_completed`, {
+ fileSize: file!.size,
+ fileName: file!.name,
+ outputSize: blob.size,
+ });
+
+ videoRef.current = null;
+ mediaRecorderRef.current = null;
+ resolve();
+ };
+
+ 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);
+ }
+ };
+
+ video.onerror = () => {
+ reject(new Error("Error loading video"));
+ };
+ });
+ };
+
const handleDownload = () => {
if (!outputUrl || !file) return;
+ let actualExtension = currentTargetFormat;
+
+ if (recordedChunksRef.current.length > 0) {
+ const firstChunk = recordedChunksRef.current[0];
+ if (firstChunk) {
+ const type = firstChunk.type;
+
+ if (type.includes("mp4")) {
+ actualExtension = "mp4";
+ } else if (type.includes("webm")) {
+ actualExtension = "webm";
+ } else if (type.includes("mp3")) {
+ actualExtension = "mp3";
+ } else if (type.includes("gif")) {
+ actualExtension = "gif";
+ }
+ }
+ }
+
const fileExtension = `.${currentSourceFormat}`;
- const newExtension = `.${currentTargetFormat}`;
+ const newExtension = `.${actualExtension}`;
const downloadFileName = file.name.replace(
new RegExp(`${fileExtension}$`),
newExtension
@@ -507,10 +604,24 @@ export const MediaFormatConverter = ({
if (outputUrl) {
URL.revokeObjectURL(outputUrl);
}
+
+ if (
+ mediaRecorderRef.current &&
+ mediaRecorderRef.current.state !== "inactive"
+ ) {
+ mediaRecorderRef.current.stop();
+ }
+
+ if (videoRef.current) {
+ videoRef.current.pause();
+ videoRef.current.src = "";
+ }
+
setFile(null);
setOutputUrl(null);
setProgress(0);
setError(null);
+ recordedChunksRef.current = [];
trackEvent(`${conversionPath}_reset`);
@@ -579,7 +690,6 @@ export const MediaFormatConverter = ({
{config.title(currentSourceFormat, currentTargetFormat)}
</h2>
- {/* Format Selector */}
<div className="w-full mb-6">
<div className="flex flex-col sm:flex-row items-center justify-center gap-3 sm:gap-2">
<div className="w-full sm:w-auto flex flex-col sm:flex-row items-center">
@@ -777,7 +887,7 @@ export const MediaFormatConverter = ({
<Button
variant="primary"
onClick={convertFile}
- disabled={!ffmpegLoaded || isConverting}
+ disabled={!mediaEngineLoaded || isConverting}
className="w-full"
>
Convert to {currentTargetFormat.toUpperCase()}
@@ -796,22 +906,35 @@ export const MediaFormatConverter = ({
)}
</div>
- {!ffmpegLoaded && !error && (
- <div className="mt-6 text-center text-gray-500">
- <p>Loading conversion engine...</p>
- <div className="mt-2 w-8 h-8 border-4 border-blue-200 border-t-blue-500 rounded-full animate-spin mx-auto"></div>
- </div>
- )}
-
<div className="mt-8 pt-6 border-t border-gray-200 text-sm text-gray-500 text-center">
<p>
This converter works entirely in your browser. Your files are never
uploaded to any server.
</p>
<p className="mt-1">
- The conversion is performed using FFmpeg, which runs locally on your
- device.
+ 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>
+ <strong>Safari Compatibility Notice:</strong> Safari has limited
+ support for some media conversion features. For best results,
+ consider using Chrome or Firefox.
+ </p>
+ </div>
+ )}
+ {isFirefox &&
+ currentSourceFormat === "webm" &&
+ currentTargetFormat === "mp4" && (
+ <div className="mt-3 p-3 bg-yellow-50 border border-yellow-200 rounded-md text-yellow-700">
+ <p>
+ <strong>Firefox Compatibility Notice:</strong> Firefox doesn't
+ fully support converting WebM to MP4. The file will be encoded
+ using WebM container format. For best results, try using Chrome.
+ </p>
+ </div>
+ )}
</div>
</div>
);
diff --git a/apps/web/components/tools/SpeedController.tsx b/apps/web/components/tools/SpeedController.tsx
index decc9a64b..1411046fd 100644
--- a/apps/web/components/tools/SpeedController.tsx
+++ b/apps/web/components/tools/SpeedController.tsx
@@ -2,8 +2,6 @@
import { useState, useRef, useEffect } from "react";
import { Button } from "@cap/ui";
-import { FFmpeg } from "@ffmpeg/ffmpeg";
-import { fetchFile } from "@ffmpeg/util";
import { trackEvent } from "@/app/utils/analytics";
const SPEED_OPTIONS = [
@@ -24,45 +22,21 @@ export const SpeedController = () => {
const [progress, setProgress] = useState(0);
const [outputUrl, setOutputUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
- const [ffmpegLoaded, setFfmpegLoaded] = useState(false);
+ const [mediaEngineLoaded, setMediaEngineLoaded] = useState(true);
const [isDragging, setIsDragging] = useState(false);
const [selectedSpeed, setSelectedSpeed] = useState<number>(1.5);
const [videoInfo, setVideoInfo] = useState<{
duration: number;
dimensions: string;
} | null>(null);
+ const [isSafari, setIsSafari] = useState(false);
+ const [selectedMimeType, setSelectedMimeType] = useState<string>("");
- const ffmpegRef = useRef<FFmpeg | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const videoPreviewRef = useRef<HTMLVideoElement | null>(null);
-
- useEffect(() => {
- const loadFFmpeg = async () => {
- try {
- const ffmpegInstance = new FFmpeg();
- ffmpegRef.current = ffmpegInstance;
-
- ffmpegInstance.on("progress", ({ progress }: { progress: number }) => {
- setProgress(Math.round(progress * 100));
- });
-
- await ffmpegInstance.load();
- setFfmpegLoaded(true);
- trackEvent("speed_controller_loaded");
- } catch (err) {
- setError("Failed to load FFmpeg. Please try again later.");
- console.error("FFmpeg loading error:", err);
- }
- };
-
- loadFFmpeg();
-
- return () => {
- if (outputUrl) {
- URL.revokeObjectURL(outputUrl);
- }
- };
- }, []);
+ const videoRef = useRef<HTMLVideoElement | null>(null);
+ const mediaRecorderRef = useRef<MediaRecorder | null>(null);
+ const recordedChunksRef = useRef<Blob[]>([]);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];
@@ -138,7 +112,7 @@ export const SpeedController = () => {
};
const processVideo = async () => {
- if (!file || !ffmpegLoaded || !ffmpegRef.current) return;
+ if (!file || !mediaEngineLoaded) return;
setIsProcessing(true);
setError(null);
@@ -152,99 +126,12 @@ export const SpeedController = () => {
});
try {
- const ffmpeg = ffmpegRef.current;
- const inputFileName = `input_${Date.now()}.mp4`;
- const outputFileName = `output_${Date.now()}.mp4`;
-
console.log(`Starting video speed adjustment: ${selectedSpeed}x`);
console.log(`Input file: ${file.name}, size: ${file.size} bytes`);
- await ffmpeg.writeFile(inputFileName, await fetchFile(file));
- console.log("File written to FFmpeg virtual filesystem");
-
- let atempoFilter = "";
- let speedFactor = selectedSpeed;
-
- if (selectedSpeed < 0.5) {
- atempoFilter = `atempo=0.5,atempo=${selectedSpeed / 0.5}`;
- } else if (selectedSpeed > 2) {
- const iterations = Math.ceil(Math.log2(selectedSpeed));
- const values = [];
- let remaining = selectedSpeed;
-
- for (let i = 0; i < iterations; i++) {
- if (remaining > 2) {
- values.push(2);
- remaining /= 2;
- } else {
- values.push(remaining);
- break;
- }
- }
-
- atempoFilter = values.map((v) => `atempo=${v}`).join(",");
- } else {
- atempoFilter = `atempo=${speedFactor}`;
- }
-
- const command = [
- "-i",
- inputFileName,
- "-filter_complex",
- `[0:v]setpts=${1 / selectedSpeed}*PTS[v];[0:a]${atempoFilter}[a]`,
- "-map",
- "[v]",
- "-map",
- "[a]",
- "-c:v",
- "libx264",
- "-preset",
- "medium",
- "-crf",
- "23",
- "-c:a",
- "aac",
- "-b:a",
- "128k",
- outputFileName,
- ];
-
- console.log("FFmpeg command:", command);
-
- await ffmpeg.exec(command);
- console.log("FFmpeg command executed");
-
- const data = await ffmpeg.readFile(outputFileName);
- console.log(`Output data received, type: ${typeof data}`);
-
- if (!data) {
- throw new Error(
- "Processing resulted in an empty file. Please try again."
- );
- }
-
- const blob = new Blob([data], { type: "video/mp4" });
- console.log(`Output blob created, size: ${blob.size} bytes`);
-
- if (blob.size < 1024 && file.size > 10 * 1024) {
- throw new Error(
- "Processing produced an unusually small file. It may be corrupted."
- );
- }
-
- const url = URL.createObjectURL(blob);
-
- setOutputUrl(url);
-
- trackEvent(`speed_controller_${action}_completed`, {
- fileSize: file.size,
- fileName: file.name,
- outputSize: blob.size,
- speedFactor: selectedSpeed,
- });
-
- await ffmpeg.deleteFile(inputFileName);
- await ffmpeg.deleteFile(outputFileName);
+ const fileUrl = URL.createObjectURL(file);
+ await adjustVideoSpeed(fileUrl);
+ URL.revokeObjectURL(fileUrl);
} catch (err: any) {
console.error("Detailed processing error:", err);
@@ -270,13 +157,271 @@ export const SpeedController = () => {
}
};
+ const adjustVideoSpeed = async (videoUrl: string): Promise<void> => {
+ return new Promise((resolve, reject) => {
+ const video = document.createElement("video");
+ videoRef.current = video;
+ video.src = videoUrl;
+ video.muted = true;
+
+ video.oncanplay = async () => {
+ try {
+ const canvas = document.createElement("canvas");
+ canvas.width = video.videoWidth;
+ canvas.height = video.videoHeight;
+ const ctx = canvas.getContext("2d", { alpha: false });
+
+ if (!ctx) {
+ throw new Error("Failed to create canvas context");
+ }
+
+ let inputFormat = "video/webm";
+ if (file?.type) {
+ inputFormat = file.type;
+ } else if (file?.name) {
+ const extension = file.name.split(".").pop()?.toLowerCase();
+ if (extension === "mp4") inputFormat = "video/mp4";
+ else if (extension === "webm") inputFormat = "video/webm";
+ else if (extension === "mov") inputFormat = "video/quicktime";
+ }
+
+ let mimeTypes: string[] = [];
+
+ if (inputFormat.includes("mp4")) {
+ mimeTypes = [
+ "video/mp4",
+ "video/webm;codecs=vp9,opus",
+ "video/webm;codecs=vp8,opus",
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8",
+ "video/webm",
+ ];
+ } else {
+ mimeTypes = [
+ "video/webm;codecs=vp9,opus",
+ "video/webm;codecs=vp8,opus",
+ "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;
+ }
+ }
+
+ if (!selectedMimeType) {
+ throw new Error(
+ "None of the media formats are supported by this browser"
+ );
+ }
+
+ setSelectedMimeType(selectedMimeType);
+ console.log(
+ `Input format: ${inputFormat}, Selected output format: ${selectedMimeType}`
+ );
+
+ let includeAudio = true;
+ const supportsAudio = MediaRecorder.isTypeSupported(
+ selectedMimeType +
+ (selectedMimeType.includes("codecs=") ? ",opus" : ";codecs=opus")
+ );
+
+ if (!supportsAudio) {
+ console.warn(
+ "Selected MIME type does not support audio: " + selectedMimeType
+ );
+ includeAudio = false;
+ }
+
+ const stream = canvas.captureStream(60);
+
+ video.muted = true;
+ if (includeAudio) {
+ 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", audioErr);
+ }
+ }
+
+ const recorder = new MediaRecorder(stream, {
+ mimeType: selectedMimeType,
+ videoBitsPerSecond: 5000000,
+ });
+ mediaRecorderRef.current = recorder;
+ recordedChunksRef.current = [];
+
+ recorder.ondataavailable = (e) => {
+ if (e.data.size > 0) {
+ recordedChunksRef.current.push(e.data);
+ }
+ };
+
+ recorder.onstop = () => {
+ const chunks = recordedChunksRef.current;
+ const blob = new Blob(chunks, {
+ type: selectedMimeType.split(";")[0],
+ });
+ const url = URL.createObjectURL(blob);
+
+ setOutputUrl(url);
+
+ trackEvent(
+ `speed_controller_${
+ selectedSpeed < 1 ? "slowing_down" : "speeding_up"
+ }_completed`,
+ {
+ fileSize: file!.size,
+ fileName: file!.name,
+ outputSize: blob.size,
+ speedFactor: selectedSpeed,
+ }
+ );
+
+ videoRef.current = null;
+ mediaRecorderRef.current = null;
+ resolve();
+ };
+
+ recorder.start(1000);
+
+ video.playbackRate = selectedSpeed;
+
+ const finishProcessing = () => {
+ if (recorder.state === "recording") {
+ recorder.stop();
+ }
+ setProgress(100);
+ cancelAnimationFrame(animationFrameId);
+ };
+
+ const totalDuration = video.duration / selectedSpeed;
+ let lastProgress = 0;
+ let stuckCounter = 0;
+ let isFrameStuck = false;
+ let lastFrameTime = 0;
+ let animationFrameId: number;
+
+ const renderFrame = () => {
+ if (video.readyState >= 2) {
+ const currentTime = video.currentTime;
+ const currentProgress = (currentTime / video.duration) * 100;
+
+ if (currentTime !== lastFrameTime) {
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
+ lastFrameTime = currentTime;
+ isFrameStuck = false;
+ } else {
+ isFrameStuck = true;
+ }
+
+ if (Math.abs(currentProgress - lastProgress) < 0.1) {
+ stuckCounter++;
+ if (stuckCounter > 180 && currentProgress > 95) {
+ console.log(
+ "Progress appears to be stuck, forcing completion"
+ );
+ finishProcessing();
+ return;
+ }
+ } else {
+ stuckCounter = 0;
+ lastProgress = currentProgress;
+ }
+
+ setProgress(Math.min(Math.round(currentProgress), 99));
+ }
+
+ if (video.ended || (isFrameStuck && stuckCounter > 300)) {
+ finishProcessing();
+ } else {
+ animationFrameId = requestAnimationFrame(renderFrame);
+ }
+ };
+
+ video
+ .play()
+ .then(() => {
+ animationFrameId = requestAnimationFrame(renderFrame);
+ })
+ .catch((err) => {
+ console.error("Error playing video:", err);
+ reject(err);
+ });
+
+ const safetyTimeout = setTimeout(() => {
+ if (recorder.state === "recording") {
+ console.log("Safety timeout reached, forcing completion");
+ finishProcessing();
+ }
+ }, totalDuration * 1000 + 5000);
+
+ video.onended = () => {
+ clearTimeout(safetyTimeout);
+ setTimeout(() => {
+ finishProcessing();
+ }, 500);
+ };
+ } catch (err) {
+ reject(err);
+ }
+ };
+
+ video.onerror = () => {
+ reject(new Error("Error loading video"));
+ };
+ });
+ };
+
const handleDownload = () => {
if (!outputUrl || !file) return;
const dotIndex = file.name.lastIndexOf(".");
const baseName =
dotIndex !== -1 ? file.name.substring(0, dotIndex) : file.name;
- const downloadFileName = `${baseName}_${selectedSpeed}x.mp4`;
+
+ const chunks = recordedChunksRef.current;
+ let extension = "webm";
+
+ if (chunks.length > 0) {
+ const firstChunk = chunks[0];
+ if (firstChunk) {
+ const type = firstChunk.type;
+ if (type.includes("mp4")) {
+ extension = "mp4";
+ } else if (type.includes("webm")) {
+ extension = "webm";
+ } else if (type.includes("quicktime") || type.includes("mov")) {
+ extension = "mov";
+ }
+ }
+ } else {
+ if (selectedMimeType.includes("mp4")) {
+ extension = "mp4";
+ } else if (selectedMimeType.includes("webm")) {
+ extension = "webm";
+ } else if (
+ selectedMimeType.includes("quicktime") ||
+ selectedMimeType.includes("mov")
+ ) {
+ extension = "mov";
+ }
+ }
+
+ const downloadFileName = `${baseName}_${selectedSpeed}x.${extension}`;
trackEvent(`speed_controller_download_clicked`, {
fileName: downloadFileName,
@@ -293,11 +438,25 @@ export const SpeedController = () => {
if (outputUrl) {
URL.revokeObjectURL(outputUrl);
}
+
+ if (
+ mediaRecorderRef.current &&
+ mediaRecorderRef.current.state !== "inactive"
+ ) {
+ mediaRecorderRef.current.stop();
+ }
+
+ if (videoRef.current) {
+ videoRef.current.pause();
+ videoRef.current.src = "";
+ }
+
setFile(null);
setOutputUrl(null);
setProgress(0);
setError(null);
setVideoInfo(null);
+ recordedChunksRef.current = [];
trackEvent(`speed_controller_reset`);
@@ -318,6 +477,13 @@ export const SpeedController = () => {
return formatDuration(estimatedDuration);
};
+ useEffect(() => {
+ const isSafariBrowser = /^((?!chrome|android).)*safari/i.test(
+ navigator.userAgent
+ );
+ setIsSafari(isSafariBrowser);
+ }, []);
+
return (
<div className="w-full">
<h2 className="text-2xl font-semibold text-center mb-6">
@@ -470,7 +636,7 @@ export const SpeedController = () => {
<Button
variant="primary"
onClick={processVideo}
- disabled={!ffmpegLoaded || isProcessing}
+ disabled={!mediaEngineLoaded || isProcessing}
className="w-full"
>
{selectedSpeed < 1 ? "Slow Down" : "Speed Up"} Video (
@@ -490,22 +656,24 @@ export const SpeedController = () => {
)}
</div>
- {!ffmpegLoaded && !error && (
- <div className="mt-6 text-center text-gray-500">
- <p>Loading processing engine...</p>
- <div className="mt-2 w-8 h-8 border-4 border-blue-200 border-t-blue-500 rounded-full animate-spin mx-auto"></div>
- </div>
- )}
-
<div className="mt-8 pt-6 border-t border-gray-200 text-sm text-gray-500 text-center">
<p>
This tool works entirely in your browser. Your videos are never
uploaded to any server.
</p>
<p className="mt-1">
- Video processing is performed using FFmpeg, which runs locally on your
- device.
+ Powered by modern browser APIs like MediaRecorder and Canvas for
+ efficient video processing.
</p>
+ {isSafari && (
+ <div className="mt-3 p-3 bg-yellow-50 border border-yellow-200 rounded-md text-yellow-700">
+ <p>
+ <strong>Safari Compatibility Notice:</strong> Safari has limited
+ support for some video processing features. For best results,
+ consider using Chrome or Firefox.
+ </p>
+ </div>
+ )}
</div>
</div>
);
diff --git a/apps/web/components/tools/ToolsPageTemplate.tsx b/apps/web/components/tools/ToolsPageTemplate.tsx
index 0f0e5b695..6e69fef93 100644
--- a/apps/web/components/tools/ToolsPageTemplate.tsx
+++ b/apps/web/components/tools/ToolsPageTemplate.tsx
@@ -4,6 +4,7 @@ import { Button } from "@cap/ui";
import { ToolPageContent } from "@/components/tools/types";
import { useEffect, ReactNode } from "react";
import { motion } from "framer-motion";
+import Link from "next/link";
const renderHTML = (content: string) => {
const styledContent = content.replace(
@@ -119,7 +120,21 @@ export const ToolsPageTemplate = ({
<>
{/* Compact Hero Section */}
<div className="relative mt-[60px] overflow-hidden bg-gradient-to-b from-blue-50/50 to-white">
- <div className="relative z-10 px-5 pt-12 pb-6 md:pt-16 md:pb-8 w-full">
+ {/* Breadcrumbs */}
+ <div className="wrapper relative z-20 pt-4 px-5 text-center">
+ <div className="flex items-center justify-center text-sm">
+ <Link
+ className="text-gray-500 hover:underline text-sm font-semibold"
+ href="/tools"
+ >
+ Tools
+ </Link>
+ <span className="mx-2 text-gray-400 text-sm">/</span>
+ <span className="text-gray-500 text-sm">{content.title}</span>
+ </div>
+ </div>
+
+ <div className="relative z-10 px-5 pt-8 pb-6 md:pt-12 md:pb-8 w-full">
<div className="mx-auto text-center wrapper wrapper-sm max-w-3xl">
<h1 className="fade-in-down text-[2rem] leading-[2.5rem] md:text-[2.75rem] md:leading-[3.25rem] relative z-10 text-black mb-4">
{content.title}
diff --git a/apps/web/package.json b/apps/web/package.json
index 9b64d05cc..8ed69012f 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -21,8 +21,6 @@
"@cap/utils": "workspace:*",
"@cap/web-api-contract": "workspace:*",
"@deepgram/sdk": "^3.3.4",
- "@ffmpeg/ffmpeg": "^0.12.10",
- "@ffmpeg/util": "^0.12.1",
"@fortawesome/free-brands-svg-icons": "^6.7.2",
"@fortawesome/free-solid-svg-icons": "^6.7.2",
"@fortawesome/react-fontawesome": "^0.2.2",
@@ -36,6 +34,8 @@
"@radix-ui/react-tooltip": "^1.2.0",
"@react-email/components": "^0.0.13",
"@react-email/render": "0.0.11",
+ "@remotion/media-parser": "^4.0.291",
+ "@remotion/webcodecs": "^4.0.291",
"@rive-app/react-canvas": "^4.18.7",
"@stripe/stripe-js": "^3.3.0",
"@t3-oss/env-nextjs": "^0.12.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 64ad9af5c..d617658bd 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -479,6 +479,12 @@ importers:
'@react-email/render':
specifier: 0.0.11
version: 0.0.11
+ '@remotion/media-parser':
+ specifier: ^4.0.291
+ version: 4.0.291
+ '@remotion/webcodecs':
+ specifier: ^4.0.291
+ version: 4.0.291
'@rive-app/react-canvas':
specifier: ^4.18.7
version: 4.18.7([email protected])
@@ -5119,6 +5125,15 @@ packages:
resolution: {integrity: sha512-baiMx18+IMuD1yyvOGaHM9QrVUPGGG0jC+z+IPHnRJWUAUvaKuWKyE8gjDj2rzv3sz9zOGoRSPgeBVHRhZnBlA==}
engines: {node: '>=14.0.0'}
+ '@remotion/[email protected]':
+ resolution: {integrity: sha512-+0yfhhgXHPfRUG7Oqo99wN6EqjKRCtDZc9dGDB9mQjMiyJYkyFUjZRtp+CYTIhA8fBy9FsUQAZEheb3/AkHmdw==}
+
+ '@remotion/[email protected]':
+ resolution: {integrity: sha512-NV+qetN27mmBGNu6k8YG03/y0mLPkIoZ1xmuZDbejobyRcdY2mklVOde8+iD8QcssL8KjZhjC8hRsCOt7o9Mqg==}
+
+ '@remotion/[email protected]':
+ resolution: {integrity: sha512-v9kd/Wves5ZRH1zUoBipD/FnZtJvL75r/c7mdFSCO3fEC+gzEw4BLcz+HzY4Gyoj3VuOFpFTxyH3fpmwM/PZ0g==}
+
'@rive-app/[email protected]':
resolution: {integrity: sha512-0/L3jsLdpVXfZHqkK6famgLQf7wFT1TuWrB4A8I8K+/uLPulpTK76/jJ78odCdZ7WyO5OpRkK2OwuW5MvH4qJg==}
@@ -5875,10 +5890,10 @@ packages:
react-dom:
optional: true
- '@storybook/[email protected]':
- resolution: {integrity: sha512-D718PrP4rbppHUE7HsosbHxTQNGRal4BazV6RCrDWnu4+UG64qur3KztjxeGZdU+Sv7UEF5BJiYEokQHH0aBNw==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-FBrVGft5u26aB47AU5k4CgHqwAFp075KFAyRSj3eeqb8kJjHDuGeFKL02fr7dprqAYsko0BkksTWbYm/+c0ysg==}
peerDependencies:
- storybook: ^9.0.0-beta.4
+ storybook: ^9.0.0-beta.5
vite: ^5.0.0 || ^6.0.0
'@storybook/[email protected]':
@@ -5889,10 +5904,10 @@ packages:
peerDependencies:
storybook: ^8.3.3
- '@storybook/[email protected]':
- resolution: {integrity: sha512-eHyYQBWW5kwn8HtaDooIeT0nuhQysafyHL5QfPlyErAzDn1oVR+0EDWPlEgXy0pzqVzY3Axh3SqZ37ccA7kIeA==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-JoParjJNyRlzzJyoacPJSpeoZMT1JRNZfzsiLK8OH3ko1cnQrx0I38q2/w7rUOiqxEyp40DEwAmjv0srRHOJBA==}
peerDependencies:
- storybook: ^9.0.0-beta.4
+ storybook: ^9.0.0-beta.5
'@storybook/[email protected]':
resolution: {integrity: sha512-dHYFQH3mA+EtnCkHXzicbLgsvzYjcDJ1JWsogbItZogkPHgSJM/Wr71uMkcvw8v9mmCyP4NpXJuu6bPoVsOnzg==}
@@ -18039,6 +18054,15 @@ snapshots:
'@remix-run/[email protected]': {}
+ '@remotion/[email protected]': {}
+
+ '@remotion/[email protected]': {}
+
+ '@remotion/[email protected]':
+ dependencies:
+ '@remotion/licensing': 4.0.291
+ '@remotion/media-parser': 4.0.291
+
'@rive-app/[email protected]': {}
'@rive-app/[email protected]': {}
@@ -18930,9 +18954,9 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
- '@storybook/csf-plugin': 9.0.0-beta.4([email protected])
+ '@storybook/csf-plugin': 9.0.0-beta.5([email protected])
browser-assert: 1.2.1
storybook: 8.3.3
ts-dedent: 2.2.0
@@ -18963,7 +18987,7 @@ snapshots:
storybook: 8.3.3
unplugin: 1.16.1
dependencies:
storybook: 8.3.3
unplugin: 1.16.1
@@ -27382,7 +27406,7 @@ snapshots:
dependencies:
transitivePeerDependencies:
- storybook
- vite