-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathPlayer.tsx
More file actions
595 lines (552 loc) · 16.8 KB
/
Player.tsx
File metadata and controls
595 lines (552 loc) · 16.8 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import { Select as KSelect } from "@kobalte/core/select";
import { ToggleButton as KToggleButton } from "@kobalte/core/toggle-button";
import { createElementBounds } from "@solid-primitives/bounds";
import { debounce } from "@solid-primitives/scheduled";
import { cx } from "cva";
import { createEffect, createSignal, onMount, Show } from "solid-js";
import Tooltip from "~/components/Tooltip";
import { captionsStore } from "~/store/captions";
import { commands } from "~/utils/tauri";
import AspectRatioSelect from "./AspectRatioSelect";
import {
FPS,
type PreviewQuality,
serializeProjectConfiguration,
useEditorContext,
} from "./context";
import { MaskOverlay } from "./MaskOverlay";
import { TextOverlay } from "./TextOverlay";
import {
EditorButton,
MenuItem,
MenuItemList,
PopperContent,
Slider,
topLeftAnimateClasses,
} from "./ui";
import { useEditorShortcuts } from "./useEditorShortcuts";
import { formatTime } from "./utils";
export function PlayerContent() {
const {
project,
editorInstance,
setDialog,
totalDuration,
editorState,
setEditorState,
zoomOutLimit,
setProject,
previewResolutionBase,
previewQuality,
setPreviewQuality,
} = useEditorContext();
const previewOptions = [
{ label: "Full", value: "full" as PreviewQuality },
{ label: "Half", value: "half" as PreviewQuality },
{ label: "Quarter", value: "quarter" as PreviewQuality },
];
// Load captions on mount
onMount(async () => {
if (editorInstance?.path) {
// Still load captions into the store since they will be used by the GPU renderer
await captionsStore.loadCaptions(editorInstance.path);
// Synchronize captions settings with project configuration
// This ensures the GPU renderer will receive the caption settings
if (editorInstance && project) {
const updatedProject = { ...project };
// Add captions data to project configuration if it doesn't exist
if (
!updatedProject.captions &&
captionsStore.state.segments.length > 0
) {
updatedProject.captions = {
segments: captionsStore.state.segments.map((segment) => ({
id: segment.id,
start: segment.start,
end: segment.end,
text: segment.text,
})),
settings: {
enabled: captionsStore.state.settings.enabled,
font: captionsStore.state.settings.font,
size: captionsStore.state.settings.size,
color: captionsStore.state.settings.color,
backgroundColor: captionsStore.state.settings.backgroundColor,
backgroundOpacity: captionsStore.state.settings.backgroundOpacity,
position: captionsStore.state.settings.position,
bold: captionsStore.state.settings.bold,
italic: captionsStore.state.settings.italic,
outline: captionsStore.state.settings.outline,
outlineColor: captionsStore.state.settings.outlineColor,
exportWithSubtitles:
captionsStore.state.settings.exportWithSubtitles,
highlightColor: captionsStore.state.settings.highlightColor,
fadeDuration: captionsStore.state.settings.fadeDuration,
},
};
// Update the project with captions data
setProject(updatedProject);
// Save the updated project configuration
await commands.setProjectConfig(
serializeProjectConfiguration(updatedProject),
);
}
}
}
});
// Continue to update current caption when playback time changes
// This is still needed for CaptionsTab to highlight the current caption
createEffect(() => {
const time = editorState.playbackTime;
// Only update captions if we have a valid time and segments exist
if (
time !== undefined &&
time >= 0 &&
captionsStore.state.segments.length > 0
) {
captionsStore.updateCurrentCaption(time);
}
});
const isAtEnd = () => {
const total = totalDuration();
return total > 0 && total - editorState.playbackTime <= 0.1;
};
const cropDialogHandler = async () => {
const display = editorInstance.recordings.segments[0].display;
setDialog({
open: true,
type: "crop",
position: {
...(project.background.crop?.position ?? { x: 0, y: 0 }),
},
size: {
...(project.background.crop?.size ?? {
x: display.width,
y: display.height,
}),
},
});
await commands.stopPlayback();
setEditorState("playing", false);
};
const handlePreviewQualityChange = async (quality: PreviewQuality) => {
if (quality === previewQuality()) return;
const wasPlaying = editorState.playing;
const currentFrame = Math.max(
Math.floor(editorState.playbackTime * FPS),
0,
);
setPreviewQuality(quality);
if (!wasPlaying) return;
try {
await commands.stopPlayback();
setEditorState("playing", false);
await commands.seekTo(currentFrame);
await commands.startPlayback(FPS, previewResolutionBase());
setEditorState("playing", true);
} catch (error) {
console.error("Failed to update preview quality:", error);
setEditorState("playing", false);
}
};
createEffect(() => {
if (isAtEnd() && editorState.playing) {
commands.stopPlayback();
setEditorState("playing", false);
}
});
const handlePlayPauseClick = async () => {
try {
if (isAtEnd()) {
await commands.stopPlayback();
setEditorState("playbackTime", 0);
await commands.seekTo(0);
await commands.startPlayback(FPS, previewResolutionBase());
setEditorState("playing", true);
} else if (editorState.playing) {
await commands.stopPlayback();
setEditorState("playing", false);
} else {
await commands.seekTo(Math.floor(editorState.playbackTime * FPS));
await commands.startPlayback(FPS, previewResolutionBase());
setEditorState("playing", true);
}
if (editorState.playing) setEditorState("previewTime", null);
} catch (error) {
console.error("Error handling play/pause:", error);
setEditorState("playing", false);
}
};
// Register keyboard shortcuts in one place
useEditorShortcuts(() => {
const el = document.activeElement;
if (!el) return true;
const tagName = el.tagName.toLowerCase();
const isContentEditable = el.getAttribute("contenteditable") === "true";
return !(
tagName === "input" ||
tagName === "textarea" ||
isContentEditable
);
}, [
{
combo: "S",
handler: () =>
setEditorState(
"timeline",
"interactMode",
editorState.timeline.interactMode === "split" ? "seek" : "split",
),
},
{
combo: "Mod+=",
handler: () =>
editorState.timeline.transform.updateZoom(
editorState.timeline.transform.zoom / 1.1,
editorState.playbackTime,
),
},
{
combo: "Mod+-",
handler: () =>
editorState.timeline.transform.updateZoom(
editorState.timeline.transform.zoom * 1.1,
editorState.playbackTime,
),
},
{
combo: "Space",
handler: async () => {
const prevTime = editorState.previewTime;
if (!editorState.playing) {
if (prevTime !== null) setEditorState("playbackTime", prevTime);
await commands.seekTo(Math.floor(editorState.playbackTime * FPS));
}
await handlePlayPauseClick();
},
},
]);
return (
<div class="flex flex-col flex-1 min-h-0">
<div class="flex items-center justify-between gap-3 p-3">
<div class="flex items-center gap-3">
<AspectRatioSelect />
<EditorButton
tooltipText="Crop Video"
onClick={cropDialogHandler}
leftIcon={<IconCapCrop class="w-5 text-gray-12" />}
>
Crop
</EditorButton>
</div>
<div class="flex items-center gap-2">
<span class="text-xs font-medium text-gray-11">Preview quality</span>
<KSelect<{ label: string; value: PreviewQuality }>
options={previewOptions}
optionValue="value"
optionTextValue="label"
value={previewOptions.find(
(option) => option.value === previewQuality(),
)}
onChange={(next) => {
if (next) handlePreviewQualityChange(next.value);
}}
disallowEmptySelection
itemComponent={(props) => (
<MenuItem<typeof KSelect.Item>
as={KSelect.Item}
item={props.item}
>
<KSelect.ItemLabel class="flex-1">
{props.item.rawValue.label}
</KSelect.ItemLabel>
<KSelect.ItemIndicator class="ml-auto text-blue-9">
<IconCapCircleCheck />
</KSelect.ItemIndicator>
</MenuItem>
)}
>
<KSelect.Trigger class="flex items-center gap-2 h-9 px-3 rounded-lg border border-gray-3 bg-gray-2 dark:bg-gray-3 text-sm text-gray-12">
<KSelect.Value<{
label: string;
value: PreviewQuality;
}> class="flex-1 text-left truncate">
{(state) =>
state.selectedOption()?.label ?? "Select preview quality"
}
</KSelect.Value>
<KSelect.Icon>
<IconCapChevronDown class="size-4 text-gray-11" />
</KSelect.Icon>
</KSelect.Trigger>
<KSelect.Portal>
<PopperContent<typeof KSelect.Content>
as={KSelect.Content}
class={cx(topLeftAnimateClasses, "w-44")}
>
<MenuItemList<typeof KSelect.Listbox>
as={KSelect.Listbox}
class="max-h-40"
/>
</PopperContent>
</KSelect.Portal>
</KSelect>
</div>
</div>
<PreviewCanvas />
<div class="flex overflow-hidden z-10 flex-row gap-3 justify-between items-center p-5">
<div class="flex-1">
<Time
class="text-gray-12"
seconds={Math.max(
editorState.previewTime ?? editorState.playbackTime,
0,
)}
/>
<span class="text-gray-11 text-[0.875rem] tabular-nums"> / </span>
<Time seconds={totalDuration()} />
</div>
<div class="flex flex-row items-center justify-center text-gray-11 gap-8 text-[0.875rem]">
<button
type="button"
class="transition-opacity hover:opacity-70 will-change-[opacity]"
onClick={async () => {
await commands.stopPlayback();
setEditorState("playing", false);
setEditorState("playbackTime", 0);
}}
>
<IconCapPrev class="text-gray-12 size-3" />
</button>
<Tooltip kbd={["Space"]} content="Play/Pause video">
<button
type="button"
onClick={handlePlayPauseClick}
class="flex justify-center items-center rounded-full border border-gray-300 transition-colors bg-gray-3 hover:bg-gray-4 hover:text-black size-9"
>
{!editorState.playing || isAtEnd() ? (
<IconCapPlay class="text-gray-12 size-3" />
) : (
<IconCapPause class="text-gray-12 size-3" />
)}
</button>
</Tooltip>
<button
type="button"
class="transition-opacity hover:opacity-70 will-change-[opacity]"
onClick={async () => {
await commands.stopPlayback();
setEditorState("playing", false);
setEditorState("playbackTime", totalDuration());
}}
>
<IconCapNext class="text-gray-12 size-3" />
</button>
</div>
<div class="flex flex-row flex-1 gap-4 justify-end items-center">
<div class="flex-1" />
<EditorButton<typeof KToggleButton>
tooltipText="Toggle Split"
kbd={["S"]}
pressed={editorState.timeline.interactMode === "split"}
onChange={(v: boolean) =>
setEditorState("timeline", "interactMode", v ? "split" : "seek")
}
as={KToggleButton}
variant="danger"
leftIcon={
<IconCapScissors
class={cx(
editorState.timeline.interactMode === "split"
? "text-white"
: "text-gray-12",
)}
/>
}
/>
<div class="w-px h-8 rounded-full bg-gray-4" />
<Tooltip kbd={["meta", "-"]} content="Zoom out">
<IconCapZoomOut
onClick={() => {
editorState.timeline.transform.updateZoom(
editorState.timeline.transform.zoom * 1.1,
editorState.playbackTime,
);
}}
class="text-gray-12 size-5 will-change-[opacity] transition-opacity hover:opacity-70"
/>
</Tooltip>
<Tooltip kbd={["meta", "+"]} content="Zoom in">
<IconCapZoomIn
onClick={() => {
editorState.timeline.transform.updateZoom(
editorState.timeline.transform.zoom / 1.1,
editorState.playbackTime,
);
}}
class="text-gray-12 size-5 will-change-[opacity] transition-opacity hover:opacity-70"
/>
</Tooltip>
<Slider
class="w-24"
minValue={0}
maxValue={1}
step={0.001}
value={[
Math.min(
Math.max(
1 - editorState.timeline.transform.zoom / zoomOutLimit(),
0,
),
1,
),
]}
onChange={([v]) => {
editorState.timeline.transform.updateZoom(
(1 - v) * zoomOutLimit(),
editorState.playbackTime,
);
}}
formatTooltip={() =>
`${editorState.timeline.transform.zoom.toFixed(
0,
)} seconds visible`
}
/>
</div>
</div>
</div>
);
}
// CSS for checkerboard grid (adaptive to light/dark mode)
const gridStyle = {
"background-image":
"linear-gradient(45deg, rgba(128,128,128,0.12) 25%, transparent 25%), " +
"linear-gradient(-45deg, rgba(128,128,128,0.12) 25%, transparent 25%), " +
"linear-gradient(45deg, transparent 75%, rgba(128,128,128,0.12) 75%), " +
"linear-gradient(-45deg, transparent 75%, rgba(128,128,128,0.12) 75%)",
"background-size": "40px 40px",
"background-position": "0 0, 0 20px, 20px -20px, -20px 0px",
"background-color": "rgba(200,200,200,0.08)",
};
function PreviewCanvas() {
const { latestFrame, canvasControls } = useEditorContext();
const hasRenderedFrame = () => canvasControls()?.hasRenderedFrame() ?? false;
const canvasTransferredRef = { current: false };
const [canvasContainerRef, setCanvasContainerRef] =
createSignal<HTMLDivElement>();
const containerBounds = createElementBounds(canvasContainerRef);
const [debouncedBounds, setDebouncedBounds] = createSignal({
width: 0,
height: 0,
});
const updateDebouncedBounds = debounce(
(width: number, height: number) => setDebouncedBounds({ width, height }),
100,
);
createEffect(() => {
const width = containerBounds.width ?? 0;
const height = containerBounds.height ?? 0;
if (debouncedBounds().width === 0 && debouncedBounds().height === 0) {
setDebouncedBounds({ width, height });
} else {
updateDebouncedBounds(width, height);
}
});
const isWindows = navigator.userAgent.includes("Windows");
const initCanvas = (canvas: HTMLCanvasElement) => {
if (canvasTransferredRef.current) return;
const controls = canvasControls();
if (!controls) return;
if (isWindows) {
controls.initDirectCanvas(canvas);
canvasTransferredRef.current = true;
return;
}
try {
const offscreen = canvas.transferControlToOffscreen();
controls.initCanvas(offscreen);
canvasTransferredRef.current = true;
} catch (e) {
console.error("[PreviewCanvas] Failed to transfer canvas:", e);
}
};
return (
<div
ref={setCanvasContainerRef}
class="relative flex-1 justify-center items-center"
style={{ contain: "layout style" }}
>
<Show when={latestFrame()}>
{(currentFrame) => {
const padding = 4;
const frameWidth = () => currentFrame().width;
const frameHeight = () => currentFrame().height;
const availableWidth = () =>
Math.max(debouncedBounds().width - padding * 2, 0);
const availableHeight = () =>
Math.max(debouncedBounds().height - padding * 2, 0);
const containerAspect = () => {
const width = availableWidth();
const height = availableHeight();
if (width === 0 || height === 0) return 1;
return width / height;
};
const frameAspect = () => {
const width = frameWidth();
const height = frameHeight();
if (width === 0 || height === 0) return containerAspect();
return width / height;
};
const size = () => {
let width: number;
let height: number;
if (frameAspect() < containerAspect()) {
height = availableHeight();
width = height * frameAspect();
} else {
width = availableWidth();
height = width / frameAspect();
}
return { width, height };
};
return (
<div class="flex overflow-hidden absolute inset-0 justify-center items-center h-full">
<div
class="relative"
style={{
width: `${size().width}px`,
height: `${size().height}px`,
contain: "strict",
}}
>
<canvas
style={{
width: `${size().width}px`,
height: `${size().height}px`,
"image-rendering": "auto",
"background-color": "#000000",
...(hasRenderedFrame() ? gridStyle : {}),
}}
ref={initCanvas}
id="canvas"
width={frameWidth()}
height={frameHeight()}
/>
<MaskOverlay size={size()} />
<TextOverlay size={size()} />
</div>
</div>
);
}}
</Show>
</div>
);
}
function Time(props: { seconds: number; fps?: number; class?: string }) {
return (
<span class={cx("text-gray-11 text-sm tabular-nums", props.class)}>
{formatTime(props.seconds, props.fps ?? FPS)}
</span>
);
}