Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Separate audio m3u8 playlist

Richie McIlroy00e01dcca5fc
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 13c614a28..47da29cce 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -55,9 +55,11 @@ pub async fn start_dual_recording(
let screen_chunks_dir = data_dir.join("chunks/screen");
let video_chunks_dir = data_dir.join("chunks/video");
+ let audio_chunks_dir = data_dir.join("chunks/audio");
clean_and_create_dir(&screen_chunks_dir)?;
clean_and_create_dir(&video_chunks_dir)?;
+ clean_and_create_dir(&audio_chunks_dir)?;
let ffmpeg_screen_args_future = construct_recording_args(&options, &screen_chunks_dir, "screen", &options.screen_index);
@@ -145,8 +147,10 @@ pub async fn start_dual_recording(
println!("Starting upload loops...");
- let screen_upload = start_upload_loop(state.clone(), screen_chunks_dir, options.clone(), "screen".to_string(), shutdown_flag.clone());
- let video_upload = start_upload_loop(state.clone(), video_chunks_dir, options.clone(), "video".to_string(), shutdown_flag.clone());
+ let audio_chunks_dir_arc = Some(Arc::new(audio_chunks_dir));
+
+ let screen_upload = start_upload_loop(state.clone(), screen_chunks_dir, None, options.clone(), "screen".to_string(), shutdown_flag.clone());
+ let video_upload = start_upload_loop(state.clone(), video_chunks_dir, audio_chunks_dir_arc, options.clone(), "video".to_string(), shutdown_flag.clone());
match tokio::try_join!(screen_upload, video_upload) {
Ok(_) => {
@@ -387,15 +391,13 @@ async fn construct_recording_args(
async fn start_upload_loop(
state: State<'_, Arc<Mutex<RecordingState>>>,
chunks_dir: PathBuf,
+ audio_chunks_dir: Option<Arc<PathBuf>>,
options: RecordingOptions,
video_type: String,
shutdown_flag: Arc<AtomicBool>,
) -> Result<(), String> {
println!("Starting upload loop for {}", video_type);
- //print the chunks_dir
- println!("chunks_dir: {:?}", chunks_dir);
-
let segment_list_path = chunks_dir.join("segment_list.txt");
let mut watched_segments: HashSet<String> = HashSet::new();
@@ -417,8 +419,27 @@ async fn start_upload_loop(
let options_clone = options.clone();
let video_type_clone = video_type.clone();
+ if let Some(audio_dir) = &audio_chunks_dir {
+ let audio_dir_path: &Path = audio_dir.as_ref();
+ let audio_segment_filename = segment_filename.replace(".ts", ".aac");
+ let audio_segment_path = audio_dir_path.join(&audio_segment_filename);
+ if audio_segment_path.exists() {
+ let audio_path_str = audio_segment_path.to_str().unwrap_or_default().to_owned();
+ let audio_options_clone = options_clone.clone();
+ let audio_video_type_clone = video_type_clone.clone();
+
+ // Schedule audio upload
+ tokio::spawn(async move {
+ println!("Uploading audio for {}: {}", audio_video_type_clone, audio_path_str);
+ match upload_file(Some(audio_options_clone), audio_path_str, "audio".to_string()).await {
+ Ok(_) => println!("Audio segment uploaded successfully."),
+ Err(e) => eprintln!("Failed to upload audio segment: {}", e),
+ }
+ });
+ }
+ }
+
let handle = tokio::spawn(async move {
- // Log the file path and the video type in one print, starting with "Uploading video from"
println!("Uploading video for {}: {}", video_type_clone, filepath_str);
match upload_file(Some(options_clone.clone()), filepath_str.clone(), video_type_clone.clone()).await {
diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rs
index e1b2b9fa5..15f5fa88c 100644
--- a/apps/desktop/src-tauri/src/upload.rs
+++ b/apps/desktop/src-tauri/src/upload.rs
@@ -67,11 +67,17 @@ pub async fn upload_file(
}
println!("Uploading file: {}", file_path);
+
+ let mime_type = if file_path.to_lowercase().ends_with(".aac") {
+ "audio/aac"
+ } else {
+ "video/mp2t"
+ };
let file_bytes = tokio::fs::read(&file_path).await.map_err(|e| format!("Failed to read file: {}", e))?;
let file_part = reqwest::multipart::Part::bytes(file_bytes)
.file_name(file_name.clone())
- .mime_str("video/mp2t")
+ .mime_str(mime_type)
.map_err(|e| format!("Error setting MIME type: {}", e))?;
form = form.part("file", file_part);
diff --git a/apps/desktop/src/components/windows/inner/Recorder.tsx b/apps/desktop/src/components/windows/inner/Recorder.tsx
index 6e81b2fae..c045c49f9 100644
--- a/apps/desktop/src/components/windows/inner/Recorder.tsx
+++ b/apps/desktop/src/components/windows/inner/Recorder.tsx
@@ -162,7 +162,7 @@ export const Recorder = () => {
try {
console.log("Stopping recordings...");
- await new Promise((resolve) => setTimeout(resolve, 3000));
+ await new Promise((resolve) => setTimeout(resolve, 3500));
await stopMediaRecording();
diff --git a/apps/desktop/src/utils/recording/useAudioRecorder.ts b/apps/desktop/src/utils/recording/useAudioRecorder.ts
index 0a9a6f3ea..4ea2c7883 100644
--- a/apps/desktop/src/utils/recording/useAudioRecorder.ts
+++ b/apps/desktop/src/utils/recording/useAudioRecorder.ts
@@ -61,13 +61,13 @@ export const useAudioRecorder = () => {
mediaRecorder.current.onstop = async () => {
try {
const audioBlob = new Blob(audioChunks.current, {
- type: "audio/mp3",
+ type: "audio/aac",
});
const buffer = await audioBlob.arrayBuffer();
const dir = await dataDir();
const filePath = await join(
dir,
- `cap_audio_${new Date().toISOString()}.mp3`
+ `cap_audio_${new Date().toISOString()}.aac`
);
await writeBinaryFile({
diff --git a/apps/desktop/src/utils/recording/useMediaRecorder.ts b/apps/desktop/src/utils/recording/useMediaRecorder.ts
index a68736bac..7e2daa586 100644
--- a/apps/desktop/src/utils/recording/useMediaRecorder.ts
+++ b/apps/desktop/src/utils/recording/useMediaRecorder.ts
@@ -35,6 +35,11 @@ export const useMediaRecorder = () => {
return join(dir, "chunks", "video");
};
+ const getAudioChunksDir = async () => {
+ const dir = await appDataDir();
+ return join(dir, "chunks", "audio");
+ };
+
const appendToSegmentListFile = async (fileName: string) => {
const dir = await getVideoChunksDir();
const segmentListPath = await join(dir, "segment_list.txt");
@@ -113,6 +118,10 @@ export const useMediaRecorder = () => {
3,
"0"
)}.ts`;
+ const audioOutputFileName = `output-${String(chunkNumber).padStart(
+ 3,
+ "0"
+ )}.aac`;
const buffer = new Uint8Array(await chunk.arrayBuffer());
const videoBuffer = await fetchFile(new Blob([buffer]));
@@ -129,27 +138,29 @@ export const useMediaRecorder = () => {
await ffmpeg.exec([
"-i",
inputFileName,
+ "-an",
"-c:v",
"libx264",
"-preset",
"veryfast",
"-tune",
"zerolatency",
- "-c:a",
- "aac",
- "-strict",
- "experimental",
- "-b:a",
- "128k",
- "-ac",
- "2",
- "-ar",
- "44100",
"-f",
"mpegts",
outputFileName,
]);
+ await ffmpeg.exec([
+ "-i",
+ inputFileName,
+ "-vn",
+ "-acodec",
+ "aac",
+ "-b:a",
+ "128k",
+ audioOutputFileName,
+ ]);
+
console.log("log-4");
try {
@@ -162,7 +173,18 @@ export const useMediaRecorder = () => {
console.error("Failed to save file:", error);
}
- console.log("log-6");
+ try {
+ const savedAudio = (await ffmpeg.readFile(
+ audioOutputFileName
+ )) as Uint8Array;
+ const audioDir = await getAudioChunksDir();
+ await createDir(audioDir, { recursive: true });
+ const audioPath = await join(audioDir, audioOutputFileName);
+ await writeBinaryFile(audioPath, savedAudio);
+ console.log("Audio saved.");
+ } catch (error) {
+ console.error("Failed to save audio:", error);
+ }
if (segmentCounter.current === 2) {
const screenshotFileName = "video-capture.jpeg";
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index 55d663a7a..f66f90e0b 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -79,93 +79,68 @@ export async function GET(request: NextRequest) {
const bucket = process.env.CAP_AWS_BUCKET || "";
const screenPrefix = `${userId}/${videoId}/screen/`;
const videoPrefix = `${userId}/${videoId}/video/`;
+ const audioPrefix = `${userId}/${videoId}/audio/`;
try {
- if (videoType === "screen") {
- const screenObjectsCommand = new ListObjectsV2Command({
- Bucket: bucket,
- Prefix: screenPrefix,
- MaxKeys: thumbnail ? 1 : undefined,
- });
- const screenObjects = await s3Client.send(screenObjectsCommand);
-
- const screenChunksUrls = await Promise.all(
- (screenObjects.Contents || []).map(async (object) => {
- const url = await getSignedUrl(
- s3Client,
- new GetObjectCommand({
- Bucket: bucket,
- Key: object.Key,
- }),
- { expiresIn: 3600 }
- );
- const metadata = await s3Client.send(
- new HeadObjectCommand({
- Bucket: bucket,
- Key: object.Key,
- })
- );
-
- return { url: url, duration: metadata?.Metadata?.duration ?? "" };
- })
- );
-
- const generatedScreenPlaylist = await generateM3U8Playlist(
- screenChunksUrls
- );
+ // 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;
+ default:
+ return new Response(
+ JSON.stringify({ error: true, message: "Invalid video type" }),
+ {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ }
- return new Response(generatedScreenPlaylist, {
- status: 200,
- headers: { "content-type": "application/x-mpegURL" },
- });
- } else if (videoType === "video") {
- const videoObjectsCommand = new ListObjectsV2Command({
- Bucket: bucket,
- Prefix: videoPrefix,
- MaxKeys: thumbnail ? 1 : undefined,
- });
- const videoObjects = await s3Client.send(videoObjectsCommand);
-
- const videoChunksUrls = await Promise.all(
- (videoObjects.Contents || []).map(async (object) => {
- const url = await getSignedUrl(
- s3Client,
- new GetObjectCommand({
- Bucket: bucket,
- Key: object.Key,
- }),
- { expiresIn: 3600 }
- );
- const metadata = await s3Client.send(
- new HeadObjectCommand({
- Bucket: bucket,
- Key: object.Key,
- })
- );
-
- return { url: url, duration: metadata?.Metadata?.duration ?? "" };
- })
- );
+ objectsCommand = new ListObjectsV2Command({
+ Bucket: bucket,
+ Prefix: prefix,
+ MaxKeys: thumbnail ? 1 : undefined,
+ });
+
+ const objects = await s3Client.send(objectsCommand);
+
+ const chunksUrls = await Promise.all(
+ (objects.Contents || []).map(async (object) => {
+ const url = await getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket: bucket,
+ Key: object.Key,
+ }),
+ { expiresIn: 3600 }
+ );
+ const metadata = await s3Client.send(
+ new HeadObjectCommand({
+ Bucket: bucket,
+ Key: object.Key,
+ })
+ );
+
+ return { url: url, duration: metadata?.Metadata?.duration ?? "" };
+ })
+ );
- const generatedVideoPlaylist = await generateM3U8Playlist(
- videoChunksUrls
- );
+ const generatedPlaylist = await generateM3U8Playlist(chunksUrls);
- return new Response(generatedVideoPlaylist, {
- status: 200,
- headers: { "content-type": "application/x-mpegURL" },
- });
- } else {
- return new Response(
- JSON.stringify({ error: true, message: "Invalid video type" }),
- {
- status: 401,
- headers: {
- "Content-Type": "application/json",
- },
- }
- );
- }
+ return new Response(generatedPlaylist, {
+ status: 200,
+ headers: { "content-type": "application/x-mpegURL" },
+ });
} catch (error) {
console.error("Error generating video segment URLs", error);
return new Response(
diff --git a/apps/web/app/api/upload/signed/route.ts b/apps/web/app/api/upload/signed/route.ts
index 08e03817b..c0f484328 100644
--- a/apps/web/app/api/upload/signed/route.ts
+++ b/apps/web/app/api/upload/signed/route.ts
@@ -33,8 +33,10 @@ export async function POST(request: NextRequest) {
);
}
+ const contentType = fileKey.endsWith(".aac") ? "audio/aac" : "video/mp2t";
+
const Fields = {
- "Content-Type": "video/mp2t",
+ "Content-Type": contentType,
"x-amz-meta-userid": userId,
"x-amz-meta-duration": duration,
};
diff --git a/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx b/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
new file mode 100644
index 000000000..6dcb9f129
--- /dev/null
+++ b/apps/web/app/share/[videoId]/_components/AudioPlayer.tsx
@@ -0,0 +1,57 @@
+import React, { useEffect, useRef } from "react";
+import Hls from "hls.js";
+
+interface AudioPlayerProps {
+ src: string;
+ isPlaying: boolean;
+ currentTime: number;
+}
+
+export const AudioPlayer: React.FC<AudioPlayerProps> = ({
+ src,
+ isPlaying,
+ currentTime,
+}) => {
+ const audioRef = useRef<HTMLAudioElement | null>(null);
+
+ useEffect(() => {
+ const audio = audioRef.current;
+ if (!audio) return;
+
+ const hls = new Hls({
+ autoStartLoad: true,
+ enableWorker: true,
+ debug: true,
+ });
+ if (Hls.isSupported()) {
+ hls.loadSource(src);
+ hls.attachMedia(audio);
+ } else if (audio.canPlayType("application/vnd.apple.mpegurl")) {
+ audio.src = src;
+ }
+
+ return () => {
+ hls.destroy();
+ };
+ }, [src]);
+
+ useEffect(() => {
+ const audio = audioRef.current;
+ if (!audio) return;
+
+ if (isPlaying) {
+ audio.play().catch((e) => console.error("Audio playback failed:", e));
+ } else {
+ audio.pause();
+ }
+ }, [isPlaying]);
+
+ useEffect(() => {
+ const audio = audioRef.current;
+ if (!audio || !audio.duration) return;
+
+ audio.currentTime = currentTime;
+ }, [currentTime]);
+
+ return <audio ref={audioRef} controls={false} style={{ display: "none" }} />;
+};
diff --git a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
index be28be32b..74947aa01 100644
--- a/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/share/[videoId]/_components/ShareVideo.tsx
@@ -3,6 +3,7 @@ import { VideoPlayer } from "./VideoPlayer";
import { useState, useEffect, useRef } from "react";
import { Play, Pause, Maximize, VolumeX, Volume2 } from "lucide-react";
import { LogoSpinner } from "@cap/ui";
+import { AudioPlayer } from "./AudioPlayer";
const formatTime = (time: number) => {
const minutes = Math.floor(time / 60);
@@ -94,7 +95,19 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
setSeeking(false);
const seekBar = event.currentTarget;
const seekTo = calculateNewTime(event, seekBar);
+
+ // Pause both videos before adjusting the time.
+ if (isPlaying) {
+ video1Ref.current?.pause();
+ video2Ref.current?.pause();
+ }
+
applyTimeToVideos(seekTo);
+
+ if (isPlaying) {
+ video1Ref.current?.play();
+ video2Ref.current?.play();
+ }
};
const handleSeekMouseMove = (event: any) => {
@@ -130,6 +143,26 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
}
}, [isPlaying]);
+ useEffect(() => {
+ const syncPlay = () => {
+ if (video1Ref.current && video2Ref.current && !isLoading) {
+ const playPromise1 = video1Ref.current.play();
+ playPromise1.catch((e) => console.log("Play failed for video 1", e));
+ const playPromise2 = video2Ref.current.play();
+ playPromise2.catch((e) => console.log("Play failed for video 2", e));
+ }
+ };
+
+ if (isPlaying) {
+ syncPlay();
+ }
+ }, [isPlaying, isLoading]);
+
+ const onAudioLoaded = (duration: number) => {
+ const videoDuration = video1Ref.current?.duration || 0;
+ setLongestDuration(Math.max(duration, videoDuration));
+ };
+
return (
<div
className="relative flex h-full w-full overflow-hidden shadow-lg rounded-lg group"
@@ -159,6 +192,11 @@ export const ShareVideo = ({ data }: { data: typeof videos.$inferSelect }) => {
</button>
</div>
)}
+ <AudioPlayer
+ src={`${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=audio`}
+ isPlaying={isPlaying}
+ currentTime={currentTime}
+ />
<div className="w-[175px] h-[175px] absolute bottom-4 right-12 overflow-hidden rounded-full z-10 shadow-lg">
<VideoPlayer
ref={video1Ref}