Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(rendering): allocate camera frame textures during setup
Akshar Patel819a9ebd6cda
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex 3875bccf5..160f8f52a 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -99,6 +99,13 @@ pub fn start_renderer_layers_creation(&constants.queue,constants.is_software_adapter,);+ layers.prepare_for_video_dimensions(+ &constants.device,+ constants.options.screen_size.x,+ constants.options.screen_size.y,+ constants.options.camera_size.map(|size| size.x),+ constants.options.camera_size.map(|size| size.y),+ );layers.preload_cursor_assets(&constants, use_svg, &cursor_type);let _ = layers_tx.send(layers);})@@ -207,6 +214,13 @@ impl Renderer {&render_constants.queue,render_constants.is_software_adapter,);+ layers.prepare_for_video_dimensions(+ &render_constants.device,+ render_constants.options.screen_size.x,+ render_constants.options.screen_size.y,+ render_constants.options.camera_size.map(|size| size.x),+ render_constants.options.camera_size.map(|size| size.y),+ );let project = render_constants.recording_meta.project_config();layers.preload_cursor_assets(&render_constants,diff --git a/crates/editor/src/preparing_preview.rs b/crates/editor/src/preparing_preview.rsindex 0d57a88e6..6a66454b3 100644--- a/crates/editor/src/preparing_preview.rs+++ b/crates/editor/src/preparing_preview.rs@@ -566,6 +566,14 @@ async fn run_preview().map_err(|error| PreparingPreviewError::Render(error.to_string()))?;control.check()?;+ layers.prepare_for_video_dimensions(+ &constants.device,+ screen_size.x,+ screen_size.y,+ camera_size.map(|size| size.x),+ camera_size.map(|size| size.y),+ );+ control.check()?;layers.preload_cursor_assets(&constants,project.cursor.use_svg,diff --git a/crates/rendering/examples/camera-texture-benchmark.rs b/crates/rendering/examples/camera-texture-benchmark.rsindex 82adb2758..629d1b2cf 100644--- a/crates/rendering/examples/camera-texture-benchmark.rs+++ b/crates/rendering/examples/camera-texture-benchmark.rs@@ -15,12 +15,18 @@ struct Args {snapshots: Option<PathBuf>,#[arg(long)]screen_only: bool,+ #[arg(long, default_value_t = 1920)]+ camera_width: u32,+ #[arg(long, default_value_t = 1080)]+ camera_height: u32,}#[tokio::main]async fn main() -> Result<()> {let args = Args::parse();ensure!(args.repetitions > 0);+ ensure!(args.camera_width > 0 && args.camera_height > 0);+ let camera_size = (!args.screen_only).then_some(XY::new(args.camera_width, args.camera_height));let metadata: RecordingMeta = serde_json::from_value(serde_json::json!({"pretty_name": "camera texture benchmark","display": { "path": "unused.mp4", "fps": 60 },@@ -32,13 +38,18 @@ async fn main() -> Result<()> {let constants = RenderVideoConstants::new_with_options(RenderOptions {screen_size: size,- camera_size: (!args.screen_only).then_some(XY::new(1920, 1080)),+ camera_size,preserve_screen_alpha: false,},metadata,studio,).await?;+ let max_dimension = constants.device.limits().max_texture_dimension_2d;+ ensure!(+ args.camera_width <= max_dimension && args.camera_height <= max_dimension,+ "Camera dimensions exceed the device texture limit of {max_dimension}"+ );println!("{}",serde_json::json!({@@ -47,15 +58,20 @@ async fn main() -> Result<()> {"repetitions": args.repetitions,"warmupRepetitions": 1,"outputSize": [size.x, size.y],- "cameraSize": [1920, 1080],+ "cameraSize": camera_size.map(|size| [size.x, size.y]),"screenOnly": args.screen_only,}));let screen = DecodedFrame::new([17, 43, 89, 255].repeat(320 * 180), 320, 180);- let cameras = [- DecodedFrame::new([255, 0, 0, 255].repeat(1920 * 1080), 1920, 1080),- DecodedFrame::new([0, 0, 255, 255].repeat(1920 * 1080), 1920, 1080),- ];+ let cameras = [[255, 0, 0, 255], [0, 0, 255, 255]].map(|color| {+ camera_size.map(|size| {+ DecodedFrame::new(+ color.repeat(size.x as usize * size.y as usize),+ size.x,+ size.y,+ )+ })+ });let cursor = CursorEvents::default();for repetition in 0..=args.repetitions {for camera_only in [false, true] {@@ -70,10 +86,14 @@ async fn main() -> Result<()> {.hal.texture_memory.read();- let started = Instant::now();- let mut layers = RendererLayers::new(&constants.device, &constants.queue);+ let startup_started = Instant::now();+ let mut layers = RendererLayers::new_with_options(+ &constants.device,+ &constants.queue,+ constants.is_software_adapter,+ );constants.device.poll(wgpu::PollType::Wait)?;- let constructor_ms = started.elapsed().as_secs_f64() * 1000.0;+ let constructor_ms = startup_started.elapsed().as_secs_f64() * 1000.0;let memory_after = constants.device.get_internal_counters()@@ -84,6 +104,23 @@ async fn main() -> Result<()> {memory_after > memory_before,"Enable WGPU native counters with --features wgpu/counters");+ let setup_started = Instant::now();+ layers.prepare_for_video_dimensions(+ &constants.device,+ constants.options.screen_size.x,+ constants.options.screen_size.y,+ constants.options.camera_size.map(|size| size.x),+ constants.options.camera_size.map(|size| size.y),+ );+ constants.device.poll(wgpu::PollType::Wait)?;+ let setup_ms = setup_started.elapsed().as_secs_f64() * 1000.0;+ let startup_ms = startup_started.elapsed().as_secs_f64() * 1000.0;+ let memory_after_setup = constants+ .device+ .get_internal_counters()+ .hal+ .texture_memory+ .read();let mut project = ProjectConfiguration::default();project.background.source = BackgroundSource::Color {value: [0, 255, 0],@@ -109,7 +146,7 @@ async fn main() -> Result<()> {let frames = DecodedSegmentFrames {screen_size: size,screen_frame: Some(screen.clone()),- camera_frame: (!args.screen_only).then(|| camera.clone()),+ camera_frame: camera.clone(),segment_time: frame_number as f32 / 60.0,recording_time: frame_number as f32 / 60.0,segment_has_camera: !args.screen_only,@@ -158,7 +195,7 @@ async fn main() -> Result<()> {};ensure!(pixels.chunks_exact(4).filter(|p| *p == expected).count() > 100,- "The camera must visibly draw both distinct frames"+ "The source must visibly draw both distinct frames");if let Some(directory) = &args.snapshots&& repetition == 1@@ -193,6 +230,10 @@ async fn main() -> Result<()> {"screenOnly": args.screen_only,"constructorMs": constructor_ms,"constructorTextureBytes": memory_after - memory_before,+ "setupMs": setup_ms,+ "setupTextureBytes": memory_after_setup - memory_after,+ "startupMs": startup_ms,+ "startupTextureBytes": memory_after_setup - memory_before,"firstTwoFrameMs": frame_ms,"firstTwoFrameTextureBytes": frame_memory,})diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rsindex 5b5d83040..82abd24eb 100644--- a/crates/rendering/src/layers/camera.rs+++ b/crates/rendering/src/layers/camera.rs@@ -130,24 +130,7 @@ impl CameraLayer {if !is_same_frame {let next_texture = 1 - self.current_texture;- if self.frame_textures[next_texture].width() != frame_size.x- || self.frame_textures[next_texture].height() != frame_size.y- {- self.frame_textures[next_texture] =- CompositeVideoFramePipeline::create_frame_texture(- device,- frame_size.x,- frame_size.y,- );- self.frame_texture_views[next_texture] =- self.frame_textures[next_texture].create_view(&Default::default());-- self.bind_groups[next_texture] = Some(self.pipeline.bind_group(- device,- &self.uniforms_buffer,- &self.frame_texture_views[next_texture],- ));- }+ self.resize_frame_texture(device, next_texture, frame_size.x, frame_size.y);match format {PixelFormat::Rgba => {@@ -415,24 +398,7 @@ impl CameraLayer {if !is_same_frame {let next_texture = 1 - self.current_texture;- if self.frame_textures[next_texture].width() != frame_size.x- || self.frame_textures[next_texture].height() != frame_size.y- {- self.frame_textures[next_texture] =- CompositeVideoFramePipeline::create_frame_texture(- device,- frame_size.x,- frame_size.y,- );- self.frame_texture_views[next_texture] =- self.frame_textures[next_texture].create_view(&Default::default());-- self.bind_groups[next_texture] = Some(self.pipeline.bind_group(- device,- &self.uniforms_buffer,- &self.frame_texture_views[next_texture],- ));- }+ self.resize_frame_texture(device, next_texture, frame_size.x, frame_size.y);match format {PixelFormat::Rgba => {@@ -635,7 +601,34 @@ impl CameraLayer {}}+ fn resize_frame_texture(+ &mut self,+ device: &wgpu::Device,+ index: usize,+ width: u32,+ height: u32,+ ) -> bool {+ if self.frame_textures[index].width() == width+ && self.frame_textures[index].height() == height+ {+ return false;+ }+ self.frame_textures[index] =+ CompositeVideoFramePipeline::create_frame_texture(device, width, height);+ self.frame_texture_views[index] =+ self.frame_textures[index].create_view(&Default::default());+ self.bind_groups[index] = Some(self.pipeline.bind_group(+ device,+ &self.uniforms_buffer,+ &self.frame_texture_views[index],+ ));+ true+ }+pub fn prepare_for_video_dimensions(&mut self, device: &wgpu::Device, width: u32, height: u32) {+ if width == 0 || height == 0 {+ return;+ }if let Err(e) = self.yuv_converter.prepare_for_dimensions(device, width, height)@@ -646,6 +639,24 @@ impl CameraLayer {error = ?e,"Failed to pre-allocate camera YUV converter textures");+ return;+ }+ let max_dimension = device.limits().max_texture_dimension_2d;+ if width > max_dimension || height > max_dimension {+ tracing::warn!(+ width,+ height,+ max_dimension,+ "Camera frame dimensions exceed the texture limit"+ );+ return;+ }+ let mut resized = false;+ for index in 0..self.frame_textures.len() {+ resized |= self.resize_frame_texture(device, index, width, height);+ }+ if resized {+ self.reset_frame_state();}}}@@ -762,6 +773,127 @@ mod tests {.all(|(&value, expected)| value.abs_diff(expected) <= 2)}+ #[tokio::test]+ #[ignore = "requires a working native WGPU adapter"]+ async fn camera_setup_keeps_frame_resources_out_of_first_uploads() {+ let constants = constants().await;+ let mut layers = RendererLayers::new(&constants.device, &constants.queue);+ layers.prepare_for_video_dimensions(&constants.device, 320, 180, None, None);+ for camera in [&layers.camera, &layers.camera_only] {+ assert!(+ camera+ .frame_textures+ .iter()+ .all(|texture| { texture.width() == 1 && texture.height() == 1 })+ );+ }+ let initial_resources = (+ layers.camera.frame_textures.clone(),+ layers.camera.frame_texture_views.clone(),+ layers.camera.bind_groups.clone(),+ );+ let max_dimension = constants.device.limits().max_texture_dimension_2d;+ for (width, height) in [(0, 1080), (max_dimension + 1, 2), (2, max_dimension + 1)] {+ layers+ .camera+ .prepare_for_video_dimensions(&constants.device, width, height);+ assert_eq!(layers.camera.frame_textures, initial_resources.0);+ assert_eq!(layers.camera.frame_texture_views, initial_resources.1);+ assert_eq!(layers.camera.bind_groups, initial_resources.2);+ }++ for (width, height) in [(1920, 1080), (1280, 720), (3840, 2160), (1080, 1920)] {+ for camera_only in [false, true] {+ for ordinary_prepare in [false, true] {+ let mut layers = RendererLayers::new(&constants.device, &constants.queue);+ layers.prepare_for_video_dimensions(+ &constants.device,+ 320,+ 180,+ Some(width),+ Some(height),+ );+ let resources: Vec<_> = [&layers.camera, &layers.camera_only]+ .into_iter()+ .map(|camera| {+ assert!(camera.frame_textures.iter().all(|texture| {+ texture.width() == width && texture.height() == height+ }));+ (+ camera.frame_textures.clone(),+ camera.frame_texture_views.clone(),+ camera.bind_groups.clone(),+ )+ })+ .collect();+ layers.prepare_for_video_dimensions(+ &constants.device,+ 320,+ 180,+ Some(width),+ Some(height),+ );+ let mut project = ProjectConfiguration::default();+ project.camera.hide = false;+ if camera_only {+ project.timeline = Some(+ serde_json::from_value(serde_json::json!({+ "segments": [], "zoomSegments": [],+ "sceneSegments": [{+ "start": 2.0, "end": 5.0, "mode": "cameraOnly",+ "transitionIn": 0.0, "transitionOut": 0.0+ }]+ }))+ .unwrap(),+ );+ }+ for (number, color) in+ [[255, 0, 0, 255], [0, 0, 255, 255]].into_iter().enumerate()+ {+ let camera = DecodedFrame::new(+ color.repeat(width as usize * height as usize),+ width,+ height,+ );+ let output = pixels(+ &constants,+ &project,+ frames(Some(camera), 180 + number as u32),+ &mut layers,+ ordinary_prepare,+ )+ .await;+ assert!(+ output+ .chunks_exact(4)+ .filter(|pixel| matches_color(pixel, color))+ .count()+ > 100+ );+ for (camera, expected) in [&layers.camera, &layers.camera_only]+ .into_iter()+ .zip(&resources)+ {+ assert_eq!(&camera.frame_textures, &expected.0);+ assert_eq!(&camera.frame_texture_views, &expected.1);+ assert_eq!(&camera.bind_groups, &expected.2);+ }+ }+ }+ }+ }++ let project = ProjectConfiguration::default();+ let camera = DecodedFrame::new([255, 0, 0, 255].repeat(1920 * 1080), 1920, 1080);+ let input = frames(Some(camera), 180);+ layers.prepare_for_video_dimensions(&constants.device, 320, 180, Some(1920), Some(1080));+ let original = pixels(&constants, &project, input.clone(), &mut layers, false).await;+ layers.prepare_for_video_dimensions(&constants.device, 320, 180, Some(1280), Some(720));+ layers.prepare_for_video_dimensions(&constants.device, 320, 180, Some(1920), Some(1080));+ let repeated = pixels(&constants, &project, input, &mut layers, false).await;+ assert_eq!(original, repeated);+ }+#[tokio::test]#[ignore = "requires a working native WGPU adapter"]async fn camera_placeholders_preserve_pixels_through_frame_state_changes() {@@ -770,6 +902,15 @@ mod tests {for ordinary_prepare in [false, true] {let mut current = RendererLayers::new(&constants.device, &constants.queue);let mut legacy = legacy_layers(&constants);+ for layers in [&mut current, &mut legacy] {+ layers.prepare_for_video_dimensions(+ &constants.device,+ 320,+ 180,+ Some(1920),+ Some(1080),+ );+ }let mut project = ProjectConfiguration::default();project.background.source = cap_project::BackgroundSource::Color {value: [0, 255, 0],