remotion-ffmpeg-skill 0.12.1 → 0.13.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.
package/README.md CHANGED
@@ -97,6 +97,7 @@ Tool names and input schemas come from the machine-readable contract (`npx remot
97
97
  | `Highlights` | sum of ranked highlights | ffmpeg-skill's audio-energy highlights back to back, counter, title |
98
98
  | `BeatMontage` | source duration | audio unbroken, picture cuts on the measured beat grid |
99
99
  | `Karaoke` | source duration | words light up at the times a local speech engine measured |
100
+ | `Emphasis` | source duration | YouTube-style captions: the words you name (or the captions' own numbers / names) pop, change colour or get a box when spoken; speech bubbles and comment cards |
100
101
  | `Pip` | source duration | a second recording (camera) in a corner, synced by the offset measured between the two audio tracks; captions on top |
101
102
 
102
103
  **Any shape:** `--aspect 9:16 | 1:1 | 4:5 | 16:9` with `--fit blur | contain | cover`; `pipeline.py --platform reels` picks 9:16 from ffmpeg-skill's own template so nothing gets cropped on delivery.
package/SKILL.md CHANGED
@@ -49,6 +49,7 @@ Changing the shape alone is not a reason: ffmpeg-skill's Reels / TikTok / Shorts
49
49
  | "graphics that react to the audio / hit on the beat / on cuts" | `analyze.py [--beats]` → `render.py --comp PeakPulse` (pulses on beats when the grid was measured) |
50
50
  | "karaoke captions / words light up as they're spoken" | `analyze.py --words WORDS.json [--captions F.srt]` → `render.py --comp Karaoke` (word timings from a local speech engine, whisper JSON; without an SRT the cues are grouped from the words) |
51
51
  | "captions from the transcript" (transcription-skill output) | `analyze.py --words talk.transcript.json` → `render.py --comp Captioned` or `Karaoke`. Only schema `transcription-skill/transcript/0.1` is read, checked against its contract; another version, a broken document or one whose duration differs from the source by more than 0.5 s is refused (`kind: input`) — ask for a fresh transcript, never patch its times. Segments without word timings become one plain cue each (named in the warnings) |
52
+ | "YouTube-style captions" / "make these words pop" / speech bubbles, comment cards | `analyze.py --words WORDS.json --emphasis words.json` (the user's words: `["42%", {"text": "launch", "at": 12.3, "style": "box"}]`; `--emphasis-auto numbers,names` adds the captions' own numbers / capitalised or katakana names) → `render.py --comp Emphasis` (`emphasisStyle`, `bubbles`, `comments` in `--options`). A word that is not a whole, timed word of its cue is refused (`kind: input`): tell the user which, never respell the caption to make it fit |
52
53
  | "lower thirds / name titles / scene titles" | `render.py --comp Titled --options` with `lowerThirds` / `sceneTitles` — the text comes from the user; ask for it, never invent names |
53
54
  | "chapters" / a YouTube chapter list (`0:00 Intro` per line) | `analyze.py --chapters chapters.txt` (or `--chapters source` for markers the file already has) → `render.py --comp Titled` (a card at each chapter start, `chapterSeconds`) → `deliver.py --platform youtube --chapters chapters.txt` (markers in the file + `<name>_description.txt` to paste). Titles as written; a line without one is refused. Not with Jumpcut / Highlights: their cuts move every chapter |
54
55
  | "highlight reel / best moments" | `analyze.py --highlights N [--target S]` → `render.py --comp Highlights` (audio-energy ranking: candidates, say so) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remotion-ffmpeg-skill",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "description": "Agent Skill: ffmpeg-skill measures the footage, Remotion draws the motion graphics from those measurements, ffmpeg-skill checks and delivers the result. Timeline-driven captions, silence jump cuts and audio-peak motion with probe-first / verify-last rendering. Local, no API keys.",
5
5
  "keywords": [
6
6
  "remotion",
@@ -25,6 +25,8 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
25
25
  | `--output` | string | | timeline file (default: <name>.timeline.json) |
26
26
  | `--captions` | string | | SRT, WebVTT or JSON cue list to carry into the timeline (text kept as written) |
27
27
  | `--words` | string | | word timings for the Karaoke and Captioned compositions: a transcription-skill transcript (schema transcription-skill/transcript/0.1, validated strictly) or whisper JSON with word timestamps; without --captions the cues are grouped from these words |
28
+ | `--emphasis` | string | | words to emphasise in the Emphasis composition (pop, colour or box at the time each is spoken): a JSON list of words or {text, at?, style?}. Each must be a whole, timed word of a caption cue (of the cue showing at `at`), or it is refused; needs --words |
29
+ | `--emphasis-auto` | string | | with --words: also emphasise the captions' own numbers and/or names (comma-separated: numbers, names = capitalised mid-sentence or katakana words) |
28
30
  | `--chapters` | string | | chapter list, one `TIME TITLE` per line (YouTube's format, the same file ffmpeg-skill metadata.py --chapters writes into the container), or `source` for the chapters already in the input file; titles are kept as written |
29
31
  | `--pip` | string | | a second recording (camera) for the Pip composition: picture-in-picture over the source. The offset between the two is measured from their audio with ffmpeg-skill sync.py |
30
32
  | `--pip-offset` | number | | with --pip: the camera starts this many seconds after the source (negative: before), instead of measuring it -- for a camera without usable audio |
@@ -42,7 +44,7 @@ Measure a source with ffmpeg-skill and write timeline.json (+ captions from a fi
42
44
  | `--margin` | number | | seconds of silence kept around speech (default 0.15) |
43
45
  | `--scene-threshold` | number | | scenes.py --threshold (default 8) |
44
46
 
45
- --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `verified` (bool), `summary` (object: duration, fps, size, scenes, silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, conformed (list: vfr / hdr)), `warnings` (list[str])
47
+ --json result (besides `status`, `dry_run`, `output`): `commands` (list[str]), `verified` (bool), `summary` (object: duration, fps, size, scenes, silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, emphasis, conformed (list: vfr / hdr)), `warnings` (list[str])
46
48
 
47
49
  --dry-run --json result (besides `status`, `dry_run`, `output`): `commands` (list[str])
48
50
 
@@ -78,7 +80,7 @@ Render single frames as PNG to check the look before a full render.
78
80
  | Argument | Type | Default | Meaning |
79
81
  |---|---|---|---|
80
82
  | `--project (required)` | string | | Remotion project folder made by init.py |
81
- | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, or yours) |
83
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or yours) |
82
84
  | `--timeline (required)` | string | | timeline.json written by analyze.py |
83
85
  | `--options` | string | | JSON object of look-and-feel options |
84
86
  | `--at` | number, repeatable | | time in seconds (repeatable) |
@@ -108,7 +110,7 @@ Render a composition from a timeline, verify it (frames, fps, size, audio) and w
108
110
  | Argument | Type | Default | Meaning |
109
111
  |---|---|---|---|
110
112
  | `--project (required)` | string | | Remotion project folder made by init.py |
111
- | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, or one you added) |
113
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or one you added) |
112
114
  | `--timeline (required)` | string | | timeline.json written by analyze.py |
113
115
  | `--options` | string | | JSON object of look-and-feel options (see references/timeline.md) |
114
116
  | `--output` | string | | output file (default: <source>_<comp>.mp4, .mov for prores) |
@@ -171,7 +173,7 @@ analyze -> render -> deliver in one call, stopping at the first failed step.
171
173
  |---|---|---|---|
172
174
  | `input` | string, repeatable | | source video; several are joined in order (ffmpeg-skill join.py) first |
173
175
  | `--project (required)` | string | | Remotion project folder made by init.py |
174
- | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, or yours) |
176
+ | `--comp (required)` | string | | composition id (Captioned, Jumpcut, PeakPulse, Titled, Highlights, BeatMontage, Karaoke, Pip, Emphasis, or yours) |
175
177
  | `--captions` | string | | SRT / WebVTT / JSON cues for the timeline |
176
178
  | `--chapters` | string | | chapters (`TIME TITLE` per line, or `source`): cards in Titled and, with --platform, chapter markers in the deliverable |
177
179
  | `--options` | string | | JSON options file passed to the composition |
@@ -28,6 +28,7 @@ props (`{ "timeline": ..., "options": ..., "frame": ..., "font": ..., "overlay":
28
28
  | `chapters` | `[{start, end, title}]` | `--chapters FILE` (`TIME TITLE` per line, YouTube's format) or `--chapters source` (the file's own markers) | titles as written; each ends where the next starts. YouTube's rules (first at 0:00, at least three, each ≥ 10 s) become warnings |
29
29
  | `pip` | `{path, name, duration, width, height, fps, offset, confidence, measured}` or null | `--pip CAMERA` (offset from ffmpeg-skill sync.py over both audio tracks) or `--pip-offset` | offset = seconds after the source's start at which the camera's first frame belongs (negative: the camera started first) |
30
30
  | `words` | `[{start, end, text}]` | `--words` (whisper JSON with word timestamps, `{"words": [...]}` or a list) | per-word timings with the engine's own spacing; Karaoke lights them up |
31
+ | `emphasis` | `[{start, end, text, style, cue, span, words, by}]` | `--emphasis FILE` (the caller's words: a JSON list of words or `{text, at?, style?}`) and / or `--emphasis-auto numbers,names`; needs `--words` | each emphasised word as a slice of caption cue `cue`'s own timed words (`words` = [first, last] index into `words`): `start` / `end` are the engine's times of those words, `text` the caption's own spelling, `span` its [start, end) code-point offsets in the cue's text (the cue text is what is drawn; when `--captions` and `--words` disagree about a word, it is refused). `style` is `pop`, `color`, `box` or null (= the `emphasisStyle` option); `by` is `caller`, `numbers` or `names`. A caller's word that is not a whole, timed word of the cue (or of the cue showing at `at`) is refused (`kind: input`) |
31
32
  | `conform` | object \| null | analyze.py `--conform` | provenance when the source was VFR or HDR: `reasons` (`vfr`, `hdr`), `original` (path, name, sha256 fingerprint, duration, frame rates, colour tags), `output` (= `source.path`), `steps` (`{reason, tool, args, command, notes}` per ffmpeg-skill call: `fit.py --fps`, then `color.py --to-sdr`), `measured` (ffmpeg-skill probe of the copy: CFR, BT.709). `pip.conform` is the same for a conformed camera. null = the source was drawn on as it is |
32
33
  | `warnings` | `[string]` | analyze.py | rotation, odd frame rate, chapters, transcript (VFR and HDR are never warnings: conformed or refused) |
33
34
 
@@ -45,6 +46,7 @@ composition exactly.
45
46
  | `Titled` | source duration | source + the user's lower thirds (`lowerThirds`) + a title card at the start of each measured scene (`sceneTitles`, in order) + a chapter card at each chapter start (`chapters`, numbered n / total) |
46
47
  | `Highlights` | sum of `highlights` (whole file if none) | ranked ranges back to back in source order, flash on cuts, "2 / 5" counter, `title` over the first |
47
48
  | `Karaoke` | source duration | caption cues whose words light up at their measured times (current word accent + lift, spoken white, upcoming dimmed); cues without timed words show plain |
49
+ | `Emphasis` | source duration | YouTube-style captions: each cue as written; its `emphasis` words pop, take the accent colour or get an accent box from the time they are spoken to the end of the cue; speech bubbles (`bubbles`) and comment-style cards (`comments`) with the user's text at their own times |
48
50
  | `Pip` | source duration | the source with `pip` (a camera) in a corner while the camera has pictures, synced by `pip.offset`; captions on top as in Captioned |
49
51
  | `BeatMontage` | source duration | audio unbroken; the picture cuts every `beatsPerCut` measured beats, cycling through highlights (or scenes); no usable grid → cuts on scene changes |
50
52
 
@@ -71,6 +73,9 @@ Every key is optional.
71
73
  | `pipSize` | `0.28` | Pip: camera width as a fraction of the frame width (circle: of the short side), 0.05–0.6 |
72
74
  | `pipShape` | `"rounded"` | Pip: `rounded` or `circle` |
73
75
  | `pipAudio` | `false` | Pip: also play the camera's own audio |
76
+ | `emphasisStyle` | `"pop"` | Emphasis: `pop` (scales up, accent colour), `color` (accent colour) or `box` (accent box, dark text) for an emphasised word without its own `style` |
77
+ | `bubbles` | `[]` | Emphasis: speech bubbles `[{"text", "start", "end", "side"?}]` (`side`: `left` or `right`), the user's text, seconds on the source timeline |
78
+ | `comments` | `[]` | Emphasis: comment-style cards `[{"text", "start", "end", "author"?}]`, top left, stacked while they overlap; the user's text |
74
79
  | `chapterSeconds` | `4` | Titled: how long a chapter card stays up (cut short by the next chapter; 0 = none) |
75
80
 
76
81
  Unknown keys and wrong types are refused by render.py / still.py before anything renders.
@@ -9,7 +9,7 @@ import json
9
9
  import re
10
10
  import unicodedata
11
11
  from pathlib import Path
12
- from typing import Any, Dict, List, Optional
12
+ from typing import Any, Dict, List, Optional, Tuple
13
13
 
14
14
  _TS = re.compile(r"(?:(\d+):)?(\d{1,2}):(\d{2})[.,](\d{1,3})")
15
15
  _ARROW = re.compile(r"^\s*(\S+)\s+-->\s+(\S+)")
@@ -345,6 +345,215 @@ def read_word_timings(path: Path) -> Dict[str, Any]:
345
345
  return {"words": parse_words(text), "cues": None, "warnings": []}
346
346
 
347
347
 
348
+ # ---------------------------------------------------------------- emphasis (YouTube-style captions)
349
+
350
+ EMPHASIS_STYLES = ("pop", "color", "box")
351
+ EMPHASIS_AUTO = ("numbers", "names")
352
+ _SENTENCE_END = (".", "!", "?", "。", "!", "?")
353
+
354
+
355
+ def _fold(s: str) -> str:
356
+ """Lower case, one character for one character, so offsets in the folded text are offsets in the original."""
357
+ return "".join(ch.lower() if len(ch.lower()) == 1 else ch for ch in s)
358
+
359
+
360
+ def _is_punct(s: str) -> bool:
361
+ return all(unicodedata.category(ch)[0] in ("P", "Z") or ch.isspace() for ch in s)
362
+
363
+
364
+ def read_emphasis(text: str) -> List[Dict[str, Any]]:
365
+ """`--emphasis FILE`: the words to emphasise, as written by the caller. A JSON list (or {"words": [...]})
366
+ of strings or {"text", "at"?, "style"?}: `at` (seconds) picks the cue showing at that time, `style`
367
+ is pop, color or box (default: the emphasisStyle option)."""
368
+ data = json.loads(text)
369
+ if isinstance(data, dict):
370
+ data = data.get("words")
371
+ if not isinstance(data, list) or not data:
372
+ raise CaptionError('emphasis must be a non-empty JSON list of words or {"text", "at"?, "style"?}')
373
+ out: List[Dict[str, Any]] = []
374
+ for i, e in enumerate(data):
375
+ if isinstance(e, str):
376
+ e = {"text": e}
377
+ if not isinstance(e, dict) or not isinstance(e.get("text"), str) or not e["text"].strip():
378
+ raise CaptionError(f"emphasis[{i}] needs a non-empty text")
379
+ unknown = set(e) - {"text", "at", "style"}
380
+ if unknown:
381
+ raise CaptionError(f"emphasis[{i}]: unknown key(s) {sorted(unknown)} (known: text, at, style)")
382
+ at = e.get("at")
383
+ if at is not None and not _num(at):
384
+ raise CaptionError(f"emphasis[{i}]: at must be seconds")
385
+ style = e.get("style")
386
+ if style is not None and style not in EMPHASIS_STYLES:
387
+ raise CaptionError(f"emphasis[{i}]: style must be one of {', '.join(EMPHASIS_STYLES)}")
388
+ out.append({"text": e["text"].strip(), "at": at, "style": style})
389
+ return out
390
+
391
+
392
+ def _cue_tokens(cue: Dict[str, Any], words: List[Dict[str, Any]]) -> Tuple[str, List[Tuple[int, int, int]]]:
393
+ """The cue's timed words (by midpoint, as the compositions assign them) joined with their own spacing,
394
+ and per word (global index, offset where its text starts after the leading space, offset where it ends)."""
395
+ joined, toks = "", []
396
+ for gi, w in enumerate(words):
397
+ mid = (w["start"] + w["end"]) / 2
398
+ if not cue["start"] <= mid <= cue["end"]:
399
+ continue
400
+ lead = len(w["text"]) - len(w["text"].lstrip())
401
+ toks.append((gi, len(joined) + lead, len(joined) + len(w["text"])))
402
+ joined += w["text"]
403
+ return joined, toks
404
+
405
+
406
+ def _find(target: str, joined: str, toks: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int, int]]:
407
+ """Every whole-word occurrence of target in the cue's words: (first word, last word, start, end offsets).
408
+ It starts where a word starts and ends where a word ends, or before only that word's trailing punctuation."""
409
+ folded, t, hits = _fold(joined), _fold(target), []
410
+ starts = {a: k for k, (_, a, _) in enumerate(toks)}
411
+ pos = folded.find(t)
412
+ while pos >= 0:
413
+ end = pos + len(t)
414
+ k = starts.get(pos)
415
+ if k is not None:
416
+ for m in range(k, len(toks)):
417
+ if toks[m][1] < end <= toks[m][2] and _is_punct(joined[end:toks[m][2]]):
418
+ hits.append((toks[k][0], toks[m][0], pos, end))
419
+ break
420
+ pos = folded.find(t, pos + 1)
421
+ return hits
422
+
423
+
424
+ def _cjk(ch: str) -> bool:
425
+ return "\u3040" <= ch <= "\u30ff" or "\u3400" <= ch <= "\u9fff" or "\uac00" <= ch <= "\ud7af" or "\uff00" <= ch <= "\uffef"
426
+
427
+
428
+ def _text_hits(target: str, text: str) -> List[Tuple[int, int]]:
429
+ """Whole-word occurrences of target in a cue's own text, as [start, end) code-point offsets. Between
430
+ Latin letters or digits a boundary is needed (`foot` is not in `football`); CJK text has no spaces, so
431
+ there the timed words decide what a word is."""
432
+ folded, t, out = _fold(text), _fold(target), []
433
+ pos = folded.find(t)
434
+ while pos >= 0:
435
+ end = pos + len(t)
436
+ before = text[pos - 1] if pos else ""
437
+ after = text[end] if end < len(text) else ""
438
+ glued = lambda x, y: bool(x and y and x.isalnum() and y.isalnum() and not (_cjk(x) or _cjk(y)))
439
+ if not glued(before, text[pos]) and not glued(text[end - 1], after):
440
+ out.append((pos, end))
441
+ pos = folded.find(t, pos + 1)
442
+ return out
443
+
444
+
445
+ def _auto_candidates(kind: str, joined: str, toks: List[Tuple[int, int, int]]) -> List[Tuple[int, str]]:
446
+ """(position among the cue's words, word) of each qualifying word: only that word, not every
447
+ occurrence of its spelling, is emphasised."""
448
+ out = []
449
+ for k, (_, a, b) in enumerate(toks):
450
+ word = joined[a:b]
451
+ core = word.rstrip("".join(ch for ch in word if _is_punct(ch)))
452
+ if not core:
453
+ continue
454
+ if kind == "numbers" and any(unicodedata.category(ch) == "Nd" for ch in core):
455
+ out.append((k, core))
456
+ elif kind == "names":
457
+ prev = joined[:a].rstrip()
458
+ katakana = len(core) >= 2 and all("\u30a0" <= ch <= "\u30ff" for ch in core)
459
+ capital = (core[0].isupper() and core[0].isascii() and k > 0 and prev and not prev.endswith(_SENTENCE_END))
460
+ if katakana or capital:
461
+ out.append((k, core))
462
+ return out
463
+
464
+
465
+ def resolve_emphasis(captions: List[Dict[str, Any]], words: List[Dict[str, Any]], entries: List[Dict[str, Any]],
466
+ auto: List[str]) -> Tuple[List[Dict[str, Any]], List[str]]:
467
+ """Place each emphasised word on the caption cue that shows it, at the time the speech engine measured.
468
+
469
+ The emphasised text is a slice of the cue's own words (case and spelling as spoken in the caption),
470
+ never the caller's spelling and never rewritten. A caller's word that is not a whole word of the cue
471
+ (or of any cue, without `at`) is refused; nothing is moved, guessed or interpolated. `auto` adds the
472
+ cue's own numbers ("numbers") and capitalised / katakana names ("names") without a style.
473
+ The word must also be a whole word of the cue's own text (that text is what is drawn); `span` is its
474
+ [start, end) code-point offsets there.
475
+ Returns ([{start, end, text, style, cue, span, words: [first, last], by}], warnings)."""
476
+ if not entries and not auto:
477
+ raise CaptionError("nothing to emphasise: give words (--emphasis) or kinds (--emphasis-auto)")
478
+ if not words:
479
+ raise CaptionError("emphasis needs word timings (--words): a word's time is measured, never guessed")
480
+ if not captions:
481
+ raise CaptionError("emphasis needs caption cues")
482
+ tokens = [_cue_tokens(c, words) for c in captions]
483
+ out: List[Dict[str, Any]] = []
484
+ warnings: List[str] = []
485
+ taken = set()
486
+
487
+ def matches(ci: int, target: str) -> List[Tuple[Tuple[int, int, int, int], Tuple[int, int]]]:
488
+ """The timed whole-word hits of target in cue ci, each paired with the same occurrence in the
489
+ cue's own text (n-th with n-th). The caption text is what is drawn, so the two must agree."""
490
+ timed = _find(target, *tokens[ci])
491
+ if not timed:
492
+ return []
493
+ in_text = _text_hits(target, captions[ci]["text"])
494
+ if len(in_text) != len(timed):
495
+ raise CaptionError(f"emphasis {target!r}: cue {ci + 1} ({captions[ci]['text']!r}) has it "
496
+ f"{len(in_text)} time(s) as a whole word but its word timings {len(timed)}; the "
497
+ "caption and the word timings disagree, so its time cannot be placed")
498
+ return list(zip(timed, in_text))
499
+
500
+ def add(ci: int, hit: Tuple[int, int, int, int], span_text: Tuple[int, int], style: Optional[str], by: str) -> bool:
501
+ first, last, _, _ = hit
502
+ span = set(range(first, last + 1))
503
+ if span & taken:
504
+ return False
505
+ taken.update(span)
506
+ a, b = span_text
507
+ out.append({"start": words[first]["start"], "end": words[last]["end"], "text": captions[ci]["text"][a:b],
508
+ "style": style, "cue": ci, "span": [a, b], "words": [first, last], "by": by})
509
+ return True
510
+
511
+ for e in entries:
512
+ if e["at"] is not None:
513
+ cues = [i for i, c in enumerate(captions) if c["start"] <= e["at"] < c["end"]]
514
+ if not cues:
515
+ raise CaptionError(f"emphasis {e['text']!r}: no caption cue shows at {e['at']:g} s")
516
+ else:
517
+ cues = list(range(len(captions)))
518
+ found, untimed_hit = 0, None
519
+ for ci in cues:
520
+ if _fold(e["text"]) not in _fold(captions[ci]["text"]):
521
+ continue
522
+ if not tokens[ci][1]:
523
+ untimed_hit = ci
524
+ for hit, span_text in matches(ci, e["text"]):
525
+ if not add(ci, hit, span_text, e["style"], "caller"):
526
+ raise CaptionError(f"emphasis {e['text']!r} overlaps another emphasised word in cue {ci + 1}")
527
+ found += 1
528
+ if not found and untimed_hit is not None:
529
+ raise CaptionError(f"emphasis {e['text']!r}: cue {untimed_hit + 1} ({captions[untimed_hit]['text']!r}) "
530
+ "has no word timings, so its time is not measured")
531
+ if not found:
532
+ where = (f"the cue at {e['at']:g} s ({captions[cues[0]]['text']!r})" if e["at"] is not None
533
+ else "any caption cue")
534
+ raise CaptionError(f"emphasis {e['text']!r} is not a whole word of {where}: only the caption's own, "
535
+ "timed words can be emphasised")
536
+ for kind in auto:
537
+ if kind not in EMPHASIS_AUTO:
538
+ raise CaptionError(f"--emphasis-auto: unknown kind {kind!r} (known: {', '.join(EMPHASIS_AUTO)})")
539
+ n = 0
540
+ for ci, (joined, toks) in enumerate(tokens):
541
+ for k, cand in _auto_candidates(kind, joined, toks):
542
+ try:
543
+ pairs = matches(ci, cand)
544
+ except CaptionError as err:
545
+ warnings.append(f"{err} (skipped)")
546
+ continue
547
+ n += sum(add(ci, hit, span_text, None, kind) for hit, span_text in pairs if hit[0] == toks[k][0])
548
+ if not n:
549
+ warnings.append(f"emphasis: no {kind} found in the timed caption words")
550
+ untimed = [i + 1 for i, (_, toks) in enumerate(tokens) if not toks]
551
+ if untimed and (entries or auto):
552
+ warnings.append("emphasis: cue(s) " + ", ".join(map(str, untimed)) + " have no word timings, so nothing "
553
+ "in them can be emphasised")
554
+ return sorted(out, key=lambda x: x["start"]), warnings
555
+
556
+
348
557
  # ---------------------------------------------------------------- chapters
349
558
 
350
559
  def _chapter_time(tok: str) -> float:
@@ -225,7 +225,7 @@ def validate_timeline(t: Any) -> List[str]:
225
225
  if t.get("pip") is not None and not (isinstance(t["pip"], dict) and isinstance(t["pip"].get("offset"), (int, float))
226
226
  and t["pip"].get("path")):
227
227
  p.append("pip must be {path, offset, duration, ...} (analyze.py --pip)")
228
- for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights", "words", "chapters"):
228
+ for k in ("scenes", "silences", "speech", "peaks", "captions", "highlights", "words", "chapters", "emphasis"):
229
229
  if not isinstance(t.get(k, []), list):
230
230
  p.append(f"{k} must be a list")
231
231
  for i, c in enumerate(t.get("captions", []) or []):
@@ -234,6 +234,28 @@ def validate_timeline(t: Any) -> List[str]:
234
234
  and c["end"] > c["start"]):
235
235
  p.append(f"captions[{i}] needs start < end and text")
236
236
  break
237
+ emph = t.get("emphasis") or []
238
+ caps = t.get("captions") if isinstance(t.get("captions"), list) else []
239
+ nwords = len(t["words"]) if isinstance(t.get("words"), list) else 0
240
+ for i, e in enumerate(emph if isinstance(emph, list) else []):
241
+ ok = (isinstance(e, dict) and _finite(e.get("start")) and _finite(e.get("end")) and e["end"] > e["start"]
242
+ and isinstance(e.get("text"), str) and e["text"] and isinstance(e.get("cue"), int)
243
+ and not isinstance(e["cue"], bool) and 0 <= e["cue"] < len(caps)
244
+ and e.get("style") in (None, "pop", "color", "box"))
245
+ for key, limit in (("span", None), ("words", nwords)):
246
+ r = e.get(key) if ok else None
247
+ ok = ok and (isinstance(r, list) and len(r) == 2 and all(isinstance(x, int) and not isinstance(x, bool)
248
+ for x in r) and 0 <= r[0] <= r[1])
249
+ if ok and limit is not None:
250
+ ok = r[1] < limit
251
+ if ok:
252
+ cue_text = caps[e["cue"]].get("text") if isinstance(caps[e["cue"]], dict) else None
253
+ ok = isinstance(cue_text, str) and e["span"][1] <= len(cue_text) and \
254
+ cue_text[e["span"][0]:e["span"][1]] == e["text"]
255
+ if not ok:
256
+ p.append(f"emphasis[{i}] needs start < end, text, its caption cue, the span of the text in that cue, "
257
+ "its word range and a style (pop, color, box or null) -- analyze.py --emphasis writes it")
258
+ break
237
259
  for i, r in enumerate(t.get("speech", []) or []):
238
260
  if not (isinstance(r, list) and len(r) == 2 and r[1] > r[0]):
239
261
  p.append(f"speech[{i}] must be [start, end] with start < end")
@@ -241,6 +263,10 @@ def validate_timeline(t: Any) -> List[str]:
241
263
  return p
242
264
 
243
265
 
266
+ def _finite(v: Any) -> bool:
267
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
268
+
269
+
244
270
  def sec_to_frames(seconds: float, fps: float) -> int:
245
271
  # JavaScript's Math.round (round half up), not Python's round() (half to even): the TypeScript
246
272
  # compositions compute the same frame numbers and the two must agree to the frame (94.5 -> 95).
@@ -254,7 +280,7 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
254
280
  and render.py then only reports the measured numbers.
255
281
  """
256
282
  fps = float(t["source"]["fps"])
257
- if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip"):
283
+ if comp in ("Captioned", "PeakPulse", "Titled", "BeatMontage", "Karaoke", "Pip", "Emphasis"):
258
284
  return max(1, sec_to_frames(float(t["source"]["duration"]), fps))
259
285
  if comp in ("Jumpcut", "Highlights"):
260
286
  if comp == "Jumpcut":
@@ -268,7 +294,8 @@ def expected_frames(comp: str, t: Dict[str, Any]) -> Optional[int]:
268
294
 
269
295
  # ---------------------------------------------------------------- Remotion project
270
296
 
271
- BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke", "Pip")
297
+ BUILTIN_COMPOSITIONS = ("Captioned", "Jumpcut", "PeakPulse", "Titled", "Highlights", "BeatMontage", "Karaoke", "Pip",
298
+ "Emphasis")
272
299
 
273
300
 
274
301
  def remotion_bin(project: Path) -> Path:
@@ -593,6 +620,7 @@ _OPTION_TYPES: Dict[str, Any] = {
593
620
  "progressBar": bool, "driver": str, "lowerThirds": list, "sceneTitles": list,
594
621
  "title": (str, type(None)), "beatsPerCut": int, "chapterSeconds": (int, float),
595
622
  "pipCorner": str, "pipSize": (int, float), "pipShape": str, "pipAudio": bool,
623
+ "emphasisStyle": str, "bubbles": list, "comments": list,
596
624
  }
597
625
 
598
626
 
@@ -625,6 +653,21 @@ def validate_options(o: Dict[str, Any]) -> List[str]:
625
653
  if isinstance(o.get("pipSize"), (int, float)) and not isinstance(o["pipSize"], bool) \
626
654
  and not 0.05 <= o["pipSize"] <= 0.6:
627
655
  p.append("pipSize must be between 0.05 and 0.6 (a fraction of the frame width)")
656
+ if "emphasisStyle" in o and o["emphasisStyle"] not in ("pop", "color", "box"):
657
+ p.append("emphasisStyle must be pop, color or box")
658
+ for key, extra in (("bubbles", "side"), ("comments", "author")):
659
+ items = o.get(key)
660
+ for i, c in enumerate(items if isinstance(items, list) else []):
661
+ ok = (isinstance(c, dict) and isinstance(c.get("text"), str) and c["text"].strip()
662
+ and _finite(c.get("start")) and _finite(c.get("end")) and c["end"] > c["start"]
663
+ and set(c) <= {"text", "start", "end", extra})
664
+ if ok and key == "bubbles":
665
+ ok = c.get("side", "left") in ("left", "right")
666
+ if ok and key == "comments":
667
+ ok = isinstance(c.get("author", ""), str)
668
+ if not ok:
669
+ p.append(f"{key}[{i}] needs text, start < end (seconds) and an optional {extra}"
670
+ + (" (left or right)" if key == "bubbles" else ""))
628
671
  if any(not isinstance(s, str) for s in (o.get("sceneTitles") or [])):
629
672
  p.append("sceneTitles must be a list of strings")
630
673
  return p
@@ -101,7 +101,7 @@ TOOL_META: Dict[str, Dict[str, Any]] = {
101
101
  OUTPUTS: Dict[str, Dict[str, Dict[str, str]]] = {
102
102
  "analyze": {
103
103
  "result": {"commands": "list[str]", "verified": "bool", "summary": "object: duration, fps, size, scenes, "
104
- "silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, "
104
+ "silences, speech_seconds, peaks, captions, chapters, beats, tempo_bpm, highlights, clips, words, emphasis, "
105
105
  "conformed (list: vfr / hdr)",
106
106
  "warnings": "list[str]"},
107
107
  "dry_run": {"commands": "list[str]"},
@@ -19,6 +19,7 @@ Examples:
19
19
  python3 analyze.py talk.mp4 --threshold -42 --min-silence 0.8 # quiet room
20
20
  python3 analyze.py intro.mp4 talk.mov outro.mp4 --captions all.srt # joined, then measured
21
21
  python3 analyze.py talk.mp4 --words talk.transcript.json # captions from a transcription-skill transcript
22
+ python3 analyze.py talk.mp4 --words talk.transcript.json --emphasis words.json # Emphasis composition
22
23
  python3 analyze.py phone_hdr.mov --conform # VFR / HDR: measure and draw on a CFR SDR copy
23
24
  """
24
25
  import argparse
@@ -34,8 +35,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
34
35
  from _common import (STATE, TIMELINE_SCHEMA, SKILL_ID, add_common, apply_common, default_output, die,
35
36
  emit, ffmpeg_skill_version, ffskill, ffskill_cmd, info, refuse_existing,
36
37
  require_ffmpeg_skill, shell_join, version)
37
- from _captions import (CaptionError, cues_from_words, parse_chapters, read_captions, read_word_timings,
38
- youtube_chapter_warnings)
38
+ from _captions import (CaptionError, cues_from_words, parse_chapters, read_captions, read_emphasis,
39
+ read_word_timings, resolve_emphasis, youtube_chapter_warnings)
39
40
 
40
41
  # seconds a transcript's duration may differ from the measured source (transcription-skill's own END_TOLERANCE)
41
42
  TRANSCRIPT_DURATION_TOLERANCE = 0.5
@@ -63,6 +64,13 @@ def build_parser() -> argparse.ArgumentParser:
63
64
  p.add_argument("--words", help="word timings for the Karaoke and Captioned compositions: a transcription-skill "
64
65
  "transcript (schema transcription-skill/transcript/0.1, validated strictly) or whisper "
65
66
  "JSON with word timestamps; without --captions the cues are grouped from these words")
67
+ p.add_argument("--emphasis", metavar="FILE",
68
+ help="words to emphasise in the Emphasis composition (pop, colour or box at the time each is "
69
+ "spoken): a JSON list of words or {text, at?, style?}. Each must be a whole, timed word of "
70
+ "a caption cue (of the cue showing at `at`), or it is refused; needs --words")
71
+ p.add_argument("--emphasis-auto", metavar="KINDS",
72
+ help="with --words: also emphasise the captions' own numbers and/or names "
73
+ "(comma-separated: numbers, names = capitalised mid-sentence or katakana words)")
66
74
  p.add_argument("--chapters", metavar="FILE|source",
67
75
  help="chapter list, one `TIME TITLE` per line (YouTube's format, the same file ffmpeg-skill "
68
76
  "metadata.py --chapters writes into the container), or `source` for the chapters already "
@@ -309,6 +317,26 @@ def main() -> None:
309
317
  if not captions:
310
318
  captions = timed["cues"] if transcript else cues_from_words(words)
311
319
 
320
+ emphasis: List[Dict[str, Any]] = []
321
+ emphasis_warnings: List[str] = []
322
+ if a.emphasis is not None or a.emphasis_auto is not None:
323
+ if not words:
324
+ die("--emphasis / --emphasis-auto need --words: an emphasised word shows at the time the speech "
325
+ "engine measured, never a guessed one", "input")
326
+ entries: List[Dict[str, Any]] = []
327
+ try:
328
+ if a.emphasis:
329
+ epath = Path(a.emphasis).expanduser()
330
+ if not epath.is_file():
331
+ die(f"emphasis file not found: {epath}", "input")
332
+ entries = read_emphasis(epath.read_text(encoding="utf-8-sig"))
333
+ auto = [k.strip() for k in (a.emphasis_auto or "").split(",") if k.strip()]
334
+ if a.emphasis_auto is not None and not auto:
335
+ die("--emphasis-auto needs at least one kind: numbers, names", "input")
336
+ emphasis, emphasis_warnings = resolve_emphasis(captions, words, entries, auto)
337
+ except (CaptionError, ValueError) as e:
338
+ die(f"--emphasis: {e}", "input")
339
+
312
340
  join_args = [*map(str, inputs), "-o", str(joined), "--transition", a.join_transition,
313
341
  "--duration", str(a.join_duration)] + (["--overwrite"] if STATE.overwrite else [])
314
342
  plan = ([shell_join(ffskill_cmd("join", join_args))] if len(inputs) > 1 else []) + \
@@ -501,11 +529,13 @@ def main() -> None:
501
529
  "clips": clips,
502
530
  "captions": captions,
503
531
  "words": words,
532
+ "emphasis": emphasis,
504
533
  "chapters": chapters,
505
534
  "pip": pip,
506
535
  # Provenance of a conformed source (--conform): the original, each ffmpeg-skill step, the measured copy.
507
536
  "conform": conform,
508
- "warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings,
537
+ "warnings": warnings_for(probe) + (youtube_chapter_warnings(chapters) if chapters else []) + transcript_warnings
538
+ + emphasis_warnings,
509
539
  }
510
540
  if pip and pip["measured"] and (pip["confidence"] or 0) < 0.3:
511
541
  timeline["warnings"].append(f"pip: the measured offset ({pip['offset']:g} s) has low confidence "
@@ -531,7 +561,7 @@ def main() -> None:
531
561
  "captions": len(captions), "chapters": len(chapters),
532
562
  "pip_offset": pip["offset"] if pip else None, "beats": bool(beats and beats.get("usable")),
533
563
  "tempo_bpm": (beats or {}).get("tempo_bpm"), "highlights": len(highlights),
534
- "clips": len(clips) or 1, "words": len(words),
564
+ "clips": len(clips) or 1, "words": len(words), "emphasis": len(emphasis),
535
565
  "conformed": (conform or {}).get("reasons", [])},
536
566
  "warnings": timeline["warnings"]},
