@softure-ai/marketing-kit 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +11 -0
  3. package/dist/footage/draft-overlays.d.ts +27 -1
  4. package/dist/footage/draft-overlays.d.ts.map +1 -1
  5. package/dist/footage/draft-overlays.js +169 -37
  6. package/dist/footage/draft-overlays.js.map +1 -1
  7. package/dist/footage/draft-text-width.d.ts +13 -0
  8. package/dist/footage/draft-text-width.d.ts.map +1 -1
  9. package/dist/footage/draft-text-width.js +12 -1
  10. package/dist/footage/draft-text-width.js.map +1 -1
  11. package/dist/footage/draft.d.ts +7 -1
  12. package/dist/footage/draft.d.ts.map +1 -1
  13. package/dist/footage/draft.js +9 -1
  14. package/dist/footage/draft.js.map +1 -1
  15. package/dist/footage/overlay-html.d.ts +13 -4
  16. package/dist/footage/overlay-html.d.ts.map +1 -1
  17. package/dist/footage/overlay-html.js +15 -9
  18. package/dist/footage/overlay-html.js.map +1 -1
  19. package/dist/footage/overlay-motion.d.ts +31 -4
  20. package/dist/footage/overlay-motion.d.ts.map +1 -1
  21. package/dist/footage/overlay-motion.js +53 -5
  22. package/dist/footage/overlay-motion.js.map +1 -1
  23. package/dist/footage/overlays.d.ts +64 -2
  24. package/dist/footage/overlays.d.ts.map +1 -1
  25. package/dist/footage/overlays.js +112 -4
  26. package/dist/footage/overlays.js.map +1 -1
  27. package/dist/index.d.ts +4 -4
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +4 -4
  30. package/dist/index.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/footage/draft-overlays.ts +202 -36
  33. package/src/footage/draft-text-width.ts +22 -1
  34. package/src/footage/draft.ts +11 -2
  35. package/src/footage/overlay-html.ts +20 -8
  36. package/src/footage/overlay-motion.ts +61 -5
  37. package/src/footage/overlays.ts +132 -4
  38. package/src/index.ts +17 -0
@@ -1,9 +1,10 @@
1
+ import { FOOTAGE_FPS } from "./normalize.js";
1
2
  import { getCornerRadiusPx, type BrandStyle, type CornerRadius } from "./brand-style.js";
2
3
  import { getDraftBoxEvents } from "./draft-boxes.js";
3
4
  import { toAssColor } from "./draft-color.js";
4
- import { getSpacingWidth, toDraftAssSize, toDraftSpacing, wrapDraftLine, type DraftFont } from "./draft-text-width.js";
5
+ import { DEFAULT_CONTENT_AREA, getSpacingWidth, toDraftAssSize, toDraftSpacing, wrapDraftLine, type DraftFont } from "./draft-text-width.js";
5
6
  import { HAND_FONT, getHandFontAssSize } from "./hand-font.js";
