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.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
fix: measure rotated frames at the size they are shown (#344)
Shogo Kajiyamaef1c29cfb517
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9358af5..a1f5559 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,10 @@## Unreleased-(nothing yet)+### Fixed++- **A rotated file is measured and composited at the size it is shown.** ffmpeg applies a 90° or 270° display rotation before the filter graph, and `probe.py` still reports the stored width and height. `overlay.py --scale-percent` took half of that stored width (a 50% logo on a 320×180 phone file shown as 180×320 was 160 px, almost the whole frame). `--platform` margins used the same stored size, so TikTok's 14% right margin was 14% of the landscape width. `broll.py` scaled the cutaway to the stored frame and clipped it onto the portrait one. `cropdetect.py` reported `source_width`/`source_height` as the stored size while the rectangle was in the displayed frame (a 176×320 crop against a 320×180 source). `look.py --safe` warned that a 9:16 phone file stored as 16:9 was the wrong shape for TikTok. The displayed size is what those tools use now.+- **The colour-emoji probe survives a path that contains a colon, and a Windows font path is not split on the drive letter.** `subtitles=C:/...` is read as the option `C` plus a following option, so the probe that decides whether libass can draw colour emoji failed on every Windows temp directory and reported the capability unknown. The same `fc-list` line `C:\Windows\Fonts\seguiemj.ttf: Segoe UI Emoji` was split on the first colon, so the font file was `C` and a monochrome fallback was never found. The probe now uses the filter-path escape, and the listing is split on colon-space, which is the separator fontconfig prints.## 2.10.6diff --git a/docs/contract.md b/docs/contract.mdindex 91eb912..aa7585e 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -613,7 +613,7 @@ Per-tool keys added in 1.18.0, all additive:| `shots` | `scenes.py --shots` | `[{start, end, label, flow_magnitude}]` per detected scene, `label` one of `static`/`pan`/`motion` from a lightweight block-matching optical-flow proxy (frames decoded at 4 fps, 48x27, no external dependency). A shot too short to sample two frames is `static` with `flow_magnitude: 0` || `audio_peaks_db` | `scenes.py --audio-peaks` | `[{time, level}]`, measured dBFS loudness peaks. A **new** key: the pre-existing `audio_peaks` (always reported, unrelated unitless RMS figures used for `--highlights` scoring) keeps its 1.0 meaning unchanged || `speech` | `scenes.py --speech` | `[{time, speech_music_ratio}]`, a per-second zero-crossing-rate ratio against the file's own median — a measured proxy, not a speech/music classification |-| `motion_centre` | `cropdetect.py --motion-centre` | `[{time, x, y, x_frac, y_frac, motion}]` per second, sampled over the same windows as the crop-bar detection. `x`/`y` are source pixels, `x_frac`/`y_frac` a 0..1 fraction of `source_width`/`source_height`; a window with no measured motion reports `x`/`y`/`x_frac`/`y_frac: null`. Report only — this tool never picks a reframe |+| `motion_centre` | `cropdetect.py --motion-centre` | `[{time, x, y, x_frac, y_frac, motion}]` per second, sampled over the same windows as the crop-bar detection. `x`/`y` are source pixels, `x_frac`/`y_frac` a 0..1 fraction of `source_width`/`source_height`. Those two sizes are the displayed frame (a 90° or 270° rotation swaps the stored size), the same frame the crop rectangle and `crop.py` use. A window with no measured motion reports `x`/`y`/`x_frac`/`y_frac: null`. Report only — this tool never picks a reframe || `speech_aware`, `speech_aware.breaths` | `silence.py --speech-aware` | `{min_silence, floor, breaths_kept, breaths_kept_seconds, breaths}`. `breaths` are the sub-`--min-silence` gaps kept because they sit inside a sentence; the removal list (`silences`, `keep`, `removed_seconds`) already reflects the speech-aware classification. Composes with `--filler` through the same `keep_ranges()`/`merge_spans()` pipeline, so `--speech-aware --filler` produces one removal list || `sources` | `sync.py` | `[{path, offset_s, confidence, drift_ppm}]`, one entry per SOURCE. Present for every run, including the original single-SOURCE shape (where it mirrors the top-level `second`/`offset_seconds`/`confidence` additively). With 2+ SOURCEs it is the *only* per-source shape: there is no top-level `second`/`offset_seconds` because there is no single pair to put there || `switch_mode`, `min_shot` | `multicam.py --switch energy` | `"energy"` and the `--min-shot` value used (default 1.5s), alongside the existing `cuts` (`[[start, end, camera], ...]`) which already carries the camera index for `--edl`'s companion cut list |diff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex 2dd57f1..9513cc5 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -1576,6 +1576,23 @@ not a new file format this tool would have to maintain.`start_snapped`'s meaning (the presented start moved) and `precision` takes`least_exact_precision`'s (the least exact segment).+## Unreleased — geometry uses the displayed frame++- **A 90° or 270° rotation is applied before a tool measures or places a rectangle.** ffmpeg+ autorotates on decode, so the filter graph sees the picture the player shows, not the stored+ width and height. `probe.py` still reports the stored size plus `rotation` (that pair is what+ a stream copy keeps). `cropdetect.py`'s `source_width`/`source_height`, its crop rectangle and+ its motion points are the displayed frame, which is the frame `crop.py` checks. `broll.py`+ scales the cutaway to that frame. `overlay.py --scale-percent` and `--platform` margins, and+ `look.py --safe`'s aspect note, use it too. Tools that already swapped (`fit`, `crop`,+ `redact`, `caption`, `graphics`, `join`, `multicam`, `proxy`) are unchanged. Code:+ `cropdetect.main()`, `broll.main()`, `overlay.main()`, `look.main()`. Tests:+ `test_cropdetect_reports_the_displayed_frame_of_a_rotated_source`,+ `test_broll_sizes_the_cutaway_to_the_displayed_frame`,+ `test_overlay_scale_percent_uses_the_displayed_width`,+ `test_overlay_platform_margins_use_the_displayed_frame`,+ `test_look_safe_compares_the_displayed_aspect_of_a_rotated_source`.+## Unreleased — an accurate cut starts its picture at 0- **`cut.py --accurate` on a video does not pass `-avoid_negative_ts make_zero`.** Thediff --git a/references/gotchas.md b/references/gotchas.mdindex f6ff667..a88c0e6 100644--- a/references/gotchas.md+++ b/references/gotchas.md@@ -281,8 +281,12 @@ see what the app covers. An explicit `--margin` always wins.### Dimensions and rotation`yuv420p` needs even width/height; `fit.py` and `export.py` round to even values-automatically. Phone footage often carries a `rotation` tag; `probe.py` reports-it and `fit.py` accounts for it when computing the output frame.+automatically. Phone footage often carries a `rotation` tag. `probe.py` reports+the stored width and height plus that rotation. A tool that places or measures+a rectangle (`fit.py`, `crop.py`, `cropdetect.py`, `broll.py`, `overlay.py+--scale-percent` / `--platform`, `look.py --safe`) uses the displayed size,+the two swapped for 90° and 270°, because ffmpeg applies the tag before the+filter graph.## Planningdiff --git a/references/scripts.md b/references/scripts.mdindex 08ddc74..ad57427 100644--- a/references/scripts.md+++ b/references/scripts.md@@ -242,7 +242,10 @@ cropdetect.py INPUT [--seconds N] [--samples N] [--limit F] [--round N] [--motioMeasurement only -- writes no file. Samples `--samples` windows spreadacross the file (default 5, totalling `--seconds` 10s of footage) andreports the crop rectangle FFmpeg's `cropdetect` filter found most often, as-`{x, y, width, height}` ready to hand to `crop.py`. Distinct from+`{x, y, width, height}` ready to hand to `crop.py`. `source_width` /+`source_height` are that same displayed frame: a 90° or 270° rotation swaps+the stored size, because the filter measures the picture after ffmpeg applies+the tag. Distinct from`fit.py --fit crop`, which crops to a target aspect ratio it computesitself with no black-bar measurement involved. A rectangle that matches thefull source frame means no bars were found. Does not decide whether@@ -501,7 +504,8 @@ broll.py A.mp4 --insert B.mp4 --at T [--duration D | --end T2] [--from T3][--insert ... --at ...] [--audio a|b|mix] [--pad-color black] [-o OUT]```A plays as it is; during each window B's picture is shown instead (scaled and-padded to A's frame, A's fps), and A resumes at its own time when the window+padded to A's displayed frame, A's fps; a 90° or 270° rotation swaps the+stored size), and A resumes at its own time when the windowends -- a cutaway, not a splice, so the output is exactly as long as A. One`--insert`/`--at` pair per cutaway (`--duration`, `--end`, `--from` are percutaway too, or given once for all; defaults 4 s and 0); windows may not@@ -1220,7 +1224,8 @@ Outputs PNG. View it with the Read tool (or any image viewer) and judge theframe like an editor would. Use `--compare` to show before/after to the user. `--safe NAME` (1.14) shades the zones thatdestination's own UI covers -- TikTok's description block and like column, the Reels/Shortschrome -- on the sheet or the frame, so "is the caption readable" can be answered about the app-rather than about the file.+rather than about the file. The "wrong aspect" note compares the displayed frame, so a phone+file stored sideways is not flagged when the picture already matches the destination.### caption.py — subtitles (static, animated, karaoke)```@@ -1466,6 +1471,9 @@ overlay.py INPUT --image PNG [--scale W | --scale-percent P] | --text "..." [--f`--platform NAME` (1.14) takes each edge's margin from that destination's safe zone(`scripts/_platforms.py`), so a template's top-left logo clears TikTok's status bar instead ofsitting 24 px into it; an explicit `--margin` (or a brand `safe_margin`) wins.+`--scale-percent` and those margins use the displayed frame width and height:+a 90° or 270° rotation swaps the stored size, which is the frame the overlay+is composited on.Alpha in PNGs is respected. Fades apply to the overlay only; the video keepsplaying. `--scale` / `--scale-percent` set the width of an image, logo or`--video` layer. They are refused with `--text`: text size is `--font-size`.diff --git a/scripts/_common/decision.py b/scripts/_common/decision.pyindex 1d68f88..e16ec9e 100644--- a/scripts/_common/decision.py+++ b/scripts/_common/decision.py@@ -244,7 +244,7 @@ def fmt_smpte_time(seconds: float, fps: float) -> str:return f"{h:02d}:{m:02d}:{s:02d}:{frame:02d}"-def escape_filter_path(path: str) -> str:+def escape_filter_path(path: str, *, bind: bool = True) -> str:"""Escape a file path for use as a filter option value (subtitles=, ass=, lut3d=file=, fontfile=, fontsdir=).A filter option value is parsed twice: the graph parser splits filters on `,` / `;` and options@@ -258,8 +258,11 @@ def escape_filter_path(path: str) -> str:token, so a single `\\'` is consumed by the first pass and "Ryo's Mac/cues.srt" reaches thefilter as "Ryos Mac/cues.srt" (Unable to open ...). Three backslashes survive both passes(measured on 6.1 and 7.1 with subtitles=, ass= and lut3d=file=).++ `bind=False` escapes without recording the path as a plan input. The colour-emoji probe+ uses that: its SRT lives in a temp directory that is gone before any plan is written."""- if os.path.isfile(path) and path not in STATE.plan_inputs:+ if bind and os.path.isfile(path) and path not in STATE.plan_inputs:STATE.plan_inputs.append(path) # a plan binds subtitle/LUT/font files too (review 6)p = str(Path(path))p = p.replace("\\", "/")diff --git a/scripts/_common/emoji.py b/scripts/_common/emoji.pyindex aef9d7e..becb9be 100644--- a/scripts/_common/emoji.py+++ b/scripts/_common/emoji.py@@ -8,6 +8,7 @@ import osimport shutilimport subprocessfrom typing import Any, Dict, List, Tuple, Optional+from _common.decision import escape_filter_pathfrom _common.emit import diefrom _common.runner import ffmpeg_exe@@ -165,6 +166,18 @@ EMOJI_ASSET_HINT = (_EMOJI_COLOR_FAMILIES = ("Noto Color Emoji", "Apple Color Emoji", "Segoe UI Emoji")+def _fc_list_path(line: str) -> str:+ """The file from one `fc-list ... file` line.++ fontconfig prints `<file>: <families>`. The separator is a colon followed by a space.+ A Windows drive letter is `C:` followed by a backslash, so splitting on the first colon+ yields `C` and the font is reported missing.+ """+ if ": " in line:+ return line.partition(": ")[0].strip()+ return line.strip().rstrip(":")++_EMOJI_SUPPORT_CACHE: "Dict[Tuple[Optional[str], bool], Dict[str, Any]]" = {}@@ -182,7 +195,7 @@ def _emoji_color_font() -> "Tuple[Optional[str], Optional[str], bool]":if proc.returncode != 0:return None, None, Falsefor line in proc.stdout.splitlines():- path = line.split(":", 1)[0].strip()+ path = _fc_list_path(line)if path and os.path.exists(path):return family, path, Truereturn None, None, True@@ -205,7 +218,7 @@ def _libass_color_probe() -> "Optional[bool]":proc = subprocess.run([exe, "-hide_banner", "-loglevel", "error", "-f", "lavfi","-i", "color=c=black:s=64x64:d=0.04",- "-vf", "subtitles=" + srt.replace("\\", "/"), "-frames:v", "1",+ "-vf", "subtitles=" + escape_filter_path(srt, bind=False), "-frames:v", "1","-f", "rawvideo", "-pix_fmt", "rgb24", "-"],stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=20)except (subprocess.TimeoutExpired, OSError):diff --git a/scripts/broll.py b/scripts/broll.pyindex a7966ba..b5c1339 100755--- a/scripts/broll.py+++ b/scripts/broll.py@@ -56,6 +56,9 @@ def main() -> int:die("A-roll has no video stream")dur_a = meta_a.get("duration") or 0.0w, h = meta_a["video"]["width"], meta_a["video"]["height"]+ # the cutaway is scaled onto the frame ffmpeg has already rotated, not the stored one+ if meta_a["video"].get("rotation") in (90, -90, 270, -270):+ w, h = h, wfps = meta_a["video"].get("fps") or 30.0has_audio_a = bool(meta_a.get("audio"))diff --git a/scripts/cropdetect.py b/scripts/cropdetect.pyindex bd5ea26..b459eb3 100644--- a/scripts/cropdetect.py+++ b/scripts/cropdetect.py@@ -138,6 +138,11 @@ def main() -> int:if not meta.get("video"):die("input has no video stream")sw, sh = meta["video"]["width"], meta["video"]["height"]+ # cropdetect and the grey decode both see the frame after ffmpeg applies rotation, so the+ # rectangle and the motion points are in that frame. Reporting the stored size made a+ # 176x320 crop look taller than a 320x180 source.+ if meta["video"].get("rotation") in (90, -90, 270, -270):+ sw, sh = sh, swduration = meta.get("duration") or 0.0rects = detect(args.input, args.seconds, args.samples, args.limit, args.round_to, duration)diff --git a/scripts/look.py b/scripts/look.pyindex bf9fcd1..17a6738 100755--- a/scripts/look.py+++ b/scripts/look.py@@ -170,8 +170,11 @@ def main() -> int:z = PLATFORMS[args.safe]["safe"]frame = PLATFORMS[args.safe]["frame"]src = meta["video"]- if src.get("width") and src.get("height") and abs(src["width"] / src["height"] - frame["w"] / frame["h"]) > 0.02:- info(f"--safe {args.safe}: this source is {src['width']}x{src['height']}, not {args.safe}'s "+ dw, dh = src.get("width") or 0, src.get("height") or 0+ if src.get("rotation") in (90, -90, 270, -270):+ dw, dh = dh, dw+ if dw and dh and abs(dw / dh - frame["w"] / frame["h"]) > 0.02:+ info(f"--safe {args.safe}: this source is {dw}x{dh}, not {args.safe}'s "f"{frame['w']}x{frame['h']} -- the zones are drawn as fractions of the frame you gave, "f"so reframe first (fit.py --aspect) to see what the app really covers")boxes = []diff --git a/scripts/overlay.py b/scripts/overlay.pyindex 5fbb074..c0f0ec3 100755--- a/scripts/overlay.py+++ b/scripts/overlay.py@@ -117,7 +117,9 @@ def main() -> int:ap.add_argument("--opacity", type=float, default=1.0, help="0..1 (default 1)")img = ap.add_argument_group("image options")img.add_argument("--scale", type=int, help="width in px for an image, logo or video layer (keeps aspect); text size is --font-size")- img.add_argument("--scale-percent", type=float, help="width as a %% of the video for an image, logo or video layer (keeps aspect); text size is --font-size")+ img.add_argument("--scale-percent", type=float,+ help="width as a %% of the displayed frame for an image, logo or video layer (keeps aspect); "+ "a 90 or 270 degree rotation uses the stored height; text size is --font-size")txt = ap.add_argument_group("text options")txt.add_argument("--font", default="DejaVu Sans", help="fontconfig font name")txt.add_argument("--font-file", help="explicit .ttf/.otf/.ttc path (use this for CJK fonts)")@@ -209,7 +211,12 @@ def main() -> int:die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")if args.audio_stream and not audio_streams:die("--audio-stream needs an input with audio streams")- vw = meta["video"]["width"]+ vw = meta["video"]["width"] or 0+ vh = meta["video"].get("height") or 0+ # ffmpeg applies display rotation before the filter graph, so the frame this overlay is+ # composited on is the displayed one. A 320x180 phone file tagged 90 degrees is 180 wide here.+ if meta["video"].get("rotation") in (90, -90, 270, -270):+ vw, vh = vh, vw# --platform: the edges this destination's own UI covers, in pixels of this frame. An# explicit --margin (or a brand safe_margin, applied above) is the more specific statement# and wins; without either, the historical 24 px default is unchanged.@@ -220,7 +227,7 @@ def main() -> int:# fall back to the destination's own delivery frame -- which is what the fitted# intermediate this stage runs on will be anywayframe = PLATFORMS[args.platform]["frame"]- pw, ph = vw or frame["w"], meta["video"].get("height") or frame["h"]+ pw, ph = vw or frame["w"], vh or frame["h"]safe_margins = safe_margins_px(args.platform, pw, ph)info(f"--platform {args.platform}: safe margins top {safe_margins['top']} / bottom {safe_margins['bottom']} / "f"left {safe_margins['left']} / right {safe_margins['right']} px (clear of the app's own UI)")diff --git a/tests/test_analysis.py b/tests/test_analysis.pyindex da3afe7..942598a 100644--- a/tests/test_analysis.py+++ b/tests/test_analysis.py@@ -56,6 +56,20 @@ class AnalysisTests(MediaFixtures):self.assertLess(result["crop"]["height"], 480)self.assertGreater(result["crop"]["y"], 0)+ def test_cropdetect_reports_the_displayed_frame_of_a_rotated_source(self):+ """cropdetect runs after ffmpeg applies rotation. The stored 1280x720 phone file is+ 720x1280 on screen, and a rectangle reported against the stored size is taller than+ the source it claims to sit in."""+ v = probe(str(self.rot))["video"]+ self.assertIn(v["rotation"], (90, -90, 270, -270))+ dw, dh = v["height"], v["width"]+ data = json.loads(script("cropdetect.py", self.rot, "--seconds", "1", "--samples", "1", "--json").stdout)+ self.assertEqual((data["source_width"], data["source_height"]), (dw, dh))+ crop = data["crop"]+ self.assertIsNotNone(crop)+ self.assertLessEqual(crop["x"] + crop["width"], data["source_width"])+ self.assertLessEqual(crop["y"] + crop["height"], data["source_height"])+def test_cropdetect_writes_no_file(self):before = set(OUT.iterdir())script("cropdetect.py", self.src, "--seconds", "1", "--samples", "1")@@ -705,6 +719,19 @@ class AnalysisTests(MediaFixtures):self.assertIn("y=ih*(1-0.22)", cmd[0])self.assertIn("x=iw*(1-0.14)", cmd[0])+ def test_look_safe_compares_the_displayed_aspect_of_a_rotated_source(self):+ """A 1280x720 file tagged 90 degrees is already 9:16. --safe tiktok used to warn that+ the stored 16:9 frame was the wrong shape for a destination the picture already matches."""+ v = probe(str(self.rot))["video"]+ self.assertIn(v["rotation"], (90, -90, 270, -270))+ proc = script("look.py", self.rot, "--at", "1", "--no-timecode", "--safe", "tiktok",+ "-o", OUT / "safe_rot.png", "--json")+ self.assertNotIn("not tiktok", proc.stderr)+ self.assertNotIn(f"{v['width']}x{v['height']}", proc.stderr)+ wide = script("look.py", self.src, "--at", "1", "--no-timecode", "--safe", "tiktok",+ "-o", OUT / "safe_wide.png", "--json")+ self.assertIn(f"{v['width']}x{v['height']}", wide.stderr)+def test_report_html(self):reels = OUT / "export_reels.mp4"if not reels.exists():diff --git a/tests/test_editing.py b/tests/test_editing.pyindex 5bd8275..572cfe0 100644--- a/tests/test_editing.py+++ b/tests/test_editing.py@@ -275,6 +275,19 @@ class EditingTests(MediaFixtures):script("broll.py", self.src, "--insert", b, "--at", "4", "--dry-run", "-o", dry)self.assertFalse(dry.exists())+ def test_broll_sizes_the_cutaway_to_the_displayed_frame(self):+ """A 1280x720 file tagged 90 degrees is shown 720x1280. The cutaway used to be scaled+ and padded to the stored 1280x180 landscape box and then clipped onto the portrait frame."""+ v = probe(str(self.rot))["video"]+ self.assertIn(v["rotation"], (90, -90, 270, -270))+ dw, dh = v["height"], v["width"]+ doc = json.loads(script("broll.py", self.rot, "--insert", self.src, "--at", "1", "--duration", "1",+ "--dry-run", "--json", "-o", OUT / "broll_rot.mp4").stdout)+ cmd = " ".join(doc["commands"])+ self.assertIn(f"scale={dw}:{dh}:", cmd)+ self.assertIn(f"pad={dw}:{dh}:", cmd)+ self.assertNotIn(f"scale={v['width']}:{v['height']}:", cmd)+def test_metadata_writes_chapters_and_tags_with_streams_copied(self):"""#140: metadata.py writes container chapter markers from a `TIME TITLE` file and thecommon tags, with every stream copied bit for bit; probe reports both back. Chapters on adiff --git a/tests/test_picture.py b/tests/test_picture.pyindex d1060b0..163b3cb 100644--- a/tests/test_picture.py+++ b/tests/test_picture.py@@ -1976,6 +1976,95 @@ class PictureTests(MediaFixtures):def test_overlay_chromakey_without_video_refused(self):script("overlay.py", self.src, "--chromakey", "green", expect_fail=True)+ def test_overlay_scale_percent_uses_the_displayed_width(self):+ """--scale-percent 50 on a 1280x720 file tagged 90 degrees used to scale the layer to+ 640 px, half the stored width, on a frame that is 720 px wide."""+ v = probe(str(self.rot))["video"]+ self.assertIn(v["rotation"], (90, -90, 270, -270))+ shown = v["height"]+ doc = json.loads(script("overlay.py", self.rot, "--image", self.logo, "--scale-percent", "50",+ "--dry-run", "--json", "-o", OUT / "ov_rot_scale.mp4").stdout)+ cmd = " ".join(doc["commands"])+ self.assertIn(f"scale={int(shown * 50 / 100)}:-1", cmd)+ self.assertNotIn(f"scale={int(v['width'] * 50 / 100)}:-1", cmd)+ plain_v = probe(str(self.src))["video"]+ plain = json.loads(script("overlay.py", self.src, "--image", self.logo, "--scale-percent", "50",+ "--dry-run", "--json", "-o", OUT / "ov_plain_scale.mp4").stdout)+ self.assertIn(f"scale={int(plain_v['width'] * 50 / 100)}:-1", " ".join(plain["commands"]))++ def test_overlay_platform_margins_use_the_displayed_frame(self):+ """TikTok's right margin is 14% of the width the viewer sees. On this rotated file that+ is 14% of 720, not 14% of the stored 1280."""+ from _platforms import safe_margins_px+ v = probe(str(self.rot))["video"]+ self.assertIn(v["rotation"], (90, -90, 270, -270))+ edges = safe_margins_px("tiktok", v["height"], v["width"])+ stored = safe_margins_px("tiktok", v["width"], v["height"])+ doc = json.loads(script("overlay.py", self.rot, "--text", "hi", "--platform", "tiktok",+ "--dry-run", "--json", "-o", OUT / "ov_rot_safe.mp4").stdout)+ cmd = " ".join(doc["commands"])+ self.assertIn(f"main_w-text_w-{edges['right']}", cmd)+ self.assertNotIn(f"main_w-text_w-{stored['right']}", cmd)++ def test_emoji_font_listing_keeps_a_colon_in_the_path(self):+ """fc-list separates the file from the family with colon-space. Splitting on the first+ colon turned `C:\\Windows\\Fonts\\seguiemj.ttf: Segoe UI Emoji` into `C`."""+ from _common import emoji as emoji_mod+ colon = OUT / "C:Fonts"+ colon.mkdir(exist_ok=True)+ real = colon / "emoji.ttf"+ real.write_bytes(b"not a font")+ self.assertEqual(emoji_mod._fc_list_path(r"C:\Windows\Fonts\seguiemj.ttf: Segoe UI Emoji:style=Regular"),+ r"C:\Windows\Fonts\seguiemj.ttf")+ line = f"{real}: Noto Color Emoji\n"++ def fake_run(cmd, **kw):+ return subprocess.CompletedProcess(cmd, 0, line, "")++ with unittest.mock.patch("shutil.which", return_value="fc-list"), \+ unittest.mock.patch("subprocess.run", side_effect=fake_run):+ family, path, answered = emoji_mod._emoji_color_font()+ self.assertEqual((family, path, answered), ("Noto Color Emoji", str(real), True))++ def test_libass_colour_probe_escapes_a_colon_in_the_srt_path(self):+ """A Windows temp path is `C:/...`. `subtitles=C:/...` is split at the colon and the+ probe reports colour emoji unknown. The escaped form opens the file."""+ from _common import emoji as emoji_mod+ colon = OUT / "C:probe"+ colon.mkdir(exist_ok=True)+ srt = colon / "e.srt"+ srt.write_text("1\n00:00:00,000 --> 00:00:01,000\nHi\n", encoding="utf-8")+ bare = "subtitles=" + str(srt).replace("\\", "/")+ escaped = "subtitles=" + escape_filter_path(str(srt), bind=False)+ self.assertNotEqual(bare, escaped)+ bad = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi",+ "-i", "color=c=black:s=64x64:d=0.04", "-vf", bare, "-frames:v", "1",+ "-f", "null", "-"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ self.assertNotEqual(bad.returncode, 0, "an unescaped colon must not parse as a subtitle path")+ good = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi",+ "-i", "color=c=black:s=64x64:d=0.04", "-vf", escaped, "-frames:v", "1",+ "-f", "null", "-"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ self.assertEqual(good.returncode, 0, good.stderr.decode(errors="replace")[-400:])++ class _Dir:+ def __enter__(self):+ return str(colon)+ def __exit__(self, *exc):+ return False++ captured = {}++ def fake_run(cmd, **kw):+ captured["cmd"] = cmd+ return subprocess.CompletedProcess(cmd, 1, b"", b"")++ with unittest.mock.patch("tempfile.TemporaryDirectory", return_value=_Dir()), \+ unittest.mock.patch.object(emoji_mod, "ffmpeg_exe", return_value=("ffmpeg",)), \+ unittest.mock.patch("subprocess.run", side_effect=fake_run):+ emoji_mod._libass_color_probe()+ vf = captured["cmd"][captured["cmd"].index("-vf") + 1]+ self.assertEqual(vf, "subtitles=" + escape_filter_path(str(colon / "e.srt"), bind=False))+def test_help_survives_a_legacy_console_encoding(self):"""--help contains non-ASCII (Japanese example, arrows); a cp1252 console must not raise UnicodeEncodeError."""env = dict(os.environ, PYTHONIOENCODING="cp1252")