537
567
  f"wrote {out}: {timeline['source']['duration']}s, {len(scenes)} scenes, {len(silences)} silences "
package/scripts/render.py CHANGED
@@ -212,7 +212,7 @@ def main() -> None:
212
212
  if a.overlay:
213
213
  if a.comp in ("Jumpcut", "Highlights", "BeatMontage", "Pip"):
214
214
  die(f"--overlay cannot do {a.comp}: it changes the picture itself (overlay works for "
215
- "Captioned, PeakPulse, Titled, Karaoke)", "input")
215
+ "Captioned, PeakPulse, Titled, Karaoke, Emphasis)", "input")
216
216
  if a.aspect not in (None, "source") or a.width is not None or a.fit not in (None, "contain"):
217
217
  die("--overlay draws on the source's own frame: drop --aspect / --width / --fit", "input")
218
218
  if a.fast or a.codec != "h264" or frames:
@@ -8,13 +8,13 @@
8
8
  "typecheck": "tsc --noEmit"
9
9
  },
10
10
  "dependencies": {
11
- "@remotion/cli": "4.0.538",
12
- "remotion": "4.0.538",
11
+ "@remotion/cli": "4.0.540",
12
+ "remotion": "4.0.540",
13
13
  "react": "19.3.1",
14
14
  "react-dom": "19.3.1"
15
15
  },
