diff --git a/src/clipwright/captions.py b/src/clipwright/captions.py index 692e440..a729de3 100644 --- a/src/clipwright/captions.py +++ b/src/clipwright/captions.py @@ -123,16 +123,17 @@ def hook_text(words: Sequence[Word], clip_start: float, clip_end: float) -> str return out or None -def build_ass(words: Sequence[Word], clip_start: float, clip_end: float, style: CaptionStyle = CaptionStyle(), - width: int = 1080, height: int = 1920, hold_gap: float = 0.6, hook: str | None = None) -> str: - """ASS document for the words inside [clip_start, clip_end], with times relative to the clip. - `hook` is a title shown at the top for the first HOOK_SECONDS.""" - inside = [w for w in words if w.end > clip_start and w.start < clip_end] +def _hook_size(style: CaptionStyle) -> int: + return round(style.size * 0.8) + + +def _ass_header(style: CaptionStyle, width: int, height: int) -> str: + """[Script Info], the Cap and Hook styles and the [Events] format line.""" border = 3 if style.box else 1 # 3 = opaque box behind the text, sized by the outline back = "&H50000000" if style.box else "&H64000000" outline_colour = "&H50000000" if style.box else "&H00000000" - hook_size = round(style.size * 0.8) - header = ( + hook_size = _hook_size(style) + return ( "[Script Info]\nScriptType: v4.00+\n" f"PlayResX: {width}\nPlayResY: {height}\nWrapStyle: 2\nScaledBorderAndShadow: yes\n\n" "[V4+ Styles]\n" @@ -146,12 +147,37 @@ def build_ass(words: Sequence[Word], clip_start: float, clip_end: float, style: f"{max(8, hook_size // 5)},0,8,60,60,{round(height * 0.09)},1\n\n" "[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n" ) + + +def _hook_lines(hook: str, style: CaptionStyle, width: int) -> str: + """The hook title as ASS text: wrapped to the frame width, at most three lines.""" + per_line = max(12, int((width - 160) / (_hook_size(style) * 0.6))) + return "\\N".join(_escape(line) for line in wrap(hook.strip(), per_line)[:3]) + + +def build_title_ass(hook: str, style: CaptionStyle = CaptionStyle(), width: int = 1080, + height: int = 1920) -> str | None: + """ASS document with only the hook title, for burning onto a cover frame: the same style and + place as the hook in the clip, but on screen the whole time and without the fade-in, so any + frame gets all of it. None for a blank title.""" + if not hook.strip(): + return None + end = _ts(10 * 3600 - 1) # the cover frame keeps its time in the clip, so cover all of it + text = _hook_lines(hook, style, width) + return _ass_header(style, width, height) + f"Dialogue: 1,{_ts(0)},{end},Hook,,0,0,0,,{text}\n" + + +def build_ass(words: Sequence[Word], clip_start: float, clip_end: float, style: CaptionStyle = CaptionStyle(), + width: int = 1080, height: int = 1920, hold_gap: float = 0.6, hook: str | None = None) -> str: + """ASS document for the words inside [clip_start, clip_end], with times relative to the clip. + `hook` is a title shown at the top for the first HOOK_SECONDS.""" + inside = [w for w in words if w.end > clip_start and w.start < clip_end] + header = _ass_header(style, width, height) hi = _ass_color(style.highlight) lines: list[str] = [] if hook and hook.strip(): - per_line = max(12, int((width - 160) / (hook_size * 0.6))) - text = "\\N".join(_escape(line) for line in wrap(hook.strip(), per_line)[:3]) until = min(HOOK_SECONDS, clip_end - clip_start) + text = _hook_lines(hook, style, width) lines.append(f"Dialogue: 1,{_ts(0)},{_ts(until)},Hook,,0,0,0,,{{\\fad(120,250)}}{text}") groups = group_words(inside, style.max_words, style.max_chars, max_gap=hold_gap) for g, group in enumerate(groups): diff --git a/src/clipwright/pipeline.py b/src/clipwright/pipeline.py index f758b24..9a3cdfe 100644 --- a/src/clipwright/pipeline.py +++ b/src/clipwright/pipeline.py @@ -287,7 +287,7 @@ def _render_one(info: MediaInfo, words: list[transcribe.Word], start: float, end cover = f"{base}{suffix}.jpg" thumb: str | None = cover try: - thumbnail.make_cover(out_dir / name, info, start, out_dir / cover, opts, keep, crop_x) + thumbnail.make_cover(out_dir / name, info, start, out_dir / cover, opts, keep, crop_x, title=hook) except (RuntimeError, OSError, ValueError, subprocess.CalledProcessError) as e: # a missing cover is no reason to throw away a finished clip. CalledProcessError's text is # the whole ffprobe command line, which says nothing a person can use diff --git a/src/clipwright/render.py b/src/clipwright/render.py index afccd56..2073ec0 100644 --- a/src/clipwright/render.py +++ b/src/clipwright/render.py @@ -3,13 +3,15 @@ from __future__ import annotations import functools +import hashlib import json import math +import os import re import shutil import subprocess from collections.abc import Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from pathlib import Path from typing import Literal @@ -262,9 +264,10 @@ def speaker_crop_x(info: MediaInfo, start: float, end: float, keep: jumpcut.Rang def cover_command(info: MediaInfo, at: float, out: Path, opts: RenderOptions, crop_x: str | None = None, - clip_time: float = 0.0, width: int = 720) -> list[str]: + clip_time: float = 0.0, width: int = 720, title_file: str | None = None) -> list[str]: """ffmpeg command that writes one frame of the source at `at` seconds as a JPEG, laid out like - the clip (same layout, aspect and crop) but without the captions. + the clip (same layout, aspect and crop) but without the captions. `title_file` is an ASS file + name (in ffmpeg's working folder) burned in at full frame size before the scale: the hook title. `crop_x` is the follow/speaker expression the clip was rendered with. It's a function of the clip's own timeline, so the frame is stamped with `clip_time` (where this frame sits in the @@ -273,16 +276,36 @@ def cover_command(info: MediaInfo, at: float, out: Path, opts: RenderOptions, cr graph = video_filter(opts.layout, None, info.fps, max(1, math.ceil(info.fps)), crop_x, frame_size(opts.aspect)) graph = graph.replace("[0:v]", f"[0:{info.video_stream}]setpts=PTS-STARTPTS+{clip_time:.3f}/TB,", 1) - graph += f";[vout]scale={width}:-2[cover]" + if title_file: + graph += f";[vout]ass={title_file}[titled];[titled]scale={width}:-2[cover]" + else: + graph += f";[vout]scale={width}:-2[cover]" return [require("ffmpeg"), "-v", "error", "-y", "-ss", f"{max(0.0, at):.3f}", "-i", str(info.path), "-filter_complex", graph, "-map", "[cover]", "-frames:v", "1", "-q:v", "3", str(out)] def render_cover(info: MediaInfo, at: float, out: Path, opts: RenderOptions, crop_x: str | None = None, - clip_time: float = 0.0, width: int = 720) -> None: - """Writes the caption-free cover frame (see cover_command). RuntimeError if ffmpeg fails.""" - proc = subprocess.run(cover_command(info, at, out, opts, crop_x, clip_time, width), - capture_output=True, text=True, errors="replace") + clip_time: float = 0.0, width: int = 720, title_ass: str | None = None) -> None: + """Writes the caption-free cover frame (see cover_command), with the ASS document `title_ass` + burned in when given. RuntimeError if ffmpeg fails.""" + if title_ass is None: + proc = subprocess.run(cover_command(info, at, out, opts, crop_x, clip_time, width), + capture_output=True, text=True, errors="replace") + else: + # same trick as render(): a safe bare name in ffmpeg's working folder, so the filter graph + # needs no path escaping. Next to the cover, which is a folder we can write to. + folder = out.resolve().parent + # unique per cover and process: covers of other clips (or another process's) can be made + # in the same folder at the same time + key = hashlib.sha1(f"{out.resolve()}|{os.getpid()}".encode()).hexdigest()[:16] + title = folder / f"_clipwright_cover_{key}.ass" + title.write_text(title_ass, encoding="utf-8") + try: + cmd = cover_command(replace(info, path=info.path.resolve()), at, out.resolve(), opts, crop_x, + clip_time, width, title_file=title.name) + proc = subprocess.run(cmd, capture_output=True, text=True, errors="replace", cwd=folder) + finally: + title.unlink(missing_ok=True) if proc.returncode != 0 or not out.is_file(): tail = "\n".join(proc.stderr.strip().splitlines()[-5:]) raise RuntimeError(f"couldn't render a cover frame from {info.path.name}:\n{tail}") diff --git a/src/clipwright/thumbnail.py b/src/clipwright/thumbnail.py index 51e10f2..90e5368 100644 --- a/src/clipwright/thumbnail.py +++ b/src/clipwright/thumbnail.py @@ -19,9 +19,10 @@ import numpy.typing as npt from . import audio, jumpcut +from .captions import STYLES, build_title_ass from .motion import read_motion from .probe import MediaInfo, probe, require -from .render import RenderOptions, render_cover +from .render import RenderOptions, frame_size, render_cover HOP = 0.1 # loudness resolution in seconds FPS = 10.0 # motion samples per second @@ -85,12 +86,18 @@ def make_thumbnail(clip: Path, out: Path) -> float: def make_cover(clip: Path, source: MediaInfo, start: float, out: Path, opts: RenderOptions, - keep: jumpcut.Ranges | None = None, crop_x: str | None = None) -> float: + keep: jumpcut.Ranges | None = None, crop_x: str | None = None, title: str | None = None) -> float: """Picks the cover time on the rendered clip and renders that frame from the source without captions. `start` is where the clip starts in the source, `keep` the jump-cut ranges it was - rendered with and `crop_x` the follow/speaker window (render() returns it). Returns the - clip time used.""" + rendered with and `crop_x` the follow/speaker window (render() returns it). `title` is the + clip's hook title, drawn where the clip shows it (the only text that belongs on a cover). + Returns the clip time used.""" t = clip_time(clip) at = start + (jumpcut.source_time(t, keep) if keep else t) - render_cover(source, at, out, opts, crop_x, clip_time=t) + title_ass = None + if title: + w, h = frame_size(opts.aspect) + style = STYLES.get(opts.caption_style, STYLES["bold"]).for_frame(w, h) + title_ass = build_title_ass(title, style, w, h) + render_cover(source, at, out, opts, crop_x, clip_time=t, title_ass=title_ass) return t diff --git a/tests/test_captions.py b/tests/test_captions.py index 0e7f633..4966658 100644 --- a/tests/test_captions.py +++ b/tests/test_captions.py @@ -72,3 +72,22 @@ def test_srt_breaks_long_lines(): words = [Word(i * 0.3, i * 0.3 + 0.25, "word") for i in range(20)] lines = [ln for ln in build_srt(words, 0.0, 10.0).splitlines() if ln.startswith("word")] assert len(lines) > 1 and all(len(ln) <= 42 for ln in lines) + + +def test_title_ass_is_the_hook_without_fade_or_end(): + from clipwright.captions import build_title_ass + + hook = "Nobody expected the last round to go like this, least of all the people playing it" + clip = build_ass([], 0.0, 30.0, hook=hook) + title = build_title_ass(hook) + assert title is not None + header, events = title.split("[Events]") + # same styles and frame as the clip's captions, so it lands exactly where the hook does + assert clip.startswith(header) + hook_line = next(line for line in clip.splitlines() if ",Hook," in line) + title_lines = [line for line in title.splitlines() if line.startswith("Dialogue:")] + assert len(title_lines) == 1 + assert title_lines[0].startswith("Dialogue: 1,0:00:00.00,9:59:59.00,Hook,") + assert "\fad" not in title_lines[0] + assert title_lines[0].split("Hook,,0,0,0,,", 1)[1] == hook_line.split("}", 1)[1] + assert build_title_ass(" ") is None diff --git a/tests/test_cover.py b/tests/test_cover.py index 1cd9a9c..6a78b8c 100644 --- a/tests/test_cover.py +++ b/tests/test_cover.py @@ -77,3 +77,66 @@ def fake_follow(*_args: object, **_kw: object) -> str: assert caption.any(), "the clip frame should have a caption on it" # everywhere else the cover is the clip's frame, give or take two encodes assert float(rows[~caption].mean()) < 4.0 + + +def test_cover_burns_the_title_at_full_size_before_scaling(): + cmd = cover_command(INFO, 5.0, Path("c.jpg"), RenderOptions(), title_file="_t.ass") + graph = cmd[cmd.index("-filter_complex") + 1] + # at the clip's frame size, like in the clip, then scaled down with the picture + assert graph.endswith(";[vout]ass=_t.ass[titled];[titled]scale=720:-2[cover]") + + +@pytest.mark.ffmpeg +@pytest.mark.skipif(not shutil.which("ffmpeg"), reason="needs ffmpeg") +def test_cover_title_matches_the_hook_in_the_clip(tmp_path: Path): + from clipwright.captions import build_title_ass + + src = tmp_path / "src.mp4" + make_video(src, duration=20) + info = probe(src) + opts = RenderOptions(layout="blur", encoder="libx264", normalize_audio=False) + hook = "This one move won the whole round" + (tmp_path / "c.ass").write_text(build_ass([], 10.0, 16.0, hook=hook), encoding="utf-8") + clip = tmp_path / "c.mp4" + render(info, 10.0, 16.0, clip, opts, "c.ass", workdir=tmp_path) + + grab(clip, 1.5, tmp_path / "from_clip.jpg") # inside HOOK_SECONDS, after the fade-in + title_ass = build_title_ass(hook) + # a relative source path and a cover in another folder: ffmpeg runs in the cover's folder + covers = tmp_path / "covers" + covers.mkdir() + with pytest.MonkeyPatch.context() as mp: + mp.chdir(tmp_path) + render_cover(probe(Path("src.mp4")), 11.5, Path("covers/titled.jpg"), opts, clip_time=1.5, + title_ass=title_ass) + render_cover(info, 11.5, covers / "clean.jpg", opts, clip_time=1.5) + assert sorted(p.name for p in covers.iterdir()) == ["clean.jpg", "titled.jpg"] # temp .ass removed + + clip_frame, titled, clean = (_gray(p) for p in (tmp_path / "from_clip.jpg", covers / "titled.jpg", + covers / "clean.jpg")) + title_rows = np.abs(titled - clean).mean(axis=1) > 12 + assert title_rows.any(), "the title should be on the cover" + assert title_rows[: len(title_rows) // 3].sum() > 20 # a few lines of text in the top third + assert not title_rows[len(title_rows) // 2:].any() # top of the frame only, like the hook + # and it's the clip's hook: same place and size, give or take two encodes + assert float(np.abs(titled - clip_frame).mean()) < 4.0 + + +def test_cover_title_temp_names_differ_per_clip(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + import clipwright.render as render_mod + + names: list[str] = [] + + def fake_run(cmd: list[str], **kw: object) -> subprocess.CompletedProcess[str]: + graph = cmd[cmd.index("-filter_complex") + 1] + name = graph.split("ass=", 1)[1].split("[", 1)[0] + assert (kw["cwd"] / name).is_file() # type: ignore[operator] + names.append(name) + Path(cmd[-1]).write_bytes(b"jpg") + return subprocess.CompletedProcess(cmd, 0, "", "") + + monkeypatch.setattr(render_mod.subprocess, "run", fake_run) + for stem in ("speech_clip01.tmp", "speech_clip02.tmp"): + render_cover(INFO, 1.0, tmp_path / f"{stem}.jpg", RenderOptions(), title_ass="x") + assert len(set(names)) == 2, names + assert not list(tmp_path.glob("*.ass")) diff --git a/tests/test_thumbnail.py b/tests/test_thumbnail.py index 8ca905d..9cb6836 100644 --- a/tests/test_thumbnail.py +++ b/tests/test_thumbnail.py @@ -55,10 +55,31 @@ def test_cover_time_is_mapped_through_the_jump_cuts(monkeypatch: pytest.MonkeyPa calls: list[tuple[float, str | None, float]] = [] monkeypatch.setattr(thumbnail, "clip_time", lambda _clip: 5.0) monkeypatch.setattr(thumbnail, "render_cover", - lambda _info, at, _out, _opts, crop_x, clip_time: calls.append((at, crop_x, clip_time))) + lambda _info, at, _out, _opts, crop_x, clip_time, title_ass=None: + calls.append((at, crop_x, clip_time))) info = MediaInfo(tmp_path / "src.mp4", 600, 1920, 1080, 30, True, video_stream=0) keep = [(0.0, 4.0), (6.0, 20.0)] # 2s pause cut at 4s, so 5.0 in the clip is 7.0 in the range t = thumbnail.make_cover(tmp_path / "c.mp4", info, 100.0, tmp_path / "c.jpg", RenderOptions(), keep, "x") thumbnail.make_cover(tmp_path / "c.mp4", info, 100.0, tmp_path / "c.jpg", RenderOptions()) assert t == 5.0 assert calls == [(107.0, "x", 5.0), (105.0, None, 5.0)] # clip clock stays 5.0 for the crop + + +def test_cover_gets_the_title_in_the_run_style_and_frame(monkeypatch: pytest.MonkeyPatch, tmp_path: Path): + from clipwright import thumbnail + from clipwright.probe import MediaInfo + from clipwright.render import RenderOptions + + sent: list[str | None] = [] + monkeypatch.setattr(thumbnail, "clip_time", lambda _clip: 2.0) + monkeypatch.setattr(thumbnail, "render_cover", + lambda *_a, title_ass=None, **_k: sent.append(title_ass)) + info = MediaInfo(tmp_path / "src.mp4", 600, 1920, 1080, 30, True, video_stream=0) + opts = RenderOptions(caption_style="clean", aspect="1:1") + thumbnail.make_cover(tmp_path / "c.mp4", info, 0.0, tmp_path / "c.jpg", opts, title="Wait for it") + thumbnail.make_cover(tmp_path / "c.mp4", info, 0.0, tmp_path / "c.jpg", opts) + thumbnail.make_cover(tmp_path / "c.mp4", info, 0.0, tmp_path / "c.jpg", opts, title=" ") + titled, clean, blank = sent + assert titled is not None and "Wait for it" in titled + assert "PlayResX: 1080\nPlayResY: 1080" in titled and "Style: Hook,Arial," in titled # 1:1, clean's font + assert clean is None and blank is None