Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Trimming (#84)

Brendan Allan870cc7f1c43c
diff --git a/apps/desktop/src-tauri/src/editor_instance.rs b/apps/desktop/src-tauri/src/editor_instance.rs
index e1e23132b..296c6aada 100644
--- a/apps/desktop/src-tauri/src/editor_instance.rs
+++ b/apps/desktop/src-tauri/src/editor_instance.rs
@@ -1,3 +1,4 @@
+use crate::display::FPS;
use crate::playback::{self, PlaybackHandle};
use crate::project_recordings::ProjectRecordings;
use crate::{editor, AudioData};
@@ -214,8 +215,14 @@ impl EditorInstance {
continue;
};
+ let Some(time) = project.timeline.as_ref().and_then(|timeline| {
+ timeline.get_recording_time(frame_number as f64 / FPS as f64)
+ }) else {
+ continue;
+ };
+
let Some((screen_frame, camera_frame)) =
- self.decoders.get_frames(frame_number).await
+ self.decoders.get_frames((time * FPS as f64) as u32).await
else {
return;
};
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index cddae2a0b..b3167dab4 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -16,10 +16,12 @@ use auth::AuthStore;
use camera::{create_camera_window, list_cameras};
use cap_ffmpeg::FFmpeg;
use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta};
-use display::{list_capture_windows, Bounds, CaptureTarget};
+use cap_utils::create_named_pipe;
+use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use editor_instance::{EditorInstance, EditorState, FRAMES_WS_PATH};
use image::{ImageBuffer, Rgba};
use mp4::Mp4Reader;
+use nix::libc::pthread_introspection_hook_t;
use num_traits::ToBytes;
use objc2_app_kit::NSScreenSaverWindowLevel;
use project_recordings::ProjectRecordings;
@@ -37,6 +39,8 @@ use tauri::{AppHandle, Manager, State, WebviewUrl, WebviewWindow, WindowEvent};
use tauri_nspanel::{cocoa::appkit::NSMainMenuWindowLevel, ManagerExt};
use tauri_plugin_decorum::WebviewWindowExt;
use tauri_specta::Event;
+use tempfile::TempDir;
+use tokio::sync::mpsc;
use tokio::{
sync::{Mutex, RwLock},
time::sleep,
@@ -417,6 +421,11 @@ async fn copy_file_to_path(src: String, dst: String) -> Result<(), String> {
}
}
+struct AudioRender {
+ data: AudioData,
+ pipe_tx: mpsc::UnboundedSender<Vec<f64>>,
+}
+
async fn render_to_file_impl(
editor_instance: &Arc<EditorInstance>,
project: ProjectConfiguration,
@@ -436,124 +445,184 @@ async fn render_to_file_impl(
let output_path_clone = output_path.clone();
let recording_dir_clone = recording_dir.clone();
- let ffmpeg_handle = tokio::spawn(async move {
- println!("Starting FFmpeg output process...");
- let mut ffmpeg = cap_ffmpeg::FFmpeg::new();
+ let ffmpeg_handle = tokio::spawn({
+ let project = project.clone();
+ async move {
+ println!("Starting FFmpeg output process...");
+ let mut ffmpeg = cap_ffmpeg::FFmpeg::new();
- let audio_path = if let Some(audio) = &audio {
let dir = tempfile::tempdir().unwrap();
- let file_path = dir.path().join("audio.raw");
- let mut file = std::fs::File::create(&file_path).unwrap();
-
- file.write_all(
- audio
- .buffer
- .iter()
- .flat_map(|f| f.to_le_bytes())
- .collect::<Vec<_>>()
- .as_slice(),
- )
- .unwrap();
+ let audio = if let Some(audio) = audio {
+ let pipe_path = dir.path().join("audio.pipe");
+ create_named_pipe(&pipe_path).unwrap();
+
+ ffmpeg.add_input(cap_ffmpeg::FFmpegRawAudioInput {
+ input: pipe_path.clone().into_os_string(),
+ sample_format: "f64le".to_string(),
+ sample_rate: audio.sample_rate,
+ channels: 1,
+ wallclock: false,
+ });
+
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Vec<f64>>();
+
+ tokio::spawn(async move {
+ let mut file = std::fs::File::create(&pipe_path).unwrap();
+ println!("audio pipe opened");
+
+ while let Some(bytes) = rx.recv().await {
+ println!("writing {} audio bytes", bytes.len() * 8);
+ file.write_all(
+ bytes
+ .iter()
+ .flat_map(|f| f.to_le_bytes())
+ .collect::<Vec<_>>()
+ .as_slice(),
+ )
+ .unwrap();
+ println!("done writing to audio pipe");
+ }
+ });
+
+ Some(AudioRender {
+ data: audio,
+ pipe_tx: tx,
+ })
+ } else {
+ None
+ };
+
+ let video_pipe_path = dir.path().join("video.pipe");
+ create_named_pipe(&video_pipe_path).unwrap();
- ffmpeg.add_input(cap_ffmpeg::FFmpegRawAudioInput {
- input: file_path.clone().into_os_string(),
- sample_format: "f64le".to_string(),
- sample_rate: 44100,
- channels: 1,
- wallclock: false,
+ ffmpeg.add_input(cap_ffmpeg::FFmpegRawVideoInput {
+ width: options.output_size.0,
+ height: options.output_size.1,
+ fps: 30,
+ pix_fmt: "rgba",
+ input: video_pipe_path.clone().into_os_string(),
});
- Some((file_path, file, dir))
- } else {
- None
- };
+ let (video_tx, mut video_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
- ffmpeg.add_input(cap_ffmpeg::FFmpegRawVideoInput {
- width: options.output_size.0,
- height: options.output_size.1,
- fps: 30,
- pix_fmt: "rgba",
- input: "pipe:0".into(),
- });
+ tokio::spawn(async move {
+ let mut file = std::fs::File::create(&video_pipe_path).unwrap();
+ println!("video pipe opened");
+
+ while let Some(bytes) = video_rx.recv().await {
+ println!("writing {} video bytes", bytes.len());
+ file.write_all(&bytes).unwrap();
+ }
+ println!("done writing to video pipe");
+ });
- ffmpeg
- .command
- .args([
- "-f", "mp4", /*, "-map", &format!("{}:v", ffmpeg_input.index) */
- ])
- .args(["-codec:v", "libx264", "-preset", "ultrafast"])
- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
- .arg("-y")
- .arg(&output_path_clone);
+ ffmpeg
+ .command
+ .args([
+ "-f", "mp4", /*, "-map", &format!("{}:v", ffmpeg_input.index) */
+ ])
+ .args(["-codec:v", "libx264", "-preset", "ultrafast"])
+ .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
+ .arg("-y")
+ .arg(&output_path_clone);
+
+ let mut ffmpeg_process = ffmpeg.start();
+
+ let mut frame_count = 0;
+ let mut first_frame = None;
+
+ loop {
+ match rx_image_data.recv().await {
+ Some(frame) => {
+ // println!("Sending image data to FFmpeg");
+ on_progress(frame_count);
+
+ if frame_count == 0 {
+ first_frame = Some(frame.clone());
+ }
- let mut ffmpeg_process = ffmpeg.start();
+ if let Some(audio) = &audio {
+ let samples_per_frame = audio.data.sample_rate as f64 / FPS as f64;
- let mut frame_count = 0;
- let mut first_frame = None;
+ if let Some(timeline) = project.timeline() {
+ if let Some(recording_time) =
+ timeline.get_recording_time(frame_count as f64 / FPS as f64)
+ {
+ let start = recording_time * audio.data.sample_rate as f64;
+ let end = start + samples_per_frame;
- loop {
- match rx_image_data.recv().await {
- Some(frame) => {
- // println!("Sending image data to FFmpeg");
- on_progress(frame_count);
+ let samples = &audio.data.buffer[start as usize..end as usize];
+ let mut samples_iter = samples.iter().copied();
- if frame_count == 0 {
- first_frame = Some(frame.clone());
- }
+ let mut frame_samples = Vec::new();
+ for _ in 0..samples_per_frame as usize {
+ frame_samples.push(samples_iter.next().unwrap_or(0.0));
+ }
+
+ println!("sending audio");
+ audio.pipe_tx.send(frame_samples).unwrap();
+ }
+ }
+ }
+
+ video_tx.send(frame).unwrap();
+ println!("sending video");
+ // if let Err(e) = ffmpeg_process.write_video_frame(&frame) {
+ // eprintln!("Error writing video frame: {:?}", e);
+ // break;
+ // }
- frame_count += 1;
- if let Err(e) = ffmpeg_process.write_video_frame(&frame) {
- eprintln!("Error writing video frame: {:?}", e);
+ frame_count += 1;
+ }
+ None => {
+ println!("All frames sent to FFmpeg");
break;
}
}
- None => {
- println!("All frames sent to FFmpeg");
- break;
- }
}
- }
- ffmpeg_process.stop();
+ ffmpeg_process.stop();
+
+ // Save the first frame as a screenshot and thumbnail
+ if let Some(frame_data) = first_frame {
+ let width = options.output_size.0;
+ let height = options.output_size.1;
+ let rgba_img: ImageBuffer<Rgba<u8>, Vec<u8>> =
+ ImageBuffer::from_raw(width, height, frame_data)
+ .expect("Failed to create image from frame data");
+
+ // Convert RGBA to RGB
+ let rgb_img: ImageBuffer<image::Rgb<u8>, Vec<u8>> =
+ ImageBuffer::from_fn(width, height, |x, y| {
+ let rgba = rgba_img.get_pixel(x, y);
+ image::Rgb([rgba[0], rgba[1], rgba[2]])
+ });
- if let Some((audio_path, _, _)) = audio_path {
- std::fs::remove_file(audio_path).ok();
- }
- // Save the first frame as a screenshot and thumbnail
- if let Some(frame_data) = first_frame {
- let width = options.output_size.0;
- let height = options.output_size.1;
- let rgba_img: ImageBuffer<Rgba<u8>, Vec<u8>> =
- ImageBuffer::from_raw(width, height, frame_data)
- .expect("Failed to create image from frame data");
-
- // Convert RGBA to RGB
- let rgb_img: ImageBuffer<image::Rgb<u8>, Vec<u8>> =
- ImageBuffer::from_fn(width, height, |x, y| {
- let rgba = rgba_img.get_pixel(x, y);
- image::Rgb([rgba[0], rgba[1], rgba[2]])
+ let screenshots_dir = recording_dir_clone.join("screenshots");
+ std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {
+ eprintln!("Failed to create screenshots directory: {:?}", e);
});
- let screenshots_dir = recording_dir_clone.join("screenshots");
- std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {
- eprintln!("Failed to create screenshots directory: {:?}", e);
- });
-
- // Save full-size screenshot
- let screenshot_path = screenshots_dir.join("display.jpg");
- rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
- eprintln!("Failed to save screenshot: {:?}", e);
- });
+ // Save full-size screenshot
+ let screenshot_path = screenshots_dir.join("display.jpg");
+ rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
+ eprintln!("Failed to save screenshot: {:?}", e);
+ });
- // Create and save thumbnail
- let thumbnail =
- image::imageops::resize(&rgb_img, 100, 100, image::imageops::FilterType::Lanczos3);
- let thumbnail_path = screenshots_dir.join("thumbnail.png");
- thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {
- eprintln!("Failed to save thumbnail: {:?}", e);
- });
- } else {
- eprintln!("No frames were processed, cannot save screenshot or thumbnail");
+ // Create and save thumbnail
+ let thumbnail = image::imageops::resize(
+ &rgb_img,
+ 100,
+ 100,
+ image::imageops::FilterType::Lanczos3,
+ );
+ let thumbnail_path = screenshots_dir.join("thumbnail.png");
+ thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {
+ eprintln!("Failed to save thumbnail: {:?}", e);
+ });
+ } else {
+ eprintln!("No frames were processed, cannot save screenshot or thumbnail");
+ }
}
});
@@ -742,7 +811,6 @@ async fn get_video_metadata(
app: AppHandle,
video_id: String,
video_type: Option<VideoType>,
- state: MutableState<'_, App>,
) -> Result<(f64, f64), String> {
let video_id = if video_id.ends_with(".cap") {
video_id.trim_end_matches(".cap").to_string()
@@ -1046,14 +1114,10 @@ async fn render_to_file(
project: ProjectConfiguration,
progress_channel: tauri::ipc::Channel<RenderProgress>,
) {
- let (duration, _size) = get_video_metadata(
- app.clone(),
- video_id.clone(),
- Some(VideoType::Screen),
- app.state(),
- )
- .await
- .unwrap();
+ let (duration, _size) =
+ get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))
+ .await
+ .unwrap();
// 30 FPS (calculated for output video)
let total_frames = (duration * 30.0).round() as u32;
diff --git a/apps/desktop/src-tauri/src/playback.rs b/apps/desktop/src-tauri/src/playback.rs
index d9bd1fcfd..cd98b8b1d 100644
--- a/apps/desktop/src-tauri/src/playback.rs
+++ b/apps/desktop/src-tauri/src/playback.rs
@@ -54,7 +54,11 @@ impl Playback {
let mut frame_number = self.start_frame_number + 1;
let uniforms = ProjectUniforms::new(&self.render_constants, &self.project);
- let duration = self.recordings.duration();
+ let duration = self
+ .project
+ .timeline()
+ .map(|t| t.duration())
+ .unwrap_or(f64::MAX);
if let Some(audio) = self.audio.clone() {
AudioPlayback {
@@ -62,6 +66,7 @@ impl Playback {
stop_rx: stop_rx.clone(),
start_frame_number: self.start_frame_number,
duration,
+ project: self.project.clone(),
}
.spawn();
};
@@ -71,11 +76,22 @@ impl Playback {
break;
};
+ let time = if let Some(timeline) = self.project.timeline() {
+ match timeline.get_recording_time(
+ start.elapsed().as_secs_f64() + self.start_frame_number as f64 / FPS as f64, /* frame_number as f64 / FPS as f64 */
+ ) {
+ Some(time) => time,
+ None => break,
+ }
+ } else {
+ frame_number as f64 / FPS as f64
+ };
+
tokio::select! {
_ = stop_rx.changed() => {
break;
},
- Some((screen_frame, camera_frame)) = self.decoders.get_frames(frame_number) => {
+ Some((screen_frame, camera_frame)) = self.decoders.get_frames((time * FPS as f64) as u32) => {
tokio::time::sleep_until(start + (frame_number - self.start_frame_number) * Duration::from_secs_f32(1.0 / FPS as f32)).await;
self
@@ -90,6 +106,7 @@ impl Playback {
event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
+
frame_number += 1;
}
else => {
@@ -124,6 +141,7 @@ struct AudioPlayback {
stop_rx: watch::Receiver<bool>,
start_frame_number: u32,
duration: f64,
+ project: ProjectConfiguration,
}
impl AudioPlayback {
@@ -141,18 +159,23 @@ impl AudioPlayback {
let mut config = supported_config.config();
config.channels = 1;
- dbg!(audio.sample_rate);
- dbg!(&config);
-
let data = audio.buffer.clone();
+ let duration = data.len() as f64 / audio.sample_rate as f64;
+ let mut time = self.start_frame_number as f64 / FPS as f64;
+
+ let time_inc = 1.0 / config.sample_rate.0 as f64;
let mut clock =
data.len() as f64 * self.start_frame_number as f64 / (FPS as f64 * self.duration);
let resample_ratio = audio.sample_rate as f64 / config.sample_rate.0 as f64;
- dbg!(resample_ratio);
let next_sample = move || {
+ time += time_inc;
+ let time = self.project.timeline()?.get_recording_time(time)?;
+
+ let index = time / duration * data.len() as f64;
+
clock += resample_ratio;
if clock >= data.len() as f64 {
@@ -160,10 +183,10 @@ impl AudioPlayback {
}
// Simple linear interpolation
- let index = clock as usize;
- let frac = clock.fract();
- let current = data[index];
- let next = data[(index + 1) % data.len()];
+ let index_int = index as usize;
+ let frac = index.fract();
+ let current = data[index_int];
+ let next = data[(index_int + 1) % data.len()];
Some(current * (1.0 - frac) + next * frac)
};
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index e2925584a..3dfc16482 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -1,9 +1,7 @@
import { Button } from "@cap/ui-solid";
-import { createElementBounds } from "@solid-primitives/bounds";
import { trackDeep } from "@solid-primitives/deep";
import { throttle } from "@solid-primitives/scheduled";
import { useSearchParams } from "@solidjs/router";
-import { cx } from "cva";
import {
For,
Match,
@@ -12,16 +10,17 @@ import {
batch,
createEffect,
createMemo,
- createResource,
createRoot,
createSignal,
on,
onMount,
} from "solid-js";
-import { platform } from "@tauri-apps/plugin-os";
-import { createStore, reconcile } from "solid-js/store";
+import { createStore } from "solid-js/store";
+import { createMutation } from "@tanstack/solid-query";
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { convertFileSrc } from "@tauri-apps/api/core";
-import { events, type RenderProgress, commands } from "../../utils/tauri";
+import { events, commands } from "../../utils/tauri";
import { EditorContextProvider, useEditorContext } from "./context";
import {
Dialog,
@@ -31,6 +30,14 @@ import {
Subfield,
Toggle,
} from "./ui";
+import {
+ EditorInstanceContextProvider,
+ useEditorInstanceContext,
+} from "./editorInstanceContext";
+import { Header } from "./Header";
+import { Player } from "./Player";
+import { ConfigSidebar } from "./ConfigSidebar";
+import { Timeline } from "./Timeline";
export function Editor() {
const [params] = useSearchParams<{ id: string }>();
@@ -65,7 +72,6 @@ function Inner() {
const {
project,
videoId,
- editorInstance,
playbackTime,
setPlaybackTime,
playing,
@@ -82,7 +88,7 @@ function Inner() {
const renderFrame = throttle((time: number) => {
events.renderFrameEvent.emit({
- frame_number: Math.floor(time * 30),
+ frame_number: Math.max(Math.floor(time * 30), 0),
project: project,
});
}, 1000 / 60);
@@ -159,288 +165,6 @@ function Inner() {
);
}
-function Header() {
- const [os] = createResource(() => platform());
-
- return (
- <header
- class={cx(
- "flex flex-row justify-between items-center",
- os() === "macos" && "pl-[4.3rem]"
- )}
- data-tauri-drag-region
- >
- <div class="flex flex-row items-center gap-[0.5rem] text-[0.875rem]">
- <div class="flex flex-row items-center gap-[0.375rem]">
- <div class="size-[1.5rem] rounded-[0.25rem] bg-gray-500 bg-black" />
- <span>My Workspace</span>
- </div>
- <span class="text-gray-400">/</span>
- <div class="flex flex-row items-center gap-[0.375rem]">
- <span>Cap Title</span>
- </div>
- </div>
- <div
- class="flex flex-row gap-4 font-medium items-center"
- data-tauri-drag-region
- >
- <ShareButton />
- <ExportButton />
- </div>
- </header>
- );
-}
-
-import { createEventListenerMap } from "@solid-primitives/event-listener";
-import { Channel, convertFileSrc } from "@tauri-apps/api/core";
-import { save } from "@tauri-apps/plugin-dialog";
-import {
- EditorInstanceContextProvider,
- useEditorInstanceContext,
-} from "./editorInstanceContext";
-import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
-import { createMutation } from "@tanstack/solid-query";
-import { ConfigSidebar } from "./ConfigSidebar";
-import { Player } from "./Player";
-import { formatTime } from "./utils";
-
-function ExportButton() {
- const { videoId, project } = useEditorContext();
-
- const [state, setState] = createStore<
- | { open: false; type: "idle" }
- | ({ open: boolean } & (
- | { type: "inProgress"; progress: number; totalFrames: number }
- | { type: "finished"; path: string }
- ))
- >({ open: false, type: "idle" });
-
- return (
- <>
- <Button
- variant="primary"
- size="md"
- onClick={() => {
- save({
- filters: [{ name: "mp4 filter", extensions: ["mp4"] }],
- }).then((p) => {
- if (!p) return;
-
- setState(
- reconcile({
- open: true,
- type: "inProgress",
- progress: 0,
- totalFrames: 0,
- })
- );
-
- const progress = new Channel<RenderProgress>();
- progress.onmessage = (p) => {
- if (p.type === "FrameRendered" && state.type === "inProgress")
- setState({ progress: p.current_frame });
- if (
- p.type === "EstimatedTotalFrames" &&
- state.type === "inProgress"
- ) {
- console.log("Total frames: ", p.total_frames);
- setState({ totalFrames: p.total_frames });
- }
- };
-
- return commands
- .renderToFile(p, videoId, project, progress)
- .then(() => {
- setState({ ...state, type: "finished", path: p });
- });
- });
- }}
- >
- Export
- </Button>
- <Dialog.Root
- open={state.open}
- onOpenChange={(o) => {
- if (!o) setState(reconcile({ ...state, open: false }));
- }}
- >
- <DialogContent
- title="Export Recording"
- confirm={
- <Show when={state.type === "finished" && state}>
- {(state) => (
- <Button
- onClick={() => {
- commands.openInFinder(state().path);
- }}
- >
- Open in Finder
- </Button>
- )}
- </Show>
- }
- >
- <Switch>
- <Match when={state.type === "finished"}>Finished exporting</Match>
- <Match when={state.type === "inProgress" && state}>
- {(state) => (
- <>
- <div class="w-full bg-gray-200 rounded-full h-2.5">
- <div
- class="bg-blue-300 h-2.5 rounded-full"
- style={{
- width: `${Math.min(
- (state().progress / (state().totalFrames || 1)) * 100,
- 100
- )}%`,
- }}
- />
- </div>
- </>
- )}
- </Match>
- </Switch>
- </DialogContent>
- </Dialog.Root>
- </>
- );
-}
-
-function ShareButton() {
- const { videoId, presets } = useEditorContext();
- const [meta, metaActions] = createResource(() =>
- commands.getRecordingMeta(videoId)
- );
-
- const uploadVideo = createMutation(() => ({
- mutationFn: async () => {
- const res = await commands.uploadRenderedVideo(
- videoId,
- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
- );
- if (res.status !== "ok") throw new Error(res.error);
- },
- onSuccess: () => metaActions.refetch(),
- }));
-
- return (
- <Show
- when={meta()?.sharing}
- fallback={
- <Button
- disabled={uploadVideo.isPending}
- onClick={() => uploadVideo.mutate()}
- class="flex items-center space-x-1"
- >
- {uploadVideo.isPending ? (
- <>
- <span>Uploading Cap</span>
- <IconLucideLoaderCircle class="size-[1rem] animate-spin" />
- </>
- ) : (
- "Create Shareable Link"
- )}
- </Button>
- }
- >
- {(sharing) => {
- const url = () => new URL(sharing().link);
-
- return (
- <a
- class="rounded-full h-[2rem] px-[1rem] flex flex-row items-center gap-[0.375rem] bg-gray-200 hover:bg-gray-300 transition-colors duration-100"
- href={sharing().link}
- target="_blank"
- rel="noreferrer"
- >
- <span class="text-[0.875rem] text-gray-500">
- {url().host}
- {url().pathname}
- </span>
- </a>
- );
- }}
- </Show>
- );
-}
-
-function Timeline() {
- const {
- project,
- videoId,
- editorInstance,
- playbackTime,
- setPlaybackTime,
- playing,
- setPlaying,
- previewTime,
- setPreviewTime,
- } = useEditorContext();
-
- const duration = () => editorInstance.recordingDuration;
-
- const [timelineRef, setTimelineRef] = createSignal<HTMLDivElement>();
- const timelineBounds = createElementBounds(timelineRef);
-
- return (
- <div class="px-[0.75rem] py-[2rem] relative">
- <Show when={previewTime()}>
- {(time) => (
- <div
- class="w-px bg-black-transparent-20 absolute left-5 top-4 bottom-0 z-10 pointer-events-none"
- style={{
- transform: `translateX(${
- (time() / duration()) * (timelineBounds.width ?? 0)
- }px)`,
- }}
- >
- <div class="size-2 bg-black-transparent-20 rounded-full -mt-2 -ml-[calc(0.25rem-0.5px)]" />
- </div>
- )}
- </Show>
- <div
- class="w-px bg-red-300 absolute left-5 top-4 bottom-0 z-10"
- style={{
- transform: `translateX(${
- (playbackTime() / duration()) * (timelineBounds.width ?? 0)
- }px)`,
- }}
- >
- <div class="size-2 bg-red-300 rounded-full -mt-2 -ml-[calc(0.25rem-0.5px)]" />
- </div>
- <div class="relative h-[3rem] border border-white ring-1 ring-blue-300 flex flex-row rounded-xl overflow-hidden">
- <div class="bg-blue-300 w-[0.5rem]" />
- <div
- ref={setTimelineRef}
- class="bg-blue-50 relative w-full h-full flex flex-row items-end justify-end px-[0.5rem] py-[0.25rem]"
- onMouseDown={(e) => {
- const { left, width } = e.currentTarget.getBoundingClientRect();
- commands.setPlayheadPosition(
- videoId,
- Math.round(30 * duration() * ((e.clientX - left) / width))
- );
- }}
- onMouseMove={(e) => {
- const { left, width } = e.currentTarget.getBoundingClientRect();
- setPreviewTime(
- Math.max(duration() * ((e.clientX - left) / width), 0)
- );
- }}
- onMouseLeave={() => {
- setPreviewTime(undefined);
- }}
- >
- <span class="text-black-transparent-60 text-[0.625rem]">0:00</span>
- <span class="text-black-transparent-60 text-[0.625rem] ml-auto">
- {formatTime(duration())}
- </span>
- </div>
- <div class="bg-blue-300 w-[0.5rem]" />
- </div>
- </div>
- );
-}
-
function Dialogs() {
const { dialog, setDialog, presets, project } = useEditorContext();
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
new file mode 100644
index 000000000..d5d3aa215
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -0,0 +1,206 @@
+import { Button } from "@cap/ui-solid";
+import { cx } from "cva";
+import { Match, Show, Switch, createResource } from "solid-js";
+import { platform } from "@tauri-apps/plugin-os";
+import { createStore, reconcile } from "solid-js/store";
+
+import { type RenderProgress, commands } from "../../utils/tauri";
+import { useEditorContext } from "./context";
+import { Dialog, DialogContent } from "./ui";
+
+export function Header() {
+ const [os] = createResource(() => platform());
+
+ return (
+ <header
+ class={cx(
+ "flex flex-row justify-between items-center",
+ os() === "macos" && "pl-[4.3rem]"
+ )}
+ data-tauri-drag-region
+ >
+ <div class="flex flex-row items-center gap-[0.5rem] text-[0.875rem]">
+ <div class="flex flex-row items-center gap-[0.375rem]">
+ <div class="size-[1.5rem] rounded-[0.25rem] bg-gray-500 bg-black" />
+ <span>My Workspace</span>
+ </div>
+ <span class="text-gray-400">/</span>
+ <div class="flex flex-row items-center gap-[0.375rem]">
+ <span>Cap Title</span>
+ </div>
+ </div>
+ <div
+ class="flex flex-row gap-4 font-medium items-center"
+ data-tauri-drag-region
+ >
+ <ShareButton />
+ <ExportButton />
+ </div>
+ </header>
+ );
+}
+
+import { Channel } from "@tauri-apps/api/core";
+import { save } from "@tauri-apps/plugin-dialog";
+import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
+import { createMutation } from "@tanstack/solid-query";
+
+function ExportButton() {
+ const { videoId, project } = useEditorContext();
+
+ const [state, setState] = createStore<
+ | { open: false; type: "idle" }
+ | ({ open: boolean } & (
+ | { type: "inProgress"; progress: number; totalFrames: number }
+ | { type: "finished"; path: string }
+ ))
+ >({ open: false, type: "idle" });
+
+ return (
+ <>
+ <Button
+ variant="primary"
+ size="md"
+ onClick={() => {
+ save({
+ filters: [{ name: "mp4 filter", extensions: ["mp4"] }],
+ }).then((p) => {
+ if (!p) return;
+
+ setState(
+ reconcile({
+ open: true,
+ type: "inProgress",
+ progress: 0,
+ totalFrames: 0,
+ })
+ );
+
+ const progress = new Channel<RenderProgress>();
+ progress.onmessage = (p) => {
+ if (p.type === "FrameRendered" && state.type === "inProgress")
+ setState({ progress: p.current_frame });
+ if (
+ p.type === "EstimatedTotalFrames" &&
+ state.type === "inProgress"
+ ) {
+ console.log("Total frames: ", p.total_frames);
+ setState({ totalFrames: p.total_frames });
+ }
+ };
+
+ return commands
+ .renderToFile(p, videoId, project, progress)
+ .then(() => {
+ setState({ ...state, type: "finished", path: p });
+ });
+ });
+ }}
+ >
+ Export
+ </Button>
+ <Dialog.Root
+ open={state.open}
+ onOpenChange={(o) => {
+ if (!o) setState(reconcile({ ...state, open: false }));
+ }}
+ >
+ <DialogContent
+ title="Export Recording"
+ confirm={
+ <Show when={state.type === "finished" && state}>
+ {(state) => (
+ <Button
+ onClick={() => {
+ commands.openInFinder(state().path);
+ }}
+ >
+ Open in Finder
+ </Button>
+ )}
+ </Show>
+ }
+ >
+ <Switch>
+ <Match when={state.type === "finished"}>Finished exporting</Match>
+ <Match when={state.type === "inProgress" && state}>
+ {(state) => (
+ <>
+ <div class="w-full bg-gray-200 rounded-full h-2.5">
+ <div
+ class="bg-blue-300 h-2.5 rounded-full"
+ style={{
+ width: `${Math.min(
+ (state().progress / (state().totalFrames || 1)) * 100,
+ 100
+ )}%`,
+ }}
+ />
+ </div>
+ </>
+ )}
+ </Match>
+ </Switch>
+ </DialogContent>
+ </Dialog.Root>
+ </>
+ );
+}
+
+function ShareButton() {
+ const { videoId, presets } = useEditorContext();
+ const [meta, metaActions] = createResource(() =>
+ commands.getRecordingMeta(videoId)
+ );
+
+ const uploadVideo = createMutation(() => ({
+ mutationFn: async () => {
+ const res = await commands.uploadRenderedVideo(
+ videoId,
+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG
+ );
+ if (res.status !== "ok") throw new Error(res.error);
+ },
+ onSuccess: () => metaActions.refetch(),
+ }));
+
+ return (
+ <Show
+ when={meta()?.sharing}
+ fallback={
+ <Button
+ disabled={uploadVideo.isPending}
+ onClick={() => uploadVideo.mutate()}
+ class="flex items-center space-x-1"
+ >
+ {uploadVideo.isPending ? (
+ <>
+ <span>Uploading Cap</span>
+ <IconLucideLoaderCircle class="size-[1rem] animate-spin" />
+ </>
+ ) : (
+ "Create Shareable Link"
+ )}
+ </Button>
+ }
+ >
+ {(sharing) => {
+ const url = () => new URL(sharing().link);
+
+ return (
+ <a
+ class="rounded-full h-[2rem] px-[1rem] flex flex-row items-center gap-[0.375rem] bg-gray-200 hover:bg-gray-300 transition-colors duration-100"
+ href={sharing().link}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <span class="text-[0.875rem] text-gray-500">
+ {url().host}
+ {url().pathname}
+ </span>
+ </a>
+ );
+ }}
+ </Show>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 5cd098a27..41e6cd5b3 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -20,6 +20,7 @@ import {
import { ASPECT_RATIOS } from "./projectConfig";
import { OUTPUT_SIZE } from "./editorInstanceContext";
import { formatTime } from "./utils";
+
export function Player() {
const {
project,
@@ -131,7 +132,14 @@ export function Player() {
<button type="button" disabled>
<IconCapFrameLast class="size-[1rem]" />
</button>
- <span>{formatTime(editorInstance.recordingDuration)}</span>
+ <span>
+ {formatTime(
+ project.timeline?.segments.reduce(
+ (acc, s) => acc + (s.end - s.start) / s.timescale,
+ 0
+ ) ?? editorInstance.recordingDuration
+ )}
+ </span>
</div>
<div class="flex-1 flex flex-row justify-end">
<ComingSoonTooltip>
diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsx
new file mode 100644
index 000000000..52aab691c
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Timeline.tsx
@@ -0,0 +1,196 @@
+import { createElementBounds } from "@solid-primitives/bounds";
+import { For, Show, createRoot, createSignal, onMount } from "solid-js";
+
+import { commands } from "../../utils/tauri";
+import { useEditorContext } from "./context";
+import { createEventListenerMap } from "@solid-primitives/event-listener";
+import { formatTime } from "./utils";
+
+export function Timeline() {
+ const {
+ project,
+ setProject,
+ videoId,
+ editorInstance,
+ playbackTime,
+ previewTime,
+ setPreviewTime,
+ history,
+ } = useEditorContext();
+
+ const duration = () => editorInstance.recordingDuration;
+
+ const [timelineRef, setTimelineRef] = createSignal<HTMLDivElement>();
+ const timelineBounds = createElementBounds(timelineRef);
+
+ onMount(() => {
+ if (!project.timeline) {
+ const resume = history.pause();
+ setProject("timeline", {
+ segments: [{ timescale: 1, start: 0, end: duration() }],
+ });
+ resume();
+ }
+ });
+
+ const xPadding = 12;
+
+ return (
+ <div
+ class="py-[2rem] relative overflow-hidden"
+ style={{
+ "padding-left": `${xPadding}px`,
+ "padding-right": `${xPadding}px`,
+ }}
+ onMouseDown={(e) => {
+ const { left, width } = timelineBounds;
+ commands.setPlayheadPosition(
+ videoId,
+ Math.round(
+ 30 * editorInstance.recordingDuration * ((e.clientX - left) / width)
+ )
+ );
+ }}
+ onMouseMove={(e) => {
+ const { left, width } = timelineBounds;
+ setPreviewTime(
+ editorInstance.recordingDuration * ((e.clientX - left) / width)
+ );
+ }}
+ onMouseLeave={() => {
+ setPreviewTime(undefined);
+ }}
+ >
+ <div ref={setTimelineRef}>
+ <Show when={previewTime()}>
+ {(time) => (
+ <div
+ class="w-px bg-black-transparent-20 absolute left-5 top-4 bottom-0 z-10 pointer-events-none"
+ style={{
+ left: `${xPadding}px`,
+ transform: `translateX(${
+ (time() / editorInstance.recordingDuration) *
+ (timelineBounds.width ?? 0)
+ }px)`,
+ }}
+ >
+ <div class="size-2 bg-black-transparent-20 rounded-full -mt-2 -ml-[calc(0.25rem-0.5px)]" />
+ </div>
+ )}
+ </Show>
+ <div
+ class="w-px bg-red-300 absolute top-4 bottom-0 z-10"
+ style={{
+ left: `${xPadding}px`,
+ transform: `translateX(${Math.min(
+ (playbackTime() / editorInstance.recordingDuration) *
+ (timelineBounds.width ?? 0),
+ timelineBounds.width ?? 0
+ )}px)`,
+ }}
+ >
+ <div class="size-2 bg-red-300 rounded-full -mt-2 -ml-[calc(0.25rem-0.5px)]" />
+ </div>
+ <For
+ each={project.timeline?.segments ?? [{ start: 0, end: duration() }]}
+ >
+ {(segment, i) => {
+ return (
+ <div
+ class="relative h-[3rem] border border-white ring-1 ring-blue-300 flex flex-row rounded-xl overflow-hidden"
+ style={{
+ width: `${
+ (100 * (segment.end - segment.start)) / duration()
+ }%`,
+ }}
+ >
+ <div
+ class="bg-blue-300 w-[0.5rem] cursor-col-resize"
+ onMouseDown={(downEvent) => {
+ const start = segment.start;
+
+ function update(event: MouseEvent) {
+ const { width } = timelineBounds;
+ setProject(
+ "timeline",
+ "segments",
+ i(),
+ "start",
+ Math.max(
+ Math.min(
+ segment.end,
+ start +
+ ((event.clientX - downEvent.clientX) / width) *
+ duration()
+ ),
+ 0
+ )
+ );
+ }
+
+ const resumeHistory = history.pause();
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: update,
+ mouseup: (e) => {
+ dispose();
+ resumeHistory();
+ update(e);
+ },
+ });
+ });
+ }}
+ />
+ <div class="bg-blue-50 relative w-full h-full flex flex-row items-end justify-end px-[0.5rem] py-[0.25rem]">
+ <span class="text-black-transparent-60 text-[0.625rem]">
+ {formatTime(segment.start)}
+ </span>
+ <span class="text-black-transparent-60 text-[0.625rem] ml-auto">
+ {formatTime(segment.end)}
+ </span>
+ </div>
+ <div
+ class="bg-blue-300 w-[0.5rem] cursor-col-resize"
+ onMouseDown={(downEvent) => {
+ const end = segment.end;
+
+ function update(event: MouseEvent) {
+ const { width } = timelineBounds;
+ setProject(
+ "timeline",
+ "segments",
+ i(),
+ "end",
+ Math.max(
+ segment.start,
+ Math.min(
+ duration(),
+ end +
+ ((event.clientX - downEvent.clientX) / width) *
+ duration()
+ )
+ )
+ );
+ }
+
+ const resumeHistory = history.pause();
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: update,
+ mouseup: (e) => {
+ dispose();
+ resumeHistory();
+ update(e);
+ },
+ });
+ });
+ }}
+ />
+ </div>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 37a0336f5..d7a5bd490 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -238,7 +238,7 @@ export type NewRecordingAdded = { path: string }
export type OSPermission = "screenRecording" | "camera" | "microphone"
export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus }
-export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration }
+export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }
export type ProjectRecordings = { display: Video; camera: Video | null; audio: Audio | null }
export type RecordingMeta = { pretty_name: string; sharing?: SharingMeta | null; display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null }
export type RecordingMetaChanged = { id: string }
@@ -252,6 +252,8 @@ export type RequestStopRecording = null
export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration | null; recordings: ProjectRecordings; path: string }
export type SharingMeta = { id: string; link: string }
export type ShowCapturesPanel = null
+export type TimelineConfiguration = { segments: TimelineSegment[] }
+export type TimelineSegment = { timescale: number; start: number; end: number }
export type Video = { duration: number; width: number; height: number; fps: number }
export type VideoType = "screen" | "output"
export type XY<T> = { x: T; y: T }
diff --git a/crates/ffmpeg/src/lib.rs b/crates/ffmpeg/src/lib.rs
index 409acba20..867ef29f5 100644
--- a/crates/ffmpeg/src/lib.rs
+++ b/crates/ffmpeg/src/lib.rs
@@ -248,7 +248,7 @@ impl Default for FFmpeg {
impl FFmpeg {
pub fn new() -> Self {
Self {
- command: Command::new(dbg!(relative_command_path("ffmpeg").unwrap())),
+ command: Command::new(relative_command_path("ffmpeg").unwrap()),
source_index: 0,
}
}
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index b7483c59f..55b904c34 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -39,8 +39,8 @@ pub struct XY<T> {
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Crop {
- pub position: XY<f32>,
- pub size: XY<f32>
+ pub position: XY<f32>,
+ pub size: XY<f32>,
}
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
@@ -117,6 +117,54 @@ pub struct HotkeysConfiguration {
show: bool,
}
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct TimelineSegment {
+ timescale: f64,
+ start: f64,
+ end: f64,
+}
+
+impl TimelineSegment {
+ fn interpolate_time(&self, tick: f64) -> Option<f64> {
+ if tick > self.duration() {
+ None
+ } else {
+ Some(self.start + tick * self.timescale)
+ }
+ }
+
+ fn duration(&self) -> f64 {
+ (self.end - self.start) / self.timescale
+ }
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct TimelineConfiguration {
+ pub segments: Vec<TimelineSegment>,
+}
+
+impl TimelineConfiguration {
+ pub fn get_recording_time(&self, tick_time: f64) -> Option<f64> {
+ let mut accum_duration = 0.0;
+
+ for segment in &self.segments {
+ if tick_time < accum_duration + segment.duration() {
+ return segment.interpolate_time(tick_time - accum_duration);
+ }
+
+ accum_duration += segment.duration();
+ }
+
+ None
+ }
+
+ pub fn duration(&self) -> f64 {
+ self.segments.iter().map(|s| s.duration()).sum()
+ }
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct ProjectConfiguration {
@@ -126,4 +174,12 @@ pub struct ProjectConfiguration {
pub audio: AudioConfiguration,
pub cursor: CursorConfiguration,
pub hotkeys: HotkeysConfiguration,
+ #[serde(default)]
+ pub timeline: Option<TimelineConfiguration>,
+}
+
+impl ProjectConfiguration {
+ pub fn timeline(&self) -> Option<&TimelineConfiguration> {
+ self.timeline.as_ref()
+ }
}
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
index 6396fb18d..4032764f3 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -197,13 +197,10 @@ impl AsyncVideoDecoder {
last_decoded_frame = Some(current_frame);
while decoder.receive_frame(&mut temp_frame).is_ok() {
- // println!(
- // "decoded frame {current_frame}. will cache: {}",
- // !too_great_for_cache_bounds && !too_small_for_cache_bounds
- // );
+ let hw_frame =
+ hw_device.as_ref().and_then(|d| d.get_hwframe(&temp_frame));
- let sw_frame = try_transfer_hwframe(&temp_frame);
- let frame = sw_frame.as_ref().unwrap_or(&temp_frame);
+ let frame = hw_frame.as_ref().unwrap_or(&temp_frame);
if frame.format() != scaler_input_format {
// Reinitialize the scaler with the new input format
@@ -221,7 +218,7 @@ impl AsyncVideoDecoder {
}
let mut rgb_frame = frame::Video::empty();
- scaler.run(frame, &mut rgb_frame).unwrap();
+ scaler.run(&frame, &mut rgb_frame).unwrap();
let width = rgb_frame.width() as usize;
let height = rgb_frame.height() as usize;
@@ -397,26 +394,28 @@ fn ff_find_decoder(
}
}
-fn try_transfer_hwframe(src: &Video) -> Option<Video> {
- unsafe {
- if src.format() == HW_PIX_FMT.get().into() {
- let mut sw_frame = frame::Video::empty();
-
- if av_hwframe_transfer_data(sw_frame.as_mut_ptr(), src.as_ptr(), 0) >= 0 {
- return Some(sw_frame);
- };
- }
- }
-
- None
-}
-
struct HwDevice {
pub device_type: AVHWDeviceType,
pub pix_fmt: Pixel,
ctx: *mut AVBufferRef,
}
+impl HwDevice {
+ pub fn get_hwframe(&self, src: &Video) -> Option<Video> {
+ unsafe {
+ if src.format() == HW_PIX_FMT.get().into() {
+ let mut sw_frame = frame::Video::empty();
+
+ if av_hwframe_transfer_data(sw_frame.as_mut_ptr(), src.as_ptr(), 0) >= 0 {
+ return Some(sw_frame);
+ };
+ }
+ }
+
+ None
+ }
+}
+
impl Drop for HwDevice {
fn drop(&mut self) {
unsafe {
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index b5cb9f58b..b47ef61b9 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -107,77 +107,34 @@ pub async fn render_video_to_channel(
ffmpeg_next::init().unwrap();
- let (screen_tx, mut screen_rx) =
- tokio::sync::mpsc::unbounded_channel::<decoder::DecodedFrame>();
-
- tokio::spawn(async move {
- let now = Instant::now();
-
- let mut i = 0;
- loop {
- match decoders.screen.get_frame(i).await {
- Some(frame) => {
- if screen_tx.send(frame).is_err() {
- println!("Error sending screen frame to renderer");
- break;
- }
- }
- None => {
- println!("Reached end of screen stream");
- break;
- }
- }
- i += 1;
- }
-
- println!("done decoding screen in {:.2?}", now.elapsed())
- });
-
- let mut camera_rx = decoders.camera.map(|decoder| {
- println!("Setting up FFmpeg input for webcam recording...");
- let (camera_tx, camera_rx) = tokio::sync::mpsc::unbounded_channel();
-
- tokio::spawn(async move {
- let now = Instant::now();
-
- let mut i = 0;
- loop {
- match decoder.get_frame(i).await {
- Some(frame) => {
- if camera_tx.send(frame).is_err() {
- println!("Error sending screen frame to renderer");
- break;
- }
- }
- None => {
- println!("Reached end of screen stream");
- break;
- }
- }
- i += 1;
- }
-
- println!("done decoding camera in {:.2?}", now.elapsed())
- });
-
- camera_rx
- });
-
let start_time = Instant::now();
+ let duration = project.timeline().map(|t| t.duration()).unwrap_or(f64::MAX);
+
let render_handle: tokio::task::JoinHandle<Result<u32, String>> = tokio::spawn(async move {
- let mut frame_count = 0;
+ let mut frame_number = 0;
let uniforms = ProjectUniforms::new(&constants, &project);
- let background = Background::from(project.background.source);
+ let background = Background::from(project.background.source.clone());
loop {
- let Some(screen_frame) = screen_rx.recv().await else {
+ if frame_number as f64 > 30 as f64 * duration {
break;
};
- let camera_frame = match &mut camera_rx {
- Some(rx) => rx.recv().await,
- None => None,
+
+ let time = if let Some(timeline) = project.timeline() {
+ match timeline.get_recording_time(frame_number as f64 / 30 as f64) {
+ Some(time) => time,
+ None => break,
+ }
+ } else {
+ frame_number as f64 / 30 as f64
+ };
+
+ let Some((screen_frame, camera_frame)) =
+ decoders.get_frames((time * 30.0) as u32).await
+ else {
+ break;
};
let frame = match produce_frame(
@@ -197,16 +154,16 @@ pub async fn render_video_to_channel(
};
if sender.send(frame).is_err() {
- eprintln!("Failed to send processed frame to FFmpeg");
+ eprintln!("Failed to send processed frame to channel");
break;
}
- frame_count += 1;
- if frame_count % 60 == 0 {
+ frame_number += 1;
+ if frame_number % 60 == 0 {
let elapsed = start_time.elapsed();
println!(
- "Processed {} frames in {:?} seconds",
- frame_count,
+ "Rendered {} frames in {:?} seconds",
+ frame_number,
elapsed.as_secs_f32()
);
}
@@ -214,7 +171,7 @@ pub async fn render_video_to_channel(
println!("Render loop exited");
- Ok(frame_count)
+ Ok(frame_number)
});
let total_frames = render_handle.await.map_err(|e| e.to_string())??;