ffmpeg-skill 0.8.2 → 0.8.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ffmpeg-skill",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "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.",
5
5
  "keywords": ["ffmpeg", "video", "agent-skill", "claude-code", "cursor", "codex", "skill", "video-editing"],
6
6
  "license": "MIT",
@@ -56,7 +56,46 @@ def require_tool(name: str) -> str:
56
56
 
57
57
 
58
58
  X264_PRESETS = ("ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo")
59
- STATE: Dict[str, Any] = {"dry_run": False, "json": False, "commands": [], "progress": False, "fast": False, "duration_hint": None}
59
+
60
+
61
+ class Context:
62
+ """Per-process settings that the shared flags (--dry-run, --json, --progress, --fast) set once.
63
+
64
+ Scripts read it as attributes (``STATE.dry_run``) or, for older call sites, like a dict
65
+ (``STATE["dry_run"]``). Keeping it a single explicit object rather than module globals makes
66
+ it obvious what run()/emit() depend on and lets tests reset it with ``STATE.reset()``.
67
+ """
68
+
69
+ __slots__ = ("dry_run", "json", "progress", "fast", "duration_hint", "commands")
70
+ _KEYS = ("dry_run", "json", "progress", "fast", "duration_hint", "commands")
71
+
72
+ def __init__(self) -> None:
73
+ self.reset()
74
+
75
+ def reset(self) -> None:
76
+ self.dry_run = False # print ffmpeg commands, run nothing (ffprobe still runs)
77
+ self.json = False # emit() prints a JSON document instead of the output path
78
+ self.progress = False # run() streams percent / ETA to stderr for ffmpeg
79
+ self.fast = False # x264 preset forced to veryfast
80
+ self.duration_hint: Optional[float] = None # expected output length, for the progress percent
81
+ self.commands: List[str] = [] # every ffmpeg command line, for --json and --dry-run
82
+
83
+ # mapping-style access kept for backwards compatibility
84
+ def __getitem__(self, key: str) -> Any:
85
+ if key not in self._KEYS:
86
+ raise KeyError(key)
87
+ return getattr(self, key)
88
+
89
+ def __setitem__(self, key: str, value: Any) -> None:
90
+ if key not in self._KEYS:
91
+ raise KeyError(key)
92
+ setattr(self, key, value)
93
+
94
+ def get(self, key: str, default: Any = None) -> Any:
95
+ return getattr(self, key, default) if key in self._KEYS else default
96
+
97
+
98
+ STATE = Context()
60
99
 
61
100
 
62
101
  def add_common(ap: "argparse.ArgumentParser") -> None:
@@ -69,19 +108,19 @@ def add_common(ap: "argparse.ArgumentParser") -> None:
69
108
 
70
109
 
71
110
  def apply_common(args: "argparse.Namespace") -> None:
72
- STATE["dry_run"] = bool(getattr(args, "dry_run", False))
73
- STATE["json"] = bool(getattr(args, "json", False))
74
- STATE["progress"] = bool(getattr(args, "progress", False))
75
- STATE["fast"] = bool(getattr(args, "fast", False))
76
- if STATE["fast"] and getattr(args, "preset", None) in X264_PRESETS:
111
+ STATE.dry_run = bool(getattr(args, "dry_run", False))
112
+ STATE.json = bool(getattr(args, "json", False))
113
+ STATE.progress = bool(getattr(args, "progress", False))
114
+ STATE.fast = bool(getattr(args, "fast", False))
115
+ if STATE.fast and getattr(args, "preset", None) in X264_PRESETS:
77
116
  args.preset = "veryfast"
78
117
 
79
118
 
80
119
  def emit(output: Optional[str], **extra: Any) -> None:
81
120
  """Final stdout line: the output path, or a JSON document with --json."""
82
- if STATE["json"]:
83
- doc: Dict[str, Any] = {"output": output, "dry_run": STATE["dry_run"], "commands": list(STATE["commands"])}
84
- if output and not STATE["dry_run"] and os.path.exists(output):
121
+ if STATE.json:
122
+ doc: Dict[str, Any] = {"output": output, "dry_run": STATE.dry_run, "commands": list(STATE.commands)}
123
+ if output and not STATE.dry_run and os.path.exists(output):
85
124
  doc["probe"] = probe(output)
86
125
  doc.update(extra)
87
126
  print_json(doc)
