forked from fal-ai-community/video-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathtrack.tsx
More file actions
426 lines (378 loc) · 13.1 KB
/
Copy pathtrack.tsx
File metadata and controls
426 lines (378 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import { db } from "@/data/db";
import {
queryKeys,
refreshVideoCache,
useProjectMediaItems,
} from "@/data/queries";
import type { MediaItem, VideoKeyFrame, VideoTrack } from "@/data/schema";
import { useProjectId, useVideoProjectStore } from "@/data/store";
import { cn, resolveDuration, resolveMediaUrl, trackIcons } from "@/lib/utils";
import {
keepPreviousData,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { TrashIcon } from "lucide-react";
import {
type HTMLAttributes,
type MouseEventHandler,
createElement,
useMemo,
useRef,
} from "react";
import { WithTooltip } from "../ui/tooltip";
type VideoTrackRowProps = {
data: VideoTrack;
} & HTMLAttributes<HTMLDivElement>;
export function VideoTrackRow({ data, ...props }: VideoTrackRowProps) {
const { data: keyframes = [] } = useQuery({
queryKey: ["frames", data],
queryFn: () => db.keyFrames.keyFramesByTrack(data.id),
});
const mediaType = useMemo(() => keyframes[0]?.data.type, [keyframes]);
return (
<div
className={cn(
"relative w-full timeline-container",
"flex flex-col select-none rounded overflow-hidden shrink-0",
{
"min-h-[64px]": mediaType,
"min-h-[56px]": !mediaType,
},
)}
{...props}
>
{keyframes.map((frame) => (
<VideoTrackView
key={frame.id}
className="absolute top-0 bottom-0"
style={{
left: `${(frame.timestamp / 10 / 30).toFixed(2)}%`,
width: `${(frame.duration / 10 / 30).toFixed(2)}%`,
}}
track={data}
frame={frame}
/>
))}
</div>
);
}
type AudioWaveformProps = {
data: MediaItem;
};
function AudioWaveform({ data }: AudioWaveformProps) {
const { data: waveform = [] } = useQuery({
queryKey: ["media", "waveform", data.id],
queryFn: async () => {
if (data.metadata?.waveform && Array.isArray(data.metadata.waveform)) {
return data.metadata.waveform;
}
const audioUrl = resolveMediaUrl(data);
if (!audioUrl) {
throw new Error("No media URL found");
}
try {
const proxyUrl = `${window.location.origin}/api/download?url=${encodeURIComponent(audioUrl)}`;
const response = await fetch(proxyUrl);
const arrayBuffer = await response.arrayBuffer();
const audioContext = new AudioContext();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
const pointsPerSecond = 5;
const precision = 3;
const channelData = audioBuffer.getChannelData(0);
const duration = audioBuffer.duration;
const totalPoints = Math.floor(duration * pointsPerSecond);
const samplesPerPoint = Math.floor(channelData.length / totalPoints);
const waveformData: number[] = [];
for (let i = 0; i < totalPoints; i++) {
const start = i * samplesPerPoint;
const end = Math.min(start + samplesPerPoint, channelData.length);
let sum = 0;
for (let j = start; j < end; j++) {
sum += channelData[j] * channelData[j];
}
const rms = Math.sqrt(sum / (end - start));
waveformData.push(Number(rms.toFixed(precision)));
}
await db.media.update(data.id, {
...data,
metadata: {
...data.metadata,
waveform: waveformData,
},
});
return waveformData;
} catch (error) {
console.error("Failed to generate waveform locally:", error);
return [];
}
},
placeholderData: keepPreviousData,
staleTime: Number.POSITIVE_INFINITY,
});
const svgHeight = 100;
if (waveform.length === 0) {
return null;
}
return (
<div className="h-full flex items-center overflow-hidden">
<div className="w-full">
<svg
width="100%"
height="80%"
viewBox={`0 0 ${waveform.length} ${svgHeight}`}
preserveAspectRatio="none"
>
<title>Audio Waveform</title>
{waveform.map((v, index) => {
const amplitude = Math.abs(v);
const height = Math.max(amplitude * svgHeight, 2);
const x = index;
const y = (svgHeight - height) / 2;
return (
<rect
key={`waveform-${index}-${x}`}
x={x}
y={y}
width="1"
height={height}
className="fill-black/40"
rx="4"
/>
);
})}
</svg>
</div>
</div>
);
}
type VideoTrackViewProps = {
track: VideoTrack;
frame: VideoKeyFrame;
} & HTMLAttributes<HTMLDivElement>;
export function VideoTrackView({
className,
track,
frame,
...props
}: VideoTrackViewProps) {
const queryClient = useQueryClient();
const deleteKeyframe = useMutation({
mutationFn: () => db.keyFrames.delete(frame.id),
onSuccess: () => refreshVideoCache(queryClient, track.projectId),
});
const handleOnDelete = () => {
deleteKeyframe.mutate();
};
const isSelected = useVideoProjectStore((state) =>
state.selectedKeyframes.includes(frame.id),
);
const selectKeyframe = useVideoProjectStore((state) => state.selectKeyframe);
const handleOnClick: MouseEventHandler = (e) => {
if (e.detail > 1) {
return;
}
selectKeyframe(frame.id);
};
const projectId = useProjectId();
const { data: mediaItems = [] } = useProjectMediaItems(projectId);
const media = mediaItems.find((item) => item.id === frame.data.mediaId);
const mediaUrl = media ? resolveMediaUrl(media) : null;
const trackRef = useRef<HTMLDivElement>(null);
const imageUrl = useMemo(() => {
if (!media) return undefined;
if (media.mediaType === "image") {
return mediaUrl;
}
if (media.mediaType === "video") {
return (
media.metadata?.thumbnail_url ||
media.input?.image_url ||
media.metadata?.start_frame_url ||
media.metadata?.end_frame_url
);
}
return undefined;
}, [media, mediaUrl]);
// TODO improve missing data
if (!media) return null;
const label = media.mediaType ?? "unknown";
const calculateBounds = () => {
const timelineElement = document.querySelector(".timeline-container");
const timelineRect = timelineElement?.getBoundingClientRect();
const trackElement = trackRef.current;
const trackRect = trackElement?.getBoundingClientRect();
if (!timelineRect || !trackRect || !trackElement)
return { left: 0, right: 0 };
const previousTrack = trackElement?.previousElementSibling;
const nextTrack = trackElement?.nextElementSibling;
const leftBound = previousTrack
? previousTrack.getBoundingClientRect().right - (timelineRect?.left || 0)
: 0;
const rightBound = nextTrack
? nextTrack.getBoundingClientRect().left -
(timelineRect?.left || 0) -
trackRect.width
: timelineRect.width - trackRect.width;
return {
left: leftBound,
right: rightBound,
};
};
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
const trackElement = trackRef.current;
if (!trackElement) return;
const bounds = calculateBounds();
const startX = e.clientX;
const startLeft = trackElement.offsetLeft;
const handleMouseMove = (moveEvent: MouseEvent) => {
const deltaX = moveEvent.clientX - startX;
let newLeft = startLeft + deltaX;
if (newLeft < bounds.left) {
newLeft = bounds.left;
} else if (newLeft > bounds.right) {
newLeft = bounds.right;
}
const timelineElement = trackElement.closest(".timeline-container");
const parentWidth = timelineElement
? (timelineElement as HTMLElement).offsetWidth
: 1;
const newTimestamp = (newLeft / parentWidth) * 30;
frame.timestamp = (newTimestamp < 0 ? 0 : newTimestamp) * 1000;
trackElement.style.left = `${((frame.timestamp / 30) * 100) / 1000}%`;
db.keyFrames.update(frame.id, { timestamp: frame.timestamp });
};
const handleMouseUp = () => {
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
queryClient.invalidateQueries({
queryKey: queryKeys.projectPreview(projectId),
});
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
};
const handleResize = (
e: React.MouseEvent<HTMLDivElement>,
direction: "left" | "right",
) => {
e.stopPropagation();
const trackElement = trackRef.current;
if (!trackElement) return;
const startX = e.clientX;
const startWidth = trackElement.offsetWidth;
const handleMouseMove = (moveEvent: MouseEvent) => {
const deltaX = moveEvent.clientX - startX;
let newWidth = startWidth + (direction === "right" ? deltaX : -deltaX);
const minDuration = 1000;
const mediaDuration = resolveDuration(media) ?? 5000;
const maxDuration = Math.min(mediaDuration, 30000);
const timelineElement = trackElement.closest(".timeline-container");
const parentWidth = timelineElement
? (timelineElement as HTMLElement).offsetWidth
: 1;
let newDuration = (newWidth / parentWidth) * 30 * 1000;
if (newDuration < minDuration) {
newWidth = (minDuration / 1000 / 30) * parentWidth;
newDuration = minDuration;
} else if (newDuration > maxDuration) {
newWidth = (maxDuration / 1000 / 30) * parentWidth;
newDuration = maxDuration;
}
frame.duration = newDuration;
trackElement.style.width = `${((frame.duration / 30) * 100) / 1000}%`;
};
const handleMouseUp = () => {
frame.duration = Math.round(frame.duration / 100) * 100;
trackElement.style.width = `${((frame.duration / 30) * 100) / 1000}%`;
db.keyFrames.update(frame.id, { duration: frame.duration });
queryClient.invalidateQueries({
queryKey: queryKeys.projectPreview(projectId),
});
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
};
return (
<div
ref={trackRef}
onMouseDown={handleMouseDown}
onContextMenu={(e) => e.preventDefault()}
aria-checked={isSelected}
onClick={handleOnClick}
className={cn(
"flex flex-col border border-white/10 rounded-lg",
className,
)}
{...props}
>
<div
className={cn(
"flex flex-col select-none rounded overflow-hidden group h-full",
{
"bg-sky-600": track.type === "video",
"bg-teal-500": track.type === "music",
"bg-indigo-500": track.type === "voiceover",
},
)}
>
<div className="p-0.5 pl-1 bg-black/10 flex flex-row items-center">
<div className="flex flex-row gap-1 text-sm items-center font-semibold text-white/60 w-full">
<div className="flex flex-row truncate gap-1 items-center">
{createElement(trackIcons[track.type], {
className: "w-5 h-5 text-white",
} as React.ComponentProps<
(typeof trackIcons)[typeof track.type]
>)}
<span className="line-clamp-1 truncate text-sm mb-[2px] w-full ">
{media.input?.prompt || label}
</span>
</div>
<div className="flex flex-row shrink-0 flex-1 items-center justify-end">
<WithTooltip tooltip="Remove content">
<button
type="button"
className="p-1 rounded hover:bg-black/5 group-hover:text-white"
onClick={handleOnDelete}
>
<TrashIcon className="w-3 h-3 text-white" />
</button>
</WithTooltip>
</div>
</div>
</div>
<div
className="p-px flex-1 items-center bg-repeat-x h-full max-h-full overflow-hidden relative"
style={
imageUrl
? {
background: `url(${imageUrl})`,
backgroundSize: "auto 100%",
}
: undefined
}
>
{(media.mediaType === "music" || media.mediaType === "voiceover") && (
<AudioWaveform data={media} />
)}
<div
className={cn(
"absolute right-0 z-50 top-0 bg-black/20 group-hover:bg-black/40",
"rounded-md bottom-0 w-2 m-1 p-px cursor-ew-resize backdrop-blur-md text-white/40",
"transition-colors flex flex-col items-center justify-center text-xs tracking-tighter",
)}
onMouseDown={(e) => handleResize(e, "right")}
>
<span className="flex gap-[1px]">
<span className="w-px h-2 rounded bg-white/40" />
<span className="w-px h-2 rounded bg-white/40" />
</span>
</div>
</div>
</div>
</div>
);
}