Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(editor): add clip transitions

Richie McIlroy227f6b877181
diff --git a/apps/cli/src/selftest/playback.rs b/apps/cli/src/selftest/playback.rs
index f66f55435..60b35f1b5 100644
--- a/apps/cli/src/selftest/playback.rs
+++ b/apps/cli/src/selftest/playback.rs
@@ -902,6 +902,7 @@ mod fixture {
timescale: 1.0,
name: None,
}],
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs b/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs
index 1671af44e..5f6811253 100644
--- a/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs
+++ b/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs
@@ -158,6 +158,7 @@ async fn load_recording(
if !timeline_segments.is_empty() {
project.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 3046e91b7..45c61a2ae 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -1,10 +1,10 @@
use crate::editor_window::{OptionalWindowEditorInstance, WindowEditorInstance};
use crate::{FramesRendered, get_video_metadata};
use cap_export::{ExporterBase, make_cursor_only_project};
-use cap_project::{RecordingMeta, XY};
+use cap_project::{RecordingMeta, TimelineFrameMapping, XY};
use cap_rendering::{
FrameRenderer, ProjectRecordingsMeta, ProjectUniforms, RenderSegment, RenderVideoConstants,
- RendererLayers, ZoomTransformTimeline,
+ RendererLayers, TransitionRenderInput, ZoomTransformTimeline,
};
use futures::FutureExt;
use image::codecs::jpeg::JpegEncoder;
@@ -1328,7 +1328,7 @@ pub async fn get_export_estimates(
let meta = RecordingMeta::load_for_project(&path).map_err(|e| e.to_string())?;
let project_config = meta.project_config();
let duration_seconds = if let Some(timeline) = &project_config.timeline {
- timeline.segments.iter().map(|s| s.duration()).sum()
+ timeline.duration()
} else {
metadata.duration
};
@@ -1513,6 +1513,21 @@ async fn generate_export_preview_inner(
})
.collect();
+ let transition_mapping = project_config.timeline.as_ref().and_then(|timeline| {
+ if timeline.transitions.is_empty() {
+ return None;
+ }
+ match timeline.get_frame_mapping(frame_time) {
+ Some(TimelineFrameMapping::Transition {
+ outgoing,
+ kind,
+ progress,
+ ..
+ }) => Some((outgoing, kind, progress)),
+ _ => None,
+ }
+ });
+
let Some((segment_time, segment)) = project_config.get_segment_time(frame_time) else {
return Err("Frame time is outside video duration".to_string());
};
@@ -1543,11 +1558,12 @@ async fn generate_export_preview_inner(
.map(|t| t.duration())
.unwrap_or(0.0);
- let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ let mut zoom_timeline = ZoomTransformTimeline::from_project_for_clip(
&project_config,
&render_segment.cursor,
total_duration,
render_constants.options.screen_size,
+ segment.recording_clip,
);
zoom_timeline.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
@@ -1570,16 +1586,74 @@ async fn generate_export_preview_inner(
render_constants.is_software_adapter,
);
- let frame = frame_renderer
- .render_immediate(
- segment_frames,
- uniforms,
- &render_segment.cursor,
- render_segment.render_display,
- &mut layers,
- )
- .await
- .map_err(|e| format!("Failed to render frame: {e}"))?;
+ let frame = if let Some((outgoing, kind, progress)) = transition_mapping {
+ let outgoing_segment = &render_segments[outgoing.segment.recording_clip as usize];
+ let outgoing_offsets = project_config
+ .clips
+ .iter()
+ .find(|clip| clip.index == outgoing.segment.recording_clip)
+ .map(|clip| clip.offsets)
+ .unwrap_or_default();
+ let outgoing_frames = outgoing_segment
+ .decoders
+ .get_frames(
+ outgoing.source_time as f32,
+ !project_config.camera.hide,
+ outgoing_segment.render_display,
+ outgoing_offsets,
+ )
+ .await
+ .ok_or_else(|| "Failed to decode outgoing frame".to_string())?;
+ let mut outgoing_zoom = ZoomTransformTimeline::from_project_for_outgoing_clip(
+ &project_config,
+ &outgoing_segment.cursor,
+ total_duration,
+ render_constants.options.screen_size,
+ outgoing.segment.recording_clip,
+ );
+ outgoing_zoom.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
+ let outgoing_uniforms = ProjectUniforms::new(
+ &render_constants,
+ &project_config,
+ frame_number,
+ settings.fps,
+ settings.resolution_base,
+ &outgoing_segment.cursor,
+ &outgoing_frames,
+ total_duration,
+ &outgoing_zoom,
+ );
+ frame_renderer
+ .render_transition_immediate(
+ TransitionRenderInput {
+ segment_frames: outgoing_frames,
+ uniforms: outgoing_uniforms,
+ cursor: &outgoing_segment.cursor,
+ render_display: outgoing_segment.render_display,
+ },
+ TransitionRenderInput {
+ segment_frames,
+ uniforms,
+ cursor: &render_segment.cursor,
+ render_display: render_segment.render_display,
+ },
+ kind,
+ progress as f32,
+ &mut layers,
+ )
+ .await
+ } else {
+ frame_renderer
+ .render_immediate(
+ segment_frames,
+ uniforms,
+ &render_segment.cursor,
+ render_segment.render_display,
+ &mut layers,
+ )
+ .await
+ }
+ .map_err(|e| format!("Failed to render frame: {e}"))?;
let frame_render_time_ms = render_start.elapsed().as_secs_f64() * 1000.0;
@@ -1612,7 +1686,7 @@ async fn generate_export_preview_inner(
let metadata = get_video_metadata(project_path.clone()).await?;
let duration_seconds = if let Some(timeline) = &project_config.timeline {
- timeline.segments.iter().map(|s| s.duration()).sum()
+ timeline.duration()
} else {
metadata.duration
};
@@ -1761,6 +1835,20 @@ async fn generate_export_preview_fast_inner(
editor.project_config.1.borrow().clone(),
settings.cursor_only,
);
+ let transition_mapping = project_config.timeline.as_ref().and_then(|timeline| {
+ if timeline.transitions.is_empty() {
+ return None;
+ }
+ match timeline.get_frame_mapping(frame_time) {
+ Some(TimelineFrameMapping::Transition {
+ outgoing,
+ kind,
+ progress,
+ ..
+ }) => Some((outgoing, kind, progress)),
+ _ => None,
+ }
+ });
let Some((segment_time, segment)) = project_config.get_segment_time(frame_time) else {
return Err("Frame time is outside video duration".to_string());
@@ -1792,11 +1880,12 @@ async fn generate_export_preview_fast_inner(
.map(|t| t.duration())
.unwrap_or(0.0);
- let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ let mut zoom_timeline = ZoomTransformTimeline::from_project_for_clip(
&project_config,
&segment_media.cursor,
total_duration,
editor.render_constants.options.screen_size,
+ segment.recording_clip,
);
zoom_timeline.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
@@ -1819,16 +1908,74 @@ async fn generate_export_preview_fast_inner(
editor.render_constants.is_software_adapter,
);
- let frame = frame_renderer
- .render_immediate(
- segment_frames,
- uniforms,
- &segment_media.cursor,
- !settings.cursor_only,
- &mut layers,
- )
- .await
- .map_err(|e| format!("Failed to render frame: {e}"))?;
+ let frame = if let Some((outgoing, kind, progress)) = transition_mapping {
+ let outgoing_media = &editor.segment_medias[outgoing.segment.recording_clip as usize];
+ let outgoing_offsets = project_config
+ .clips
+ .iter()
+ .find(|clip| clip.index == outgoing.segment.recording_clip)
+ .map(|clip| clip.offsets)
+ .unwrap_or_default();
+ let outgoing_frames = outgoing_media
+ .decoders
+ .get_frames(
+ outgoing.source_time as f32,
+ !project_config.camera.hide,
+ !settings.cursor_only,
+ outgoing_offsets,
+ )
+ .await
+ .ok_or_else(|| "Failed to decode outgoing frame".to_string())?;
+ let mut outgoing_zoom = ZoomTransformTimeline::from_project_for_outgoing_clip(
+ &project_config,
+ &outgoing_media.cursor,
+ total_duration,
+ editor.render_constants.options.screen_size,
+ outgoing.segment.recording_clip,
+ );
+ outgoing_zoom.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
+ let outgoing_uniforms = ProjectUniforms::new(
+ &editor.render_constants,
+ &project_config,
+ frame_number,
+ settings.fps,
+ settings.resolution_base,
+ &outgoing_media.cursor,
+ &outgoing_frames,
+ total_duration,
+ &outgoing_zoom,
+ );
+ frame_renderer
+ .render_transition_immediate(
+ TransitionRenderInput {
+ segment_frames: outgoing_frames,
+ uniforms: outgoing_uniforms,
+ cursor: &outgoing_media.cursor,
+ render_display: !settings.cursor_only,
+ },
+ TransitionRenderInput {
+ segment_frames,
+ uniforms,
+ cursor: &segment_media.cursor,
+ render_display: !settings.cursor_only,
+ },
+ kind,
+ progress as f32,
+ &mut layers,
+ )
+ .await
+ } else {
+ frame_renderer
+ .render_immediate(
+ segment_frames,
+ uniforms,
+ &segment_media.cursor,
+ !settings.cursor_only,
+ &mut layers,
+ )
+ .await
+ }
+ .map_err(|e| format!("Failed to render frame: {e}"))?;
let frame_render_time_ms = render_start.elapsed().as_secs_f64() * 1000.0;
diff --git a/apps/desktop/src-tauri/src/import.rs b/apps/desktop/src-tauri/src/import.rs
index 6b5be86e5..b841c2cdb 100644
--- a/apps/desktop/src-tauri/src/import.rs
+++ b/apps/desktop/src-tauri/src/import.rs
@@ -368,6 +368,7 @@ fn ensure_project_timeline<'a>(
if config.timeline.is_none() {
config.timeline = Some(TimelineConfiguration {
segments: full_timeline_for_segments(project_path, segments)?,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index aae64c216..d6a7fcbce 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -3851,6 +3851,7 @@ fn project_config_from_recording(
config.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
+ transitions: Vec::new(),
zoom_segments,
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/apps/desktop/src/routes/editor/CaptionsTab.tsx b/apps/desktop/src/routes/editor/CaptionsTab.tsx
index 6efc8f4f4..cb78dd7b6 100644
--- a/apps/desktop/src/routes/editor/CaptionsTab.tsx
+++ b/apps/desktop/src/routes/editor/CaptionsTab.tsx
@@ -282,15 +282,20 @@ export function CaptionsTab(props: {
if (!source) return;
const recordingSegments = editorInstance.recordings.segments;
+ const sourceRange = { start: source.start, end: source.end };
const start = mapEditedTimeToSource(
timelineSegment.start,
timeline.segments,
recordingSegments,
+ timeline.transitions ?? [],
+ sourceRange,
);
const end = mapEditedTimeToSource(
timelineSegment.end,
timeline.segments,
recordingSegments,
+ timeline.transitions ?? [],
+ sourceRange,
);
if (start !== null) source.start = start;
if (end !== null) source.end = end;
diff --git a/apps/desktop/src/routes/editor/ClipsSidebar.tsx b/apps/desktop/src/routes/editor/ClipsSidebar.tsx
index e587fb0ec..0673e2959 100644
--- a/apps/desktop/src/routes/editor/ClipsSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ClipsSidebar.tsx
@@ -52,6 +52,12 @@ import {
RecordingOptionsProvider,
useRecordingOptions,
} from "../(window-chrome)/OptionsContext";
+import {
+ clipTimelineOffsets,
+ getClipTransition,
+ rippleTimelineTrack,
+ transitionsAfterClipMove,
+} from "./clip-transitions";
import {
type EditorTimelineSegment,
serializeProjectConfiguration,
@@ -259,6 +265,7 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
const {
project,
setProject,
+ projectActions,
editorInstance,
editorState,
setEditorState,
@@ -634,14 +641,52 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
if (from < insertionIndex) to -= 1;
if (from === to) return;
setProject(
- "timeline",
- "segments",
- produce((segs) => {
- if (!segs) return;
- const [moved] = segs.splice(from, 1);
- segs.splice(to, 0, moved);
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline) return;
+ const proposedSegments = [...timeline.segments];
+ const [proposedMoved] = proposedSegments.splice(from, 1);
+ proposedSegments.splice(to, 0, proposedMoved);
+ const { kept, dropped } = transitionsAfterClipMove(
+ timeline.segments.length,
+ timeline.transitions ?? [],
+ from,
+ to,
+ );
+ dropped.sort((a, b) => b.segmentIndex - a.segmentIndex);
+
+ for (const transition of dropped) {
+ const effective = getClipTransition(
+ timeline.segments,
+ timeline.transitions,
+ transition.segmentIndex,
+ );
+ if (!effective) continue;
+ const boundary =
+ clipTimelineOffsets(timeline.segments, timeline.transitions)[
+ transition.segmentIndex
+ ] + effective.duration;
+ timeline.transitions = timeline.transitions.filter(
+ (candidate) => candidate.segmentIndex !== transition.segmentIndex,
+ );
+ for (const track of [
+ timeline.zoomSegments,
+ timeline.sceneSegments ?? [],
+ timeline.maskSegments,
+ timeline.textSegments,
+ timeline.captionSegments ?? [],
+ timeline.keyboardSegments ?? [],
+ timeline.audioSegments ?? [],
+ ]) {
+ rippleTimelineTrack(track, boundary, effective.duration);
+ }
+ }
+
+ timeline.segments = proposedSegments;
+ timeline.transitions = kept;
}),
);
+ setEditorState("timeline", "selection", null);
};
const computeDropIndex = (clientY: number) => {
@@ -713,14 +758,7 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
const deleteClip = (index: number) => {
if (segments().length < 2) return;
- setProject(
- "timeline",
- "segments",
- produce((segs) => {
- if (!segs) return;
- segs.splice(index, 1);
- }),
- );
+ projectActions.deleteClipSegment(index);
};
createEventListener(window, "keydown", (event) => {
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 8deccb05a..2eae18aa7 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -108,6 +108,7 @@ export function PlayerContent() {
sceneSegments: [],
maskSegments: [],
textSegments: [],
+ transitions: [],
}),
captionSegments: createCaptionTrackSegments(captionSegments),
};
diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
index 4122059f0..2b7a6e2f1 100644
--- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
@@ -1,7 +1,5 @@
-import {
- createEventListener,
- createEventListenerMap,
-} from "@solid-primitives/event-listener";
+import { Popover } from "@kobalte/core/popover";
+import { createEventListenerMap } from "@solid-primitives/event-listener";
import { cx } from "cva";
import {
batch,
@@ -20,6 +18,16 @@ import {
import { produce } from "solid-js/store";
import type { TimelineSegment } from "~/utils/tauri";
+import {
+ clampTransitionDuration,
+ clipTimelineDuration,
+ clipTimelineOffsets,
+ clipTransitionMap,
+ DEFAULT_CLIP_TRANSITION_DURATION,
+ getClipTransition,
+ MIN_CLIP_TRANSITION_DURATION,
+ maxTransitionDuration,
+} from "../clip-transitions";
import { useEditorContext } from "../context";
import { useSegmentContext, useTimelineContext } from "./context";
import { getSectionMarker } from "./sectionMarker";
@@ -326,40 +334,63 @@ export function ClipTrack(
const segments = (): Array<TimelineSegment> =>
project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }];
+ const [transitionDrag, setTransitionDrag] = createSignal<{
+ index: number;
+ duration: number;
+ } | null>(null);
const selectedClipIndices = createMemo(() => {
const selection = editorState.timeline.selection;
if (!selection || selection.type !== "clip") return null;
return new Set(selection.indices);
});
const totalClipTimelineDuration = createMemo(() => {
- const segs = segments();
- let total = 0;
- for (let i = 0; i < segs.length; i++) {
- total += (segs[i].end - segs[i].start) / segs[i].timescale;
- }
- return total;
+ return clipTimelineDuration(
+ segments(),
+ project.timeline?.transitions ?? [],
+ );
});
+ const effectiveTransitions = createMemo(() =>
+ clipTransitionMap(segments(), project.timeline?.transitions ?? []),
+ );
const segmentOffsets = createMemo(() => {
const segs = segments();
- const offsets: number[] = new Array(segs.length);
- let sum = 0;
- for (let idx = 0; idx < segs.length; idx++) {
- offsets[idx] = sum;
- sum += (segs[idx].end - segs[idx].start) / segs[idx].timescale;
+ const transitions = project.timeline?.transitions ?? [];
+ const offsets = clipTimelineOffsets(segs, transitions);
+ const drag = transitionDrag();
+ if (drag) {
+ const committed =
+ getClipTransition(segs, transitions, drag.index)?.duration ?? 0;
+ const shift = committed - drag.duration;
+ for (let index = drag.index; index < offsets.length; index++) {
+ offsets[index] += shift;
+ }
}
return offsets;
});
+ const transitionAt = (index: number) => {
+ const drag = transitionDrag();
+ const transition = effectiveTransitions()[index] ?? null;
+ if (drag?.index !== index) return transition;
+ if (drag.duration === 0) return null;
+ return {
+ segmentIndex: index,
+ type: transition?.type ?? ("cross-fade" as const),
+ duration: drag.duration,
+ };
+ };
+
const visibleSegmentIndices = createMemo(() => {
const segs = segments();
const offsets = segmentOffsets();
+ const draggedIndex = transitionDrag()?.index;
const visible: number[] = [];
for (let i = 0; i < segs.length; i++) {
const seg = segs[i];
const segStart = offsets[i];
const segEnd = segStart + (seg.end - seg.start) / seg.timescale;
- if (isSegmentVisible(segStart, segEnd)) {
+ if (i === draggedIndex || isSegmentVisible(segStart, segEnd)) {
visible.push(i);
}
}
@@ -367,6 +398,7 @@ export function ClipTrack(
});
function onHandleReleased() {
+ projectActions.normalizeClipTransitions();
const { transform } = editorState.timeline;
if (transform.position + transform.zoom > totalDuration() + 4) {
@@ -382,6 +414,38 @@ export function ClipTrack(
const split = () => editorState.timeline.interactMode === "split";
+ function selectClip(currentIndex: number, event: MouseEvent) {
+ const selection = editorState.timeline.selection;
+ const isMac = navigator.platform.toUpperCase().includes("MAC");
+ const isMultiSelect = isMac ? event.metaKey : event.ctrlKey;
+
+ if (event.shiftKey && selection?.type === "clip") {
+ const lastIndex = selection.indices.at(-1) ?? currentIndex;
+ const start = Math.min(lastIndex, currentIndex);
+ const end = Math.max(lastIndex, currentIndex);
+ setEditorState("timeline", "selection", {
+ type: "clip",
+ indices: Array.from({ length: end - start + 1 }, (_, i) => start + i),
+ });
+ } else if (isMultiSelect && selection?.type === "clip") {
+ const indices = selection.indices.includes(currentIndex)
+ ? selection.indices.filter((index) => index !== currentIndex)
+ : [...selection.indices, currentIndex];
+ setEditorState(
+ "timeline",
+ "selection",
+ indices.length > 0 ? { type: "clip", indices } : null,
+ );
+ } else {
+ setEditorState("timeline", "selection", {
+ type: "clip",
+ indices: [currentIndex],
+ });
+ }
+
+ props.handleUpdatePlayhead(event);
+ }
+
return (
<TrackRoot
ref={props.ref}
@@ -556,6 +620,13 @@ export function ClipTrack(
segment={relativeSegment()}
onMouseDown={(e) => {
e.stopPropagation();
+ if (e.button !== 0) return;
+ if (
+ (e.target as HTMLElement).closest(
+ "[data-clip-handle], [data-transition]",
+ )
+ )
+ return;
if (editorState.timeline.interactMode === "split") {
const rect = e.currentTarget.getBoundingClientRect();
@@ -565,84 +636,94 @@ export function ClipTrack(
const splitTime =
(fraction * (seg.end - seg.start)) / seg.timescale;
- projectActions.splitClipSegment(prevDuration() + splitTime);
+ projectActions.splitClipSegment(
+ prevDuration() + splitTime,
+ i(),
+ );
} else {
- createRoot((dispose) => {
- createEventListener(
- e.currentTarget,
- "mouseup",
- (upEvent) => {
- dispose();
-
- const currentIndex = i();
- const selection = editorState.timeline.selection;
- const isMac =
- navigator.platform.toUpperCase().indexOf("MAC") >=
- 0;
- const isMultiSelect = isMac
- ? upEvent.metaKey
- : upEvent.ctrlKey;
- const isRangeSelect = upEvent.shiftKey;
-
- if (
- isRangeSelect &&
- selection &&
- selection.type === "clip"
- ) {
- // Range selection: select from last selected to current
- const existingIndices = selection.indices;
- const lastIndex =
- existingIndices[existingIndices.length - 1];
- const start = Math.min(lastIndex, currentIndex);
- const end = Math.max(lastIndex, currentIndex);
- const rangeIndices = Array.from(
- { length: end - start + 1 },
- (_, idx) => start + idx,
+ const index = i();
+ const initialTransition = getClipTransition(
+ segments(),
+ project.timeline?.transitions ?? [],
+ index,
+ );
+ const initialDuration = initialTransition?.duration ?? 0;
+ const canDrag =
+ index > 0 && !e.shiftKey && !e.ctrlKey && !e.metaKey;
+ const startX = e.clientX;
+ let active = false;
+ let nextDuration = initialDuration;
+ let pendingX = startX;
+ let frame: number | null = null;
+
+ const update = () => {
+ frame = null;
+ const delta = pendingX - startX;
+ if (!active) {
+ if (!canDrag || Math.abs(delta) < 4) return;
+ if (!initialTransition && delta > 0) return;
+ active = true;
+ }
+
+ const requested =
+ initialDuration - delta * secsPerPixel();
+ nextDuration =
+ requested < MIN_CLIP_TRANSITION_DURATION / 2
+ ? 0
+ : clampTransitionDuration(
+ requested || DEFAULT_CLIP_TRANSITION_DURATION,
+ segments()[index - 1],
+ segments()[index],
);
+ setTransitionDrag({ index, duration: nextDuration });
+ };
- setEditorState("timeline", "selection", {
- type: "clip" as const,
- indices: rangeIndices,
- });
- } else if (
- isMultiSelect &&
- selection &&
- selection.type === "clip"
- ) {
- // Multi-select: toggle current index
- const existingIndices = selection.indices;
-
- if (existingIndices.includes(currentIndex)) {
- // Remove from selection
- const newIndices = existingIndices.filter(
- (idx) => idx !== currentIndex,
- );
- if (newIndices.length > 0) {
- setEditorState("timeline", "selection", {
- type: "clip" as const,
- indices: newIndices,
- });
- } else {
- setEditorState("timeline", "selection", null);
- }
- } else {
- // Add to selection
- setEditorState("timeline", "selection", {
- type: "clip" as const,
- indices: [...existingIndices, currentIndex],
- });
- }
+ createRoot((dispose) => {
+ onCleanup(() => {
+ if (frame !== null) cancelAnimationFrame(frame);
+ });
+ createEventListenerMap(window, {
+ mousemove: (event) => {
+ pendingX = event.clientX;
+ if (frame === null)
+ frame = requestAnimationFrame(update);
+ },
+ mouseup: (event) => {
+ pendingX = event.clientX;
+ if (frame !== null) {
+ cancelAnimationFrame(frame);
+ frame = null;
+ }
+ update();
+ if (active) {
+ projectActions.setClipTransition(
+ index,
+ nextDuration > 0
+ ? {
+ type:
+ initialTransition?.type ?? "cross-fade",
+ duration: nextDuration,
+ }
+ : null,
+ );
+ setEditorState(
+ "timeline",
+ "selection",
+ nextDuration > 0
+ ? { type: "transition", index }
+ : null,
+ );
+ setTransitionDrag(null);
} else {
- // Normal single selection
- setEditorState("timeline", "selection", {
- type: "clip" as const,
- indices: [currentIndex],
- });
+ selectClip(index, event);
}
-
- props.handleUpdatePlayhead(upEvent);
+ dispose();
},
- );
+ blur: () => {
+ setTransitionDrag(null);
+ dispose();
+ },
+ });
});
}
}}
@@ -658,8 +739,139 @@ export function ClipTrack(
<Markings segment={segment()} prevDuration={prevDuration()} />
+ <Show when={i() > 0 && !transitionAt(i())}>
+ <button
+ type="button"
+ data-transition
+ class="absolute inset-y-0 left-0 z-[4] grid w-4 -translate-x-1/2 place-items-center bg-blue-9/40 text-xs text-white opacity-0 transition-opacity hover:bg-blue-9/60 group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-blue-9"
+ aria-label={`Add transition before clip ${i() + 1}`}
+ onClick={(event) => {
+ event.stopPropagation();
+ projectActions.setClipTransition(i(), {
+ type: "cross-fade",
+ duration: DEFAULT_CLIP_TRANSITION_DURATION,
+ });
+ setEditorState("timeline", "selection", {
+ type: "transition",
+ index: i(),
+ });
+ }}
+ >
+ +
+ </button>
+ </Show>
+
+ <Show when={transitionAt(i())}>
+ {(transition) => (
+ <Popover
+ placement="top"
+ gutter={8}
+ open={
+ editorState.timeline.selection?.type === "transition" &&
+ editorState.timeline.selection.index === i()
+ }
+ onOpenChange={(open) =>
+ setEditorState(
+ "timeline",
+ "selection",
+ open ? { type: "transition", index: i() } : null,
+ )
+ }
+ >
+ <Popover.Trigger
+ data-transition
+ class={cx(
+ "absolute inset-y-0 left-0 z-[5] overflow-hidden border-x border-blue-7/80 bg-blue-9/25 text-white transition-colors hover:bg-blue-9/40",
+ editorState.timeline.selection?.type ===
+ "transition" &&
+ editorState.timeline.selection.index === i() &&
+ "bg-blue-9/50 ring-1 ring-inset ring-blue-10",
+ )}
+ style={{
+ width: `${transition().duration / secsPerPixel()}px`,
+ "background-image":
+ "linear-gradient(135deg, transparent 42%, rgb(96 165 250 / 0.7) 43%, rgb(96 165 250 / 0.7) 57%, transparent 58%)",
+ }}
+ title={`${transition().type === "cross-fade" ? "Crossfade" : "Fade through black"} · ${transition().duration.toFixed(2)}s`}
+ onMouseDown={(event) => event.stopPropagation()}
+ >
+ <span class="sr-only">Edit clip transition</span>
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content
+ onMouseDown={(event) => event.stopPropagation()}
+ class="z-50 flex w-64 flex-col gap-3 rounded-xl border border-gray-3 bg-gray-1 p-3 text-gray-12 shadow-xl outline-hidden"
+ >
+ <div class="flex items-center justify-between">
+ <span class="text-sm font-medium">
+ Clip transition
+ </span>
+ <span class="text-xs tabular-nums text-gray-10">
+ {transition().duration.toFixed(2)}s
+ </span>
+ </div>
+ <div class="grid grid-cols-2 gap-1 rounded-lg bg-gray-2 p-1">
+ {(
+ [
+ ["cross-fade", "Crossfade"],
+ ["fade-through-black", "Fade"],
+ ] as const
+ ).map(([type, label]) => (
+ <button
+ type="button"
+ aria-pressed={transition().type === type}
+ class={cx(
+ "rounded-md px-2 py-1.5 text-xs transition-colors",
+ transition().type === type
+ ? "bg-gray-4 text-gray-12"
+ : "text-gray-10 hover:text-gray-12",
+ )}
+ onClick={() =>
+ projectActions.setClipTransition(i(), {
+ type,
+ duration: transition().duration,
+ })
+ }
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ <input
+ type="range"
+ aria-label="Transition duration"
+ min={MIN_CLIP_TRANSITION_DURATION}
+ max={maxTransitionDuration(
+ segments()[i() - 1],
+ segment(),
+ )}
+ step={0.05}
+ value={transition().duration}
+ onChange={(event) =>
+ projectActions.setClipTransition(i(), {
+ type: transition().type,
+ duration: event.currentTarget.valueAsNumber,
+ })
+ }
+ />
+ <button
+ type="button"
+ class="rounded-lg border border-red-500/30 px-3 py-2 text-xs text-red-400 transition-colors hover:bg-red-500/10"
+ onClick={() =>
+ projectActions.deleteClipTransition(i())
+ }
+ >
+ Remove transition
+ </button>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ )}
+ </Show>
+
<SegmentHandle
position="start"
+ data-clip-handle
class="opacity-0 group-hover:opacity-100"
onMouseDown={(downEvent) => {
if (split()) return;
@@ -669,6 +881,12 @@ export function ClipTrack(
secsPerPixel() *
MIN_CLIP_SEGMENT_PIXEL_WIDTH *
seg.timescale,
+ Math.max(
+ effectiveTransitions()[i()]?.duration ?? 0,
+ effectiveTransitions()[i() + 1]?.duration ?? 0,
+ ) *
+ 2 *
+ seg.timescale,
);
const initialStart = seg.start;
@@ -780,6 +998,7 @@ export function ClipTrack(
</SegmentContent>
<SegmentHandle
position="end"
+ data-clip-handle
class="opacity-0 group-hover:opacity-100"
onMouseDown={(downEvent) => {
const seg = segment();
@@ -789,6 +1008,12 @@ export function ClipTrack(
secsPerPixel() *
MIN_CLIP_SEGMENT_PIXEL_WIDTH *
seg.timescale,
+ Math.max(
+ effectiveTransitions()[i()]?.duration ?? 0,
+ effectiveTransitions()[i() + 1]?.duration ?? 0,
+ ) *
+ 2 *
+ seg.timescale,
);
if (split()) return;
diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx
index 4d5c7bc04..4919ec4fd 100644
--- a/apps/desktop/src/routes/editor/Timeline/index.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx
@@ -551,6 +551,7 @@ export function Timeline(props: {
textSegments: [],
captionSegments: [],
keyboardSegments: [],
+ transitions: [],
};
project.timeline.captionSegments = [];
}),
@@ -574,6 +575,7 @@ export function Timeline(props: {
textSegments: [],
captionSegments: [],
keyboardSegments: [],
+ transitions: [],
};
project.timeline.keyboardSegments = [];
}),
@@ -645,6 +647,7 @@ export function Timeline(props: {
textSegments: [],
captionSegments: [],
keyboardSegments: [],
+ transitions: [],
});
resume();
}
@@ -688,6 +691,7 @@ export function Timeline(props: {
textSegments: [],
captionSegments: [],
keyboardSegments: [],
+ transitions: [],
};
project.timeline.sceneSegments ??= [];
project.timeline.captionSegments ??= [];
@@ -846,6 +850,8 @@ export function Timeline(props: {
projectActions.deleteTextSegments(selection.indices);
} else if (selection.type === "audio") {
projectActions.deleteAudioSegments(selection.indices);
+ } else if (selection.type === "transition") {
+ projectActions.deleteClipTransition(selection.index);
} else if (selection.type === "clip") {
// Delete all selected clips in reverse order
[...selection.indices]
diff --git a/apps/desktop/src/routes/editor/TranscriptPage.tsx b/apps/desktop/src/routes/editor/TranscriptPage.tsx
index 3896154ea..ec25105e1 100644
--- a/apps/desktop/src/routes/editor/TranscriptPage.tsx
+++ b/apps/desktop/src/routes/editor/TranscriptPage.tsx
@@ -18,6 +18,7 @@ import { defaultCaptionSettings } from "~/store/captions";
import { commands } from "~/utils/tauri";
import {
getCaptionTextFromWords,
+ type MappedTimeRange,
mapEditedTimeToSource,
mapSourceRangeToEdited,
mapSourceTimeToEdited,
@@ -29,6 +30,10 @@ import {
createCaptionExportCues,
formatCaptionCues,
} from "./captions-export";
+import {
+ clipCutPreservesTransitionGeometry,
+ rangeIntersectsClipTransition,
+} from "./clip-transitions";
import { FPS, useEditorContext } from "./context";
import { rippleDeleteAllTracks } from "./timeline-utils";
@@ -84,6 +89,7 @@ export function TranscriptPanel() {
project.captions?.segments ?? [],
project.timeline?.segments ?? [],
recordingSegments(),
+ project.timeline?.transitions ?? [],
),
);
@@ -180,6 +186,7 @@ export function TranscriptPanel() {
outputStart,
project.timeline?.segments ?? [],
recordingSegments(),
+ project.timeline?.transitions ?? [],
) ?? outputStart;
const end = start + defaultDuration;
const text = "New caption";
@@ -205,6 +212,7 @@ export function TranscriptPanel() {
textSegments: [],
captionSegments: [],
keyboardSegments: [],
+ transitions: [],
};
p.captions.segments.push({
@@ -259,6 +267,7 @@ export function TranscriptPanel() {
editorState.playbackTime,
project.timeline?.segments ?? [],
recordingSegments(),
+ project.timeline?.transitions ?? [],
);
if (sourceTime === null) return -1;
@@ -283,6 +292,7 @@ export function TranscriptPanel() {
word.start,
project.timeline?.segments ?? [],
recordingSegments(),
+ project.timeline?.transitions ?? [],
);
if (outputTime === null) return;
if (editorState.playing) {
@@ -331,10 +341,6 @@ export function TranscriptPanel() {
}
}
- // Deleting transcript words also removes the matching span of video. The
- // caption master is source-timed, so translate the deleted source ranges
- // into the output-time ranges they currently occupy and ripple those out
- // of every output-time track (clips + zoom/mask/text/keyboard).
const outputRanges = mergedSourceRanges
.flatMap((range) =>
mapSourceRangeToEdited(
@@ -342,20 +348,51 @@ export function TranscriptPanel() {
range.end,
project.timeline?.segments ?? [],
recordingSegments(),
+ project.timeline?.transitions ?? [],
),
)
- .sort((a, b) => a.start - b.start);
+ .sort((a, b) => a.start - b.start || a.segmentIndex - b.segmentIndex);
- const mergedOutputRanges: { start: number; end: number }[] = [];
+ const mergedOutputRanges: MappedTimeRange[] = [];
for (const range of outputRanges) {
const last = mergedOutputRanges[mergedOutputRanges.length - 1];
- if (last && range.start <= last.end + 0.0001) {
+ if (
+ last &&
+ last.segmentIndex === range.segmentIndex &&
+ range.start <= last.end + 0.0001
+ ) {
last.end = Math.max(last.end, range.end);
} else {
mergedOutputRanges.push({ ...range });
}
}
+ const timeline = project.timeline;
+ if (
+ timeline &&
+ mergedOutputRanges.some(
+ (range) =>
+ rangeIntersectsClipTransition(
+ timeline.segments,
+ timeline.transitions ?? [],
+ range.start,
+ range.end,
+ ) ||
+ !clipCutPreservesTransitionGeometry(
+ timeline.segments,
+ timeline.transitions ?? [],
+ range.segmentIndex,
+ range.start,
+ range.end,
+ ),
+ )
+ ) {
+ toast.error(
+ "Remove the nearby transition before deleting this transcript range.",
+ );
+ return;
+ }
+
setProject(
produce((p) => {
if (!p.captions?.segments) return;
@@ -382,19 +419,22 @@ export function TranscriptPanel() {
if (p.timeline) {
for (const range of [...mergedOutputRanges].reverse()) {
if (range.end - range.start <= 0.001) continue;
- rippleDeleteAllTracks(p.timeline, range.start, range.end);
+ rippleDeleteAllTracks(
+ p.timeline,
+ range.start,
+ range.end,
+ range.segmentIndex,
+ );
}
}
}),
);
+ setEditorState("timeline", "selection", null);
setEditorState("captions", "isStale", false);
- const newDuration = project.timeline?.segments.reduce(
- (acc, s) => acc + (s.end - s.start) / s.timescale,
- 0,
- );
- if (newDuration !== undefined && editorState.playbackTime > newDuration) {
+ const newDuration = totalDuration();
+ if (editorState.playbackTime > newDuration) {
setEditorState("playbackTime", Math.max(newDuration - 0.01, 0));
}
};
diff --git a/apps/desktop/src/routes/editor/captions-export.ts b/apps/desktop/src/routes/editor/captions-export.ts
index 69ae2539f..1e6fd5d56 100644
--- a/apps/desktop/src/routes/editor/captions-export.ts
+++ b/apps/desktop/src/routes/editor/captions-export.ts
@@ -7,6 +7,7 @@ import {
getCaptionTextFromWords,
mapCaptionsToEditedTimeline,
} from "./captions";
+import type { ClipTransition } from "./clip-transitions";
export type CaptionExportFormat = "srt" | "vtt";
@@ -107,11 +108,13 @@ export function createCaptionExportCues(
segments: CaptionSegment[],
timelineSegments: TimelineSegment[],
recordingSegments: SegmentRecordings[],
+ transitions: ClipTransition[] = [],
): CaptionExportCue[] {
return mapCaptionsToEditedTimeline(
segments,
timelineSegments,
recordingSegments,
+ transitions,
)
.map(cueFromCaptionSegment)
.filter((cue): cue is CaptionExportCue => cue !== null)
diff --git a/apps/desktop/src/routes/editor/captions.ts b/apps/desktop/src/routes/editor/captions.ts
index 94ad9e3ae..50c3e6abf 100644
--- a/apps/desktop/src/routes/editor/captions.ts
+++ b/apps/desktop/src/routes/editor/captions.ts
@@ -11,6 +11,7 @@ import {
type SegmentRecordings,
type TimelineSegment,
} from "~/utils/tauri";
+import { type ClipTransition, clipTimelineOffsets } from "./clip-transitions";
export const DEFAULT_CAPTION_MODEL = "best";
export const DEFAULT_WHISPER_CAPTION_MODEL = "small";
export const DEFAULT_CAPTION_LANGUAGE = "auto";
@@ -74,13 +75,15 @@ export function getSelectedTranscriptionSettings() {
}
interface SourceToEditedMapping {
+ segmentIndex: number;
sourceStart: number;
sourceEnd: number;
editedStart: number;
timescale: number;
}
-interface MappedTimeRange {
+export interface MappedTimeRange {
+ segmentIndex: number;
start: number;
end: number;
}
@@ -88,6 +91,7 @@ interface MappedTimeRange {
function buildSourceToEditedMappings(
timelineSegments: TimelineSegment[],
recordingSegments: SegmentRecordings[],
+ transitions: ClipTransition[] = [],
): SourceToEditedMapping[] {
const recordingOffsets: number[] = [];
let cumulativeOffset = 0;
@@ -97,20 +101,20 @@ function buildSourceToEditedMappings(
}
const mappings: SourceToEditedMapping[] = [];
- let editedOffset = 0;
+ const editedOffsets = clipTimelineOffsets(timelineSegments, transitions);
- for (const seg of timelineSegments) {
+ for (let index = 0; index < timelineSegments.length; index++) {
+ const seg = timelineSegments[index];
const recIdx = seg.recordingSegment ?? 0;
const recOff = recordingOffsets[recIdx] ?? 0;
mappings.push({
+ segmentIndex: index,
sourceStart: recOff + seg.start,
sourceEnd: recOff + seg.end,
- editedStart: editedOffset,
+ editedStart: editedOffsets[index],
timescale: seg.timescale,
});
-
- editedOffset += (seg.end - seg.start) / seg.timescale;
}
return mappings;
@@ -127,6 +131,7 @@ function mapTimeRangeWithinMapping(
if (overlapStart >= overlapEnd) return null;
return {
+ segmentIndex: mapping.segmentIndex,
start:
mapping.editedStart +
(overlapStart - mapping.sourceStart) / mapping.timescale,
@@ -160,6 +165,7 @@ export function mapCaptionsToEditedTimeline(
rawSegments: CaptionSegment[],
timelineSegments: TimelineSegment[],
recordingSegments: SegmentRecordings[],
+ transitions: ClipTransition[] = [],
): CaptionSegment[] {
const sanitizedSegments = rawSegments.map(clampCaptionSegmentWords);
@@ -170,6 +176,7 @@ export function mapCaptionsToEditedTimeline(
const mappings = buildSourceToEditedMappings(
timelineSegments,
recordingSegments,
+ transitions,
);
const result: CaptionSegment[] = [];
@@ -296,6 +303,7 @@ export function deriveCaptionTrackSegments(
timelineSegments: TimelineSegment[],
recordingSegments: SegmentRecordings[],
previousTrack: CaptionTrackSegment[] = [],
+ transitions: ClipTransition[] = [],
): CaptionTrackSegment[] {
const overridesBySourceId = new Map<string, CaptionTrackOverrides>();
for (const segment of previousTrack) {
@@ -316,6 +324,7 @@ export function deriveCaptionTrackSegments(
sourceSegments,
timelineSegments,
recordingSegments,
+ transitions,
);
return mapped
@@ -340,10 +349,12 @@ export function mapSourceTimeToEdited(
sourceTime: number,
timelineSegments: TimelineSegment[],
recordingSegments: SegmentRecordings[],
+ transitions: ClipTransition[] = [],
): number | null {
const mappings = buildSourceToEditedMappings(
timelineSegments,
recordingSegments,
+ transitions,
);
for (const mapping of mappings) {
if (sourceTime >= mapping.sourceStart && sourceTime <= mapping.sourceEnd) {
@@ -366,10 +377,12 @@ export function mapSourceRangeToEdited(
sourceEnd: number,
timelineSegments: TimelineSegment[],
recordingSegments: SegmentRecordings[],
+ transitions: ClipTransition[] = [],
): MappedTimeRange[] {
const mappings = buildSourceToEditedMappings(
timelineSegments,
recordingSegments,
+ transitions,
);
const ranges: MappedTimeRange[] = [];
for (const mapping of mappings) {
@@ -388,23 +401,34 @@ export function mapEditedTimeToSource(
editedTime: number,
timelineSegments: TimelineSegment[],
recordingSegments: SegmentRecordings[],
+ transitions: ClipTransition[] = [],
+ sourceRange?: { start: number; end: number },
): number | null {
const mappings = buildSourceToEditedMappings(
timelineSegments,
recordingSegments,
+ transitions,
);
+ let fallback: number | null = null;
for (const mapping of mappings) {
const editedEnd =
mapping.editedStart +
(mapping.sourceEnd - mapping.sourceStart) / mapping.timescale;
if (editedTime >= mapping.editedStart && editedTime <= editedEnd) {
- return (
+ const sourceTime =
mapping.sourceStart +
- (editedTime - mapping.editedStart) * mapping.timescale
- );
+ (editedTime - mapping.editedStart) * mapping.timescale;
+ if (
+ sourceRange &&
+ sourceRange.start < mapping.sourceEnd &&
+ sourceRange.end > mapping.sourceStart
+ ) {
+ return sourceTime;
+ }
+ fallback = sourceTime;
}
}
- return null;
+ return fallback;
}
export function applyCaptionResultToProject<
@@ -419,6 +443,7 @@ export function applyCaptionResultToProject<
| ({
segments: TimelineSegment[];
captionSegments?: CaptionTrackSegment[] | null;
+ transitions?: ClipTransition[] | null;
} & Record<string, unknown>)
| null;
},
@@ -460,6 +485,7 @@ export function applyCaptionResultToProject<
timeline.segments,
recordingSegments,
timeline.captionSegments ?? [],
+ timeline.transitions ?? [],
);
}
@@ -790,4 +816,30 @@ if (import.meta.vitest) {
expect(rederived.find((s) => s.id === "capA")?.fontSizeOverride).toBe(42);
});
});
+
+ describe("mapEditedTimeToSource", () => {
+ it("selects the incoming source by default and honors a caption source hint", () => {
+ const segments: TimelineSegment[] = [
+ { start: 4, end: 6, timescale: 1, recordingSegment: 0 },
+ { start: 0, end: 2, timescale: 1, recordingSegment: 1 },
+ ];
+ const recordings = [
+ { display: { duration: 10 } } as SegmentRecordings,
+ { display: { duration: 10 } } as SegmentRecordings,
+ ];
+ const transitions: ClipTransition[] = [
+ { segmentIndex: 1, type: "cross-fade", duration: 0.5 },
+ ];
+
+ expect(
+ mapEditedTimeToSource(1.75, segments, recordings, transitions),
+ ).toBeCloseTo(10.25);
+ expect(
+ mapEditedTimeToSource(1.75, segments, recordings, transitions, {
+ start: 5,
+ end: 6,
+ }),
+ ).toBeCloseTo(5.75);
+ });
+ });
}
diff --git a/apps/desktop/src/routes/editor/clip-transitions.test.ts b/apps/desktop/src/routes/editor/clip-transitions.test.ts
new file mode 100644
index 000000000..b072eb75e
--- /dev/null
+++ b/apps/desktop/src/routes/editor/clip-transitions.test.ts
@@ -0,0 +1,211 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ type ClipTransition,
+ clampTransitionDuration,
+ clipCutPreservesTransitionGeometry,
+ clipTimelineDuration,
+ clipTimelineOffsets,
+ getClipTransition,
+ maxTransitionDuration,
+ normalizeClipTransitions,
+ rangeIntersectsClipTransition,
+ rippleTimelineTrack,
+ timelineShiftAfterClipDurationChange,
+ transitionsAfterClipDelete,
+ transitionsAfterClipMove,
+ transitionsAfterClipSplit,
+} from "./clip-transitions";
+
+const segment = (duration: number) => ({
+ start: 0,
+ end: duration,
+ timescale: 1,
+});
+
+const transition = (
+ segmentIndex: number,
+ duration: number,
+ type: ClipTransition["type"] = "cross-fade",
+): ClipTransition => ({ segmentIndex, type, duration });
+
+describe("clip transitions", () => {
+ it("keeps a legacy timeline unchanged", () => {
+ const segments = [segment(4), segment(6), segment(2)];
+
+ expect(clipTimelineOffsets(segments, [])).toEqual([0, 4, 10]);
+ expect(clipTimelineDuration(segments, [])).toBe(12);
+ });
+
+ it("overlaps an incoming clip by its transition duration", () => {
+ const segments = [segment(4), segment(6), segment(2)];
+ const transitions = [
+ transition(1, 1),
+ transition(2, 0.5, "fade-through-black"),
+ ];
+
+ expect(clipTimelineOffsets(segments, transitions)).toEqual([0, 3, 8.5]);
+ expect(clipTimelineDuration(segments, transitions)).toBe(10.5);
+ expect(getClipTransition(segments, transitions, 1)).toEqual({
+ segmentIndex: 1,
+ type: "cross-fade",
+ duration: 1,
+ });
+ });
+
+ it("clamps overlap to half of the shorter adjacent clip", () => {
+ const previous = segment(8);
+ const current = segment(1);
+
+ expect(maxTransitionDuration(previous, current)).toBe(0.5);
+ expect(clampTransitionDuration(3, previous, current)).toBe(0.5);
+ });
+
+ it("rejects transitions without two usable adjacent clips", () => {
+ const segments = [segment(0.04), segment(2)];
+ const transitions = [transition(1, 0.5)];
+
+ expect(getClipTransition(segments, transitions, 0)).toBeNull();
+ expect(getClipTransition(segments, transitions, 1)).toBeNull();
+ expect(clipTimelineDuration(segments, transitions)).toBe(2.04);
+ });
+
+ it("uses the last transition for a duplicated boundary", () => {
+ const segments = [segment(4), segment(4)];
+ const transitions = [transition(1, 0.5), transition(1, 1)];
+
+ expect(getClipTransition(segments, transitions, 1)?.duration).toBe(1);
+ });
+
+ it("normalizes stored durations so later clip edits cannot re-expand them", () => {
+ const transitions = normalizeClipTransitions(
+ [segment(8), segment(1)],
+ [transition(1, 3)],
+ );
+
+ expect(transitions).toEqual([transition(1, 0.5)]);
+ expect(
+ getClipTransition([segment(8), segment(8)], transitions, 1)?.duration,
+ ).toBe(0.5);
+ });
+
+ it("ripples tracks without detaching items that start on the cut", () => {
+ const track = [
+ { start: 3, end: 4 },
+ { start: 2.75, end: 3.25 },
+ { start: 2, end: 3 },
+ ];
+
+ rippleTimelineTrack(track, 3, -0.5);
+
+ expect(track).toEqual([
+ { start: 2.5, end: 3.5 },
+ { start: 2.75, end: 2.75 },
+ { start: 2, end: 3 },
+ ]);
+ });
+
+ it("reaches the full speed-change shift at an outgoing transition", () => {
+ const oldSegments = [segment(10), segment(5)];
+ const transitions = [transition(1, 2)];
+ const newSegments = [{ ...segment(10), timescale: 2 }, segment(5)];
+ const oldOffsets = clipTimelineOffsets(oldSegments, transitions);
+ const newOffsets = clipTimelineOffsets(newSegments, transitions);
+
+ expect(oldOffsets[1]).toBe(8);
+ expect(newOffsets[1]).toBe(3);
+ expect(
+ timelineShiftAfterClipDurationChange(
+ 8,
+ oldOffsets[0],
+ newOffsets[0],
+ oldOffsets[0],
+ oldOffsets[1],
+ newOffsets[1],
+ ),
+ ).toBe(-5);
+ });
+
+ it("moves tracks with an incoming transition that becomes shorter", () => {
+ const oldSegments = [segment(10), segment(1)];
+ const transitions = [transition(1, 0.5)];
+ const newSegments = [segment(10), { ...segment(1), timescale: 2 }];
+ const oldOffsets = clipTimelineOffsets(oldSegments, transitions);
+ const newOffsets = clipTimelineOffsets(newSegments, transitions);
+
+ expect(oldOffsets[1]).toBe(9.5);
+ expect(newOffsets[1]).toBe(9.75);
+ expect(
+ timelineShiftAfterClipDurationChange(
+ 9.5,
+ oldOffsets[1],
+ newOffsets[1],
+ 10,
+ 10.5,
+ 10.25,
+ ),
+ ).toBe(0.25);
+ expect(
+ timelineShiftAfterClipDurationChange(
+ 10,
+ oldOffsets[1],
+ newOffsets[1],
+ 10,
+ 10.5,
+ 10.25,
+ ),
+ ).toBe(0);
+ });
+
+ it("uses the full shift when incoming and outgoing transitions share a boundary", () => {
+ expect(timelineShiftAfterClipDurationChange(4, 3, 3, 4, 4, 6)).toBe(2);
+ });
+
+ it("detects only ranges inside active transition overlaps", () => {
+ const segments = [segment(4), segment(4)];
+ const transitions = [transition(1, 1)];
+
+ expect(
+ rangeIntersectsClipTransition(segments, transitions, 3.25, 3.5),
+ ).toBe(true);
+ expect(rangeIntersectsClipTransition(segments, transitions, 2.5, 3)).toBe(
+ false,
+ );
+ expect(rangeIntersectsClipTransition(segments, transitions, 4, 4.5)).toBe(
+ false,
+ );
+ });
+
+ it("rejects cuts that would force an adjacent transition to shrink", () => {
+ const segments = [segment(4), segment(4)];
+ const transitions = [transition(1, 1)];
+
+ expect(
+ clipCutPreservesTransitionGeometry(segments, transitions, 1, 4.1, 4.2),
+ ).toBe(false);
+ expect(
+ clipCutPreservesTransitionGeometry(segments, transitions, 1, 5.1, 5.2),
+ ).toBe(true);
+ });
+
+ it("repairs transition indices after clip splits and deletes", () => {
+ const transitions = [transition(1, 0.5), transition(3, 0.75)];
+
+ expect(transitionsAfterClipSplit(transitions, 1)).toEqual([
+ transition(1, 0.5),
+ transition(4, 0.75),
+ ]);
+ expect(transitionsAfterClipDelete(transitions, 1)).toEqual([
+ transition(2, 0.75),
+ ]);
+ });
+
+ it("preserves only clip adjacencies that survive a reorder", () => {
+ const transitions = [transition(1, 0.5), transition(3, 0.75)];
+
+ expect(transitionsAfterClipMove(4, transitions, 1, 3)).toEqual({
+ kept: [transition(2, 0.75)],
+ dropped: [transition(1, 0.5)],
+ });
+ });
+});
diff --git a/apps/desktop/src/routes/editor/clip-transitions.ts b/apps/desktop/src/routes/editor/clip-transitions.ts
new file mode 100644
index 000000000..ed82bc526
--- /dev/null
+++ b/apps/desktop/src/routes/editor/clip-transitions.ts
@@ -0,0 +1,268 @@
+import type { TimelineSegment } from "~/utils/tauri";
+
+export const DEFAULT_CLIP_TRANSITION_DURATION = 0.5;
+export const MIN_CLIP_TRANSITION_DURATION = 0.05;
+
+export type ClipTransitionKind = "cross-fade" | "fade-through-black";
+
+export type ClipTransition = {
+ segmentIndex: number;
+ type: ClipTransitionKind;
+ duration: number;
+};
+
+export type ClipTransitionInput = Omit<ClipTransition, "segmentIndex">;
+
+export function clipDuration(segment: TimelineSegment) {
+ return Math.max(0, (segment.end - segment.start) / segment.timescale);
+}
+
+export function maxTransitionDuration(
+ previous: TimelineSegment | undefined,
+ current: TimelineSegment | undefined,
+) {
+ if (!previous || !current) return 0;
+ return Math.min(clipDuration(previous), clipDuration(current)) / 2;
+}
+
+export function clampTransitionDuration(
+ duration: number,
+ previous: TimelineSegment | undefined,
+ current: TimelineSegment | undefined,
+) {
+ const maximum = maxTransitionDuration(previous, current);
+ if (maximum < MIN_CLIP_TRANSITION_DURATION) return 0;
+ return Math.min(Math.max(duration, MIN_CLIP_TRANSITION_DURATION), maximum);
+}
+
+export function getClipTransition(
+ segments: TimelineSegment[],
+ transitions: ClipTransition[],
+ index: number,
+): ClipTransition | null {
+ if (index <= 0 || index >= segments.length) return null;
+ let transition: ClipTransition | undefined;
+ for (
+ let transitionIndex = transitions.length - 1;
+ transitionIndex >= 0;
+ transitionIndex--
+ ) {
+ const candidate = transitions[transitionIndex];
+ if (candidate.segmentIndex === index) {
+ transition = candidate;
+ break;
+ }
+ }
+ if (!transition) return null;
+ const duration = clampTransitionDuration(
+ transition.duration,
+ segments[index - 1],
+ segments[index],
+ );
+ if (duration === 0) return null;
+ return { ...transition, duration };
+}
+
+export function clipTransitionMap(
+ segments: TimelineSegment[],
+ transitions: ClipTransition[],
+) {
+ const configured = new Array<ClipTransition | undefined>(segments.length);
+ for (const transition of transitions) {
+ if (
+ transition.segmentIndex > 0 &&
+ transition.segmentIndex < segments.length
+ ) {
+ configured[transition.segmentIndex] = transition;
+ }
+ }
+
+ return configured.map((transition, index): ClipTransition | null => {
+ if (!transition) return null;
+ const duration = clampTransitionDuration(
+ transition.duration,
+ segments[index - 1],
+ segments[index],
+ );
+ return duration > 0 ? { ...transition, duration } : null;
+ });
+}
+
+export function clipTimelineOffsets(
+ segments: TimelineSegment[],
+ transitions: ClipTransition[],
+) {
+ const offsets = new Array<number>(segments.length);
+ const effectiveTransitions = clipTransitionMap(segments, transitions);
+ let offset = 0;
+
+ for (let index = 0; index < segments.length; index++) {
+ offset -= effectiveTransitions[index]?.duration ?? 0;
+ offsets[index] = offset;
+ offset += clipDuration(segments[index]);
+ }
+
+ return offsets;
+}
+
+export function normalizeClipTransitions(
+ segments: TimelineSegment[],
+ transitions: ClipTransition[],
+) {
+ return clipTransitionMap(segments, transitions).filter(
+ (transition): transition is ClipTransition => transition !== null,
+ );
+}
+
+export function clipTimelineDuration(
+ segments: TimelineSegment[],
+ transitions: ClipTransition[],
+) {
+ if (segments.length === 0) return 0;
+ const offsets = clipTimelineOffsets(segments, transitions);
+ return (
+ offsets[offsets.length - 1] + clipDuration(segments[segments.length - 1])
+ );
+}
+
+export function rangeIntersectsClipTransition(
+ segments: TimelineSegment[],
+ transitions: ClipTransition[],
+ start: number,
+ end: number,
+) {
+ const offsets = clipTimelineOffsets(segments, transitions);
+ return clipTransitionMap(segments, transitions).some((transition, index) => {
+ if (!transition) return false;
+ const transitionStart = offsets[index];
+ return (
+ end > transitionStart && start < transitionStart + transition.duration
+ );
+ });
+}
+
+export function clipCutPreservesTransitionGeometry(
+ segments: TimelineSegment[],
+ transitions: ClipTransition[],
+ segmentIndex: number,
+ cutStart: number,
+ cutEnd: number,
+) {
+ const segment = segments[segmentIndex];
+ if (!segment) return false;
+ const offsets = clipTimelineOffsets(segments, transitions);
+ const segmentStart = offsets[segmentIndex];
+ const duration = clipDuration(segment);
+ const localStart = cutStart - segmentStart;
+ const localEnd = cutEnd - segmentStart;
+ if (localStart < 0 || localEnd > duration || localStart >= localEnd)
+ return false;
+ const incomingDuration =
+ getClipTransition(segments, transitions, segmentIndex)?.duration ?? 0;
+ const outgoingDuration =
+ getClipTransition(segments, transitions, segmentIndex + 1)?.duration ?? 0;
+ return (
+ localStart + Number.EPSILON >= incomingDuration * 2 &&
+ duration - localEnd + Number.EPSILON >= outgoingDuration * 2
+ );
+}
+
+export function rippleTimelineTrack(
+ track: { start: number; end: number }[],
+ boundary: number,
+ shift: number,
+) {
+ for (const item of track) {
+ if (item.start >= boundary) {
+ item.start += shift;
+ item.end += shift;
+ } else if (item.end > boundary) {
+ item.end = Math.max(item.start, item.end + shift);
+ }
+ }
+}
+
+export function timelineShiftAfterClipDurationChange(
+ time: number,
+ oldCurrentStart: number,
+ newCurrentStart: number,
+ oldStableStart: number,
+ oldNextBoundary: number,
+ newNextBoundary: number,
+) {
+ if (time < oldCurrentStart) return 0;
+ if (time < oldStableStart) {
+ const incomingDuration = oldStableStart - oldCurrentStart;
+ if (incomingDuration <= Number.EPSILON) return 0;
+ return (
+ ((newCurrentStart - oldCurrentStart) * (oldStableStart - time)) /
+ incomingDuration
+ );
+ }
+ const fullShift = newNextBoundary - oldNextBoundary;
+ if (time >= oldNextBoundary) return fullShift;
+ if (time <= oldStableStart) return 0;
+ const affectedDuration = oldNextBoundary - oldStableStart;
+ if (affectedDuration <= Number.EPSILON) return fullShift;
+ return (fullShift * (time - oldStableStart)) / affectedDuration;
+}
+
+export function transitionsAfterClipSplit(
+ transitions: ClipTransition[],
+ segmentIndex: number,
+) {
+ return transitions.map((transition) =>
+ transition.segmentIndex > segmentIndex
+ ? { ...transition, segmentIndex: transition.segmentIndex + 1 }
+ : transition,
+ );
+}
+
+export function transitionsAfterClipDelete(
+ transitions: ClipTransition[],
+ segmentIndex: number,
+) {
+ return transitions.flatMap((transition) => {
+ if (
+ transition.segmentIndex === segmentIndex ||
+ transition.segmentIndex === segmentIndex + 1
+ )
+ return [];
+ return [
+ transition.segmentIndex > segmentIndex
+ ? { ...transition, segmentIndex: transition.segmentIndex - 1 }
+ : transition,
+ ];
+ });
+}
+
+export function transitionsAfterClipMove(
+ segmentCount: number,
+ transitions: ClipTransition[],
+ from: number,
+ to: number,
+) {
+ const order = Array.from({ length: segmentCount }, (_, index) => index);
+ const [moved] = order.splice(from, 1);
+ order.splice(to, 0, moved);
+ const kept: ClipTransition[] = [];
+ const dropped: ClipTransition[] = [];
+
+ for (const transition of transitions) {
+ const originalIndex = transition.segmentIndex;
+ const nextIndex = order.findIndex(
+ (segmentIndex, index) =>
+ index > 0 &&
+ order[index - 1] === originalIndex - 1 &&
+ segmentIndex === originalIndex,
+ );
+ if (nextIndex > 0) {
+ kept.push({ ...transition, segmentIndex: nextIndex });
+ } else {
+ dropped.push(transition);
+ }
+ }
+
+ kept.sort((a, b) => a.segmentIndex - b.segmentIndex);
+ return { kept, dropped };
+}
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 64768a25e..616f9ccb1 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -59,6 +59,19 @@ import {
MIN_AUDIO_SEGMENT_DURATION,
} from "./audio";
import { deriveCaptionTrackSegments, mapEditedTimeToSource } from "./captions";
+import {
+ type ClipTransition,
+ type ClipTransitionInput,
+ clampTransitionDuration,
+ clipTimelineDuration,
+ clipTimelineOffsets,
+ getClipTransition,
+ normalizeClipTransitions,
+ rippleTimelineTrack,
+ timelineShiftAfterClipDurationChange,
+ transitionsAfterClipDelete,
+ transitionsAfterClipSplit,
+} from "./clip-transitions";
import type { MaskSegment } from "./masks";
import type { SnapGuide } from "./snapping";
import type { TextSegment } from "./text";
@@ -166,9 +179,14 @@ export type EditorTimelineSegment = TimelineSegment & {
type EditorTimelineConfiguration = Omit<
TimelineConfiguration,
- "sceneSegments" | "maskSegments" | "segments" | "audioSegments"
+ | "sceneSegments"
+ | "maskSegments"
+ | "segments"
+ | "audioSegments"
+ | "transitions"
> & {
segments: EditorTimelineSegment[];
+ transitions: ClipTransition[];
sceneSegments?: SceneSegment[];
maskSegments: MaskSegment[];
textSegments: TextSegment[];
@@ -220,6 +238,12 @@ export function normalizeProject(
const timeline = config.timeline
? {
...config.timeline,
+ transitions:
+ (
+ config.timeline as TimelineConfiguration & {
+ transitions?: ClipTransition[];
+ }
+ ).transitions ?? [],
sceneSegments: config.timeline.sceneSegments ?? [],
captionSegments: config.timeline.captionSegments ?? [],
keyboardSegments: config.timeline.keyboardSegments ?? [],
@@ -274,6 +298,7 @@ export function serializeProjectConfiguration(
const timeline = project.timeline
? {
...project.timeline,
+ transitions: project.timeline.transitions ?? [],
captionSegments: project.timeline.captionSegments ?? [],
keyboardSegments: project.timeline.keyboardSegments ?? [],
maskSegments: project.timeline.maskSegments ?? [],
@@ -307,30 +332,141 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
normalizeProject(props.editorInstance.savedProjectConfig),
);
+ const setClipTransition = (
+ segmentIndex: number,
+ transition: ClipTransitionInput | null,
+ ) => {
+ setProject(
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline || segmentIndex <= 0) return;
+ const segment = timeline.segments[segmentIndex];
+ const previous = timeline.segments[segmentIndex - 1];
+ if (!segment || !previous) return;
+ const transitions = timeline.transitions ?? [];
+
+ const oldDuration =
+ getClipTransition(timeline.segments, transitions, segmentIndex)
+ ?.duration ?? 0;
+ const duration = transition
+ ? clampTransitionDuration(transition.duration, previous, segment)
+ : 0;
+ const boundary =
+ clipTimelineOffsets(timeline.segments, transitions)[segmentIndex] +
+ oldDuration;
+ const shift = oldDuration - duration;
+
+ timeline.transitions = transitions.filter(
+ (value) => value.segmentIndex !== segmentIndex,
+ );
+ if (transition && duration > 0) {
+ timeline.transitions.push({
+ ...transition,
+ segmentIndex,
+ duration,
+ });
+ timeline.transitions.sort(
+ (a, b) => a.segmentIndex - b.segmentIndex,
+ );
+ }
+
+ if (shift === 0) return;
+ const tracks = [
+ timeline.zoomSegments,
+ timeline.sceneSegments ?? [],
+ timeline.maskSegments,
+ timeline.textSegments,
+ timeline.captionSegments ?? [],
+ timeline.keyboardSegments ?? [],
+ timeline.audioSegments ?? [],
+ ];
+ for (const track of tracks) {
+ rippleTimelineTrack(track, boundary, shift);
+ }
+ }),
+ );
+ };
+
const projectActions = {
- splitClipSegment: (time: number) => {
+ setClipTransition,
+ normalizeClipTransitions: () => {
setProject(
- "timeline",
- "segments",
- produce((segments) => {
- let searchTime = time;
- let _prevDuration = 0;
- const currentSegmentIndex = segments.findIndex((segment) => {
- const duration =
- (segment.end - segment.start) / segment.timescale;
- if (searchTime > duration) {
- searchTime -= duration;
- _prevDuration += duration;
- return false;
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline) return;
+ const normalized = normalizeClipTransitions(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ if (
+ normalized.length === timeline.transitions.length &&
+ normalized.every((transition, index) => {
+ const current = timeline.transitions[index];
+ return (
+ current?.segmentIndex === transition.segmentIndex &&
+ current.type === transition.type &&
+ current.duration === transition.duration
+ );
+ })
+ )
+ return;
+ timeline.transitions = normalized;
+ }),
+ );
+ },
+ deleteClipTransition: (segmentIndex: number) => {
+ setClipTransition(segmentIndex, null);
+ setEditorState("timeline", "selection", null);
+ },
+ splitClipSegment: (time: number, requestedSegmentIndex?: number) => {
+ let didSplit = false;
+ setProject(
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline) return;
+ const segments = timeline.segments;
+ const offsets = clipTimelineOffsets(
+ segments,
+ timeline.transitions ?? [],
+ );
+ let currentSegmentIndex = requestedSegmentIndex ?? -1;
+ if (currentSegmentIndex < 0) {
+ for (let index = 0; index < segments.length; index++) {
+ const duration =
+ (segments[index].end - segments[index].start) /
+ segments[index].timescale;
+ if (
+ time >= offsets[index] &&
+ time <= offsets[index] + duration
+ ) {
+ currentSegmentIndex = index;
+ }
}
-
- return true;
- });
+ }
if (currentSegmentIndex === -1) return;
const segment = segments[currentSegmentIndex];
-
- const splitPositionInRecording = searchTime * segment.timescale;
+ const localTime = time - offsets[currentSegmentIndex];
+ const duration = (segment.end - segment.start) / segment.timescale;
+ if (localTime <= 0 || localTime >= duration) return;
+ const incomingDuration =
+ getClipTransition(
+ segments,
+ timeline.transitions ?? [],
+ currentSegmentIndex,
+ )?.duration ?? 0;
+ const outgoingDuration =
+ getClipTransition(
+ segments,
+ timeline.transitions ?? [],
+ currentSegmentIndex + 1,
+ )?.duration ?? 0;
+ if (
+ localTime < incomingDuration * 2 ||
+ duration - localTime < outgoingDuration * 2
+ )
+ return;
+ const splitPositionInRecording = localTime * segment.timescale;
segments.splice(currentSegmentIndex + 1, 0, {
...segment,
@@ -339,8 +475,14 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
});
segments[currentSegmentIndex].end =
segment.start + splitPositionInRecording;
+ timeline.transitions = transitionsAfterClipSplit(
+ timeline.transitions ?? [],
+ currentSegmentIndex,
+ );
+ didSplit = true;
}),
);
+ if (didSplit) setEditorState("timeline", "selection", null);
},
deleteClipSegment: (segmentIndex: number) => {
if (!project.timeline) return;
@@ -349,11 +491,14 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
batch(() => {
setProject(
- "timeline",
- "segments",
- produce((s) => {
- if (!s) return;
- s.splice(segmentIndex, 1);
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline) return;
+ timeline.segments.splice(segmentIndex, 1);
+ timeline.transitions = transitionsAfterClipDelete(
+ timeline.transitions ?? [],
+ segmentIndex,
+ );
}),
);
setEditorState("timeline", "selection", null);
@@ -736,30 +881,57 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
const segment = timeline.segments[index];
if (!segment) return;
- const currentLength =
- (segment.end - segment.start) / segment.timescale;
- const nextLength = (segment.end - segment.start) / timescale;
-
- const lengthDiff = nextLength - currentLength;
-
- const absoluteStart = timeline.segments.reduce((acc, curr, i) => {
- if (i >= index) return acc;
- return acc + (curr.end - curr.start) / curr.timescale;
- }, 0);
-
- const diff = (v: number) => {
- const diff = (lengthDiff * (v - absoluteStart)) / currentLength;
-
- if (v > absoluteStart + currentLength) return lengthDiff;
- else if (v > absoluteStart) return diff;
- else return 0;
- };
+ const oldDuration = clipTimelineDuration(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ const oldOffsets = clipTimelineOffsets(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ const incomingDuration =
+ getClipTransition(
+ timeline.segments,
+ timeline.transitions ?? [],
+ index,
+ )?.duration ?? 0;
+ segment.timescale = timescale;
+ timeline.transitions = normalizeClipTransitions(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ const newDuration = clipTimelineDuration(
+ timeline.segments,
+ timeline.transitions,
+ );
+ const newOffsets = clipTimelineOffsets(
+ timeline.segments,
+ timeline.transitions,
+ );
+ const absoluteStart = oldOffsets[index] + incomingDuration;
+ const oldNextBoundary = oldOffsets[index + 1] ?? oldDuration;
+ const newNextBoundary = newOffsets[index + 1] ?? newDuration;
+
+ const diff = (value: number) =>
+ timelineShiftAfterClipDurationChange(
+ value,
+ oldOffsets[index],
+ newOffsets[index],
+ absoluteStart,
+ oldNextBoundary,
+ newNextBoundary,
+ );
for (const zoomSegment of timeline.zoomSegments) {
zoomSegment.start += diff(zoomSegment.start);
zoomSegment.end += diff(zoomSegment.end);
}
+ for (const sceneSegment of timeline.sceneSegments ?? []) {
+ sceneSegment.start += diff(sceneSegment.start);
+ sceneSegment.end += diff(sceneSegment.end);
+ }
+
for (const maskSegment of timeline.maskSegments) {
maskSegment.start += diff(maskSegment.start);
maskSegment.end += diff(maskSegment.end);
@@ -784,8 +956,6 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
keyboardSegment.start += diff(keyboardSegment.start);
keyboardSegment.end += diff(keyboardSegment.end);
}
-
- segment.timescale = timescale;
}),
);
},
@@ -961,10 +1131,12 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
);
const totalDuration = () =>
- project.timeline?.segments.reduce(
- (acc, s) => acc + (s.end - s.start) / s.timescale,
- 0,
- ) ?? props.editorInstance.recordingDuration;
+ project.timeline
+ ? clipTimelineDuration(
+ project.timeline.segments,
+ project.timeline.transitions ?? [],
+ )
+ : props.editorInstance.recordingDuration;
type State = {
zoom: number;
@@ -1026,6 +1198,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
| null
| { type: "zoom"; indices: number[] }
| { type: "clip"; indices: number[] }
+ | { type: "transition"; index: number }
| { type: "scene"; indices: number[] }
| { type: "mask"; indices: number[] }
| { type: "caption"; indices: number[] }
@@ -1179,6 +1352,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
time,
timeline.segments,
captionRecordingSegments,
+ timeline.transitions ?? [],
);
const inverted = segments.flatMap((segment) => {
const start = toSource(segment.start);
@@ -1222,7 +1396,13 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
`${s.start}|${s.end}|${s.timescale}|${s.recordingSegment ?? 0}`,
)
.join(",");
- return `${captionsSig}@@${timelineSig}`;
+ const transitionSig = (timeline.transitions ?? [])
+ .map(
+ (transition) =>
+ `${transition.segmentIndex}|${transition.type}|${transition.duration}`,
+ )
+ .join(",");
+ return `${captionsSig}@@${timelineSig}@@${transitionSig}`;
},
() => {
const timeline = project.timeline;
@@ -1233,6 +1413,7 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
timeline.segments,
captionRecordingSegments,
timeline.captionSegments ?? [],
+ timeline.transitions ?? [],
);
setProject(
"timeline",
diff --git a/apps/desktop/src/routes/editor/timeline-utils.ts b/apps/desktop/src/routes/editor/timeline-utils.ts
index b1c1ecd8b..95ec540d8 100644
--- a/apps/desktop/src/routes/editor/timeline-utils.ts
+++ b/apps/desktop/src/routes/editor/timeline-utils.ts
@@ -34,25 +34,25 @@ export function rippleDeleteFromTrack(
segments: Array<{ start: number; end: number }>,
cutStart: number,
cutEnd: number,
+ shiftDuration = cutEnd - cutStart,
) {
- const cutDuration = cutEnd - cutStart;
for (let i = segments.length - 1; i >= 0; i--) {
const seg = segments[i];
if (seg.end <= cutStart) {
continue;
}
if (seg.start >= cutEnd) {
- seg.start -= cutDuration;
- seg.end -= cutDuration;
+ seg.start -= shiftDuration;
+ seg.end -= shiftDuration;
} else if (seg.start >= cutStart && seg.end <= cutEnd) {
segments.splice(i, 1);
} else if (seg.start < cutStart && seg.end > cutEnd) {
- seg.end -= cutDuration;
+ seg.end -= shiftDuration;
} else if (seg.start < cutStart) {
seg.end = cutStart;
} else {
seg.start = cutStart;
- seg.end -= cutDuration;
+ seg.end = Math.max(seg.start, seg.end - shiftDuration);
}
}
}
@@ -63,34 +63,36 @@ export function cutClipSegmentsForRange(
start: number;
end: number;
}>,
+ transitions: ClipTransition[],
cutStart: number,
cutEnd: number,
+ requestedSegmentIndex?: number,
) {
- let editedOffset = 0;
+ const editedOffsets = clipTimelineOffsets(segments, transitions);
let startSegIdx = -1;
let startRelative = 0;
let endSegIdx = -1;
let endRelative = 0;
for (let i = 0; i < segments.length; i++) {
+ if (requestedSegmentIndex !== undefined && i !== requestedSegmentIndex)
+ continue;
const seg = segments[i];
const duration = (seg.end - seg.start) / seg.timescale;
- const segEditedStart = editedOffset;
- const segEditedEnd = editedOffset + duration;
+ const segEditedStart = editedOffsets[i];
+ const segEditedEnd = segEditedStart + duration;
- if (startSegIdx === -1 && cutStart < segEditedEnd) {
+ if (cutStart >= segEditedStart && cutStart < segEditedEnd) {
startSegIdx = i;
startRelative = (cutStart - segEditedStart) * seg.timescale;
}
- if (cutEnd <= segEditedEnd) {
+ if (cutEnd > segEditedStart && cutEnd <= segEditedEnd) {
endSegIdx = i;
endRelative = (cutEnd - segEditedStart) * seg.timescale;
- break;
}
- editedOffset += duration;
}
- if (startSegIdx === -1 || endSegIdx === -1) return;
+ if (startSegIdx === -1 || endSegIdx === -1) return transitions;
if (startSegIdx === endSegIdx) {
const seg = segments[startSegIdx];
@@ -106,6 +108,13 @@ export function cutClipSegmentsForRange(
}
segments.splice(startSegIdx, 1, ...newSegs);
+ if (newSegs.length === 2) {
+ return transitionsAfterClipSplit(transitions, startSegIdx);
+ }
+ if (newSegs.length === 0) {
+ return transitionsAfterClipDelete(transitions, startSegIdx);
+ }
+ return transitions;
} else {
const firstSeg = segments[startSegIdx];
const lastSeg = segments[endSegIdx];
@@ -118,36 +127,137 @@ export function cutClipSegmentsForRange(
for (let i = startSegIdx + 1; i < endSegIdx; i++) toRemove.push(i);
if (lastSeg.end <= lastSeg.start + 0.001) toRemove.push(endSegIdx);
+ let nextTransitions = transitions;
for (const idx of toRemove.sort((a, b) => b - a)) {
+ nextTransitions = transitionsAfterClipDelete(nextTransitions, idx);
segments.splice(idx, 1);
}
+ return nextTransitions;
}
}
export function rippleDeleteAllTracks(
timeline: {
segments: Array<{ timescale: number; start: number; end: number }>;
+ transitions?: ClipTransition[] | null;
zoomSegments?: Array<{ start: number; end: number }> | null;
sceneSegments?: Array<{ start: number; end: number }> | null;
maskSegments?: Array<{ start: number; end: number }> | null;
textSegments?: Array<{ start: number; end: number }> | null;
captionSegments?: Array<{ start: number; end: number }> | null;
keyboardSegments?: Array<{ start: number; end: number }> | null;
+ audioSegments?: Array<{ start: number; end: number }> | null;
},
cutStart: number,
cutEnd: number,
+ requestedSegmentIndex?: number,
) {
- cutClipSegmentsForRange(timeline.segments, cutStart, cutEnd);
+ const durationBefore = clipTimelineDuration(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ timeline.transitions = cutClipSegmentsForRange(
+ timeline.segments,
+ timeline.transitions ?? [],
+ cutStart,
+ cutEnd,
+ requestedSegmentIndex,
+ );
+ const shiftDuration = Math.max(
+ 0,
+ durationBefore -
+ clipTimelineDuration(timeline.segments, timeline.transitions),
+ );
if (timeline.zoomSegments)
- rippleDeleteFromTrack(timeline.zoomSegments, cutStart, cutEnd);
+ rippleDeleteFromTrack(
+ timeline.zoomSegments,
+ cutStart,
+ cutEnd,
+ shiftDuration,
+ );
if (timeline.sceneSegments)
- rippleDeleteFromTrack(timeline.sceneSegments, cutStart, cutEnd);
+ rippleDeleteFromTrack(
+ timeline.sceneSegments,
+ cutStart,
+ cutEnd,
+ shiftDuration,
+ );
if (timeline.maskSegments)
- rippleDeleteFromTrack(timeline.maskSegments, cutStart, cutEnd);
+ rippleDeleteFromTrack(
+ timeline.maskSegments,
+ cutStart,
+ cutEnd,
+ shiftDuration,
+ );
if (timeline.textSegments)
- rippleDeleteFromTrack(timeline.textSegments, cutStart, cutEnd);
+ rippleDeleteFromTrack(
+ timeline.textSegments,
+ cutStart,
+ cutEnd,
+ shiftDuration,
+ );
if (timeline.captionSegments)
- rippleDeleteFromTrack(timeline.captionSegments, cutStart, cutEnd);
+ rippleDeleteFromTrack(
+ timeline.captionSegments,
+ cutStart,
+ cutEnd,
+ shiftDuration,
+ );
if (timeline.keyboardSegments)
- rippleDeleteFromTrack(timeline.keyboardSegments, cutStart, cutEnd);
+ rippleDeleteFromTrack(
+ timeline.keyboardSegments,
+ cutStart,
+ cutEnd,
+ shiftDuration,
+ );
+ if (timeline.audioSegments)
+ rippleDeleteFromTrack(
+ timeline.audioSegments,
+ cutStart,
+ cutEnd,
+ shiftDuration,
+ );
}
+
+if (import.meta.vitest) {
+ const { expect, it } = import.meta.vitest;
+
+ it("cuts the requested overlap source without discarding the adjacent clip", () => {
+ const segments = [
+ { start: 0, end: 4, timescale: 1 },
+ { start: 0, end: 4, timescale: 1 },
+ { start: 0, end: 4, timescale: 1 },
+ ];
+ const transitions: ClipTransition[] = [
+ { segmentIndex: 1, type: "cross-fade", duration: 1 },
+ { segmentIndex: 2, type: "cross-fade", duration: 1 },
+ ];
+
+ const nextTransitions = cutClipSegmentsForRange(
+ segments,
+ transitions,
+ 3.2,
+ 3.4,
+ 0,
+ );
+
+ expect(segments).toEqual([
+ { start: 0, end: 3.2, timescale: 1 },
+ { start: 3.4, end: 4, timescale: 1 },
+ { start: 0, end: 4, timescale: 1 },
+ { start: 0, end: 4, timescale: 1 },
+ ]);
+ expect(nextTransitions).toEqual([
+ { segmentIndex: 2, type: "cross-fade", duration: 1 },
+ { segmentIndex: 3, type: "cross-fade", duration: 1 },
+ ]);
+ });
+}
+
+import {
+ type ClipTransition,
+ clipTimelineDuration,
+ clipTimelineOffsets,
+ transitionsAfterClipDelete,
+ transitionsAfterClipSplit,
+} from "./clip-transitions";
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index dd1ac221d..323ef5580 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -691,6 +691,8 @@ export type ClipConfiguration = { index: number; offsets: ClipOffsets;
*/
offsetsAutoCalculated?: boolean }
export type ClipOffsets = { camera?: number; mic?: number; system_audio?: number }
+export type ClipTransition = { segmentIndex: number; type: ClipTransitionType; duration: number }
+export type ClipTransitionType = "cross-fade" | "fade-through-black"
export type ClipboardSource = "raw" | "rendered"
export type CommercialLicense = { licenseKey: string; expiryDate: number | null; refresh: number; activatedOn: number }
export type Condition = { type: "captureTargetIs"; target: CaptureTargetKind } | { type: "recordingModeIs"; mode: AutomationRecordingMode } | { type: "durationAtLeast"; secs: number } | { type: "durationAtMost"; secs: number } | { type: "windowTitleContains"; pattern: string } | { type: "organizationIs"; id: string }
@@ -915,7 +917,7 @@ export type StudioRecordingStatus = { status: "InProgress" } | { status: "NeedsR
export type SystemDiagnostics = { macosVersion: MacOSVersionInfo | null; availableEncoders: string[]; screenCaptureSupported: boolean; metalSupported: boolean; gpuName: string | null }
export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }
export type TextSegment = { start: number; end: number; track?: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string; fadeDuration?: number }
-export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[]; captionSegments?: CaptionTrackSegment[]; keyboardSegments?: KeyboardTrackSegment[]; audioSegments?: AudioTrackSegment[] }
+export type TimelineConfiguration = { segments: TimelineSegment[]; transitions: ClipTransition[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[]; captionSegments?: CaptionTrackSegment[]; keyboardSegments?: KeyboardTrackSegment[]; audioSegments?: AudioTrackSegment[] }
export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number; name?: string | null }
export type TranscriptionEngine = "Whisper" | "Parakeet"
export type Trigger = "screenshotTaken" | "studioRecordingFinished" | "instantRecordingFinished" | "recordingStarted" | "uploadCompleted" | "videoImported" | "recordingDeleted"
diff --git a/crates/editor/examples/editor-playback-benchmark.rs b/crates/editor/examples/editor-playback-benchmark.rs
index 609b762e5..67bb6454e 100644
--- a/crates/editor/examples/editor-playback-benchmark.rs
+++ b/crates/editor/examples/editor-playback-benchmark.rs
@@ -378,6 +378,7 @@ async fn load_recording(
if !timeline_segments.is_empty() {
project.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/crates/editor/examples/playback-pipeline-benchmark.rs b/crates/editor/examples/playback-pipeline-benchmark.rs
index 00d9c16f7..d8a1d67ab 100644
--- a/crates/editor/examples/playback-pipeline-benchmark.rs
+++ b/crates/editor/examples/playback-pipeline-benchmark.rs
@@ -304,6 +304,7 @@ async fn load_recording(
if !timeline_segments.is_empty() {
project.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rs
index 82e9a41d5..4a9066f60 100644
--- a/crates/editor/src/audio.rs
+++ b/crates/editor/src/audio.rs
@@ -3,7 +3,10 @@ use cap_audio::{
};
use cap_media::MediaError;
use cap_media_info::AudioInfo;
-use cap_project::{AudioConfiguration, ClipOffsets, ProjectConfiguration, TimelineConfiguration};
+use cap_project::{
+ AudioConfiguration, ClipOffsets, ClipTransitionType, ProjectConfiguration,
+ TimelineConfiguration, TimelineFrameMapping, TimelineSource,
+};
use ffmpeg::{
ChannelLayout, Dictionary, format as avformat, frame::Audio as FFAudio, software::resampling,
};
@@ -32,6 +35,8 @@ pub struct AudioRenderer {
// this * channel count = cursor
elapsed_samples: usize,
music: MusicTracks,
+ transition_outgoing: Vec<f32>,
+ transition_incoming: Vec<f32>,
}
#[derive(Clone, Copy, Debug)]
@@ -120,6 +125,8 @@ impl AudioRenderer {
},
elapsed_samples: 0,
music: MusicTracks::new(),
+ transition_outgoing: Vec::new(),
+ transition_incoming: Vec::new(),
}
}
@@ -197,6 +204,10 @@ impl AudioRenderer {
project: &ProjectConfiguration,
timeline: &TimelineConfiguration,
) -> Option<(usize, Vec<f32>)> {
+ if !timeline.transitions.is_empty() {
+ return self.render_timeline_transition_frame_raw(samples, project, timeline);
+ }
+
if samples == 0 {
return None;
}
@@ -238,6 +249,110 @@ impl AudioRenderer {
}
}
+ fn render_timeline_transition_frame_raw(
+ &mut self,
+ samples: usize,
+ project: &ProjectConfiguration,
+ timeline: &TimelineConfiguration,
+ ) -> Option<(usize, Vec<f32>)> {
+ if samples == 0 {
+ return None;
+ }
+
+ let mut output = vec![0.0; samples * 2];
+ let mut written = 0usize;
+ 'render: while written < samples {
+ let mut mapping_time = self.elapsed_samples_to_playhead();
+ let (mapping, output_end_samples) = loop {
+ let Some(mapping) = timeline.get_frame_mapping(mapping_time) else {
+ break 'render;
+ };
+ let output_end = match mapping {
+ TimelineFrameMapping::Single { output_end, .. }
+ | TimelineFrameMapping::Transition { output_end, .. } => output_end,
+ };
+ let output_end_samples = self.playhead_to_samples(output_end);
+ if output_end_samples > self.elapsed_samples {
+ break (mapping, output_end_samples);
+ }
+ if output_end <= mapping_time {
+ break 'render;
+ }
+ mapping_time = output_end;
+ };
+ let chunk_samples = output_end_samples
+ .saturating_sub(self.elapsed_samples)
+ .min(samples - written);
+
+ match mapping {
+ TimelineFrameMapping::Single { source, .. } => {
+ let source_samples = self.playhead_to_samples(source.source_time);
+ self.render_segment_chunk(
+ project,
+ source,
+ chunk_samples,
+ written * 2,
+ &mut output,
+ );
+ self.cursor = source_cursor(source, source_samples + chunk_samples);
+ }
+ TimelineFrameMapping::Transition {
+ outgoing,
+ incoming,
+ kind,
+ progress,
+ duration,
+ ..
+ } => {
+ let mut outgoing_buffer = std::mem::take(&mut self.transition_outgoing);
+ let mut incoming_buffer = std::mem::take(&mut self.transition_incoming);
+ outgoing_buffer.resize(chunk_samples * 2, 0.0);
+ incoming_buffer.resize(chunk_samples * 2, 0.0);
+ outgoing_buffer.fill(0.0);
+ incoming_buffer.fill(0.0);
+ self.render_segment_chunk(
+ project,
+ outgoing,
+ chunk_samples,
+ 0,
+ &mut outgoing_buffer,
+ );
+ self.render_segment_chunk(
+ project,
+ incoming,
+ chunk_samples,
+ 0,
+ &mut incoming_buffer,
+ );
+ mix_transition_audio(
+ &outgoing_buffer,
+ &incoming_buffer,
+ &mut output[written * 2..(written + chunk_samples) * 2],
+ kind,
+ progress,
+ duration,
+ );
+ self.transition_outgoing = outgoing_buffer;
+ self.transition_incoming = incoming_buffer;
+ self.cursor = source_cursor(
+ incoming,
+ self.playhead_to_samples(incoming.source_time) + chunk_samples,
+ );
+ }
+ }
+
+ self.elapsed_samples += chunk_samples;
+ written += chunk_samples;
+ }
+
+ if written == 0 {
+ None
+ } else {
+ output.truncate(written * 2);
+ Some((written, output))
+ }
+ }
+
fn render_linear_frame_raw(
&mut self,
samples: usize,
@@ -301,7 +416,33 @@ impl AudioRenderer {
out_offset: usize,
out: &mut [f32],
) -> usize {
- let Some(segment) = self.data.get(self.cursor.clip_index as usize) else {
+ self.render_chunk_at_cursor(project, self.cursor, samples, out_offset, out)
+ }
+
+ fn render_segment_chunk(
+ &self,
+ project: &ProjectConfiguration,
+ source: TimelineSource<'_>,
+ samples: usize,
+ out_offset: usize,
+ out: &mut [f32],
+ ) -> usize {
+ if source.segment.timescale != 1.0 {
+ return 0;
+ }
+ let cursor = source_cursor(source, self.playhead_to_samples(source.source_time));
+ self.render_chunk_at_cursor(project, cursor, samples, out_offset, out)
+ }
+
+ fn render_chunk_at_cursor(
+ &self,
+ project: &ProjectConfiguration,
+ cursor: AudioRendererCursor,
+ samples: usize,
+ out_offset: usize,
+ out: &mut [f32],
+ ) -> usize {
+ let Some(segment) = self.data.get(cursor.clip_index as usize) else {
return 0;
};
let tracks = &segment.tracks;
@@ -313,7 +454,7 @@ impl AudioRenderer {
let offsets = project
.clips
.iter()
- .find(|c| c.index == self.cursor.clip_index)
+ .find(|c| c.index == cursor.clip_index)
.map(|c| c.offsets)
.unwrap_or_default();
@@ -328,11 +469,11 @@ impl AudioRenderer {
.max()
.unwrap_or(0);
- if self.cursor.samples >= max_samples {
+ if cursor.samples >= max_samples {
return 0;
}
- let samples = samples.min(max_samples - self.cursor.samples);
+ let samples = samples.min(max_samples - cursor.samples);
let track_datas = tracks
.iter()
@@ -349,7 +490,48 @@ impl AudioRenderer {
})
.collect::<Vec<_>>();
- cap_audio::render_audio(&track_datas, self.cursor.samples, samples, out_offset, out)
+ cap_audio::render_audio(&track_datas, cursor.samples, samples, out_offset, out)
+ }
+}
+
+fn source_cursor(source: TimelineSource<'_>, samples: usize) -> AudioRendererCursor {
+ AudioRendererCursor {
+ clip_index: source.segment.recording_clip,
+ timescale: source.segment.timescale,
+ samples,
+ }
+}
+
+fn mix_transition_audio(
+ outgoing: &[f32],
+ incoming: &[f32],
+ output: &mut [f32],
+ kind: ClipTransitionType,
+ progress: f64,
+ duration: f64,
+) {
+ let progress_per_sample = 1.0 / (duration * AudioData::SAMPLE_RATE as f64);
+ for (sample_index, ((outgoing_frame, incoming_frame), output_frame)) in outgoing
+ .chunks_exact(2)
+ .zip(incoming.chunks_exact(2))
+ .zip(output.chunks_exact_mut(2))
+ .enumerate()
+ {
+ let progress = (progress + sample_index as f64 * progress_per_sample).clamp(0.0, 1.0);
+ let (outgoing_gain, incoming_gain) = match kind {
+ ClipTransitionType::CrossFade => {
+ let angle = progress * std::f64::consts::FRAC_PI_2;
+ (angle.cos() as f32, angle.sin() as f32)
+ }
+ ClipTransitionType::FadeThroughBlack => (
+ (1.0 - progress * 2.0).max(0.0) as f32,
+ (progress * 2.0 - 1.0).max(0.0) as f32,
+ ),
+ };
+ output_frame[0] = (outgoing_frame[0] * outgoing_gain + incoming_frame[0] * incoming_gain)
+ .clamp(-1.0, 1.0);
+ output_frame[1] = (outgoing_frame[1] * outgoing_gain + incoming_frame[1] * incoming_gain)
+ .clamp(-1.0, 1.0);
}
}
@@ -1172,7 +1354,8 @@ fn spawn_progressive_render(
mod tests {
use super::*;
use cap_project::{
- ClipConfiguration, ProjectConfiguration, TimelineConfiguration, TimelineSegment,
+ ClipConfiguration, ClipTransition, ProjectConfiguration, TimelineConfiguration,
+ TimelineSegment,
};
use std::{path::Path, sync::Arc};
use tempfile::TempDir;
@@ -1302,6 +1485,7 @@ mod tests {
name: None,
},
],
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
@@ -1430,6 +1614,7 @@ mod tests {
let project = ProjectConfiguration {
timeline: Some(TimelineConfiguration {
segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
@@ -1505,6 +1690,105 @@ mod tests {
value as f32 / 32768.0
}
+ fn transition_fixture(
+ kind: ClipTransitionType,
+ ) -> (TempDir, AudioRenderer, ProjectConfiguration) {
+ let _ = ffmpeg::init();
+ let dir = TempDir::new().unwrap();
+ let outgoing_path = dir.path().join("outgoing.wav");
+ let incoming_path = dir.path().join("incoming.wav");
+ write_step_wav(&outgoing_path, &[8000]);
+ write_step_wav(&incoming_path, &[16000]);
+ let audio_segments = vec![
+ AudioSegment {
+ tracks: vec![AudioSegmentTrack::new(
+ Arc::new(AudioData::from_file(&outgoing_path).unwrap()),
+ gain,
+ stereo,
+ no_offset,
+ )],
+ },
+ AudioSegment {
+ tracks: vec![AudioSegmentTrack::new(
+ Arc::new(AudioData::from_file(&incoming_path).unwrap()),
+ gain,
+ stereo,
+ no_offset,
+ )],
+ },
+ ];
+ let project = ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: vec![segment(0, 0.0, 1.0, 1.0), segment(1, 0.0, 1.0, 1.0)],
+ transitions: vec![ClipTransition {
+ segment_index: 1,
+ kind,
+ duration: 0.5,
+ }],
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ }),
+ clips: vec![
+ ClipConfiguration {
+ index: 0,
+ ..Default::default()
+ },
+ ClipConfiguration {
+ index: 1,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ };
+
+ (dir, AudioRenderer::new(audio_segments), project)
+ }
+
+ fn left_at_time(stream: &[f32], time: f64) -> f32 {
+ let sample = (time * AudioData::SAMPLE_RATE as f64).round() as usize;
+ stream[sample * 2]
+ }
+
+ #[test]
+ fn crossfade_audio_uses_equal_power_weights() {
+ let (_dir, mut renderer, project) = transition_fixture(ClipTransitionType::CrossFade);
+ let stream = render_export_audio(&mut renderer, &project, 30, 45);
+ let midpoint = left_at_time(&stream, 0.75);
+ let expected_midpoint =
+ (expected(8000) + expected(16000)) * std::f32::consts::FRAC_1_SQRT_2;
+
+ assert!((midpoint - expected_midpoint).abs() < 0.01);
+ }
+
+ #[test]
+ fn fade_through_black_audio_reaches_silence_at_midpoint() {
+ let (_dir, mut renderer, project) =
+ transition_fixture(ClipTransitionType::FadeThroughBlack);
+ let stream = render_export_audio(&mut renderer, &project, 30, 45);
+
+ assert!(left_at_time(&stream, 0.75).abs() < 0.0001);
+ }
+
+ #[test]
+ fn transition_audio_advances_past_fractional_sample_boundaries() {
+ let (_dir, mut renderer, mut project) = transition_fixture(ClipTransitionType::CrossFade);
+ let timeline = project.timeline.as_mut().unwrap();
+ timeline.segments[0].end = 1.100_01;
+ timeline.segments[1].end = 1.100_01;
+ let expected = (timeline.duration() * AudioData::SAMPLE_RATE as f64).round() as usize;
+
+ renderer.set_playhead(0.0, &project);
+ let (written, samples) = renderer.render_frame_raw(expected, &project).unwrap();
+
+ assert_eq!(written, expected);
+ assert_eq!(samples.len(), expected * 2);
+ }
+
#[test]
fn export_audio_virtual_negative_timing_offset_inserts_leading_silence() {
let dir = TempDir::new().unwrap();
@@ -1520,6 +1804,7 @@ mod tests {
let project = ProjectConfiguration {
timeline: Some(TimelineConfiguration {
segments: vec![segment(0, 0.0, 3.0, 1.0)],
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
@@ -1558,6 +1843,7 @@ mod tests {
let project = ProjectConfiguration {
timeline: Some(TimelineConfiguration {
segments: vec![segment(0, 0.0, 3.0, 1.0)],
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
@@ -1697,6 +1983,7 @@ mod tests {
ProjectConfiguration {
timeline: Some(TimelineConfiguration {
segments: vec![segment(0, 0.0, 3.0, 1.0)],
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index d9b0e0c07..b32113413 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -1,10 +1,10 @@
use std::sync::Arc;
use std::time::Instant;
-use cap_project::{CursorEvents, ProjectConfiguration};
+use cap_project::{ClipTransitionType, CursorEvents, ProjectConfiguration};
use cap_rendering::{
- DecodedSegmentFrames, FrameLayout, FrameRenderer, Nv12RenderedFrame, ProjectUniforms,
- RenderVideoConstants, RenderedFrame, RendererLayers,
+ DecodedSegmentFrames, FrameLayout, FrameRenderStageTimings, FrameRenderer, Nv12RenderedFrame,
+ ProjectUniforms, RenderVideoConstants, RenderedFrame, RendererLayers, TransitionRenderInput,
};
use tokio::sync::{mpsc, oneshot};
@@ -23,11 +23,25 @@ pub enum RendererMessage {
cursor: Arc<CursorEvents>,
queued_at: Instant,
},
+ RenderTransition {
+ outgoing: RendererTransitionInput,
+ incoming: RendererTransitionInput,
+ kind: ClipTransitionType,
+ progress: f32,
+ finished: oneshot::Sender<bool>,
+ queued_at: Instant,
+ },
Stop {
finished: oneshot::Sender<()>,
},
}
+pub struct RendererTransitionInput {
+ pub segment_frames: DecodedSegmentFrames,
+ pub uniforms: ProjectUniforms,
+ pub cursor: Arc<CursorEvents>,
+}
+
pub enum EditorFrameOutput {
Rgba(RenderedFrame),
Nv12(Nv12RenderedFrame),
@@ -144,13 +158,30 @@ impl Renderer {
};
struct PendingFrame {
- segment_frames: DecodedSegmentFrames,
- uniforms: ProjectUniforms,
+ input: PendingRenderInput,
finished: oneshot::Sender<bool>,
- cursor: Arc<CursorEvents>,
queued_at: Instant,
}
+ enum PendingRenderInput {
+ Single(RendererTransitionInput),
+ Transition {
+ outgoing: RendererTransitionInput,
+ incoming: Box<RendererTransitionInput>,
+ kind: ClipTransitionType,
+ progress: f32,
+ },
+ }
+
+ impl PendingRenderInput {
+ fn uniforms(&self) -> &ProjectUniforms {
+ match self {
+ Self::Single(input) => &input.uniforms,
+ Self::Transition { incoming, .. } => &incoming.uniforms,
+ }
+ }
+ }
+
let mut pending_frame: Option<PendingFrame> = None;
loop {
@@ -169,10 +200,29 @@ impl Renderer {
cursor,
queued_at,
}) => Some(PendingFrame {
- segment_frames,
- uniforms,
+ input: PendingRenderInput::Single(RendererTransitionInput {
+ segment_frames,
+ uniforms,
+ cursor,
+ }),
+ finished,
+ queued_at,
+ }),
+ Some(RendererMessage::RenderTransition {
+ outgoing,
+ incoming,
+ kind,
+ progress,
+ finished,
+ queued_at,
+ }) => Some(PendingFrame {
+ input: PendingRenderInput::Transition {
+ outgoing,
+ incoming: Box::new(incoming),
+ kind,
+ progress,
+ },
finished,
- cursor,
queued_at,
}),
Some(RendererMessage::Stop { finished }) => {
@@ -201,7 +251,7 @@ impl Renderer {
cursor,
queued_at,
} => {
- let dropped_frame_number = current.uniforms.frame_number;
+ let dropped_frame_number = current.input.uniforms().frame_number;
let replacement_frame_number = uniforms.frame_number;
let _ = current.finished.send(false);
if let Some(telemetry) = &telemetry {
@@ -211,10 +261,41 @@ impl Renderer {
});
}
current = PendingFrame {
- segment_frames,
- uniforms,
+ input: PendingRenderInput::Single(RendererTransitionInput {
+ segment_frames,
+ uniforms,
+ cursor,
+ }),
+ finished,
+ queued_at,
+ };
+ drained_count += 1;
+ }
+ RendererMessage::RenderTransition {
+ outgoing,
+ incoming,
+ kind,
+ progress,
+ finished,
+ queued_at,
+ } => {
+ let dropped_frame_number = current.input.uniforms().frame_number;
+ let replacement_frame_number = incoming.uniforms.frame_number;
+ let _ = current.finished.send(false);
+ if let Some(telemetry) = &telemetry {
+ telemetry.emit(PlaybackTelemetryEvent::RendererDropped {
+ frame_number: dropped_frame_number,
+ replacement_frame_number,
+ });
+ }
+ current = PendingFrame {
+ input: PendingRenderInput::Transition {
+ outgoing,
+ incoming: Box::new(incoming),
+ kind,
+ progress,
+ },
finished,
- cursor,
queued_at,
};
drained_count += 1;
@@ -243,18 +324,47 @@ impl Renderer {
};
let render_start = Instant::now();
- let input_frame_number = current.uniforms.frame_number;
- let frame_layout = current.uniforms.frame_layout();
- match frame_renderer
- .render_immediate_with_timings(
- current.segment_frames,
- current.uniforms,
- &current.cursor,
- true,
- &mut layers,
- )
- .await
- {
+ let input_frame_number = current.input.uniforms().frame_number;
+ let frame_layout = current.input.uniforms().frame_layout();
+ let render_result = match current.input {
+ PendingRenderInput::Single(input) => {
+ frame_renderer
+ .render_immediate_with_timings(
+ input.segment_frames,
+ input.uniforms,
+ &input.cursor,
+ true,
+ &mut layers,
+ )
+ .await
+ }
+ PendingRenderInput::Transition {
+ outgoing,
+ incoming,
+ kind,
+ progress,
+ } => frame_renderer
+ .render_transition_immediate(
+ TransitionRenderInput {
+ segment_frames: outgoing.segment_frames,
+ uniforms: outgoing.uniforms,
+ cursor: &outgoing.cursor,
+ render_display: true,
+ },
+ TransitionRenderInput {
+ segment_frames: incoming.segment_frames,
+ uniforms: incoming.uniforms,
+ cursor: &incoming.cursor,
+ render_display: true,
+ },
+ kind,
+ progress,
+ &mut layers,
+ )
+ .await
+ .map(|frame| (frame, FrameRenderStageTimings::default())),
+ };
+ match render_result {
Ok((frame, render_stage_timings)) => {
let render_duration = render_start.elapsed();
let frame_number = frame.frame_number;
@@ -335,6 +445,32 @@ impl RendererHandle {
}
}
+ pub fn render_transition_frame(
+ &self,
+ outgoing: RendererTransitionInput,
+ incoming: RendererTransitionInput,
+ kind: ClipTransitionType,
+ progress: f32,
+ ) {
+ let (finished_tx, _finished_rx) = oneshot::channel();
+ let frame_number = incoming.uniforms.frame_number;
+ if self
+ .tx
+ .try_send(RendererMessage::RenderTransition {
+ outgoing,
+ incoming,
+ kind,
+ progress,
+ finished: finished_tx,
+ queued_at: Instant::now(),
+ })
+ .is_err()
+ && let Some(telemetry) = &self.telemetry
+ {
+ telemetry.emit(PlaybackTelemetryEvent::RendererSendFailed { frame_number });
+ }
+ }
+
pub fn render_frame_blocking(
&self,
segment_frames: DecodedSegmentFrames,
@@ -382,6 +518,33 @@ impl RendererHandle {
finished_rx.await.unwrap_or(false)
}
+ pub async fn render_transition_frame_confirmed(
+ &self,
+ outgoing: RendererTransitionInput,
+ incoming: RendererTransitionInput,
+ kind: ClipTransitionType,
+ progress: f32,
+ ) -> bool {
+ let (finished_tx, finished_rx) = oneshot::channel();
+ let frame_number = incoming.uniforms.frame_number;
+ let message = RendererMessage::RenderTransition {
+ outgoing,
+ incoming,
+ kind,
+ progress,
+ finished: finished_tx,
+ queued_at: Instant::now(),
+ };
+ if self.tx.send(message).await.is_err() {
+ if let Some(telemetry) = &self.telemetry {
+ telemetry.emit(PlaybackTelemetryEvent::RendererSendFailed { frame_number });
+ }
+ return false;
+ }
+
+ finished_rx.await.unwrap_or(false)
+ }
+
pub fn render_frame_wait(
&self,
segment_frames: DecodedSegmentFrames,
@@ -407,6 +570,33 @@ impl RendererHandle {
finished_rx.blocking_recv().unwrap_or(false)
}
+ pub fn render_transition_frame_wait(
+ &self,
+ outgoing: RendererTransitionInput,
+ incoming: RendererTransitionInput,
+ kind: ClipTransitionType,
+ progress: f32,
+ ) -> bool {
+ let (finished_tx, finished_rx) = oneshot::channel();
+ let frame_number = incoming.uniforms.frame_number;
+ let message = RendererMessage::RenderTransition {
+ outgoing,
+ incoming,
+ kind,
+ progress,
+ finished: finished_tx,
+ queued_at: Instant::now(),
+ };
+ if self.tx.blocking_send(message).is_err() {
+ if let Some(telemetry) = &self.telemetry {
+ telemetry.emit(PlaybackTelemetryEvent::RendererSendFailed { frame_number });
+ }
+ return false;
+ }
+
+ finished_rx.blocking_recv().unwrap_or(false)
+ }
+
pub async fn stop(&self) {
let (tx, rx) = oneshot::channel();
if self
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 2ba08c018..2958b33ab 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -4,7 +4,7 @@ use cap_audio::AudioData;
use cap_project::StudioRecordingMeta;
use cap_project::{
CursorEvents, ProjectConfiguration, RecordingMeta, RecordingMetaInner, TimelineConfiguration,
- TimelineSegment, XY,
+ TimelineFrameMapping, TimelineSegment, XY,
};
use cap_rendering::{
ProjectRecordingsMeta, ProjectUniforms, RecordingSegmentDecoders, RenderVideoConstants,
@@ -211,6 +211,7 @@ impl EditorInstance {
if !timeline_segments.is_empty() {
project.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
@@ -522,10 +523,23 @@ impl EditorInstance {
}
let project = self.project_config.1.borrow().clone();
+ let frame_time = frame_number as f64 / fps as f64;
+ let transition_mapping = project.timeline.as_ref().and_then(|timeline| {
+ if timeline.transitions.is_empty() {
+ return None;
+ }
+ match timeline.get_frame_mapping(frame_time) {
+ Some(TimelineFrameMapping::Transition {
+ outgoing,
+ kind,
+ progress,
+ ..
+ }) => Some((outgoing, kind, progress)),
+ _ => None,
+ }
+ });
- let Some((segment_time, segment)) =
- project.get_segment_time(frame_number as f64 / fps as f64)
- else {
+ let Some((segment_time, segment)) = project.get_segment_time(frame_time) else {
warn!(
"Preview renderer: no segment found for frame {}",
frame_number
@@ -617,15 +631,81 @@ impl EditorInstance {
// timeline playback and export use (the old focus
// interpolator was never precomputed here and fell
// back to a divergent direct interpolation).
- let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ let mut zoom_timeline =
+ ZoomTransformTimeline::from_project_for_clip(
&project,
&segment_medias.cursor,
total_duration,
self.render_constants.options.screen_size,
+ segment.recording_clip,
);
zoom_timeline
.ensure_precomputed_until((frame_number as f32 + 1.0) / fps as f32);
+ let outgoing_transition = if let Some((outgoing, kind, progress)) =
+ transition_mapping
+ {
+ let outgoing_media =
+ &self.segment_medias[outgoing.segment.recording_clip as usize];
+ let outgoing_offsets = project
+ .clips
+ .iter()
+ .find(|clip| clip.index == outgoing.segment.recording_clip)
+ .map(|clip| clip.offsets)
+ .unwrap_or_default();
+ let outgoing_frames = tokio::select! {
+ biased;
+ _ = preview_rx.changed() => {
+ continue;
+ }
+ frames = outgoing_media.decoders.get_frames_initial(
+ outgoing.source_time as f32,
+ !project.camera.hide,
+ true,
+ outgoing_offsets,
+ ) => frames,
+ };
+ if let Some(outgoing_frames) = outgoing_frames {
+ let mut outgoing_zoom =
+ ZoomTransformTimeline::from_project_for_outgoing_clip(
+ &project,
+ &outgoing_media.cursor,
+ total_duration,
+ self.render_constants.options.screen_size,
+ outgoing.segment.recording_clip,
+ );
+ outgoing_zoom.ensure_precomputed_until(
+ (frame_number as f32 + 1.0) / fps as f32,
+ );
+ let outgoing_uniforms = ProjectUniforms::new(
+ &self.render_constants,
+ &project,
+ frame_number,
+ fps,
+ resolution_base,
+ &outgoing_media.cursor,
+ &outgoing_frames,
+ total_duration,
+ &outgoing_zoom,
+ );
+ Some((
+ outgoing_frames,
+ outgoing_uniforms,
+ outgoing_media.cursor.clone(),
+ kind,
+ progress as f32,
+ ))
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ if preview_rx.has_changed().unwrap_or(false) {
+ continue;
+ }
+
let mut next_segment_frames = segment_frames_opt;
let mut rendered = false;
@@ -646,15 +726,40 @@ impl EditorInstance {
&zoom_timeline,
);
- if self
- .renderer
- .render_frame_confirmed(
- segment_frames,
- uniforms,
- segment_medias.cursor.clone(),
- )
- .await
+ let render_confirmed = if let Some((
+ outgoing_frames,
+ outgoing_uniforms,
+ outgoing_cursor,
+ kind,
+ progress,
+ )) = &outgoing_transition
{
+ self.renderer
+ .render_transition_frame_confirmed(
+ editor::RendererTransitionInput {
+ segment_frames: outgoing_frames.clone(),
+ uniforms: outgoing_uniforms.clone(),
+ cursor: outgoing_cursor.clone(),
+ },
+ editor::RendererTransitionInput {
+ segment_frames,
+ uniforms,
+ cursor: segment_medias.cursor.clone(),
+ },
+ *kind,
+ *progress,
+ )
+ .await
+ } else {
+ self.renderer
+ .render_frame_confirmed(
+ segment_frames,
+ uniforms,
+ segment_medias.cursor.clone(),
+ )
+ .await
+ };
+ if render_confirmed {
rendered = true;
break;
}
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index e3b77f9ff..26053d013 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -1,7 +1,10 @@
-use cap_project::{ProjectConfiguration, XY};
+use cap_project::{
+ ClipOffsets, ClipTransitionType, ProjectConfiguration, TimelineFrameMapping, XY,
+};
use cap_rendering::{
- DecodedSegmentFrames, PrecomputedCursorTimeline, ProjectUniforms, RenderVideoConstants,
- ZoomTransformTimeline, spring_mass_damper::SpringMassDamperSimulationConfig,
+ DecodedSegmentFrames, PrecomputedCursorTimeline, ProjectUniforms, RecordingSegmentDecoders,
+ RenderVideoConstants, ZoomTransformTimeline,
+ spring_mass_damper::SpringMassDamperSimulationConfig,
};
use futures::stream::{FuturesUnordered, StreamExt};
use lru::LruCache;
@@ -117,10 +120,38 @@ struct PrefetchedFrame {
frame_number: u32,
segment_frames: DecodedSegmentFrames,
segment_index: u32,
+ transition: Option<PrefetchedTransition>,
+}
+
+struct PrefetchedTransition {
+ segment_frames: DecodedSegmentFrames,
+ segment_index: u32,
+ kind: ClipTransitionType,
+ progress: f32,
}
+impl PrefetchedFrame {
+ fn into_cached(self) -> CachedFrame {
+ (
+ Arc::new(self.segment_frames),
+ self.segment_index,
+ self.transition.map(|transition| {
+ (
+ Arc::new(transition.segment_frames),
+ transition.segment_index,
+ transition.kind,
+ transition.progress,
+ )
+ }),
+ )
+ }
+}
+
+type CachedTransition = (Arc<DecodedSegmentFrames>, u32, ClipTransitionType, f32);
+type CachedFrame = (Arc<DecodedSegmentFrames>, u32, Option<CachedTransition>);
+
struct FrameCache {
- cache: LruCache<u32, (Arc<DecodedSegmentFrames>, u32)>,
+ cache: LruCache<u32, CachedFrame>,
}
impl FrameCache {
@@ -130,10 +161,25 @@ impl FrameCache {
}
}
- fn get(&mut self, frame_number: u32) -> Option<(Arc<DecodedSegmentFrames>, u32)> {
+ fn get(&mut self, frame_number: u32) -> Option<CachedFrame> {
self.cache
.get(&frame_number)
- .map(|(frames, idx)| (Arc::clone(frames), *idx))
+ .map(|(frames, segment_index, transition)| {
+ (
+ Arc::clone(frames),
+ *segment_index,
+ transition.as_ref().map(
+ |(transition_frames, transition_index, kind, progress)| {
+ (
+ Arc::clone(transition_frames),
+ *transition_index,
+ *kind,
+ *progress,
+ )
+ },
+ ),
+ )
+ })
}
fn insert(
@@ -141,9 +187,10 @@ impl FrameCache {
frame_number: u32,
segment_frames: Arc<DecodedSegmentFrames>,
segment_index: u32,
+ transition: Option<CachedTransition>,
) {
self.cache
- .put(frame_number, (segment_frames, segment_index));
+ .put(frame_number, (segment_frames, segment_index, transition));
}
fn evict_far_from(&mut self, current_frame: u32, max_distance: u32) {
@@ -165,6 +212,126 @@ impl FrameCache {
}
}
+struct TransitionDecodeRequest {
+ decoders: RecordingSegmentDecoders,
+ segment_time: f64,
+ segment_index: u32,
+ offsets: ClipOffsets,
+ kind: ClipTransitionType,
+ progress: f32,
+}
+
+struct PrefetchDecodeRequest {
+ frame_number: u32,
+ decoders: RecordingSegmentDecoders,
+ segment_time: f64,
+ segment_index: u32,
+ offsets: ClipOffsets,
+ hide_camera: bool,
+ is_initial: bool,
+ transition: Option<TransitionDecodeRequest>,
+}
+
+type PrefetchDecodeResult = (
+ u32,
+ u32,
+ Option<DecodedSegmentFrames>,
+ Option<PrefetchedTransition>,
+);
+
+async fn decode_prefetched_frame(request: PrefetchDecodeRequest) -> PrefetchDecodeResult {
+ let PrefetchDecodeRequest {
+ frame_number,
+ decoders,
+ segment_time,
+ segment_index,
+ offsets,
+ hide_camera,
+ is_initial,
+ transition,
+ } = request;
+ let primary = async {
+ if is_initial {
+ decoders
+ .get_frames_initial(segment_time as f32, !hide_camera, true, offsets)
+ .await
+ } else {
+ decoders
+ .get_frames(segment_time as f32, !hide_camera, true, offsets)
+ .await
+ }
+ };
+ let transition = async {
+ let transition = transition?;
+ let segment_frames = if is_initial {
+ transition
+ .decoders
+ .get_frames_initial(
+ transition.segment_time as f32,
+ !hide_camera,
+ true,
+ transition.offsets,
+ )
+ .await
+ } else {
+ transition
+ .decoders
+ .get_frames(
+ transition.segment_time as f32,
+ !hide_camera,
+ true,
+ transition.offsets,
+ )
+ .await
+ }?;
+ Some(PrefetchedTransition {
+ segment_frames,
+ segment_index: transition.segment_index,
+ kind: transition.kind,
+ progress: transition.progress,
+ })
+ };
+ let (segment_frames, transition) = tokio::join!(primary, transition);
+
+ (frame_number, segment_index, segment_frames, transition)
+}
+
+fn transition_decode_request(
+ project: &ProjectConfiguration,
+ segment_medias: &[SegmentMedia],
+ frame_time: f64,
+) -> Option<TransitionDecodeRequest> {
+ let timeline = project.timeline.as_ref()?;
+ if timeline.transitions.is_empty() {
+ return None;
+ }
+ let TimelineFrameMapping::Transition {
+ outgoing,
+ kind,
+ progress,
+ ..
+ } = timeline.get_frame_mapping(frame_time)?
+ else {
+ return None;
+ };
+ let segment_media = segment_medias.get(outgoing.segment.recording_clip as usize)?;
+ let offsets = project
+ .clips
+ .iter()
+ .find(|clip| clip.index == outgoing.segment.recording_clip)
+ .map(|clip| clip.offsets)
+ .unwrap_or_default();
+
+ Some(TransitionDecodeRequest {
+ decoders: segment_media.decoders.clone(),
+ segment_time: outgoing.source_time,
+ segment_index: outgoing.segment.recording_clip,
+ offsets,
+ kind,
+ progress: progress as f32,
+ })
+}
+
impl Playback {
pub async fn start(
mut self,
@@ -226,12 +393,8 @@ impl Playback {
if segment_media_count == 0 {
warn!("Prefetch: No segment media available");
}
- type PrefetchFuture = std::pin::Pin<
- Box<
- dyn std::future::Future<Output = (u32, u32, Option<DecodedSegmentFrames>)>
- + Send,
- >,
- >;
+ type PrefetchFuture =
+ std::pin::Pin<Box<dyn std::future::Future<Output = PrefetchDecodeResult> + Send>>;
let mut next_prefetch_frame = *frame_request_rx.borrow();
let mut in_flight: FuturesUnordered<PrefetchFuture> = FuturesUnordered::new();
let mut frames_decoded: u32 = 0;
@@ -328,33 +491,26 @@ impl Playback {
let hide_camera = cached_project.camera.hide;
let segment_index = segment.recording_clip;
let is_initial = frames_decoded < 10;
+ let transition = transition_decode_request(
+ &cached_project,
+ &prefetch_segment_medias,
+ prefetch_time,
+ );
if let Ok(mut in_flight_guard) = prefetch_in_flight.write() {
in_flight_guard.insert(frame_num);
}
- in_flight.push(Box::pin(async move {
- let result = if is_initial {
- decoders
- .get_frames_initial(
- segment_time as f32,
- !hide_camera,
- true,
- clip_offsets,
- )
- .await
- } else {
- decoders
- .get_frames(
- segment_time as f32,
- !hide_camera,
- true,
- clip_offsets,
- )
- .await
- };
- (frame_num, segment_index, result)
- }));
+ in_flight.push(Box::pin(decode_prefetched_frame(PrefetchDecodeRequest {
+ frame_number: frame_num,
+ decoders,
+ segment_time,
+ segment_index,
+ offsets: clip_offsets,
+ hide_camera,
+ is_initial,
+ transition,
+ })));
}
next_prefetch_frame += 1;
@@ -398,23 +554,29 @@ impl Playback {
let decoders = segment_media.decoders.clone();
let hide_camera = cached_project.camera.hide;
let segment_index = segment.recording_clip;
+ let transition = transition_decode_request(
+ &cached_project,
+ &prefetch_segment_medias,
+ prefetch_time,
+ );
if let Ok(mut in_flight_guard) = prefetch_in_flight.write() {
in_flight_guard.insert(behind_frame);
}
prefetched_behind.insert(behind_frame);
- in_flight.push(Box::pin(async move {
- let result = decoders
- .get_frames(
- segment_time as f32,
- !hide_camera,
- true,
- clip_offsets,
- )
- .await;
- (behind_frame, segment_index, result)
- }));
+ in_flight.push(Box::pin(decode_prefetched_frame(
+ PrefetchDecodeRequest {
+ frame_number: behind_frame,
+ decoders,
+ segment_time,
+ segment_index,
+ offsets: clip_offsets,
+ hide_camera,
+ is_initial: false,
+ transition,
+ },
+ )));
}
}
}
@@ -422,7 +584,7 @@ impl Playback {
tokio::select! {
biased;
- Some((frame_num, segment_index, result)) = in_flight.next() => {
+ Some((frame_num, segment_index, result, transition)) = in_flight.next() => {
if let Ok(mut in_flight_guard) = prefetch_in_flight.write() {
in_flight_guard.remove(&frame_num);
}
@@ -433,6 +595,7 @@ impl Playback {
frame_number: frame_num,
segment_frames,
segment_index,
+ transition,
});
} else if frames_decoded <= 5 {
warn!(
@@ -580,12 +743,37 @@ impl Playback {
|project: &ProjectConfiguration| -> Vec<ZoomTransformTimeline> {
self.segment_medias
.iter()
- .map(|seg| {
- ZoomTransformTimeline::from_project(
+ .enumerate()
+ .map(|(recording_clip, seg)| {
+ ZoomTransformTimeline::from_project_for_clip(
project,
&seg.cursor,
duration,
self.render_constants.options.screen_size,
+ recording_clip as u32,
+ )
+ })
+ .collect()
+ };
+ let build_outgoing_zoom_timelines =
+ |project: &ProjectConfiguration| -> Vec<ZoomTransformTimeline> {
+ if project
+ .timeline
+ .as_ref()
+ .is_none_or(|timeline| timeline.transitions.is_empty())
+ {
+ return Vec::new();
+ }
+ self.segment_medias
+ .iter()
+ .enumerate()
+ .map(|(recording_clip, segment)| {
+ ZoomTransformTimeline::from_project_for_outgoing_clip(
+ project,
+ &segment.cursor,
+ duration,
+ self.render_constants.options.screen_size,
+ recording_clip as u32,
)
})
.collect()
@@ -593,6 +781,7 @@ impl Playback {
let mut cursor_timelines = build_cursor_timelines(&cached_project);
let mut zoom_timelines = build_zoom_timelines(&cached_project);
+ let mut outgoing_zoom_timelines = build_outgoing_zoom_timelines(&cached_project);
if !*stop_rx.borrow()
&& let Some(prefetched_idx) = prefetch_buffer
@@ -602,15 +791,17 @@ impl Playback {
let frame_acquire_start = Instant::now();
let prefetched = prefetch_buffer.remove(prefetched_idx).unwrap();
let frame_acquire_duration = frame_acquire_start.elapsed();
- let segment_index = prefetched.segment_index;
+ let (segment_frames, segment_index, transition) = prefetched.into_cached();
if let Some(segment_media) = self.segment_medias.get(segment_index as usize) {
- let segment_frames = Arc::new(prefetched.segment_frames);
-
let zoom_until = (frame_number as f32 + 1.0) / fps as f32;
if let Some(timeline) = zoom_timelines.get_mut(segment_index as usize) {
timeline.ensure_precomputed_until(zoom_until);
}
+ if let Some(timeline) = outgoing_zoom_timelines.get_mut(segment_index as usize)
+ {
+ timeline.ensure_precomputed_until(zoom_until);
+ }
let zoom_timeline = zoom_timelines.get(segment_index as usize);
let empty_timeline;
@@ -646,11 +837,49 @@ impl Playback {
let uniforms_duration = uniforms_start.elapsed();
let submit_start = Instant::now();
let submitted_frame_number = frame_number;
- let rendered = self.renderer.render_frame_wait(
- Arc::unwrap_or_clone(segment_frames),
- uniforms,
- segment_media.cursor.clone(),
- );
+ let rendered = if let Some((outgoing_frames, outgoing_index, kind, progress)) =
+ transition
+ {
+ let outgoing_media = &self.segment_medias[outgoing_index as usize];
+ if let Some(timeline) =
+ outgoing_zoom_timelines.get_mut(outgoing_index as usize)
+ {
+ timeline.ensure_precomputed_until(zoom_until);
+ }
+ let outgoing_zoom = &outgoing_zoom_timelines[outgoing_index as usize];
+ let outgoing_uniforms = ProjectUniforms::new_with_precomputed_cursor(
+ &self.render_constants,
+ &cached_project,
+ frame_number,
+ fps,
+ resolution_base,
+ &outgoing_media.cursor,
+ &outgoing_frames,
+ duration,
+ outgoing_zoom,
+ &cursor_timelines[outgoing_index as usize],
+ );
+ self.renderer.render_transition_frame_wait(
+ editor::RendererTransitionInput {
+ segment_frames: Arc::unwrap_or_clone(outgoing_frames),
+ uniforms: outgoing_uniforms,
+ cursor: outgoing_media.cursor.clone(),
+ },
+ editor::RendererTransitionInput {
+ segment_frames: Arc::unwrap_or_clone(segment_frames),
+ uniforms,
+ cursor: segment_media.cursor.clone(),
+ },
+ kind,
+ progress,
+ )
+ } else {
+ self.renderer.render_frame_wait(
+ Arc::unwrap_or_clone(segment_frames),
+ uniforms,
+ segment_media.cursor.clone(),
+ )
+ };
let submit_duration = submit_start.elapsed();
if rendered {
@@ -736,6 +965,7 @@ impl Playback {
cached_project = self.project.borrow_and_update().clone();
cursor_timelines = build_cursor_timelines(&cached_project);
zoom_timelines = build_zoom_timelines(&cached_project);
+ outgoing_zoom_timelines = build_outgoing_zoom_timelines(&cached_project);
}
let frame_offset = frame_number.saturating_sub(self.start_frame_number) as f64;
@@ -816,10 +1046,7 @@ impl Playback {
frame_source = PlaybackFrameSource::PrefetchFront;
let prefetched = prefetch_buffer.pop_front().unwrap();
prefetch_hits += 1;
- Some((
- Arc::new(prefetched.segment_frames),
- prefetched.segment_index,
- ))
+ Some(prefetched.into_cached())
} else {
let prefetched_idx = prefetch_buffer
.iter()
@@ -829,10 +1056,7 @@ impl Playback {
frame_source = PlaybackFrameSource::PrefetchSearch;
let prefetched = prefetch_buffer.remove(idx).unwrap();
prefetch_hits += 1;
- Some((
- Arc::new(prefetched.segment_frames),
- prefetched.segment_index,
- ))
+ Some(prefetched.into_cached())
} else if prefetch_buffer.is_empty() {
let _ = frame_request_tx.send(frame_number);
@@ -851,10 +1075,7 @@ impl Playback {
Some(prefetched) => {
if prefetched.frame_number == frame_number {
frame_source = PlaybackFrameSource::PrefetchWaitExact;
- Some((
- Arc::new(prefetched.segment_frames),
- prefetched.segment_index,
- ))
+ Some(prefetched.into_cached())
} else if prefetched.frame_number > frame_number {
frame_source = PlaybackFrameSource::PrefetchWaitFuture;
let skipped_from = frame_number;
@@ -868,10 +1089,7 @@ impl Playback {
prefetch_buffer_len: prefetch_buffer.len(),
});
}
- Some((
- Arc::new(prefetched.segment_frames),
- prefetched.segment_index,
- ))
+ Some(prefetched.into_cached())
} else {
prefetch_buffer.push_back(prefetched);
let skipped_from = frame_number;
@@ -951,10 +1169,7 @@ impl Playback {
frame_source = PlaybackFrameSource::LateDrain;
let prefetched = prefetch_buffer.remove(late_idx).unwrap();
prefetch_hits += 1;
- Some((
- Arc::new(prefetched.segment_frames),
- prefetched.segment_index,
- ))
+ Some(prefetched.into_cached())
} else {
let min_buffered = prefetch_buffer.iter().map(|p| p.frame_number).min();
if let Some(next_available_frame) = min_buffered
@@ -1007,7 +1222,7 @@ impl Playback {
};
let frame_acquire_duration = frame_acquire_start.elapsed();
- if let Some((segment_frames, segment_index)) = segment_frames_opt {
+ if let Some((segment_frames, segment_index, transition)) = segment_frames_opt {
let Some(segment_media) = self.segment_medias.get(segment_index as usize)
else {
frame_number = frame_number.saturating_add(1);
@@ -1019,6 +1234,11 @@ impl Playback {
frame_number,
Arc::clone(&segment_frames),
segment_index,
+ transition.as_ref().map(
+ |(frames, transition_index, kind, progress)| {
+ (Arc::clone(frames), *transition_index, *kind, *progress)
+ },
+ ),
);
}
@@ -1026,6 +1246,10 @@ impl Playback {
if let Some(timeline) = zoom_timelines.get_mut(segment_index as usize) {
timeline.ensure_precomputed_until(zoom_until);
}
+ if let Some(timeline) = outgoing_zoom_timelines.get_mut(segment_index as usize)
+ {
+ timeline.ensure_precomputed_until(zoom_until);
+ }
let zoom_timeline = zoom_timelines.get(segment_index as usize);
let empty_timeline;
@@ -1062,11 +1286,46 @@ impl Playback {
let uniforms_duration = uniforms_start.elapsed();
let submit_start = Instant::now();
let submitted_frame_number = frame_number;
- self.renderer.render_frame(
- Arc::unwrap_or_clone(segment_frames),
- uniforms,
- segment_media.cursor.clone(),
- );
+ if let Some((outgoing_frames, outgoing_index, kind, progress)) = transition {
+ let outgoing_media = &self.segment_medias[outgoing_index as usize];
+ if let Some(timeline) =
+ outgoing_zoom_timelines.get_mut(outgoing_index as usize)
+ {
+ timeline.ensure_precomputed_until(zoom_until);
+ }
+ let outgoing_uniforms = ProjectUniforms::new_with_precomputed_cursor(
+ &self.render_constants,
+ &cached_project,
+ frame_number,
+ fps,
+ resolution_base,
+ &outgoing_media.cursor,
+ &outgoing_frames,
+ duration,
+ &outgoing_zoom_timelines[outgoing_index as usize],
+ &cursor_timelines[outgoing_index as usize],
+ );
+ self.renderer.render_transition_frame(
+ editor::RendererTransitionInput {
+ segment_frames: Arc::unwrap_or_clone(outgoing_frames),
+ uniforms: outgoing_uniforms,
+ cursor: outgoing_media.cursor.clone(),
+ },
+ editor::RendererTransitionInput {
+ segment_frames: Arc::unwrap_or_clone(segment_frames),
+ uniforms,
+ cursor: segment_media.cursor.clone(),
+ },
+ kind,
+ progress,
+ );
+ } else {
+ self.renderer.render_frame(
+ Arc::unwrap_or_clone(segment_frames),
+ uniforms,
+ segment_media.cursor.clone(),
+ );
+ }
let submit_duration = submit_start.elapsed();
if let Some(telemetry) = &self.telemetry {
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index ec4f6458c..54b7335ab 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -123,6 +123,7 @@ impl ExporterBuilder {
if !segments.is_empty() {
project_config.timeline = Some(TimelineConfiguration {
segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/crates/export/src/preview.rs b/crates/export/src/preview.rs
index a9b1e3fb7..51dc6812d 100644
--- a/crates/export/src/preview.rs
+++ b/crates/export/src/preview.rs
@@ -1,8 +1,10 @@
use std::path::PathBuf;
use base64::{Engine, engine::general_purpose::STANDARD};
-use cap_project::{RecordingMeta, XY};
-use cap_rendering::{FrameRenderer, ProjectUniforms, RendererLayers, ZoomTransformTimeline};
+use cap_project::{RecordingMeta, TimelineFrameMapping, XY};
+use cap_rendering::{
+ FrameRenderer, ProjectUniforms, RendererLayers, TransitionRenderInput, ZoomTransformTimeline,
+};
use image::codecs::jpeg::JpegEncoder;
use serde::{Deserialize, Serialize};
@@ -56,6 +58,24 @@ async fn render_preview_with_base(
frame_time: f64,
settings: ExportPreviewSettings,
) -> Result<ExportPreviewResult, ExportError> {
+ let transition_mapping = exporter_base
+ .project_config
+ .timeline
+ .as_ref()
+ .and_then(|timeline| {
+ if timeline.transitions.is_empty() {
+ return None;
+ }
+ match timeline.get_frame_mapping(frame_time) {
+ Some(TimelineFrameMapping::Transition {
+ outgoing,
+ kind,
+ progress,
+ ..
+ }) => Some((outgoing, kind, progress)),
+ _ => None,
+ }
+ });
let Some((segment_time, segment)) = exporter_base.project_config.get_segment_time(frame_time)
else {
return Err(ExportError::Other(
@@ -94,11 +114,12 @@ async fn render_preview_with_base(
&exporter_base.project_config,
);
- let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ let mut zoom_timeline = ZoomTransformTimeline::from_project_for_clip(
&exporter_base.project_config,
&segment_media.cursor,
total_duration,
exporter_base.render_constants.options.screen_size,
+ segment.recording_clip,
);
zoom_timeline.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
@@ -121,15 +142,80 @@ async fn render_preview_with_base(
exporter_base.render_constants.is_software_adapter,
);
- let frame = frame_renderer
- .render_immediate(
- segment_frames,
- uniforms,
- &segment_media.cursor,
- !settings.cursor_only,
- &mut layers,
- )
- .await?;
+ let frame = if let Some((outgoing, kind, progress)) = transition_mapping {
+ let outgoing_media = exporter_base
+ .segments
+ .get(outgoing.segment.recording_clip as usize)
+ .ok_or_else(|| {
+ ExportError::Other("Outgoing recording clip is unavailable".to_string())
+ })?;
+ let outgoing_offsets = exporter_base
+ .project_config
+ .clips
+ .iter()
+ .find(|clip| clip.index == outgoing.segment.recording_clip)
+ .map(|clip| clip.offsets)
+ .unwrap_or_default();
+ let outgoing_frames = outgoing_media
+ .decoders
+ .get_frames(
+ outgoing.source_time as f32,
+ !exporter_base.project_config.camera.hide,
+ !settings.cursor_only,
+ outgoing_offsets,
+ )
+ .await
+ .ok_or_else(|| ExportError::Other("Failed to decode outgoing frame".to_string()))?;
+ let mut outgoing_zoom = ZoomTransformTimeline::from_project_for_outgoing_clip(
+ &exporter_base.project_config,
+ &outgoing_media.cursor,
+ total_duration,
+ exporter_base.render_constants.options.screen_size,
+ outgoing.segment.recording_clip,
+ );
+ outgoing_zoom.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
+ let outgoing_uniforms = ProjectUniforms::new(
+ &exporter_base.render_constants,
+ &exporter_base.project_config,
+ frame_number,
+ settings.fps,
+ settings.resolution_base,
+ &outgoing_media.cursor,
+ &outgoing_frames,
+ total_duration,
+ &outgoing_zoom,
+ );
+
+ frame_renderer
+ .render_transition_immediate(
+ TransitionRenderInput {
+ segment_frames: outgoing_frames,
+ uniforms: outgoing_uniforms,
+ cursor: &outgoing_media.cursor,
+ render_display: !settings.cursor_only,
+ },
+ TransitionRenderInput {
+ segment_frames,
+ uniforms,
+ cursor: &segment_media.cursor,
+ render_display: !settings.cursor_only,
+ },
+ kind,
+ progress as f32,
+ &mut layers,
+ )
+ .await?
+ } else {
+ frame_renderer
+ .render_immediate(
+ segment_frames,
+ uniforms,
+ &segment_media.cursor,
+ !settings.cursor_only,
+ &mut layers,
+ )
+ .await?
+ };
let frame_render_time_ms = render_start.elapsed().as_secs_f64() * 1000.0;
let width = frame.width;
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 59a3d159b..70e33107e 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -1,4 +1,5 @@
use std::{
+ collections::BTreeMap,
fmt,
ops::{Add, Div, Mul, Sub, SubAssign},
path::Path,
@@ -1006,10 +1007,47 @@ impl AudioTrackSegment {
}
}
+pub const MIN_CLIP_TRANSITION_DURATION: f64 = 0.05;
+
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum ClipTransitionType {
+ #[default]
+ CrossFade,
+ FadeThroughBlack,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct ClipTransition {
+ pub segment_index: u32,
+ #[serde(rename = "type")]
+ pub kind: ClipTransitionType,
+ pub duration: f64,
+}
+
+fn deserialize_clip_transitions<'de, D>(deserializer: D) -> Result<Vec<ClipTransition>, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ let transitions = Vec::<ClipTransition>::deserialize(deserializer)?;
+ let mut by_segment = BTreeMap::new();
+ for transition in transitions {
+ by_segment.insert(transition.segment_index, transition);
+ }
+ Ok(by_segment.into_values().collect())
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct TimelineConfiguration {
pub segments: Vec<TimelineSegment>,
+ #[serde(
+ default,
+ deserialize_with = "deserialize_clip_transitions",
+ skip_serializing_if = "Vec::is_empty"
+ )]
+ pub transitions: Vec<ClipTransition>,
pub zoom_segments: Vec<ZoomSegment>,
#[serde(default)]
pub scene_segments: Vec<SceneSegment>,
@@ -1025,6 +1063,29 @@ pub struct TimelineConfiguration {
pub audio_segments: Vec<AudioTrackSegment>,
}
+#[derive(Clone, Copy, Debug)]
+pub struct TimelineSource<'a> {
+ pub source_time: f64,
+ pub segment_index: usize,
+ pub segment: &'a TimelineSegment,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum TimelineFrameMapping<'a> {
+ Single {
+ source: TimelineSource<'a>,
+ output_end: f64,
+ },
+ Transition {
+ outgoing: TimelineSource<'a>,
+ incoming: TimelineSource<'a>,
+ kind: ClipTransitionType,
+ progress: f64,
+ duration: f64,
+ output_end: f64,
+ },
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CaptionTrackSegment {
@@ -1049,14 +1110,144 @@ pub struct CaptionTrackSegment {
}
impl TimelineConfiguration {
+ pub fn effective_transition(&self, segment_index: usize) -> Option<ClipTransition> {
+ if segment_index == 0 || segment_index >= self.segments.len() {
+ return None;
+ }
+
+ let transition_position = self
+ .transitions
+ .partition_point(|transition| transition.segment_index as usize <= segment_index);
+ let transition = self.transitions.get(transition_position.checked_sub(1)?)?;
+ if transition.segment_index as usize != segment_index {
+ return None;
+ }
+ if !transition.duration.is_finite() || transition.duration <= 0.0 {
+ return None;
+ }
+
+ let maximum = self.segments[segment_index - 1]
+ .duration()
+ .min(self.segments[segment_index].duration())
+ / 2.0;
+ if !maximum.is_finite() || maximum < MIN_CLIP_TRANSITION_DURATION {
+ return None;
+ }
+
+ Some(ClipTransition {
+ duration: transition
+ .duration
+ .clamp(MIN_CLIP_TRANSITION_DURATION, maximum),
+ ..*transition
+ })
+ }
+
+ pub fn get_frame_mapping(&self, frame_time: f64) -> Option<TimelineFrameMapping<'_>> {
+ if self.transitions.is_empty() {
+ return self.get_segment_time_without_transitions(frame_time).map(
+ |(source_time, segment, segment_index, output_end)| TimelineFrameMapping::Single {
+ source: TimelineSource {
+ source_time,
+ segment_index,
+ segment,
+ },
+ output_end,
+ },
+ );
+ }
+
+ let mut segment_start = 0.0;
+
+ for (segment_index, segment) in self.segments.iter().enumerate() {
+ let incoming = self.effective_transition(segment_index);
+ let incoming_duration = incoming.as_ref().map_or(0.0, |value| value.duration);
+
+ if let Some(transition) = incoming {
+ let output_end = segment_start + transition.duration;
+ if frame_time >= segment_start && frame_time < output_end {
+ let elapsed = frame_time - segment_start;
+ let outgoing_segment = &self.segments[segment_index - 1];
+ let outgoing_time = outgoing_segment.interpolate_time(
+ outgoing_segment.duration() - transition.duration + elapsed,
+ )?;
+ let incoming_time = segment.interpolate_time(elapsed)?;
+
+ return Some(TimelineFrameMapping::Transition {
+ outgoing: TimelineSource {
+ source_time: outgoing_time,
+ segment_index: segment_index - 1,
+ segment: outgoing_segment,
+ },
+ incoming: TimelineSource {
+ source_time: incoming_time,
+ segment_index,
+ segment,
+ },
+ kind: transition.kind,
+ progress: (elapsed / transition.duration).clamp(0.0, 1.0),
+ duration: transition.duration,
+ output_end,
+ });
+ }
+ }
+
+ let next_transition = self.effective_transition(segment_index + 1);
+ let next_duration = next_transition.as_ref().map_or(0.0, |value| value.duration);
+ let single_start = segment_start + incoming_duration;
+ let output_end = segment_start + segment.duration() - next_duration;
+
+ if frame_time >= single_start && frame_time < output_end {
+ let source_time = segment.interpolate_time(frame_time - segment_start)?;
+ return Some(TimelineFrameMapping::Single {
+ source: TimelineSource {
+ source_time,
+ segment_index,
+ segment,
+ },
+ output_end,
+ });
+ }
+
+ segment_start += segment.duration() - next_duration;
+ }
+
+ None
+ }
+
pub fn get_segment_time(&self, frame_time: f64) -> Option<(f64, &TimelineSegment)> {
+ if !self.transitions.is_empty() {
+ return match self.get_frame_mapping(frame_time)? {
+ TimelineFrameMapping::Single { source, .. } => {
+ Some((source.source_time, source.segment))
+ }
+ TimelineFrameMapping::Transition { incoming, .. } => {
+ Some((incoming.source_time, incoming.segment))
+ }
+ };
+ }
+
+ self.get_segment_time_without_transitions(frame_time)
+ .map(|(source_time, segment, _, _)| (source_time, segment))
+ }
+
+ fn get_segment_time_without_transitions(
+ &self,
+ frame_time: f64,
+ ) -> Option<(f64, &TimelineSegment, usize, f64)> {
let mut accum_duration = 0.0;
- for segment in self.segments.iter() {
+ for (segment_index, segment) in self.segments.iter().enumerate() {
if frame_time < accum_duration + segment.duration() {
return segment
.interpolate_time(frame_time - accum_duration)
- .map(|t| (t, segment));
+ .map(|time| {
+ (
+ time,
+ segment,
+ segment_index,
+ accum_duration + segment.duration(),
+ )
+ });
}
accum_duration += segment.duration();
@@ -1066,7 +1257,16 @@ impl TimelineConfiguration {
}
pub fn duration(&self) -> f64 {
- self.segments.iter().map(|s| s.duration()).sum()
+ let segment_duration = self.segments.iter().map(TimelineSegment::duration).sum();
+ if self.transitions.is_empty() {
+ return segment_duration;
+ }
+
+ segment_duration
+ - (1..self.segments.len())
+ .filter_map(|segment_index| self.effective_transition(segment_index))
+ .map(|transition| transition.duration)
+ .sum::<f64>()
}
}
@@ -1602,6 +1802,139 @@ pub const FAST_VELOCITY_THRESHOLD: f64 = 0.015;
mod tests {
use super::*;
+ fn timeline_with_transitions(transitions: Vec<ClipTransition>) -> TimelineConfiguration {
+ TimelineConfiguration {
+ segments: vec![
+ TimelineSegment {
+ recording_clip: 0,
+ timescale: 1.0,
+ start: 0.0,
+ end: 4.0,
+ name: None,
+ },
+ TimelineSegment {
+ recording_clip: 1,
+ timescale: 1.0,
+ start: 10.0,
+ end: 16.0,
+ name: None,
+ },
+ ],
+ transitions,
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn timeline_without_transitions_keeps_legacy_mapping() {
+ let timeline = timeline_with_transitions(Vec::new());
+
+ assert_eq!(timeline.duration(), 10.0);
+ let (time, segment) = timeline.get_segment_time(4.5).unwrap();
+ assert_eq!(time, 10.5);
+ assert_eq!(segment.recording_clip, 1);
+ assert!(matches!(
+ timeline.get_frame_mapping(4.5),
+ Some(TimelineFrameMapping::Single { source, output_end: 10.0 })
+ if source.segment_index == 1 && source.source_time == 10.5
+ ));
+ assert!(
+ serde_json::to_value(&timeline)
+ .unwrap()
+ .get("transitions")
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn timeline_maps_both_sources_inside_transition() {
+ let timeline = timeline_with_transitions(vec![ClipTransition {
+ segment_index: 1,
+ kind: ClipTransitionType::CrossFade,
+ duration: 1.0,
+ }]);
+
+ assert_eq!(timeline.duration(), 9.0);
+ assert_eq!(
+ serde_json::to_value(&timeline).unwrap()["transitions"][0]["type"],
+ "cross-fade"
+ );
+ assert!(matches!(
+ timeline.get_frame_mapping(3.5),
+ Some(TimelineFrameMapping::Transition {
+ outgoing,
+ incoming,
+ kind: ClipTransitionType::CrossFade,
+ progress,
+ duration: 1.0,
+ output_end: 4.0,
+ }) if outgoing.segment_index == 0
+ && outgoing.source_time == 3.5
+ && incoming.segment_index == 1
+ && incoming.source_time == 10.5
+ && progress == 0.5
+ ));
+ }
+
+ #[test]
+ fn timeline_clamps_transition_to_half_the_shorter_clip() {
+ let timeline = timeline_with_transitions(vec![ClipTransition {
+ segment_index: 1,
+ kind: ClipTransitionType::FadeThroughBlack,
+ duration: 9.0,
+ }]);
+
+ let transition = timeline.effective_transition(1).unwrap();
+ assert_eq!(transition.duration, 2.0);
+ assert_eq!(timeline.duration(), 8.0);
+ }
+
+ #[test]
+ fn legacy_timeline_json_defaults_to_no_transitions() {
+ let timeline: TimelineConfiguration = serde_json::from_value(serde_json::json!({
+ "segments": [
+ { "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 4.0 }
+ ],
+ "zoomSegments": []
+ }))
+ .unwrap();
+
+ assert!(timeline.transitions.is_empty());
+ assert_eq!(timeline.duration(), 4.0);
+ }
+
+ #[test]
+ fn transition_json_is_normalized_by_segment_index() {
+ let timeline: TimelineConfiguration = serde_json::from_value(serde_json::json!({
+ "segments": [
+ { "recordingSegment": 0, "timescale": 1.0, "start": 0.0, "end": 4.0 },
+ { "recordingSegment": 0, "timescale": 1.0, "start": 4.0, "end": 8.0 },
+ { "recordingSegment": 0, "timescale": 1.0, "start": 8.0, "end": 12.0 }
+ ],
+ "transitions": [
+ { "segmentIndex": 2, "type": "cross-fade", "duration": 0.5 },
+ { "segmentIndex": 1, "type": "cross-fade", "duration": 0.25 },
+ { "segmentIndex": 2, "type": "fade-through-black", "duration": 1.0 }
+ ],
+ "zoomSegments": []
+ }))
+ .unwrap();
+
+ assert_eq!(timeline.transitions.len(), 2);
+ assert_eq!(timeline.transitions[0].segment_index, 1);
+ assert_eq!(timeline.transitions[1].segment_index, 2);
+ assert_eq!(
+ timeline.transitions[1].kind,
+ ClipTransitionType::FadeThroughBlack
+ );
+ }
+
fn write_config_with_motion_blur_values(
project_path: &std::path::Path,
cursor_motion_blur: f64,
@@ -1747,6 +2080,7 @@ mod tests {
let config = ProjectConfiguration {
timeline: Some(TimelineConfiguration {
segments: Vec::new(),
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rs
index 572d4b10f..c2f9f84e6 100644
--- a/crates/recording/src/recovery.rs
+++ b/crates/recording/src/recovery.rs
@@ -1509,6 +1509,7 @@ impl RecoveryManager {
config.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 9c0ddb705..1dbcb5893 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -1182,6 +1182,7 @@ async fn stop_recording(
if !timeline_segments.is_empty() {
project_config.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
+ transitions: Vec::new(),
zoom_segments: Vec::new(),
scene_segments: Vec::new(),
mask_segments: Vec::new(),
diff --git a/crates/recording/src/track_heal.rs b/crates/recording/src/track_heal.rs
index c156714bc..4ddaba840 100644
--- a/crates/recording/src/track_heal.rs
+++ b/crates/recording/src/track_heal.rs
@@ -1043,6 +1043,7 @@ mod tests {
end: 202.220711,
name: None,
}],
+ transitions: Vec::new(),
zoom_segments: vec![ZoomSegment {
start: 100.0,
end: 150.0,
@@ -1099,6 +1100,7 @@ mod tests {
name: None,
},
],
+ transitions: Vec::new(),
zoom_segments: vec![ZoomSegment {
start: 10.0,
end: 20.0,
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 261a0aad9..3afbb1512 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,8 +1,9 @@
use anyhow::Result;
use cap_project::{
- AspectRatio, Camera, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets, CornerStyle,
- Crop, CursorEvents, CursorType, FrameConfiguration, FrameStyle, ProjectConfiguration,
- RecordingMeta, SceneMode, StudioRecordingMeta, XY,
+ AspectRatio, Camera, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets,
+ ClipTransitionType, CornerStyle, Crop, CursorEvents, CursorType, FrameConfiguration,
+ FrameStyle, ProjectConfiguration, RecordingMeta, SceneMode, StudioRecordingMeta,
+ TimelineFrameMapping, TimelineSource, XY,
};
use composite_frame::CompositeVideoFrameUniforms;
use core::f64;
@@ -45,6 +46,7 @@ mod project_recordings;
mod scene;
pub mod spring_mass_damper;
mod text;
+mod transition;
pub mod yuv_converter;
mod zoom;
mod zoom_spring;
@@ -54,6 +56,7 @@ pub use decoder::{DecodedFrame, DecoderStatus, DecoderType, PixelFormat};
pub use frame_pipeline::{GpuOutputFormat, Nv12RenderedFrame, RenderedFrame, SharedNv12Buffer};
pub use layers::{BackgroundTextureCache, clean_background_path};
pub use project_recordings::{ProjectRecordingsMeta, SegmentRecordings, Video};
+use transition::{TransitionCompositor, TransitionParameters};
/// Warms the process-wide system-font scan used by the text/captions/keyboard
/// layers. The first scan is the slow part (hundreds of ms to over a second on
@@ -567,15 +570,36 @@ pub async fn render_video_to_channel(
let mut zoom_timelines: Vec<ZoomTransformTimeline> = render_segments
.iter()
- .map(|segment| {
- ZoomTransformTimeline::from_project(
+ .enumerate()
+ .map(|(recording_clip, segment)| {
+ ZoomTransformTimeline::from_project_for_clip(
project,
&segment.cursor,
duration,
constants.options.screen_size,
+ recording_clip as u32,
)
})
.collect();
+ let mut outgoing_zoom_timelines = project
+ .timeline
+ .as_ref()
+ .is_some_and(|timeline| !timeline.transitions.is_empty())
+ .then(|| {
+ render_segments
+ .iter()
+ .enumerate()
+ .map(|(recording_clip, segment)| {
+ ZoomTransformTimeline::from_project_for_outgoing_clip(
+ project,
+ &segment.cursor,
+ duration,
+ constants.options.screen_size,
+ recording_clip as u32,
+ )
+ })
+ .collect::<Vec<_>>()
+ });
let mut frame_number = 0;
@@ -611,9 +635,23 @@ pub async fn render_video_to_channel(
break;
}
- let Some((segment_time, segment)) =
- project.get_segment_time(frame_number as f64 / fps as f64)
- else {
+ let frame_time = frame_number as f64 / fps as f64;
+ let transition_mapping = project.timeline.as_ref().and_then(|timeline| {
+ if timeline.transitions.is_empty() {
+ return None;
+ }
+ match timeline.get_frame_mapping(frame_time) {
+ Some(TimelineFrameMapping::Transition {
+ outgoing,
+ kind,
+ progress,
+ ..
+ }) => Some((outgoing, kind, progress)),
+ _ => None,
+ }
+ });
+
+ let Some((segment_time, segment)) = project.get_segment_time(frame_time) else {
break;
};
@@ -633,8 +671,11 @@ pub async fn render_video_to_channel(
let zoom_until = (current_frame_number as f32 + 1.0) / fps as f32;
zoom_timelines[segment_clip_index].ensure_precomputed_until(zoom_until);
+ if let Some(timelines) = &mut outgoing_zoom_timelines {
+ timelines[segment_clip_index].ensure_precomputed_until(zoom_until);
+ }
- let segment_frames =
+ let incoming_decode = async {
if let Some((pf_num, _pf_time, pf_clip, pf_result)) = prefetched_decode.take() {
if pf_num == current_frame_number && pf_clip == segment_clip_index {
pf_result
@@ -663,7 +704,24 @@ pub async fn render_video_to_channel(
fps,
)
.await
- };
+ }
+ };
+ let (segment_frames, outgoing_frames) = if let Some((outgoing, _, _)) = transition_mapping {
+ tokio::join!(
+ incoming_decode,
+ decode_timeline_source_frames(
+ project,
+ &render_segments,
+ outgoing,
+ needs_camera,
+ current_frame_number,
+ is_initial_frame,
+ fps,
+ )
+ )
+ } else {
+ (incoming_decode.await, None)
+ };
if let Some(segment_frames) = segment_frames {
consecutive_failures = 0;
@@ -716,7 +774,44 @@ pub async fn render_video_to_channel(
None
};
- let render_result = if let Some(prefetch) = prefetch_future {
+ let render_result = if let Some((outgoing, kind, progress)) = transition_mapping {
+ let render_future = render_transition_rgba(
+ TransitionExportContext {
+ constants,
+ project,
+ render_segments: &render_segments,
+ outgoing_zoom_timelines: outgoing_zoom_timelines
+ .as_mut()
+ .expect("transition zoom timelines are initialized"),
+ precomputed_cursor_timelines: &precomputed_cursor_timelines,
+ current_frame_number,
+ fps,
+ resolution_base,
+ duration,
+ },
+ &mut frame_renderer,
+ &mut layers,
+ (outgoing, outgoing_frames),
+ kind,
+ progress,
+ TransitionRenderInput {
+ segment_frames,
+ uniforms,
+ cursor: &render_segment.cursor,
+ render_display: render_segment.render_display,
+ },
+ );
+ if let Some(prefetch) = prefetch_future {
+ let (render, decoded) = tokio::join!(render_future, prefetch);
+ if let Some((next_seg_time, next_clip_index)) = next_prefetch_meta {
+ prefetched_decode =
+ Some((next_frame_number, next_seg_time, next_clip_index, decoded));
+ }
+ render
+ } else {
+ render_future.await
+ }
+ } else if let Some(prefetch) = prefetch_future {
let (render, decoded) = tokio::join!(
frame_renderer.render(
segment_frames,
@@ -911,18 +1006,44 @@ pub async fn render_video_to_channel_nv12(
let zoom_build_start = Instant::now();
let mut zoom_timelines: Vec<ZoomTransformTimeline> = render_segments
.iter()
- .map(|segment| {
- ZoomTransformTimeline::from_project(
+ .enumerate()
+ .map(|(recording_clip, segment)| {
+ ZoomTransformTimeline::from_project_for_clip(
project,
&segment.cursor,
duration,
constants.options.screen_size,
+ recording_clip as u32,
)
})
.collect();
+ let mut outgoing_zoom_timelines = project
+ .timeline
+ .as_ref()
+ .is_some_and(|timeline| !timeline.transitions.is_empty())
+ .then(|| {
+ render_segments
+ .iter()
+ .enumerate()
+ .map(|(recording_clip, segment)| {
+ ZoomTransformTimeline::from_project_for_outgoing_clip(
+ project,
+ &segment.cursor,
+ duration,
+ constants.options.screen_size,
+ recording_clip as u32,
+ )
+ })
+ .collect::<Vec<_>>()
+ });
for timeline in &mut zoom_timelines {
timeline.precompute();
}
+ if let Some(timelines) = &mut outgoing_zoom_timelines {
+ for timeline in timelines {
+ timeline.precompute();
+ }
+ }
let zoom_focus_interpolators_construct_ms = zoom_build_start.elapsed().as_millis() as u64;
let mut frame_number = 0;
@@ -967,9 +1088,23 @@ pub async fn render_video_to_channel_nv12(
break;
}
- let Some((segment_time, segment)) =
- project.get_segment_time(frame_number as f64 / fps as f64)
- else {
+ let frame_time = frame_number as f64 / fps as f64;
+ let transition_mapping = project.timeline.as_ref().and_then(|timeline| {
+ if timeline.transitions.is_empty() {
+ return None;
+ }
+ match timeline.get_frame_mapping(frame_time) {
+ Some(TimelineFrameMapping::Transition {
+ outgoing,
+ kind,
+ progress,
+ ..
+ }) => Some((outgoing, kind, progress)),
+ _ => None,
+ }
+ });
+
+ let Some((segment_time, segment)) = project.get_segment_time(frame_time) else {
break;
};
@@ -990,10 +1125,13 @@ pub async fn render_video_to_channel_nv12(
let zoom_pre_start = Instant::now();
let zoom_until = (current_frame_number as f32 + 1.0) / fps as f32;
zoom_timelines[segment_clip_index].ensure_precomputed_until(zoom_until);
+ if let Some(timelines) = &mut outgoing_zoom_timelines {
+ timelines[segment_clip_index].ensure_precomputed_until(zoom_until);
+ }
let this_zoom_pre_ms = zoom_pre_start.elapsed().as_millis() as u64;
let decode_wall_start = Instant::now();
- let segment_frames =
+ let incoming_decode = async {
if let Some((pf_num, _pf_time, pf_clip, pf_result)) = prefetched_decode.take() {
if pf_num == current_frame_number && pf_clip == segment_clip_index {
pf_result
@@ -1022,7 +1160,24 @@ pub async fn render_video_to_channel_nv12(
fps,
)
.await
- };
+ }
+ };
+ let (segment_frames, outgoing_frames) = if let Some((outgoing, _, _)) = transition_mapping {
+ tokio::join!(
+ incoming_decode,
+ decode_timeline_source_frames(
+ project,
+ &render_segments,
+ outgoing,
+ needs_camera,
+ current_frame_number,
+ is_initial_frame,
+ fps,
+ )
+ )
+ } else {
+ (incoming_decode.await, None)
+ };
let this_decode_ms = decode_wall_start.elapsed().as_millis() as u64;
if let Some(segment_frames) = segment_frames {
@@ -1081,7 +1236,77 @@ pub async fn render_video_to_channel_nv12(
first_phase_render_ms,
first_phase_prefetch_ms,
first_phase_join_wall_ms,
- ) = if let Some(prefetch) = prefetch_future {
+ ) = if let Some((outgoing, kind, progress)) = transition_mapping {
+ let render_future = render_transition_nv12_export(
+ TransitionExportContext {
+ constants,
+ project,
+ render_segments: &render_segments,
+ outgoing_zoom_timelines: outgoing_zoom_timelines
+ .as_mut()
+ .expect("transition zoom timelines are initialized"),
+ precomputed_cursor_timelines: &precomputed_cursor_timelines,
+ current_frame_number,
+ fps,
+ resolution_base,
+ duration,
+ },
+ &mut frame_renderer,
+ &mut layers,
+ (outgoing, outgoing_frames),
+ kind,
+ progress,
+ TransitionRenderInput {
+ segment_frames,
+ uniforms,
+ cursor: &render_segment.cursor,
+ render_display: render_segment.render_display,
+ },
+ );
+ if let Some(prefetch) = prefetch_future {
+ if record_first_frame_nv12_phases {
+ let join_wall_start = Instant::now();
+ let render_fut = async {
+ let started = Instant::now();
+ let result = render_future.await;
+ (started.elapsed(), result)
+ };
+ let prefetch_fut = async {
+ let started = Instant::now();
+ let decoded = prefetch.await;
+ (started.elapsed(), decoded)
+ };
+ let ((render_elapsed, render), (prefetch_elapsed, decoded)) =
+ tokio::join!(render_fut, prefetch_fut);
+ if let Some((next_seg_time, next_clip_index)) = next_prefetch_meta {
+ prefetched_decode =
+ Some((next_frame_number, next_seg_time, next_clip_index, decoded));
+ }
+ (
+ render,
+ Some(render_elapsed.as_millis() as u64),
+ Some(prefetch_elapsed.as_millis() as u64),
+ Some(join_wall_start.elapsed().as_millis() as u64),
+ )
+ } else {
+ let (render, decoded) = tokio::join!(render_future, prefetch);
+ if let Some((next_seg_time, next_clip_index)) = next_prefetch_meta {
+ prefetched_decode =
+ Some((next_frame_number, next_seg_time, next_clip_index, decoded));
+ }
+ (render, None, None, None)
+ }
+ } else {
+ let render_start = Instant::now();
+ let render = render_future.await;
+ (
+ render,
+ Some(render_start.elapsed().as_millis() as u64),
+ None,
+ None,
+ )
+ }
+ } else if let Some(prefetch) = prefetch_future {
if record_first_frame_nv12_phases {
let join_wall_start = Instant::now();
let render_fut = async {
@@ -1335,6 +1560,163 @@ pub async fn render_video_to_channel_nv12(
Ok(())
}
+struct TransitionExportContext<'a> {
+ constants: &'a RenderVideoConstants,
+ project: &'a ProjectConfiguration,
+ render_segments: &'a [RenderSegment],
+ outgoing_zoom_timelines: &'a mut [ZoomTransformTimeline],
+ precomputed_cursor_timelines: &'a [Arc<PrecomputedCursorTimeline>],
+ current_frame_number: u32,
+ fps: u32,
+ resolution_base: XY<u32>,
+ duration: f64,
+}
+
+async fn decode_timeline_source_frames(
+ project: &ProjectConfiguration,
+ render_segments: &[RenderSegment],
+ source: TimelineSource<'_>,
+ needs_camera: bool,
+ current_frame_number: u32,
+ is_initial_frame: bool,
+ fps: u32,
+) -> Option<DecodedSegmentFrames> {
+ let render_segment = &render_segments[source.segment.recording_clip as usize];
+ let clip_config = project
+ .clips
+ .iter()
+ .find(|clip| clip.index == source.segment.recording_clip);
+ decode_segment_frames_with_retry(
+ &render_segment.decoders,
+ source.source_time,
+ needs_camera,
+ render_segment.render_display,
+ clip_config.map(|clip| clip.offsets).unwrap_or_default(),
+ current_frame_number,
+ is_initial_frame,
+ fps,
+ )
+ .await
+}
+
+async fn render_transition_rgba(
+ context: TransitionExportContext<'_>,
+ frame_renderer: &mut FrameRenderer<'_>,
+ layers: &mut RendererLayers,
+ outgoing: (TimelineSource<'_>, Option<DecodedSegmentFrames>),
+ kind: ClipTransitionType,
+ progress: f64,
+ incoming: TransitionRenderInput<'_>,
+) -> Result<Option<RenderedFrame>, RenderingError> {
+ let (outgoing, outgoing_frames) = outgoing;
+ let outgoing_clip_index = outgoing.segment.recording_clip as usize;
+ let outgoing_render_segment = &context.render_segments[outgoing_clip_index];
+ context.outgoing_zoom_timelines[outgoing_clip_index]
+ .ensure_precomputed_until((context.current_frame_number as f32 + 1.0) / context.fps as f32);
+
+ let Some(outgoing_frames) = outgoing_frames else {
+ tracing::warn!(
+ frame_number = context.current_frame_number,
+ "Outgoing transition frame decode failed; rendering incoming frame"
+ );
+ return frame_renderer
+ .render(
+ incoming.segment_frames,
+ incoming.uniforms,
+ incoming.cursor,
+ incoming.render_display,
+ layers,
+ )
+ .await;
+ };
+ let outgoing_uniforms = ProjectUniforms::new_with_precomputed_cursor(
+ context.constants,
+ context.project,
+ context.current_frame_number,
+ context.fps,
+ context.resolution_base,
+ &outgoing_render_segment.cursor,
+ &outgoing_frames,
+ context.duration,
+ &context.outgoing_zoom_timelines[outgoing_clip_index],
+ &context.precomputed_cursor_timelines[outgoing_clip_index],
+ );
+
+ frame_renderer
+ .render_transition(
+ TransitionRenderInput {
+ segment_frames: outgoing_frames,
+ uniforms: outgoing_uniforms,
+ cursor: &outgoing_render_segment.cursor,
+ render_display: outgoing_render_segment.render_display,
+ },
+ incoming,
+ kind,
+ progress as f32,
+ layers,
+ )
+ .await
+}
+
+async fn render_transition_nv12_export(
+ context: TransitionExportContext<'_>,
+ frame_renderer: &mut FrameRenderer<'_>,
+ layers: &mut RendererLayers,
+ outgoing: (TimelineSource<'_>, Option<DecodedSegmentFrames>),
+ kind: ClipTransitionType,
+ progress: f64,
+ incoming: TransitionRenderInput<'_>,
+) -> Result<Option<Nv12RenderedFrame>, RenderingError> {
+ let (outgoing, outgoing_frames) = outgoing;
+ let outgoing_clip_index = outgoing.segment.recording_clip as usize;
+ let outgoing_render_segment = &context.render_segments[outgoing_clip_index];
+ context.outgoing_zoom_timelines[outgoing_clip_index]
+ .ensure_precomputed_until((context.current_frame_number as f32 + 1.0) / context.fps as f32);
+
+ let Some(outgoing_frames) = outgoing_frames else {
+ tracing::warn!(
+ frame_number = context.current_frame_number,
+ "Outgoing transition frame decode failed; rendering incoming NV12 frame"
+ );
+ return frame_renderer
+ .render_nv12(
+ incoming.segment_frames,
+ incoming.uniforms,
+ incoming.cursor,
+ incoming.render_display,
+ layers,
+ )
+ .await;
+ };
+ let outgoing_uniforms = ProjectUniforms::new_with_precomputed_cursor(
+ context.constants,
+ context.project,
+ context.current_frame_number,
+ context.fps,
+ context.resolution_base,
+ &outgoing_render_segment.cursor,
+ &outgoing_frames,
+ context.duration,
+ &context.outgoing_zoom_timelines[outgoing_clip_index],
+ &context.precomputed_cursor_timelines[outgoing_clip_index],
+ );
+
+ frame_renderer
+ .render_transition_nv12(
+ TransitionRenderInput {
+ segment_frames: outgoing_frames,
+ uniforms: outgoing_uniforms,
+ cursor: &outgoing_render_segment.cursor,
+ render_display: outgoing_render_segment.render_display,
+ },
+ incoming,
+ kind,
+ progress as f32,
+ layers,
+ )
+ .await
+}
+
const DECODE_MAX_RETRIES_INITIAL: u32 = 5;
const DECODE_MAX_RETRIES_STEADY: u32 = 2;
const MAX_INITIAL_CONSECUTIVE_FAILURES: u32 = 8;
@@ -4031,6 +4413,14 @@ pub struct DecodedSegmentFrames {
pub segment_has_camera: bool,
}
+#[derive(Clone)]
+pub struct TransitionRenderInput<'a> {
+ pub segment_frames: DecodedSegmentFrames,
+ pub uniforms: ProjectUniforms,
+ pub cursor: &'a CursorEvents,
+ pub render_display: bool,
+}
+
#[derive(Clone, Copy, Debug, Default)]
pub struct FrameRenderStageTimings {
pub prepare_duration: std::time::Duration,
@@ -4057,6 +4447,7 @@ pub struct FrameRenderer<'a> {
session: Option<RenderSession>,
nv12_converter: Option<frame_pipeline::RgbaToNv12Converter>,
nv12_buffer_pool: NV12BufferPool,
+ transition_compositor: Option<TransitionCompositor>,
}
impl<'a> FrameRenderer<'a> {
@@ -4068,6 +4459,7 @@ impl<'a> FrameRenderer<'a> {
session: None,
nv12_converter: None,
nv12_buffer_pool: NV12BufferPool::new(6),
+ transition_compositor: None,
}
}
@@ -4167,6 +4559,107 @@ impl<'a> FrameRenderer<'a> {
Err(last_error.unwrap_or(RenderingError::BufferMapWaitingFailed))
}
+ pub async fn render_transition(
+ &mut self,
+ outgoing: TransitionRenderInput<'_>,
+ incoming: TransitionRenderInput<'_>,
+ kind: ClipTransitionType,
+ progress: f32,
+ layers: &mut RendererLayers,
+ ) -> Result<Option<RenderedFrame>, RenderingError> {
+ let mut last_error = None;
+
+ for attempt in 0..Self::MAX_RENDER_RETRIES {
+ if attempt > 0 {
+ tracing::warn!(
+ frame_number = incoming.uniforms.frame_number,
+ attempt = attempt + 1,
+ "Retrying transition frame render after GPU error"
+ );
+ self.reset_session();
+ tokio::time::sleep(std::time::Duration::from_millis(100 * (attempt as u64 + 1)))
+ .await;
+ }
+
+ let session = self.session.get_or_insert_with(|| {
+ RenderSession::new(
+ &self.constants.device,
+ incoming.uniforms.output_size.0,
+ incoming.uniforms.output_size.1,
+ )
+ });
+ session.update_texture_size(
+ &self.constants.device,
+ incoming.uniforms.output_size.0,
+ incoming.uniforms.output_size.1,
+ );
+ let compositor = self
+ .transition_compositor
+ .get_or_insert_with(|| TransitionCompositor::new(&self.constants.device));
+ compositor.ensure_size(
+ &self.constants.device,
+ incoming.uniforms.output_size.0,
+ incoming.uniforms.output_size.1,
+ );
+
+ let encoder = match produce_transition_texture(
+ self.constants,
+ &outgoing,
+ &incoming,
+ (kind, progress),
+ layers,
+ session,
+ compositor,
+ )
+ .await
+ {
+ Ok(encoder) => encoder,
+ Err(error) => return Err(error),
+ };
+
+ match finish_encoder_timed(
+ session,
+ &self.constants.device,
+ &self.constants.queue,
+ &incoming.uniforms,
+ encoder,
+ )
+ .await
+ {
+ Ok((frame, _)) => return Ok(frame),
+ Err(RenderingError::BufferMapWaitingFailed) => {
+ last_error = Some(RenderingError::BufferMapWaitingFailed);
+ }
+ Err(RenderingError::BufferMapFailed(error)) => {
+ last_error = Some(RenderingError::BufferMapFailed(error));
+ }
+ Err(error) => return Err(error),
+ }
+ }
+
+ Err(last_error.unwrap_or(RenderingError::BufferMapWaitingFailed))
+ }
+
+ pub async fn render_transition_immediate(
+ &mut self,
+ outgoing: TransitionRenderInput<'_>,
+ incoming: TransitionRenderInput<'_>,
+ kind: ClipTransitionType,
+ progress: f32,
+ layers: &mut RendererLayers,
+ ) -> Result<RenderedFrame, RenderingError> {
+ if let Some(frame) = self
+ .render_transition(outgoing, incoming, kind, progress, layers)
+ .await?
+ {
+ return Ok(frame);
+ }
+
+ self.flush_pipeline()
+ .await
+ .unwrap_or(Err(RenderingError::BufferMapWaitingFailed))
+ }
+
pub async fn render_immediate(
&mut self,
segment_frames: DecodedSegmentFrames,
@@ -4262,6 +4755,94 @@ impl<'a> FrameRenderer<'a> {
.await
}
+ pub async fn render_transition_nv12(
+ &mut self,
+ outgoing: TransitionRenderInput<'_>,
+ incoming: TransitionRenderInput<'_>,
+ kind: ClipTransitionType,
+ progress: f32,
+ layers: &mut RendererLayers,
+ ) -> Result<Option<frame_pipeline::Nv12RenderedFrame>, RenderingError> {
+ if self.constants.is_software_adapter {
+ let frame = self
+ .render_transition(outgoing, incoming, kind, progress, layers)
+ .await?;
+ return Ok(frame.map(|frame| self.convert_rgba_to_nv12(frame)));
+ }
+
+ let mut last_error = None;
+ for attempt in 0..Self::MAX_RENDER_RETRIES {
+ if attempt > 0 {
+ tracing::warn!(
+ frame_number = incoming.uniforms.frame_number,
+ attempt = attempt + 1,
+ "Retrying NV12 transition frame render after GPU error"
+ );
+ self.reset_session();
+ self.nv12_converter = None;
+ tokio::time::sleep(std::time::Duration::from_millis(100 * (attempt as u64 + 1)))
+ .await;
+ }
+
+ let session = self.session.get_or_insert_with(|| {
+ RenderSession::new(
+ &self.constants.device,
+ incoming.uniforms.output_size.0,
+ incoming.uniforms.output_size.1,
+ )
+ });
+ session.update_texture_size(
+ &self.constants.device,
+ incoming.uniforms.output_size.0,
+ incoming.uniforms.output_size.1,
+ );
+ let compositor = self
+ .transition_compositor
+ .get_or_insert_with(|| TransitionCompositor::new(&self.constants.device));
+ compositor.ensure_size(
+ &self.constants.device,
+ incoming.uniforms.output_size.0,
+ incoming.uniforms.output_size.1,
+ );
+ let encoder = produce_transition_texture(
+ self.constants,
+ &outgoing,
+ &incoming,
+ (kind, progress),
+ layers,
+ session,
+ compositor,
+ )
+ .await?;
+ let nv12_converter = self.nv12_converter.get_or_insert_with(|| {
+ frame_pipeline::RgbaToNv12Converter::new(&self.constants.device)
+ });
+
+ match finish_encoder_nv12_pooled(
+ session,
+ nv12_converter,
+ &self.constants.device,
+ &self.constants.queue,
+ &incoming.uniforms,
+ encoder,
+ Some(&mut self.nv12_buffer_pool),
+ )
+ .await
+ {
+ Ok(frame) => return Ok(frame),
+ Err(RenderingError::BufferMapWaitingFailed) => {
+ last_error = Some(RenderingError::BufferMapWaitingFailed);
+ }
+ Err(RenderingError::BufferMapFailed(error)) => {
+ last_error = Some(RenderingError::BufferMapFailed(error));
+ }
+ Err(error) => return Err(error),
+ }
+ }
+
+ Err(last_error.unwrap_or(RenderingError::BufferMapWaitingFailed))
+ }
+
async fn render_nv12_software_path(
&mut self,
segment_frames: DecodedSegmentFrames,
@@ -4284,6 +4865,13 @@ impl<'a> FrameRenderer<'a> {
return Ok(None);
};
+ Ok(Some(self.convert_rgba_to_nv12(rgba_frame)))
+ }
+
+ fn convert_rgba_to_nv12(
+ &mut self,
+ rgba_frame: RenderedFrame,
+ ) -> frame_pipeline::Nv12RenderedFrame {
let width = rgba_frame.width;
let height = rgba_frame.height;
let padded_bytes_per_row = rgba_frame.padded_bytes_per_row;
@@ -4347,7 +4935,7 @@ impl<'a> FrameRenderer<'a> {
}
}
- Ok(Some(frame_pipeline::Nv12RenderedFrame {
+ frame_pipeline::Nv12RenderedFrame {
data: self.nv12_buffer_pool.wrap(nv12_buf),
width,
height,
@@ -4355,7 +4943,7 @@ impl<'a> FrameRenderer<'a> {
frame_number,
target_time_ns,
format: frame_pipeline::GpuOutputFormat::Nv12,
- }))
+ }
}
async fn render_nv12_gpu_path(
@@ -5078,6 +5666,83 @@ async fn produce_frame_with_timings(
Ok((frame, timings))
}
+async fn produce_transition_texture(
+ constants: &RenderVideoConstants,
+ outgoing: &TransitionRenderInput<'_>,
+ incoming: &TransitionRenderInput<'_>,
+ transition: (ClipTransitionType, f32),
+ layers: &mut RendererLayers,
+ session: &mut RenderSession,
+ compositor: &TransitionCompositor,
+) -> Result<wgpu::CommandEncoder, RenderingError> {
+ let mut outgoing_encoder =
+ constants
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("Outgoing Transition Render Encoder"),
+ });
+ layers
+ .prepare_with_encoder(
+ constants,
+ &outgoing.uniforms,
+ &outgoing.segment_frames,
+ outgoing.cursor,
+ &mut outgoing_encoder,
+ outgoing.render_display,
+ )
+ .await?;
+ layers.render(
+ &constants.device,
+ &constants.queue,
+ &mut outgoing_encoder,
+ session,
+ &outgoing.uniforms,
+ outgoing.render_display,
+ );
+ compositor.capture_outgoing(&mut outgoing_encoder, session.current_texture());
+ constants
+ .queue
+ .submit(std::iter::once(outgoing_encoder.finish()));
+
+ let mut incoming_encoder =
+ constants
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("Incoming Transition Render Encoder"),
+ });
+ layers
+ .prepare_with_encoder(
+ constants,
+ &incoming.uniforms,
+ &incoming.segment_frames,
+ incoming.cursor,
+ &mut incoming_encoder,
+ incoming.render_display,
+ )
+ .await?;
+ layers.render(
+ &constants.device,
+ &constants.queue,
+ &mut incoming_encoder,
+ session,
+ &incoming.uniforms,
+ incoming.render_display,
+ );
+ compositor.capture_incoming_and_render(
+ &constants.queue,
+ &mut incoming_encoder,
+ session.current_texture(),
+ session.current_texture_view(),
+ TransitionParameters {
+ kind: transition.0,
+ progress: transition.1,
+ opaque: outgoing.render_display || incoming.render_display,
+ },
+ );
+
+ Ok(incoming_encoder)
+}
+
fn blur_mode_from_config(
config: &cap_project::BackgroundBlurConfig,
) -> Option<cap_camera_effects::BlurMode> {
diff --git a/crates/rendering/src/shaders/transition.wgsl b/crates/rendering/src/shaders/transition.wgsl
new file mode 100644
index 000000000..b0d89d63b
--- /dev/null
+++ b/crates/rendering/src/shaders/transition.wgsl
@@ -0,0 +1,47 @@
+struct TransitionUniforms {
+ progress: f32,
+ kind: u32,
+ opaque: u32,
+ padding: u32,
+};
+
+@group(0) @binding(0) var<uniform> uniforms: TransitionUniforms;
+@group(0) @binding(1) var outgoing_texture: texture_2d<f32>;
+@group(0) @binding(2) var incoming_texture: texture_2d<f32>;
+@group(0) @binding(3) var frame_sampler: sampler;
+
+struct VertexOutput {
+ @builtin(position) position: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
+ var positions = array<vec2<f32>, 3>(
+ vec2<f32>(-1.0, -1.0),
+ vec2<f32>(3.0, -1.0),
+ vec2<f32>(-1.0, 3.0),
+ );
+ var output: VertexOutput;
+ output.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
+ let uv = (positions[vertex_index] + 1.0) * 0.5;
+ output.uv = vec2<f32>(uv.x, 1.0 - uv.y);
+ return output;
+}
+
+@fragment
+fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
+ let outgoing = textureSample(outgoing_texture, frame_sampler, input.uv);
+ let incoming = textureSample(incoming_texture, frame_sampler, input.uv);
+ if uniforms.kind == 0u {
+ return mix(outgoing, incoming, uniforms.progress);
+ }
+
+ let outgoing_weight = max(1.0 - uniforms.progress * 2.0, 0.0);
+ let incoming_weight = max(uniforms.progress * 2.0 - 1.0, 0.0);
+ let black_weight = 1.0 - outgoing_weight - incoming_weight;
+ let black_alpha = select(0.0, 1.0, uniforms.opaque != 0u);
+ return outgoing * outgoing_weight
+ + incoming * incoming_weight
+ + vec4<f32>(0.0, 0.0, 0.0, black_alpha) * black_weight;
+}
diff --git a/crates/rendering/src/transition.rs b/crates/rendering/src/transition.rs
new file mode 100644
index 000000000..0b3937e5f
--- /dev/null
+++ b/crates/rendering/src/transition.rs
@@ -0,0 +1,289 @@
+use cap_project::ClipTransitionType;
+use wgpu::util::DeviceExt;
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+struct TransitionUniforms {
+ progress: f32,
+ kind: u32,
+ opaque: u32,
+ padding: u32,
+}
+
+struct TransitionTextures {
+ outgoing: wgpu::Texture,
+ incoming: wgpu::Texture,
+ bind_group: wgpu::BindGroup,
+ width: u32,
+ height: u32,
+}
+
+pub struct TransitionCompositor {
+ bind_group_layout: wgpu::BindGroupLayout,
+ pipeline: wgpu::RenderPipeline,
+ sampler: wgpu::Sampler,
+ uniforms_buffer: wgpu::Buffer,
+ textures: Option<TransitionTextures>,
+}
+
+pub struct TransitionParameters {
+ pub kind: ClipTransitionType,
+ pub progress: f32,
+ pub opaque: bool,
+}
+
+impl TransitionCompositor {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Transition Compositor Bind Group Layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::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::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 3,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Transition Compositor Pipeline Layout"),
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ });
+ let shader = device.create_shader_module(wgpu::include_wgsl!("shaders/transition.wgsl"));
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Transition Compositor Pipeline"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: None,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("Transition Compositor Sampler"),
+ 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,
+ ..Default::default()
+ });
+ let uniforms_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Transition Compositor Uniforms"),
+ contents: bytemuck::bytes_of(&TransitionUniforms {
+ progress: 0.0,
+ kind: 0,
+ opaque: 1,
+ padding: 0,
+ }),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+
+ Self {
+ bind_group_layout,
+ pipeline,
+ sampler,
+ uniforms_buffer,
+ textures: None,
+ }
+ }
+
+ pub fn ensure_size(&mut self, device: &wgpu::Device, width: u32, height: u32) {
+ if self
+ .textures
+ .as_ref()
+ .is_some_and(|textures| textures.width == width && textures.height == height)
+ {
+ return;
+ }
+
+ let create_texture = |label| {
+ device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(label),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ })
+ };
+ let outgoing = create_texture("Transition Outgoing Texture");
+ let incoming = create_texture("Transition Incoming Texture");
+ let outgoing_view = outgoing.create_view(&wgpu::TextureViewDescriptor::default());
+ let incoming_view = incoming.create_view(&wgpu::TextureViewDescriptor::default());
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Transition Compositor Bind Group"),
+ layout: &self.bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: self.uniforms_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&outgoing_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(&incoming_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::Sampler(&self.sampler),
+ },
+ ],
+ });
+
+ self.textures = Some(TransitionTextures {
+ outgoing,
+ incoming,
+ bind_group,
+ width,
+ height,
+ });
+ }
+
+ pub fn capture_outgoing(&self, encoder: &mut wgpu::CommandEncoder, source: &wgpu::Texture) {
+ if let Some(textures) = &self.textures {
+ copy_texture(
+ encoder,
+ source,
+ &textures.outgoing,
+ textures.width,
+ textures.height,
+ );
+ }
+ }
+
+ pub fn capture_incoming_and_render(
+ &self,
+ queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
+ source: &wgpu::Texture,
+ target: &wgpu::TextureView,
+ parameters: TransitionParameters,
+ ) {
+ let Some(textures) = &self.textures else {
+ return;
+ };
+ copy_texture(
+ encoder,
+ source,
+ &textures.incoming,
+ textures.width,
+ textures.height,
+ );
+ queue.write_buffer(
+ &self.uniforms_buffer,
+ 0,
+ bytemuck::bytes_of(&TransitionUniforms {
+ progress: parameters.progress.clamp(0.0, 1.0),
+ kind: match parameters.kind {
+ ClipTransitionType::CrossFade => 0,
+ ClipTransitionType::FadeThroughBlack => 1,
+ },
+ opaque: u32::from(parameters.opaque),
+ padding: 0,
+ }),
+ );
+
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("Transition Compositor Pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, &textures.bind_group, &[]);
+ pass.draw(0..3, 0..1);
+ }
+}
+
+fn copy_texture(
+ encoder: &mut wgpu::CommandEncoder,
+ source: &wgpu::Texture,
+ destination: &wgpu::Texture,
+ width: u32,
+ height: u32,
+) {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: source,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: destination,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+}
diff --git a/crates/rendering/src/zoom_spring.rs b/crates/rendering/src/zoom_spring.rs
index f1d42d1a2..baba573a0 100644
--- a/crates/rendering/src/zoom_spring.rs
+++ b/crates/rendering/src/zoom_spring.rs
@@ -255,6 +255,7 @@ struct TimeMapSegment {
timeline_end: f64,
recording_start: f64,
timescale: f64,
+ recording_clip: u32,
}
fn build_time_map(timeline: Option<&TimelineConfiguration>) -> Vec<TimeMapSegment> {
@@ -262,9 +263,14 @@ fn build_time_map(timeline: Option<&TimelineConfiguration>) -> Vec<TimeMapSegmen
return Vec::new();
};
- let mut accum = 0.0;
let mut map = Vec::with_capacity(timeline.segments.len());
- for segment in &timeline.segments {
+ let mut accum = 0.0;
+ for (segment_index, segment) in timeline.segments.iter().enumerate() {
+ if !timeline.transitions.is_empty() {
+ accum -= timeline
+ .effective_transition(segment_index)
+ .map_or(0.0, |transition| transition.duration);
+ }
let duration = segment.duration();
if !duration.is_finite() || duration <= 0.0 {
continue;
@@ -274,6 +280,7 @@ fn build_time_map(timeline: Option<&TimelineConfiguration>) -> Vec<TimeMapSegmen
timeline_end: accum + duration,
recording_start: segment.start,
timescale: segment.timescale,
+ recording_clip: segment.recording_clip,
});
accum += duration;
}
@@ -282,7 +289,12 @@ fn build_time_map(timeline: Option<&TimelineConfiguration>) -> Vec<TimeMapSegmen
/// Maps a timeline timestamp to recording seconds. Identity when no timeline
/// is configured; clamps to the nearest edit boundary outside the timeline.
-fn map_timeline_to_recording_secs(map: &[TimeMapSegment], timeline_secs: f64) -> f64 {
+fn map_timeline_to_recording_secs(
+ map: &[TimeMapSegment],
+ timeline_secs: f64,
+ recording_clip: Option<u32>,
+ prefer_outgoing: bool,
+) -> f64 {
let Some(first) = map.first() else {
return timeline_secs;
};
@@ -291,11 +303,26 @@ fn map_timeline_to_recording_secs(map: &[TimeMapSegment], timeline_secs: f64) ->
return first.recording_start;
}
- for segment in map {
- if timeline_secs < segment.timeline_end {
- return segment.recording_start
- + (timeline_secs - segment.timeline_start) * segment.timescale;
- }
+ let contains = |segment: &&TimeMapSegment| {
+ timeline_secs >= segment.timeline_start && timeline_secs < segment.timeline_end
+ };
+ let segment = recording_clip
+ .and_then(|recording_clip| {
+ if prefer_outgoing {
+ map.iter()
+ .filter(contains)
+ .find(|segment| segment.recording_clip == recording_clip)
+ } else {
+ map.iter()
+ .rev()
+ .filter(contains)
+ .find(|segment| segment.recording_clip == recording_clip)
+ }
+ })
+ .or_else(|| map.iter().rev().find(contains));
+ if let Some(segment) = segment {
+ return segment.recording_start
+ + (timeline_secs - segment.timeline_start) * segment.timescale;
}
let last = map.last().expect("map is non-empty");
@@ -344,10 +371,17 @@ pub struct ZoomTransformTimeline {
/// Auto segments, `None` for Manual ones.
clusters: Vec<Option<Vec<ClickCluster>>>,
time_map: Vec<TimeMapSegment>,
+ recording_clip: Option<u32>,
+ prefer_outgoing: bool,
/// Total number of samples covering [0, duration] plus one lerp partner.
total_samples: usize,
}
+struct RecordingClipSelection {
+ recording_clip: Option<u32>,
+ prefer_outgoing: bool,
+}
+
impl ZoomTransformTimeline {
pub fn new(
zoom_segments: &[ZoomSegment],
@@ -357,6 +391,33 @@ impl ZoomTransformTimeline {
duration_secs: f64,
crop: Option<CursorCropMap>,
) -> Self {
+ Self::new_for_recording_clip(
+ zoom_segments,
+ timeline,
+ cursor_events,
+ spring,
+ duration_secs,
+ crop,
+ RecordingClipSelection {
+ recording_clip: None,
+ prefer_outgoing: false,
+ },
+ )
+ }
+
+ fn new_for_recording_clip(
+ zoom_segments: &[ZoomSegment],
+ timeline: Option<&TimelineConfiguration>,
+ cursor_events: &CursorEvents,
+ spring: ScreenMovementSpring,
+ duration_secs: f64,
+ crop: Option<CursorCropMap>,
+ selection: RecordingClipSelection,
+ ) -> Self {
+ let RecordingClipSelection {
+ recording_clip,
+ prefer_outgoing,
+ } = selection;
let mut zoom_segments = zoom_segments.to_vec();
zoom_segments.sort_by(|a, b| a.start.total_cmp(&b.start).then(a.end.total_cmp(&b.end)));
@@ -365,9 +426,19 @@ impl ZoomTransformTimeline {
.iter()
.map(|segment| match segment.mode {
ZoomMode::Auto => {
- let recording_start = map_timeline_to_recording_secs(&time_map, segment.start);
- let recording_end =
- map_timeline_to_recording_secs(&time_map, segment.end).max(recording_start);
+ let recording_start = map_timeline_to_recording_secs(
+ &time_map,
+ segment.start,
+ recording_clip,
+ prefer_outgoing,
+ );
+ let recording_end = map_timeline_to_recording_secs(
+ &time_map,
+ segment.end,
+ recording_clip,
+ prefer_outgoing,
+ )
+ .max(recording_start);
Some(build_clusters(
cursor_events,
recording_start,
@@ -388,6 +459,23 @@ impl ZoomTransformTimeline {
// One sample per step across the duration, plus one trailing sample so
// a lookup right at the end always has a lerp partner.
let total_samples = (duration_secs * 1000.0 / STEP_MS).ceil() as usize + 2;
+ if zoom_segments.is_empty() {
+ return Self {
+ samples: vec![TimelineSample {
+ amount: 1.0,
+ center: XY::new(0.5, 0.5),
+ activity: 0.0,
+ snapped: false,
+ }],
+ state: None,
+ zoom_segments,
+ clusters,
+ time_map,
+ recording_clip,
+ prefer_outgoing,
+ total_samples: 1,
+ };
+ }
let spring_config = SpringMassDamperSimulationConfig {
tension: spring.stiffness,
@@ -401,6 +489,8 @@ impl ZoomTransformTimeline {
zoom_segments,
clusters,
time_map,
+ recording_clip,
+ prefer_outgoing,
total_samples,
};
@@ -444,13 +534,65 @@ impl ZoomTransformTimeline {
cursor_events: &CursorEvents,
duration_secs: f64,
screen_size: XY<u32>,
+ ) -> Self {
+ Self::from_project_for_recording_clip(
+ project,
+ cursor_events,
+ duration_secs,
+ screen_size,
+ None,
+ false,
+ )
+ }
+
+ pub fn from_project_for_clip(
+ project: &ProjectConfiguration,
+ cursor_events: &CursorEvents,
+ duration_secs: f64,
+ screen_size: XY<u32>,
+ recording_clip: u32,
+ ) -> Self {
+ Self::from_project_for_recording_clip(
+ project,
+ cursor_events,
+ duration_secs,
+ screen_size,
+ Some(recording_clip),
+ false,
+ )
+ }
+
+ pub fn from_project_for_outgoing_clip(
+ project: &ProjectConfiguration,
+ cursor_events: &CursorEvents,
+ duration_secs: f64,
+ screen_size: XY<u32>,
+ recording_clip: u32,
+ ) -> Self {
+ Self::from_project_for_recording_clip(
+ project,
+ cursor_events,
+ duration_secs,
+ screen_size,
+ Some(recording_clip),
+ true,
+ )
+ }
+
+ fn from_project_for_recording_clip(
+ project: &ProjectConfiguration,
+ cursor_events: &CursorEvents,
+ duration_secs: f64,
+ screen_size: XY<u32>,
+ recording_clip: Option<u32>,
+ prefer_outgoing: bool,
) -> Self {
let crop = project
.background
.crop
.as_ref()
.and_then(|crop| CursorCropMap::from_crop(crop, screen_size));
- Self::new(
+ Self::new_for_recording_clip(
project
.timeline
.as_ref()
@@ -461,6 +603,10 @@ impl ZoomTransformTimeline {
project.screen_movement_spring,
duration_secs,
crop,
+ RecordingClipSelection {
+ recording_clip,
+ prefer_outgoing,
+ },
)
}
@@ -635,8 +781,12 @@ impl ZoomTransformTimeline {
(f64::from(x).clamp(0.0, 1.0), f64::from(y).clamp(0.0, 1.0))
}
ZoomMode::Auto => {
- let recording_ms =
- map_timeline_to_recording_secs(&self.time_map, timeline_secs) * 1000.0;
+ let recording_ms = map_timeline_to_recording_secs(
+ &self.time_map,
+ timeline_secs,
+ self.recording_clip,
+ self.prefer_outgoing,
+ ) * 1000.0;
let focus = self.clusters[index]
.as_deref()
.and_then(|clusters| cluster_center_at_time(clusters, recording_ms))
@@ -672,7 +822,8 @@ impl ZoomTransformTimeline {
#[cfg(test)]
mod tests {
use cap_project::{
- CursorClickEvent, CursorMoveEvent, GlideDirection, TimelineSegment, ZoomMode,
+ ClipTransition, ClipTransitionType, CursorClickEvent, CursorMoveEvent, GlideDirection,
+ TimelineSegment, ZoomMode,
};
use super::*;
@@ -735,6 +886,16 @@ mod tests {
)
}
+ #[test]
+ fn empty_zoom_timeline_stays_constant_without_precompute_work() {
+ let mut timeline = timeline_for(&[], &CursorEvents::default(), 60.0 * 60.0);
+ timeline.ensure_precomputed_until(60.0 * 60.0);
+
+ assert!(timeline.state.is_none());
+ assert_eq!(timeline.samples.len(), 1);
+ assert_eq!(timeline.sample(60.0 * 60.0).display_amount(), 1.0);
+ }
+
/// Max |value delta| and |slope delta| between adjacent 8ms sample
/// intervals across the whole precomputed range, measured on the VISIBLE
/// viewport rect (bounds corners + amount), not the latent channels: the
@@ -1331,6 +1492,7 @@ mod tests {
end: 20.0,
name: None,
}],
+ transitions: vec![],
zoom_segments: vec![],
scene_segments: vec![],
mask_segments: vec![],
@@ -1374,6 +1536,58 @@ mod tests {
);
}
+ #[test]
+ fn timeline_mapping_uses_incoming_source_during_transition() {
+ let timeline = TimelineConfiguration {
+ segments: vec![
+ TimelineSegment {
+ recording_clip: 0,
+ timescale: 1.0,
+ start: 0.0,
+ end: 4.0,
+ name: None,
+ },
+ TimelineSegment {
+ recording_clip: 0,
+ timescale: 1.0,
+ start: 10.0,
+ end: 14.0,
+ name: None,
+ },
+ ],
+ transitions: vec![ClipTransition {
+ segment_index: 1,
+ kind: ClipTransitionType::CrossFade,
+ duration: 0.5,
+ }],
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ };
+ let map = build_time_map(Some(&timeline));
+
+ assert_eq!(
+ map_timeline_to_recording_secs(&map, 3.25, None, false),
+ 3.25
+ );
+ assert_eq!(
+ map_timeline_to_recording_secs(&map, 3.75, None, false),
+ 10.25
+ );
+ assert_eq!(
+ map_timeline_to_recording_secs(&map, 3.75, Some(0), false),
+ 10.25
+ );
+ assert_eq!(
+ map_timeline_to_recording_secs(&map, 3.75, Some(0), true),
+ 3.75
+ );
+ }
+
#[test]
fn crop_map_identity_cases() {
let screen = XY::new(1000u32, 1000u32);