Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

wip

neo773835d8c886de8
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 8206e2767..30b467d8e 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -34,14 +34,14 @@ import {
} from "./projectConfig";
const BACKGROUND_SOURCES = {
- wallpaper: "Wallpaper",
+ // wallpaper: "Wallpaper",
image: "Image",
color: "Color",
gradient: "Gradient",
} satisfies Record<BackgroundSource["type"], string>;
const BACKGROUND_SOURCES_LIST = [
- "wallpaper",
+ // "wallpaper",
"image",
"color",
"gradient",
@@ -67,10 +67,10 @@ export function ConfigSidebar() {
const backgrounds: {
[K in BackgroundSource["type"]]: Extract<BackgroundSource, { type: K }>;
} = {
- wallpaper: {
- type: "wallpaper",
- id: 0,
- },
+ // wallpaper: {
+ // type: "wallpaper",
+ // id: 0,
+ // },
image: {
type: "image",
path: null,
@@ -138,12 +138,6 @@ export function ConfigSidebar() {
const tab = v as BackgroundSource["type"];
switch (tab) {
- case "wallpaper": {
- setProject("background", "source", {
- ...backgrounds.wallpaper,
- });
- return;
- }
case "image": {
setProject("background", "source", {
...backgrounds.image,
@@ -211,7 +205,7 @@ export function ConfigSidebar() {
</KTabs.Indicator>
</KTabs.List>
<KTabs.Content value="wallpaper">
- <KRadioGroup
+ {/* <KRadioGroup
value={
project.background.source.type === "wallpaper"
? project.background.source.id.toString()
@@ -237,7 +231,7 @@ export function ConfigSidebar() {
</KRadioGroup.Item>
)}
</For>
- </KRadioGroup>
+ </KRadioGroup> */}
</KTabs.Content>
<KTabs.Content value="image">
<Show
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 0b166cfbc..7317068b4 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -227,7 +227,7 @@ export type AudioMeta = { path: string }
export type AuthStore = { token: string; user_id: string | null; expires: number; plan: Plan | null }
export type AuthenticationInvalid = null
export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null }
-export type BackgroundSource = { type: "wallpaper"; id: number } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }
+export type BackgroundSource = { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }
export type Bounds = { x: number; y: number; width: number; height: number }
export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoom_size: number | null; rounding: number; shadow: number }
export type CameraMeta = { path: string; fps?: number }
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 9891f78c9..acd404278 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -22,9 +22,9 @@ pub type Color = [u16; 3];
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum BackgroundSource {
- Wallpaper {
- id: u16,
- },
+ // Wallpaper {
+ // id: u16,
+ // },
Image {
path: Option<String>,
},
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 8d7aab468..8ea8f9add 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -48,7 +48,7 @@ pub struct WebcamStyle {
pub shadow_offset: (f32, f32),
}
-#[derive(Debug, Clone, Serialize, Deserialize, Type, Copy)]
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub enum Background {
Color([f32; 4]),
Gradient {
@@ -56,9 +56,9 @@ pub enum Background {
end: [f32; 4],
angle: f32,
},
- // Image {
- // path: String,
- // },
+ Image {
+ path: String,
+ },
}
impl From<BackgroundSource> for Background {
@@ -85,8 +85,9 @@ impl From<BackgroundSource> for Background {
],
angle: angle as f32,
},
- // BackgroundSource::Image { path } => Background::Image { path: path.clone().unwrap() },
- _ => unimplemented!(),
+ BackgroundSource::Image { path } => Background::Image {
+ path: path.clone().unwrap(),
+ },
}
}
}
@@ -156,6 +157,8 @@ pub enum RenderingError {
BufferMapFailed(#[from] wgpu::BufferAsyncError),
#[error("Sending frame to channel failed")]
ChannelSendFrameFailed(#[from] mpsc::error::SendError<RenderedFrame>),
+ #[error("Failed to load image: {0}")]
+ ImageLoadError(String),
}
pub struct RenderSegment {
@@ -173,7 +176,7 @@ pub async fn render_video_to_channel(
resolution_base: XY<u32>,
is_upgraded: bool,
) -> Result<(), RenderingError> {
- let constants = RenderVideoConstants::new(options, meta).await?;
+ let mut constants = RenderVideoConstants::new(options, meta).await?;
let recordings = ProjectRecordings::new(meta);
ffmpeg::init().unwrap();
@@ -230,12 +233,11 @@ pub async fn render_video_to_channel(
resolution_base,
is_upgraded,
);
-
let frame = produce_frame(
- &constants,
+ &mut constants,
&screen_frame,
&camera_frame,
- background,
+ background.clone(),
&uniforms,
source_time as f32,
total_frames,
@@ -318,6 +320,8 @@ pub struct RenderVideoConstants {
watermark_texture: wgpu::Texture,
watermark_bind_group: wgpu::BindGroup,
watermark_dimensions: (u32, u32),
+ image_background_pipeline: ImageBackgroundPipeline,
+ background_textures: std::sync::Arc<tokio::sync::RwLock<HashMap<String, wgpu::Texture>>>,
}
impl RenderVideoConstants {
@@ -432,6 +436,9 @@ impl RenderVideoConstants {
],
});
+ let image_background_pipeline = ImageBackgroundPipeline::new(&device);
+ let background_textures = Arc::new(tokio::sync::RwLock::new(HashMap::new()));
+
Ok(Self {
_instance: instance,
_adapter: adapter,
@@ -446,6 +453,8 @@ impl RenderVideoConstants {
watermark_texture,
watermark_bind_group,
watermark_dimensions: dimensions,
+ image_background_pipeline,
+ background_textures,
})
}
@@ -987,22 +996,110 @@ pub async fn produce_frame(
let mut output_is_left = true;
- // First, clear the background
- {
- let bind_group = constants.gradient_or_color_pipeline.bind_group(
- &constants.device,
- &GradientOrColorUniforms::from(background).to_buffer(&constants.device),
- );
+ // First, handle the background
+ match background {
+ // ... existing code ...
+
+Background::Image { path } => {
+ // Use entry API to handle texture caching
+ let mut textures = constants.background_textures.write().await;
+ let texture = match textures.entry(path.clone()) {
+ std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
+ std::collections::hash_map::Entry::Vacant(e) => {
+ // Load image with error propagation
+ let img = image::open(&path)
+ .map_err(|e| RenderingError::ImageLoadError(e.to_string()))?;
+ let rgba = img.to_rgba8();
+ let dimensions = img.dimensions();
+
+ // Create texture
+ let texture = constants.device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Background Image Texture"),
+ size: wgpu::Extent3d {
+ width: dimensions.0,
+ height: dimensions.1,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
- do_render_pass(
- &mut encoder,
- get_either(texture_views, output_is_left),
- &constants.gradient_or_color_pipeline.render_pipeline,
- bind_group,
- wgpu::LoadOp::Clear(wgpu::Color::BLACK),
- );
+ // Write texture data
+ constants.queue.write_texture(
+ wgpu::ImageCopyTexture {
+ texture: &texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &rgba,
+ wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(4 * dimensions.0),
+ rows_per_image: Some(dimensions.1),
+ },
+ wgpu::Extent3d {
+ width: dimensions.0,
+ height: dimensions.1,
+ depth_or_array_layers: 1,
+ },
+ );
- output_is_left = !output_is_left;
+ e.insert(texture)
+ }
+ };
+
+ // Create uniforms and bind group
+ let image_uniforms = ImageBackgroundUniforms {
+ output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],
+ padding: uniforms.project.background.padding as f32,
+ _padding: 0.0,
+ };
+
+ let uniform_buffer = constants.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Image Background Uniforms"),
+ contents: bytemuck::cast_slice(&[image_uniforms]),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+
+ let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ let bind_group = constants.image_background_pipeline.bind_group(
+ &constants.device,
+ &uniform_buffer,
+ &texture_view,
+ );
+
+ do_render_pass(
+ &mut encoder,
+ get_either(texture_views, output_is_left),
+ &constants.image_background_pipeline.render_pipeline,
+ bind_group,
+ wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ );
+
+ output_is_left = !output_is_left;
+}
+ _ => {
+ // Existing gradient/color background handling
+ let bind_group = constants.gradient_or_color_pipeline.bind_group(
+ &constants.device,
+ &GradientOrColorUniforms::from(background).to_buffer(&constants.device),
+ );
+
+ do_render_pass(
+ &mut encoder,
+ get_either(texture_views, output_is_left),
+ &constants.gradient_or_color_pipeline.render_pipeline,
+ bind_group,
+ wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ );
+
+ output_is_left = !output_is_left;
+ }
}
// Then render the screen frame
@@ -1069,7 +1166,7 @@ pub async fn produce_frame(
if FLAGS.zoom {
// Then render the cursor
draw_cursor(
- constants,
+ &constants,
uniforms,
time,
&mut encoder,
@@ -1661,6 +1758,7 @@ impl From<Background> for GradientOrColorUniforms {
angle,
_padding: [0.0; 3],
},
+ Background::Image { .. } => unreachable!("Image backgrounds should be handled separately"),
}
}
}
@@ -2326,3 +2424,148 @@ struct WatermarkUniforms {
opacity: f32,
is_upgraded: f32,
}
+
+struct ImageBackgroundPipeline {
+ pub bind_group_layout: wgpu::BindGroupLayout,
+ pub render_pipeline: wgpu::RenderPipeline,
+}
+
+#[repr(C)]
+#[derive(Copy, Clone, Pod, Zeroable)]
+struct ImageBackgroundUniforms {
+ output_size: [f32; 2],
+ padding: f32,
+ _padding: f32, // For alignment
+}
+
+impl ImageBackgroundPipeline {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("ImageBackgroundBindGroupLayout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ });
+
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("ImageBackgroundShader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/image-background.wgsl").into()),
+ });
+
+ let empty_constants: HashMap<String, f64> = HashMap::new();
+
+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("ImageBackgroundPipeline"),
+ layout: Some(
+ &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("ImageBackgroundPipelineLayout"),
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ }),
+ ),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: "vs_main",
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &empty_constants,
+ zero_initialize_workgroup_memory: false,
+ vertex_pulling_transform: false,
+ },
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: "fs_main",
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ blend: Some(wgpu::BlendState::REPLACE),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &empty_constants,
+ zero_initialize_workgroup_memory: false,
+ vertex_pulling_transform: false,
+ },
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ strip_index_format: None,
+ front_face: wgpu::FrontFace::Ccw,
+ cull_mode: Some(wgpu::Face::Back),
+ unclipped_depth: false,
+ polygon_mode: wgpu::PolygonMode::Fill,
+ conservative: false,
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+
+ Self {
+ bind_group_layout,
+ render_pipeline,
+ }
+ }
+
+ pub fn bind_group(
+ &self,
+ device: &wgpu::Device,
+ uniforms: &wgpu::Buffer,
+ texture: &wgpu::TextureView,
+ ) -> wgpu::BindGroup {
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ address_mode_w: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ mipmap_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ImageBackgroundBindGroup"),
+ layout: &self.bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniforms.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(texture),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ })
+ }
+}
diff --git a/crates/rendering/src/shaders/image-background.wgsl b/crates/rendering/src/shaders/image-background.wgsl
new file mode 100644
index 000000000..c5cf059e2
--- /dev/null
+++ b/crates/rendering/src/shaders/image-background.wgsl
@@ -0,0 +1,42 @@
+struct Uniforms {
+ output_size: vec2<f32>,
+ padding: f32,
+ _padding: f32, // Matches the Rust struct alignment padding
+};
+
+@group(0) @binding(0) var<uniform> u: Uniforms;
+@group(0) @binding(1) var t_image: texture_2d<f32>;
+@group(0) @binding(2) var s_image: sampler;
+
+struct VertexOutput {
+ @builtin(position) clip_position: vec4<f32>,
+ @location(0) tex_coords: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
+ var out: VertexOutput;
+ let x = f32(i32(in_vertex_index & 1u) * 4 - 1);
+ let y = f32(i32(in_vertex_index & 2u) * 2 - 1);
+ out.tex_coords = vec2<f32>(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
+ out.clip_position = vec4<f32>(x, y, 0.0, 1.0);
+ return out;
+}
+
+@fragment
+fn fs_main(@location(0) tex_coords: vec2<f32>) -> @location(0) vec4<f32> {
+ // Calculate the padding in UV space
+ let padding_uv = u.padding / max(u.output_size.x, u.output_size.y);
+
+ // Adjust UV coordinates to account for padding
+ let adjusted_coords = tex_coords * (1.0 - 2.0 * padding_uv) + padding_uv;
+
+ // Sample the texture with the adjusted coordinates
+ let color = textureSample(t_image, s_image, adjusted_coords);
+
+ // If the adjusted coordinates are outside the [0,1] range, return transparent
+ let is_inside = all(adjusted_coords >= vec2<f32>(0.0)) &&
+ all(adjusted_coords <= vec2<f32>(1.0));
+
+ return select(vec4<f32>(0.0), color, is_inside);
+}