Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
wip: Add resolution, codecs to m3u8 playlist
Richie McIlroyb0dcd3a6004b
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex cd2de7a49..994129fba 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -15,8 +15,25 @@ pub async fn upload_file(if let Some(ref options) = options {println!("Uploading video...");- let video_duration = get_video_duration(&file_path).await?;- let video_duration_str = format!("{:.1}", video_duration);+ let (video_duration_str, bandwidth_str, resolution, video_codec, audio_codec) = match file_type.as_str() {+ "screenshot" => ("".to_string(), "".to_string(), "".to_string(), "".to_string(), "".to_string()),+ "audio" => {+ let (video_duration, audio_codec) = get_audio_metadata(&file_path).await?;+ let video_duration_str = format!("{:.1}", video_duration);+ println!("Audio duration: {} seconds", video_duration_str);+ (video_duration_str, "".to_string(), "".to_string(), "".to_string(), audio_codec)+ },+ "video" => {+ let (video_duration, bandwidth, resolution, video_codec) = get_video_metadata(&file_path).await?;+ let video_duration_str = format!("{:.1}", video_duration);+ let bandwidth_str = format!("{}", bandwidth);+ println!("Video duration: {} seconds", video_duration_str);+ println!("Bandwidth: {} kbps", bandwidth_str);+ println!("Resolution: {}", resolution);+ (video_duration_str, bandwidth_str, resolution, video_codec, "".to_string())+ }+ _ => return Err("Invalid file type".to_string()),+ };let file_name = Path::new(&file_path).file_name()@@ -33,6 +50,10 @@ pub async fn upload_file(let body = serde_json::json!({"userId": options.user_id,"duration": video_duration_str,+ "bandwidth": bandwidth_str,+ "resolution": resolution,+ "videoCodec": video_codec,+ "audioCodec": audio_codec,"fileKey": file_key,"awsBucket": options.aws_bucket,"awsRegion": options.aws_region,@@ -127,7 +148,7 @@ pub async fn upload_file(}}-async fn get_video_duration(file_path: &str) -> Result<f64, String> {+async fn get_audio_metadata(file_path: &str) -> Result<(f64, String), String> {let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;let output = Command::new(&ffmpeg_binary_path_str)@@ -136,24 +157,68 @@ async fn get_video_duration(file_path: &str) -> Result<f64, String> {"-f", "null","-"]).output()- .map_err(|e| format!("Failed to execute FFmpeg for getting duration: {}", e))?;+ .map_err(|e| format!("Failed to execute FFmpeg for getting metadata: {}", e))?;- // Extract the duration from FFmpeg's stderr+ // Extract the metadata from FFmpeg's stderrlet stderr = String::from_utf8_lossy(&output.stderr);- println!("Stderr: {}", stderr);-+ // Extract durationlet duration_line = stderr.split('\n').find(|line| line.contains("Duration")).ok_or("Duration line not found in FFmpeg output")?;- println!("Duration line: {}", duration_line);-let duration_str = duration_line.split("Duration:").nth(1).unwrap().split(',').next().unwrap().trim();- println!("Duration string: {}", duration_str);+ let duration_parts: Vec<&str> = duration_str.split(':').collect();+ if duration_parts.len() != 3 {+ return Err("Invalid duration format".to_string());+ }++ let hours: f64 = duration_parts[0].parse().map_err(|_| "Failed to parse hours")?;+ let minutes: f64 = duration_parts[1].parse().map_err(|_| "Failed to parse minutes")?;+ let seconds: f64 = duration_parts[2].parse().map_err(|_| "Failed to parse seconds")?;++ let total_seconds = hours * 3600.0 + minutes * 60.0 + seconds;+++ // Extract audio codec+ let audio_codec_line = stderr.split('\n')+ .find(|line| line.contains("Audio:"))+ .ok_or("Audio line not found in FFmpeg output")?;++ let audio_codec_str = audio_codec_line.split("Audio:").nth(1).unwrap()+ .split(',').next().unwrap()+ .trim();++ let audio_codec = audio_codec_str.to_string();++ Ok((total_seconds, audio_codec))+}++async fn get_video_metadata(file_path: &str) -> Result<(f64, u64, String, String), String> {+ let ffmpeg_binary_path_str = ffmpeg_path_as_str()?;++ let output = Command::new(&ffmpeg_binary_path_str)+ .args(&[+ "-i", file_path,+ "-f", "null",+ "-"])+ .output()+ .map_err(|e| format!("Failed to execute FFmpeg for getting metadata: {}", e))?;++ // Extract the metadata from FFmpeg's stderr+ let stderr = String::from_utf8_lossy(&output.stderr);++ // Extract duration+ let duration_line = stderr.split('\n')+ .find(|line| line.contains("Duration"))+ .ok_or("Duration line not found in FFmpeg output")?;++ let duration_str = duration_line.split("Duration:").nth(1).unwrap()+ .split(',').next().unwrap()+ .trim();let duration_parts: Vec<&str> = duration_str.split(':').collect();if duration_parts.len() != 3 {@@ -166,5 +231,38 @@ async fn get_video_duration(file_path: &str) -> Result<f64, String> {let total_seconds = hours * 3600.0 + minutes * 60.0 + seconds;- Ok(total_seconds)+ let bitrate_line = stderr.split('\n')+ .find(|line| line.contains("bitrate"))+ .ok_or("Bitrate line not found in FFmpeg output")?;++ let bitrate_str = bitrate_line.split("bitrate:").nth(1)+ .and_then(|s| s.split(',').next())+ .and_then(|s| s.trim().split(' ').next())+ .ok_or("Failed to parse bitrate")?;++ let bitrate_kbps: u64 = bitrate_str.parse().map_err(|_| "Failed to parse bitrate")?;+ let bandwidth = bitrate_kbps * 1000;++ // Extract resolution+ let resolution_line = stderr.split('\n')+ .find(|line| line.contains("Video:"))+ .ok_or("Video line not found in FFmpeg output")?;++ let resolution_str = resolution_line.split(',').nth(2).unwrap()+ .trim()+ .split(' ').next().unwrap();++ let resolution = resolution_str.to_string();++ let video_codec_line = stderr.split('\n')+ .find(|line| line.contains("Video:"))+ .ok_or("Video line not found in FFmpeg output")?;++ let video_codec_str = video_codec_line.split("Video:").nth(1).unwrap()+ .split(',').next().unwrap()+ .trim();++ let video_codec = video_codec_str.to_string();++ Ok((total_seconds, bandwidth, resolution, video_codec))}\ No newline at end of filediff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsxindex 3e0eb6fb5..9a1c3fd58 100644--- a/apps/desktop/src/components/windows/inner/Recorder.tsx+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx@@ -6,7 +6,7 @@ import { Video } from "@/components/icons/Video";import { Microphone } from "@/components/icons/Microphone";import { Screen } from "@/components/icons/Screen";import { Window } from "@/components/icons/Window";-import { ActionButton } from "@/components/recording/ActionButton";+import { ActionButton } from "@/components/windows/inner/ActionButton";import { Button } from "@cap/ui";import { Logo } from "@/components/icons/Logo";import { emit, listen, UnlistenFn } from "@tauri-apps/api/event";diff --git a/apps/web/app/api/desktop/video/metadata/create/route.ts b/apps/web/app/api/desktop/video/metadata/create/route.tsindex c71ce2d6a..34af8e5f2 100644--- a/apps/web/app/api/desktop/video/metadata/create/route.ts+++ b/apps/web/app/api/desktop/video/metadata/create/route.ts@@ -12,11 +12,6 @@ export async function GET(request: NextRequest) {const startTime = url.searchParams.get("startTime");const logType = url.searchParams.get("logType");- console.log("...Updating video or audio start time...");- console.log("videoId", videoId);- console.log("startTime", startTime);- console.log("logType", logType);-if (!videoId || !startTime || !logType) {return new Response(JSON.stringify({ error: "Missing required fields" }),diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.tsindex 27c2d09ba..1fe1fc9f4 100644--- a/apps/web/app/api/playlist/route.ts+++ b/apps/web/app/api/playlist/route.ts@@ -138,8 +138,51 @@ export async function GET(request: NextRequest) {);}+ 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 || "",+ },+ });+if (prefix === null) {+ const videoSegmentCommand = new ListObjectsV2Command({+ Bucket: bucket,+ Prefix: videoPrefix,+ MaxKeys: 1,+ });++ const audioSegmentCommand = new ListObjectsV2Command({+ Bucket: bucket,+ Prefix: audioPrefix,+ MaxKeys: 1,+ });++ const [videoSegment, audioSegment] = await Promise.all([+ s3Client.send(videoSegmentCommand),+ s3Client.send(audioSegmentCommand),+ ]);++ const [videoMetadata, audioMetadata] = await Promise.all([+ s3Client.send(+ new HeadObjectCommand({+ Bucket: bucket,+ Key: videoSegment.Contents?.[0]?.Key ?? "",+ })+ ),+ s3Client.send(+ new HeadObjectCommand({+ Bucket: bucket,+ Key: audioSegment.Contents?.[0]?.Key ?? "",+ })+ ),+ ]);+const generatedPlaylist = await generateMasterPlaylist(+ videoMetadata?.Metadata?.resolution ?? "",+ videoMetadata?.Metadata?.videocodec ?? "",+ audioMetadata?.Metadata?.audiocodec ?? "",process.env.NEXT_PUBLIC_URL +"/api/playlist?userId=" +userId +@@ -167,14 +210,6 @@ export async function GET(request: NextRequest) {});}- 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 || "",- },- });-objectsCommand = new ListObjectsV2Command({Bucket: bucket,Prefix: prefix,@@ -200,7 +235,14 @@ export async function GET(request: NextRequest) {}));- return { url: url, duration: metadata?.Metadata?.duration ?? "" };+ return {+ url: url,+ duration: metadata?.Metadata?.duration ?? "",+ bandwidth: metadata?.Metadata?.bandwidth ?? "",+ resolution: metadata?.Metadata?.resolution ?? "",+ videoCodec: metadata?.Metadata?.videocodec ?? "",+ audioCodec: metadata?.Metadata?.audiocodec ?? "",+ };}));diff --git a/apps/web/app/api/upload/signed/route.ts b/apps/web/app/api/upload/signed/route.tsindex 7ab99bf8d..31103c34a 100644--- a/apps/web/app/api/upload/signed/route.ts+++ b/apps/web/app/api/upload/signed/route.ts@@ -12,10 +12,19 @@ const s3Client = new S3Client({export async function POST(request: NextRequest) {try {- const { userId, fileKey, duration, awsBucket, awsRegion } =- await request.json();+ const {+ userId,+ fileKey,+ duration,+ bandwidth,+ resolution,+ videoCodec,+ audioCodec,+ awsBucket,+ awsRegion,+ } = await request.json();- if (!userId || !duration || !fileKey || !awsBucket || !awsRegion) {+ if (!userId || !fileKey || !awsBucket || !awsRegion) {console.error("Missing required fields in /api/upload/signed/route.ts");return new Response(@@ -38,7 +47,11 @@ export async function POST(request: NextRequest) {const Fields = {"Content-Type": contentType,"x-amz-meta-userid": userId,- "x-amz-meta-duration": duration,+ "x-amz-meta-duration": duration ?? "",+ "x-amz-meta-bandwidth": bandwidth ?? "",+ "x-amz-meta-resolution": resolution ?? "",+ "x-amz-meta-videocodec": videoCodec ?? "",+ "x-amz-meta-audiocodec": audioCodec ?? "",};const presignedPostData: PresignedPost = await createPresignedPost(diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.tsnew file mode 100644index 000000000..9957fa127--- /dev/null+++ b/apps/web/app/api/webhooks/stripe/route.ts@@ -0,0 +1,265 @@+import prisma from "@/lib/prisma";+import { stripe } from "@/lib/stripe";+import { redis } from "@/lib/upstash";+import { db } from "@cap/database";+import { users } from "@cap/database/schema";+import { FREE_PLAN, getPlanFromPriceId, log } from "@dub/utils";+import { eq } from "drizzle-orm";+import { sendEmail } from "emails";+import UpgradeEmail from "emails/upgrade-email";+import { NextResponse } from "next/server";+import Stripe from "stripe";++const relevantEvents = new Set([+ "checkout.session.completed",+ "customer.subscription.updated",+ "customer.subscription.deleted",+]);++// POST /api/callback/stripe – listen to Stripe webhooks+export const POST = async (req: Request) => {+ const buf = await req.text();+ const sig = req.headers.get("Stripe-Signature") as string;+ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;+ let event: Stripe.Event;+ try {+ if (!sig || !webhookSecret) return;+ event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);+ } catch (err: any) {+ console.log(`❌ Error message: ${err.message}`);+ return new Response(`Webhook Error: ${err.message}`, {+ status: 400,+ });+ }+ if (relevantEvents.has(event.type)) {+ try {+ if (event.type === "checkout.session.completed") {+ const checkoutSession = event.data.object as Stripe.Checkout.Session;++ if (+ checkoutSession.client_reference_id === null ||+ checkoutSession.customer === null+ ) {+ await log({+ message: "Missing items in Stripe webhook callback",+ type: "errors",+ });+ return;+ }++ const subscription = await stripe.subscriptions.retrieve(+ checkoutSession.subscription as string+ );+ const priceId = subscription.items.data[0].price.id;++ const plan = getPlanFromPriceId(priceId);++ if (!plan) {+ await log({+ message: `Invalid price ID in checkout.session.completed event: ${priceId}`,+ type: "errors",+ });+ return;+ }++ const stripeId = checkoutSession.customer.toString();++ // when the workspace subscribes to a plan, set their stripe customer ID+ // in the database for easy identification in future webhook events+ // also update the billingCycleStart to today's date++ let referenceId;+ let isSpaceCustomer = false;+ if (checkoutSession.metadata?.space_id) {+ isSpaceCustomer = true;+ referenceId = checkoutSession.metadata?.space_id;+ } else {+ referenceId = checkoutSession.client_reference_id;+ }++ if (isSpaceCustomer === false) {+ await db+ .update(users)+ .set({+ stripeCustomerId: stripeId,+ stripeSubscriptionId: subscription.id,+ stripeSubscriptionStatus: subscription.status,+ stripeSubscriptionPriceId: priceId,+ })+ .where(eq(users.id, referenceId));+ } else {+ }++ sendEmail({+ email: users.email+ subject: `Thank you for upgrading to Cap Pro!`,+ react: UpgradeEmail({+ name: user.name,+ email: user.email as string,+ plan: plan.name,+ }),+ marketing: true,+ });+ }++ // for subscription updates+ if (event.type === "customer.subscription.updated") {+ const subscriptionUpdated = event.data.object as Stripe.Subscription;+ const priceId = subscriptionUpdated.items.data[0].price.id;++ const plan = getPlanFromPriceId(priceId);++ if (!plan) {+ await log({+ message: `Invalid price ID in customer.subscription.updated event: ${priceId}`,+ type: "errors",+ });+ return;+ }++ const stripeId = subscriptionUpdated.customer.toString();++ const workspace = await prisma.project.findUnique({+ where: {+ stripeId,+ },+ });++ if (!workspace) {+ await log({+ message:+ "Workspace with Stripe ID *`" ++ stripeId ++ "`* not found in Stripe webhook `customer.subscription.updated` callback",+ type: "errors",+ });+ return NextResponse.json({ received: true });+ }++ const newPlan = plan.name.toLowerCase();++ // If a workspace upgrades/downgrades their subscription, update their usage limit in the database.+ if (workspace.plan !== newPlan) {+ await prisma.project.update({+ where: {+ stripeId,+ },+ data: {+ plan: newPlan,+ usageLimit: plan.limits.clicks!,+ linksLimit: plan.limits.links!,+ domainsLimit: plan.limits.domains!,+ tagsLimit: plan.limits.tags!,+ usersLimit: plan.limits.users!,+ },+ });+ }+ }++ // If workspace cancels their subscription+ if (event.type === "customer.subscription.deleted") {+ const subscriptionDeleted = event.data.object as Stripe.Subscription;++ const stripeId = subscriptionDeleted.customer.toString();++ // If a workspace deletes their subscription, reset their usage limit in the database to 1000.+ // Also remove the root domain redirect for all their domains from Redis.+ const workspace = await prisma.project.findUnique({+ where: {+ stripeId,+ },+ select: {+ id: true,+ slug: true,+ domains: true,+ users: {+ select: {+ user: {+ select: {+ email: true,+ },+ },+ },+ },+ },+ });++ if (!workspace) {+ await log({+ message:+ "Workspace with Stripe ID *`" ++ stripeId ++ "`* not found in Stripe webhook `customer.subscription.deleted` callback",+ type: "errors",+ });+ return NextResponse.json({ received: true });+ }++ const workspaceUsers = workspace.users.map(+ ({ user }) => user.email as string+ );++ const pipeline = redis.pipeline();+ // remove root domain redirect for all domains+ workspace.domains.forEach((domain) => {+ pipeline.hset(domain.slug.toLowerCase(), {+ _root: {+ id: domain.id,+ projectId: workspace.id,+ },+ });+ });++ await Promise.allSettled([+ prisma.project.update({+ where: {+ stripeId,+ },+ data: {+ plan: "free",+ usageLimit: FREE_PLAN.limits.clicks!,+ linksLimit: FREE_PLAN.limits.links!,+ domainsLimit: FREE_PLAN.limits.domains!,+ tagsLimit: FREE_PLAN.limits.tags!,+ usersLimit: FREE_PLAN.limits.users!,+ },+ }),+ pipeline.exec(),+ log({+ message:+ ":cry: Workspace *`" ++ workspace.slug ++ "`* deleted their subscription",+ type: "cron",+ mention: true,+ }),+ workspaceUsers.map((email) =>+ sendEmail({+ email,+ from: "[email protected]",+ subject: "Feedback on your Dub.co experience?",+ text: "Hey!\n\nI noticed you recently cancelled your Dub.co subscription – we're sorry to see you go!\n\nI'd love to hear your feedback on your experience with Dub – what could we have done better?\n\nThanks!\n\nSteven Tey\nFounder, Dub.co",+ })+ ),+ ]);+ }+ } catch (error) {+ await log({+ message: `Stripe webook failed. Error: ${error.message}`,+ type: "errors",+ });+ return new Response(+ 'Webhook error: "Webhook handler failed. View logs."',+ {+ status: 400,+ }+ );+ }+ } else {+ return new Response(`🤷♀️ Unhandled event type: ${event.type}`, {+ status: 400,+ });+ }++ return NextResponse.json({ received: true });+};diff --git a/apps/web/utils/video/ffmpeg/helpers.ts b/apps/web/utils/video/ffmpeg/helpers.tsindex 88fd15ea1..6a61f7fda 100644--- a/apps/web/utils/video/ffmpeg/helpers.ts+++ b/apps/web/utils/video/ffmpeg/helpers.ts@@ -74,7 +74,12 @@ export const concatenateSegments = async (};export async function generateM3U8Playlist(- urls: { url: string; duration: string }[]+ urls: {+ url: string;+ duration: string;+ resolution?: string;+ bandwidth?: string;+ }[]) {const baseM3U8Content = `#EXTM3U#EXT-X-TARGETDURATION:3@@ -83,8 +88,9 @@ export async function generateM3U8Playlist(`;let m3u8Content = baseM3U8Content;- urls.forEach((url) => {- m3u8Content += `#EXTINF:${url.duration},\n${url.url}\n`;+ urls.forEach((segment) => {+ const { url, duration } = segment;+ m3u8Content += `#EXTINF:${duration},\n${url}\n`;});m3u8Content += "#EXT-X-ENDLIST";@@ -93,6 +99,9 @@ export async function generateM3U8Playlist(}export async function generateMasterPlaylist(+ resolution: string,+ videoCodec: string,+ audioCodec: string,videoPlaylistUrl: string,audioPlaylistUrl: string) {@@ -100,7 +109,7 @@ export async function generateMasterPlaylist(#EXT-X-VERSION:4#EXT-X-INDEPENDENT-SEGMENTS#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="Audio",DEFAULT=YES,AUTOSELECT=YES,LANGUAGE="en",URI="${audioPlaylistUrl}"-#EXT-X-STREAM-INF:AUDIO="audio"+#EXT-X-STREAM-INF:RESOLUTION=${resolution},CODECS="avc1.42001e,mp4a.40.2",AUDIO="audio"${videoPlaylistUrl}`;