Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: Video and audio sync (master playlist)

Richie McIlroy100396c5a17b
diff --git a/apps/desktop/src-tauri/src/media.rs b/apps/desktop/src-tauri/src/media.rs
index d43a2bca0..c00f7cb63 100644
--- a/apps/desktop/src-tauri/src/media.rs
+++ b/apps/desktop/src-tauri/src/media.rs
@@ -427,6 +427,7 @@ impl MediaRecorder {
"-async", "1",
"-f", "segment",
"-segment_time", "3",
+ "-segment_time_delta", "0.01",
"-segment_list", &audio_segment_list_filename,
"-reset_timestamps", "1",
&audio_output_chunk_pattern,
@@ -439,14 +440,16 @@ impl MediaRecorder {
"-r", "30",
"-thread_queue_size", "4096",
"-i", "pipe:0",
- "-vf", "fps=30,scale=in_range=full:out_range=limited,eq=saturation=1.15",
+ "-vf", "fps=30,scale=in_range=full:out_range=limited",
"-c:v", "libx264",
"-preset", "ultrafast",
"-pix_fmt", "yuv420p",
"-tune", "zerolatency",
"-vsync", "1",
+ "-force_key_frames", "expr:gte(t,n_forced*3)",
"-f", "segment",
"-segment_time", "3",
+ "-segment_time_delta", "0.01",
"-segment_list", &video_segment_list_filename,
"-segment_format", "mpegts",
"-reset_timestamps", "1",
diff --git a/apps/desktop/src-tauri/src/utils.rs b/apps/desktop/src-tauri/src/utils.rs
index 465323b3f..5a9fad2d9 100644
--- a/apps/desktop/src-tauri/src/utils.rs
+++ b/apps/desktop/src-tauri/src/utils.rs
@@ -5,6 +5,7 @@ use ffmpeg_sidecar::{
use capture::{Capturer, Display};
use std::time::{Duration, Instant};
use std::panic;
+use std::path::Path;
use std::thread;
use std::io::ErrorKind::WouldBlock;
@@ -94,7 +95,12 @@ pub fn ffmpeg_path_as_str() -> Result<String, String> {
};
let path = sidecar_dir().map_err(|e| e.to_string())?.join(binary_name);
- path.to_str()
- .map(|s| s.to_owned()) // Converts the &str to a String
- .ok_or_else(|| "Failed to convert FFmpeg binary path to string".to_string())
+
+ if Path::new(&path).exists() {
+ path.to_str()
+ .map(|s| s.to_owned())
+ .ok_or_else(|| "Failed to convert FFmpeg binary path to string".to_string())
+ } else {
+ Ok("ffmpeg".to_string())
+ }
}
\ No newline at end of file
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index 9d8e704c9..73c35e3bb 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -10,7 +10,10 @@ import {
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { getCurrentUser } from "@cap/database/auth/session";
-import { generateM3U8Playlist } from "@/utils/video/ffmpeg/helpers";
+import {
+ generateM3U8Playlist,
+ generateMasterPlaylist,
+} from "@/utils/video/ffmpeg/helpers";
const allowedOrigins = [
process.env.NEXT_PUBLIC_URL,
@@ -100,16 +103,7 @@ 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 || "",
- },
- });
-
const bucket = process.env.CAP_AWS_BUCKET || "";
- const screenPrefix = `${userId}/${videoId}/screen/`;
const videoPrefix = `${userId}/${videoId}/video/`;
const audioPrefix = `${userId}/${videoId}/audio/`;
@@ -117,15 +111,15 @@ export async function GET(request: NextRequest) {
// Handle screen, video, and now audio types
let objectsCommand, prefix;
switch (videoType) {
- case "screen":
- prefix = screenPrefix;
- break;
case "video":
prefix = videoPrefix;
break;
case "audio":
prefix = audioPrefix;
break;
+ case "master":
+ prefix = null;
+ break;
default:
return new Response(
JSON.stringify({ error: true, message: "Invalid video type" }),
@@ -142,6 +136,43 @@ export async function GET(request: NextRequest) {
);
}
+ if (prefix === null) {
+ const generatedPlaylist = await generateMasterPlaylist(
+ process.env.NEXT_PUBLIC_URL +
+ "/api/playlist?userId=" +
+ userId +
+ "&videoId=" +
+ videoId +
+ "&videoType=video",
+ process.env.NEXT_PUBLIC_URL +
+ "/api/playlist?userId=" +
+ userId +
+ "&videoId=" +
+ videoId +
+ "&videoType=audio"
+ );
+
+ return new Response(generatedPlaylist, {
+ status: 200,
+ headers: {
+ "content-type": "application/x-mpegURL",
+ "Access-Control-Allow-Origin": allowedOrigins.includes(origin)
+ ? origin
+ : "null",
+ "Access-Control-Allow-Credentials": "true",
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
+ },
+ });
+ }
+
+ 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,
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 2f6b4e452..d6a1e1d3f 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -280,8 +280,7 @@ export const ShareVideo = ({
>
<VideoPlayer
ref={videoRef}
- videoSrc={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=video`}
- audioSrc={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=audio`}
+ videoSrc={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=master`}
/>
</div>
<div className="absolute bottom-0 z-20 w-full text-white bg-black bg-opacity-50 opacity-0 group-hover:opacity-100 transition-all">
diff --git a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
index 28ffce7b3..c40bcaf1b 100644
--- a/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/VideoPlayer.tsx
@@ -9,115 +9,48 @@ import Hls from "hls.js";
interface VideoPlayerProps {
videoSrc: string;
- audioSrc?: string;
}
export const VideoPlayer = memo(
- forwardRef<HTMLVideoElement, VideoPlayerProps>(
- ({ videoSrc, audioSrc }, ref) => {
- const videoRef = useRef<HTMLVideoElement>(null);
- const audioRef = useRef<HTMLAudioElement>(null);
- const videoHlsInstance = useRef<Hls | null>(null);
- const audioHlsInstance = useRef<Hls | null>(null);
-
- useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
-
- const initializeHls = (
- src: string,
- media: HTMLMediaElement,
- hlsInstance: React.MutableRefObject<Hls | null>
- ) => {
- const hls = new Hls();
- hlsInstance.current = hls;
- hls.loadSource(src);
- hls.attachMedia(media);
+ forwardRef<HTMLVideoElement, VideoPlayerProps>(({ videoSrc }, ref) => {
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const videoHlsInstance = useRef<Hls | null>(null);
+
+ useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
+
+ const initializeHls = (
+ src: string,
+ media: HTMLMediaElement,
+ hlsInstance: React.MutableRefObject<Hls | null>
+ ) => {
+ const hls = new Hls({ progressive: true });
+ hls.on(Hls.Events.ERROR, (event, data) => {
+ console.error("HLS error:", data);
+ });
+
+ hlsInstance.current = hls;
+ hls.loadSource(src);
+ hls.attachMedia(media);
+ };
+
+ useEffect(() => {
+ if (!videoRef.current) return;
+ initializeHls(videoSrc, videoRef.current, videoHlsInstance);
+
+ return () => {
+ videoHlsInstance.current?.destroy();
};
-
- useEffect(() => {
- if (!videoRef.current) return;
- initializeHls(videoSrc, videoRef.current, videoHlsInstance);
-
- return () => {
- videoHlsInstance.current?.destroy();
- };
- }, [videoSrc]);
-
- useEffect(() => {
- if (!audioSrc || !audioRef.current) return;
- initializeHls(audioSrc, audioRef.current, audioHlsInstance);
-
- return () => {
- audioHlsInstance.current?.destroy();
- };
- }, [audioSrc]);
-
- useEffect(() => {
- if (!audioSrc || !videoRef.current || !audioRef.current) return;
- const video = videoRef.current;
- const audio = audioRef.current;
-
- const playListener = async () => {
- if (audio.paused) {
- await audio.play();
- }
- };
-
- const pauseListener = () => {
- if (!audio.paused) {
- audio.pause();
- }
- };
-
- const seekListener = () => {
- audio.currentTime = video.currentTime;
- };
-
- const volumeChangeListener = () => {
- audio.muted = video.muted;
- };
-
- const endedListener = () => {
- audio.pause();
- audio.currentTime = 0;
- };
-
- video.addEventListener("play", playListener);
- video.addEventListener("pause", pauseListener);
- video.addEventListener("seeked", seekListener);
- video.addEventListener("volumechange", volumeChangeListener);
- video.addEventListener("ended", endedListener);
-
- return () => {
- video.removeEventListener("play", playListener);
- video.removeEventListener("pause", pauseListener);
- video.removeEventListener("seeked", seekListener);
- video.removeEventListener("volumechange", volumeChangeListener);
- video.removeEventListener("ended", endedListener);
- };
- }, [audioSrc]);
-
- return (
- <>
- <video
- id="video-player"
- ref={videoRef}
- className="absolute top-0 left-0 rounded-lg w-full h-full object-contain"
- preload="metadata"
- playsInline
- controls={false}
- />
- {audioSrc && (
- <audio
- muted={false}
- ref={audioRef}
- style={{ display: "none" }}
- preload="metadata"
- controls={false}
- playsInline
- />
- )}
- </>
- );
- }
- )
+ }, [videoSrc]);
+
+ return (
+ <video
+ id="video-player"
+ ref={videoRef}
+ className="absolute top-0 left-0 rounded-lg w-full h-full object-contain"
+ preload="metadata"
+ playsInline
+ controls={false}
+ />
+ );
+ })
);
diff --git a/apps/web/utils/video/ffmpeg/helpers.ts b/apps/web/utils/video/ffmpeg/helpers.ts
index 33f53104d..88fd15ea1 100644
--- a/apps/web/utils/video/ffmpeg/helpers.ts
+++ b/apps/web/utils/video/ffmpeg/helpers.ts
@@ -77,9 +77,7 @@ export async function generateM3U8Playlist(
urls: { url: string; duration: string }[]
) {
const baseM3U8Content = `#EXTM3U
-#EXT-X-INDEPENDENT-SEGMENTS
-#EXT-X-PLAYLIST-TYPE:VOD
-#EXT-X-TARGETDURATION:7
+#EXT-X-TARGETDURATION:3
#EXT-X-VERSION:4
#EXT-X-MEDIA-SEQUENCE:0
`;
@@ -93,3 +91,18 @@ export async function generateM3U8Playlist(
return m3u8Content;
}
+
+export async function generateMasterPlaylist(
+ videoPlaylistUrl: string,
+ audioPlaylistUrl: string
+) {
+ const masterPlaylist = `#EXTM3U
+#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"
+${videoPlaylistUrl}
+`;
+
+ return masterPlaylist;
+}