@@ -89,32 +128,58 @@ def emit(output: Optional[str], **extra: Any) -> None:
89
128
  print(output)
90
129
 
91
130
 
131
+ def _cmdline(cmd: Sequence[str]) -> str:
132
+ return " ".join(shell_quote(c) for c in cmd)
133
+
134
+
135
+ def _is_ffmpeg(cmd: Sequence[str]) -> bool:
136
+ return os.path.basename(cmd[0]).startswith("ffmpeg")
137
+
138
+
139
+ def _fail(cmd: Sequence[str], returncode: int, stderr: str) -> None:
140
+ tail = "\n".join(stderr.strip().splitlines()[-15:])
141
+ die(f"command failed ({returncode}): {cmd[0]}\n{tail}", code=returncode or 1)
142
+
143
+
92
144
  def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True) -> subprocess.CompletedProcess:
93
145
  """Run a command, echoing it to stderr unless quiet. Exits on failure when check=True.
94
146
 
95
- With --dry-run, ffmpeg invocations are printed and skipped (ffprobe still runs so
96
- scripts can plan); a fake successful CompletedProcess is returned.
147
+ ffmpeg invocations are recorded in STATE.commands (for --json), skipped under --dry-run
148
+ (a fake successful CompletedProcess is returned so scripts can keep planning), and run
149
+ with a progress readout under --progress. ffprobe and other tools always run.
97
150
  """
98
- is_ffmpeg = os.path.basename(cmd[0]).startswith("ffmpeg")
151
+ is_ffmpeg = _is_ffmpeg(cmd)
99
152
  if is_ffmpeg:
100
- STATE["commands"].append(" ".join(shell_quote(c) for c in cmd))
153
+ STATE.commands.append(_cmdline(cmd))
101
154
  if not quiet:
102
- info(("[dry-run] $ " if STATE["dry_run"] and is_ffmpeg else "$ ") + " ".join(shell_quote(c) for c in cmd))
103
- if STATE["dry_run"] and is_ffmpeg:
155
+ info(("[dry-run] $ " if STATE.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd))
156
+ if STATE.dry_run and is_ffmpeg:
104
157
  return subprocess.CompletedProcess(list(cmd), 0, "", "")
105
- if STATE["progress"] and is_ffmpeg and cmd[-1] != "-":
158
+ if STATE.progress and is_ffmpeg and cmd[-1] != "-":
106
159
  return _run_with_progress(list(cmd), check)
160
+ return _run_captured(list(cmd), check)
161
+
162
+
163
+ def _run_captured(cmd: List[str], check: bool) -> subprocess.CompletedProcess:
164
+ """Plain run with stdout/stderr captured."""
107
165
  proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
108
166
  if check and proc.returncode != 0:
109
- tail = "\n".join(proc.stderr.strip().splitlines()[-15:])
110
- die(f"command failed ({proc.returncode}): {cmd[0]}\n{tail}", code=proc.returncode or 1)
167
+ _fail(cmd, proc.returncode, proc.stderr)
111
168
  return proc
112
169
 
113
170
 
171
+ def _progress_line(done: float, total: float, elapsed: float) -> str:
172
+ if total > 0:
173
+ pct = min(99.9, done / total * 100)
174
+ eta = (elapsed / pct * (100 - pct)) if pct > 0.5 else 0
175
+ return f"\r {pct:5.1f}% {done:7.1f}s / {total:.1f}s ETA {eta:4.0f}s"
176
+ return f"\r {done:7.1f}s encoded"
177
+
178
+
114
179
  def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProcess:
115
180
  """Run ffmpeg with -progress on a pipe and print percent/ETA to stderr."""
116
181
  import time
117
- total = STATE.get("duration_hint") or 0.0
182
+ total = STATE.duration_hint or 0.0
118
183
  full = cmd[:1] + ["-progress", "pipe:1", "-nostats"] + cmd[1:]
119
184
  t0 = time.time()
120
185
  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
126
191
  done = int(line.split("=")[1]) / 1_000_000
127
192
  except ValueError:
128
193
  continue
129
- if total > 0:
130
- pct = min(99.9, done / total * 100)
131
- elapsed = time.time() - t0
132
- eta = (elapsed / pct * (100 - pct)) if pct > 0.5 else 0
133
- msg = f"\r {pct:5.1f}% {done:7.1f}s / {total:.1f}s ETA {eta:4.0f}s"
134
- else:
135
- msg = f"\r {done:7.1f}s encoded"
194
+ msg = _progress_line(done, total, time.time() - t0)
136
195
  if msg != last:
137
196
  sys.stderr.write(msg)
138
197
  sys.stderr.flush()
@@ -140,11 +199,9 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProce
140
199
  _, err = proc.communicate()
141
200
  if last:
142
201
  sys.stderr.write("\r" + " " * len(last) + "\r")
143
- result = subprocess.CompletedProcess(full, proc.returncode, "", err)
144
202
  if check and proc.returncode != 0:
145
- tail = "\n".join(err.strip().splitlines()[-15:])
146
- die(f"command failed ({proc.returncode}): {cmd[0]}\n{tail}", code=proc.returncode or 1)
147
- return result
203
+ _fail(cmd, proc.returncode, err)
204
+ return subprocess.CompletedProcess(full, proc.returncode, "", err)
148
205
 
149
206
 
150
207
  def shell_quote(s: str) -> str:
package/scripts/sync.py CHANGED
@@ -30,6 +30,22 @@ from _common import video_args, add_common, apply_common, emit, aac_args, audio_
30
30
 
31
31
  SR = 8000 # decode sample rate
32
32
 
33
+ # Scoring constants for coarse alignment. Both come from tests/bench_sync.py on real dialogue and
34
+ # music with +/-30 s offsets, gain, noise and EQ (see evals/results and CHANGELOG 0.8.0):
35
+ #
36
+ # MIN_OVERLAP_FRACTION: lags whose overlap with the other track is shorter than this share of the
37
+ # shorter track are never candidates. With the documented rule "analysis window >= 4x the largest
38
+ # expected offset" a true offset keeps >= 75 % overlap, so 0.35 costs nothing there, while the
39
+ # coincidental peaks on quasi-periodic material (music, tone beds) live below it. Raising it to
40
+ # 0.5 started rejecting true 28 s offsets in 60 s windows; lowering it to 0.2 let the partial
41
+ # matches back in (86 % -> 95 % of 60 s stress cases fixed by this alone).
42
+ # OVERLAP_WEIGHT_EXP: normalised similarity is multiplied by (overlap fraction) ** exponent so a
43
+ # perfect match over 55 % of the window cannot tie a perfect match over 100 %. 0.5 keeps a true
44
+ # 75 % overlap at x0.87 and a 53 % one (28 s in 60 s) at x0.73 while a coincidental 40 % match
45
+ # drops to x0.63; exponent 1.0 over-penalised large true offsets, 0.25 left exact ties.
46
+ MIN_OVERLAP_FRACTION = 0.35
47
+ OVERLAP_WEIGHT_EXP = 0.5
48
+
33
49
 
34
50
  def decode_mono(path: str, seconds: float, start: float = 0.0) -> List[float]:
35
51
  ffmpeg = require_tool("ffmpeg")
@@ -119,10 +135,7 @@ def cross_correlate(ref: List[float], other: List[float], max_lag: int):
119
135
  lr, lo = len(ref), len(other)
120
136
  max_lag = min(max_lag, n // 2 - 1)
121
137
  best_lag, best_val, second = 0, -float("inf"), -float("inf")
122
- # ignore lags with less than 35 % overlap: with the documented rule (analysis window >= 4x the
123
- # largest expected offset) true offsets always keep >= 75 % overlap, while short-overlap lags are
124
- # where coincidental matches on quasi-periodic material (music, tone beds) live
125
- min_overlap = max(10, int(0.35 * min(lr, lo)))
138
+ min_overlap = max(10, int(MIN_OVERLAP_FRACTION * min(lr, lo))) # see constants above
126
139
  scores = []
127
140
  for lag in range(-max_lag, max_lag + 1):
128
141
  # 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):
135
148
  if denom <= 0:
136
149
  continue
137
150
  val = corr[lag % n].real / denom
138
- # mild preference for longer overlaps: a perfect match over 55 % of the window must not tie
139
- # 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
140
- # offsets (28 s in 60 s = 53 % overlap -> x0.94) competitive while still breaking exact ties.
141
- val *= ((r1 - r0) / min(lr, lo)) ** 0.5
151
+ val *= ((r1 - r0) / min(lr, lo)) ** OVERLAP_WEIGHT_EXP # longer overlap wins ties
152
+
142
153
  scores.append((val, lag))
143
154
  if val > best_val:
144
155
  second = best_val