16
16
  "devDependencies": {
17
17
  "@types/react": "^19.0.0",
18
- "typescript": "^5.6.0"
18
+ "typescript": "^7.0.2"
19
19
  }
20
20
  }
@@ -8,6 +8,7 @@ import { Highlights } from "./compositions/Highlights";
8
8
  import { BeatMontage } from "./compositions/BeatMontage";
9
9
  import { Karaoke } from "./compositions/Karaoke";
10
10
  import { Pip } from "./compositions/Pip";
11
+ import { Emphasis } from "./compositions/Emphasis";
11
12
  import { SAMPLE_TIMELINE, fullLengthFrames, highlightFrames, jumpcutFrames, outputFrame, type Props, type Timeline } from "./timeline";
12
13
 
13
14
  // Length and fps come from the measured timeline, never from constants; the frame is the
@@ -32,5 +33,6 @@ export const RemotionRoot: React.FC = () => (
32
33
  <Composition id="BeatMontage" component={BeatMontage} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
33
34
  <Composition id="Karaoke" component={Karaoke} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
34
35
  <Composition id="Pip" component={Pip} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
36
+ <Composition id="Emphasis" component={Emphasis} {...base} calculateMetadata={metadataFrom(fullLengthFrames)} />
35
37
  </>
36
38
  );
