Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

timeline zoom + pan (#309)

Brendan Allanfa735f60d2e8
diff --git a/Cargo.lock b/Cargo.lock
index 1d80d2136..4f9724745 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -182,6 +182,16 @@ dependencies = [
"windows-sys 0.59.0",
]
+[[package]]
+name = "any_spawner"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41058deaa38c9d9dd933d6d238d825227cffa668e2839b52879f6619c63eee3b"
+dependencies = [
+ "futures",
+ "thiserror 2.0.6",
+]
+
[[package]]
name = "anyhow"
version = "1.0.86"
@@ -1121,6 +1131,7 @@ dependencies = [
"image 0.25.5",
"log",
"pretty_assertions",
+ "reactive_graph",
"serde",
"specta",
"thiserror 1.0.63",
@@ -3161,6 +3172,12 @@ dependencies = [
"syn 2.0.90",
]
+[[package]]
+name = "guardian"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17e2ac29387b1aa07a1e448f7bb4f35b500787971e965b02842b900afa5c8f6f"
+
[[package]]
name = "h2"
version = "0.4.6"
@@ -3706,10 +3723,11 @@ checksum = "f5d4a7da358eff58addd2877a45865158f0d78c911d43a5784ceb7bbf52833b0"
[[package]]
name = "js-sys"
-version = "0.3.70"
+version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a"
+checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f"
dependencies = [
+ "once_cell",
"wasm-bindgen",
]
@@ -4959,6 +4977,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "or_poisoned"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c04f5d74368e4d0dfe06c45c8627c81bd7c317d52762d118fb9b3076f6420fd"
+
[[package]]
name = "ordered-multimap"
version = "0.7.3"
@@ -5254,9 +5278,9 @@ dependencies = [
[[package]]
name = "pin-project-lite"
-version = "0.2.14"
+version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "pin-utils"
@@ -5757,6 +5781,25 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "reactive_graph"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "059aede5acae8f5c25b1d34b6df34700006418b3c493db3698b7ebcd4a8a6287"
+dependencies = [
+ "any_spawner",
+ "async-lock",
+ "futures",
+ "guardian",
+ "or_poisoned",
+ "pin-project-lite",
+ "rustc-hash 2.0.0",
+ "send_wrapper",
+ "slotmap",
+ "thiserror 2.0.6",
+ "web-sys",
+]
+
[[package]]
name = "readkey"
version = "0.2.1"
@@ -6239,6 +6282,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "send_wrapper"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
+dependencies = [
+ "futures-core",
+]
+
[[package]]
name = "sentry"
version = "0.34.0"
@@ -8400,24 +8452,24 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
-version = "0.2.93"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5"
+checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5"
dependencies = [
"cfg-if 1.0.0",
"once_cell",
+ "rustversion",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
-version = "0.2.93"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b"
+checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6"
dependencies = [
"bumpalo",
"log",
- "once_cell",
"proc-macro2",
"quote",
"syn 2.0.90",
@@ -8438,9 +8490,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.93"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf"
+checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -8448,9 +8500,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.93"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836"
+checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de"
dependencies = [
"proc-macro2",
"quote",
@@ -8461,9 +8513,12 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.93"
+version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484"
+checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d"
+dependencies = [
+ "unicode-ident",
+]
[[package]]
name = "wasm-streams"
@@ -8540,9 +8595,9 @@ dependencies = [
[[package]]
name = "web-sys"
-version = "0.3.70"
+version = "0.3.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0"
+checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2"
dependencies = [
"js-sys",
"wasm-bindgen",
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 14f720d20..8eb573ce9 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -11,6 +11,7 @@ import {
createSignal,
on,
onMount,
+ untrack,
} from "solid-js";
import { createStore } from "solid-js/store";
import { createMutation } from "@tanstack/solid-query";
@@ -94,7 +95,9 @@ function Inner() {
events.editorStateChanged.listen((e) => {
renderFrame.clear();
- setPlaybackTime(e.payload.playhead_position / FPS);
+ untrack(() => {
+ setPlaybackTime(e.payload.playhead_position / FPS);
+ });
});
} catch (error) {
console.error("Failed to initialize editor:", error);
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 4e230e5f9..1690e6951 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -11,9 +11,9 @@ import {
createEffect,
createResource,
createSignal,
+ on,
} from "solid-js";
import { reconcile } from "solid-js/store";
-import { useNavigate } from "@solidjs/router";
import { type AspectRatio, commands } from "~/utils/tauri";
import { FPS, OUTPUT_SIZE, useEditorContext } from "./context";
@@ -26,13 +26,13 @@ import {
MenuItem,
MenuItemList,
PopperContent,
+ Slider,
dropdownContainerClasses,
topLeftAnimateClasses,
} from "./ui";
import { formatTime } from "./utils";
export function Player() {
- const navigate = useNavigate();
const [auth] = createResource(() => authStore.get());
const {
project,
@@ -44,10 +44,14 @@ export function Player() {
playbackTime,
setPlaybackTime,
previewTime,
+ setPreviewTime,
playing,
setPlaying,
split,
setSplit,
+ totalDuration,
+ state,
+ zoomOutLimit,
} = useEditorContext();
let canvasRef!: HTMLCanvasElement;
@@ -76,12 +80,6 @@ export function Player() {
</EditorButton>
);
- const totalDuration = () =>
- project.timeline?.segments.reduce(
- (acc, s) => acc + (s.end - s.start) / s.timescale,
- 0
- ) ?? editorInstance.recordingDuration;
-
const isAtEnd = () => {
const total = totalDuration();
return total > 0 && total - playbackTime() <= 0.1;
@@ -109,6 +107,7 @@ export function Player() {
await commands.startPlayback(FPS, OUTPUT_SIZE);
setPlaying(true);
}
+ if (playing()) setPreviewTime();
} catch (error) {
console.error("Error handling play/pause:", error);
setPlaying(false);
@@ -233,7 +232,7 @@ export function Player() {
}}
</Show>
</div>
- <div class="flex flex-row items-center p-[0.75rem] z-10 bg-gray-50 justify-between">
+ <div class="flex flex-row items-center p-[0.75rem] gap-[0.5rem] z-10 bg-gray-50 justify-between">
<div class="flex-1 flex items-center">
<Show when={!auth()?.plan?.upgraded}>
<EditorButton
@@ -243,15 +242,16 @@ export function Player() {
Remove watermark
</EditorButton>
</Show>
+ <div class="flex-1" />
+ <Time seconds={Math.max(previewTime() ?? playbackTime(), 0)} />
</div>
- <div class="flex-1 flex flex-row items-center justify-center gap-[0.5rem] text-gray-400 text-[0.875rem]">
- <span>{formatTime(playbackTime())}</span>
+ <div class="flex flex-row items-center justify-center text-gray-400 text-[0.875rem]">
<button
type="button"
onClick={async () => {
setPlaying(false);
await commands.stopPlayback();
- await commands.setPlayheadPosition(0);
+ setPlaybackTime(0);
}}
>
<IconCapFrameFirst class="size-[1.2rem]" />
@@ -272,21 +272,38 @@ export function Player() {
onClick={async () => {
setPlaying(false);
await commands.stopPlayback();
- await commands.setPlayheadPosition(
- Math.floor(totalDuration() * FPS)
- );
+ setPlaybackTime(totalDuration());
}}
>
<IconCapFrameLast class="size-[1rem]" />
</button>
- <span>{formatTime(totalDuration())}</span>
</div>
- <div class="flex-1 flex flex-row justify-end">
+ <div class="flex-1 flex flex-row justify-end items-center gap-2">
+ <Time seconds={totalDuration()} />
+ <div class="flex-1" />
{window.FLAGS.split ? (
splitButton()
) : (
<ComingSoonTooltip>{splitButton()}</ComingSoonTooltip>
)}
+ <Slider
+ class="w-24"
+ minValue={0}
+ maxValue={1}
+ step={0.001}
+ value={[
+ Math.min(
+ Math.max(1 - state.timelineTransform.zoom / zoomOutLimit(), 0),
+ 1
+ ),
+ ]}
+ onChange={([v]) => {
+ state.timelineTransform.updateZoom(
+ (1 - v) * zoomOutLimit(),
+ playbackTime()
+ );
+ }}
+ />
</div>
</div>
</div>
@@ -499,3 +516,11 @@ function PresetsDropdown() {
</KDropdownMenu>
);
}
+
+function Time(props: { seconds: number; fps?: number }) {
+ return (
+ <span class="text-gray-400 text-[0.875rem] tabular-nums">
+ {formatTime(props.seconds, props.fps ?? FPS)}
+ </span>
+ );
+}
diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsx
index c55b15d31..7c66bd5dc 100644
--- a/apps/desktop/src/routes/editor/Timeline.tsx
+++ b/apps/desktop/src/routes/editor/Timeline.tsx
@@ -3,10 +3,13 @@ import { createElementBounds } from "@solid-primitives/bounds";
import {
ComponentProps,
For,
+ Index,
+ Setter,
Show,
batch,
createRoot,
createSignal,
+ on,
onMount,
} from "solid-js";
import {
@@ -31,19 +34,29 @@ import {
} from "./context";
import { formatTime } from "./utils";
+type ZoomSegmentDragState =
+ | { type: "idle" }
+ | { type: "movePending" }
+ | { type: "moving" };
+
+const MAX_TIMELINE_MARKINGS = 20;
+const TIMELINE_MARKING_RESOLUTIONS = [0.5, 1, 2.5, 5, 10, 30];
+
export function Timeline() {
const {
project,
setProject,
- videoId,
editorInstance,
playbackTime,
+ setPlaybackTime,
previewTime,
setPreviewTime,
history,
split,
setState,
playing,
+ totalDuration,
+ state,
} = useEditorContext();
const duration = () => editorInstance.recordingDuration;
@@ -51,6 +64,9 @@ export function Timeline() {
const [timelineRef, setTimelineRef] = createSignal<HTMLDivElement>();
const timelineBounds = createElementBounds(timelineRef);
+ const secsPerPixel = () =>
+ state.timelineTransform.zoom / (timelineBounds.width ?? 1);
+
onMount(() => {
if (!project.timeline) {
const resume = history.pause();
@@ -69,9 +85,6 @@ export function Timeline() {
const xPadding = 12;
- const segments = (): Array<TimelineSegment> =>
- project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }];
-
if (
!project.timeline?.zoomSegments ||
project.timeline.zoomSegments.length < 1
@@ -92,25 +105,27 @@ export function Timeline() {
);
}
- let zoomSegmentDragState = { type: "idle" } as
- | { type: "idle" }
- | { type: "movePending" }
- | { type: "moving" };
-
- function handleUpdatePlayhead(e: MouseEvent) {
- const { left, width } = timelineBounds;
- if (zoomSegmentDragState.type !== "moving")
- commands.setPlayheadPosition(
- Math.round(
- FPS *
- editorInstance.recordingDuration *
- ((e.clientX - left!) / width!)
+ let zoomSegmentDragState = { type: "idle" } as ZoomSegmentDragState;
+
+ async function handleUpdatePlayhead(e: MouseEvent) {
+ const { left } = timelineBounds;
+ if (zoomSegmentDragState.type !== "moving") {
+ setPlaybackTime(
+ Math.min(
+ secsPerPixel() * (e.clientX - left!) +
+ state.timelineTransform.position,
+ totalDuration()
)
);
+ }
}
return (
- <TimelineContextProvider duration={duration()}>
+ <TimelineContextProvider
+ duration={duration()}
+ secsPerPixel={secsPerPixel()}
+ timelineBounds={timelineBounds}
+ >
<div
class="py-[2rem] relative overflow-hidden"
style={{
@@ -129,15 +144,41 @@ export function Timeline() {
});
}}
onMouseMove={(e) => {
- const { left, width } = timelineBounds;
+ const { left } = timelineBounds;
+ if (playing()) return;
setPreviewTime(
- editorInstance.recordingDuration * ((e.clientX - left!) / width!)
+ state.timelineTransform.position +
+ secsPerPixel() * (e.clientX - left!)
);
}}
onMouseLeave={() => {
setPreviewTime(undefined);
}}
+ onWheel={(e) => {
+ // pinch zoom or ctrl + scroll
+ if (e.ctrlKey) {
+ console.log(e);
+ batch(() => {
+ const zoomDelta =
+ (e.deltaY * Math.sqrt(state.timelineTransform.zoom)) / 30;
+
+ const newZoom = state.timelineTransform.zoom + zoomDelta;
+
+ state.timelineTransform.updateZoom(
+ newZoom,
+ previewTime() ?? playbackTime()
+ );
+ });
+ }
+ // scroll
+ else {
+ state.timelineTransform.setPosition(
+ state.timelineTransform.position + secsPerPixel() * e.deltaX
+ );
+ }
+ }}
>
+ <TimelineMarkings />
<Show when={!playing() && previewTime()}>
{(time) => (
<div
@@ -148,8 +189,7 @@ export function Timeline() {
style={{
left: `${xPadding}px`,
transform: `translateX(${
- (time() / editorInstance.recordingDuration) *
- (timelineBounds.width ?? 0)
+ (time() - state.timelineTransform.position) / secsPerPixel()
}px)`,
}}
>
@@ -168,8 +208,8 @@ export function Timeline() {
style={{
left: `${xPadding}px`,
transform: `translateX(${Math.min(
- (playbackTime() / editorInstance.recordingDuration) *
- (timelineBounds.width ?? 0),
+ (playbackTime() - state.timelineTransform.position) /
+ secsPerPixel(),
timelineBounds.width ?? 0
)}px)`,
}}
@@ -177,105 +217,184 @@ export function Timeline() {
<div class="size-2 bg-red-300 rounded-full -mt-2 -ml-[calc(0.25rem-0.5px)]" />
</div>
</Show>
- <TrackRoot ref={setTimelineRef} isFreeForm={false}>
- <For each={segments()}>
- {(segment, i) => (
- <SegmentRoot
- class="border-blue-300"
- innerClass="ring-blue-300"
- segment={segment}
- onMouseDown={(e) => {
- if (!split()) return;
- e.stopPropagation();
+ <ClipTrack ref={setTimelineRef} />
+ <ZoomTrack
+ onDragStateChanged={(v) => {
+ zoomSegmentDragState = v;
+ }}
+ handleUpdatePlayhead={handleUpdatePlayhead}
+ />
+ </div>
+ </TimelineContextProvider>
+ );
+}
- const rect = e.currentTarget.getBoundingClientRect();
- const fraction = (e.clientX - rect.left) / rect.width;
+function TimelineMarkings() {
+ const { state } = useEditorContext();
+ const { secsPerPixel } = useTimelineContext();
- const splitTime =
- segment.start + fraction * (segment.end - segment.start);
+ const timelineMarkings = () => {
+ const resolution =
+ TIMELINE_MARKING_RESOLUTIONS.find(
+ (r) => state.timelineTransform.zoom / r <= MAX_TIMELINE_MARKINGS
+ ) ?? 30;
- setProject(
- "timeline",
- "segments",
- produce((segments) => {
- segments.splice(i() + 1, 0, {
- start: splitTime,
- end: segment.end,
- timescale: 1,
- recordingSegment: segment.recordingSegment,
- });
- segments[i()].end = splitTime;
- })
- );
- }}
- >
- <SegmentHandle
- class="bg-blue-300"
- onMouseDown={(downEvent) => {
- const start = segment.start;
-
- const maxSegmentDuration =
- editorInstance.recordings.segments[
- segment.recordingSegment ?? 0
- ].display.duration;
-
- const availableTimelineDuration =
- editorInstance.recordingDuration -
- segments().reduce(
- (acc, segment, segmentI) =>
- segmentI === i()
- ? acc
- : acc +
- (segment.end - segment.start) / segment.timescale,
- 0
- );
+ const diff = state.timelineTransform.position % resolution;
- const maxDuration = Math.min(
- maxSegmentDuration,
- availableTimelineDuration
- );
+ return Array.from(
+ { length: (state.timelineTransform.zoom + 5) / resolution },
+ (_, i) => state.timelineTransform.position - diff + (i + 1) * resolution
+ );
+ };
- function update(event: MouseEvent) {
- const { width } = timelineBounds;
+ return (
+ <div class="text-xs relative h-4 mb-1">
+ <For each={timelineMarkings()}>
+ {(second) => (
+ <div
+ class="absolute bottom-1 left-0 text-center rounded-full w-1 h-1 bg-gray-400 text-gray-400"
+ style={{
+ left: `${
+ (second - state.timelineTransform.position) / secsPerPixel() - 1
+ }px`,
+ }}
+ >
+ <Show when={second % 1 === 0}>
+ <div class="absolute -top-4 -translate-x-1/2">
+ 0:{second.toString().padStart(2, "0")}
+ </div>
+ </Show>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
- const newStart =
- start +
- ((event.clientX - downEvent.clientX) / width!) *
- duration();
+function ClipTrack(props: Pick<ComponentProps<"div">, "ref">) {
+ const {
+ project,
+ setProject,
+ editorInstance,
+ history,
+ split,
+ state,
+ totalDuration,
+ previewTime,
+ } = useEditorContext();
- setProject(
- "timeline",
- "segments",
- i(),
- "start",
- Math.min(
- Math.max(
- Math.max(newStart, 0),
- segment.end - maxDuration
- ),
- segment.end - 1
- )
- );
- }
+ const { secsPerPixel, duration } = useTimelineContext();
- const resumeHistory = history.pause();
- createRoot((dispose) => {
- createEventListenerMap(window, {
- mousemove: update,
- mouseup: (e) => {
- dispose();
- resumeHistory();
- update(e);
- },
- });
- });
- }}
- />
- <SegmentContent class="bg-blue-50 justify-between">
- <span class="text-black-transparent-60 text-[0.625rem] mt-auto">
- {formatTime(segment.start)}
- </span>
- {/* <Show when={segments().length > 1}>
+ const segments = (): Array<TimelineSegment> =>
+ project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }];
+
+ function onHandleReleased() {
+ if (
+ state.timelineTransform.position + state.timelineTransform.zoom >
+ totalDuration() + 4
+ ) {
+ state.timelineTransform.updateZoom(totalDuration(), previewTime()!);
+ }
+ }
+
+ return (
+ <TrackRoot ref={props.ref}>
+ <For each={segments()}>
+ {(segment, i) => (
+ <SegmentRoot
+ class="border-blue-300"
+ innerClass="ring-blue-300"
+ segment={segment}
+ onMouseDown={(e) => {
+ if (!split()) return;
+ e.stopPropagation();
+
+ const rect = e.currentTarget.getBoundingClientRect();
+ const fraction = (e.clientX - rect.left) / rect.width;
+
+ const splitTime =
+ segment.start + fraction * (segment.end - segment.start);
+
+ setProject(
+ "timeline",
+ "segments",
+ produce((segments) => {
+ segments.splice(i() + 1, 0, {
+ start: splitTime,
+ end: segment.end,
+ timescale: 1,
+ recordingSegment: segment.recordingSegment,
+ });
+ segments[i()].end = splitTime;
+ })
+ );
+ }}
+ >
+ <SegmentHandle
+ class="bg-blue-300"
+ onMouseDown={(downEvent) => {
+ const start = segment.start;
+
+ const maxSegmentDuration =
+ editorInstance.recordings.segments[
+ segment.recordingSegment ?? 0
+ ].display.duration;
+
+ const availableTimelineDuration =
+ editorInstance.recordingDuration -
+ segments().reduce(
+ (acc, segment, segmentI) =>
+ segmentI === i()
+ ? acc
+ : acc +
+ (segment.end - segment.start) / segment.timescale,
+ 0
+ );
+
+ const maxDuration = Math.min(
+ maxSegmentDuration,
+ availableTimelineDuration
+ );
+
+ function update(event: MouseEvent) {
+ const newStart =
+ start +
+ (event.clientX - downEvent.clientX) * secsPerPixel();
+
+ setProject(
+ "timeline",
+ "segments",
+ i(),
+ "start",
+ Math.min(
+ Math.max(
+ Math.max(newStart, 0),
+ segment.end - maxDuration
+ ),
+ segment.end - 1
+ )
+ );
+ }
+
+ const resumeHistory = history.pause();
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: update,
+ mouseup: (e) => {
+ dispose();
+ resumeHistory();
+ update(e);
+ onHandleReleased();
+ },
+ });
+ });
+ }}
+ />
+ <SegmentContent class="bg-blue-50 justify-between">
+ <span class="text-black-transparent-60 text-[0.625rem] mt-auto">
+ {formatTime(segment.start)}
+ </span>
+ {/* <Show when={segments().length > 1}>
<button
onClick={() => {
setProject(
@@ -291,442 +410,417 @@ export function Timeline() {
<IconCapTrash class="size-4 text-gray-400 group-hover/button:text-gray-500 transition-colors" />
</button>
</Show> */}
- <span class="text-black-transparent-60 text-[0.625rem] mt-auto">
- {formatTime(segment.end)}
- </span>
- </SegmentContent>
- <SegmentHandle
- class="bg-blue-300"
- onMouseDown={(downEvent) => {
- const end = segment.end;
-
- const maxSegmentDuration =
- editorInstance.recordings.segments[
- segment.recordingSegment ?? 0
- ].display.duration;
-
- const availableTimelineDuration =
- editorInstance.recordingDuration -
- segments().reduce(
- (acc, segment, segmentI) =>
- segmentI === i()
- ? acc
- : acc +
- (segment.end - segment.start) / segment.timescale,
- 0
- );
+ <span class="text-black-transparent-60 text-[0.625rem] mt-auto">
+ {formatTime(segment.end)}
+ </span>
+ </SegmentContent>
+ <SegmentHandle
+ class="bg-blue-300"
+ onMouseDown={(downEvent) => {
+ const end = segment.end;
+
+ const maxSegmentDuration =
+ editorInstance.recordings.segments[
+ segment.recordingSegment ?? 0
+ ].display.duration;
+
+ const availableTimelineDuration =
+ editorInstance.recordingDuration -
+ segments().reduce(
+ (acc, segment, segmentI) =>
+ segmentI === i()
+ ? acc
+ : acc +
+ (segment.end - segment.start) / segment.timescale,
+ 0
+ );
- const maxDuration = Math.min(
- maxSegmentDuration,
- availableTimelineDuration
- );
+ function update(event: MouseEvent) {
+ const newEnd =
+ end + (event.clientX - downEvent.clientX) * secsPerPixel();
- function update(event: MouseEvent) {
- const { width } = timelineBounds;
+ setProject(
+ "timeline",
+ "segments",
+ i(),
+ "end",
+ Math.max(
+ Math.min(
+ newEnd,
+ maxSegmentDuration,
+ availableTimelineDuration
+ ),
+ segment.start + 1
+ )
+ );
+ }
- const newEnd =
- end +
- ((event.clientX - downEvent.clientX) / width!) *
- duration();
+ const resumeHistory = history.pause();
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: update,
+ mouseup: (e) => {
+ dispose();
+ resumeHistory();
+ update(e);
+ onHandleReleased();
+ },
+ });
+ });
+ }}
+ />
+ </SegmentRoot>
+ )}
+ </For>
+ </TrackRoot>
+ );
+}
- setProject(
- "timeline",
- "segments",
- i(),
- "end",
- Math.max(
- Math.min(
- newEnd,
- maxSegmentDuration,
- availableTimelineDuration
- ),
- segment.start + 1
- )
- );
- }
+function ZoomTrack(props: {
+ onDragStateChanged: (v: ZoomSegmentDragState) => void;
+ handleUpdatePlayhead: (e: MouseEvent) => void;
+}) {
+ const { project, setProject, history, setState, state } = useEditorContext();
+
+ const { duration, timelineBounds, secsPerPixel } = useTimelineContext();
+
+ const [hoveringSegment, setHoveringSegment] = createSignal(false);
+ const [hoveredTime, setHoveredTime] = createSignal<number>();
+
+ return (
+ <>
+ <div class="h-2 w-full" />
- const resumeHistory = history.pause();
- createRoot((dispose) => {
- createEventListenerMap(window, {
- mousemove: update,
- mouseup: (e) => {
- dispose();
- resumeHistory();
- update(e);
+ <TrackRoot
+ isFreeForm
+ onMouseMove={(e) => {
+ if (hoveringSegment()) {
+ setHoveredTime(undefined);
+ return;
+ }
+
+ const bounds = e.target.getBoundingClientRect()!;
+
+ let time =
+ (e.clientX - bounds.left) * secsPerPixel() +
+ state.timelineTransform.position;
+
+ const prevSegmentIndex = project.timeline?.zoomSegments?.findIndex(
+ (s) => s.end < time
+ );
+
+ const nextSegmentIndex = project.timeline?.zoomSegments?.findIndex(
+ (s) => time < s.start
+ );
+
+ if (nextSegmentIndex !== undefined) {
+ const nextSegment =
+ project.timeline?.zoomSegments?.[nextSegmentIndex];
+
+ if (prevSegmentIndex !== undefined && nextSegment) {
+ const prevSegment =
+ project.timeline?.zoomSegments?.[prevSegmentIndex];
+
+ if (prevSegment) {
+ const availableTime = nextSegment?.start - prevSegment?.end;
+
+ if (availableTime < 1) return;
+ }
+ }
+
+ if (nextSegment && nextSegment.start - time < 1) {
+ time = nextSegment.start - 1;
+ }
+ }
+
+ setHoveredTime(Math.min(time, duration() - 1));
+ }}
+ onMouseLeave={() => setHoveredTime()}
+ onMouseDown={(e) => {
+ createRoot((dispose) => {
+ createEventListener(e.currentTarget, "mouseup", (e) => {
+ dispose();
+
+ const time = hoveredTime();
+ if (time === undefined) return;
+
+ e.stopPropagation();
+ batch(() => {
+ setProject("timeline", "zoomSegments", (v) => v ?? []);
+ setProject(
+ "timeline",
+ "zoomSegments",
+ produce((zoomSegments) => {
+ zoomSegments ??= [];
+ zoomSegments.push({
+ start: time,
+ end: time + 1,
+ amount: 1.5,
+ mode: {
+ manual: {
+ x: 0.5,
+ y: 0.5,
},
- });
+ },
});
- }}
- />
- </SegmentRoot>
- )}
- </For>
- </TrackRoot>
- {((_) => {
- const [hoveringSegment, setHoveringSegment] = createSignal(false);
- const [hoveredTime, setHoveredTime] = createSignal<number>();
-
- return (
- <>
- <div class="h-2 w-full" />
-
- <TrackRoot
- isFreeForm
- onMouseMove={(e) => {
- if (hoveringSegment()) {
- setHoveredTime(undefined);
- return;
- }
+ })
+ );
+ });
+ });
+ });
+ }}
+ >
+ <Show
+ when={!useTrackContext().trackState.draggingSegment && hoveredTime()}
+ >
+ {(time) => (
+ <SegmentRoot
+ class="border-red-300 group pointer-events-none opacity-70"
+ innerClass="ring-red-300"
+ segment={{
+ start: time(),
+ end: time() + 1,
+ }}
+ >
+ <SegmentHandle class="bg-red-300" />
+ <SegmentContent class="bg-red-50" />
+ <SegmentHandle class="bg-red-300" />
+ </SegmentRoot>
+ )}
+ </Show>
+ <For each={project.timeline?.zoomSegments}>
+ {(segment, i) => {
+ const { setTrackState } = useTrackContext();
- const bounds = e.target.getBoundingClientRect()!;
+ const zoomPercentage = () => {
+ const amount = segment.amount;
+ return `${amount.toFixed(1)}x`;
+ };
- let time =
- ((e.clientX - bounds.left) / bounds.width) * duration();
+ const zoomSegments = () => project.timeline!.zoomSegments!;
- const prevSegmentIndex =
- project.timeline?.zoomSegments?.findIndex(
- (s) => s.end < time
- );
+ function createMouseDownDrag<T>(
+ setup: () => T,
+ _update: (e: MouseEvent, v: T, initialMouseX: number) => void
+ ) {
+ return function (downEvent: MouseEvent) {
+ downEvent.stopPropagation();
- const nextSegmentIndex =
- project.timeline?.zoomSegments?.findIndex(
- (s) => time < s.start
- );
+ const initial = setup();
- if (nextSegmentIndex !== undefined) {
- const nextSegment =
- project.timeline?.zoomSegments?.[nextSegmentIndex];
+ let moved = false;
+ let initialMouseX: null | number = null;
- if (prevSegmentIndex !== undefined && nextSegment) {
- const prevSegment =
- project.timeline?.zoomSegments?.[prevSegmentIndex];
+ setTrackState("draggingSegment", true);
- if (prevSegment) {
- const availableTime =
- nextSegment?.start - prevSegment?.end;
+ const resumeHistory = history.pause();
- if (availableTime < 1) return;
- }
- }
+ props.onDragStateChanged({ type: "movePending" });
- if (nextSegment && nextSegment.start - time < 1) {
- time = nextSegment.start - 1;
+ function finish(e: MouseEvent) {
+ resumeHistory();
+ if (!moved) {
+ e.stopPropagation();
+ setState("timelineSelection", {
+ type: "zoom",
+ index: i(),
+ });
+ props.handleUpdatePlayhead(e);
+ }
+ props.onDragStateChanged({ type: "idle" });
+ setTrackState("draggingSegment", false);
+ }
+
+ function update(event: MouseEvent) {
+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {
+ if (!moved) {
+ moved = true;
+ initialMouseX = event.clientX;
+ props.onDragStateChanged({
+ type: "moving",
+ });
}
}
- setHoveredTime(Math.min(time, duration() - 1));
- }}
- onMouseLeave={() => setHoveredTime()}
- onMouseDown={(e) => {
- createRoot((dispose) => {
- createEventListener(e.currentTarget, "mouseup", (e) => {
- dispose();
+ if (initialMouseX === null) return;
- const time = hoveredTime();
- if (time === undefined) return;
+ _update(event, initial, initialMouseX);
+ }
- e.stopPropagation();
- batch(() => {
- setProject("timeline", "zoomSegments", (v) => v ?? []);
- setProject(
- "timeline",
- "zoomSegments",
- produce((zoomSegments) => {
- zoomSegments ??= [];
- zoomSegments.push({
- start: time,
- end: time + 1,
- amount: 1.5,
- mode: {
- manual: {
- x: 0.5,
- y: 0.5,
- },
- },
- });
- })
- );
- });
- });
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: (e) => {
+ update(e);
+ },
+ mouseup: (e) => {
+ update(e);
+ finish(e);
+ dispose();
+ },
});
+ });
+ };
+ }
+
+ return (
+ <SegmentRoot
+ class="border-red-300 group bg-red-50 hover:bg-opacity-80 transition-colors"
+ innerClass="ring-red-300"
+ segment={segment}
+ onMouseEnter={() => {
+ setHoveringSegment(true);
+ }}
+ onMouseLeave={() => {
+ setHoveringSegment(false);
}}
>
- <Show
- when={
- !useTrackContext().trackState.draggingSegment &&
- hoveredTime()
- }
- >
- {(time) => (
- <SegmentRoot
- class="border-red-300 group pointer-events-none opacity-70"
- innerClass="ring-red-300"
- segment={{
- start: time(),
- end: time() + 1,
- }}
- >
- <SegmentHandle class="bg-red-300" />
- <SegmentContent class="bg-red-50" />
- <SegmentHandle class="bg-red-300" />
- </SegmentRoot>
- )}
- </Show>
- <For each={project.timeline?.zoomSegments}>
- {(segment, i) => {
- const { setTrackState, trackBounds } = useTrackContext();
-
- const zoomPercentage = () => {
- const amount = segment.amount;
- return `${amount.toFixed(1)}x`;
- };
-
- const zoomSegments = () => project.timeline!.zoomSegments!;
-
- function handleSegmentMouseUp(e: MouseEvent) {}
-
- function createMouseDownDrag<T>(
- setup: () => T,
- _update: (
- e: MouseEvent,
- v: T,
- initialMouseX: number
- ) => void
- ) {
- return function (downEvent: MouseEvent) {
- downEvent.stopPropagation();
-
- const initial = setup();
-
- let moved = false;
- let initialMouseX: null | number = null;
-
- setTrackState("draggingSegment", true);
-
- const resumeHistory = history.pause();
-
- zoomSegmentDragState = { type: "movePending" };
-
- function finish(e: MouseEvent) {
- resumeHistory();
- if (!moved) {
- e.stopPropagation();
- setState("timelineSelection", {
- type: "zoom",
- index: i(),
- });
- handleUpdatePlayhead(e);
- }
- zoomSegmentDragState = { type: "idle" };
- setTrackState("draggingSegment", false);
- }
+ <SegmentHandle
+ class="bg-red-300 hover:opacity-80 transition-colors"
+ onMouseDown={createMouseDownDrag(
+ () => {
+ const start = segment.start;
- function update(event: MouseEvent) {
- if (Math.abs(event.clientX - downEvent.clientX) > 2) {
- if (!moved) {
- moved = true;
- initialMouseX = event.clientX;
- zoomSegmentDragState = {
- type: "moving",
- };
- }
- }
+ let minValue = 0;
- if (initialMouseX === null) return;
+ let maxValue = segment.end - 1;
- _update(event, initial, initialMouseX);
+ for (let i = zoomSegments().length - 1; i >= 0; i--) {
+ const segment = zoomSegments()[i]!;
+ if (segment.end <= start) {
+ minValue = segment.end;
+ break;
}
+ }
- createRoot((dispose) => {
- createEventListenerMap(window, {
- mousemove: (e) => {
- update(e);
- },
- mouseup: (e) => {
- update(e);
- finish(e);
- dispose();
- },
- });
- });
+ return { start, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const newStart =
+ value.start +
+ (e.clientX - initialMouseX) * secsPerPixel();
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ i(),
+ "start",
+ Math.min(
+ value.maxValue,
+ Math.max(value.minValue, newStart)
+ )
+ );
+ }
+ )}
+ />
+ <SegmentContent
+ class="cursor-pointer flex items-center justify-center"
+ onMouseDown={createMouseDownDrag(
+ () => {
+ const original = { ...segment };
+
+ const prevSegment = zoomSegments()[i() - 1];
+ const nextSegment = zoomSegments()[i() + 1];
+
+ const minStart = prevSegment?.end ?? 0;
+ const maxEnd = nextSegment?.start ?? duration();
+
+ return {
+ original,
+ minStart,
+ maxEnd,
};
+ },
+ (e, value, initialMouseX) => {
+ const rawDelta =
+ (e.clientX - initialMouseX) * secsPerPixel();
+
+ const newStart = value.original.start + rawDelta;
+ const newEnd = value.original.end + rawDelta;
+
+ let delta = rawDelta;
+
+ if (newStart < value.minStart)
+ delta = value.minStart - value.original.start;
+ else if (newEnd > value.maxEnd)
+ delta = value.maxEnd - value.original.end;
+
+ setProject("timeline", "zoomSegments", i(), {
+ start: value.original.start + delta,
+ end: value.original.end + delta,
+ });
}
+ )}
+ >
+ {(() => {
+ const ctx = useSegmentContext();
return (
- <SegmentRoot
- class="border-red-300 group bg-red-50 hover:bg-opacity-80 transition-colors"
- innerClass="ring-red-300"
- segment={segment}
- onMouseEnter={() => {
- setHoveringSegment(true);
- }}
- onMouseLeave={() => {
- setHoveringSegment(false);
- }}
- >
- <SegmentHandle
- class="bg-red-300 hover:opacity-80 transition-colors"
- onMouseDown={createMouseDownDrag(
- () => {
- const start = segment.start;
-
- let minValue = 0;
-
- let maxValue = segment.end - 1;
-
- for (
- let i = zoomSegments().length - 1;
- i >= 0;
- i--
- ) {
- const segment = zoomSegments()[i]!;
- if (segment.end <= start) {
- minValue = segment.end;
- break;
- }
- }
-
- return { start, minValue, maxValue };
- },
- (e, value, initialMouseX) => {
- const { width } = timelineBounds;
-
- const newStart =
- value.start +
- ((e.clientX - initialMouseX) / width!) *
- duration();
-
- setProject(
- "timeline",
- "zoomSegments",
- i(),
- "start",
- Math.min(
- value.maxValue,
- Math.max(value.minValue, newStart)
- )
- );
- }
- )}
- />
- <SegmentContent
- class="cursor-pointer flex items-center justify-center"
- onMouseDown={createMouseDownDrag(
- () => {
- const original = { ...segment };
-
- const prevSegment = zoomSegments()[i() - 1];
- const nextSegment = zoomSegments()[i() + 1];
-
- const minStart = prevSegment?.end ?? 0;
- const maxEnd = nextSegment?.start ?? duration();
-
- const secsPerPixel =
- duration() / trackBounds.width!;
-
- return {
- secsPerPixel,
- original,
- minStart,
- maxEnd,
- };
- },
- (e, value, initialMouseX) => {
- const rawDelta =
- (e.clientX - initialMouseX) *
- value.secsPerPixel;
-
- const newStart = value.original.start + rawDelta;
- const newEnd = value.original.end + rawDelta;
-
- let delta = rawDelta;
-
- if (newStart < value.minStart)
- delta = value.minStart - value.original.start;
- else if (newEnd > value.maxEnd)
- delta = value.maxEnd - value.original.end;
-
- setProject("timeline", "zoomSegments", i(), {
- start: value.original.start + delta,
- end: value.original.end + delta,
- });
- }
- )}
- >
- {(() => {
- const ctx = useSegmentContext();
-
- return (
- <Show when={ctx.width() > 100}>
- <div class="text-xs text-gray-500 whitespace-nowrap flex flex-col justify-center items-center gap-1">
- <div class="flex items-center gap-1 text-red-300">
- <IconLucideSearch class="size-3" />{" "}
- {zoomPercentage()}
- </div>
- </div>
- </Show>
- );
- })()}
- </SegmentContent>
- <SegmentHandle
- class="bg-red-300 hover:opacity-80 transition-colors"
- onMouseDown={createMouseDownDrag(
- () => {
- const end = segment.end;
-
- const minValue = segment.start + 1;
-
- let maxValue = duration();
-
- for (let i = 0; i < zoomSegments().length; i++) {
- const segment = zoomSegments()[i]!;
- if (segment.start > end) {
- maxValue = segment.start;
- break;
- }
- }
-
- return { end, minValue, maxValue };
- },
- (e, value, initialMouseX) => {
- const { width } = timelineBounds;
-
- const newEnd =
- value.end +
- ((e.clientX - initialMouseX) / width!) *
- duration();
-
- setProject(
- "timeline",
- "zoomSegments",
- i(),
- "end",
- Math.min(
- value.maxValue,
- Math.max(value.minValue, newEnd)
- )
- );
- }
- )}
- />
- </SegmentRoot>
+ <Show when={ctx.width() > 100}>
+ <div class="text-xs text-gray-500 whitespace-nowrap flex flex-col justify-center items-center gap-1">
+ <div class="flex items-center gap-1 text-red-300">
+ <IconLucideSearch class="size-3" />{" "}
+ {zoomPercentage()}
+ </div>
+ </div>
+ </Show>
);
- }}
- </For>
- </TrackRoot>
- </>
- );
- })()}
- </div>
- </TimelineContextProvider>
+ })()}
+ </SegmentContent>
+ <SegmentHandle
+ class="bg-red-300 hover:opacity-80 transition-colors"
+ onMouseDown={createMouseDownDrag(
+ () => {
+ const end = segment.end;
+
+ const minValue = segment.start + 1;
+
+ let maxValue = duration();
+
+ for (let i = 0; i < zoomSegments().length; i++) {
+ const segment = zoomSegments()[i]!;
+ if (segment.start > end) {
+ maxValue = segment.start;
+ break;
+ }
+ }
+
+ return { end, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const newEnd =
+ value.end +
+ (e.clientX - initialMouseX) * secsPerPixel();
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ i(),
+ "end",
+ Math.min(
+ value.maxValue,
+ Math.max(value.minValue, newEnd)
+ )
+ );
+ }
+ )}
+ />
+ </SegmentRoot>
+ );
+ }}
+ </For>
+ </TrackRoot>
+ </>
);
}
-function TrackRoot(props: ComponentProps<"div"> & { isFreeForm: boolean }) {
+function TrackRoot(props: ComponentProps<"div"> & { isFreeForm?: boolean }) {
const [ref, setRef] = createSignal<HTMLDivElement>();
return (
- <TrackContextProvider ref={ref} isFreeForm={() => props.isFreeForm}>
+ <TrackContextProvider
+ ref={ref}
+ isFreeForm={() => props.isFreeForm ?? false}
+ >
<div
{...props}
ref={mergeRefs(setRef, props.ref)}
@@ -747,9 +841,8 @@ function SegmentRoot(
) => void;
}
) {
- const { duration } = useTimelineContext();
- const { trackBounds, isFreeForm, setTrackState } = useTrackContext();
- const { state, project, history, setProject } = useEditorContext();
+ const { isFreeForm, secsPerPixel } = useTrackContext();
+ const { state, project } = useEditorContext();
const isSelected = createMemo(() => {
const selection = state.timelineSelection;
@@ -763,27 +856,29 @@ function SegmentRoot(
});
const translateX = createMemo(() => {
- if (!isFreeForm()) return 0;
- return (props.segment.start / duration()) * (trackBounds.width ?? 0);
+ const base = state.timelineTransform.position;
+
+ const delta = !isFreeForm() ? 0 : props.segment.start;
+
+ return (delta - base) / secsPerPixel();
});
- const width = () =>
- ((trackBounds.width ?? 0) * (props.segment.end - props.segment.start)) /
- duration();
+ const width = () => {
+ return (props.segment.end - props.segment.start) / secsPerPixel();
+ };
return (
<SegmentContextProvider width={width}>
<div
{...props}
class={cx(
- "border rounded-[calc(0.75rem+1px)] h-[3rem] w-full",
+ "absolute border rounded-[calc(0.75rem+1px)] h-[3rem] w-full",
props.class,
- isSelected() && "wobble-wrapper",
- isFreeForm() && "absolute"
+ isSelected() && "wobble-wrapper"
)}
style={{
"--segment-x": `${translateX()}px`,
- transform: isFreeForm() ? "translateX(var(--segment-x))" : undefined,
+ transform: "translateX(var(--segment-x))",
width: `${width()}px`,
}}
ref={props.ref}
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 02d3f3431..3cb9e229d 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -6,13 +6,14 @@ import { createUndoHistory } from "@solid-primitives/history";
import { debounce } from "@solid-primitives/scheduled";
import {
Accessor,
+ batch,
createEffect,
createResource,
createSignal,
on,
} from "solid-js";
import { createStore, reconcile, unwrap } from "solid-js/store";
-import { createElementBounds } from "@solid-primitives/bounds";
+import { createElementBounds, NullableBounds } from "@solid-primitives/bounds";
import type { PresetsStore } from "../../store";
import {
@@ -41,6 +42,8 @@ export const OUTPUT_SIZE = {
y: 1080,
};
+export const MAX_ZOOM_IN = 3;
+
export const [EditorContextProvider, useEditorContext] = createContextProvider(
(props: {
editorInstance: SerializedEditorInstance;
@@ -84,10 +87,77 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
const [playbackTime, setPlaybackTime] = createSignal<number>(0);
const [playing, setPlaying] = createSignal(false);
+ createEffect(() => {
+ if (!playing())
+ commands.setPlayheadPosition(Math.floor(playbackTime() * FPS));
+ });
+
const [split, setSplit] = createSignal(false);
+ const totalDuration = () =>
+ project.timeline?.segments.reduce(
+ (acc, s) => acc + (s.end - s.start) / s.timescale,
+ 0
+ ) ?? props.editorInstance.recordingDuration;
+
+ type State = {
+ zoom: number;
+ position: number;
+ };
+
+ const zoomOutLimit = () => totalDuration();
+
+ function updateZoom(state: State, newZoom: number, origin: number): State {
+ const zoom = Math.max(Math.min(newZoom, zoomOutLimit()), MAX_ZOOM_IN);
+
+ const visibleOrigin = origin - state.position;
+
+ const originPercentage = Math.min(1, visibleOrigin / state.zoom);
+
+ const newVisibleOrigin = zoom * originPercentage;
+ const newPosition = origin - newVisibleOrigin;
+
+ return {
+ zoom,
+ position: newPosition,
+ };
+ }
+
const [state, setState] = createStore({
timelineSelection: null as null | { type: "zoom"; index: number },
+ timelineTransform: {
+ // visible seconds
+ zoom: 17,
+ updateZoom(z: number, origin: number) {
+ const { zoom, position } = updateZoom(
+ {
+ zoom: state.timelineTransform.zoom,
+ position: state.timelineTransform.position,
+ },
+ z,
+ origin
+ );
+
+ const transform = state.timelineTransform;
+ batch(() => {
+ setState("timelineTransform", "zoom", zoom);
+ if (transform.zoom !== zoom) return;
+ transform.setPosition(position);
+ });
+ },
+ // number of seconds of leftmost point
+ position: 0,
+ setPosition(p: number) {
+ setState(
+ "timelineTransform",
+ "position",
+ Math.min(
+ Math.max(p, 0),
+ zoomOutLimit() + 4 - state.timelineTransform.zoom
+ )
+ );
+ },
+ },
});
return {
@@ -110,6 +180,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
setSplit,
state,
setState,
+ totalDuration,
+ zoomOutLimit,
};
},
// biome-ignore lint/style/noNonNullAssertion: it's ok
@@ -213,23 +285,38 @@ type Static<T = unknown> =
| T[];
export const [TimelineContextProvider, useTimelineContext] =
- createContextProvider((props: { duration: number }) => {
- return {
- duration: () => props.duration,
- };
- }, null!);
+ createContextProvider(
+ (props: {
+ duration: number;
+ secsPerPixel: number;
+ timelineBounds: Readonly<NullableBounds>;
+ }) => {
+ return {
+ duration: () => props.duration,
+ secsPerPixel: () => props.secsPerPixel,
+ timelineBounds: props.timelineBounds,
+ };
+ },
+ null!
+ );
export const [TrackContextProvider, useTrackContext] = createContextProvider(
(props: {
ref: Accessor<Element | undefined>;
isFreeForm: Accessor<boolean>;
}) => {
+ const { state } = useEditorContext();
+
const [trackState, setTrackState] = createStore({
draggingSegment: false,
});
const bounds = createElementBounds(() => props.ref());
+ const secsPerPixel = () =>
+ state.timelineTransform.zoom / (bounds.width ?? 1);
+
return {
+ secsPerPixel,
trackBounds: bounds,
isFreeForm: () => props.isFreeForm(),
trackState,
diff --git a/apps/desktop/src/routes/editor/utils.ts b/apps/desktop/src/routes/editor/utils.ts
index 684b6cf19..aef7c011e 100644
--- a/apps/desktop/src/routes/editor/utils.ts
+++ b/apps/desktop/src/routes/editor/utils.ts
@@ -1,6 +1,13 @@
-export function formatTime(secs: number) {
+export function formatTime(secs: number, fps?: number) {
const minutes = Math.floor(secs / 60);
- const seconds = Math.round(secs % 60);
+ const seconds = Math.floor(secs % 60);
+ const frames = fps === undefined ? undefined : Math.floor((secs % 1) * fps);
- return `${minutes}:${seconds.toString().padStart(2, "0")}`;
+ let str = `${minutes}:${seconds.toString().padStart(2, "0")}`;
+
+ if (frames !== undefined) {
+ str += `.${frames.toString().padStart(2, "0 ")}`;
+ }
+
+ return str;
}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index e48c36ece..1d278e6d4 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -248,7 +248,7 @@ export type CursorType = "pointer" | "circle"
export type Display = { path: string; fps?: number }
export type EditorStateChanged = { playhead_position: number }
export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
-export type Flags = { recordMouse: boolean; split: boolean }
+export type Flags = { recordMouse: boolean; split: boolean; timelineZooming: boolean }
export type GeneralSettingsStore = { uploadIndividualFiles?: boolean; openEditorAfterRecording?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; recordingConfig?: RecordingConfig | null }
export type HapticPattern = "Alignment" | "LevelChange" | "Generic"
export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted"
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 6bb29e481..cb94c5d4c 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -3,7 +3,7 @@ use std::{sync::Arc, time::Instant};
use cap_media::{feeds::RawCameraFrame, frame_ws::WSFrame};
use cap_project::{BackgroundSource, RecordingMeta, XY};
use cap_rendering::{
- decoder::DecodedFrame, produce_frame, DecodedSegmentFrames, ProjectRecordings, ProjectUniforms,
+ decoder::DecodedFrame, DecodedSegmentFrames, FrameRenderer, ProjectRecordings, ProjectUniforms,
RenderVideoConstants,
};
use tokio::{
@@ -70,6 +70,8 @@ impl Renderer {
async fn run(mut self) {
let mut frame_task: Option<JoinHandle<()>> = None;
+ let mut frame_renderer = FrameRenderer::new(&self.render_constants);
+
loop {
while let Some(msg) = self.rx.recv().await {
match msg {
@@ -91,9 +93,9 @@ impl Renderer {
let render_constants = self.render_constants.clone();
let frame_tx = self.frame_tx.clone();
- frame_task = Some(tokio::spawn(async move {
- let frame = produce_frame(
- &render_constants,
+ // frame_task = Some(tokio::spawn(async move {
+ let frame = frame_renderer
+ .render(
segment_frames,
cap_rendering::Background::from(background),
&uniforms,
@@ -102,16 +104,16 @@ impl Renderer {
.await
.unwrap();
- frame_tx
- .try_send(WSFrame {
- data: frame.data,
- width: uniforms.output_size.0,
- height: uniforms.output_size.1,
- stride: frame.padded_bytes_per_row,
- })
- .ok();
- finished.send(()).ok();
- }));
+ frame_tx
+ .try_send(WSFrame {
+ data: frame.data,
+ width: uniforms.output_size.0,
+ height: uniforms.output_size.1,
+ stride: frame.padded_bytes_per_row,
+ })
+ .ok();
+ finished.send(()).ok();
+ // }));
}
RendererMessage::Stop { finished } => {
// Cancel any ongoing frame task
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 094291508..d229cd1f2 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -55,8 +55,6 @@ impl Playback {
tokio::spawn(async move {
let start = Instant::now();
- let mut frame_number = self.start_frame_number + 1;
-
let duration = if let Some(timeline) = &self.project.borrow().timeline {
timeline.duration()
} else {
@@ -80,15 +78,17 @@ impl Playback {
};
loop {
+ let time =
+ (self.start_frame_number as f64 / fps as f64) + start.elapsed().as_secs_f64();
+ let frame_number = (time * fps as f64).floor() as u32;
+
if frame_number as f64 >= fps as f64 * duration {
break;
};
let project = self.project.borrow().clone();
- if let Some((segment_time, segment_i)) =
- project.get_segment_time(frame_number as f64 / fps as f64)
- {
+ if let Some((segment_time, segment_i)) = project.get_segment_time(time) {
let segment = &self.segments[segment_i as usize];
tokio::select! {
@@ -130,8 +130,6 @@ impl Playback {
.await;
event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
-
- frame_number += 1;
}
stop_tx.send(true).ok();
@@ -194,7 +192,6 @@ impl AudioPlayback {
handle.block_on(stop_rx.changed()).ok();
stream.pause().ok();
- drop(stream);
});
}
diff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rs
index aa983092b..991c9d5ea 100644
--- a/crates/flags/src/lib.rs
+++ b/crates/flags/src/lib.rs
@@ -3,9 +3,11 @@
pub struct Flags {
pub record_mouse: bool,
pub split: bool,
+ pub timeline_zooming: bool,
}
pub const FLAGS: Flags = Flags {
record_mouse: true,
split: cfg!(debug_assertions),
+ timeline_zooming: cfg!(debug_assertions),
};
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 3bf26294e..f671df0ed 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -22,6 +22,7 @@ specta.workspace = true
thiserror.workspace = true
wgpu.workspace = true
bezier_easing = "0.1.1"
+reactive_graph = "0.1.5"
[target.'cfg(target_os = "macos")'.dependencies]
cidre.workspace = true
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index 0a417e975..a1eb894d6 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -208,7 +208,7 @@ impl AVAssetReaderDecoder {
.ok_or_else(|| format!("UrlAsset::with_url{{{path:?}}}"))?;
Ok((
- get_reader_track_output(&asset, 0.0, &handle, pixel_format)?,
+ get_reader_track_output(&path, 0.0, &handle, pixel_format)?,
width,
height,
asset,
@@ -267,7 +267,7 @@ impl AVAssetReaderDecoder {
{
reader.cancel_reading();
(track_output, reader) = get_reader_track_output(
- &asset,
+ &path,
requested_time,
&handle,
pixel_format,
@@ -404,11 +404,18 @@ fn pixel_format_to_pixel(format: cv::PixelFormat) -> format::Pixel {
}
fn get_reader_track_output(
- asset: &av::UrlAsset,
+ path: &PathBuf,
+ // asset: &av::UrlAsset,
time: f32,
handle: &TokioHandle,
pixel_format: cv::PixelFormat,
) -> Result<(R<av::AssetReaderTrackOutput>, R<av::AssetReader>), String> {
+ let asset = av::UrlAsset::with_url(
+ &ns::Url::with_fs_path_str(path.to_str().unwrap(), false),
+ None,
+ )
+ .ok_or_else(|| format!("UrlAsset::with_url{{{path:?}}}"))?;
+
let mut reader =
av::AssetReader::with_asset(&asset).map_err(|e| format!("AssetReader::with_asset: {e}"))?;
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index eb6a63bc4..b5e8413df 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -13,6 +13,9 @@ use decoder::{spawn_decoder, AsyncVideoDecoderHandle};
use futures::future::OptionFuture;
use futures::FutureExt;
use futures_intrusive::channel::shared::oneshot_channel;
+use reactive_graph::computed::ArcMemo;
+use reactive_graph::signal::{arc_signal, ArcReadSignal, ArcWriteSignal};
+use reactive_graph::traits::{Get, Write};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::ops::{Add, Deref, Mul, Sub};
@@ -219,6 +222,8 @@ pub async fn render_video_to_channel(
let mut frame_number = 0;
let background = Background::from(project.background.source.clone());
+ let mut frame_renderer = FrameRenderer::new(&constants);
+
loop {
if frame_number >= total_frames {
break;
@@ -251,14 +256,14 @@ pub async fn render_video_to_channel(
resolution_base,
is_upgraded,
);
- let frame = produce_frame(
- &constants,
- segment_frames,
- background.clone(),
- &uniforms,
- resolution_base,
- )
- .await?;
+ let frame = frame_renderer
+ .render(
+ segment_frames,
+ background.clone(),
+ &uniforms,
+ resolution_base,
+ )
+ .await?;
if frame.width == 0 || frame.height == 0 {
continue;
@@ -337,6 +342,8 @@ pub struct RenderVideoConstants {
watermark_dimensions: (u32, u32),
image_background_pipeline: ImageBackgroundPipeline,
background_textures: std::sync::Arc<tokio::sync::RwLock<HashMap<String, wgpu::Texture>>>,
+ screen_frame: (wgpu::Texture, wgpu::TextureView),
+ camera_frame: Option<(wgpu::Texture, wgpu::TextureView)>,
}
impl RenderVideoConstants {
@@ -454,6 +461,56 @@ impl RenderVideoConstants {
let image_background_pipeline = ImageBackgroundPipeline::new(&device);
let background_textures = Arc::new(tokio::sync::RwLock::new(HashMap::new()));
+ let screen_frame = {
+ let texture = device.create_texture(
+ &(wgpu::TextureDescriptor {
+ size: wgpu::Extent3d {
+ width: options.screen_size.x,
+ height: options.screen_size.y,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::COPY_DST,
+ label: Some("Screen Frame texture"),
+ view_formats: &[],
+ }),
+ );
+
+ let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+
+ (texture, texture_view)
+ };
+
+ let camera_frame = options.camera_size.map(|s| {
+ let texture = device.create_texture(
+ &(wgpu::TextureDescriptor {
+ size: wgpu::Extent3d {
+ width: s.x,
+ height: s.y,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::COPY_DST,
+ label: Some("Camera texture"),
+ view_formats: &[],
+ }),
+ );
+
+ let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+
+ (texture, texture_view)
+ });
+
Ok(Self {
_instance: instance,
_adapter: adapter,
@@ -470,6 +527,8 @@ impl RenderVideoConstants {
watermark_dimensions: dimensions,
image_background_pipeline,
background_textures,
+ screen_frame,
+ camera_frame,
})
}
@@ -950,12 +1009,79 @@ pub struct DecodedSegmentFrames {
pub segment_time: f32,
}
-pub async fn produce_frame(
+pub struct FrameRenderer<'a> {
+ constants: &'a RenderVideoConstants,
+ output_texture_desc: Option<wgpu::TextureDescriptor<'static>>,
+ output_textures: Option<(wgpu::Texture, wgpu::Texture)>,
+}
+
+impl<'a> FrameRenderer<'a> {
+ pub fn new(constants: &'a RenderVideoConstants) -> Self {
+ Self {
+ constants,
+ output_texture_desc: None,
+ output_textures: None,
+ }
+ }
+
+ fn update_output_textures(&mut self, width: u32, height: u32) {
+ if let Some(desc) = &self.output_texture_desc {
+ if desc.size.width == width && desc.size.height == height {
+ return;
+ }
+ }
+
+ let output_texture_desc = self.output_texture_desc.insert(wgpu::TextureDescriptor {
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::COPY_SRC,
+ label: Some("Intermediate Texture"),
+ view_formats: &[],
+ });
+
+ self.output_textures = Some((
+ self.constants.device.create_texture(output_texture_desc),
+ self.constants.device.create_texture(output_texture_desc),
+ ));
+ }
+
+ pub async fn render(
+ &mut self,
+ segment_frames: DecodedSegmentFrames,
+ background: Background,
+ uniforms: &ProjectUniforms,
+ resolution_base: XY<u32>,
+ ) -> Result<RenderedFrame, RenderingError> {
+ self.update_output_textures(uniforms.output_size.0, uniforms.output_size.1);
+
+ produce_frame(
+ &self.constants,
+ segment_frames,
+ background,
+ uniforms,
+ resolution_base,
+ self.output_textures.as_ref().unwrap(),
+ )
+ .await
+ }
+}
+
+async fn produce_frame(
constants: &RenderVideoConstants,
segment_frames: DecodedSegmentFrames,
background: Background,
uniforms: &ProjectUniforms,
resolution_base: XY<u32>,
+ textures: &(wgpu::Texture, wgpu::Texture),
) -> Result<RenderedFrame, RenderingError> {
let mut encoder = constants.device.create_command_encoder(
&(wgpu::CommandEncoderDescriptor {
@@ -963,28 +1089,6 @@ pub async fn produce_frame(
}),
);
- let output_texture_desc = wgpu::TextureDescriptor {
- size: wgpu::Extent3d {
- width: uniforms.output_size.0,
- height: uniforms.output_size.1,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
- usage: wgpu::TextureUsages::TEXTURE_BINDING
- | wgpu::TextureUsages::RENDER_ATTACHMENT
- | wgpu::TextureUsages::COPY_SRC,
- label: Some("Intermediate Texture"),
- view_formats: &[],
- };
-
- let textures = (
- constants.device.create_texture(&output_texture_desc),
- constants.device.create_texture(&output_texture_desc),
- );
-
let textures = (&textures.0, &textures.1);
let texture_views = (
@@ -1055,10 +1159,30 @@ pub async fn produce_frame(
}
};
+ let output_ar = uniforms.output_size.1 as f32 / uniforms.output_size.0 as f32;
+ let image_ar = texture.height() as f32 / texture.width() as f32;
+
+ let y_height = if output_ar < image_ar {
+ ((image_ar - output_ar) / 2.0) / image_ar
+ } else {
+ 0.0
+ };
+
+ let x_width = if output_ar > image_ar {
+ let output_ar = 1.0 / output_ar;
+ let image_ar = 1.0 / image_ar;
+
+ ((image_ar - output_ar) / 2.0) / image_ar
+ } else {
+ 0.0
+ };
+
// Create uniforms and bind group
let image_uniforms = ImageBackgroundUniforms {
output_size: [uniforms.output_size.0 as f32, uniforms.output_size.1 as f32],
- padding: uniforms.project.background.padding as f32,
+ padding: 0.0, //uniforms.project.background.padding as f32,
+ x_width,
+ y_height,
_padding: 0.0,
};
@@ -1111,30 +1235,9 @@ pub async fn produce_frame(
{
let frame_size = constants.options.screen_size;
- let texture = constants.device.create_texture(
- &(wgpu::TextureDescriptor {
- size: wgpu::Extent3d {
- width: constants.options.screen_size.x,
- height: constants.options.screen_size.y,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
- usage: wgpu::TextureUsages::TEXTURE_BINDING
- | wgpu::TextureUsages::RENDER_ATTACHMENT
- | wgpu::TextureUsages::COPY_DST,
- label: Some("Screen Frame texture"),
- view_formats: &[],
- }),
- );
-
- let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
-
constants.queue.write_texture(
wgpu::ImageCopyTexture {
- texture: &texture,
+ texture: &constants.screen_frame.0,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
@@ -1159,7 +1262,7 @@ pub async fn produce_frame(
constants.composite_video_frame_pipeline.bind_group(
&constants.device,
&uniforms.display.to_buffer(&constants.device),
- &texture_view,
+ &constants.screen_frame.1,
get_either(texture_views, !output_is_left),
),
wgpu::LoadOp::Load, // Load existing content
@@ -1179,32 +1282,12 @@ pub async fn produce_frame(
);
// camera
- if let (Some(camera_size), Some(camera_frame), Some(uniforms)) = (
+ if let (Some(camera_size), Some(camera_frame), Some(uniforms), Some((texture, texture_view))) = (
constants.options.camera_size,
&segment_frames.camera_frame,
&uniforms.camera,
+ &constants.camera_frame,
) {
- let texture = constants.device.create_texture(
- &(wgpu::TextureDescriptor {
- size: wgpu::Extent3d {
- width: camera_size.x,
- height: camera_size.y,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
- usage: wgpu::TextureUsages::TEXTURE_BINDING
- | wgpu::TextureUsages::RENDER_ATTACHMENT
- | wgpu::TextureUsages::COPY_DST,
- label: Some("Camera texture"),
- view_formats: &[],
- }),
- );
-
- let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
-
constants.queue.write_texture(
wgpu::ImageCopyTexture {
texture: &texture,
@@ -2445,6 +2528,8 @@ struct ImageBackgroundPipeline {
struct ImageBackgroundUniforms {
output_size: [f32; 2],
padding: f32,
+ x_width: f32,
+ y_height: f32,
_padding: f32, // For alignment
}
diff --git a/crates/rendering/src/shaders/image-background.wgsl b/crates/rendering/src/shaders/image-background.wgsl
index fd92b4ffe..fdc0009fa 100644
--- a/crates/rendering/src/shaders/image-background.wgsl
+++ b/crates/rendering/src/shaders/image-background.wgsl
@@ -1,6 +1,8 @@
struct Uniforms {
output_size: vec2<f32>,
padding: f32,
+ x_width: f32,
+ y_height: f32,
_padding: f32, // Matches the Rust struct alignment padding
};
@@ -22,34 +24,18 @@ fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
out.clip_position = vec4<f32>(x, y, 0.0, 1.0);
return out;
}
+
@fragment
fn fs_main(@location(0) tex_coords: vec2<f32>) -> @location(0) vec4<f32> {
- // Calculate the padding in UV space
- let padding_uv = u.padding / max(u.output_size.x, u.output_size.y);
-
- // Adjust UV coordinates to account for padding
- let adjusted_coords = tex_coords * (1.0 - 2.0 * padding_uv) + padding_uv;
-
- // Calculate aspect ratios
- let container_ratio = u.output_size.x / u.output_size.y;
- let texture_dims = vec2<f32>(textureDimensions(t_image));
- let texture_ratio = texture_dims.x / texture_dims.y;
-
- // Calculate scale factors to achieve 'cover' behavior
- var scale = vec2<f32>(1.0);
- if (container_ratio > texture_ratio) {
- // Container is wider than texture - scale based on height
- scale.x = texture_ratio / container_ratio;
- scale.y = 1.0;
- } else {
- // Container is taller than texture - scale based on width
- scale.x = 1.0;
- scale.y = container_ratio / texture_ratio;
- }
-
- // Transform coordinates to center and scale the image
- let transformed_coords = (adjusted_coords - 0.5) * scale + 0.5;
-
- // Let the sampler handle the edge clamping
- return textureSample(t_image, s_image, transformed_coords);
-}
\ No newline at end of file
+ let x_width = (0.5 - u.x_width) * 2.0;
+ let y_height = (0.5 - u.y_height) * 2.0;
+
+ return textureSample(
+ t_image,
+ s_image,
+ vec2<f32>(
+ u.x_width + x_width * tex_coords.x,
+ u.y_height + y_height * tex_coords.y
+ )
+ );
+}