Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Clip source offsetting (#1003)
Brendan Allan5579dc245707
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsxindex 2d3693cd2..f744933b1 100644--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx@@ -1,3 +1,4 @@+import { NumberField } from "@kobalte/core";import {Collapsible,Collapsible as KCollapsible,@@ -31,7 +32,7 @@ import {Suspense,type ValidComponent,} from "solid-js";-import { createStore } from "solid-js/store";+import { createStore, produce } from "solid-js/store";import { Dynamic } from "solid-js/web";import toast from "solid-toast";import colorBg from "~/assets/illustrations/color.webp";@@ -43,6 +44,7 @@ import { generalSettingsStore } from "~/store";import {type BackgroundSource,type CameraShape,+ type ClipOffsets,commands,type SceneSegment,type StereoMode,@@ -2317,9 +2319,33 @@ function ClipSegmentConfig(props: {segmentIndex: number;segment: TimelineSegment;}) {- const { setProject, setEditorState, project, projectActions } =+ const { setProject, setEditorState, project, projectActions, meta } =useEditorContext();+ // Get current clip configuration+ const clipConfig = () =>+ project.clips?.find((c) => c.index === props.segmentIndex);+ const offsets = () => clipConfig()?.offsets || {};++ function setOffset(type: keyof ClipOffsets, offset: number) {+ if (Number.isNaN(offset)) return;++ setProject(+ produce((proj) => {+ const clips = (proj.clips ??= []);+ let clip = clips.find(+ (clip) => clip.index === (props.segment.recordingSegment ?? 0),+ );+ if (!clip) {+ clip = { index: 0, offsets: {} };+ clips.push(clip);+ }++ clip.offsets[type] = offset / 1000;+ }),+ );+ }+return (<><div class="flex flex-row justify-between items-center">@@ -2348,20 +2374,111 @@ function ClipSegmentConfig(props: {Delete</EditorButton></div>- <ComingSoonTooltip>- <Field name="Hide Cursor" disabled value={<Toggle disabled />} />- </ComingSoonTooltip>- <ComingSoonTooltip>- <Field- name="Disable Smooth Cursor Movement"- disabled- value={<Toggle disabled />}++ <div class="space-y-1">+ <h3 class="font-medium text-gray-12">Clip Settings</h3>+ <p class="text-gray-11">+ These settings apply to all segments for the current clip+ </p>+ </div>++ {meta().hasSystemAudio && (+ <SourceOffsetField+ name="System Audio Offset"+ value={offsets().system_audio}+ onChange={(offset) => {+ setOffset("system_audio", offset);+ }}/>- </ComingSoonTooltip>+ )}+ {meta().hasMicrophone && (+ <SourceOffsetField+ name="Microphone Offset"+ value={offsets().mic}+ onChange={(offset) => {+ setOffset("mic", offset);+ }}+ />+ )}+ {meta().hasCamera && (+ <SourceOffsetField+ name="Camera Offset"+ value={offsets().camera}+ onChange={(offset) => {+ setOffset("camera", offset);+ }}+ />+ )}++ {/*<ComingSoonTooltip>+ <Field name="Hide Cursor" disabled value={<Toggle disabled />} />+ </ComingSoonTooltip>+ <ComingSoonTooltip>+ <Field+ name="Disable Smooth Cursor Movement"+ disabled+ value={<Toggle disabled />}+ />+ </ComingSoonTooltip>*/}</>);}+function SourceOffsetField(props: {+ name: string;+ // seconds+ value?: number;+ onChange: (value: number) => void;+}) {+ const rawValue = () => Math.round((props.value ?? 0) * 1000);++ const [value, setValue] = createSignal(rawValue().toString());++ return (+ <Field name={props.name}>+ <div class="flex flex-row items-center justify-between w-full -mt-2">+ <div class="flex flex-row space-x-1 items-end">+ <NumberField.Root+ value={value()}+ onChange={setValue}+ rawValue={rawValue()}+ onRawValueChange={(v) => {+ props.onChange(v);+ }}+ >+ <NumberField.Input+ onBlur={() => {+ if (!rawValue() || value() === "" || Number.isNaN(rawValue())) {+ setValue("0");+ props.onChange(0);+ }+ }}+ class="w-[5rem] p-[0.375rem] border rounded-[0.5rem] bg-gray-1 focus-visible:outline-none"+ />+ </NumberField.Root>+ <span class="text-gray-11">ms</span>+ </div>+ <div class="text-gray-11 flex flex-row space-x-1">+ {[-100, -10, 10, 100].map((v) => (+ <button+ type="button"+ onClick={() => {+ const currentValue = rawValue() + v;+ props.onChange(currentValue);+ setValue(currentValue.toString());+ }}+ class="text-gray-11 hover:text-gray-12 text-xs px-1 py-0.5 bg-gray-1 border border-gray-3 rounded"+ >+ {Math.sign(v) > 0 ? "+" : "-"}+ {Math.abs(v)}ms+ </button>+ ))}+ </div>+ </div>+ </Field>+ );+}+function SceneSegmentConfig(props: {segmentIndex: number;segment: SceneSegment;diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsxindex 7683dbd42..4ab4faf98 100644--- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx+++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx@@ -369,21 +369,22 @@ export function ClipTrack(createEventListener(e.currentTarget, "mouseup", (e) => {dispose();- // If there's only one segment, don't open the clip config panel- // since there's nothing to configure - just let the normal click behavior happen- const hasOnlyOneSegment = segments().length === 1;-- if (hasOnlyOneSegment) {- // Clear any existing selection (zoom, layout, etc.) when clicking on a clip- // This ensures the sidebar updates properly- setEditorState("timeline", "selection", null);- } else {- // When there are multiple segments, show the clip configuration- setEditorState("timeline", "selection", {- type: "clip",- index: i(),- });- }+ // // If there's only one segment, don't open the clip config panel+ // // since there's nothing to configure - just let the normal click behavior happen+ // const hasOnlyOneSegment = segments().length === 1;++ // if (hasOnlyOneSegment) {+ // // Clear any existing selection (zoom, layout, etc.) when clicking on a clip+ // // This ensures the sidebar updates properly+ // setEditorState("timeline", "selection", null);+ // } else {+ // When there are multiple segments, show the clip configuration+ setEditorState("timeline", "selection", {+ type: "clip",+ index: i(),+ });++ // }props.handleUpdatePlayhead(e);});});diff --git a/apps/desktop/src/utils/createPresets.ts b/apps/desktop/src/utils/createPresets.tsindex 2217a7526..9ba9943d3 100644--- a/apps/desktop/src/utils/createPresets.ts+++ b/apps/desktop/src/utils/createPresets.ts@@ -28,6 +28,7 @@ export function createPresets() {const config = { ...preset.config };// @ts-expect-error we reeeally don't want the timeline in the presetconfig.timeline = undefined;+ config.clips = undefined;await updatePresets((store) => {store.presets.push({ name: preset.name, config });diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex b7719566d..a6d2405a0 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -349,6 +349,8 @@ export type CaptionSettings = { enabled: boolean; font: string; size: number; coexport type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettings }export type CaptureDisplay = { id: DisplayId; name: string; refresh_rate: number }export type CaptureWindow = { id: WindowId; owner_name: string; name: string; bounds: LogicalBounds; refresh_rate: number }+export type ClipConfiguration = { index: number; offsets: ClipOffsets }+export type ClipOffsets = { camera?: number; mic?: number; system_audio?: number }export type CommercialLicense = { licenseKey: string; expiryDate: number | null; refresh: number; activatedOn: number }export type Crop = { position: XY<number>; size: XY<number> }export type CurrentRecording = { target: CurrentRecordingTarget; mode: RecordingMode }@@ -411,7 +413,7 @@ export type PostDeletionBehaviour = "doNothing" | "reopenRecordingWindow"export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay"export type Preset = { name: string; config: ProjectConfiguration }export type PresetsStore = { presets: Preset[]; default: number | null }-export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null; captions?: CaptionsData | null }+export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null; captions?: CaptionsData | null; clips?: ClipConfiguration[] }export type ProjectRecordingsMeta = { segments: SegmentRecordings[] }export type RecordingDeleted = { path: string }export type RecordingEvent = { variant: "Countdown"; value: number } | { variant: "Started" } | { variant: "Stopped" } | { variant: "Failed"; error: string }diff --git a/crates/audio/src/renderer.rs b/crates/audio/src/renderer.rsindex 9033dff13..bb22ae7ea 100644--- a/crates/audio/src/renderer.rs+++ b/crates/audio/src/renderer.rs@@ -6,9 +6,16 @@ pub enum StereoMode {MonoR,}+pub struct AudioRendererTrack<'a> {+ pub data: &'a AudioData,+ pub gain: f32,+ pub stereo_mode: StereoMode,+ pub offset: isize,+}+// Renders a combination of audio tracks into a single stereo bufferpub fn render_audio(- tracks: &[(&AudioData, f32, StereoMode)],+ tracks: &[AudioRendererTrack],offset: usize,samples: usize,out_offset: usize,@@ -17,7 +24,7 @@ pub fn render_audio(let samples = samples.min(tracks.iter()- .flat_map(|t| (t.0.samples().len() / t.0.channels() as usize).checked_sub(offset))+ .flat_map(|t| (t.data.samples().len() / t.data.channels() as usize).checked_sub(offset)).max().unwrap_or(0),);@@ -27,27 +34,30 @@ pub fn render_audio(let mut right = 0.0;for track in tracks {- let gain = gain_for_db(track.1);+ let i = i.wrapping_add_signed(track.offset);++ let data = track.data;+ let gain = gain_for_db(track.gain);if gain == f32::NEG_INFINITY {continue;}- if track.0.channels() == 1 {- if let Some(sample) = track.0.samples().get(offset + i) {+ if data.channels() == 1 {+ if let Some(sample) = data.samples().get(offset + i) {left += sample * 0.707 * gain;right += sample * 0.707 * gain;}- } else if track.0.channels() == 2 {+ } else if data.channels() == 2 {let base_idx = offset * 2 + i * 2;- let Some(l_sample) = track.0.samples().get(base_idx) else {+ let Some(l_sample) = data.samples().get(base_idx) else {continue;};- let Some(r_sample) = track.0.samples().get(base_idx + 1) else {+ let Some(r_sample) = data.samples().get(base_idx + 1) else {continue;};- match track.2 {+ match track.stereo_mode {StereoMode::Stereo => {left += l_sample * gain;right += r_sample * gain;diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rsindex 3edfec456..99e195444 100644--- a/crates/editor/src/audio.rs+++ b/crates/editor/src/audio.rs@@ -1,7 +1,9 @@-use cap_audio::{AudioData, FromSampleBytes, StereoMode, cast_f32_slice_to_bytes};+use cap_audio::{+ AudioData, AudioRendererTrack, FromSampleBytes, StereoMode, cast_f32_slice_to_bytes,+};use cap_media::MediaError;use cap_media_info::AudioInfo;-use cap_project::{AudioConfiguration, ProjectConfiguration, TimelineConfiguration};+use cap_project::{AudioConfiguration, ClipOffsets, ProjectConfiguration, TimelineConfiguration};use ffmpeg::{ChannelLayout, format as avformat, frame::Audio as FFAudio, software::resampling};use ringbuf::{HeapRb,@@ -29,11 +31,13 @@ pub struct AudioSegment {pub tracks: Vec<AudioSegmentTrack>,}+// yeah this is cursed oh well#[derive(Clone)]pub struct AudioSegmentTrack {data: Arc<AudioData>,get_gain: fn(&AudioConfiguration) -> f32,get_stereo_mode: fn(&AudioConfiguration) -> StereoMode,+ get_offset: fn(&ClipOffsets) -> f32,}impl AudioSegmentTrack {@@ -41,11 +45,13 @@ impl AudioSegmentTrack {data: Arc<AudioData>,get_gain: fn(&AudioConfiguration) -> f32,get_stereo_mode: fn(&AudioConfiguration) -> StereoMode,+ get_offset: fn(&ClipOffsets) -> f32,) -> Self {Self {data,get_gain,get_stereo_mode,+ get_offset,}}@@ -60,6 +66,10 @@ impl AudioSegmentTrack {pub fn stereo_mode(&self, config: &AudioConfiguration) -> StereoMode {(self.get_stereo_mode)(config)}++ pub fn offset(&self, offsets: &ClipOffsets) -> f32 {+ (self.get_offset)(offsets)+ }}impl AudioRenderer {@@ -184,16 +194,24 @@ impl AudioRenderer {let track_datas = tracks.iter().map(|t| {- (- t.data().as_ref(),- if project.audio.mute {+ let offsets = project+ .clips+ .iter()+ .find(|c| c.index == start.segment_index)+ .map(|c| c.offsets)+ .unwrap_or_default();++ AudioRendererTrack {+ data: t.data().as_ref(),+ gain: if project.audio.mute {f32::NEG_INFINITY} else {let g = t.gain(&project.audio);if g < -30.0 { f32::NEG_INFINITY } else { g }},- t.stereo_mode(&project.audio),- )+ stereo_mode: t.stereo_mode(&project.audio),+ offset: (t.offset(&offsets) * Self::SAMPLE_RATE as f32) as isize,+ }}).collect::<Vec<_>>();diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex c39a1f10a..6dd25c6f0 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -211,10 +211,12 @@ impl EditorInstance {};let segment = &self.segments[segment_i as usize];+ let clip_config = project.clips.iter().find(|v| v.index == segment_i);+ let clip_offsets = clip_config.map(|v| v.offsets).unwrap_or_default();if let Some(segment_frames) = segment.decoders- .get_frames(segment_time as f32, !project.camera.hide)+ .get_frames(segment_time as f32, !project.camera.hide, clip_offsets).await{let uniforms = ProjectUniforms::new(diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rsindex 4a762ca28..42c7a302d 100644--- a/crates/editor/src/playback.rs+++ b/crates/editor/src/playback.rs@@ -83,10 +83,12 @@ impl Playback {if let Some((segment_time, segment_i)) = project.get_segment_time(time) {let segment = &self.segments[segment_i as usize];+ let clip_config = project.clips.iter().find(|v| v.index == segment_i);+ let clip_offsets = clip_config.map(|v| v.offsets).unwrap_or_default();let data = tokio::select! {_ = stop_rx.changed() => { break; },- data = segment.decoders.get_frames(segment_time as f32, !project.camera.hide) => { data }+ data = segment.decoders.get_frames(segment_time as f32, !project.camera.hide, clip_offsets) => { data }};if let Some(segment_frames) = data {@@ -248,13 +250,11 @@ impl AudioPlayback {move |buffer: &mut [T], _info| {let project = project.borrow();- if prev_audio_config != project.audio {- audio_renderer.set_playhead(- playhead + elapsed as f64 / output_info.sample_rate as f64,- &project,- );- prev_audio_config = project.audio.clone();- }+ audio_renderer.set_playhead(+ playhead + elapsed as f64 / output_info.sample_rate as f64,+ &project,+ );+ prev_audio_config = project.audio.clone();audio_renderer.render(&project);audio_renderer.fill(buffer);diff --git a/crates/editor/src/segments.rs b/crates/editor/src/segments.rsindex a9422a3d9..1d13ed4fc 100644--- a/crates/editor/src/segments.rs+++ b/crates/editor/src/segments.rs@@ -17,6 +17,7 @@ pub fn get_audio_segments(segments: &[Segment]) -> Vec<AudioSegment> {cap_project::StereoMode::MonoL => cap_audio::StereoMode::MonoL,cap_project::StereoMode::MonoR => cap_audio::StereoMode::MonoR,},+ |o| o.mic,)}),s.system_audio.clone().map(|a| -> AudioSegmentTrack {@@ -24,6 +25,7 @@ pub fn get_audio_segments(segments: &[Segment]) -> Vec<AudioSegment> {a,|c| c.system_volume_db,|_| cap_audio::StereoMode::Stereo,+ |o| o.system_audio,)}),]diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rsindex 735b9a66e..289824234 100644--- a/crates/project/src/configuration.rs+++ b/crates/project/src/configuration.rs@@ -580,17 +580,32 @@ impl Default for CaptionSettings {}}-#[derive(Type, Serialize, Deserialize, Clone, Debug)]+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]#[serde(rename_all = "camelCase")]-#[derive(Default)]pub struct CaptionsData {pub segments: Vec<CaptionSegment>,pub settings: CaptionSettings,}-#[derive(Type, Serialize, Deserialize, Clone, Debug)]+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default)]+pub struct ClipOffsets {+ #[serde(default)]+ pub camera: f32,+ #[serde(default)]+ pub mic: f32,+ #[serde(default)]+ pub system_audio: f32,+}++#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]+#[serde(rename_all = "camelCase")]+pub struct ClipConfiguration {+ pub index: u32,+ pub offsets: ClipOffsets,+}++#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]#[serde(rename_all = "camelCase")]-#[derive(Default)]pub struct ProjectConfiguration {pub aspect_ratio: Option<AspectRatio>,pub background: BackgroundConfiguration,@@ -602,6 +617,8 @@ pub struct ProjectConfiguration {pub timeline: Option<TimelineConfiguration>,#[serde(default)]pub captions: Option<CaptionsData>,+ #[serde(default)]+ pub clips: Vec<ClipConfiguration>,}impl ProjectConfiguration {diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 1e32e8942..c7447d125 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -1,6 +1,6 @@use anyhow::Result;use cap_project::{- AspectRatio, CameraShape, CameraXPosition, CameraYPosition, Crop, CursorEvents,+ AspectRatio, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets, Crop, CursorEvents,ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY,};use composite_frame::CompositeVideoFrameUniforms;@@ -136,12 +136,16 @@ impl RecordingSegmentDecoders {&self,segment_time: f32,needs_camera: bool,+ offsets: ClipOffsets,) -> Option<DecodedSegmentFrames> {let (screen, camera) = tokio::join!(self.screen.get_frame(segment_time),OptionFuture::from(needs_camera- .then(|| self.camera.as_ref().map(|d| d.get_frame(segment_time)))+ .then(|| self+ .camera+ .as_ref()+ .map(|d| d.get_frame(segment_time + offsets.camera))).flatten()));@@ -216,6 +220,7 @@ pub async fn render_video_to_channel(};let segment = &segments[segment_i as usize];+ let clip_config = project.clips.iter().find(|v| v.index == segment_i);let frame_number = {let prev = frame_number;@@ -224,7 +229,11 @@ pub async fn render_video_to_channel(if let Some(segment_frames) = segment.decoders- .get_frames(segment_time as f32, !project.camera.hide)+ .get_frames(+ segment_time as f32,+ !project.camera.hide,+ clip_config.map(|v| v.offsets).unwrap_or_default(),+ ).await{let uniforms = ProjectUniforms::new(