6
- import { getCounterSeconds, getOverlayColors, getPlaceCardTimes, getTypingTimes, type OverlayColors } from "./overlay-html.js";
7
+ import { getCounterValueAt, getOverlayColors, getPlaceCardTimes, getTypingStep, getTypingTimes, type OverlayColors } from "./overlay-html.js";
7
8
  import {
8
9
  DROP_LETTER_SECONDS,
9
10
  NOTE_GROW_FROM_SCALE,
@@ -11,6 +12,7 @@ import {
11
12
  NOTE_TICK_SECONDS,
12
13
  OVERLAY_EASES,
13
14
  getDropLetterTimes,
15
+ getFrameSteps,
14
16
  PIN_DROP_SECONDS,
15
17
  PIN_DROP_SHARE,
16
18
  UNDERLINE_EM,
@@ -18,6 +20,7 @@ import {
18
20
  getEntranceMotion,
19
21
  getExitMotion,
20
22
  getWipeHalves,
23
+ type OverlayEase,
21
24
  type OverlayEntranceMotion,
22
25
  type OverlayExitMotion,
23
26
  } from "./overlay-motion.js";
@@ -37,7 +40,14 @@ import {
37
40
  getChipCoveredTimes,
38
41
  getChipParts,
39
42
  getChipTickPoints,
43
+ COUNTER_UNIT_GAP_EM,
44
+ getCounterCard,
40
45
  getDrawnOverlayCard,
46
+ getKeywordMarkBlock,
47
+ getSideTextLayout,
48
+ KEYWORD_EDGE_EM,
49
+ MARK_PADDING_EM,
50
+ MARK_RADIUS_EM,
41
51
  getListCardsByItem,
42
52
  getListItemTimes,
43
53
  getListStops,
@@ -55,7 +65,9 @@ import {
55
65
  type OverlayBox,
56
66
  type OverlayFontRole,
57
67
  type OverlayPoint,
68
+ type OverlayTextMeasure,
58
69
  type ResolvedOverlay,
70
+ type SideTextLayout,
59
71
  } from "./overlays.js";
60
72
 
61
73
  /**
@@ -63,7 +75,7 @@ import {
63
75
  * drawn rounded cards of the brand's background, fitted to their text, with the text in its foreground; an
64
76
  * arrow is a straight shaft and head in the accent; a highlight the accent's outline round its rectangle; a pin and a
65
77
  * magnifier are drawings in the accent. A typed text shows letter by letter (the rest transparent, so its card keeps
66
- * its size), a counter steps up to its value every tenth of a second, a slide moves up into place. A `punch_in` is drawn
78
+ * its size), a counter shows its value in every frame, a slide moves up into place. A `punch_in` is drawn
67
79
  * by the picture's zoom (`buildPictureFilters`), not here. They sit on layers 3 and 4, over the captions' 0 to 2.
68
80
  */
69
81
 
@@ -78,8 +90,6 @@ const FADE = `\\fad(${FADE_IN_MS},${FADE_OUT_MS})`;
78
90
  /** How far a slide starts below its place, in px of a 1080 px wide frame, and how long it takes. */
79
91
  const SLIDE_PX = 28;
80
92
  const SLIDE_MS = 300;
81
- /** A counter's step in the draft, in seconds. */
82
- const COUNT_STEP = 0.1;
83
93
  /** A transparent primary colour: the typed text not shown yet. */
84
94
  const HIDDEN = "{\\1a&HFF&}";
85
95
 
@@ -188,6 +198,13 @@ interface DraftContext {
188
198
  spacing: (spacingEm: number, cssPx: number) => string;
189
199
  /** The brand's style: the cards' radius, shadow and border; absent: each kind's own corner, no shadow, no border. */
190
200
  style?: BrandStyle;
201
+ /**
202
+ * With the draft's fonts: the render's measure, so side texts, counters and highlight marks are laid out as the
203
+ * render lays them out (`getSideTextLayout`, `getCounterCard`); absent: the estimated cards of before.
204
+ */
205
+ layout?: OverlayTextMeasure;
206
+ /** The content area (ascent, descent in ems) of the font of `role`, as a browser sizes an inline box. */
207
+ contentArea: (role: DraftFontRole) => { ascentEm: number; descentEm: number };
191
208
  }
192
209
 
193
210
  /**
@@ -252,6 +269,24 @@ function getWipeClip(motion: DraftMotion): { x0: number; y0: number; x1: number;
252
269
  }
253
270
 
254
271
  const toClip = (box: { x0: number; y0: number; x1: number; y1: number }): string => `\\clip(${box.x0},${box.y0},${box.x1},${box.y1})`;
272
+
273
+ type ClipBox = { x0: number; y0: number; x1: number; y1: number };
274
+
275
+ /**
276
+ * A clip moving from `from` to `to` between `fromMs` and `toMs` of its event along the render's `ease`: one `\\t` per
277
+ * render frame (libass interpolates each straight), so the draft's clip stands where the render's does in every frame.
278
+ */
279
+ export function getEasedClipTags(from: ClipBox, to: ClipBox, input: { fromMs: number; toMs: number; ease: OverlayEase }): string {
280
+ const frames = Math.max(1, Math.round(((input.toMs - input.fromMs) / 1000) * FOOTAGE_FPS));
281
+ const at = (share: number): ClipBox => ({
282
+ x0: r0(from.x0 + (to.x0 - from.x0) * share),
283
+ y0: r0(from.y0 + (to.y0 - from.y0) * share),
284
+ x1: r0(from.x1 + (to.x1 - from.x1) * share),
285
+ y1: r0(from.y1 + (to.y1 - from.y1) * share),
286
+ });
287
+ const ms = (frame: number) => Math.round(input.fromMs + ((input.toMs - input.fromMs) * frame) / frames);
288
+ return Array.from({ length: frames }, (_unused, index) => `\\t(${ms(index)},${ms(index + 1)},${toClip(index + 1 === frames ? to : at(OVERLAY_EASES[input.ease]((index + 1) / frames)))})`).join("");
289
+ }
255
290
  const toMs = (seconds: number): number => Math.max(0, Math.round(seconds * 1000));
256
291
 
257
292
  /**
@@ -283,15 +318,16 @@ function getMotionTags(motion: DraftMotion, input: { isFirst: boolean; isLast: b
283
318
  if (input.isFirst && entrance.kind === "wipe") {
284
319
  const halves = getWipeHalves(entrance.seconds);
285
320
  const [grow, reveal] = [toMs(halves.grow), toMs(halves.reveal)];
286
- const closed = toClip({ ...clip, x1: clip.x0 });
287
- tags.push(input.part === "card" ? `${closed}\\t(0,${grow},${toClip(clip)})` : `${closed}\\t(${grow},${grow + reveal},${toClip(clip)})`);
321
+ const closed = { ...clip, x1: clip.x0 };
322
+ const half = input.part === "card" ? { fromMs: 0, toMs: grow } : { fromMs: grow, toMs: grow + reveal };
323
+ tags.push(`${toClip(closed)}${getEasedClipTags(closed, clip, { ...half, ease: entrance.ease })}`);
288
324
  }
289
325
  let fadeOut = 0;
290
326
  if (input.isLast && exit.kind !== "none") {
291
327
  if (exit.kind === "wipe") {
292
328
  const exitMs = toMs(exit.seconds);
293
329
  if (!(input.isFirst && entrance.kind === "wipe")) tags.push(toClip(clip));
294
- tags.push(`\\t(${Math.max(0, ms - exitMs)},${ms},${toClip({ ...clip, x0: clip.x1 })})`);
330
+ tags.push(getEasedClipTags(clip, { ...clip, x0: clip.x1 }, { fromMs: Math.max(0, ms - exitMs), toMs: ms, ease: exit.ease }));
295
331
  } else {
296
332
  fadeOut = motion.isSnappy ? r0(FADE_OUT_MS * 0.7) : FADE_OUT_MS;
297
333
  if (exit.kind === "tween" && exit.from.y > 0 && !motion.isCardMoved) {
@@ -404,7 +440,9 @@ function getWipePanelEvent(overlay: Pick<ResolvedOverlay, "start">, drawing: str
404
440
  const halves = getWipeHalves(motion.entrance.seconds);
405
441
  const [grow, reveal] = [toMs(halves.grow), toMs(halves.reveal)];
406
442
  const clip = getWipeClip(motion);
407
- const tags = `${toClip({ ...clip, x1: clip.x0 })}\\t(0,${grow},${toClip(clip)})\\t(${grow},${grow + reveal},${toClip({ ...clip, x0: clip.x1 })})`;
443
+ const ease = motion.entrance.ease;
444
+ const closed = { ...clip, x1: clip.x0 };
445
+ const tags = `${toClip(closed)}${getEasedClipTags(closed, clip, { fromMs: 0, toMs: grow, ease })}${getEasedClipTags(clip, { ...clip, x0: clip.x1 }, { fromMs: grow, toMs: grow + reveal, ease })}`;
408
446
  return [`Dialogue: 3,${toAssTime(overlay.start)},${toAssTime(overlay.start + motion.entrance.seconds)},OverlayShape,,0,0,0,,{\\an7\\pos(0,0)${tags}\\1c${toTagColor(accent)}\\p1}${drawing}{\\p0}`];
409
447
  }
410
448
 
@@ -429,10 +467,6 @@ export function getDropText(text: string, times: readonly number[], eventStart:
429
467
  .join("");
430
468
  }
431
469
 
432
- /** A highlight mark's padding round its text and its corner, in font sizes (as the render's `.ov-mark`). */
433
- const MARK_PADDING_EM = { x: 0.22, y: 0.04 } as const;
434
- const MARK_RADIUS_EM = 0.14;
435
-
436
470
  /**
437
471
  * A highlight backdrop's marks under one line of text (`style.backdrop` highlight): a tight rounded box in the card
438
472
  * colour, its width the text shown so far (each typed letter widens it, as the render's box grows), anchored where
@@ -450,14 +484,22 @@ function getBackdropMarkEvents(input: {
450
484
  typing: number | null;
451
485
  /** When the line starts typing, if not at the span's start (a second line of a title). */
452
486
  typeFrom?: number;
487
+ /**
488
+ * The render's measure of a line in the text's font and its content area: the mark is the text's width and its
489
+ * content area tall, centred in a line `lineHeight` tall from `top` (an inline box's background); absent: the
490
+ * estimated width and the whole line's height.
491
+ */
492
+ measured?: { measure: (text: string) => number; contentArea: { ascentEm: number; descentEm: number }; lineHeight: number };
453
493
  }): string[] {
454
- const { fontSize, span } = input;
494
+ const { fontSize, span, measured } = input;
455
495
  const pad = { x: fontSize * MARK_PADDING_EM.x, y: fontSize * MARK_PADDING_EM.y };
456
- const height = fontSize * OVERLAY_LINE_HEIGHT + 2 * pad.y;
496
+ const content = measured === undefined ? fontSize * OVERLAY_LINE_HEIGHT : fontSize * (measured.contentArea.ascentEm + measured.contentArea.descentEm);
497
+ const height = content + 2 * pad.y;
498
+ const top = measured === undefined ? input.top - pad.y : input.top + (fontSize * measured.lineHeight - content) / 2 - pad.y;
457
499
  const boxFor = (shown: string): OverlayBox => {
458
- const width = estimateTextWidth(shown, fontSize) + 2 * pad.x;
500
+ const width = (measured === undefined ? estimateTextWidth(shown, fontSize) : measured.measure(shown)) + 2 * pad.x;
459
501
  const left = input.align === "left" ? input.x - pad.x : input.align === "right" ? input.x + pad.x - width : input.x - width / 2;
460
- return { left, top: input.top - pad.y, width, height };
502
+ return { left, top, width, height };
461
503
  };
462
504
  const clean = toAssText(input.text);
463
505
  const steps =
@@ -499,6 +541,7 @@ function getUnderlineEvent(overlay: Extract<ResolvedOverlay, { kind: "keyword" }
499
541
  */
500
542
  function getSideTextEvents(overlay: Extract<ResolvedOverlay, { kind: "keyword" | "lower_third" | "list" }>, context: DraftContext): string[] {
501
543
  if (overlay.kind === "list") return getListEvents(overlay, context);
544
+ if (context.layout !== undefined) return getLaidOutSideTextEvents(overlay, context, context.layout);
502
545
  const colors = getOverlayColors(overlay, context.brand);
503
546
  const { fontSize, side } = overlay;
504
547
  // A side text always has a card: only a punch_in has none.
@@ -531,6 +574,104 @@ function getSideTextEvents(overlay: Extract<ResolvedOverlay, { kind: "keyword" |
531
574
  return [...shape, ...text({ x, y }, steps), ...(overlay.kind === "keyword" ? getUnderlineEvent(overlay, card, colors.accent, motion) : [])];
532
575
  }
533
576
 
577
+ /**
578
+ * A highlighted keyword's mark as the render draws it (`getKeywordMarkBlock`): one rounded block round its lines;
579
+ * while it types, the block of the letters typed so far, on the lines they take in the whole text.
580
+ */
581
+ function getBlockMarkEvents(input: {
582
+ overlay: Extract<ResolvedOverlay, { kind: "keyword" }>;
583
+ layout: SideTextLayout;
584
+ measure: OverlayTextMeasure;
585
+ colour: string;
586
+ motion: DraftMotion;
587
+ }): string[] {
588
+ const { overlay, layout } = input;
589
+ const { fontSize } = overlay;
590
+ const blockFor = (lines: readonly string[]): OverlayBox => getKeywordMarkBlock(overlay, layout, lines, input.measure);
591
+ const span = { start: overlay.start, end: overlay.end };
592
+ const text = layout.lines.join(" ");
593
+ const steps =
594
+ overlay.typing === null || overlay.entrance === null || overlay.entrance === "drop"
595
+ ? [{ from: span.start, to: span.end, lines: layout.lines }]
596
+ : getTypingTimes(span.start, text, overlay.typing).map((at, index, times) => {
597
+ // The typed letters stay on the lines they take in the whole text.
598
+ let left = index + 1;
599
+ const lines = layout.lines.map((line) => {
600
+ const shown = [...line].slice(0, Math.max(0, left)).join("").trimEnd();
601
+ left -= [...line].length + 1;
602
+ return shown;
603
+ });
604
+ return { from: Math.min(at, span.end), to: Math.min(times[index + 1] ?? span.end, span.end), lines: lines.filter((line) => line.length > 0) };
605
+ });
606
+ const visible = steps.filter((step) => step.to > step.from && step.lines.length > 0);
607
+ return visible.map((step, index) =>
608
+ getShapeEvent({ start: step.from, end: step.to }, getRoundedRectDrawing(blockFor(step.lines), fontSize * MARK_RADIUS_EM), input.colour, input.motion, 3, {
609
+ start: step.from,
610
+ end: step.to,
611
+ isFirst: index === 0,
612
+ isLast: index === visible.length - 1,
613
+ }),
614
+ );
615
+ }
616
+
617
+ /**
618
+ * A keyword or a lower third laid out as the render lays it out (`getSideTextLayout`): its card as wide and tall as
619
+ * its lines (a keyword with its accent edge, a lower third with its dot), each line its own event one CSS line apart,
620
+ * so libass's own line pitch does not stretch them; a highlighted keyword has one mark per line.
621
+ */
622
+ function getLaidOutSideTextEvents(overlay: Extract<ResolvedOverlay, { kind: "keyword" | "lower_third" }>, context: DraftContext, measure: OverlayTextMeasure): string[] {
623
+ const colors = getOverlayColors(overlay, context.brand);
624
+ const { fontSize } = overlay;
625
+ const layout = getSideTextLayout(overlay, measure);
626
+ const { card } = layout;
627
+ const role = OVERLAY_FONT_ROLES[overlay.kind];
628
+ const isCentred = overlay.kind === "keyword" && overlay.isCentred === true;
629
+ const isMarked = overlay.kind === "keyword" && overlay.backdrop === "highlight";
630
+ const motion = getDraftMotion(overlay, overlay.entrance === null || overlay.entrance === "type" ? "fade" : overlay.entrance, card, context);
631
+ const span = { start: overlay.start, end: overlay.end };
632
+ const lineHeight = fontSize * OVERLAY_LINE_HEIGHT;
633
+ const tags = `\\an${isCentred ? 8 : 7}\\fs${context.toAssSize(role, fontSize)}${context.spacing(OVERLAY_LETTER_SPACING_EM.card, fontSize)}${getTextTags(overlay, colors, context, role)}`;
634
+ const edge = overlay.kind === "keyword" && !isMarked ? Math.round(fontSize * KEYWORD_EDGE_EM) : 0;
635
+ const shapes: string[] = [];
636
+ if (isMarked) {
637
+ // The render's highlighted keyword is one block (a flex item): one mark round all its lines, growing as it types.
638
+ shapes.push(...getBlockMarkEvents({ overlay, layout, measure, colour: colors.background, motion }));
639
+ } else {
640
+ const fill = getCardShapeEvents(overlay, { ...card, height: card.height - edge }, fontSize, colors, motion, context);
641
+ // The keyword's accent edge: the whole card in the accent under its fill, which leaves the edge's height at its foot.
642
+ const radius = getDraftCardRadius(overlay, card, context, getOwnCardRadius(overlay, card, fontSize));
643
+ const edgeEvents = edge === 0 || (overlay.kind === "keyword" && overlay.underline === true) ? [] : [getShapeEvent(overlay, getRoundedRectDrawing(card, radius), colors.accent, motion)];
644
+ const under = context.style?.shadow === "soft" ? 1 : 0;
645
+ shapes.push(...fill.slice(0, under), ...edgeEvents, ...fill.slice(under));
646
+ }
647
+ if (layout.dot !== null) {
648
+ // The dot settles in with the card (the render scales it in a little later; the draft shows it with its card).
649
+ shapes.push(getShapeEvent(overlay, getCircleDrawing(layout.dot.centre, layout.dot.radius), colors.accent, motion, 4));
650
+ }
651
+ const text = layout.lines.join(" ");
652
+ const letters = overlay.entrance === "drop" ? getDropLetterTimes(span.start, text) : [];
653
+ const isTyped = overlay.entrance !== null && overlay.entrance !== "drop" && overlay.typing !== null;
654
+ let typedBefore = 0;
655
+ const lines = layout.lines.flatMap((line, index) => {
656
+ const pos = { x: layout.textX, y: layout.textTop + index * lineHeight };
657
+ const lineStart = overlay.typing === null ? span.start : span.start + typedBefore / overlay.typing;
658
+ const count = [...line].length;
659
+ const steps =
660
+ overlay.entrance === "drop"
661
+ ? [{ from: span.start, to: span.end, text: getDropText(line, letters.slice(typedBefore, typedBefore + count), span.start) }]
662
+ : isTyped
663
+ ? getTypedSteps(line, { start: lineStart, end: span.end }, overlay.typing, isCentred)
664
+ : [{ from: span.start, to: span.end, text: toAssText(line) }];
665
+ typedBefore += count + 1;
666
+ // A left line holds its place transparent from the start, so its first event carries the entrance.
667
+ const held = isTyped && !isCentred ? steps.map((step, at) => (at === 0 ? { ...step, from: span.start } : step)) : steps;
668
+ const own = overlay.entrance === "drop" || (isTyped && isCentred) ? getPlainMotion(motion) : motion;
669
+ return getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags, steps: held, motion: own });
670
+ });
671
+ const underline = overlay.kind === "keyword" ? getUnderlineEvent(overlay, { ...card, height: card.height - edge }, colors.accent, motion) : [];
672
+ return [...shapes, ...lines, ...underline];
673
+ }
674
+
534
675
  /** A list's card grows to its next point's size over these seconds, in this many steps along the render's ease. */
535
676
  const LIST_GROW_SECONDS = 0.35;
536
677
  const LIST_GROW_STEPS = 3;
@@ -762,7 +903,9 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
762
903
  const motion = getDraftMotion(overlay, name, box, context);
763
904
  const span = { start: overlay.start, end: overlay.end };
764
905
  const isMarked = overlay.kind === "hook_title" && overlay.backdrop === "highlight";
765
- const events = isMarked ? [] : getCardShapeEvents(overlay, box, fontSize, colors, motion, context);
906
+ // A laid-out counter draws its card with each number it shows (below), as the render's card follows its text.
907
+ const isCounterLaidOut = overlay.kind === "counter" && context.layout !== undefined;
908
+ const events = isMarked || isCounterLaidOut ? [] : getCardShapeEvents(overlay, box, fontSize, colors, motion, context);
766
909
  const { x: padX, y: padY } = getOverlayPadding(overlay);
767
910
  const centerX = box.left + box.width / 2;
768
911
  const tagsFor = (role: OverlayFontRole) => getTextTags(overlay, colors, context, role);
@@ -800,17 +943,24 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
800
943
  if (overlay.kind === "hook_title" && (isMarked || overlay.entrance === "drop")) {
801
944
  const letters = getDropLetterTimes(span.start, overlay.lines.join(""));
802
945
  overlay.lines.forEach((line) => {
803
- const lineStart = overlay.typing === null ? span.start : span.start + typedBefore / overlay.typing;
946
+ const lineStart = overlay.typing === null ? span.start : span.start + typedBefore * getTypingStep(overlay.typing);
804
947
  if (isMarked) {
805
948
  const align = isLeft ? "left" : "center";
806
- events.push(...getBackdropMarkEvents({ text: line, x: lineX, align, top: y, fontSize, colour: colors.background, motion, span, typing: overlay.typing, typeFrom: lineStart }));
949
+ const { layout } = context;
950
+ const measured =
951
+ layout === undefined
952
+ ? {}
953
+ : { measured: { measure: (shown: string) => layout("heading", shown, fontSize, spacingFor("heading")), contentArea: context.contentArea("heading"), lineHeight } };
954
+ events.push(...getBackdropMarkEvents({ text: line, x: lineX, align, top: y, fontSize, colour: colors.background, motion, span, typing: overlay.typing, typeFrom: lineStart, ...measured }));
807
955
  }
808
956
  const steps =
809
957
  overlay.entrance === "drop"
810
958
  ? [{ from: span.start, to: span.end, text: getDropText(line, letters.slice(typedBefore, typedBefore + [...line].length), span.start) }]
811
959
  : getTypedSteps(line, { start: lineStart, end: span.end }, overlay.typing, !isLeft);
812
960
  const isQuiet = overlay.entrance === "drop" || (!isLeft && overlay.typing !== null);
813
- events.push(...text({ x: lineX, y }, lineAlign, fontSize, "heading", isLeft && overlay.entrance !== "drop" ? steps.map((step, index) => (index === 0 ? { ...step, from: span.start } : step)) : steps, isQuiet ? plain : motion));
961
+ // A left mark's padding pushes its text in, as an inline box's padding does in the render.
962
+ const textX = isMarked && isLeft && context.layout !== undefined ? lineX + fontSize * MARK_PADDING_EM.x : lineX;
963
+ events.push(...text({ x: textX, y }, lineAlign, fontSize, "heading", isLeft && overlay.entrance !== "drop" ? steps.map((step, index) => (index === 0 ? { ...step, from: span.start } : step)) : steps, isQuiet ? plain : motion));
814
964
  typedBefore += [...line].length;
815
965
  y += fontSize * lineHeight;
816
966
  });
@@ -819,7 +969,7 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
819
969
  overlay.lines.forEach((line) => {
820
970
  // The lines type one after the other, as the render's characters do; a left line holds its place transparent
821
971
  // from the start, a centred one shows its typed part only (`getTypedSteps`).
822
- const lineStart = overlay.typing === null ? times.title : span.start + typedBefore / overlay.typing;
972
+ const lineStart = overlay.typing === null ? times.title : span.start + typedBefore * getTypingStep(overlay.typing);
823
973
  const steps = getTypedSteps(line, { start: lineStart, end: span.end }, overlay.typing, !isLeft);
824
974
  // A centred typed line has no hidden first step to carry the entrance: its letters appear as typed, as the render's.
825
975
  const isTypedCentre = !isLeft && overlay.typing !== null;
@@ -845,20 +995,34 @@ function getCardEvents(overlay: CardOverlay, context: DraftContext): string[] {
845
995
  return events;
846
996
  }
847
997
  if (overlay.kind === "counter") {
848
- const unit = overlay.unit === null ? "" : `{\\fs${context.toAssSize("heading", overlay.unitFontSize)}} ${toAssText(overlay.unit)}`;
849
- const count = getCounterSeconds(overlay);
850
- const steps: TextStep[] = [];
851
- const ticks = Math.max(1, Math.round(count.duration / COUNT_STEP));
998
+ // Laid out, the unit stands the render's gap after the number: a hard space widened to it.
999
+ const gap = context.layout === undefined ? null : toDraftSpacing(overlay.fontSize * COUNTER_UNIT_GAP_EM - context.layout("heading", " ", overlay.unitFontSize, 0), 1);
1000
+ const space = gap === null ? " " : `{\\fsp${String(gap)}}\\h{\\fsp${String(toDraftSpacing(OVERLAY_LETTER_SPACING_EM.card, fontSize))}}`;
1001
+ const unit = overlay.unit === null ? "" : `{\\fs${context.toAssSize("heading", overlay.unitFontSize)}}${space}${toAssText(overlay.unit)}`;
852
1002
  const show = (value: number) => `${formatOverlayNumber(value, overlay.decimals, context.locale)}${unit}`;
853
- steps.push({ from: span.start, to: count.start, text: show(overlay.from) });
854
- for (let tick = 1; tick <= ticks; tick++) {
855
- const progress = tick / ticks;
856
- // power2.out, as the render's tween eases: the count slows down to its value.
857
- const eased = OVERLAY_EASES["power2.out"](progress);
858
- const value = overlay.from + (overlay.value - overlay.from) * eased;
859
- steps.push({ from: count.start + (tick - 1) * COUNT_STEP, to: tick === ticks ? span.end : count.start + tick * COUNT_STEP, text: show(value) });
860
- }
861
- return [...events, ...text({ x: centerX, y: box.top + box.height / 2 }, 5, fontSize, "heading", steps.filter((step) => step.to > step.from))];
1003
+ // One step per render frame, each the value the render's tween shows in that frame.
1004
+ const steps: TextStep[] = getFrameSteps({ start: span.start, end: span.end, fps: FOOTAGE_FPS, valueAt: (seconds) => show(getCounterValueAt(overlay, seconds)) });
1005
+ const shown = steps.filter((step) => step.to > step.from);
1006
+ const { layout } = context;
1007
+ if (layout === undefined) return [...events, ...text({ x: centerX, y: box.top + box.height / 2 }, 5, fontSize, "heading", shown)];
1008
+ // The render's card follows its number: one card per width the count shows, the entrance on the first, the exit on the last.
1009
+ const cardFor = (value: string): OverlayBox => getCounterCard(overlay, value, layout);
1010
+ // The number alone: the unit's override tags start at the first brace.
1011
+ const values = shown.map((step) => {
1012
+ const brace = step.text.indexOf("{");
1013
+ return brace === -1 ? step.text : step.text.slice(0, brace);
1014
+ });
1015
+ const runs: { card: OverlayBox; from: number; to: number }[] = [];
1016
+ shown.forEach((step, index) => {
1017
+ const card = cardFor(values[index] as string);
1018
+ const last = runs[runs.length - 1];
1019
+ if (last !== undefined && last.card.width === card.width) last.to = step.to;
1020
+ else runs.push({ card, from: step.from, to: step.to });
1021
+ });
1022
+ const final = runs[runs.length - 1]?.card ?? cardFor(formatOverlayNumber(overlay.value, overlay.decimals, context.locale));
1023
+ const counted = { ...motion, card: final };
1024
+ const cards = runs.flatMap((run, index) => getCardShapeEvents(overlay, run.card, fontSize, colors, counted, context, { start: run.from, end: run.to, isFirst: index === 0, isLast: index === runs.length - 1 }));
1025
+ return [...cards, ...text({ x: centerX, y: final.top + final.height / 2 }, 5, fontSize, "heading", shown, counted)];
862
1026
  }
863
1027
  const isRight = overlay.side === "right";
864
1028
  const x = isRight ? box.left + box.width - padX : box.left + padX;
@@ -961,7 +1125,7 @@ function getNoteEvents(overlay: Extract<ResolvedOverlay, { kind: "note" }>, cont
961
1125
  if (isStrip) {
962
1126
  const before = overlay.lines.slice(0, index).join("").length;
963
1127
  const typing = overlay.typing ?? 14;
964
- const steps = getTypedSteps(line, { start: overlay.start + before / typing, end: overlay.end }, typing).map((step, stepIndex) => (stepIndex === 0 ? { ...step, from: overlay.start } : step));
1128
+ const steps = getTypedSteps(line, { start: overlay.start + before * getTypingStep(typing), end: overlay.end }, typing).map((step, stepIndex) => (stepIndex === 0 ? { ...step, from: overlay.start } : step));
965
1129
  events.push(...getTextEvents({ layer: 4, style: "OverlayPlain", pos, tags, steps, motion: textMotion }));
966
1130
  return;
967
1131
  }
@@ -1027,7 +1191,9 @@ export function buildDraftOverlayEvents(
1027
1191
  toAssSize: (role, cssPx) => (drawn === undefined ? cssPx : toDraftAssSize(cssPx, drawn[role].assScale)),
1028
1192
  measure: (role, text, cssPx, spacingEm) => (drawn === undefined ? estimateTextWidth(text, cssPx) : drawn[role].measure(text, cssPx) + getSpacingWidth(text, spacingEm, cssPx)),
1029
1193
  spacing: (spacingEm, cssPx) => (drawn === undefined || spacingEm === 0 ? "" : `\\fsp${String(toDraftSpacing(spacingEm, cssPx))}`),
1194
+ contentArea: (role) => drawn?.[role].contentArea ?? DEFAULT_CONTENT_AREA,
1030
1195
  ...(options.style === undefined ? {} : { style: options.style }),
1196
+ ...(drawn === undefined ? {} : { layout: (role: OverlayFontRole, text: string, cssPx: number, spacingEm: number) => drawn[role].measure(text, cssPx) + getSpacingWidth(text, spacingEm, cssPx) }),
1031
1197
  };
1032
1198
  return overlays.flatMap((overlay) => {
1033
1199
  if (overlay.kind === "punch_in") return [];
@@ -16,6 +16,18 @@ interface Metrics {
16
16
  /** The font's units per em (`head`), what a browser sizes it by; 0 when the font has no `head`. */
17
17
  unitsPerEm: number;
18
18
  advances: (glyph: number) => number;
19
+ /** The ascent and descent of a browser's inline box, in font units: `hhea`'s, or OS/2's typo metrics when the font says to use them. */
20
+ ascent: number;
21
+ descent: number;
22
+ }
23
+
24
+ /** OS/2 `fsSelection` bit 7: a browser takes the typo ascender and descender for the line's content area. */
25
+ const USE_TYPO_METRICS = 1 << 7;
26
+
27
+ /** The content area's ascent and descent in font units, as a browser reads them (`hhea`, or typo metrics on request). */
28
+ function readContentArea(hhea: Buffer, os2: Buffer | undefined): { ascent: number; descent: number } {
29
+ if (os2 !== undefined && os2.length >= 72 && (readUint16(os2, 62) & USE_TYPO_METRICS) !== 0) return { ascent: readInt16(os2, 68), descent: -readInt16(os2, 70) };
30
+ return { ascent: readInt16(hhea, 4), descent: -readInt16(hhea, 6) };
19
31
  }
20
32
 
21
33
  function readMetrics(font: Buffer): Metrics | null {
@@ -32,7 +44,7 @@ function readMetrics(font: Buffer): Metrics | null {
32
44
  const head = tables.value.get("head");
33
45
  const unitsPerEm = head === undefined ? 0 : readUint16(head, 18);
34
46
  // Glyphs past `numberOfHMetrics` share the last advance (OpenType `hmtx`).
35
- return { unitsPerSize, unitsPerEm, advances: (glyph) => readUint16(hmtx, Math.min(glyph, count - 1) * 4) };
47
+ return { unitsPerSize, unitsPerEm, advances: (glyph) => readUint16(hmtx, Math.min(glyph, count - 1) * 4), ...readContentArea(hhea, os2) };
36
48
  }
37
49
 
38
50
  /**
@@ -69,8 +81,16 @@ export interface DraftFont {
69
81
  assScale: number;
70
82
  /** A line's width in CSS px at a CSS font size (advances per em; kerning not read). */
71
83
  measure: DraftTextMeasure;
84
+ /**
85
+ * The ascent and descent of the render's inline box (a highlight mark's background), in ems; absent for a font made
86
+ * elsewhere, which then takes `DEFAULT_CONTENT_AREA`.
87
+ */
88
+ contentArea?: { ascentEm: number; descentEm: number };
72
89
  }
73
90
 
91
+ /** The content area a font without its own is given, in ems: a common sans serif's. */
92
+ export const DEFAULT_CONTENT_AREA = { ascentEm: 0.93, descentEm: 0.24 } as const;
93
+
74
94
  /** The ASS size (`Fontsize`, `\fs`) that draws a font of `assScale` as large as the render's `cssPx`, to 0.01. */
75
95
  export function toDraftAssSize(cssPx: number, assScale: number): number {
76
96
  return Math.round(cssPx * assScale * 100) / 100;
@@ -107,6 +127,7 @@ export function createDraftFont(source: { family: string; file: string }, data:
107
127
  family: source.family,
108
128
  file: source.file,
109
129
  assScale: metrics.unitsPerSize / unitsPerEm,
130
+ contentArea: { ascentEm: metrics.ascent / unitsPerEm, descentEm: metrics.descent / unitsPerEm },
110
131
  measure: (text, fontSize) => {
111
132
  let units = 0;
112
133
  for (const character of text) units += metrics.advances(map.getGlyph(character.codePointAt(0) ?? 0));
@@ -16,12 +16,12 @@ import { toAssColor } from "./draft-color.js";
16
16
  import { buildDraftOverlayEvents, getDraftOverlayStyles, getRoundedRectDrawing } from "./draft-overlays.js";
17
17
  import { getCaptionCornerRadius, getCornerRadiusPx, getStylePadding, type BrandStyle } from "./brand-style.js";
18
18
  import { getDraftBoxEvents } from "./draft-boxes.js";
19
- import { createDraftFont, toDraftAssSize, toDraftSpacing, withLetterSpacing, wrapDraftLine, type DraftFont, type DraftTextMeasure } from "./draft-text-width.js";
19
+ import { createDraftFont, getSpacingWidth, toDraftAssSize, toDraftSpacing, withLetterSpacing, wrapDraftLine, type DraftFont, type DraftTextMeasure } from "./draft-text-width.js";
20
20
  import { CAPTION_LETTER_SPACING_EM, CAPTION_PILL_PADDING, CAPTION_RIBBON_LETTER_SPACING_EM } from "../compose/timeline.js";
21
21
  import { estimateTextWidth, isHandFontNeeded } from "./overlays.js";
22
22
  import { HAND_FONT } from "./hand-font.js";
23
23
  import type { OverlayColors } from "./overlay-html.js";
24
- import { resolveEdlOverlays, type OverlayFontRole, type ResolvedOverlay } from "./overlays.js";
24
+ import { resolveEdlOverlays, type OverlayFontRole, type OverlayTextMeasure, type ResolvedOverlay } from "./overlays.js";
25
25
  import { chooseFootageDraftFont } from "./draft-font.js";
26
26
  import { getEdlDuration, getSegmentStarts, remapWords, type Edl } from "./edl.js";
27
27
  import { declickSpeech, describeDeclick, type DeclickReport } from "./declick.js";
@@ -101,6 +101,15 @@ export function loadFootageDraftFonts(fonts: Partial<Record<"body" | OverlayFont
101
101
  return { body, heading: forRole("heading"), interface: forRole("interface") };
102
102
  }
103
103
 
104
+ /**
105
+ * The render's measure of overlay text (`OverlayTextMeasure`) from the draft's fonts: a line's width in CSS px in the
106
+ * font of its role, its letters spaced as the render spaces them. With it `getDrawnOverlayCard` answers the card the
107
+ * render lays out, as the draft draws it, so an app reports where a card really stands.
108
+ */
109
+ export function createOverlayTextMeasure(fonts: FootageDraftFonts): OverlayTextMeasure {
110
+ return (role, text, cssPx, spacingEm) => fonts[role].measure(text, cssPx) + getSpacingWidth(text, spacingEm, cssPx);
111
+ }
112
+
104
113
  /** How far a segment marked `kenburns` zooms when the film's `kenBurnsPercent` is 0, as in the render. */
105
114
  const HAND_KEN_BURNS_PERCENT = 4;
106
115
  const DRAFT_CRF = 28;
@@ -11,6 +11,7 @@ import {
11
11
  NOTE_GROW_FROM_SCALE,
12
12
  NOTE_GROW_SECONDS,
13
13
  NOTE_TICK_SECONDS,
14
+ OVERLAY_EASES,
14
15
  getDropLetterTurns,
15
16
  PIN_DROP_SECONDS,
16
17
  PIN_DROP_SHARE,
@@ -19,10 +20,15 @@ import {
19
20
  UNDERLINE_SECONDS,
20
21
  getEntranceMotion,
21
22
  getExitMotion,
23
+ getTypingStep,
22
24
  getWipeHalves,
25
+ OVERLAY_TYPING_DELAY,
26
+ type OverlayEase,
23
27
  type OverlayEntranceMotion,
24
28
  type OverlayMotionOffset,
25
29
  } from "./overlay-motion.js";
30
+
31
+ export { OVERLAY_TYPING_DELAY, getTypingStep, getTypingTimes } from "./overlay-motion.js";
26
32
  import {
27
33
  NOTE_LINE_HEIGHT,
28
34
  OVERLAY_LETTER_SPACING_EM,
@@ -72,8 +78,6 @@ const EXIT_SECONDS = 0.3;
72
78
  const STROKE_WIDTH = 10;
73
79
  /** The arrow head's length, in px of a 1080 px wide frame. */
74
80
  const ARROW_HEAD = 46;
75
- /** When a typed overlay starts typing, after its card has faded in, in seconds from its start. */
76
- export const OVERLAY_TYPING_DELAY = 0.3;
77
81
  /** When a counter starts counting, in seconds from its start. */
78
82
  const COUNT_DELAY = 0.15;
79
83
 
@@ -99,9 +103,17 @@ export function getCounterSeconds(overlay: { start: number; end: number }): { st
99
103
  return { start: r3(overlay.start + COUNT_DELAY), duration: r3(Math.min(1.6, Math.max(0.6, (overlay.end - overlay.start) * 0.5))) };
100
104
  }
101
105
 
102
- /** The film seconds each character of a typed text appears at, from `OVERLAY_TYPING_DELAY` after the overlay's start. */
103
- export function getTypingTimes(start: number, text: string, speed: number): number[] {
104
- return [...text].map((_char, index) => r3(start + OVERLAY_TYPING_DELAY + index / speed));
106
+ /** The ease a counter counts along. */
107
+ export const COUNTER_EASE = "power2.out" satisfies OverlayEase;
108
+
109
+ /**
110
+ * A counter's value at film second `seconds`, as the render's tween sets it: `from` until it starts counting, then
111
+ * along `COUNTER_EASE` to `value`, and `value` after. The draft shows this value in every frame.
112
+ */
113
+ export function getCounterValueAt(overlay: { start: number; end: number; from: number; value: number }, seconds: number): number {
114
+ const count = getCounterSeconds(overlay);
115
+ const progress = Math.min(1, Math.max(0, (seconds - count.start) / count.duration));
116
+ return overlay.from + (overlay.value - overlay.from) * OVERLAY_EASES[COUNTER_EASE](progress);
105
117
  }
106
118
 
107
119
  /** The CSS every overlay kind shares, written once when the film has any drawn overlay. */
@@ -320,7 +332,7 @@ function getExitTweens(target: string, overlay: Exclude<ResolvedOverlay, { kind:
320
332
  /** The typing tweens: each character of `#<id>` shown at its time. */
321
333
  function getTypingTweens(id: string, overlay: { start: number; typing: number | null }, length: number): string[] {
322
334
  if (overlay.typing === null || length === 0) return [];
323
- return [`tl.to("#${id} .ch", { opacity: 1, display: "inline", duration: 0.01, ease: "none", stagger: ${r3(1 / overlay.typing)} }, ${r3(overlay.start + OVERLAY_TYPING_DELAY)});`];
335
+ return [`tl.to("#${id} .ch", { opacity: 1, display: "inline", duration: 0.01, ease: "none", stagger: ${getTypingStep(overlay.typing)} }, ${r3(overlay.start + OVERLAY_TYPING_DELAY)});`];
324
336
  }
325
337
 
326
338
  /** Shows each typed line's highlight mark (`#<id>m<line>`, a keyword's `#<id>t`) with the line's first letter. */
@@ -329,7 +341,7 @@ function getMarkRevealTweens(ids: readonly string[], overlay: { start: number; t
329
341
  if (typing === null) return [];
330
342
  let offset = 0;
331
343
  return lines.flatMap((line, index) => {
332
- const at = overlay.start + OVERLAY_TYPING_DELAY + offset / typing;
344
+ const at = overlay.start + OVERLAY_TYPING_DELAY + offset * getTypingStep(typing);
333
345
  offset += [...line].length;
334
346
  const target = ids[index];
335
347
  return line === "" || target === undefined ? [] : [`tl.set("#${target}", { display: "inline" }, ${r3(at)});`];
@@ -540,7 +552,7 @@ function addCard(overlay: CardOverlay, id: string, context: MarkupContext, out:
540
552
  const format = `new Intl.NumberFormat(${toScriptString(getScriptLocale(context.locale))}, { minimumFractionDigits: ${overlay.decimals}, maximumFractionDigits: ${overlay.decimals} })`;
541
553
  // The number eases up to its value; the timeline renders it on every seek, so each frame shows its own count.
542
554
  out.tweens.push(
543
- `(function () { const el = document.getElementById("${id}n"); const nf = ${format}; const n = { v: ${overlay.from} }; tl.fromTo(n, { v: ${overlay.from} }, { v: ${overlay.value}, duration: ${count.duration}, ease: "power2.out", immediateRender: false, onUpdate: () => { el.textContent = nf.format(n.v).replace(/[\\u00a0\\u202f]/g, " "); } }, ${count.start}); })();`,
555
+ `(function () { const el = document.getElementById("${id}n"); const nf = ${format}; const n = { v: ${overlay.from} }; tl.fromTo(n, { v: ${overlay.from} }, { v: ${overlay.value}, duration: ${count.duration}, ease: "${COUNTER_EASE}", immediateRender: false, onUpdate: () => { el.textContent = nf.format(n.v).replace(/[\\u00a0\\u202f]/g, " "); } }, ${count.start}); })();`,
544
556
  );
545
557
  }
546
558
  out.tweens.push(...getExitTweens(`#${id} .ov-card`, overlay, context.frame, `tl.to("#${id} .ov-card", { y: 10, opacity: 0, duration: ${EXIT_SECONDS}, ease: "power2.in" }, ${r3(overlay.end - EXIT_SECONDS)});`));