Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip: Ffmpeg segments on initial load

Richie McIlroyabe46acdfcb8
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 64023c97f..4bdd421ce 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -79,7 +79,7 @@ fn main() {
if let Some(options_window) = app.get_window("options") {
let _ = options_window.move_window(Position::Center);
#[cfg(target_os = "macos")]
- apply_vibrancy(&options_window, NSVisualEffectMaterial::HudWindow, None, Some(16.0)).expect("Unsupported platform! 'apply_vibrancy' is only supported on macOS");
+ apply_vibrancy(&options_window, NSVisualEffectMaterial::MediumLight, None, Some(16.0)).expect("Unsupported platform! 'apply_vibrancy' is only supported on macOS");
#[cfg(target_os = "windows")]
apply_blur(&options_window, Some((255, 255, 255, 255))).expect("Unsupported platform! 'apply_blur' is only supported on Windows");
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index 39d85f6cc..f9fa5485d 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -19,7 +19,7 @@ pub async fn upload_file(
.ok_or("Invalid file path")?
.to_string();
- let file_key = format!("{}/{}/{}/{}", options.user_id, file_type, options.video_id, file_name);
+ let file_key = format!("{}/{}/{}/{}", options.user_id, options.video_id, file_type, file_name);
// Here we assume your server listens on localhost:3000 and the route is `api/upload/new`
let server_url = format!("http://localhost:3000/api/upload/new");
diff --git a/apps/web/app/share/[videoId]/Share.tsx b/apps/web/app/share/[videoId]/Share.tsx
index 237794e43..b1bbdde46 100644
--- a/apps/web/app/share/[videoId]/Share.tsx
+++ b/apps/web/app/share/[videoId]/Share.tsx
@@ -1,17 +1,172 @@
"use client";
-import { videos } from "@cap/database/schema";
+import { fetchFile } from "@ffmpeg/util";
+import { useEffect, useRef, useState } from "react";
import { ShareHeader } from "./_components/ShareHeader";
-import { ShareVideo } from "./_components/ShareVideo";
+import { videos } from "@cap/database/schema";
+import { FFmpeg as FfmpegType } from "@ffmpeg/ffmpeg";
+
+export const Share = ({
+ data,
+ urls,
+}: {
+ data: typeof videos.$inferSelect;
+ urls: {
+ videoUrls: string[];
+ screenUrls: string[];
+ singleScreenUrl: string;
+ singleVideoUrl: string;
+ };
+}) => {
+ const [videoSrc, setVideoSrc] = useState<string>("");
+ const [screenSrc, setScreenSrc] = useState<string>("");
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const screenRef = useRef<HTMLVideoElement>(null);
+ const [loading, setLoading] = useState(true);
+ const [ffmpegLoaded, setFfmpegLoaded] = useState(false);
+ const ffmpegRef = useRef<FfmpegType | null>(null);
+
+ useEffect(() => {
+ const loadFfmpeg = async () => {
+ const { FFmpeg } = await import("@ffmpeg/ffmpeg");
+ ffmpegRef.current = new FFmpeg();
+ setFfmpegLoaded(true);
+ };
+
+ if (!ffmpegLoaded && !ffmpegRef.current) {
+ loadFfmpeg();
+ }
+ }, [ffmpegLoaded]);
+
+ const concatenateSegments = async (
+ ffmpeg: FfmpegType,
+ segmentsUrls: string[],
+ outputFilename: string,
+ inputFormat: string,
+ outputFormat: string
+ ) => {
+ if (!ffmpegRef.current) {
+ throw new Error("FFmpeg not loaded");
+ }
+
+ console.log("concatenateSegments:", segmentsUrls);
+
+ await ffmpegRef.current.load();
+
+ // Feed the video segments to FFmpeg
+ for (let i = 0; i < segmentsUrls.length; i++) {
+ console.log("Fetching file...");
+ const fetchedFile = await fetchFile(segmentsUrls[i]);
+ ffmpeg.writeFile(`file${i}.${inputFormat}`, fetchedFile);
+ }
+
+ // Create a file with all the file names
+ const fileList = "file_list.txt";
+ const concatList = segmentsUrls
+ .map((url, index) => `file file${index}.${inputFormat}`)
+ .join("\n");
+ ffmpeg.writeFile(fileList, concatList);
+
+ console.log("Concatenating using ffmpeg script...");
+
+ await ffmpeg.exec([
+ "-f",
+ "concat",
+ "-safe",
+ "0",
+ "-i",
+ fileList,
+ "-r",
+ `${outputFilename === "video_output.mp4" ? 30 : 60}`,
+ "-c",
+ "copy",
+ outputFilename,
+ ]);
+
+ // Read the resulting file
+ const data = ffmpeg.readFile(outputFilename);
+
+ // Convert the data to a Blob
+ // const videoBlob = new Blob([data.buffer], { type: `video/${outputFormat}` });
+
+ // // Create a URL for the Blob
+ // const videoUrl = URL.createObjectURL(videoBlob);
+
+ // Return the URL to the MP4 on S3
+ return data;
+ };
+
+ useEffect(() => {
+ const loadVideos = async () => {
+ setLoading(true);
+ try {
+ if (urls.videoUrls.length > 0 && ffmpegRef.current) {
+ const concatenatedVideoData = await concatenateSegments(
+ ffmpegRef.current,
+ urls.videoUrls,
+ "video_output.mp4",
+ "webm",
+ "mp4"
+ );
+ setVideoSrc(
+ URL.createObjectURL(
+ new Blob([concatenatedVideoData], { type: "video/mp4" })
+ )
+ );
+ } else if (urls.singleVideoUrl) {
+ setVideoSrc(urls.singleVideoUrl);
+ }
+
+ if (urls.screenUrls.length > 0 && ffmpegRef.current) {
+ const concatenatedScreenData = await concatenateSegments(
+ ffmpegRef.current,
+ urls.screenUrls,
+ "screen_output.mp4",
+ "mkv",
+ "mp4"
+ );
+ setScreenSrc(
+ URL.createObjectURL(
+ new Blob([concatenatedScreenData], { type: "video/mp4" })
+ )
+ );
+ } else if (urls.singleScreenUrl) {
+ setScreenSrc(urls.singleScreenUrl);
+ }
+ } catch (error) {
+ console.error("Error loading videos", error);
+ // Handle video loading error if desired
+ } finally {
+ setLoading(false); // End loading process
+ }
+ };
+
+ loadVideos();
+ }, [urls, ffmpegLoaded]);
-export const Share = async ({ data }: { data: typeof videos.$inferSelect }) => {
return (
<div className="wrapper py-6">
<div className="space-y-8">
<ShareHeader title={data.name} />
- <ShareVideo
- data={{ title: data.name, created: data.createdAt.toISOString() }}
- />
+ <div className="aspect-video">
+ {loading ? (
+ <p>Loading</p>
+ ) : (
+ <>
+ {screenSrc && (
+ <div className="absolute bottom-2 right-0 w-[180px] h-[180px] m-0 p-0 rounded-full overflow-hidden">
+ <video
+ ref={screenRef}
+ className="w-full h-full object-cover"
+ controls
+ src={screenSrc}
+ />
+ </div>
+ )}
+ {videoSrc && <video ref={videoRef} controls src={videoSrc} />}
+ </>
+ )}
+ </div>
</div>
</div>
);
diff --git a/apps/web/app/share/[videoId]/page.tsx b/apps/web/app/share/[videoId]/page.tsx
index c67d64c4d..2963bcea6 100644
--- a/apps/web/app/share/[videoId]/page.tsx
+++ b/apps/web/app/share/[videoId]/page.tsx
@@ -1,25 +1,164 @@
"use server";
import { Share } from "./Share";
-import { uuidFormat } from "@cap/utils";
import { db } from "@cap/database";
import { eq } from "drizzle-orm";
import { videos } from "@cap/database/schema";
+import {
+ S3Client,
+ ListObjectsV2Command,
+ GetObjectCommand,
+ HeadObjectCommand,
+} from "@aws-sdk/client-s3";
+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
type Props = {
params: { [key: string]: string | string[] | undefined };
};
+const revalidate = 0;
+
+const s3Client = new S3Client({
+ region: process.env.CAP_AWS_REGION || "",
+ credentials: {
+ accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
+ secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
+ },
+});
+
+async function generateVideoSegmentUrls(userId: string, videoId: string) {
+ const bucket = process.env.CAP_AWS_BUCKET || "";
+ const outputScreenKey = `${userId}/${videoId}/screen_output.mp4`;
+ const outputVideoKey = `${userId}/${videoId}/video_output.mp4`;
+
+ // Prefixes for screen and video segments
+ const screenPrefix = `${userId}/${videoId}/screen/`;
+ const videoPrefix = `${userId}/${videoId}/video/`;
+
+ const checkSingleOutputsExist = async (key: string) => {
+ try {
+ const headObjectCommand = new HeadObjectCommand({
+ Bucket: bucket,
+ Key: key,
+ });
+ await s3Client.send(headObjectCommand);
+ return true;
+ } catch (error: any) {
+ if (error?.name === "NotFound") return false;
+ throw error;
+ }
+ };
+
+ const doesScreenOutputExist = await checkSingleOutputsExist(outputScreenKey);
+ const doesVideoOutputExist = await checkSingleOutputsExist(outputVideoKey);
+
+ if (doesScreenOutputExist && doesVideoOutputExist) {
+ // Return pre-signed URLs for the single output files
+ const screenOutputUrl = await getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket: bucket,
+ Key: outputScreenKey,
+ })
+ );
+
+ const videoOutputUrl = await getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket: bucket,
+ Key: outputVideoKey,
+ })
+ );
+
+ return {
+ singleScreenUrl: screenOutputUrl,
+ singleVideoUrl: videoOutputUrl,
+ screenChunksUrls: [],
+ videoChunksUrls: [],
+ };
+ }
+
+ try {
+ // Fetch the list of objects for screen recordings
+ const screenObjectsCommand = new ListObjectsV2Command({
+ Bucket: bucket,
+ Prefix: screenPrefix,
+ });
+ const screenObjects = await s3Client.send(screenObjectsCommand);
+
+ // Fetch the list of objects for video recordings
+ const videoObjectsCommand = new ListObjectsV2Command({
+ Bucket: bucket,
+ Prefix: videoPrefix,
+ });
+ const videoObjects = await s3Client.send(videoObjectsCommand);
+
+ // Generate pre-signed URLs for screen recording chunks
+ const screenChunksUrls = await Promise.all(
+ (screenObjects.Contents || []).map(async (object) => {
+ return getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket: bucket,
+ Key: object.Key,
+ }),
+ { expiresIn: 3600 }
+ );
+ })
+ );
+
+ // Generate pre-signed URLs for video recording chunks
+ const videoChunksUrls = await Promise.all(
+ (videoObjects.Contents || []).map(async (object) => {
+ return getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket: bucket,
+ Key: object.Key,
+ }),
+ { expiresIn: 3600 }
+ );
+ })
+ );
+
+ return {
+ screenChunksUrls,
+ videoChunksUrls,
+ singleScreenUrl: "",
+ singleVideoUrl: "",
+ };
+ } catch (error) {
+ console.error("Error generating video segment URLs", error);
+ throw new Error("Could not generate video segment URLs");
+ }
+}
+
export default async function ShareVideoPage(props: Props) {
const params = props.params;
- const videoId = uuidFormat(params.videoId as string);
+ const videoId = params.videoId as string;
+
+ console.log("videoId: ", videoId);
const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ console.log("query", query);
+
if (query.length === 0) {
return <p>No video found</p>;
}
const video = query[0];
- return <Share data={video} />;
+ const urls = await generateVideoSegmentUrls(video.ownerId, video.id);
+
+ const videoUrls = urls.videoChunksUrls || [];
+ const screenUrls = urls.screenChunksUrls || [];
+ const singleVideoUrl = urls.singleVideoUrl || "";
+ const singleScreenUrl = urls.singleScreenUrl || "";
+
+ return (
+ <Share
+ data={video}
+ urls={{ videoUrls, screenUrls, singleScreenUrl, singleVideoUrl }}
+ />
+ );
}
diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs
index f7f550538..f3fac1885 100644
--- a/apps/web/next.config.mjs
+++ b/apps/web/next.config.mjs
@@ -41,6 +41,23 @@ const nextConfig = {
},
],
},
+ {
+ source: "/(.*)",
+ headers: [
+ {
+ key: "Access-Control-Allow-Origin",
+ value: "https://*.amazonaws.com",
+ },
+ {
+ key: "Access-Control-Allow-Methods",
+ value: "GET",
+ },
+ {
+ key: "Access-Control-Allow-Credentials",
+ value: "true",
+ },
+ ],
+ },
];
},
};
diff --git a/apps/web/package.json b/apps/web/package.json
index 19dd813c6..7b42a0029 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -15,6 +15,8 @@
"@cap/database": "workspace:*",
"@cap/ui": "workspace:*",
"@cap/utils": "workspace:*",
+ "@ffmpeg/ffmpeg": "^0.12.10",
+ "@ffmpeg/util": "^0.12.1",
"@headlessui/react": "^1.7.17",
"@hookform/resolvers": "^3.3.2",
"@react-email/components": "^0.0.13",
diff --git a/apps/web/utils/video/ffmpeg/helpers.ts b/apps/web/utils/video/ffmpeg/helpers.ts
new file mode 100644
index 000000000..986303689
--- /dev/null
+++ b/apps/web/utils/video/ffmpeg/helpers.ts
@@ -0,0 +1,53 @@
+import { FFmpeg } from "@ffmpeg/ffmpeg";
+import { fetchFile } from "@ffmpeg/util";
+import { useRef, useEffect } from "react";
+
+export const concatenateSegments = async (
+ segmentsUrls: string[],
+ outputFilename: string,
+ inputFormat: string,
+ outputFormat: string
+) => {
+ const ffmpegRef = useRef(new FFmpeg());
+ const ffmpeg = ffmpegRef.current;
+
+ await ffmpeg.load();
+
+ // Feed the video segments to FFmpeg
+ for (let i = 0; i < segmentsUrls.length; i++) {
+ const fetchedFile = await fetchFile(segmentsUrls[i]);
+ ffmpeg.writeFile(`file${i}.${inputFormat}`, fetchedFile);
+ }
+
+ // Create a file with all the file names
+ const fileList = "file_list.txt";
+ const concatList = segmentsUrls
+ .map((url, index) => `file file${index}.${inputFormat}`)
+ .join("\n");
+ ffmpeg.writeFile(fileList, concatList);
+
+ // Run the FFmpeg command to concatenate
+ await ffmpeg.exec([
+ "-f",
+ "concat",
+ "-safe",
+ "0",
+ "-i",
+ fileList,
+ "-c",
+ "copy",
+ outputFilename,
+ ]);
+
+ // Read the resulting file
+ const data = ffmpeg.readFile(outputFilename);
+
+ // Convert the data to a Blob
+ // const videoBlob = new Blob([data.buffer], { type: `video/${outputFormat}` });
+
+ // // Create a URL for the Blob
+ // const videoUrl = URL.createObjectURL(videoBlob);
+
+ // Return the URL to the MP4 on S3
+ return data;
+};
diff --git a/packages/database/helpers.ts b/packages/database/helpers.ts
index ccd97fc28..77540f2ce 100644
--- a/packages/database/helpers.ts
+++ b/packages/database/helpers.ts
@@ -17,3 +17,8 @@ export const nanoIdToken = customAlphabet(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
32
);
+
+export type VideoMetadata = {
+ resolution: string;
+ framerate: string;
+};
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 2c05068f1..f010fda53 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -7,6 +7,7 @@ import {
text,
timestamp,
index,
+ boolean,
uniqueIndex,
varchar,
} from "drizzle-orm/mysql-core";
@@ -139,16 +140,16 @@ export const videos = mysqlTable(
name: varchar("name", { length: 255 }).notNull().default("My Video"),
awsRegion: varchar("awsRegion", { length: 255 }),
awsBucket: varchar("awsBucket", { length: 255 }),
- thumbnailUrl: text("thumbnailUrl"),
- duration: int("duration"),
metadata: json("metadata"),
- isPublic: int("isPublic").notNull().default(1),
+ converted: boolean("converted").notNull().default(false),
+ public: boolean("public").notNull().default(true),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
},
(table) => ({
+ idIndex: index("id_idx").on(table.id),
ownerIdIndex: index("owner_id_idx").on(table.ownerId),
- isPublicIndex: index("is_public_idx").on(table.isPublic),
+ publicIndex: index("is_public_idx").on(table.public),
})
);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4162e9196..fe1284d8d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -117,6 +117,12 @@ importers:
'@cap/utils':
specifier: workspace:*
version: link:../../packages/utils
+ '@ffmpeg/ffmpeg':
+ specifier: ^0.12.10
+ version: 0.12.10
+ '@ffmpeg/util':
+ specifier: ^0.12.1
+ version: 0.12.1
'@headlessui/react':
specifier: ^1.7.17
@@ -2004,6 +2010,23 @@ packages:
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dev: true
+ /@ffmpeg/[email protected]:
+ resolution: {integrity: sha512-lVtk8PW8e+NUzGZhPTWj2P1J4/NyuCrbDD3O9IGpSeLYtUZKBqZO8CNj1WYGghep/MXoM8e1qVY1GztTkf8YYQ==}
+ engines: {node: '>=18.x'}
+ dependencies:
+ '@ffmpeg/types': 0.12.2
+ dev: false
+
+ /@ffmpeg/[email protected]:
+ resolution: {integrity: sha512-NJtxwPoLb60/z1Klv0ueshguWQ/7mNm106qdHkB4HL49LXszjhjCCiL+ldHJGQ9ai2Igx0s4F24ghigy//ERdA==}
+ engines: {node: '>=16.x'}
+ dev: false
+
+ /@ffmpeg/[email protected]:
+ resolution: {integrity: sha512-10jjfAKWaDyb8+nAkijcsi9wgz/y26LOc1NKJradNMyCIl6usQcBbhkjX5qhALrSBcOy6TOeksunTYa+a03qNQ==}
+ engines: {node: '>=18.x'}
+ dev: false
+
/@floating-ui/[email protected]:
resolution: {integrity: sha512-O0WKDOo0yhJuugCx6trZQj5jVJ9yR0ystG2JaNAemYUWce+pmM6WUEFIibnWyEJKdrDxhm75NoSRME35FNaM/Q==}
dependencies: