Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Multi-segment video playback (#196)

Brendan Allanc05c3e215200
diff --git a/Cargo.toml b/Cargo.toml
index 51221b366..5ec6ad855 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,7 +29,11 @@ nokhwa-bindings-macos = { git = "https://github.com/CapSoftware/nokhwa", rev = "
wgpu = "22.1.0"
flume = "0.11.0"
thiserror = "1.0"
-sentry = { version = "0.34.0", features = ["anyhow"] }
+sentry = { version = "0.34.0", features = [
+ "anyhow",
+ "backtrace",
+ "debug-images",
+] }
windows = "0.58.0"
windows-sys = "0.59.0"
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 615031e13..330047dc8 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -1,5 +1,6 @@
use crate::{
- get_video_metadata, upsert_editor_instance, windows::ShowCapWindow, RenderProgress, VideoType,
+ get_video_metadata, upsert_editor_instance, windows::ShowCapWindow, RenderProgress,
+ VideoRecordingMetadata, VideoType,
};
use cap_project::ProjectConfiguration;
use std::path::PathBuf;
@@ -14,11 +15,7 @@ pub async fn export_video(
progress: tauri::ipc::Channel<RenderProgress>,
force: bool,
) -> Result<PathBuf, String> {
- sentry::configure_scope(|scope| {
- scope.set_tag("cmd", "export_video");
- });
-
- let (duration, _size) =
+ let VideoRecordingMetadata { duration, .. } =
get_video_metadata(app.clone(), video_id.clone(), Some(VideoType::Screen))
.await
.unwrap();
@@ -42,9 +39,11 @@ pub async fn export_video(
cap_export::export_video_to_file(
project,
output_path.clone(),
- move |current_frame| {
+ move |frame_index| {
progress
- .send(RenderProgress::FrameRendered { current_frame })
+ .send(RenderProgress::FrameRendered {
+ current_frame: frame_index + 1,
+ })
.ok();
},
&editor_instance.project_path,
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 8d122be09..4bc38c6c2 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -27,7 +27,7 @@ use cap_media::{
feeds::{CameraFeed, CameraFrameSender},
sources::ScreenCaptureTarget,
};
-use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta};
+use cap_project::{Content, ProjectConfiguration, RecordingMeta, SharingMeta};
use cap_recording::RecordingOptions;
use fake_window::FakeWindowBounds;
// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
@@ -131,7 +131,6 @@ impl App {
async fn set_start_recording_options(&mut self, new_options: RecordingOptions) {
let options = new_options.clone();
sentry::configure_scope(move |scope| {
- scope.set_tag("cmd", "set_start_recording_options");
let mut ctx = std::collections::BTreeMap::new();
ctx.insert(
"capture_target".into(),
@@ -569,10 +568,6 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
#[tauri::command]
#[specta::specta]
async fn copy_screenshot_to_clipboard(app: AppHandle, path: PathBuf) -> Result<(), String> {
- sentry::configure_scope(|scope| {
- scope.set_tag("cmd", "copy_screenshot_to_clipboard");
- });
-
println!("Copying screenshot to clipboard: {:?}", path);
let image_data = match tokio::fs::read(&path).await {
@@ -824,100 +819,95 @@ async fn copy_video_to_clipboard(app: AppHandle, path: String) -> Result<(), Str
Ok(())
}
+#[derive(Serialize, Deserialize, specta::Type)]
+pub struct VideoRecordingMetadata {
+ duration: f64,
+ size: f64,
+}
+
#[tauri::command]
#[specta::specta]
async fn get_video_metadata(
app: AppHandle,
video_id: String,
video_type: Option<VideoType>,
-) -> Result<(f64, f64), String> {
+) -> Result<VideoRecordingMetadata, String> {
let video_id = if video_id.ends_with(".cap") {
video_id.trim_end_matches(".cap").to_string()
} else {
video_id
};
- let video_dir = app
+ let project_path = app
.path()
.app_data_dir()
.unwrap()
.join("recordings")
.join(format!("{}.cap", video_id));
- let screen_video_path = video_dir.join("content").join("display.mp4");
- let output_video_path = video_dir.join("output").join("result.mp4");
-
- println!("video_dir: {:?} \n video_id: {:?}", video_dir, video_id);
+ let meta = RecordingMeta::load_for_project(&project_path)?;
- let video_path = match video_type {
- Some(VideoType::Screen) => {
- println!("Using screen video path: {:?}", screen_video_path);
- if !screen_video_path.exists() {
- return Err(format!(
- "Screen video does not exist: {:?}",
- screen_video_path
- ));
+ fn content_paths(project_path: &PathBuf, meta: &RecordingMeta) -> Vec<PathBuf> {
+ match &meta.content {
+ Content::SingleSegment { segment } => {
+ vec![segment.path(&meta, &segment.display.path)]
}
- screen_video_path
+ Content::MultipleSegments { inner } => inner
+ .segments
+ .iter()
+ .map(|s| inner.path(&meta, &s.display.path))
+ .collect(),
}
+ }
+
+ let paths = match video_type {
+ Some(VideoType::Screen) => content_paths(&project_path, &meta),
Some(VideoType::Output) | None => {
+ let output_video_path = project_path.join("output").join("result.mp4");
println!("Using output video path: {:?}", output_video_path);
if output_video_path.exists() {
- output_video_path
+ vec![output_video_path]
} else {
- println!(
- "Output video not found, falling back to screen video path: {:?}",
- screen_video_path
- );
- if !screen_video_path.exists() {
- return Err(format!(
- "Screen video does not exist: {:?}",
- screen_video_path
- ));
- }
- screen_video_path
+ println!("Output video not found, falling back to screen paths");
+ content_paths(&project_path, &meta)
}
}
};
- let file = File::open(&video_path).map_err(|e| {
- println!("Failed to open video file: {}", e);
- format!("Failed to open video file: {}", e)
- })?;
+ let mut ret = VideoRecordingMetadata {
+ size: 0.0,
+ duration: 0.0,
+ };
- let size = (file
- .metadata()
- .map_err(|e| {
- println!("Failed to get file metadata: {}", e);
- format!("Failed to get file metadata: {}", e)
- })?
- .len() as f64)
- / (1024.0 * 1024.0);
+ for path in paths {
+ let file = File::open(&path).map_err(|e| format!("Failed to open video file: {}", e))?;
- println!("File size: {} MB", size);
+ ret.size += (file
+ .metadata()
+ .map_err(|e| format!("Failed to get file metadata: {}", e))?
+ .len() as f64)
+ / (1024.0 * 1024.0);
- let reader = BufReader::new(file);
- let file_size = video_path
- .metadata()
- .map_err(|e| {
- println!("Failed to get file metadata: {}", e);
- format!("Failed to get file metadata: {}", e)
- })?
- .len();
+ let reader = BufReader::new(file);
+ let file_size = path
+ .metadata()
+ .map_err(|e| format!("Failed to get file metadata: {}", e))?
+ .len();
- let duration = match Mp4Reader::read_header(reader, file_size) {
- Ok(mp4) => mp4.duration().as_secs_f64(),
- Err(e) => {
- println!(
- "Failed to read MP4 header: {}. Falling back to default duration.",
- e
- );
- // Return a default duration (e.g., 0.0) or try to estimate it based on file size
- 0.0 // or some estimated value
- }
- };
+ ret.duration += match Mp4Reader::read_header(reader, file_size) {
+ Ok(mp4) => mp4.duration().as_secs_f64(),
+ Err(e) => {
+ println!(
+ "Failed to read MP4 header: {}. Falling back to default duration.",
+ e
+ );
+ // Return a default duration (e.g., 0.0) or try to estimate it based on file size
+ 0.0 // or some estimated value
+ }
+ };
+ }
- Ok((duration, size))
+ Ok(ret)
}
#[tauri::command(async)]
@@ -1860,7 +1850,17 @@ pub async fn run() {
.build(),
)
.plugin(flags::plugin::init())
- .invoke_handler(specta_builder.invoke_handler())
+ .invoke_handler({
+ let handler = specta_builder.invoke_handler();
+
+ move |invoke| {
+ sentry::configure_scope(|scope| {
+ scope.set_tag("cmd", invoke.message.command());
+ });
+
+ handler(invoke)
+ }
+ })
.setup(move |app| {
let app = app.handle().clone();
specta_builder.mount_events(&app);
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index d307108b1..2075dc3f3 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -10,7 +10,10 @@ fn main() {
sentry::ClientOptions {
release: sentry::release_name!(),
debug: cfg!(debug_assertions),
- before_send: Some(Arc::new(|event| {
+ before_send: Some(Arc::new(|mut event| {
+ // this is irrelevant to us + users probably don't want us knowing their computer names
+ event.server_name = None;
+
#[cfg(debug_assertions)]
{
let msg = event.message.clone().unwrap_or("No message".into());
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index c4a4a4538..7b810b9eb 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -6,7 +6,7 @@ use crate::{
create_screenshot,
export::export_video,
general_settings::GeneralSettingsStore,
- notifications, open_editor, open_external_link, platform,
+ list_recordings, notifications, open_editor, open_external_link, platform,
upload::get_s3_config,
upload_exported_video, web_api,
windows::{CapWindowId, ShowCapWindow},
@@ -46,10 +46,6 @@ pub fn list_cameras() -> Vec<String> {
#[tauri::command]
#[specta::specta]
pub async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
- sentry::configure_scope(|scope| {
- scope.set_tag("cmd", "start_recording");
- });
-
let mut state = state.write().await;
let id = uuid::Uuid::new_v4().to_string();
@@ -149,10 +145,6 @@ pub async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String
#[tauri::command]
#[specta::specta]
pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {
- sentry::configure_scope(|scope| {
- scope.set_tag("cmd", "stop_recording");
- });
-
let mut state = state.write().await;
let Some(current_recording) = state.clear_current_recording() else {
return Err("Recording not in progress".to_string())?;
@@ -210,50 +202,7 @@ pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Res
let recordings = ProjectRecordings::new(&completed_recording.meta);
- let config = {
- let segments = {
- let mut segments = vec![];
- let mut passed_duration = 0.0;
-
- // multi-segment
- // for segment in &completed_recording.segments {
- // let start = passed_duration;
- // passed_duration += segment.end - segment.start;
- // segments.push(TimelineSegment {
- // recording_segment: None,
- // start,
- // end: passed_duration.min(recordings.duration()),
- // timescale: 1.0,
- // });
- // }
-
- // single-segment
- for i in (0..completed_recording.segments.len()).step_by(2) {
- let start = passed_duration;
- passed_duration +=
- completed_recording.segments[i + 1] - completed_recording.segments[i];
- segments.push(TimelineSegment {
- recording_segment: None,
- start,
- end: passed_duration.min(recordings.duration()),
- timescale: 1.0,
- });
- }
-
- segments
- };
-
- ProjectConfiguration {
- timeline: Some(TimelineConfiguration {
- segments,
- zoom_segments: generate_zoom_segments_from_clicks(
- &completed_recording,
- &recordings,
- ),
- }),
- ..Default::default()
- }
- };
+ let config = project_config_from_recording(&completed_recording, &recordings);
config
.write(&completed_recording.recording_dir)
@@ -391,3 +340,26 @@ fn generate_zoom_segments_from_clicks(
segments
}
+
+fn project_config_from_recording(
+ completed_recording: &CompletedRecording,
+ recordings: &ProjectRecordings,
+) -> ProjectConfiguration {
+ ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: recordings
+ .segments
+ .iter()
+ .enumerate()
+ .map(|(i, segment)| TimelineSegment {
+ recording_segment: Some(i as u32),
+ start: 0.0,
+ end: segment.duration(),
+ timescale: 1.0,
+ })
+ .collect(),
+ zoom_segments: generate_zoom_segments_from_clicks(&completed_recording, &recordings),
+ }),
+ ..Default::default()
+ }
+}
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index a23cd41bc..89761a20c 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -145,7 +145,7 @@ function Inner() {
<div class="w-screen h-screen flex flex-col">
<Header />
<div
- class="p-5 pt-0 flex-1 w-full overflow-y-hidden flex flex-col gap-4 bg-gray-50 rounded-lg leading-5 animate-in fade-in"
+ class="p-5 pt-0 flex-1 w-full overflow-y-hidden flex flex-col gap-4 bg-gray-50 leading-5 animate-in fade-in"
data-tauri-drag-region
>
<div class="rounded-2xl overflow-hidden shadow border flex-1 flex flex-col divide-y bg-white">
diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsx
index b80fbd38a..d42553317 100644
--- a/apps/desktop/src/routes/editor/Timeline.tsx
+++ b/apps/desktop/src/routes/editor/Timeline.tsx
@@ -199,7 +199,12 @@ export function Timeline() {
onMouseDown={(downEvent) => {
const start = segment.start;
- const maxDuration =
+ const maxSegmentDuration =
+ editorInstance.recordings.segments[
+ segment.recordingSegment ?? 0
+ ].display.duration;
+
+ const availableTimelineDuration =
editorInstance.recordingDuration -
segments().reduce(
(acc, segment, segmentI) =>
@@ -210,6 +215,11 @@ export function Timeline() {
0
);
+ const maxDuration = Math.min(
+ maxSegmentDuration,
+ availableTimelineDuration
+ );
+
function update(event: MouseEvent) {
const { width } = timelineBounds;
@@ -250,7 +260,7 @@ export function Timeline() {
<span class="text-black-transparent-60 text-[0.625rem] mt-auto">
{formatTime(segment.start)}
</span>
- <Show when={segments().length > 1}>
+ {/* <Show when={segments().length > 1}>
<button
onClick={() => {
setProject(
@@ -265,7 +275,7 @@ export function Timeline() {
>
<IconCapTrash class="size-4 text-gray-400 group-hover/button:text-gray-500 transition-colors" />
</button>
- </Show>
+ </Show> */}
<span class="text-black-transparent-60 text-[0.625rem] mt-auto">
{formatTime(segment.end)}
</span>
@@ -275,7 +285,12 @@ export function Timeline() {
onMouseDown={(downEvent) => {
const end = segment.end;
- const maxDuration =
+ const maxSegmentDuration =
+ editorInstance.recordings.segments[
+ segment.recordingSegment ?? 0
+ ].display.duration;
+
+ const availableTimelineDuration =
editorInstance.recordingDuration -
segments().reduce(
(acc, segment, segmentI) =>
@@ -286,6 +301,11 @@ export function Timeline() {
0
);
+ const maxDuration = Math.min(
+ maxSegmentDuration,
+ availableTimelineDuration
+ );
+
function update(event: MouseEvent) {
const { width } = timelineBounds;
@@ -658,9 +678,10 @@ function SegmentRoot(
<div
{...props}
class={cx(
- "absolute border rounded-[calc(0.75rem+1px)] h-[3rem] w-full",
+ "border rounded-[calc(0.75rem+1px)] h-[3rem] w-full",
props.class,
- isSelected() && "wobble-wrapper"
+ isSelected() && "wobble-wrapper",
+ isFreeForm() && "absolute"
)}
style={{
"--segment-x": `${translateX()}px`,
diff --git a/apps/desktop/src/routes/editor/ui.tsx b/apps/desktop/src/routes/editor/ui.tsx
index a93d1f02c..1703a6b84 100644
--- a/apps/desktop/src/routes/editor/ui.tsx
+++ b/apps/desktop/src/routes/editor/ui.tsx
@@ -113,7 +113,7 @@ export const Dialog = {
<KDialog {...props}>
<KDialog.Portal>
{!props.hideOverlay && (
- <KDialog.Overlay class="fixed inset-0 z-50 bg-black-transparent-80 ui-expanded:animate-in ui-expanded:fade-in ui-closed:animate-out ui-closed:fade-out" />
+ <KDialog.Overlay class="fixed inset-0 z-50 bg-[#000]/80 ui-expanded:animate-in ui-expanded:fade-in ui-closed:animate-out ui-closed:fade-out" />
)}
<div class="fixed inset-0 z-50 flex items-center justify-center">
<KDialog.Content
diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsx
index e288fc2f6..f05d2db43 100644
--- a/apps/desktop/src/routes/prev-recordings.tsx
+++ b/apps/desktop/src/routes/prev-recordings.tsx
@@ -176,7 +176,7 @@ export default function () {
});
if (!result) return;
- const [duration, size] = result;
+ const { duration, size } = result;
console.log(
`Metadata for ${media.path}: duration=${duration}, size=${size}`
);
@@ -351,7 +351,9 @@ export default function () {
// For other progress types
return Math.min(
- progressState.progress || 0,
+ ("progress" in progressState &&
+ progressState.progress) ||
+ 0,
100
);
})()}%`,
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 07d44f777..147d9273e 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -68,7 +68,7 @@ async copyScreenshotToClipboard(path: string) : Promise<null> {
async openFilePath(path: string) : Promise<null> {
return await TAURI_INVOKE("open_file_path", { path });
},
-async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<[number, number]> {
+async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<VideoRecordingMetadata> {
return await TAURI_INVOKE("get_video_metadata", { videoId, videoType });
},
async createEditorInstance(videoId: string) : Promise<SerializedEditorInstance> {
@@ -279,6 +279,7 @@ export type UploadMode = { Initial: { pre_created_video: PreCreatedVideo | null
export type UploadProgress = { stage: string; progress: number; message: string }
export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"
export type Video = { duration: number; width: number; height: number }
+export type VideoRecordingMetadata = { duration: number; size: number }
export type VideoType = "screen" | "output"
export type XY<T> = { x: T; y: T }
export type ZoomSegment = { start: number; end: number; amount: number }
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 93568321c..381bb6e08 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -64,10 +64,13 @@ impl Playback {
// TODO: make this work with >1 segment
if let Some(audio_data) = self.segments[0].audio.as_ref() {
AudioPlayback {
- audio: audio_data.clone(),
+ segments: self
+ .segments
+ .iter()
+ .map(|s| s.audio.as_ref().as_ref().unwrap().clone())
+ .collect(),
stop_rx: stop_rx.clone(),
start_frame_number: self.start_frame_number,
- duration,
project: self.project.clone(),
}
.spawn();
@@ -80,48 +83,53 @@ impl Playback {
let project = self.project.borrow().clone();
- let (time, segment) = if let Some(timeline) = project.timeline() {
- match timeline.get_recording_time(frame_number as f64 / FPS as f64) {
- Some(time) => time,
- None => break,
+ let time = project
+ .timeline()
+ .map(|t| t.get_recording_time(frame_number as f64 / FPS as f64))
+ .unwrap_or(Some((frame_number as f64 / FPS as f64, None)));
+
+ if let Some((time, segment)) = time {
+ let segment = &self.segments[segment.unwrap_or(0) as usize];
+
+ tokio::select! {
+ _ = stop_rx.changed() => {
+ break;
+ },
+ value = segment.decoders.get_frames((time * FPS as f64) as u32) => {
+ if let Some((screen_frame, camera_frame)) = value {
+ let uniforms = ProjectUniforms::new(&self.render_constants, &project, time as f32);
+
+ self
+ .renderer
+ .render_frame(
+ screen_frame,
+ camera_frame,
+ project.background.source.clone(),
+ uniforms.clone(),
+ time as f32 // Add the time parameter
+ )
+ .await;
+ }
+ }
+ else => {
+ }
}
- } else {
- (frame_number as f64 / FPS as f64, None)
- };
-
- let segment = &self.segments[segment.unwrap_or(0) as usize];
-
- tokio::select! {
- _ = stop_rx.changed() => {
- break;
- },
- Some((screen_frame, camera_frame)) = segment.decoders.get_frames((time * FPS as f64) as u32) => {
- // println!("decoded frame in {:?}", debug.elapsed());
- let uniforms = ProjectUniforms::new(&self.render_constants, &project, time as f32);
-
- self
- .renderer
- .render_frame(
- screen_frame,
- camera_frame,
- project.background.source.clone(),
- uniforms.clone(),
- time as f32 // Add the time parameter
- )
- .await;
+ }
- tokio::time::sleep_until(start + (frame_number - self.start_frame_number) * Duration::from_secs_f32(1.0 / FPS as f32)).await;
+ tokio::time::sleep_until(
+ start
+ + (frame_number - self.start_frame_number)
+ * Duration::from_secs_f32(1.0 / FPS as f32),
+ )
+ .await;
- event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
+ event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
- frame_number += 1;
- }
- else => {
- break;
- }
- }
+ frame_number += 1;
}
+ println!("stopped playback");
+
stop_tx.send(true).ok();
event_tx.send(PlaybackEvent::Stop).ok();
@@ -143,10 +151,9 @@ impl PlaybackHandle {
}
struct AudioPlayback {
- audio: AudioData,
+ segments: Vec<AudioData>,
stop_rx: watch::Receiver<bool>,
start_frame_number: u32,
- duration: f64,
project: watch::Receiver<ProjectConfiguration>,
}
@@ -191,10 +198,10 @@ impl AudioPlayback {
supported_config: cpal::SupportedStreamConfig,
) -> (watch::Receiver<bool>, cpal::Stream) {
let AudioPlayback {
- audio,
stop_rx,
start_frame_number,
project,
+ segments,
..
} = self;
@@ -204,7 +211,7 @@ impl AudioPlayback {
// TODO: Get fps and duration from video (once we start supporting other frame rates)
// Also, it's a bit weird that self.duration can ever be infinity to begin with, since
// pre-recorded videos are obviously a fixed size
- let mut audio_renderer = AudioPlaybackBuffer::new(audio, output_info);
+ let mut audio_renderer = AudioPlaybackBuffer::new(segments, output_info);
let playhead = f64::from(start_frame_number) / f64::from(FPS);
audio_renderer.set_playhead(playhead, project.borrow().timeline());
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index be65e8d42..5f614758d 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -51,35 +51,29 @@ pub async fn export_video_to_file(
let (render_segments, audio_segments): (Vec<_>, Vec<_>) = segments
.iter()
.enumerate()
- .map(|(i, segment)| match &meta.content {
- cap_project::Content::SingleSegment { segment: s } => (
- RenderSegment {
- cursor: segment.cursor.clone(),
- decoders: RecordingSegmentDecoders::new(
- &meta,
- SegmentVideoPaths {
- display: s.display.path.as_path(),
- camera: s.camera.as_ref().map(|c| c.path.as_path()),
- },
- ),
+ .map(|(i, segment)| {
+ let segment_paths = match &meta.content {
+ cap_project::Content::SingleSegment { segment: s } => SegmentVideoPaths {
+ display: s.display.path.as_path(),
+ camera: s.camera.as_ref().map(|c| c.path.as_path()),
},
- segment.audio.clone(),
- ),
- cap_project::Content::MultipleSegments { inner } => {
- let s = &inner.segments[i];
+ cap_project::Content::MultipleSegments { inner } => {
+ let s = &inner.segments[i];
- segment.cursor.clone();
- RecordingSegmentDecoders::new(
- &meta,
SegmentVideoPaths {
display: s.display.path.as_path(),
camera: s.camera.as_ref().map(|c| c.path.as_path()),
- },
- );
- segment.audio.clone();
+ }
+ }
+ };
- todo!()
- }
+ (
+ RenderSegment {
+ cursor: segment.cursor.clone(),
+ decoders: RecordingSegmentDecoders::new(&meta, segment_paths),
+ },
+ segment.audio.clone(),
+ )
})
.unzip();
@@ -107,9 +101,13 @@ pub async fn export_video_to_file(
channels: audio_data.info.channels as u16,
});
- let buffer = AudioFrameBuffer::new(audio_data.clone());
Some(AudioRender {
- buffer,
+ buffer: AudioFrameBuffer::new(
+ audio_segments
+ .iter()
+ .map(|s| s.as_ref().as_ref().unwrap().clone())
+ .collect(),
+ ),
pipe_tx: tx,
})
} else {
diff --git a/crates/media/src/feeds/audio.rs b/crates/media/src/feeds/audio.rs
index 792be1fae..f0bbb12ec 100644
--- a/crates/media/src/feeds/audio.rs
+++ b/crates/media/src/feeds/audio.rs
@@ -55,26 +55,28 @@ impl AudioData {
}
pub struct AudioFrameBuffer {
- data: AudioData,
- cursor: usize,
+ data: Vec<AudioData>,
+ cursor: (usize, usize),
elapsed_samples: usize,
sample_size: usize,
}
impl AudioFrameBuffer {
- pub fn new(data: AudioData) -> Self {
- let sample_size = data.info.channels * data.info.sample_format.bytes();
+ pub fn new(data: Vec<AudioData>) -> Self {
+ let info = data[0].info;
+ let sample_size = info.channels * info.sample_format.bytes();
Self {
data,
- cursor: 0,
+ cursor: (0, 0),
elapsed_samples: 0,
sample_size,
}
}
pub fn info(&self) -> AudioInfo {
- self.data.info
+ self.data[0].info
+ // self.data.info
}
pub fn set_playhead(&mut self, playhead: f64, maybe_timeline: Option<&TimelineConfiguration>) {
@@ -82,10 +84,13 @@ impl AudioFrameBuffer {
self.cursor = match maybe_timeline {
Some(timeline) => match timeline.get_recording_time(playhead) {
- Some((time, _)) => self.playhead_to_samples(time) * self.sample_size,
- None => self.data.buffer.len(),
+ Some((time, segment)) => {
+ let index = segment.unwrap_or(0) as usize;
+ (index, self.playhead_to_samples(time) * self.sample_size)
+ }
+ None => (0, self.data[0].buffer.len()),
},
- None => self.elapsed_samples * self.sample_size,
+ None => (0, self.elapsed_samples * self.sample_size),
};
}
@@ -97,23 +102,28 @@ impl AudioFrameBuffer {
// (corresponding to a trim or split point). Currently this change is at least 0.2 seconds
// - not sure we offer that much precision in the editor even!
let new_cursor = match timeline.get_recording_time(playhead) {
- Some((time, _)) => self.playhead_to_samples(time) * self.sample_size,
- None => self.data.buffer.len(),
+ Some((time, segment)) => (
+ segment.unwrap_or(0) as usize,
+ self.playhead_to_samples(time) * self.sample_size,
+ ),
+ None => (0, self.data[0].buffer.len()),
};
- let cursor_diff = new_cursor as isize - self.cursor as isize;
- if cursor_diff.unsigned_abs() > (self.data.info.sample_rate as usize) / 5 {
+ let cursor_diff = new_cursor.1 as isize - self.cursor.1 as isize;
+ if new_cursor.0 != self.cursor.0
+ || cursor_diff.unsigned_abs() > (self.info().sample_rate as usize) / 5
+ {
self.cursor = new_cursor;
}
}
fn playhead_to_samples(&self, playhead: f64) -> usize {
- let estimated_start_sample = playhead * f64::from(self.data.info.sample_rate);
+ let estimated_start_sample = playhead * f64::from(self.info().sample_rate);
num_traits::cast(estimated_start_sample).unwrap()
}
fn elapsed_samples_to_playhead(&self) -> f64 {
- self.elapsed_samples as f64 / f64::from(self.data.info.sample_rate)
+ self.elapsed_samples as f64 / f64::from(self.info().sample_rate)
}
pub fn next_frame(
@@ -121,9 +131,9 @@ impl AudioFrameBuffer {
requested_samples: usize,
timeline: Option<&TimelineConfiguration>,
) -> Option<FFAudio> {
- let format = self.data.info.sample_format;
- let channels = self.data.info.channel_layout();
- let sample_rate = self.data.info.sample_rate;
+ let format = self.info().sample_format;
+ let channels = self.info().channel_layout();
+ let sample_rate = self.info().sample_rate;
self.next_frame_data(requested_samples, timeline)
.map(move |(samples, data)| {
@@ -144,13 +154,14 @@ impl AudioFrameBuffer {
self.adjust_cursor(timeline);
}
- if self.cursor >= self.data.buffer.len() {
+ let buffer = &self.data[self.cursor.0].buffer;
+ if self.cursor.1 >= buffer.len() {
return None;
}
let mut bytes_size = self.sample_size * samples;
- let remaining_data = self.data.buffer.len() - self.cursor;
+ let remaining_data = buffer.len() - self.cursor.1;
if remaining_data < bytes_size {
bytes_size = remaining_data;
samples = remaining_data / self.sample_size;
@@ -158,8 +169,8 @@ impl AudioFrameBuffer {
let start = self.cursor;
self.elapsed_samples += samples;
- self.cursor += bytes_size;
- Some((samples, &self.data.buffer[start..self.cursor]))
+ self.cursor.1 += bytes_size;
+ Some((samples, &buffer[start.1..self.cursor.1]))
}
}
@@ -173,11 +184,11 @@ impl<T: FromSampleBytes> AudioPlaybackBuffer<T> {
pub const PLAYBACK_SAMPLES_COUNT: u32 = 256;
const PROCESSING_SAMPLES_COUNT: u32 = 1024;
- pub fn new(data: AudioData, output_info: AudioInfo) -> Self {
- println!("Input info: {:?}", data.info);
+ pub fn new(data: Vec<AudioData>, output_info: AudioInfo) -> Self {
+ println!("Input info: {:?}", data[0].info);
println!("Output info: {:?}", output_info);
- let resampler = AudioResampler::new(data.info, output_info).unwrap();
+ let resampler = AudioResampler::new(data[0].info, output_info).unwrap();
// Up to 1 second of pre-rendered audio
let capacity = (output_info.sample_rate as usize)
@@ -199,7 +210,7 @@ impl<T: FromSampleBytes> AudioPlaybackBuffer<T> {
self.resampled_buffer.clear();
self.frame_buffer.set_playhead(playhead, maybe_timeline);
- println!("Successful seek to sample {}", self.frame_buffer.cursor);
+ println!("Successful seek to sample {:?}", self.frame_buffer.cursor);
}
pub fn buffer_reaching_limit(&self) -> bool {
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 7a2de64c7..3197b0d8b 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -304,7 +304,7 @@ impl TimelineConfiguration {
pub fn get_recording_time(&self, tick_time: f64) -> Option<(f64, Option<u32>)> {
let mut accum_duration = 0.0;
- for segment in &self.segments {
+ for segment in self.segments.iter() {
if tick_time < accum_duration + segment.duration() {
return segment
.interpolate_time(tick_time - accum_duration)
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
index adaa9d1f9..d320df149 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -123,8 +123,6 @@ impl AsyncVideoDecoder {
while let Ok(r) = peekable_requests.recv() {
match r {
VideoDecoderMessage::GetFrame(requested_frame, sender) => {
- let time_in = Instant::now();
-
let mut sender = if let Some(cached) = cache.get(&requested_frame) {
sender.send(Some(cached.clone())).ok();
last_sent_frame = Some((requested_frame, cached.clone()));
@@ -180,13 +178,14 @@ impl AsyncVideoDecoder {
last_active_frame = Some(requested_frame);
- let now = Instant::now();
loop {
if peekable_requests.peek().is_some() {
break;
}
let Some((stream, packet)) = packets.next() else {
- sender.take().map(|s| s.send(None));
+ sender
+ .take()
+ .map(|s| s.send(last_sent_frame.clone().map(|f| f.1)));
break;
};
@@ -329,7 +328,8 @@ impl AsyncVideoDecoderHandle {
self.sender
.send(VideoDecoderMessage::GetFrame(time, tx))
.unwrap();
- rx.await.ok().flatten()
+ let res = rx.await.ok().flatten();
+ res
}
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 673da2ed7..e542603a3 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -161,36 +161,39 @@ pub async fn render_video_to_channel(
break;
};
- let (time, segment) = if let Some(timeline) = project.timeline() {
+ let (time, segment_i) = if let Some(timeline) = project.timeline() {
match timeline.get_recording_time(frame_number as f64 / 30_f64) {
Some(value) => value,
- None => break,
+ None => {
+ println!("no time");
+ break;
+ }
}
} else {
(frame_number as f64 / 30_f64, None)
};
- let segment = &segments[segment.unwrap_or(0) as usize];
+ let segment = &segments[segment_i.unwrap_or(0) as usize];
let uniforms = ProjectUniforms::new(&constants, &project, time as f32);
- let Some((screen_frame, camera_frame)) =
+ if let Some((screen_frame, camera_frame)) =
segment.decoders.get_frames((time * 30.0) as u32).await
- else {
- break;
- };
-
- let frame = produce_frame(
- &constants,
- &screen_frame,
- &camera_frame,
- background,
- &uniforms,
- time as f32,
- )
- .await?;
+ {
+ let frame = produce_frame(
+ &constants,
+ &screen_frame,
+ &camera_frame,
+ background,
+ &uniforms,
+ time as f32,
+ )
+ .await?;
- sender.send(frame).await?;
+ sender.send(frame).await?;
+ } else {
+ println!("no decoder frames: {:?}", (time, segment_i));
+ };
frame_number += 1;
if frame_number % 60 == 0 {