Skip to content

Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.

fix: caption word wider than the column breaks at the edge instead of clipping (#255)

Shogo Kajiyama050183c18aa7
diff --git a/scripts/_common/__init__.py b/scripts/_common/__init__.py
index ae77739..ea3e81a 100644
--- a/scripts/_common/__init__.py
+++ b/scripts/_common/__init__.py
@@ -107,7 +107,7 @@ from _common.text import (
JA_NO_LINE_END, JA_NO_LINE_START, JA_PARTICLE_WORDS, JA_PARTICLES, JA_SENTENCE_END, _join, ORPHAN_MIN_EM,
PENALTY_FORBIDDEN, PENALTY_FUNCTION_WORD, PENALTY_FUNCTION_WORD_START, PENALTY_IDEOGRAPHS,
PENALTY_NEUTRAL, PENALTY_OKURIGANA,
- PENALTY_PARTICLE, PENALTY_SENTENCE_END, _rebalance, _rebalance_phrase, SAFE_WIDTH_FRACTION, _split_hyphens,
+ PENALTY_PARTICLE, PENALTY_SENTENCE_END, _rebalance, _rebalance_phrase, SAFE_WIDTH_FRACTION, _split_hyphens, _slice_atom,
_particle_ends, _particle_starts, wrap_text, wrap_variants, WRAP_MODES,
fit_size, line_em_for_size, MIN_CAPTION_FRACTION, ass_units_local,
script_font_for_text, script_font_status, _script_font_uncached, _SCRIPT_RANGES, SCRIPTS, _SHAPING_BUILD_CACHE,
@@ -223,7 +223,7 @@ __all__ = [
"PENALTY_FUNCTION_WORD_START",
"JA_SENTENCE_END", "_join", "ORPHAN_MIN_EM", "PENALTY_FORBIDDEN", "PENALTY_FUNCTION_WORD",
"PENALTY_IDEOGRAPHS", "PENALTY_NEUTRAL", "PENALTY_OKURIGANA", "PENALTY_PARTICLE", "PENALTY_SENTENCE_END",
- "_rebalance", "_rebalance_phrase", "SAFE_WIDTH_FRACTION", "_split_hyphens", "_particle_ends",
+ "_rebalance", "_rebalance_phrase", "SAFE_WIDTH_FRACTION", "_split_hyphens", "_slice_atom", "_particle_ends",
"_particle_starts", "wrap_text", "wrap_variants", "WRAP_MODES",
"fit_size", "line_em_for_size", "MIN_CAPTION_FRACTION", "ass_units_local"
]
diff --git a/scripts/_common/text.py b/scripts/_common/text.py
index 9772607..42617b0 100644
--- a/scripts/_common/text.py
+++ b/scripts/_common/text.py
@@ -38,7 +38,7 @@ from _common.wrap import (
text_width_em, SAFE_WIDTH_FRACTION, ORPHAN_MIN_EM, WRAP_MODES, JA_PARTICLES, JA_PARTICLE_WORDS,
JA_SENTENCE_END, JA_NO_LINE_START, JA_NO_LINE_END, FUNCTION_WORDS, _FUNCTION_WORDS_ANY, PENALTY_FORBIDDEN,
PENALTY_OKURIGANA, PENALTY_FUNCTION_WORD, PENALTY_IDEOGRAPHS, PENALTY_NEUTRAL, PENALTY_FUNCTION_WORD_START,
- PENALTY_PARTICLE, PENALTY_SENTENCE_END, _HYPHENS, _atoms, _split_hyphens, _join, _break_spaced, _is_kana,
+ PENALTY_PARTICLE, PENALTY_SENTENCE_END, _HYPHENS, _atoms, _split_hyphens, _slice_atom, _join, _break_spaced, _is_kana,
_is_katakana_run, _is_hiragana, _is_ideograph, _is_weak_line, _function_words, _bare_word, _particle_starts,
_particle_ends, break_penalty, _cut_penalty, best_break, _fix_orphans, _fix_weak_lines, _rebalance,
_rebalance_phrase, _greedy_chunks, _balance, wrap_text, wrap_variants, MIN_CAPTION_FRACTION,
diff --git a/scripts/_common/wrap.py b/scripts/_common/wrap.py
index 2a486ec..2db6bfc 100644
--- a/scripts/_common/wrap.py
+++ b/scripts/_common/wrap.py
@@ -265,6 +265,37 @@ def _split_hyphens(atoms: "List[Tuple[str, bool]]") -> "List[Tuple[str, bool]]":
return out
+def _slice_atom(atom: str, max_em: float) -> "List[str]":
+ """The escape hatch (1.18.4): hard-slice a single atom that is wider than `max_em` all by
+ itself -- a word or run with no break point the wrapper may use, and that STILL does not fit
+ even alone on its own line. Nothing else in this file may ever chop an atom mid-character;
+ this is the one place that does, and only once every other mechanism (wrapping, then
+ caption.py's --min-size shrink) has already failed to make it fit.
+
+ No dictionary, no hyphenation library: an existing hyphen is preferred as the cut (the same
+ break R1 already allows), then whatever is left is cut again at exactly the widest prefix
+ that still measures within `max_em`, one character at a time. The characters themselves are
+ never rewritten -- every piece concatenates back to the original atom exactly."""
+ if text_width_em(atom) <= max_em:
+ return [atom]
+ for i in range(len(atom) - 2, 0, -1):
+ # latest hyphen whose left side still fits -- keeps the left half as large as possible
+ if atom[i] in _HYPHENS and text_width_em(atom[:i + 1]) <= max_em:
+ return [atom[:i + 1]] + _slice_atom(atom[i + 1:], max_em)
+ pieces: "List[str]" = []
+ cur = ""
+ for ch in atom:
+ candidate = cur + ch
+ if cur and text_width_em(candidate) > max_em:
+ pieces.append(cur)
+ cur = ch
+ else:
+ cur = candidate
+ if cur:
+ pieces.append(cur)
+ return pieces or [atom]
+
+
def _join(left: str, atom: str, spaced: bool) -> str:
"""Put an atom back on a line, restoring the space that stood before it."""
if not left:
@@ -574,15 +605,38 @@ def _rebalance_phrase(lines: "List[str]", max_em: float, lang: "Optional[str]")
return out, moved
-def _greedy_chunks(raw: str, max_em: float) -> "List[str]":
- """The greedy fill on its own: the line count every mode must keep."""
+def _greedy_chunks(raw: str, max_em: float, *, slice_overlong: bool = False,
+ sliced: "Optional[List[int]]" = None) -> "List[str]":
+ """The greedy fill on its own: the line count every mode must keep.
+
+ `slice_overlong` (off by default -- only caption.py's final burn-in pass turns it on, never
+ fit_size()'s search) is the escape hatch: an atom that lands alone on a line and is STILL
+ wider than `max_em` -- a fitting atom never reaches this branch, so a Thai phrase or a
+ katakana run that already fits is completely untouched -- is hard-sliced by _slice_atom()
+ instead of kept whole. `sliced`, when given, gets one entry (the number of extra lines that
+ one atom produced) per atom actually sliced, which is how the caller counts
+ `broken_inside_word` without re-deriving it from the output lines."""
current = ""
chunk: "List[str]" = []
for atom, spaced in _atoms(raw):
+ if slice_overlong and not current and text_width_em(atom) > max_em:
+ pieces = _slice_atom(atom, max_em)
+ if sliced is not None and len(pieces) > 1:
+ sliced.append(len(pieces) - 1)
+ chunk.extend(pieces[:-1])
+ current = pieces[-1]
+ continue
candidate = _join(current, atom, spaced)
if current and text_width_em(candidate) > max_em:
chunk.append(current)
- current = atom
+ if slice_overlong and text_width_em(atom) > max_em:
+ pieces = _slice_atom(atom, max_em)
+ if sliced is not None and len(pieces) > 1:
+ sliced.append(len(pieces) - 1)
+ chunk.extend(pieces[:-1])
+ current = pieces[-1]
+ else:
+ current = atom
else:
current = candidate
if current:
@@ -608,7 +662,8 @@ def _balance(chunk: "List[str]", max_em: float, mode: str, lang: "Optional[str]"
def wrap_text(text: str, max_em: float, *, balance: bool = True, mode: str = "phrase",
- lang: "Optional[str]" = None) -> "List[str]":
+ lang: "Optional[str]" = None, slice_overlong: bool = False,
+ sliced: "Optional[List[int]]" = None) -> "List[str]":
"""Wrap `text` to lines no wider than `max_em` em, keeping the manual breaks it already has.
An atom wider than the whole line (one very long word) is left alone on its line rather than
@@ -626,11 +681,12 @@ def wrap_text(text: str, max_em: float, *, balance: bool = True, mode: str = "ph
for raw in text.split("\n"):
if not raw.strip():
continue
- chunk = _greedy_chunks(raw, max_em)
+ chunk = _greedy_chunks(raw, max_em, slice_overlong=slice_overlong, sliced=sliced)
lines.extend(_balance(chunk, max_em, mode, lang) if balance else chunk)
return lines or [text]
def wrap_variants(text: str, max_em: float, *, mode: str = "phrase",
- lang: "Optional[str]" = None) -> "Tuple[List[str], List[str], List[str]]":
+ lang: "Optional[str]" = None, slice_overlong: bool = False,
+ sliced: "Optional[List[int]]" = None) -> "Tuple[List[str], List[str], List[str]]":
"""`(wrapped, greedy, measured)` for one cue from a single greedy fill.
layout_cues needs all three -- `wrapped` is what is burnt in, `greedy` is what `rebalanced`
@@ -645,7 +701,7 @@ def wrap_variants(text: str, max_em: float, *, mode: str = "phrase",
for raw in text.split("\n"):
if not raw.strip():
continue
- chunk = _greedy_chunks(raw, max_em)
+ chunk = _greedy_chunks(raw, max_em, slice_overlong=slice_overlong, sliced=sliced)
greedy.extend(chunk)
wrapped.extend(_balance(list(chunk), max_em, mode, lang))
measured.extend(chunk if mode == "measured" else _balance(list(chunk), max_em, "measured", None))
diff --git a/scripts/caption.py b/scripts/caption.py
index 954a61c..3f5e3f7 100755
--- a/scripts/caption.py
+++ b/scripts/caption.py
@@ -53,7 +53,7 @@ from _common import (ASR_INSTALL_HINT, die_no_engine, parse_srt, transcribe, whi
from _common import (SAFE_WIDTH_FRACTION, ORPHAN_MIN_EM, WRAP_MODES, wrap_text, wrap_variants, best_break,
fit_size, line_em_for_size, MIN_CAPTION_FRACTION,
break_penalty, _is_weak_line, _atoms, _join, _break_spaced, _bare_word, _function_words,
- _split_hyphens, FUNCTION_WORDS, JA_PARTICLES, JA_SENTENCE_END, _fix_orphans, _rebalance)
+ _split_hyphens, _slice_atom, FUNCTION_WORDS, JA_PARTICLES, JA_SENTENCE_END, _fix_orphans, _rebalance)
# The breaker's names are caption.py's public surface as much as _common's: every caller and test
# that reached for `caption.wrap_text` before 1.16 still does.
@@ -62,7 +62,7 @@ __all__ = ["parse_srt", "write_srt", "transcribe", "whisper_word_timings", "die_
"SAFE_WIDTH_FRACTION", "ORPHAN_MIN_EM", "WRAP_MODES", "wrap_text", "wrap_variants",
"fit_size", "line_em_for_size", "MIN_CAPTION_FRACTION",
"best_break", "break_penalty", "_is_weak_line", "_atoms", "_join", "_break_spaced",
- "_bare_word", "_function_words", "_split_hyphens", "FUNCTION_WORDS", "JA_PARTICLES",
+ "_bare_word", "_function_words", "_split_hyphens", "_slice_atom", "FUNCTION_WORDS", "JA_PARTICLES",
"JA_SENTENCE_END", "_fix_orphans", "_rebalance", "char_script", "NO_SPACE_SCRIPTS",
"text_width_em"]
@@ -319,6 +319,10 @@ def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float]
"""
stats = {"shifted": 0, "wrapped": 0, "split": 0, "extended": 0, "dropped": 0, "rebalanced": 0,
"wrap": wrap, "phrase_breaks": 0}
+ # ass_units_local's floor + the escape hatch below mean an atom this loop hands to
+ # wrap_variants(..., slice_overlong=True) can still overflow only if a SINGLE character is
+ # wider than the column -- practically unreachable at any real --min-size. `overlong` stays
+ # in stats for that theoretical remainder; `broken_inside_word` is the count that matters now.
staged: List[Tuple[float, float, str]] = []
staged_sizes: List[Optional[int]] = []
for cue_index, (start, end, text) in enumerate(cues):
@@ -339,12 +343,19 @@ def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float]
# one greedy fill per cue, three answers off it: what gets burnt in, what the
# greedy wrap would have given (`rebalanced`) and what 1.15's wrap would have
# given (`phrase_breaks`). Three wrap_text() calls re-ran the atomiser each time.
- lines, greedy, measured = wrap_variants(text, own_em, mode=wrap, lang=lang)
+ sliced_atoms: List[int] = []
+ lines, greedy, measured = wrap_variants(text, own_em, mode=wrap, lang=lang,
+ slice_overlong=True, sliced=sliced_atoms)
if lines != [l for l in text.split("\n") if l.strip()]:
stats["wrapped"] += 1
+ if sliced_atoms:
+ # the escape hatch fired: a word or run with no break point the wrapper may use
+ # was still wider than the column alone, even at the size in force, so it was
+ # hard-sliced at the column edge (or after its own hyphen) instead of clipping
+ stats["broken_inside_word"] = stats.get("broken_inside_word", 0) + len(sliced_atoms)
if any(text_width_em(l) > own_em for l in lines):
- # a run with no break point the wrapper may use (a long word, a Thai phrase
- # without spaces) stays long rather than chopped: say so, and name the fix
+ # the escape hatch above could not make every piece fit -- only possible when a
+ # single character is wider than the column itself
stats["overlong"] = stats.get("overlong", 0) + 1
if lines != greedy:
stats["rebalanced"] += 1
@@ -381,13 +392,19 @@ def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float]
def report_layout(stats: dict) -> None:
"""One info line, only when a cue actually changed."""
- parts = [f"{stats[k]} {k}" for k in ("shifted", "wrapped", "rebalanced", "phrase_breaks", "split", "extended", "dropped", "overlong") if stats.get(k)]
+ parts = [f"{stats[k]} {k}" for k in ("shifted", "wrapped", "rebalanced", "phrase_breaks", "split",
+ "extended", "dropped", "broken_inside_word", "overlong") if stats.get(k)]
if parts:
info("cues: " + ", ".join(parts))
+ if stats.get("broken_inside_word"):
+ info(f"{stats['broken_inside_word']} cue line(s) had a word or run with no break point "
+ "(Thai writes none inside a phrase) that was still wider than the column alone -- it "
+ "was sliced at the column edge (after its own hyphen when it has one) instead of "
+ "clipping past the frame; put a space or `|` where the line may break, or use a "
+ "smaller --size, to avoid the slice")
if stats.get("overlong"):
- info(f"{stats['overlong']} cue line(s) wider than the safe width: a word or a run with no break "
- "point (Thai writes none inside a phrase) was kept whole rather than chopped -- put a "
- "space or `|` where the line may break, or use a smaller --size")
+ info(f"{stats['overlong']} cue line(s) wider than the safe width even after slicing: a "
+ "single character was wider than the column -- use a smaller --size")
def margins_x(args, play_w: Optional[int]) -> Tuple[int, int]:
diff --git a/tests/test_picture.py b/tests/test_picture.py
index 377dd6b..2b9c89c 100644
--- a/tests/test_picture.py
+++ b/tests/test_picture.py
@@ -2703,6 +2703,84 @@ class PhraseWrapTests(unittest.TestCase):
self.assertEqual(C.wrap_text("\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u30fc\u3092\u8cb7\u3063\u305f", 7.0), ["\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u30fc", "\u3092\u8cb7\u3063\u305f"])
self.assertEqual([a for a, _ in C._atoms("\u30bf\u30a4\u30df\u30f3\u30b0\u304c")][0], "\u30bf\u30a4\u30df\u30f3\u30b0")
+ # -------------------------------------------------------------- escape hatch (1.18.4, cs2)
+ def test_overlong_word_is_sliced_at_the_column_edge(self):
+ """cs2 (eval 20): a single 32-letter word with no break point, wider than the live column
+ even at --min-size, used to be kept whole and clipped past both frame edges. It is now
+ hard-sliced at exactly the column width, wherever `slice_overlong` is turned on -- the
+ escape hatch itself is off by default in wrap_text()/wrap_variants(), so nothing here
+ changes unless a caller asks for it (caption.py's burn-in pass is the only caller that
+ does)."""
+ C = self.caption
+ word = "Supercalifragil\u00edsticoespialidoso"
+ for max_em in (self.NARROW, 8.0, self.W):
+ with self.subTest(max_em=max_em):
+ # off by default: the word is kept whole, exactly as before this change
+ self.assertEqual(C.wrap_text(word, max_em), [word])
+ # the escape hatch: every produced line now measures within the column
+ lines = C.wrap_text(word, max_em, slice_overlong=True)
+ for line in lines:
+ self.assertLessEqual(C.text_width_em(line), max_em, lines)
+ # no character was added, dropped or reordered
+ self.assertEqual("".join(lines), word)
+
+ def test_overlong_word_prefers_its_own_hyphen(self):
+ """When the overlong atom already has a hyphen, the slice prefers the cut right after it
+ -- the same break R1 already allows elsewhere -- over an arbitrary character cut, as long
+ as that still fits the column."""
+ C = self.caption
+ atom = "co-occurrencemeasurementsomethingunbreakablylong"
+ pieces = C._slice_atom(atom, 12.0)
+ self.assertTrue(pieces[0].endswith("-"), pieces)
+ for piece in pieces:
+ self.assertLessEqual(C.text_width_em(piece), 12.0, pieces)
+ self.assertEqual("".join(pieces), atom)
+
+ def test_layout_cues_reports_broken_inside_word_not_overlong(self):
+ """caption.py's per-cue loop (layout_cues) is the one caller that turns the escape hatch
+ on. cs2's cue now burns in with every line inside the safe column, and the new
+ `broken_inside_word` stat -- not `overlong` -- counts it."""
+ C = self.caption
+ word = "Supercalifragil\u00edsticoespialidoso"
+ max_em = self.NARROW
+ cues = [(0.0, 3.0, word)]
+ out, stats = C.layout_cues(cues, max_em=max_em, max_lines=4, min_duration=0.0, offset=0.0)
+ self.assertEqual(stats.get("broken_inside_word", 0), 1, stats)
+ self.assertNotIn("overlong", stats)
+ for _start, _end, text in out:
+ for line in text.split("\n"):
+ self.assertLessEqual(C.text_width_em(line), max_em, out)
+
+ def test_overlong_still_fires_when_even_one_character_does_not_fit(self):
+ """The escape hatch guarantees every piece fits as long as at least one character does.
+ `overlong` is not dead code: it is the fallback for the one case the hatch cannot fix, a
+ single character wider than the column itself (a pathologically small --size)."""
+ C = self.caption
+ # a full-width ideograph is 1.0 em; 0.5 em is narrower than any single character of it
+ text = "\u4e00\u4e8c\u4e09"
+ max_em = 0.5
+ cues = [(0.0, 3.0, text)]
+ out, stats = C.layout_cues(cues, max_em=max_em, max_lines=1, min_duration=0.0, offset=0.0)
+ self.assertEqual(stats.get("overlong", 0), 1, stats)
+
+ def test_escape_hatch_never_touches_a_fitting_thai_or_katakana_run(self):
+ """The hard constraint: an atom that already fits is never eligible for the escape hatch,
+ even with `slice_overlong=True` -- a fitting Thai phrase or katakana run must come back
+ exactly as written, same as 1.16.1."""
+ C = self.caption
+ thai_run = "\u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e35\u0e0a\u0e32\u0e27\u0e42\u0e25\u0e01"
+ kata_run = "\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u30fc"
+ wide = self.W # both runs fit comfortably at the wide platform width
+ self.assertLessEqual(C.text_width_em(thai_run), wide)
+ self.assertLessEqual(C.text_width_em(kata_run), wide)
+ self.assertEqual(C.wrap_text(thai_run, wide, slice_overlong=True), [thai_run])
+ self.assertEqual(C.wrap_text(kata_run, wide, slice_overlong=True), [kata_run])
+ # and unbroken through wrap_variants, the entry point caption.py actually calls
+ wrapped, greedy, measured = C.wrap_variants(thai_run, wide, slice_overlong=True)
+ self.assertEqual(wrapped, [thai_run])
+ wrapped, greedy, measured = C.wrap_variants(kata_run, wide, slice_overlong=True)
+ self.assertEqual(wrapped, [kata_run])
+
# -------------------------------------------------------------- R4: function words
def test_function_word_never_ends_a_line(self):
C = self.caption