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.

0.8.3: Context object, sync constants with rationale, trigger tests (#13)

Shogo Kajiyamaa88419610cb4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 822ba92..61b24c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## 0.8.3 — internals and triggering
+
+- `_common.py`: the shared flag state is an explicit `Context` object (`STATE.dry_run` etc., dict-style access kept), `run()` is split into recording, dry-run, captured and progress paths with one failure handler. Behaviour unchanged: 54/54 tests and the sync benchmark give identical numbers before and after.
+- `sync.py`: the 35 % minimum-overlap and the square-root overlap weight are named constants with the benchmark rationale (what 0.2 / 0.5 and exponents 0.25 / 1.0 did) written next to them.
+- Trigger tests (`evals/trigger/`): 10 should-trigger and 10 should-not requests judged by an independent model against a catalog with four decoy skills. 20/20 on this description.
+
## 0.8.2 — second agent-run evaluation
24 prompts (12 English edits, 8 Japanese edits, 4 that must be declined) run by independent agents against the 0.8.1 skill (`evals/agent_prompts_24.json`, `evals/grade_runs_24.py`, `evals/results/iteration-2.json`). Routing 24/24, honest refusals 4/4, Japanese reports 9/9, visual check whenever the picture changed 8/8, mean 6.5 commands per job.
diff --git a/evals/trigger/README.md b/evals/trigger/README.md
new file mode 100644
index 0000000..f1216b5
--- /dev/null
+++ b/evals/trigger/README.md
@@ -0,0 +1,7 @@
+# Trigger tests: should / should-not
+
+`prompts.json` holds 10 requests the skill must trigger on (English and Japanese, some without a file extension or the word "edit") and 10 near-miss requests it must not (still images, installing ffmpeg, downloading from YouTube, writing a script, an editor shortcut, thumbnail design, CSV to JSON, a codec explainer, AI video generation, meeting transcription).
+
+Method: show an independent model a skill catalog made of this skill's `description` plus four decoy skills that own the neighbouring territory (image-tools, web-research, copywriter, meeting-notes), give it the raw request, and ask which one skill it would load or `none`. A run is correct when ffmpeg-skill is chosen exactly for the should-trigger prompts.
+
+Results: `results-<date>.json`. 2026-09-04: 20/20.
diff --git a/evals/trigger/prompts.json b/evals/trigger/prompts.json
new file mode 100644
index 0000000..030226b
--- /dev/null
+++ b/evals/trigger/prompts.json
@@ -0,0 +1,122 @@
+[
+ {
+ "id": "t01",
+ "lang": "en",
+ "prompt": "Can you make this clip 60 seconds? /Users/me/Desktop/IMG_4412.MOV",
+ "should_trigger": true
+ },
+ {
+ "id": "t02",
+ "lang": "ja",
+ "prompt": "この動画、縦にしてインスタのリールに上げたい。字幕もつけて。",
+ "should_trigger": true
+ },
+ {
+ "id": "t03",
+ "lang": "en",
+ "prompt": "the audio on the interview is way too quiet compared to the intro, can you fix the levels in interview.mp4",
+ "should_trigger": true
+ },
+ {
+ "id": "t04",
+ "lang": "ja",
+ "prompt": "Zoom の録画(zoom_0.mp4)から無音の部分を全部カットしてほしい",
+ "should_trigger": true
+ },
+ {
+ "id": "t05",
+ "lang": "en",
+ "prompt": "I recorded with a Rode mic separately, sync mic.wav to camera.mov please",
+ "should_trigger": true
+ },
+ {
+ "id": "t06",
+ "lang": "ja",
+ "prompt": "iPhone で撮った HDR の動画が YouTube で白っぽく見える。直せる?",
+ "should_trigger": true
+ },
+ {
+ "id": "t07",
+ "lang": "en",
+ "prompt": "put our logo top right on all the videos in ./exports and add a fade at the end",
+ "should_trigger": true
+ },
+ {
+ "id": "t08",
+ "lang": "ja",
+ "prompt": "podcast_ep12.wav を -16 LUFS にして m4a で書き出して",
+ "should_trigger": true
+ },
+ {
+ "id": "t09",
+ "lang": "en",
+ "prompt": "Does this file meet TikTok's specs? final_v3.mp4",
+ "should_trigger": true
+ },
+ {
+ "id": "t10",
+ "lang": "ja",
+ "prompt": "2 台のカメラで撮った結婚式の動画、いいところだけ 3 分にまとめられる?",
+ "should_trigger": true
+ },
+ {
+ "id": "n01",
+ "lang": "en",
+ "prompt": "Resize this PNG logo to 512x512 and make the background transparent: logo.png",
+ "should_trigger": false
+ },
+ {
+ "id": "n02",
+ "lang": "ja",
+ "prompt": "Windows に ffmpeg をインストールする方法を教えて",
+ "should_trigger": false
+ },
+ {
+ "id": "n03",
+ "lang": "en",
+ "prompt": "Download this YouTube video for me: https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ "should_trigger": false
+ },
+ {
+ "id": "n04",
+ "lang": "ja",
+ "prompt": "新商品紹介動画の台本(60 秒)を書いて",
+ "should_trigger": false
+ },
+ {
+ "id": "n05",
+ "lang": "en",
+ "prompt": "What's the keyboard shortcut for ripple delete in Premiere Pro?",
+ "should_trigger": false
+ },
+ {
+ "id": "n06",
+ "lang": "en",
+ "prompt": "Design a YouTube thumbnail in Figma for my cooking channel",
+ "should_trigger": false
+ },
+ {
+ "id": "n07",
+ "lang": "ja",
+ "prompt": "このCSVをJSONに変換して: sales.csv",
+ "should_trigger": false
+ },
+ {
+ "id": "n08",
+ "lang": "en",
+ "prompt": "Explain the difference between H.264 and H.265 in simple terms",
+ "should_trigger": false
+ },
+ {
+ "id": "n09",
+ "lang": "en",
+ "prompt": "Generate a 10-second video of a cat surfing with AI",
+ "should_trigger": false
+ },
+ {
+ "id": "n10",
+ "lang": "ja",
+ "prompt": "会議の音声を文字起こしして議事録にまとめて(meeting.m4a)",
+ "should_trigger": false
+ }
+]
\ No newline at end of file
diff --git a/evals/trigger/results-2026-09-04.json b/evals/trigger/results-2026-09-04.json
new file mode 100644
index 0000000..b215d93
--- /dev/null
+++ b/evals/trigger/results-2026-09-04.json
@@ -0,0 +1,191 @@
+{
+ "date": "2026-09-04",
+ "method": "Skill catalog (ffmpeg-skill description + 4 decoy skills: image-tools, web-research, copywriter, meeting-notes) shown to an independent model with the raw user request; it names the one skill it would load or 'none'. Each prompt once.",
+ "results": [
+ {
+ "id": "t01",
+ "lang": "en",
+ "prompt": "Can you make this clip 60 seconds? /Users/me/Desktop/IMG_4412.MOV",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t02",
+ "lang": "ja",
+ "prompt": "この動画、縦にしてインスタのリールに上げたい。字幕もつけて。",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t03",
+ "lang": "en",
+ "prompt": "the audio on the interview is way too quiet compared to the intro, can you fix the levels in interview.mp4",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t04",
+ "lang": "ja",
+ "prompt": "Zoom の録画(zoom_0.mp4)から無音の部分を全部カットしてほしい",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t05",
+ "lang": "en",
+ "prompt": "I recorded with a Rode mic separately, sync mic.wav to camera.mov please",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t06",
+ "lang": "ja",
+ "prompt": "iPhone で撮った HDR の動画が YouTube で白っぽく見える。直せる?",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t07",
+ "lang": "en",
+ "prompt": "put our logo top right on all the videos in ./exports and add a fade at the end",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t08",
+ "lang": "ja",
+ "prompt": "podcast_ep12.wav を -16 LUFS にして m4a で書き出して",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t09",
+ "lang": "en",
+ "prompt": "Does this file meet TikTok's specs? final_v3.mp4",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "t10",
+ "lang": "ja",
+ "prompt": "2 台のカメラで撮った結婚式の動画、いいところだけ 3 分にまとめられる?",
+ "should_trigger": true,
+ "chosen": "ffmpeg-skill",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "n01",
+ "lang": "en",
+ "prompt": "Resize this PNG logo to 512x512 and make the background transparent: logo.png",
+ "should_trigger": false,
+ "chosen": "image-tools",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n02",
+ "lang": "ja",
+ "prompt": "Windows に ffmpeg をインストールする方法を教えて",
+ "should_trigger": false,
+ "chosen": "web-research",
+ "model": "haiku",
+ "correct": true
+ },
+ {
+ "id": "n03",
+ "lang": "en",
+ "prompt": "Download this YouTube video for me: https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ "should_trigger": false,
+ "chosen": "none",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n04",
+ "lang": "ja",
+ "prompt": "新商品紹介動画の台本(60 秒)を書いて",
+ "should_trigger": false,
+ "chosen": "copywriter",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n05",
+ "lang": "en",
+ "prompt": "What's the keyboard shortcut for ripple delete in Premiere Pro?",
+ "should_trigger": false,
+ "chosen": "none",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n06",
+ "lang": "en",
+ "prompt": "Design a YouTube thumbnail in Figma for my cooking channel",
+ "should_trigger": false,
+ "chosen": "none",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n07",
+ "lang": "ja",
+ "prompt": "このCSVをJSONに変換して: sales.csv",
+ "should_trigger": false,
+ "chosen": "none",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n08",
+ "lang": "en",
+ "prompt": "Explain the difference between H.264 and H.265 in simple terms",
+ "should_trigger": false,
+ "chosen": "none",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n09",
+ "lang": "en",
+ "prompt": "Generate a 10-second video of a cat surfing with AI",
+ "should_trigger": false,
+ "chosen": "none",
+ "model": "sonnet",
+ "correct": true
+ },
+ {
+ "id": "n10",
+ "lang": "ja",
+ "prompt": "会議の音声を文字起こしして議事録にまとめて(meeting.m4a)",
+ "should_trigger": false,
+ "chosen": "meeting-notes",
+ "model": "sonnet",
+ "correct": true
+ }
+ ],
+ "summary": {
+ "should_trigger": "10/10",
+ "should_not_trigger": "10/10",
+ "note": "Haiku judged 11 of the 20 (session rate limit hit on the rest); Sonnet judged 9. Five Sonnet runs refused when the prompt was delivered via a file and were re-run with the prompt inline. Reference decoys are hypothetical skill descriptions written for this test."
+ }
+}
\ No newline at end of file
diff --git a/package.json b/package.json
index f65556a..d2a362d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "ffmpeg-skill",
- "version": "0.8.2",
+ "version": "0.8.3",
"description": "Agent Skill that lets coding agents (Claude Code, Cursor, Codex) do professional video editing with local FFmpeg: MCP server, batch processing, declarative project rendering, brand kits, motion-graphics templates, HTML delivery reports, scene detection, delivery checks, cut, silence removal, transitions, multicam, captions, sync with drift correction, HDR to SDR, LUTs, audio clean-up and ducking, loudness, platform exports. No API keys, no cloud, no dependencies.",
"keywords": ["ffmpeg", "video", "agent-skill", "claude-code", "cursor", "codex", "skill", "video-editing"],
"license": "MIT",
diff --git a/scripts/_common.py b/scripts/_common.py
index fb154e2..97ba2ec 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -56,7 +56,46 @@ def require_tool(name: str) -> str:
X264_PRESETS = ("ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo")
-STATE: Dict[str, Any] = {"dry_run": False, "json": False, "commands": [], "progress": False, "fast": False, "duration_hint": None}
+
+
+class Context:
+ """Per-process settings that the shared flags (--dry-run, --json, --progress, --fast) set once.
+
+ Scripts read it as attributes (``STATE.dry_run``) or, for older call sites, like a dict
+ (``STATE["dry_run"]``). Keeping it a single explicit object rather than module globals makes
+ it obvious what run()/emit() depend on and lets tests reset it with ``STATE.reset()``.
+ """
+
+ __slots__ = ("dry_run", "json", "progress", "fast", "duration_hint", "commands")
+ _KEYS = ("dry_run", "json", "progress", "fast", "duration_hint", "commands")
+
+ def __init__(self) -> None:
+ self.reset()
+
+ def reset(self) -> None:
+ self.dry_run = False # print ffmpeg commands, run nothing (ffprobe still runs)
+ self.json = False # emit() prints a JSON document instead of the output path
+ self.progress = False # run() streams percent / ETA to stderr for ffmpeg
+ self.fast = False # x264 preset forced to veryfast
+ self.duration_hint: Optional[float] = None # expected output length, for the progress percent
+ self.commands: List[str] = [] # every ffmpeg command line, for --json and --dry-run
+
+ # mapping-style access kept for backwards compatibility
+ def __getitem__(self, key: str) -> Any:
+ if key not in self._KEYS:
+ raise KeyError(key)
+ return getattr(self, key)
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ if key not in self._KEYS:
+ raise KeyError(key)
+ setattr(self, key, value)
+
+ def get(self, key: str, default: Any = None) -> Any:
+ return getattr(self, key, default) if key in self._KEYS else default
+
+
+STATE = Context()
def add_common(ap: "argparse.ArgumentParser") -> None:
@@ -69,19 +108,19 @@ def add_common(ap: "argparse.ArgumentParser") -> None:
def apply_common(args: "argparse.Namespace") -> None:
- STATE["dry_run"] = bool(getattr(args, "dry_run", False))
- STATE["json"] = bool(getattr(args, "json", False))
- STATE["progress"] = bool(getattr(args, "progress", False))
- STATE["fast"] = bool(getattr(args, "fast", False))
- if STATE["fast"] and getattr(args, "preset", None) in X264_PRESETS:
+ STATE.dry_run = bool(getattr(args, "dry_run", False))
+ STATE.json = bool(getattr(args, "json", False))
+ STATE.progress = bool(getattr(args, "progress", False))
+ STATE.fast = bool(getattr(args, "fast", False))
+ if STATE.fast and getattr(args, "preset", None) in X264_PRESETS:
args.preset = "veryfast"
def emit(output: Optional[str], **extra: Any) -> None:
"""Final stdout line: the output path, or a JSON document with --json."""
- if STATE["json"]:
- doc: Dict[str, Any] = {"output": output, "dry_run": STATE["dry_run"], "commands": list(STATE["commands"])}
- if output and not STATE["dry_run"] and os.path.exists(output):
+ if STATE.json:
+ doc: Dict[str, Any] = {"output": output, "dry_run": STATE.dry_run, "commands": list(STATE.commands)}
+ if output and not STATE.dry_run and os.path.exists(output):
doc["probe"] = probe(output)
doc.update(extra)
print_json(doc)
@@ -89,32 +128,58 @@ def emit(output: Optional[str], **extra: Any) -> None:
print(output)
+def _cmdline(cmd: Sequence[str]) -> str:
+ return " ".join(shell_quote(c) for c in cmd)
+
+
+def _is_ffmpeg(cmd: Sequence[str]) -> bool:
+ return os.path.basename(cmd[0]).startswith("ffmpeg")
+
+
+def _fail(cmd: Sequence[str], returncode: int, stderr: str) -> None:
+ tail = "\n".join(stderr.strip().splitlines()[-15:])
+ die(f"command failed ({returncode}): {cmd[0]}\n{tail}", code=returncode or 1)
+
+
def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprocess.CompletedProcess:
"""Run a command, echoing it to stderr unless quiet. Exits on failure when check=True.
- With --dry-run, ffmpeg invocations are printed and skipped (ffprobe still runs so
- scripts can plan); a fake successful CompletedProcess is returned.
+ ffmpeg invocations are recorded in STATE.commands (for --json), skipped under --dry-run
+ (a fake successful CompletedProcess is returned so scripts can keep planning), and run
+ with a progress readout under --progress. ffprobe and other tools always run.
"""
- is_ffmpeg = os.path.basename(cmd[0]).startswith("ffmpeg")
+ is_ffmpeg = _is_ffmpeg(cmd)
if is_ffmpeg:
- STATE["commands"].append(" ".join(shell_quote(c) for c in cmd))
+ STATE.commands.append(_cmdline(cmd))
if not quiet:
- info(("[dry-run] $ " if STATE["dry_run"] and is_ffmpeg else "$ ") + " ".join(shell_quote(c) for c in cmd))
- if STATE["dry_run"] and is_ffmpeg:
+ info(("[dry-run] $ " if STATE.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd))
+ if STATE.dry_run and is_ffmpeg:
return subprocess.CompletedProcess(list(cmd), 0, "", "")
- if STATE["progress"] and is_ffmpeg and cmd[-1] != "-":
+ if STATE.progress and is_ffmpeg and cmd[-1] != "-":
return _run_with_progress(list(cmd), check)
+ return _run_captured(list(cmd), check)
+
+
+def _run_captured(cmd: List[str], check: bool) -> subprocess.CompletedProcess:
+ """Plain run with stdout/stderr captured."""
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if check and proc.returncode != 0:
- tail = "\n".join(proc.stderr.strip().splitlines()[-15:])
- die(f"command failed ({proc.returncode}): {cmd[0]}\n{tail}", code=proc.returncode or 1)
+ _fail(cmd, proc.returncode, proc.stderr)
return proc
+def _progress_line(done: float, total: float, elapsed: float) -> str:
+ if total > 0:
+ pct = min(99.9, done / total * 100)
+ eta = (elapsed / pct * (100 - pct)) if pct > 0.5 else 0
+ return f"\r {pct:5.1f}% {done:7.1f}s / {total:.1f}s ETA {eta:4.0f}s"
+ return f"\r {done:7.1f}s encoded"
+
+
def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProcess:
"""Run ffmpeg with -progress on a pipe and print percent/ETA to stderr."""
import time
- total = STATE.get("duration_hint") or 0.0
+ total = STATE.duration_hint or 0.0
full = cmd[:1] + ["-progress", "pipe:1", "-nostats"] + cmd[1:]
t0 = time.time()
proc = subprocess.Popen(full, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
@@ -126,13 +191,7 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
done = int(line.split("=")[1]) / 1_000_000
except ValueError:
continue
- if total > 0:
- pct = min(99.9, done / total * 100)
- elapsed = time.time() - t0
- eta = (elapsed / pct * (100 - pct)) if pct > 0.5 else 0
- msg = f"\r {pct:5.1f}% {done:7.1f}s / {total:.1f}s ETA {eta:4.0f}s"
- else:
- msg = f"\r {done:7.1f}s encoded"
+ msg = _progress_line(done, total, time.time() - t0)
if msg != last:
sys.stderr.write(msg)
sys.stderr.flush()
@@ -140,11 +199,9 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
_, err = proc.communicate()
if last:
sys.stderr.write("\r" + " " * len(last) + "\r")
- result = subprocess.CompletedProcess(full, proc.returncode, "", err)
if check and proc.returncode != 0:
- tail = "\n".join(err.strip().splitlines()[-15:])
- die(f"command failed ({proc.returncode}): {cmd[0]}\n{tail}", code=proc.returncode or 1)
- return result
+ _fail(cmd, proc.returncode, err)
+ return subprocess.CompletedProcess(full, proc.returncode, "", err)
def shell_quote(s: str) -> str:
diff --git a/scripts/sync.py b/scripts/sync.py
index 21380e5..10a3fc6 100755
--- a/scripts/sync.py
+++ b/scripts/sync.py
@@ -30,6 +30,22 @@ from _common import video_args, add_common, apply_common, emit, aac_args, audio_
SR = 8000 # decode sample rate
+# Scoring constants for coarse alignment. Both come from tests/bench_sync.py on real dialogue and
+# music with +/-30 s offsets, gain, noise and EQ (see evals/results and CHANGELOG 0.8.0):
+#
+# MIN_OVERLAP_FRACTION: lags whose overlap with the other track is shorter than this share of the
+# shorter track are never candidates. With the documented rule "analysis window >= 4x the largest
+# expected offset" a true offset keeps >= 75 % overlap, so 0.35 costs nothing there, while the
+# coincidental peaks on quasi-periodic material (music, tone beds) live below it. Raising it to
+# 0.5 started rejecting true 28 s offsets in 60 s windows; lowering it to 0.2 let the partial
+# matches back in (86 % -> 95 % of 60 s stress cases fixed by this alone).
+# OVERLAP_WEIGHT_EXP: normalised similarity is multiplied by (overlap fraction) ** exponent so a
+# perfect match over 55 % of the window cannot tie a perfect match over 100 %. 0.5 keeps a true
+# 75 % overlap at x0.87 and a 53 % one (28 s in 60 s) at x0.73 while a coincidental 40 % match
+# drops to x0.63; exponent 1.0 over-penalised large true offsets, 0.25 left exact ties.
+MIN_OVERLAP_FRACTION = 0.35
+OVERLAP_WEIGHT_EXP = 0.5
+
def decode_mono(path: str, seconds: float, start: float = 0.0) -> List[float]:
ffmpeg = require_tool("ffmpeg")
@@ -119,10 +135,7 @@ def cross_correlate(ref: List[float], other: List[float], max_lag: int):
lr, lo = len(ref), len(other)
max_lag = min(max_lag, n // 2 - 1)
best_lag, best_val, second = 0, -float("inf"), -float("inf")
- # ignore lags with less than 35 % overlap: with the documented rule (analysis window >= 4x the
- # largest expected offset) true offsets always keep >= 75 % overlap, while short-overlap lags are
- # where coincidental matches on quasi-periodic material (music, tone beds) live
- min_overlap = max(10, int(0.35 * min(lr, lo)))
+ min_overlap = max(10, int(MIN_OVERLAP_FRACTION * min(lr, lo))) # see constants above
scores = []
for lag in range(-max_lag, max_lag + 1):
# corr[lag] = sum_i ref[i] * other[i - lag] -> ref index range and other index range overlap:
@@ -135,10 +148,8 @@ def cross_correlate(ref: List[float], other: List[float], max_lag: int):
if denom <= 0:
continue
val = corr[lag % n].real / denom
- # mild preference for longer overlaps: a perfect match over 55 % of the window must not tie
- # with a perfect match over 100 % (quasi-periodic material). Exponent 0.5: with the window rule (>= 4x offset) a true match keeps >= 75 % overlap (x0.87) while a coincidental 55 % match drops to x0.74; keeps large true
- # offsets (28 s in 60 s = 53 % overlap -> x0.94) competitive while still breaking exact ties.
- val *= ((r1 - r0) / min(lr, lo)) ** 0.5
+ val *= ((r1 - r0) / min(lr, lo)) ** OVERLAP_WEIGHT_EXP # longer overlap wins ties
+
scores.append((val, lag))
if val > best_val:
second = best_val
diff --git a/tests/test_all.py b/tests/test_all.py
index 7ee64b2..252c743 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -810,6 +810,22 @@ class FFmpegSkillTests(unittest.TestCase):
proc = script("loudness.py", silent, "-o", OUT / "silent_norm.mp4", expect_fail=True)
self.assertIn("silent", proc.stderr)
+ # ---------------------------------------------------------------- _common
+ def test_context_attribute_and_mapping_access_agree(self):
+ from _common import Context
+ ctx = Context()
+ ctx["dry_run"] = True
+ self.assertTrue(ctx.dry_run)
+ ctx.fast = True
+ self.assertTrue(ctx["fast"])
+ self.assertIsNone(ctx.get("duration_hint"))
+ self.assertIsNone(ctx.get("nonexistent"))
+ with self.assertRaises(KeyError):
+ ctx["nonexistent"] = 1
+ ctx.commands.append("x")
+ ctx.reset()
+ self.assertEqual((ctx.dry_run, ctx.fast, ctx.commands), (False, False, []))
+
# ---------------------------------------------------------------- help
def test_every_script_has_help(self):
for name in sorted(p.name for p in SCRIPTS.glob("*.py") if not p.name.startswith("_")):