Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve: GPU-side RGBA→NV12 conversion eliminates CPU conversion and reduces readback by 62%

Cursor Agentd5b0d17a8416
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index 7af023004..35da7c3c4 100644
--- a/apps/desktop/src-tauri/src/editor_window.rs
+++ b/apps/desktop/src-tauri/src/editor_window.rs
@@ -5,7 +5,7 @@ use tokio_util::sync::CancellationToken;
use crate::{
create_editor_instance_impl,
- frame_ws::{WSFrame, create_watch_frame_ws},
+ frame_ws::{WSFrame, WSFrameFormat, create_watch_frame_ws},
};
pub struct EditorInstance {
@@ -27,17 +27,30 @@ async fn do_prewarm(app: AppHandle, path: PathBuf) -> PendingResult {
let inner = create_editor_instance_impl(
&app,
path,
- Box::new(move |frame| {
- let _ = frame_tx.send(Some(std::sync::Arc::new(
- WSFrame::from_rendered_frame_nv12(
- frame.data,
- frame.width,
- frame.height,
- frame.padded_bytes_per_row,
- frame.frame_number,
- frame.target_time_ns,
- ),
- )));
+ Box::new(move |output| {
+ let ws_frame = match output {
+ cap_editor::editor::EditorFrameOutput::Nv12(frame) => WSFrame {
+ data: frame.data,
+ width: frame.width,
+ height: frame.height,
+ stride: frame.y_stride,
+ frame_number: frame.frame_number,
+ target_time_ns: frame.target_time_ns,
+ format: WSFrameFormat::Nv12,
+ created_at: Instant::now(),
+ },
+ cap_editor::editor::EditorFrameOutput::Rgba(frame) => {
+ WSFrame::from_rendered_frame_nv12(
+ frame.data,
+ frame.width,
+ frame.height,
+ frame.padded_bytes_per_row,
+ frame.frame_number,
+ frame.target_time_ns,
+ )
+ }
+ };
+ let _ = frame_tx.send(Some(std::sync::Arc::new(ws_frame)));
}),
)
.await?;
@@ -219,17 +232,30 @@ impl EditorInstances {
let inner = create_editor_instance_impl(
window.app_handle(),
path,
- Box::new(move |frame| {
- let _ = frame_tx.send(Some(std::sync::Arc::new(
- WSFrame::from_rendered_frame_nv12(
- frame.data,
- frame.width,
- frame.height,
- frame.padded_bytes_per_row,
- frame.frame_number,
- frame.target_time_ns,
- ),
- )));
+ Box::new(move |output| {
+ let ws_frame = match output {
+ cap_editor::editor::EditorFrameOutput::Nv12(frame) => WSFrame {
+ data: frame.data,
+ width: frame.width,
+ height: frame.height,
+ stride: frame.y_stride,
+ frame_number: frame.frame_number,
+ target_time_ns: frame.target_time_ns,
+ format: WSFrameFormat::Nv12,
+ created_at: Instant::now(),
+ },
+ cap_editor::editor::EditorFrameOutput::Rgba(frame) => {
+ WSFrame::from_rendered_frame_nv12(
+ frame.data,
+ frame.width,
+ frame.height,
+ frame.padded_bytes_per_row,
+ frame.frame_number,
+ frame.target_time_ns,
+ )
+ }
+ };
+ let _ = frame_tx.send(Some(std::sync::Arc::new(ws_frame)));
}),
)
.await?;
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 00dc6903b..6a24f81a8 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -3853,7 +3853,7 @@ async fn resume_uploads(app: AppHandle) -> Result<(), String> {
async fn create_editor_instance_impl(
app: &AppHandle,
path: PathBuf,
- frame_cb: Box<dyn FnMut(RenderedFrame) + Send>,
+ frame_cb: Box<dyn FnMut(cap_editor::editor::EditorFrameOutput) + Send>,
) -> Result<Arc<EditorInstance>, String> {
let app = app.clone();
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index a80d18b39..71cee1d0f 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -3,7 +3,7 @@ use std::time::Instant;
use cap_project::{CursorEvents, RecordingMeta, StudioRecordingMeta};
use cap_rendering::{
- DecodedSegmentFrames, FrameRenderer, ProjectRecordingsMeta, ProjectUniforms,
+ DecodedSegmentFrames, FrameRenderer, Nv12RenderedFrame, ProjectRecordingsMeta, ProjectUniforms,
RenderVideoConstants, RenderedFrame, RendererLayers,
};
use tokio::sync::{mpsc, oneshot};
@@ -21,9 +21,14 @@ pub enum RendererMessage {
},
}
+pub enum EditorFrameOutput {
+ Rgba(RenderedFrame),
+ Nv12(Nv12RenderedFrame),
+}
+
pub struct Renderer {
rx: mpsc::Receiver<RendererMessage>,
- frame_cb: Box<dyn FnMut(RenderedFrame) + Send>,
+ frame_cb: Box<dyn FnMut(EditorFrameOutput) + Send>,
render_constants: Arc<RenderVideoConstants>,
#[allow(unused)]
total_frames: u32,
@@ -36,7 +41,7 @@ pub struct RendererHandle {
impl Renderer {
pub fn spawn(
render_constants: Arc<RenderVideoConstants>,
- frame_cb: Box<dyn FnMut(RenderedFrame) + Send>,
+ frame_cb: Box<dyn FnMut(EditorFrameOutput) + Send>,
recording_meta: &RecordingMeta,
meta: &StudioRecordingMeta,
) -> Result<RendererHandle, String> {
@@ -143,7 +148,7 @@ impl Renderer {
}
}
match frame_renderer
- .render(
+ .render_nv12(
current.segment_frames,
current.uniforms,
&current.cursor,
@@ -152,7 +157,7 @@ impl Renderer {
.await
{
Ok(frame) => {
- (self.frame_cb)(frame);
+ (self.frame_cb)(EditorFrameOutput::Nv12(frame));
}
Err(e) => {
tracing::error!(error = %e, "Failed to render frame in editor");
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index a48f65c06..4879fadc2 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -8,7 +8,7 @@ use cap_project::{
};
use cap_rendering::{
ProjectRecordingsMeta, ProjectUniforms, RecordingSegmentDecoders, RenderVideoConstants,
- RenderedFrame, SegmentVideoPaths, Video, ZoomFocusInterpolator, get_duration,
+ SegmentVideoPaths, Video, ZoomFocusInterpolator, get_duration,
spring_mass_damper::SpringMassDamperSimulationConfig,
};
use std::{
@@ -94,7 +94,7 @@ impl EditorInstance {
pub async fn new(
project_path: PathBuf,
on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,
- frame_cb: Box<dyn FnMut(RenderedFrame) + Send>,
+ frame_cb: Box<dyn FnMut(editor::EditorFrameOutput) + Send>,
) -> Result<Arc<Self>, String> {
if !project_path.exists() {
return Err(format!("Video path {} not found!", project_path.display()));
diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rs
index 89af32ea2..a08a7afe2 100644
--- a/crates/editor/src/lib.rs
+++ b/crates/editor/src/lib.rs
@@ -1,5 +1,5 @@
mod audio;
-mod editor;
+pub mod editor;
mod editor_instance;
mod playback;
mod segments;
diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rs
index ac4492927..f4ca4ca5c 100644
--- a/crates/rendering/src/frame_pipeline.rs
+++ b/crates/rendering/src/frame_pipeline.rs
@@ -231,7 +231,10 @@ pub struct PendingNv12Readback {
}
impl PendingNv12Readback {
- pub async fn wait(mut self, device: &wgpu::Device) -> Result<Nv12RenderedFrame, RenderingError> {
+ pub async fn wait(
+ mut self,
+ device: &wgpu::Device,
+ ) -> Result<Nv12RenderedFrame, RenderingError> {
let mut poll_count = 0u32;
let start_time = Instant::now();
let timeout_duration = std::time::Duration::from_secs(GPU_BUFFER_WAIT_TIMEOUT_SECS);
@@ -748,6 +751,48 @@ pub async fn finish_encoder(
pending.wait(device).await
}
+pub async fn finish_encoder_nv12(
+ session: &mut RenderSession,
+ nv12_converter: &mut RgbaToNv12Converter,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ uniforms: &ProjectUniforms,
+ mut encoder: wgpu::CommandEncoder,
+) -> Result<Nv12RenderedFrame, RenderingError> {
+ let width = uniforms.output_size.0;
+ let height = uniforms.output_size.1;
+
+ let texture = if session.current_is_left {
+ &session.textures.0
+ } else {
+ &session.textures.1
+ };
+
+ if let Some(pending) = nv12_converter.convert_and_readback(
+ device,
+ queue,
+ &mut encoder,
+ texture,
+ width,
+ height,
+ uniforms.frame_number,
+ uniforms.frame_rate,
+ ) {
+ queue.submit(std::iter::once(encoder.finish()));
+ pending.wait(device).await
+ } else {
+ let rgba_frame = finish_encoder(session, device, queue, uniforms, encoder).await?;
+ Ok(Nv12RenderedFrame {
+ data: rgba_frame.data,
+ width: rgba_frame.width,
+ height: rgba_frame.height,
+ y_stride: rgba_frame.padded_bytes_per_row,
+ frame_number: rgba_frame.frame_number,
+ target_time_ns: rgba_frame.target_time_ns,
+ })
+ }
+}
+
pub async fn flush_pending_readback(
session: &mut RenderSession,
device: &wgpu::Device,
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 1bd37aa80..ac75b9384 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -7,7 +7,7 @@ use composite_frame::CompositeVideoFrameUniforms;
use core::f64;
use cursor_interpolation::{InterpolatedCursorPosition, interpolate_cursor};
use decoder::{AsyncVideoDecoderHandle, spawn_decoder};
-use frame_pipeline::{RenderSession, finish_encoder, flush_pending_readback};
+use frame_pipeline::{RenderSession, finish_encoder, finish_encoder_nv12, flush_pending_readback};
use futures::FutureExt;
use futures::future::OptionFuture;
use layers::{
@@ -42,7 +42,7 @@ pub mod zoom_focus_interpolation;
pub use coord::*;
pub use decoder::{DecodedFrame, DecoderStatus, DecoderType, PixelFormat};
-pub use frame_pipeline::RenderedFrame;
+pub use frame_pipeline::{Nv12RenderedFrame, RenderedFrame};
pub use project_recordings::{ProjectRecordingsMeta, SegmentRecordings, Video};
use mask::interpolate_masks;
@@ -1799,6 +1799,7 @@ pub struct DecodedSegmentFrames {
pub struct FrameRenderer<'a> {
constants: &'a RenderVideoConstants,
session: Option<RenderSession>,
+ nv12_converter: Option<frame_pipeline::RgbaToNv12Converter>,
}
impl<'a> FrameRenderer<'a> {
@@ -1808,6 +1809,7 @@ impl<'a> FrameRenderer<'a> {
Self {
constants,
session: None,
+ nv12_converter: None,
}
}
@@ -1892,6 +1894,66 @@ impl<'a> FrameRenderer<'a> {
None
}
}
+
+ pub async fn render_nv12(
+ &mut self,
+ segment_frames: DecodedSegmentFrames,
+ uniforms: ProjectUniforms,
+ cursor: &CursorEvents,
+ layers: &mut RendererLayers,
+ ) -> Result<frame_pipeline::Nv12RenderedFrame, RenderingError> {
+ let session = self.session.get_or_insert_with(|| {
+ RenderSession::new(
+ &self.constants.device,
+ uniforms.output_size.0,
+ uniforms.output_size.1,
+ )
+ });
+
+ session.update_texture_size(
+ &self.constants.device,
+ uniforms.output_size.0,
+ uniforms.output_size.1,
+ );
+
+ let nv12_converter = self.nv12_converter.get_or_insert_with(|| {
+ frame_pipeline::RgbaToNv12Converter::new(&self.constants.device)
+ });
+
+ let mut encoder = self.constants.device.create_command_encoder(
+ &(wgpu::CommandEncoderDescriptor {
+ label: Some("Render Encoder (NV12)"),
+ }),
+ );
+
+ layers
+ .prepare_with_encoder(
+ self.constants,
+ &uniforms,
+ &segment_frames,
+ cursor,
+ &mut encoder,
+ )
+ .await?;
+
+ layers.render(
+ &self.constants.device,
+ &self.constants.queue,
+ &mut encoder,
+ session,
+ &uniforms,
+ );
+
+ finish_encoder_nv12(
+ session,
+ nv12_converter,
+ &self.constants.device,
+ &self.constants.queue,
+ &uniforms,
+ encoder,
+ )
+ .await
+ }
}
pub struct RendererLayers {