@@ -0,0 +1,291 @@
1
+ import React from "react";
2
+ import { AbsoluteFill, Sequence, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
3
+ import { SourceVideo } from "../lib/SourceVideo";
4
+ import { useStagedFont } from "../lib/useStagedFont";
5
+ import { captionMarginPx } from "./Captioned";
6
+ import {
7
+ Props,
8
+ fontStack,
9
+ outputFrame,
10
+ resolveOptions,
11
+ secToFrames,
12
+ type Bubble,
13
+ type Caption,
14
+ type CommentCard,
15
+ type Emphasis as EmphasisWord,
16
+ type Options,
17
+ } from "../timeline";
18
+
19
+ /**
20
+ * Emphasis: YouTube-style captions. Each caption cue shows as written; the words analyze.py --emphasis
21
+ * placed on it pop, take the accent colour or get an accent box from the time the speech engine measured
22
+ * them to the end of the cue. Speech bubbles and comment-style cards (the user's text, options `bubbles`
23
+ * and `comments`) show at their own times. Nothing here chooses or rewrites a word.
24
+ */
25
+ export const Emphasis: React.FC<Props> = (props) => {
26
+ const { timeline, options, font, overlay } = props;
27
+ useStagedFont(font);
28
+ const o = resolveOptions(options);
29
+ const family = fontStack(o, font);
30
+ const { fps } = useVideoConfig();
31
+ const emphasis = timeline.emphasis ?? [];
32
+ // Cards showing at once stack downwards: each takes the lowest slot no earlier overlapping card holds.
33
+ const slots: number[] = [];
34
+ o.comments.forEach((c, i) => {
35
+ const busy = new Set(o.comments.slice(0, i).flatMap((p, j) => (p.start < c.end && p.end > c.start ? [slots[j]] : [])));
36
+ let s = 0;
37
+ while (busy.has(s)) s += 1;
38
+ slots.push(s);
39
+ });
40
+ return (
41
+ <AbsoluteFill style={{ backgroundColor: overlay ? "transparent" : "black" }}>
42
+ {overlay ? null : <SourceVideo source={timeline.source} fit={outputFrame(props).fit} />}
43
+ {timeline.captions.map((c, i) => {
44
+ const from = secToFrames(c.start, fps);
45
+ const dur = Math.max(1, secToFrames(c.end, fps) - from);
46
+ return (
47
+ <Sequence key={`c${i}`} from={from} durationInFrames={dur} name={`cue ${i + 1}`} layout="none">
48
+ <EmphasisCue
49
+ cue={c}
50
+ from={from}
51
+ emphasis={emphasis.filter((e) => e.cue === i)}
52
+ len={dur}
53
+ o={o}
54
+ fontFamily={family}
55
+ />
56
+ </Sequence>
57
+ );
58
+ })}
59
+ {o.bubbles.map((b, i) => {
60
+ const from = secToFrames(b.start, fps);
61
+ const dur = Math.max(1, secToFrames(b.end, fps) - from);
62
+ return (
63
+ <Sequence key={`b${i}`} from={from} durationInFrames={dur} name={`bubble ${i + 1}`} layout="none">
64
+ <SpeechBubble bubble={b} len={dur} o={o} fontFamily={family} />
65
+ </Sequence>
66
+ );
67
+ })}
68
+ {o.comments.map((c, i) => {
69
+ const from = secToFrames(c.start, fps);
70
+ const dur = Math.max(1, secToFrames(c.end, fps) - from);
71
+ const slot = slots[i];
72
+ return (
73
+ <Sequence key={`m${i}`} from={from} durationInFrames={dur} name={`comment ${i + 1}`} layout="none">
74
+ <Comment card={c} slot={slot} len={dur} o={o} fontFamily={family} />
75
+ </Sequence>
76
+ );
77
+ })}
78
+ </AbsoluteFill>
79
+ );
80
+ };
81
+
82
+ const langOf = (text: string): string | undefined =>
83
+ /[぀-ヿ㐀-鿿]/.test(text) ? "ja" : /[가-힯]/.test(text) ? "ko" : undefined;
84
+
85
+ const useInOut = (len: number) => {
86
+ const frame = useCurrentFrame();
87
+ const { fps } = useVideoConfig();
88
+ const enter = spring({ frame, fps, config: { damping: 14, stiffness: 180, mass: 0.6 } });
89
+ const fade = Math.min(6, Math.floor(len / 3));
90
+ const exit = fade > 0 ? interpolate(frame, [len - fade, len], [1, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }) : 1;
91
+ return { frame, enter, exit };
92
+ };
93
+
94
+ const EmphasisCue: React.FC<{
95
+ cue: Caption;
96
+ from: number;
97
+ emphasis: EmphasisWord[];
98
+ len: number;
99
+ o: Options;
100
+ fontFamily: string;
101
+ }> = ({ cue, from, emphasis, len, o, fontFamily }) => {
102
+ const { fps, width, height } = useVideoConfig();
103
+ const { frame, enter, exit } = useInOut(len);
104
+ const size = Math.round(Math.min(width, height) * o.captionSize * 1.1);
105
+ // Source time of this frame, nudged by a microsecond as in Karaoke so a word starting exactly on a
106
+ // frame shows on that frame.
107
+ const now = (from + frame) / fps + 1e-6;
108
+ // The cue's own text, cut at the emphasised spans (code points, as analyze.py counted them).
109
+ const chars = Array.from(cue.text);
110
+ const parts: React.ReactNode[] = [];
111
+ let at = 0;
112
+ for (const [k, e] of [...emphasis].sort((x, y) => x.span[0] - y.span[0]).entries()) {
113
+ if (e.span[0] < at) continue;
114
+ parts.push(chars.slice(at, e.span[0]).join(""));
115
+ parts.push(
116
+ <Emphasised key={k} text={chars.slice(e.span[0], e.span[1]).join("")} style={e.style ?? o.emphasisStyle} at={e.start} now={now} o={o} />,
117
+ );
118
+ at = e.span[1];
119
+ }
120
+ parts.push(chars.slice(at).join(""));
121
+ return (
122
+ <AbsoluteFill style={{ justifyContent: "flex-end", alignItems: "center", paddingBottom: captionMarginPx(o, width, height) }}>
123
+ <div
124
+ lang={langOf(cue.text)}
125
+ style={{
126
+ maxWidth: width * 0.88,
127
+ padding: `${size * 0.25}px ${size * 0.55}px`,
128
+ borderRadius: size * 0.3,
129
+ background: "rgba(0,0,0,0.6)",
130
+ color: o.textColor,
131
+ fontFamily,
132
+ fontWeight: 800,
133
+ fontSize: size,
134
+ lineHeight: 1.45,
135
+ textAlign: "center",
136
+ whiteSpace: "pre-wrap",
137
+ textWrap: "balance",
138
+ opacity: Math.min(enter, exit),
139
+ transform: `translateY(${(1 - enter) * size * 0.5}px)`,
140
+ }}
141
+ >
142
+ {parts}
143
+ </div>
144
+ </AbsoluteFill>
145
+ );
146
+ };
147
+
148
+ /** One emphasised word: plain until it is spoken, then popped, coloured or boxed until the cue ends. */
149
+ const Emphasised: React.FC<{ text: string; style: "pop" | "color" | "box"; at: number; now: number; o: Options }> = ({
150
+ text,
151
+ style,
152
+ at,
153
+ now,
154
+ o,
155
+ }) => {
156
+ const on = now >= at;
157
+ const t = now - at;
158
+ const scale = !on
159
+ ? 1
160
+ : style === "pop"
161
+ ? interpolate(t, [0, 0.08, 0.25], [1, 1.35, 1.15], { extrapolateRight: "clamp" })
162
+ : interpolate(t, [0, 0.06, 0.18], [1, 1.12, 1], { extrapolateRight: "clamp" });
163
+ const boxed = on && style === "box";
164
+ return (
165
+ <span
166
+ style={{
167
+ display: "inline-block",
168
+ transform: `scale(${scale})`,
169
+ transformOrigin: "50% 70%",
170
+ color: on ? (boxed ? "#111111" : o.accent) : o.textColor,
171
+ background: boxed ? o.accent : "transparent",
172
+ borderRadius: "0.18em",
173
+ padding: "0 0.12em",
174
+ margin: "0 -0.12em",
175
+ textShadow: on && style === "pop" ? "0 0.06em 0 rgba(0,0,0,0.65)" : "none",
176
+ }}
177
+ >
178
+ {text}
179
+ </span>
180
+ );
181
+ };
182
+
183
+ /** A speech bubble in the upper part of the frame, its tail pointing down-left or down-right. */
184
+ const SpeechBubble: React.FC<{ bubble: Bubble; len: number; o: Options; fontFamily: string }> = ({ bubble, len, o, fontFamily }) => {
185
+ const { width, height } = useVideoConfig();
186
+ const { enter, exit } = useInOut(len);
187
+ const size = Math.round(Math.min(width, height) * o.captionSize);
188
+ const right = bubble.side === "right";
189
+ const tail = size * 0.6;
190
+ return (
191
+ <AbsoluteFill
192
+ style={{ justifyContent: "flex-start", alignItems: right ? "flex-end" : "flex-start", padding: `${height * 0.1}px ${width * 0.08}px` }}
193
+ >
194
+ <div
195
+ lang={langOf(bubble.text)}
196
+ style={{
197
+ position: "relative",
198
+ maxWidth: width * 0.5,
199
+ padding: `${size * 0.45}px ${size * 0.7}px`,
200
+ borderRadius: size * 0.9,
201
+ background: "#ffffff",
202
+ color: "#111111",
203
+ fontFamily,
204
+ fontWeight: 800,
205
+ fontSize: size,
206
+ lineHeight: 1.3,
207
+ whiteSpace: "pre-wrap",
208
+ boxShadow: `0 ${size * 0.12}px ${size * 0.4}px rgba(0,0,0,0.35)`,
209
+ opacity: exit,
210
+ transform: `scale(${enter})`,
211
+ transformOrigin: right ? "85% 100%" : "15% 100%",
212
+ }}
213
+ >
214
+ {bubble.text}
215
+ <div
216
+ style={{
217
+ position: "absolute",
218
+ bottom: -tail * 0.8,
219
+ [right ? "right" : "left"]: size * 0.9,
220
+ width: 0,
221
+ height: 0,
222
+ borderLeft: `${tail * 0.5}px solid transparent`,
223
+ borderRight: `${tail * 0.5}px solid transparent`,
224
+ borderTop: `${tail}px solid #ffffff`,
225
+ transform: `skewX(${right ? 25 : -25}deg)`,
226
+ }}
227
+ />
228
+ </div>
229
+ </AbsoluteFill>
230
+ );
231
+ };
232
+
233
+ /** A comment-style card sliding in at the top left (a live-chat / comment look), cards at once stacked. */
234
+ const Comment: React.FC<{ card: CommentCard; slot: number; len: number; o: Options; fontFamily: string }> = ({
235
+ card,
236
+ slot,
237
+ len,
238
+ o,
239
+ fontFamily,
240
+ }) => {
241
+ const { width, height } = useVideoConfig();
242
+ const { enter, exit } = useInOut(len);
243
+ const size = Math.round(Math.min(width, height) * o.captionSize * 0.7);
244
+ const avatar = size * 2;
245
+ return (
246
+ <AbsoluteFill style={{ justifyContent: "flex-start", alignItems: "flex-start", padding: `${height * 0.06}px ${width * 0.04}px` }}>
247
+ <div
248
+ lang={langOf(card.text)}
249
+ style={{
250
+ marginTop: slot * size * 4.2,
251
+ display: "flex",
252
+ alignItems: "center",
253
+ gap: size * 0.6,
254
+ maxWidth: width * 0.55,
255
+ padding: `${size * 0.5}px ${size * 0.8}px ${size * 0.5}px ${size * 0.5}px`,
256
+ borderRadius: size * 0.6,
257
+ background: "rgba(255,255,255,0.94)",
258
+ color: "#111111",
259
+ fontFamily,
260
+ fontSize: size,
261
+ lineHeight: 1.3,
262
+ boxShadow: `0 ${size * 0.1}px ${size * 0.4}px rgba(0,0,0,0.3)`,
263
+ opacity: Math.min(enter, exit),
264
+ transform: `translateX(${(1 - enter) * -width * 0.1}px)`,
265
+ }}
266
+ >
267
+ <div
268
+ style={{
269
+ flex: "none",
270
+ width: avatar,
271
+ height: avatar,
272
+ borderRadius: "50%",
273
+ background: o.accent,
274
+ color: "#111111",
275
+ fontWeight: 800,
276
+ fontSize: size * 1.1,
277
+ display: "flex",
278
+ alignItems: "center",
279
+ justifyContent: "center",
280
+ }}
281
+ >
282
+ {card.author ? Array.from(card.author.trim())[0] ?? "" : ""}
283
+ </div>
284
+ <div style={{ whiteSpace: "pre-wrap" }}>
285
+ {card.author ? <div style={{ fontWeight: 800, fontSize: size * 0.85, opacity: 0.7 }}>{card.author}</div> : null}
286
+ <div style={{ fontWeight: 600 }}>{card.text}</div>
287
+ </div>
288
+ </div>
289
+ </AbsoluteFill>
290
+ );
291
+ };
@@ -19,6 +19,23 @@ export type Source = {
19
19
 
20
20
  export type Caption = { start: number; end: number; text: string };
21
21
  export type Chapter = { start: number; end: number; title: string };
22
+ /** An emphasised word (analyze.py --emphasis / --emphasis-auto): the slice `span` ([start, end) in code
23
+ * points) of caption cue `cue`'s own text, timed by the words `words` = [first, last] (indices into
24
+ * timeline.words), shown from the time the engine measured. style null = the emphasisStyle option. */
25
+ export type EmphasisStyle = "pop" | "color" | "box";
26
+ export type Emphasis = {
27
+ start: number;
28
+ end: number;
29
+ text: string;
30
+ style: EmphasisStyle | null;
31
+ cue: number;
32
+ span: [number, number];
33
+ words: [number, number];
34
+ by: "caller" | "numbers" | "names";
35
+ };
36
+ /** A speech bubble or a comment-style card: the user's text, timing in source seconds. */
37
+ export type Bubble = { text: string; start: number; end: number; side?: "left" | "right" };
38
+ export type CommentCard = { text: string; start: number; end: number; author?: string };
22
39
  /** A second recording shown picture-in-picture (analyze.py --pip). offset: seconds after the source's
23
40
  * start at which the camera's first frame belongs (measured from both audio tracks, or given). */
24
41
  export type Pip = {
@@ -67,6 +84,8 @@ export type Timeline = {
67
84
  words?: Caption[];
68
85
  /** Chapters from the user's list or the source's own markers (analyze.py --chapters); titles as written. */
69
86
  chapters?: Chapter[];
87
+ /** Emphasised caption words (analyze.py --emphasis); drawn by the Emphasis composition. */
88
+ emphasis?: Emphasis[];
70
89
  pip?: Pip | null;
71
90
  /** Set when analyze.py --conform measured a conformed copy instead of the original (null otherwise). */
72
91
  conform?: Conform | null;
@@ -108,6 +127,12 @@ export type Options = {
108
127
  pipShape: "rounded" | "circle";
109
128
  /** Pip: play the camera's own audio too (off: the source's audio only). */
110
129
  pipAudio: boolean;
130
+ /** Emphasis: how an emphasised word shows when it is spoken (an entry's own style wins). */
131
+ emphasisStyle: EmphasisStyle;
132
+ /** Emphasis: speech bubbles (text from the user, never invented). */
133
+ bubbles: Bubble[];
134
+ /** Emphasis: comment-style cards (text and author from the user). */
135
+ comments: CommentCard[];
111
136
  };
112
137
 
113
138
  export const DEFAULT_OPTIONS: Options = {
@@ -129,6 +154,9 @@ export const DEFAULT_OPTIONS: Options = {
129
154
  pipSize: 0.28,
130
155
  pipShape: "rounded",
131
156
  pipAudio: false,
157
+ emphasisStyle: "pop",
158
+ bubbles: [],
159
+ comments: [],
132
160
  };
133
161
 
134
162
  /** Where the camera plays on the source timeline: [from, durationInFrames, trimBefore] in frames. */