-
-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathcompositeLayout.ts
More file actions
715 lines (659 loc) · 26.7 KB
/
Copy pathcompositeLayout.ts
File metadata and controls
715 lines (659 loc) · 26.7 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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
import { frameFootprint, frameUnit } from "@/lib/frameFootprint";
import {
DEFAULT_WEBCAM_ROUNDNESS,
type RecordingFrame,
WEBCAM_SIZE_MAX,
WEBCAM_SIZE_MIN,
type WebcamAnchor,
webcamAnchorFractions,
} from "@/lib/projectDefaults";
import { clamp01 } from "@/utils/math";
export interface RenderRect {
x: number;
y: number;
width: number;
height: number;
}
export interface StyledRenderRect extends RenderRect {
borderRadius: number;
maskShape?: import("@/components/video-editor/types").WebcamMaskShape;
}
/**
* The camera's rect during a "Full Camera" region: its layout rect at `progress` 0,
* the WHOLE frame at 1.
*
* Full Camera is not a zoom of the picture-in-picture bubble — it is the camera taking
* the frame. The endpoint is exactly `[0, 0, canvasWidth, canvasHeight]`: no margin, no
* padding, no corner rounding, and nothing of the composition (wallpaper, screen,
* shadow) left showing behind it. The box may change aspect ratio on its way there
* because every renderer cover-crops the camera into whatever box it is handed, so the
* image is never stretched by the animation.
*
* The mask shape degenerates to a plain rounded rectangle whose radius eases to 0, which
* is what makes the morph continuous instead of a pop: `computeCompositeLayout` already
* gives a circle mask a radius of half its (square) box, and a rounded rect at that
* radius IS that circle — so one lerp carries every shape out of existence with no
* per-shape branch.
*
* Pure, and shared by the preview, both exporters and the native compositor, so all four
* animate to the identical rect.
*/
export function computeCameraFullscreenRect(
base: StyledRenderRect,
canvasSize: Size,
progress: number,
): StyledRenderRect {
const t = Math.max(0, Math.min(1, progress));
const lerp = (from: number, to: number) => from + (to - from) * t;
return {
x: lerp(base.x, 0),
y: lerp(base.y, 0),
width: lerp(base.width, canvasSize.width),
height: lerp(base.height, canvasSize.height),
borderRadius: lerp(base.borderRadius, 0),
maskShape: "rectangle",
};
}
export interface Size {
width: number;
height: number;
}
export type WebcamLayoutPreset =
| "picture-in-picture"
| "vertical-stack"
| "dual-frame"
| "no-webcam";
/** Webcam size as a percentage of the canvas reference dimension (15–50). */
export type WebcamSizePreset = number;
export interface WebcamLayoutShadow {
color: string;
blur: number;
offsetX: number;
offsetY: number;
}
interface BorderRadiusRule {
max: number;
min: number;
fraction: number;
}
interface OverlayTransform {
type: "overlay";
marginFraction: number;
minMargin: number;
minSize: number;
}
/**
* Screen + camera welded into one solid block that keeps the screen capture's own
* aspect ratio, then contain-fits into the (padded) scene — see the design notes in
* `computeCompositeLayout`. Used by both "Side by side" and "Top / bottom".
*/
interface BlockTransform {
type: "block";
/** Where the camera sits relative to the screen: beside it, or under it. */
direction: "row" | "column";
/** Gap between screen and camera, as a fraction of the screen's own width. */
gapFraction: number;
}
export interface WebcamLayoutPresetDefinition {
label: string;
transform: OverlayTransform | BlockTransform;
borderRadius: BorderRadiusRule;
shadow: WebcamLayoutShadow | null;
}
/**
* Presets whose camera box is welded to the screen. Their geometry is fully derived
* from the screen capture's aspect ratio, so the webcam-size slider, the mask-shape
* picker and the reactive "shrink on zoom" scaling have nothing to act on there.
*/
export function isWebcamBlockLayout(preset: WebcamLayoutPreset = "picture-in-picture"): boolean {
return preset === "dual-frame" || preset === "vertical-stack";
}
/**
* Whether "shrink on zoom" (the reactive webcam scaling) applies to a preset. Only the
* free-floating picture-in-picture bubble can shrink: the block layouts size their
* camera off the screen box, so shrinking it would break the "same width / same height
* as the screen capture" contract and tear a hole in the block. Single rule shared by
* the UI (which hides the toggle), the preview, both exporters and the native scene.
*/
export function supportsWebcamReactiveZoom(
preset: WebcamLayoutPreset = "picture-in-picture",
): boolean {
return preset === "picture-in-picture";
}
/** Effective reactive-zoom flag: the stored setting, gated by the active preset. */
export function resolveWebcamReactiveZoom(
preset: WebcamLayoutPreset | undefined,
enabled: boolean | undefined,
): boolean {
return Boolean(enabled) && supportsWebcamReactiveZoom(preset);
}
/**
* Effective layout preset: the stored setting, gated by whether there is a camera to lay
* out at all. Without one the answer is `no-webcam` whatever the panel holds — hiding
* just the webcam slot is not enough, because the block presets size the SCREEN off the
* block and would leave it squeezed into half an empty canvas. One rule shared by the
* settings panel, the preview and the native scene, so the three cannot drift.
*
* `hasCamera` is the caller's question to answer, and they do not all ask it the same
* way on purpose: the preview and the scene resolve it per clip, while the settings
* panel asks whether the project has any camera at all.
*/
export function resolveWebcamLayoutPreset(
preset: WebcamLayoutPreset | undefined,
hasCamera: boolean,
): WebcamLayoutPreset {
return hasCamera ? (preset ?? "picture-in-picture") : "no-webcam";
}
export interface WebcamCompositeLayout {
screenRect: RenderRect;
webcamRect: StyledRenderRect | null;
screenBorderRadius?: number;
/**
* When true, the video should be scaled to cover screenRect (cropping overflow), and
* screenRect masks it: a zoom or a 3D tilt stays inside instead of growing past it.
*/
screenCover?: boolean;
}
/** Convert a webcam size percentage (15–50) to a fraction (0..1) of the reference dimension. */
export function webcamSizeToFraction(percent: number): number {
const safe = Number.isFinite(percent) ? percent : 25;
const clamped = Math.max(WEBCAM_SIZE_MIN, Math.min(WEBCAM_SIZE_MAX, safe));
return clamped / 100;
}
const MARGIN_FRACTION = 0.02;
const MAX_BORDER_RADIUS = 24;
/** Picture-in-picture rounds by the user's `webcamRoundness`, and no-webcam draws no camera. */
const NO_PRESET_ROUNDING = { max: 0, min: 0, fraction: 0 };
/**
* Breathing room between the screen box and the camera box inside a block layout,
* as a fraction of the screen's own width. Expressed against the screen (not the
* canvas) so it scales with the block itself: the same value reads as the same
* visual gap whether the block is width- or height-constrained by the scene.
*/
const BLOCK_GAP_FRACTION = 0.02;
/**
* How far the camera box may drift from square, as a maximum aspect ratio (its
* reciprocal is the minimum). The camera's free side is chosen to make the whole
* block match the SCENE's aspect ratio — perfect contain-fit, no bars — but the
* result is then held within `[1/T, T]` of square, so the camera never becomes an
* extreme slice. This single knob is the whole of "the camera tends toward square,
* going only slightly rectangular when filling the scene asks it to". `1.25` keeps
* it between 4:5 and 5:4.
*/
const BLOCK_CAMERA_ASPECT_TOLERANCE = 1.25;
const WEBCAM_LAYOUT_PRESET_MAP: Record<WebcamLayoutPreset, WebcamLayoutPresetDefinition> = {
"picture-in-picture": {
label: "Picture in Picture",
transform: {
type: "overlay",
marginFraction: MARGIN_FRACTION,
minMargin: 0,
minSize: 0,
},
borderRadius: NO_PRESET_ROUNDING,
shadow: {
color: "rgba(0,0,0,0.35)",
blur: 24,
offsetX: 0,
offsetY: 10,
},
},
"vertical-stack": {
label: "Top / bottom",
transform: {
type: "block",
direction: "column",
gapFraction: BLOCK_GAP_FRACTION,
},
borderRadius: {
max: 24,
min: 8,
fraction: 0.06,
},
shadow: null,
},
"dual-frame": {
label: "Side by side",
transform: {
type: "block",
direction: "row",
gapFraction: BLOCK_GAP_FRACTION,
},
borderRadius: {
max: MAX_BORDER_RADIUS,
min: 12,
fraction: 0.06,
},
shadow: null,
},
"no-webcam": {
label: "No Webcam",
transform: {
type: "overlay",
marginFraction: 0,
minMargin: 0,
minSize: 0,
},
borderRadius: NO_PRESET_ROUNDING,
shadow: null,
},
};
export const WEBCAM_LAYOUT_PRESETS = Object.entries(WEBCAM_LAYOUT_PRESET_MAP).map(
([value, preset]) => ({
value: value as WebcamLayoutPreset,
label: preset.label,
}),
);
export function getWebcamLayoutPresetDefinition(
preset: WebcamLayoutPreset = "picture-in-picture",
): WebcamLayoutPresetDefinition {
return WEBCAM_LAYOUT_PRESET_MAP[preset];
}
export function getWebcamLayoutCssBoxShadow(
preset: WebcamLayoutPreset = "picture-in-picture",
): string {
const shadow = getWebcamLayoutPresetDefinition(preset).shadow;
return shadow
? `${shadow.offsetX}px ${shadow.offsetY}px ${shadow.blur}px ${shadow.color}`
: "none";
}
/**
* A block's footprint in UNIT space, where the screen is exactly 1 wide: the screen's element
* (the screen, or the frame around it), the gap, and a camera `cameraAlong` long on the split
* axis. One definition for the layout below and for the resting shape Auto frames, so the two
* cannot disagree on it.
*/
function blockUnitSize(element: Size, block: BlockTransform, cameraAlong: number): Size {
return block.direction === "row"
? { width: element.width + block.gapFraction + cameraAlong, height: element.height }
: { width: element.width, height: element.height + block.gapFraction + cameraAlong };
}
/**
* The screen and its frame at rest, in UNIT space where the screen is exactly 1 wide: the
* frame's body, everything it draws, and the box of the whole (`element`). The frame's thickness
* follows the scene it is drawn in (`frameUnit`), of which only the shape counts. Without a
* frame every inset is 0 and the element is the screen.
*/
function framedScreen(screenAspect: number, canvas: Size, frame: RecordingFrame) {
const screen = { width: 1, height: 1 / screenAspect };
const { body, outer } = frameFootprint(frame, screen, frameUnit(screen, canvas));
const element = {
width: outer[0] + screen.width + outer[2],
height: outer[1] + screen.height + outer[3],
};
return { screen, body, outer, element };
}
/**
* The composition's own shape (width / height) before any frame constrains it — what the
* Auto format frames. Nothing is bent to fit: the screen keeps its ratio, and a block
* layout's camera takes its resting shape, square, beside or under it. A picture-in-picture
* bubble floats over the screen, so the composition is the screen alone.
*
* The screen wears its device frame: every layout measures the padding from what that frame
* draws, so it is part of the shape. Its thickness follows the scene's shape, `canvas`, which
* `autoFormatAspect` settles.
*/
export function restingCompositionAspect(
screenSize: Size,
preset: WebcamLayoutPreset,
frame: RecordingFrame = "none",
canvas: Size = screenSize,
): number {
const { screen, body, element } = framedScreen(
screenSize.width / screenSize.height,
canvas,
frame,
);
const transform = getWebcamLayoutPresetDefinition(preset).transform;
if (transform.type !== "block") return element.width / element.height;
// Square, lined up with the frame's body, as `computeCompositeLayout` lays it at rest.
const cameraCross =
transform.direction === "row"
? body[1] + screen.height + body[3]
: body[0] + screen.width + body[2];
const block = blockUnitSize(element, transform, cameraCross);
return block.width / block.height;
}
/** The share of the frame the composition keeps at `padding` (0–100): 1 at 0%, 0.6 at 100%. */
export function paddingFit(padding: number): number {
return 1 - (Math.min(100, Math.max(0, padding)) / 100) * 0.4;
}
/**
* The box the composition is contain-fitted into: the frame minus its padding.
*
* A fixed format keeps `paddingFit` of each axis. An Auto frame (`evenBorder`) is shaped
* around the composition instead, so its padding is a border of one thickness on all four
* sides — `(1 - fit) / 2` of the short side, which is what a fixed format leaves on the
* short axis too. The two agree on a square frame, and on the short axis of any frame.
*/
export function paddedContentSize(canvas: Size, padding: number, evenBorder: boolean): Size {
const fit = paddingFit(padding);
if (!evenBorder) {
return { width: Math.round(canvas.width * fit), height: Math.round(canvas.height * fit) };
}
const border = ((1 - fit) / 2) * Math.min(canvas.width, canvas.height);
return {
width: Math.round(canvas.width - 2 * border),
height: Math.round(canvas.height - 2 * border),
};
}
/**
* The Auto frame's shape: the composition's resting shape plus an even padding border.
*
* With `paddedContentSize`'s border, the frame's elongation (long side / short side) is
* `fit · e + (1 − fit)` for a composition of elongation `e`: the composition's own at 0%
* padding, pulled toward square as the border grows. Orientation never flips.
*/
export function autoFrameAspect(compositionAspect: number, padding: number): number {
const fit = paddingFit(padding);
const elongation = Math.max(compositionAspect, 1 / compositionAspect);
const framed = fit * elongation + (1 - fit);
return compositionAspect >= 1 ? framed : 1 / framed;
}
/**
* What the Auto format resolves to: `autoFrameAspect` over `restingCompositionAspect`.
*
* Under a device frame the two depend on each other: the device's thickness follows the shape of
* the scene it is drawn in (`frameUnit`), and Auto shapes that scene around the device. Each pass
* lays the device out in the scene the previous one gave. A device is thin next to its screen, so
* each pass moves the shape by a small fraction of the one before, and a few leave nothing a pixel
* could show.
*/
export function autoFormatAspect(
screenSize: Size,
preset: WebcamLayoutPreset,
frame: RecordingFrame,
padding: number,
): number {
let aspect = autoFrameAspect(restingCompositionAspect(screenSize, preset), padding);
if (frame === "none") return aspect;
for (let pass = 0; pass < 8; pass++) {
const canvas = { width: aspect, height: 1 };
aspect = autoFrameAspect(restingCompositionAspect(screenSize, preset, frame, canvas), padding);
}
return aspect;
}
export function computeCompositeLayout(params: {
canvasSize: Size;
maxContentSize?: Size;
screenSize: Size;
webcamSize?: Size | null;
layoutPreset?: WebcamLayoutPreset;
webcamSizePreset?: WebcamSizePreset;
/** Picture-in-picture only: where the camera sits. The block layouts place their own. */
webcamAnchor?: WebcamAnchor;
webcamMaskShape?: import("@/components/video-editor/types").WebcamMaskShape;
/** Picture-in-picture only: 0 square corners to 1 fully round. */
webcamRoundness?: number;
/**
* The frame around the screen. Every layout makes room for everything it draws: the padding
* is measured from its outer edge. In the block layouts it is also the screen's fixed
* container, and the camera lines up with its body.
*/
frame?: RecordingFrame;
}): WebcamCompositeLayout | null {
const {
canvasSize,
maxContentSize = canvasSize,
screenSize,
webcamSize,
layoutPreset = "picture-in-picture",
webcamSizePreset = 25,
webcamAnchor = "bottom-right",
webcamMaskShape = "rectangle",
webcamRoundness = DEFAULT_WEBCAM_ROUNDNESS,
frame = "none",
} = params;
const { width: canvasWidth, height: canvasHeight } = canvasSize;
const { width: screenWidth, height: screenHeight } = screenSize;
// no-webcam: hide the webcam, screen fills the canvas normally.
if (layoutPreset === "no-webcam") {
const screenRect = centerScreen(canvasSize, screenSize, maxContentSize, frame);
return { screenRect, webcamRect: null };
}
const webcamWidth = webcamSize?.width;
const webcamHeight = webcamSize?.height;
const preset = getWebcamLayoutPresetDefinition(layoutPreset);
const MAX_STAGE_FRACTION = webcamSizeToFraction(webcamSizePreset);
if (canvasWidth <= 0 || canvasHeight <= 0 || screenWidth <= 0 || screenHeight <= 0) {
return null;
}
if (preset.transform.type === "block") {
const block = preset.transform;
if (!webcamWidth || !webcamHeight || webcamWidth <= 0 || webcamHeight <= 0) {
// No camera on this clip: the block degenerates to the screen alone, which
// contain-fits the padded area like every other preset does.
return {
screenRect: centerScreen(canvasSize, screenSize, maxContentSize, frame),
webcamRect: null,
};
}
// The block is laid out in UNIT space first, where the screen is exactly
// 1 wide and `h = 1 / screenAspect` tall. The gap and the camera are
// expressed against that same unit, so a single contain-fit at the end
// scales screen, gap and camera together.
//
// The camera's SOURCE aspect ratio plays no part: the box is a mask cut
// from the block's geometry, and the camera video is cover-cropped into it
// downstream (`screenCover` for the screen, the renderers' cover crop for
// the camera).
const screenAspect = screenWidth / screenHeight;
const unitScreenHeight = 1 / screenAspect; // h
const gap = block.gapFraction;
const isRow = block.direction === "row";
// The frame, at rest, in the same unit space. Here it is the screen's container: it
// neither zooms nor tilts (the footage does, inside it), so the block lays it out like
// the screen itself. Its BODY is what the camera lines up with; what sticks out of the
// body (a laptop's deck, a monitor's stand) keeps the gap to the camera. Without a frame
// every inset is 0 and the arithmetic below is the frameless one, term for term.
const { body, outer, element } = framedScreen(screenAspect, canvasSize, frame);
// The camera shares the screen's cross-edge (same height beside it, same
// width under it — the aligned edge that makes them one solid block), so its
// size ALONG the split axis is the one free dimension. Under a frame, the cross-edge
// is the frame's body. Three constraints fix it, in order:
// 1. screen keeps its own aspect ratio → screen is 1 × h, untouched;
// 2. the block contain-fits the padded area → pick `along` so the block's
// aspect equals that area's (fills it, no bars) — see `alongForFill`;
// 3. the camera tends toward square → but clamp `along` so the
// camera stays within `[1/T, T]` of square, so filling the scene only
// nudges it slightly rectangular, never into a slice.
// Square is `along === cameraCross`; the clamp is symmetric in both layouts.
//
// The target is the PADDED area, not the canvas: the block is fitted into the
// former, so that is the shape it has to match. The two only differ under an
// Auto frame's even border (`paddedContentSize`), which is exactly the shape of
// the block at rest, so the camera comes out square there by construction.
const contentWidth = Math.min(canvasWidth, Math.max(1, maxContentSize.width));
const contentHeight = Math.min(canvasHeight, Math.max(1, maxContentSize.height));
const cameraCross = isRow ? body[1] + unitScreenHeight + body[3] : body[0] + 1 + body[2];
const contentAspect = contentWidth / contentHeight;
const alongForFill = isRow
? contentAspect * element.height - element.width - gap // block width = w + gap + along
: element.width / contentAspect - element.height - gap; // block height = h + gap + along
const cameraAlong = Math.min(
cameraCross * BLOCK_CAMERA_ASPECT_TOLERANCE,
Math.max(cameraCross / BLOCK_CAMERA_ASPECT_TOLERANCE, alongForFill),
);
const unitCameraWidth = isRow ? cameraAlong : cameraCross;
const unitCameraHeight = isRow ? cameraCross : cameraAlong;
const { width: blockWidth, height: blockHeight } = blockUnitSize(element, block, cameraAlong);
// Contain-fit the whole block into the padded content area, so padding
// shrinks the BLOCK (not just the screen) and padding 0 leaves it flush
// against the two scene edges its own ratio makes it touch — bottom/top for a
// column, left/right for a row.
const scale = Math.min(contentWidth / blockWidth, contentHeight / blockHeight);
const originX = (canvasWidth - blockWidth * scale) / 2;
const originY = (canvasHeight - blockHeight * scale) / 2;
const screenRect = snapRect(
originX + outer[0] * scale,
originY + outer[1] * scale,
scale,
unitScreenHeight * scale,
);
// Beside or under the whole frame, lined up with its body.
const cameraRect = snapRect(
isRow ? originX + (element.width + gap) * scale : originX + (outer[0] - body[0]) * scale,
isRow ? originY + (outer[1] - body[1]) * scale : originY + (element.height + gap) * scale,
unitCameraWidth * scale,
unitCameraHeight * scale,
);
const webcamBorderRadius = Math.min(
preset.borderRadius.max,
Math.max(
preset.borderRadius.min,
Math.round(Math.min(cameraRect.width, cameraRect.height) * preset.borderRadius.fraction),
),
);
return {
screenRect,
// Both halves of the block are framed alike, so the screen picks up the
// camera's corner rounding instead of the free-standing Roundness slider.
screenBorderRadius: webcamBorderRadius,
webcamRect: {
...cameraRect,
borderRadius: webcamBorderRadius,
maskShape: "rectangle",
},
// The screen box already carries the capture's exact aspect ratio, so
// cover and contain agree here; cover just absorbs the ±1px rounding
// above instead of letterboxing a hairline of wallpaper into the frame.
screenCover: true,
};
}
const transform = preset.transform;
const screenRect = centerScreen(canvasSize, screenSize, maxContentSize, frame);
if (!webcamWidth || !webcamHeight || webcamWidth <= 0 || webcamHeight <= 0) {
return { screenRect, webcamRect: null };
}
const margin = Math.max(
transform.minMargin,
Math.round(Math.min(canvasWidth, canvasHeight) * transform.marginFraction),
);
// The SHORT axis, not the geometric mean: sqrt(w*h) sits close to the diagonal, so at an
// extreme aspect ratio (e.g. 9:16) it barely shrinks even though the actual narrow axis is
// much smaller — the webcam box then ends up a large fraction of that narrow axis, eating
// most of the room there is to drag it around (reported: dragging the webcam PiP felt stuck
// in a wide "dead band" near each edge — confirmed via logging: a 230px-wide 9:16 frame at a
// modest 34% size preset produced a 104px-wide box, 45% of the frame's own width). Using the
// short axis directly still keeps the box the same size when width/height are swapped
// (min(a,b) is symmetric, same as sqrt(a*b) was), but it now actually shrinks with whichever
// axis is the tight constraint, instead of only reacting to the frame's overall area.
const referenceDim = Math.min(canvasWidth, canvasHeight);
const maxWidth = Math.max(transform.minSize, referenceDim * MAX_STAGE_FRACTION);
const maxHeight = Math.max(transform.minSize, referenceDim * MAX_STAGE_FRACTION);
const scale = Math.min(maxWidth / webcamWidth, maxHeight / webcamHeight);
let width = Math.round(webcamWidth * scale);
let height = Math.round(webcamHeight * scale);
// Shape-specific dimension adjustments
if (webcamMaskShape === "circle" || webcamMaskShape === "square") {
const side = Math.min(width, height);
width = side;
height = side;
}
// The anchor's corner or edge middle, the same margin from the border whatever the
// camera's size: the camera takes 0, a half or all of the room it leaves on each axis.
const [fx, fy] = webcamAnchorFractions(webcamAnchor);
const webcamX = Math.max(0, Math.round(margin + fx * (canvasWidth - 2 * margin - width)));
const webcamY = Math.max(0, Math.round(margin + fy * (canvasHeight - 2 * margin - height)));
// A fraction of half the short side, so the shape holds at any size and resolution:
// at 1 a square camera is a circle, a rectangular one a pill.
const borderRadius = Math.round((clamp01(webcamRoundness) * Math.min(width, height)) / 2);
return {
screenRect,
webcamRect: {
x: webcamX,
y: webcamY,
width,
height,
borderRadius,
maskShape: webcamMaskShape,
},
};
}
/**
* Rounds a float rect to whole pixels by rounding its EDGES rather than its origin
* and size independently. Adjacent boxes computed from the same float grid then keep
* a consistent gap, and the block's outer edges land exactly where the contain-fit
* put them, instead of drifting by a pixel per box.
*/
function snapRect(x: number, y: number, width: number, height: number): RenderRect {
const left = Math.round(x);
const top = Math.round(y);
return {
x: left,
y: top,
width: Math.max(1, Math.round(x + width) - left),
height: Math.max(1, Math.round(y + height) - top),
};
}
/**
* The screen with nothing welded to it, contain-fitted into the padded area and centred.
*
* Under a frame, what fits and centres is everything the frame draws: a window's bar, a laptop's
* deck, a monitor's stand. The padding is measured from the frame's outer edge, so at 0% the frame
* touches the scene and never goes past it, and a lopsided frame sits in the middle as a whole.
* The screen pays for it: it is smaller under a frame than without one.
*/
function centerScreen(
canvasSize: Size,
screenSize: Size,
maxContentSize: Size,
frame: RecordingFrame,
): RenderRect {
if (frame === "none") {
return centerRect({ canvasSize, size: screenSize, maxSize: maxContentSize });
}
const { screen, outer, element } = framedScreen(
screenSize.width / screenSize.height,
canvasSize,
frame,
);
const scale = Math.min(
maxContentSize.width / element.width,
maxContentSize.height / element.height,
);
const originX = (canvasSize.width - element.width * scale) / 2;
const originY = (canvasSize.height - element.height * scale) / 2;
return snapRect(
originX + outer[0] * scale,
originY + outer[1] * scale,
scale,
screen.height * scale,
);
}
function centerRect(params: { canvasSize: Size; size: Size; maxSize: Size }): RenderRect {
const { canvasSize, size, maxSize } = params;
return centerRectInBounds({
bounds: { x: 0, y: 0, width: canvasSize.width, height: canvasSize.height },
size,
maxSize,
});
}
function centerRectInBounds(params: { bounds: RenderRect; size: Size; maxSize: Size }): RenderRect {
const { bounds, size, maxSize } = params;
const { x: boundsX, y: boundsY, width: boundsWidth, height: boundsHeight } = bounds;
const { width, height } = size;
const { width: maxWidth, height: maxHeight } = maxSize;
const scale = Math.min(maxWidth / width, maxHeight / height);
const resolvedWidth = Math.round(width * scale);
const resolvedHeight = Math.round(height * scale);
if (
maxWidth >= boundsWidth &&
maxHeight >= boundsHeight &&
Math.abs(boundsWidth - resolvedWidth) <= 4 &&
Math.abs(boundsHeight - resolvedHeight) <= 4
) {
return {
x: boundsX,
y: boundsY,
width: boundsWidth,
height: boundsHeight,
};
}
return {
x: boundsX + Math.max(0, Math.floor((boundsWidth - resolvedWidth) / 2)),
y: boundsY + Math.max(0, Math.floor((boundsHeight - resolvedHeight) / 2)),
width: resolvedWidth,
height: resolvedHeight,
};
}