@auscera/cleoedits 0.0.0-stage → 0.1.0

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.
Files changed (230) hide show
  1. package/README.md +62 -2
  2. package/cli.mjs +149 -0
  3. package/lib/dependencies.mjs +384 -0
  4. package/lib/run.mjs +114 -0
  5. package/lib/workspace.mjs +167 -0
  6. package/package.json +240 -3
  7. package/workspace/.agents/skills/cleoedits/SKILL.md +29 -0
  8. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/audiogram.json +41 -0
  9. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/facebook.json +48 -0
  10. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/linkedin.json +48 -0
  11. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/podcast.json +23 -0
  12. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/reels.json +48 -0
  13. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/shorts.json +48 -0
  14. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/tiktok.json +48 -0
  15. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/x.json +48 -0
  16. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube-shorts.json +48 -0
  17. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube.json +48 -0
  18. package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/LICENSE-SimpleIcons +30 -0
  19. package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/logos.json +1 -0
  20. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Anton-Regular.ttf +0 -0
  21. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/ArchivoBlack-Regular.ttf +0 -0
  22. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/InstrumentSerif-Italic.ttf +0 -0
  23. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Inter.ttf +0 -0
  24. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/LICENSE-PermanentMarker.txt +202 -0
  25. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Montserrat.ttf +0 -0
  26. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Anton.txt +93 -0
  27. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-ArchivoBlack.txt +93 -0
  28. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-InstrumentSerif.txt +93 -0
  29. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Inter.txt +93 -0
  30. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Montserrat.txt +93 -0
  31. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-PlayfairDisplay.txt +93 -0
  32. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Poppins.txt +93 -0
  33. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-SpaceMono.txt +93 -0
  34. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PermanentMarker-Regular.ttf +0 -0
  35. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay-Italic.ttf +0 -0
  36. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay.ttf +0 -0
  37. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Black.ttf +0 -0
  38. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Bold.ttf +0 -0
  39. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-ExtraBold.ttf +0 -0
  40. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/SpaceMono-Bold.ttf +0 -0
  41. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-MediaPipe +218 -0
  42. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-YuNet +21 -0
  43. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/NOTICE.md +4 -0
  44. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/selfie_segmenter.tflite +0 -0
  45. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/yunet.onnx +0 -0
  46. package/workspace/.agents/skills/cleoedits/assets/video_styles/LICENSE +21 -0
  47. package/workspace/.agents/skills/cleoedits/assets/video_styles/audio-app-ui/STYLE.md +65 -0
  48. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/STYLE.md +53 -0
  49. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/index.html +328 -0
  50. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/studio.js +57 -0
  51. package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/STYLE.md +65 -0
  52. package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/index.html +575 -0
  53. package/workspace/.agents/skills/cleoedits/assets/video_styles/design-app-ui/STYLE.md +68 -0
  54. package/workspace/.agents/skills/cleoedits/assets/video_styles/editor-ui/STYLE.md +73 -0
  55. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/STYLE.md +54 -0
  56. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/index.html +189 -0
  57. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/studio.js +57 -0
  58. package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/STYLE.md +64 -0
  59. package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/index.html +620 -0
  60. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/STYLE.md +55 -0
  61. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/index.html +238 -0
  62. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/studio.js +57 -0
  63. package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/STYLE.md +66 -0
  64. package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/index.html +602 -0
  65. package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/STYLE.md +66 -0
  66. package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/index.html +777 -0
  67. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/STYLE.md +56 -0
  68. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/index.html +186 -0
  69. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/studio.js +57 -0
  70. package/workspace/.agents/skills/cleoedits/assets/video_styles/motion-app-ui/STYLE.md +68 -0
  71. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/STYLE.md +56 -0
  72. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/index.html +244 -0
  73. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/studio.js +57 -0
  74. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/STYLE.md +67 -0
  75. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/index.html +663 -0
  76. package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/STYLE.md +59 -0
  77. package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/index.html +395 -0
  78. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/STYLE.md +52 -0
  79. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/index.html +194 -0
  80. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/studio.js +57 -0
  81. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/STYLE.md +58 -0
  82. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/index.html +242 -0
  83. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/studio.js +57 -0
  84. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/STYLE.md +53 -0
  85. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/index.html +138 -0
  86. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/studio.js +57 -0
  87. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/STYLE.md +63 -0
  88. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/index.html +599 -0
  89. package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/STYLE.md +65 -0
  90. package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/index.html +1297 -0
  91. package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/STYLE.md +69 -0
  92. package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/index.html +674 -0
  93. package/workspace/.agents/skills/cleoedits/references/audio-clearervoice-elevenlabs.md +11 -0
  94. package/workspace/.agents/skills/cleoedits/references/ffmpeg-and-reels.md +15 -0
  95. package/workspace/.agents/skills/cleoedits/references/hyperframes-workflows.md +13 -0
  96. package/workspace/.agents/skills/cleoedits/references/kdenlive-cli-and-mcp.md +12 -0
  97. package/workspace/.agents/skills/cleoedits/references/motion-design-pipeline.md +7 -0
  98. package/workspace/.agents/skills/cleoedits/references/motion-taste-emil.md +5 -0
  99. package/workspace/.agents/skills/cleoedits/references/playwright-demo-capture.md +9 -0
  100. package/workspace/.agents/skills/cleoedits/references/remotion-workflows.md +13 -0
  101. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/LICENSE +21 -0
  102. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_ass_overlay.py +399 -0
  103. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/__init__.py +235 -0
  104. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/alpha.py +560 -0
  105. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/asr.py +1237 -0
  106. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/color.py +540 -0
  107. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/decision.py +2452 -0
  108. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/drawtext.py +290 -0
  109. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emit.py +1309 -0
  110. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emoji.py +518 -0
  111. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/fonts.py +875 -0
  112. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing.py +263 -0
  113. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing_edit.py +432 -0
  114. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/probe.py +1613 -0
  115. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/runner.py +3994 -0
  116. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/text.py +73 -0
  117. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/timeline.py +721 -0
  118. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/wrap.py +981 -0
  119. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_contract.py +2454 -0
  120. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_platforms.py +258 -0
  121. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.html +754 -0
  122. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.py +258 -0
  123. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_smartcut.py +450 -0
  124. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/audio.py +867 -0
  125. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/background.py +136 -0
  126. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/batch.py +1409 -0
  127. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/broll.py +282 -0
  128. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/caption.py +2207 -0
  129. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/check.py +815 -0
  130. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/color.py +695 -0
  131. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/crop.py +91 -0
  132. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cropdetect.py +214 -0
  133. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cut.py +2076 -0
  134. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/deinterlace.py +90 -0
  135. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/denoise.py +94 -0
  136. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/export.py +1033 -0
  137. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/fit.py +729 -0
  138. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/freeze.py +197 -0
  139. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/graphics.py +920 -0
  140. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/grid.py +235 -0
  141. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/insert.py +142 -0
  142. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/join.py +1083 -0
  143. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/look.py +475 -0
  144. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loop.py +395 -0
  145. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loudness.py +397 -0
  146. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/metadata.py +416 -0
  147. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/multicam.py +414 -0
  148. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/overlay.py +766 -0
  149. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/pad.py +121 -0
  150. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/probe.py +145 -0
  151. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/proxy.py +93 -0
  152. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/redact.py +162 -0
  153. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/render.py +2424 -0
  154. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/report.py +354 -0
  155. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/reverse.py +114 -0
  156. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/scenes.py +439 -0
  157. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sequence.py +285 -0
  158. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/silence.py +945 -0
  159. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/speedramp.py +193 -0
  160. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sphere.py +137 -0
  161. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/stabilize.py +141 -0
  162. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/straighten.py +120 -0
  163. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sync.py +500 -0
  164. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/verify.py +411 -0
  165. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/waveform.py +502 -0
  166. package/workspace/.agents/skills/cleoedits/scripts/kdenlive_builder.py +284 -0
  167. package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-claude-motion +21 -0
  168. package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-motion-design +21 -0
  169. package/workspace/.agents/skills/cleoedits/scripts/motion/_media.py +43 -0
  170. package/workspace/.agents/skills/cleoedits/scripts/motion/pacing_check.py +90 -0
  171. package/workspace/.agents/skills/cleoedits/scripts/motion/storyboard.py +77 -0
  172. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/LICENSE +26 -0
  173. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/fx.py +2717 -0
  174. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/logos.py +194 -0
  175. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/sfx.py +105 -0
  176. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/trim.py +99 -0
  177. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/words.py +60 -0
  178. package/workspace/.claude/commands/blender-3d.md +12 -0
  179. package/workspace/.claude/commands/business-short-form-reels.md +12 -0
  180. package/workspace/.claude/commands/color-grade.md +12 -0
  181. package/workspace/.claude/commands/cutout-grid-reel.md +12 -0
  182. package/workspace/.claude/commands/depth-ui-reel.md +12 -0
  183. package/workspace/.claude/commands/explainer-panel-reel.md +12 -0
  184. package/workspace/.claude/commands/freeze-frame.md +12 -0
  185. package/workspace/.claude/commands/glass-graph.md +12 -0
  186. package/workspace/.claude/commands/over-the-shoulder.md +12 -0
  187. package/workspace/.claude/commands/personal-short-form-reels.md +12 -0
  188. package/workspace/.claude/commands/ranking-format.md +12 -0
  189. package/workspace/.claude/commands/relight.md +12 -0
  190. package/workspace/.claude/commands/reverse-engineer.md +12 -0
  191. package/workspace/.claude/commands/text-behind.md +12 -0
  192. package/workspace/.claude/commands/tier-list.md +12 -0
  193. package/workspace/.claude-plugin/plugin.json +8 -0
  194. package/workspace/.npmignore +15 -0
  195. package/workspace/AGENTS.md +30 -0
  196. package/workspace/README.md +63 -0
  197. package/workspace/assets/fonts/TikTokSans-OFL.txt +93 -0
  198. package/workspace/assets/fonts/TikTokSans-Variable.ttf +0 -0
  199. package/workspace/assets/luts/clean_warm.cube +4917 -0
  200. package/workspace/assets/luts/golden_hour.cube +4917 -0
  201. package/workspace/assets/luts/moody_dark.cube +4917 -0
  202. package/workspace/assets/luts/teal_orange.cube +4917 -0
  203. package/workspace/assets/sfx/NOTICE.txt +1 -0
  204. package/workspace/assets/sfx/click.wav +0 -0
  205. package/workspace/assets/sfx/pop.wav +0 -0
  206. package/workspace/assets/sfx/riser.wav +0 -0
  207. package/workspace/assets/sfx/whoosh.wav +0 -0
  208. package/workspace/generators/hyperframes/index.html +39 -0
  209. package/workspace/generators/hyperframes/package.json +15 -0
  210. package/workspace/generators/hyperframes/pnpm-lock.yaml +1181 -0
  211. package/workspace/generators/hyperframes/pnpm-workspace.yaml +10 -0
  212. package/workspace/generators/remotion/eslint.config.mjs +3 -0
  213. package/workspace/generators/remotion/package.json +36 -0
  214. package/workspace/generators/remotion/pnpm-lock.yaml +4179 -0
  215. package/workspace/generators/remotion/pnpm-workspace.yaml +10 -0
  216. package/workspace/generators/remotion/remotion.config.ts +13 -0
  217. package/workspace/generators/remotion/src/Root.tsx +52 -0
  218. package/workspace/generators/remotion/src/index.css +1 -0
  219. package/workspace/generators/remotion/src/index.ts +4 -0
  220. package/workspace/generators/remotion/tsconfig.json +15 -0
  221. package/workspace/pipeline/scripts/_codec.py +28 -0
  222. package/workspace/pipeline/scripts/ai_media_api.py +109 -0
  223. package/workspace/pipeline/scripts/blender_render.py +166 -0
  224. package/workspace/pipeline/scripts/composite.py +49 -0
  225. package/workspace/pipeline/scripts/melt.sh +68 -0
  226. package/workspace/pipeline/scripts/normalize_audio.py +39 -0
  227. package/workspace/pipeline/scripts/person_matte.py +216 -0
  228. package/workspace/pipeline/scripts/record_demo.py +69 -0
  229. package/workspace/pipeline/scripts/whisper_cut.py +98 -0
  230. package/workspace-manifest.json +908 -0
@@ -0,0 +1,1409 @@
1
+ #!/usr/bin/env python3
2
+ """Apply the same recipe to every file in a folder, with a content-hash cache
3
+ so re-runs only process what changed. A recipe is a list of script steps;
4
+ {in} and {out} are substituted, and the output of one step feeds the next.
5
+
6
+ Recipe (batch.json):
7
+ {
8
+ "glob": "*.mp4",
9
+ "output_dir": "out",
10
+ "suffix": "_final",
11
+ "steps": [
12
+ ["silence.py", "{in}", "--threshold", "-38", "-o", "{out}"],
13
+ ["loudness.py", "{in}", "-o", "{out}"],
14
+ ["export.py", "{in}", "--preset", "youtube", "-o", "{out}"]
15
+ ]
16
+ }
17
+ or use a render project for every file: {"project": "project.json", "clip_key": 0}
18
+
19
+ Examples:
20
+ python3 batch.py ~/Footage --recipe batch.json
21
+ python3 batch.py ~/Footage --recipe batch.json --dry-run
22
+ python3 batch.py ~/Footage --recipe batch.json --force # ignore the cache
23
+ python3 batch.py ~/Footage --recipe batch.json --watch 30 # poll the folder every 30 s
24
+ """
25
+ import argparse
26
+ import difflib
27
+ import hashlib
28
+ import json
29
+ import os
30
+ import sys
31
+ import threading
32
+ import time
33
+ from pathlib import Path
34
+ from typing import Any, Dict, List, Optional
35
+
36
+ from _common import STATE, add_common, apply_common, child_args, die, emit, info, run_tool, MEDIA_EXT as _MEDIA_EXT
37
+ from _common.runner import (with_flags, HW_FORCED_ENV, OWNED_ENV, _OutputLock, add_hw_orchestrator_args, copy_to_sibling, env_hw, read_json,
38
+ owned_identity, stop_children)
39
+ from _common.emit import absorb_stage_hw, audit, note, record_skip, shown, steps_encoder_report, warn
40
+ from _common.decision import NO_DEFAULT_ENCODE_EXT, brand_asset_files, rebase_project_paths
41
+ from _common.runner import parse_json
42
+
43
+ HERE = Path(__file__).resolve().parent
44
+ MEDIA_EXT = {e for e in _MEDIA_EXT if e not in (".png", ".jpg", ".jpeg", ".webp")} # one list (_common); a batch walks media, not stills
45
+ # recipe steps name the script to run as plain, untrusted JSON -- run_step() joins it onto HERE
46
+ # with the `/` operator, which silently ignores the left side when the right side is itself an
47
+ # absolute path (Path("/scripts") / "/tmp/evil.py" == Path("/tmp/evil.py")), and does nothing to
48
+ # stop a "../" traversal either. Without this allowlist, a batch.json a caller didn't author
49
+ # themselves (from a template, a shared config, anywhere) could name any Python file on disk and
50
+ # have it executed with the caller's own privileges on every matching media file.
51
+ ALLOWED_STEP_SCRIPTS = {p.name for p in HERE.glob("*.py") if not p.name.startswith("_")}
52
+
53
+
54
+ def file_key(path: Path) -> str:
55
+ """A cheap change detector: the name, the size, the modification time in nanoseconds and the
56
+ first and last MiB. A rewrite of the middle of a file keeps its size and its ends, so the
57
+ modification time is what tells it apart: in whole seconds (up to 3.8.4) two writes within
58
+ one second shared a key, and the old output was served as cached. A file whose mtime is reset
59
+ to the earlier value (``touch -r``, a copy that preserves it) or a filesystem that keeps
60
+ whole seconds (FAT keeps two) still shares one; hashing every byte would cost a read of the
61
+ whole file per item per run (docs/design-decisions.md, "After 3.8.4")."""
62
+ st = path.stat()
63
+ h = hashlib.sha1(usedforsecurity=False) # a change detector, not a secret
64
+ h.update(f"{path.name}|{st.st_size}|{st.st_mtime_ns}".encode())
65
+ with open(path, "rb") as fh: # first and last MB: cheap and good enough to detect changes
66
+ h.update(fh.read(1 << 20))
67
+ if st.st_size > 2 << 20:
68
+ fh.seek(-(1 << 20), os.SEEK_END)
69
+ h.update(fh.read(1 << 20))
70
+ return h.hexdigest()
71
+
72
+
73
+ def side_input_file(value: str) -> Path:
74
+ """The file a side-input argument reads: the argument itself, or, when that is no file and it
75
+ ends in `:SUFFIX`, the part before the last colon when that is one (caption.py's
76
+ `--srt FILE:LANG`, which split_srt_lang() reads the same way). Keying the whole token hashed a
77
+ path that does not exist, so an edited subtitle file kept its key (#510 review)."""
78
+ path = Path(value)
79
+ try:
80
+ if path.is_file() or ":" not in value:
81
+ return path
82
+ head = Path(value.rpartition(":")[0])
83
+ return head if value.rpartition(":")[0] and head.is_file() else path
84
+ except OSError:
85
+ return path
86
+
87
+
88
+ def is_brand_value(step: List[Any], j: int) -> bool:
89
+ """Whether step[j] is the value of --brand (`--brand X` or `--brand=X`)."""
90
+ arg = str(step[j])
91
+ return arg.startswith("--brand=") or (j > 0 and str(step[j - 1]) == "--brand")
92
+
93
+
94
+ def key_brand_assets(h: Any, path: Path) -> None:
95
+ """Hash the logo and font file a brand file names into `h`: the brand file's own bytes do not
96
+ change when one of them is replaced under its name (#510 review; render.py's stage key and a
97
+ project recipe's key already cover them)."""
98
+ for key, asset in brand_asset_files(str(path)):
99
+ a = Path(asset)
100
+ try:
101
+ ident = file_key(a) if a.is_file() else "-"
102
+ except OSError:
103
+ ident = "-"
104
+ h.update(f"brand:{key}\0{asset}\0{ident}\0".encode())
105
+
106
+
107
+ def side_inputs_key(recipe: Dict[str, Any]) -> str:
108
+ """The files a recipe's steps name besides {in}/{out} (check.py --compare REF, a LUT, a logo),
109
+ keyed by their own content: editing or removing one is a change the cache must see, or a QC
110
+ pass is served its old verdict against a reference that changed or is gone (#428 review).
111
+ Read on every pass, so a --watch loop sees the edit too."""
112
+ h = hashlib.sha1(usedforsecurity=False)
113
+ for step in recipe.get("steps") or []:
114
+ for j, arg in enumerate(step) if isinstance(step, list) else []:
115
+ if j == 0 or not isinstance(arg, str) or "{" in arg:
116
+ continue
117
+ value = arg.split("=", 1)[1] if arg.startswith("-") and "=" in arg else arg
118
+ if value.startswith("-") or not value:
119
+ continue
120
+ path = side_input_file(value)
121
+ try:
122
+ if path.is_file():
123
+ h.update(f"{value}\0{file_key(path)}\0".encode())
124
+ if is_brand_value(step, j):
125
+ key_brand_assets(h, path)
126
+ continue
127
+ except OSError:
128
+ pass
129
+ h.update(f"{value}\0-\0".encode()) # absent now: different from when it existed
130
+ return h.hexdigest()[:8]
131
+
132
+
133
+ def item_side_inputs_key(recipe: Dict[str, Any], src: Path) -> "tuple[str, Optional[Dict[str, Any]]]":
134
+ """The side inputs a step names through a placeholder, for one item (#510): `--image {in}.png`
135
+ in the first step is a file beside this item's source, and editing it is a change the cache
136
+ must see as side_inputs_key() sees a literal path's. Returns (key part, None), "" when the
137
+ recipe names none, or ("", why) when one cannot be resolved before the item runs: a later
138
+ step's {in} is an intermediate that does not exist yet, so its file cannot be keyed, and the
139
+ item is not served from the cache at all."""
140
+ h = hashlib.sha1(usedforsecurity=False)
141
+ named = False
142
+ for i, step in enumerate(recipe.get("steps") or []):
143
+ for j, arg in enumerate(step) if isinstance(step, list) else []:
144
+ if j == 0 or not isinstance(arg, str) or "{in}" not in arg or "{out}" in arg:
145
+ continue # literal paths are side_inputs_key()'s; {out} names an output, not an input
146
+ value = arg.split("=", 1)[1] if arg.startswith("-") and "=" in arg else arg
147
+ if value == "{in}" or "{in}" not in value:
148
+ continue # the step's own input
149
+ if i > 0:
150
+ return "", {"reason": "side_input_unresolved", "step": i, "argument": arg,
151
+ "message": f"step {i} names {arg!r}, a file derived from an intermediate that does not "
152
+ "exist before the item runs, so the cache cannot key it; the item always runs"}
153
+ path = side_input_file(value.replace("{in}", str(src)))
154
+ named = True
155
+ try:
156
+ if path.is_file():
157
+ h.update(f"{path}\0{file_key(path)}\0".encode())
158
+ if is_brand_value(step, j):
159
+ key_brand_assets(h, path)
160
+ continue
161
+ except OSError:
162
+ pass
163
+ h.update(f"{path}\0-\0".encode())
164
+ return (h.hexdigest()[:8] if named else ""), None
165
+
166
+
167
+ def caseless_glob(pattern: str) -> str:
168
+ """`pattern` with every letter outside a [...] class matched in either case: "*.mp4" finds
169
+ GOPR0001.MP4, as it already did on macOS's and Windows' default filesystems, so a recipe means
170
+ the same files on every platform (A82: on Linux a camera folder was an empty batch). pathlib's
171
+ case_sensitive= needs Python 3.12; 3.10 is the floor."""
172
+ out: List[str] = []
173
+ in_class = False
174
+ first = -1 # index of the class's first member: a "]" there is a member, not the end ("[]a]", "[!]a]")
175
+ for i, ch in enumerate(pattern):
176
+ if in_class:
177
+ out.append(ch)
178
+ if ch == "]" and i > first:
179
+ in_class = False
180
+ elif ch == "[":
181
+ first = i + 2 if pattern[i + 1:i + 2] == "!" else i + 1
182
+ in_class = "]" in pattern[first + 1:] # an unclosed [ ("[!]x") is a literal character to fnmatch
183
+ out.append(ch if in_class else "[[]")
184
+ elif ch.isalpha() and ch.lower() != ch.upper():
185
+ out.append(f"[{ch.lower()}{ch.upper()}]")
186
+ else:
187
+ out.append(ch)
188
+ return "".join(out)
189
+
190
+
191
+ def recipe_key(recipe: Dict[str, Any]) -> str:
192
+ # A "project" recipe is just {"project": "<path>", "clip_key": N} -- the actual settings
193
+ # (export preset, captions, everything) live in the file at that path, not in this dict.
194
+ # Hashing only `recipe` meant editing project.json's content (without touching batch.json
195
+ # itself) left the key, and so every cache hit, unchanged: a preset swapped from "copy" to
196
+ # "x" (a real re-encode) still served the old cached output. Fold the referenced file's own
197
+ # content into the key so a content change invalidates the cache like any other edit would.
198
+ # main() calls this on every pass, so a --watch loop sees an edit made while it runs (A81).
199
+ project_content = ""
200
+ if recipe.get("project"):
201
+ try:
202
+ project_content = Path(recipe["project"]).read_text(encoding="utf-8")
203
+ except (OSError, UnicodeDecodeError) as exc:
204
+ # keyed on the recipe alone: an unreadable project cannot invalidate the cache by its
205
+ # content, so say so (each item that needs it then fails on reading it); once per run
206
+ entry = {"code": "recipe_project_unreadable", "path": str(recipe["project"])}
207
+ if not any(all(w.get(k) == v for k, v in entry.items()) for w in STATE.warnings if isinstance(w, dict)):
208
+ warn(f"recipe.project {recipe['project']} could not be read ({exc}); the cache key covers the recipe only",
209
+ "recipe_project_unreadable", path=str(recipe["project"]), error=str(exc))
210
+ else:
211
+ project_content += "\0" + project_files_key(recipe, project_content)
212
+ return hashlib.sha1((json.dumps(recipe, sort_keys=True) + "\0" + project_content).encode(), usedforsecurity=False).hexdigest()[:12]
213
+
214
+
215
+ def project_files_key(recipe: Dict[str, Any], text: str) -> str:
216
+ """The files a project recipe's project names (music, cues, the brand and its logo and font,
217
+ overlay images and videos, the chapters file, every clip but the one each item replaces),
218
+ each keyed by its own content as file_key() keys a source (A80): an edited cue file or music
219
+ bed changes the output, so it has to change the key. The list is render.py's own
220
+ project_input_files(), read against the project file's directory as render reads it. A
221
+ project that does not parse adds nothing: each item then fails reading it."""
222
+ try:
223
+ proj = parse_json(text)
224
+ except ValueError:
225
+ return ""
226
+ if not isinstance(proj, dict):
227
+ return ""
228
+ from render import project_input_files # here, not at the top: render.py imports this module
229
+ base = Path(str(recipe["project"])).resolve().parent
230
+ clips = proj.get("clips")
231
+ idx = int(recipe.get("clip_key") or 0) # check_recipe_types() has refused anything else
232
+ if isinstance(clips, list) and idx < len(clips) and isinstance(clips[idx], dict):
233
+ # the clip every item replaces with itself: its placeholder is no input of any item
234
+ proj = dict(proj, clips=[dict(c, src=None) if i == idx else c for i, c in enumerate(clips)])
235
+
236
+ def rel(p: Any) -> str:
237
+ return str(p) if os.path.isabs(str(p)) else str(base / str(p))
238
+ h = hashlib.sha1(usedforsecurity=False)
239
+ for name in sorted(set(project_input_files(proj, rel))):
240
+ path = Path(name)
241
+ try:
242
+ ident = file_key(path) if path.is_file() else "-"
243
+ except OSError:
244
+ ident = "-"
245
+ h.update(f"{name}\0{ident}\0".encode())
246
+ return h.hexdigest()
247
+
248
+
249
+ def gpu_key() -> str:
250
+ """The GPU setting the steps resolve, as a suffix for the item cache key: a VideoToolbox file is
251
+ not the CPU's bytes, so a --hw output is never served to a --no-hw run or the other way round
252
+ (render.py's cache_key folds the same two variables in). Read after apply_common(), which has
253
+ exported --hw/--no-hw to the steps. '' when every step encodes on the CPU -- no flag and no
254
+ $FFMPEG_SKILL_HW, or --no-hw -- so the keys of a cache written before --hw existed still hit."""
255
+ if not env_hw():
256
+ return ""
257
+ # the variable alone leaves export.py's delivery presets on the CPU; --hw puts them on the GPU
258
+ return ":hw" if os.environ.get(HW_FORCED_ENV) == "1" else ":hw-env"
259
+
260
+
261
+ JOBS_CAP = 8 # beyond this, concurrent encodes contend for the same cores and memory
262
+
263
+ _LOG = threading.local()
264
+ # source -> {real path -> owned_identity()} of every file this process delivered for that item (a
265
+ # --watch loop's earlier passes): its final output and every side file its steps were allowed to
266
+ # write (an .srt beside the video). An existing path that is still exactly that file is the item's
267
+ # own, not someone else's, so a later pass of the SAME item replaces it (design-decisions: "A path
268
+ # this same run wrote ... is never someone else's file"); the permission is per item and per path,
269
+ # and is checked again where the write happens -- by deliver() under the output lock, by a step at
270
+ # its own output check (runner.OWNED_ENV). A file edited or replaced since, one an earlier run
271
+ # left, or one another item delivered (two items naming one side file) is still refused.
272
+ _OWN_OUTPUTS: Dict[str, Dict[str, Dict[str, int]]] = {}
273
+ _OWN_LOCK = threading.Lock()
274
+ # source -> (final path, its owned_identity() before the last step started), while that step runs
275
+ _WATCHED: Dict[str, Any] = {}
276
+ # set by batch.py's signal handler: a --jobs worker between two steps must not start the next one
277
+ _STOP = threading.Event()
278
+
279
+
280
+ def log(message: str) -> None:
281
+ """info(), unless this thread is a --jobs worker -- then the line is buffered and flushed in
282
+ file order when the item finishes, so a parallel run's log reads exactly like a serial one."""
283
+ buf = getattr(_LOG, "buffer", None)
284
+ if buf is None:
285
+ info(message)
286
+ else:
287
+ buf.append(message)
288
+
289
+
290
+ class ItemError(Exception):
291
+ """An item that cannot be processed, with the structured `error` its results row carries.
292
+ process() raises it instead of die(): die() inside an item printed a second JSON document
293
+ and left the row with error "1" (str(SystemExit))."""
294
+
295
+ def __init__(self, error: Dict[str, Any]) -> None:
296
+ super().__init__(error.get("message"))
297
+ self.error = error
298
+
299
+
300
+ def step_error(index: Optional[int], tool: Optional[str], doc: Any) -> Dict[str, Any]:
301
+ """A failed step's own failure, for its item's row: {step, tool, kind, message, code, reason,
302
+ details, hint, exit_code} from the step's --json document (keys it did not report are left
303
+ out; step and tool are always there)."""
304
+ err = doc.get("error") if isinstance(doc, dict) and isinstance(doc.get("error"), dict) else {}
305
+ out: Dict[str, Any] = {"step": index, "tool": tool}
306
+ for k in ("kind", "message", "code", "reason", "details", "hint"):
307
+ if err.get(k) is not None:
308
+ out[k] = err[k]
309
+ if isinstance(doc, dict) and doc.get("exit_code") is not None:
310
+ out["exit_code"] = doc["exit_code"]
311
+ return out
312
+
313
+
314
+ def run_step(argv: List[str], per_call: "Optional[float]" = None,
315
+ owned: "Optional[Path]" = None) -> "tuple[bool, Optional[dict]]":
316
+ """Returns (ok, doc): doc is the step's own --json result document; a failed step that
317
+ printed none that parses gets one in the failure shape (error.reason step_output_unparsed,
318
+ the last stderr line as the message), so its row still says why. {in}/{out} are already resolved by the caller before argv reaches here, so forcing
319
+ --json on every step (harmless: no step reads another step's stdout, only its output path)
320
+ costs nothing and lets a caller like process() read back tool-specific fields, e.g. cut.py's
321
+ `reencoded`, without adding a bespoke flag per field it might someday want. `owned`: the
322
+ owned_config() file the step reads under runner.OWNED_ENV."""
323
+ script = argv[0]
324
+ if script not in ALLOWED_STEP_SCRIPTS:
325
+ # main() refuses such a recipe before any item runs; this stays as the last line of defence
326
+ raise ItemError({"step": None, "tool": script, "kind": "input", "reason": "step_script_not_allowed",
327
+ "message": f"recipe step names a script that isn't one of this skill's own tools: {script!r} "
328
+ "(must be a bare filename like 'silence.py', found in scripts/)"})
329
+ if _STOP.is_set():
330
+ return False, {"status": "failed", "exit_code": 130,
331
+ "error": {"kind": "interrupted", "message": f"interrupted before {script} started"}}
332
+ # before a bare `--` in the step, where argparse still reads them as options (#510 review)
333
+ cmd = [str(HERE / script)] + with_flags(argv[1:], child_args() + (["--json"] if "--json" not in argv[1:] else []))
334
+ log(" → " + " ".join(os.path.basename(c) if i < 1 else c for i, c in enumerate(cmd)))
335
+ env = dict(os.environ, **{OWNED_ENV: str(owned)}) if owned else None
336
+ proc = run_tool(cmd, per_call=per_call, env=env)
337
+ try:
338
+ doc = json.loads(proc.stdout)
339
+ except ValueError:
340
+ doc = None
341
+ if proc.returncode != 0:
342
+ log(" " + "\n ".join(proc.stderr.strip().splitlines()[-4:]))
343
+ if not isinstance(doc, dict):
344
+ doc = {"status": "failed", "exit_code": proc.returncode,
345
+ "error": {"reason": "step_output_unparsed",
346
+ "message": (proc.stderr.strip().splitlines() or [f"{script} exited {proc.returncode} and printed nothing"])[-1][:300]}}
347
+ return False, doc
348
+ for line in proc.stderr.splitlines():
349
+ if line.startswith("warning:"): # a step's deprecation notice is not swallowed by a success (review 9)
350
+ log(" " + line)
351
+ return True, doc
352
+
353
+
354
+ def _run_buffered(fn, *a):
355
+ """Run a worker and hand back (its result, the log lines it produced)."""
356
+ r = fn(*a)
357
+ return r, list(getattr(_LOG, "lines", None) or [])
358
+
359
+
360
+ def final_path(src: Path, recipe: Dict[str, Any], outdir: Path) -> Path:
361
+ suffix = recipe.get("suffix", "_out")
362
+ # By default final_ext falls back to each source's OWN extension, so files that only differ
363
+ # by extension don't collide -- but a recipe that fixes "ext" (e.g. converting a folder of
364
+ # mixed .mp4/.mov masters to one format) makes every source with the same stem land on the
365
+ # same final path, e.g. clip.mp4 and clip.mov both -> clip_out.mp4. process() has no collision
366
+ # detection of its own; see one_pass()'s pre-flight check, which uses this same computation
367
+ # to catch that before any file is actually processed (and the earlier one silently clobbered).
368
+ final_ext = recipe.get("ext") or src.suffix.lstrip(".") or "mp4"
369
+ if not recipe.get("ext") and src.suffix.lower() in NO_DEFAULT_ENCODE_EXT:
370
+ # the #415 default-name rule (default_output()): the steps re-encode to x264/AAC, which a
371
+ # WebM cannot hold, so every .webm item was refused output_container_codecs (A83). A
372
+ # recipe that keeps WebM (a stream copy, export.py --preset vp9-alpha) sets "ext".
373
+ final_ext = "mp4"
374
+ steps = recipe.get("steps") or []
375
+ if not recipe.get("ext") and not recipe.get("project") and steps and not step_writes(steps[-1]) and not writes_nothing(recipe):
376
+ # the last step writes nothing, so what is delivered is an intermediate: its name says its
377
+ # container (a .webm source's fit.py step writes MP4, which must not be named .webm)
378
+ final_ext = intermediate_ext(src)
379
+ return outdir / f"{src.stem}{suffix}.{final_ext}"
380
+
381
+
382
+ def intermediate_ext(src: Path) -> str:
383
+ """The extension of an item's intermediate step files: the source's own for an audio file,
384
+ else mp4 (the tools' encoders write x264/AAC, which .webm and friends do not take)."""
385
+ return src.suffix.lstrip(".") if src.suffix.lower() in (".wav", ".mp3", ".m4a", ".flac") else "mp4"
386
+
387
+
388
+ # the recipe keys the run reads as a string: a path, a glob, a file-name part
389
+ RECIPE_STRINGS = ("glob", "project", "output_dir", "suffix", "ext")
390
+ # every key a recipe may carry; anything else is refused, as render.py refuses a project's
391
+ RECIPE_KEYS = RECIPE_STRINGS + ("clip_key", "steps")
392
+
393
+
394
+ def check_recipe_types(recipe: Dict[str, Any]) -> None:
395
+ """Refuse a recipe value of the wrong JSON type before anything runs (A18): a number where a
396
+ path or glob goes, an absolute glob (pathlib refuses it), a step that is not a list. Each was
397
+ a traceback, or a failure of every item naming the step's first character."""
398
+ for key in recipe:
399
+ # A104: a misspelled key ("ouput_dir", "sufix", "globs") was not read, so the batch ran
400
+ # with that key's default: other files, another folder, another name
401
+ if key not in RECIPE_KEYS:
402
+ near = difflib.get_close_matches(str(key), RECIPE_KEYS, n=1, cutoff=0.6)
403
+ die(f"recipe: unknown key {key!r}" + (f" (did you mean {near[0]!r}?)" if near
404
+ else f" (valid keys: {', '.join(sorted(RECIPE_KEYS))})"), kind="input")
405
+ for key in RECIPE_STRINGS:
406
+ value = recipe.get(key)
407
+ if value is not None and not isinstance(value, str):
408
+ die(f'recipe "{key}" must be a string, got {type(value).__name__} {value!r:.60}', kind="input")
409
+ glob = recipe.get("glob")
410
+ if glob and (os.path.isabs(glob) or glob.startswith(("/", "\\"))):
411
+ die(f'recipe "glob" {glob!r} is an absolute path: it matches names inside the batch folder, e.g. "*.mp4" '
412
+ 'or "sub/*.mov"', kind="input")
413
+ key = recipe.get("clip_key")
414
+ try:
415
+ index = int(key) if key is not None and not isinstance(key, (bool, float)) else (0 if key is None else -1)
416
+ except (TypeError, ValueError):
417
+ index = -1
418
+ if index < 0:
419
+ die(f'recipe "clip_key" must be a clip index (0, 1, ...), got {key!r:.60}', kind="input")
420
+ steps = recipe.get("steps")
421
+ if steps is not None and not isinstance(steps, list):
422
+ die(f'recipe "steps" must be a list of steps, each ["script.py", args...], got {type(steps).__name__}',
423
+ kind="input")
424
+ for i, st in enumerate(steps or []):
425
+ if not isinstance(st, list) or not st:
426
+ die(f'recipe step {i} must be a list ["script.py", args...], got {type(st).__name__} {st!r:.60}',
427
+ kind="input")
428
+
429
+
430
+ STEP_WRITES_WITHOUT_OUT = "step_writes_without_out"
431
+
432
+
433
+ def names_output(step: Any) -> bool:
434
+ """Whether a step names where it writes itself (-o/--output with a path that is not {out}): a
435
+ side product the caller placed on purpose (look.py {in} -o {in}.png), not an implicit output."""
436
+ for tok in (step[1:] if isinstance(step, list) else []):
437
+ tok = str(tok)
438
+ if tok in ("-o", "--output") or tok.startswith("--output=") or (tok.startswith("-o") and not tok.startswith("--") and len(tok) > 2):
439
+ return True
440
+ return False
441
+
442
+
443
+ def work_files(work: Path) -> "set":
444
+ """The names of the files directly in an item's work directory, batch's own excepted (the
445
+ owned*.json snapshots, the owned-report directory, hidden temporaries)."""
446
+ try:
447
+ return {p.name for p in work.iterdir()
448
+ if p.is_file() and not p.name.startswith(".") and not (p.name.startswith("owned") and p.suffix == ".json")}
449
+ except OSError:
450
+ return set()
451
+
452
+
453
+ def wrote_without_out(i: int, tool: str, path: str, src: Path) -> Dict[str, Any]:
454
+ """The error of a step that reports an output file while naming no {out}: the batch stops."""
455
+ written = not STATE.dry_run and os.path.isfile(path)
456
+ where = (f"this run wrote {path} for {src.name} before stopping and left it there; no later item ran"
457
+ if written else "nothing was written" + (" (dry run)" if STATE.dry_run else ""))
458
+ return {"step": i, "tool": tool, "kind": "input", "reason": STEP_WRITES_WITHOUT_OUT,
459
+ "message": (f"step {i} ({tool}) names no {{out}} but writes {path}, its own default output: the next "
460
+ f"step does not read it and the batch does not deliver it; {where}"),
461
+ "hint": f"give step {i} \"-o\", \"{{out}}\" so its file is the one the next step reads and the batch delivers",
462
+ "details": {"step": i, "tool": tool, "file": path, "written": written}}
463
+
464
+
465
+ def step_writes(step: Any) -> bool:
466
+ """Whether a recipe step writes a file: it names {out} (check.py and probe.py do not)."""
467
+ return isinstance(step, list) and any("{out}" in str(a) for a in step[1:])
468
+
469
+
470
+ def writes_nothing(recipe: Dict[str, Any]) -> bool:
471
+ """A steps recipe in which no step names {out}: it measures each file and writes none."""
472
+ return not recipe.get("project") and not any(step_writes(st) for st in recipe.get("steps") or [])
473
+
474
+
475
+ def row_output(src: Path, recipe: Dict[str, Any], outdir: Path) -> Dict[str, Any]:
476
+ """An item's output fields for its row: `output` is always the final path, a string as it has
477
+ been since 1.x (a --json key never changes type within a major), and a recipe that writes
478
+ nothing adds `written: false` (#415, #428 review)."""
479
+ fields: Dict[str, Any] = {"output": str(final_path(src, recipe, outdir))}
480
+ if writes_nothing(recipe):
481
+ fields["written"] = False
482
+ return fields
483
+
484
+
485
+ def own_expected(src: Path, path: "Path | str") -> "Optional[Dict[str, int]]":
486
+ """The identity this process left `path` with, if it delivered a file there for `src`."""
487
+ with _OWN_LOCK:
488
+ return _OWN_OUTPUTS.get(str(src), {}).get(os.path.realpath(str(path)))
489
+
490
+
491
+ def is_own_output(src: Path, final: Path) -> bool:
492
+ """Whether `final` is still the file this process delivered there for `src` (_OWN_OUTPUTS)."""
493
+ expected = own_expected(src, final)
494
+ return expected is not None and owned_identity(str(final)) == expected
495
+
496
+
497
+ def record_own(src: Path, committed: "Dict[str, Dict[str, int]]", work: Path) -> None:
498
+ """Remember the files this item delivered, each with the identity it had when it was written
499
+ (a step's report_committed(), deliver() for the final path), never as it is now: a sidecar
500
+ edited while a later step ran no longer matches, so the item's next pass refuses it. Paths in
501
+ the item's work directory go with it and are skipped. Replaces what an earlier pass of the item
502
+ recorded."""
503
+ base = os.path.realpath(str(work))
504
+ mine: Dict[str, Dict[str, int]] = {}
505
+ for p, ident in committed.items():
506
+ real = os.path.realpath(p)
507
+ if real == base or real.startswith(base + os.sep) or not isinstance(ident, dict):
508
+ continue
509
+ mine[real] = ident
510
+ with _OWN_LOCK:
511
+ _OWN_OUTPUTS[str(src)] = mine
512
+
513
+
514
+ def owned_config(src: Path, work: Path, i: int) -> Path:
515
+ """The file a step reads under runner.OWNED_ENV: a snapshot of what this process delivered for
516
+ `src`, taken right before the step starts (one file per step, since a step reads it once), and
517
+ the directory where each of its processes reports the paths it passed the output check for."""
518
+ report = work / "owned-report"
519
+ report.mkdir(exist_ok=True)
520
+ with _OWN_LOCK:
521
+ replaceable = dict(_OWN_OUTPUTS.get(str(src), {}))
522
+ cfg = work / f"owned{i}.json"
523
+ cfg.write_text(json.dumps({"replaceable": replaceable, "report": str(report)}), encoding="utf-8")
524
+ return cfg
525
+
526
+
527
+ def owned_reports(work: Path) -> "Dict[str, Dict[str, int]]":
528
+ """{path: identity when written} for every file the item's steps reported committing
529
+ (owned_config's report directory). A path a step was allowed to write but never reported
530
+ writing is not in it."""
531
+ found: Dict[str, Dict[str, int]] = {}
532
+ for f in sorted((work / "owned-report").glob("*.json")) if (work / "owned-report").is_dir() else []:
533
+ try:
534
+ doc = json.loads(f.read_text(encoding="utf-8"))
535
+ except (OSError, ValueError):
536
+ continue
537
+ committed = doc.get("committed") if isinstance(doc, dict) else None
538
+ if isinstance(committed, dict):
539
+ found.update({p: i for p, i in committed.items() if isinstance(p, str) and isinstance(i, dict)})
540
+ return found
541
+
542
+
543
+ def deliver(src: str, final: Path, expected: "Optional[Dict[str, int]]" = None) -> "Optional[Dict[str, int]]":
544
+ """Move an item's last written intermediate to its final path, under the output guard every
545
+ tool applies: an existing file is replaced only with --overwrite, or when it is still exactly
546
+ `expected` -- the file this process delivered there on an earlier pass -- checked under the
547
+ output lock, so a file another process put there since is refused. A dry run writes nothing."""
548
+ if STATE.dry_run:
549
+ # the refusal the real run would meet, as a step writing {out} plans it (#428 review)
550
+ if final.exists() and not STATE.overwrite:
551
+ raise ItemError({"step": None, "tool": None, "kind": "input", "reason": "output_exists",
552
+ "message": f"refusing to overwrite existing output {str(final)!r}: pass --overwrite to replace it"})
553
+ log(f" [dry-run] would deliver the last written file to {final}")
554
+ return
555
+
556
+ def locked(msg: str, hint: str, details: Dict[str, Any]) -> None:
557
+ raise ItemError({"step": None, "tool": None, "kind": "input", "reason": "output_locked",
558
+ "message": msg, "hint": hint, "details": details})
559
+ # under the output lock every tool's write holds, so the existence check and the move are one
560
+ # step for another run delivering or writing the same path
561
+ with _OutputLock(str(final), on_locked=locked):
562
+ if final.exists() and not STATE.overwrite and not (expected is not None and owned_identity(str(final)) == expected):
563
+ raise ItemError({"step": None, "tool": None, "kind": "input", "reason": "output_exists",
564
+ "message": f"refusing to overwrite existing output {str(final)!r}: pass --overwrite to replace it"})
565
+ try:
566
+ os.replace(src, final)
567
+ except OSError:
568
+ # another filesystem: copy beside the final path and rename, so a copy that fails part
569
+ # way never leaves a truncated file where the caller's was
570
+ # created exclusively and written through the descriptor that created it: never through
571
+ # an entry planted at the name, and two threads delivering side by side get two names
572
+ tmp = None
573
+ try:
574
+ tmp = copy_to_sibling(str(src), str(final))
575
+ os.replace(tmp, final)
576
+ except OSError as exc:
577
+ if tmp:
578
+ try:
579
+ os.remove(tmp)
580
+ except OSError:
581
+ pass
582
+ raise ItemError({"step": None, "tool": None, "kind": "output",
583
+ "message": f"could not deliver {src} to {final}: {exc}"})
584
+ # the delivered file as it was put there, taken under the lock: what a later pass may replace
585
+ ident = owned_identity(str(final))
586
+ log(f" delivered the last written file to {final}")
587
+ return ident
588
+
589
+
590
+ def process(src: Path, recipe: Dict[str, Any], outdir: Path, work: Path,
591
+ deadline: "Optional[float]" = None) -> Dict[str, Any]:
592
+ final = final_path(src, recipe, outdir)
593
+ t0 = time.time()
594
+ # replacing this run's own earlier output is decided per path and at the write, never here:
595
+ # each step gets a snapshot of what this process delivered (runner.OWNED_ENV) and checks every
596
+ # existing file it would write against it; deliver() checks the final path under its lock
597
+ track = not STATE.dry_run and not STATE.overwrite
598
+
599
+ delivered: Dict[str, Dict[str, int]] = {}
600
+
601
+ def owned(i: int) -> "Optional[Path]":
602
+ return owned_config(src, work, i) if track else None
603
+
604
+ def budget() -> "Optional[float]":
605
+ """What is left of the BATCH's time limit -- not a fresh one per item. A --timeout is a
606
+ promise about the whole run, so a queue of 40 files cannot quietly take 40 timeouts."""
607
+ if deadline is None:
608
+ return None
609
+ return max(1.0, deadline - time.monotonic())
610
+ if recipe.get("project"):
611
+ try:
612
+ proj = read_json(str(recipe["project"])) # too deep is a ValueError too (A20)
613
+ except (OSError, ValueError) as e:
614
+ raise ItemError({"step": None, "tool": "render.py", "kind": "input", "reason": "recipe_project_unreadable",
615
+ "message": f"recipe.project: {recipe['project']} could not be read as JSON: {e}"})
616
+ if not isinstance(proj, dict):
617
+ raise ItemError({"step": None, "tool": "render.py", "kind": "input", "reason": "recipe_project_unreadable",
618
+ "message": f"recipe.project: {recipe['project']} is not a JSON object"})
619
+ idx = int(recipe.get("clip_key") or 0) # null is clip 0, as check_recipe_types() reads it
620
+ proj.setdefault("clips", [{}])
621
+ while len(proj["clips"]) <= idx:
622
+ proj["clips"].append({})
623
+ # the copy is written in the item's work directory, and render.py reads a project's
624
+ # relative paths against the project file's own directory: they are made absolute
625
+ # against the recipe's project, or "bed.wav" beside it was looked for in .work/<n>-xxx/
626
+ proj = rebase_project_paths(proj, Path(str(recipe["project"])).resolve().parent)
627
+ proj["clips"][idx]["src"] = str(src.resolve())
628
+ proj["output"] = str(final.resolve())
629
+ pj = work / "project.json"
630
+ pj.write_text(json.dumps(proj, indent=2), encoding="utf-8")
631
+ owned_cfg = owned(0)
632
+ if not STATE.dry_run:
633
+ # the render writes the final path itself: a stop while it runs reports a file it left
634
+ # there as kept, as for a steps recipe's last step (#510 review)
635
+ with _OWN_LOCK:
636
+ _WATCHED[str(src)] = (str(final), owned_identity(str(final)))
637
+ ok, _doc = run_step(["render.py", str(pj)], budget(), owned=owned_cfg)
638
+ if ok:
639
+ with _OWN_LOCK:
640
+ _WATCHED.pop(str(src), None)
641
+ step_docs = [("render", _doc)]
642
+ failure = None if ok else step_error(0, "render.py", _doc)
643
+ cut_reencoded: List[bool] = []
644
+ cut_reasons: List[str] = []
645
+ cut_possible: List[List[str]] = []
646
+ else:
647
+ steps = recipe.get("steps") or []
648
+ if not steps:
649
+ raise ItemError({"step": None, "tool": None, "kind": "input", "reason": "recipe_has_no_steps",
650
+ "message": "recipe needs steps or project"})
651
+ cur = str(src)
652
+ ok = True
653
+ failure = None
654
+ cut_reencoded = []
655
+ step_docs = []
656
+ cut_reasons = []
657
+ cut_possible = []
658
+ for i, step in enumerate(steps):
659
+ last = i == len(steps) - 1
660
+ # the item's directory is its own, so the name needs no stem (a long one overflowed it)
661
+ out = str(final) if last else str(work / f"step{i}.{intermediate_ext(src)}")
662
+ # a step that names no {out} (check.py, probe.py) writes nothing: the next step reads
663
+ # what this one read, and when it is the last, the last file written is delivered (#415)
664
+ writes = step_writes(step)
665
+ argv = [str(a).replace("{in}", cur).replace("{out}", out) for a in step]
666
+ if last and writes and track and is_own_output(src, final):
667
+ log(f" {final.name} is this run's own earlier output, unchanged since: it may be replaced")
668
+ owned_cfg = owned(i)
669
+ before = set() if last else work_files(work)
670
+ if last and writes and not STATE.dry_run:
671
+ # what is at the final path before the step that writes it: a stop while it runs
672
+ # reports a file the step left there as kept, not as nothing (#510)
673
+ with _OWN_LOCK:
674
+ _WATCHED[str(src)] = (str(final), owned_identity(str(final)))
675
+ step_ok, doc = run_step(argv, budget(), owned=owned_cfg)
676
+ if step_ok:
677
+ with _OWN_LOCK:
678
+ _WATCHED.pop(str(src), None) # a stopped step's stays for interrupted_row()
679
+ step_docs.append((Path(str(argv[0])).stem if argv else "step", doc))
680
+ # only cut.py's own doc carries `reencoded` -- true if ANY range this call cut (or its
681
+ # --segments join) re-encoded, for the reasons in its `reencode_reason` (distinct per
682
+ # call, so cut_reencode_reasons lists each reason once per cut.py call that named it).
683
+ # Per cut.py call, not per --segments range.
684
+ if step_ok and argv and argv[0] == "cut.py" and isinstance(doc, dict) and "reencoded" in doc:
685
+ cut_reencoded.append(bool(doc["reencoded"]))
686
+ cut_reasons.extend(r for r in (doc.get("reencode_reason") or []) if isinstance(r, str))
687
+ # a dry run's planned copy may still re-encode: what each call's plan says (#510 review)
688
+ cut_possible.append([r for r in (doc.get("possible_reencode_reason") or []) if isinstance(r, str)])
689
+ if not step_ok:
690
+ ok = False
691
+ failure = step_error(i, str(argv[0]) if argv else None, doc)
692
+ break
693
+ reported = doc.get("output") if isinstance(doc, dict) else None
694
+ if not writes and isinstance(reported, str) and reported and not names_output(step):
695
+ # #510: the step wrote (or under --dry-run would write) its own default output, which
696
+ # the next step does not read and the batch does not deliver: refused, and the batch stops
697
+ raise ItemError(wrote_without_out(i, str(argv[0]), os.path.abspath(reported), src))
698
+ if writes and not last:
699
+ lost = sorted(set(work_files(work)) - before - {os.path.basename(out)})
700
+ if lost:
701
+ # a side file the step wrote beside its intermediate (caption.py's .srt, an .ass):
702
+ # the item's work directory goes when the item ends, and it with it (#510)
703
+ record_skip(f"{src.name}: step {i} ({argv[0]}) also wrote {', '.join(lost)} beside its intermediate; "
704
+ "it is removed with the item's work directory, not delivered (only the last step's "
705
+ "side files land beside the output)",
706
+ "batch_side_file_not_delivered", file=str(src), step=i, tool=str(argv[0]), files=lost)
707
+ if writes:
708
+ cur = out
709
+ if ok and cur != str(final) and not writes_nothing(recipe):
710
+ # the last step wrote nothing: the item's deliverable is the last file a step wrote,
711
+ # which is in this item's work directory and would be removed with it (#415)
712
+ try:
713
+ ident = deliver(cur, final, expected=own_expected(src, final))
714
+ if ident:
715
+ delivered[str(final)] = ident
716
+ except ItemError as exc:
717
+ ok, failure = False, exc.error
718
+ if ok and track:
719
+ # what this item delivered, each file as it was when written: the paths its steps reported
720
+ # committing (side files included) and the final path deliver() moved into place
721
+ record_own(src, {**owned_reports(work), **delivered}, work)
722
+ result: Dict[str, Any] = {"file": str(src), **row_output(src, recipe, outdir), "ok": ok, "seconds": round(time.time() - t0, 1)}
723
+ if failure:
724
+ result["error"] = failure
725
+ # `ok` is "every step completed" (design-decisions: a spec miss a tool cannot fix is completed +
726
+ # verified false, not a failure); `verified` is whether every step also verified what it wrote,
727
+ # and `unverified` names the steps that did not and which of their checks failed
728
+ unverified = []
729
+ for idx, (name, doc) in enumerate(step_docs):
730
+ if ok and isinstance(doc, dict) and doc.get("verified") is not True:
731
+ unverified.append({"step": idx, "tool": name,
732
+ "failed": [str(v.get("step")) + (f" ({v['stage']})" if v.get("stage") else "")
733
+ for v in doc.get("verification") or [] if isinstance(v, dict) and not v.get("ok")]})
734
+ result["verified"] = bool(ok and not STATE.dry_run and step_docs and not unverified)
735
+ if unverified and not STATE.dry_run:
736
+ result["unverified"] = unverified
737
+ diag: Dict[str, List[Any]] = {}
738
+ for name, doc in step_docs:
739
+ for bucket, entries in ((doc or {}).get("diagnostics") or {}).items() if isinstance(doc, dict) else []:
740
+ diag.setdefault(bucket, []).extend(dict(e, step=name) for e in entries if isinstance(e, dict))
741
+ if diag:
742
+ result["diagnostics"] = diag
743
+ if cut_reencoded:
744
+ result["cut_reencoded"] = cut_reencoded
745
+ result["cut_reencode_reasons"] = cut_reasons
746
+ if STATE.dry_run:
747
+ result["cut_possible_reencode_reason"] = cut_possible
748
+ # the encoder each item really ran and its GPU facts (--hw / FFMPEG_SKILL_HW: on VideoToolbox,
749
+ # fell back and why): this process encodes nothing itself, so its top-level hw.used is null
750
+ result.update(steps_encoder_report(step_docs))
751
+ return result
752
+
753
+
754
+ def output_identity(path: str) -> "Optional[Dict[str, int]]":
755
+ """What a cache entry remembers of the output it served: size and mtime_ns (a stat, no read)."""
756
+ try:
757
+ st = os.stat(path)
758
+ except OSError:
759
+ return None
760
+ return {"size": st.st_size, "mtime_ns": st.st_mtime_ns}
761
+
762
+
763
+ def cached_output_changed(hit: Dict[str, Any], recipe: "Optional[Dict[str, Any]]" = None) -> "Optional[Dict[str, Any]]":
764
+ """None when the entry's output is still the file this batch wrote; else why it is not served:
765
+ output_missing, output_changed (size or mtime differ: something replaced or edited it),
766
+ entry_unverifiable (an entry written by 2.10.11 or earlier recorded no identity, so nothing can say
767
+ the file is the one it describes), or entry_predates_output_check: the recipe has a step that
768
+ names no {out}, and the entry was stored before such a step's own output was checked (#510), so
769
+ a step that writes its default output (metadata.py {in}) was cached as one that writes nothing."""
770
+ steps = (recipe or {}).get("steps") or []
771
+ if not (recipe or {}).get("project") and any(not step_writes(st) for st in steps) and not hit.get("output_checked"):
772
+ return {"reason": "entry_predates_output_check", "output": hit.get("output"),
773
+ "message": "the entry was stored before batch checked what a step naming no {out} writes"}
774
+ if hit.get("written") is False or ("output" in hit and hit["output"] is None):
775
+ return None # a recipe that writes nothing (check.py over a folder): no file to have changed
776
+ out = str(hit.get("output") or "")
777
+ now = output_identity(out) if out else None
778
+ if now is None:
779
+ return {"reason": "output_missing", "output": out, "message": "the output is gone"}
780
+ expected = hit.get("output_identity")
781
+ if not isinstance(expected, dict):
782
+ return {"reason": "entry_unverifiable", "output": out,
783
+ "message": "the cache entry predates output identities, so the file cannot be checked"}
784
+ if expected != now:
785
+ return {"reason": "output_changed", "output": out, "expected": expected, "actual": now,
786
+ "message": "the output changed since the batch wrote it"}
787
+ return None
788
+
789
+
790
+ def main() -> int:
791
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
792
+ ap.add_argument("folder")
793
+ ap.add_argument("--recipe", required=True, help="batch.json")
794
+ ap.add_argument("--force", action="store_true", help="ignore the cache and redo everything")
795
+ ap.add_argument("--watch", type=float, help="keep polling the folder every N seconds")
796
+ ap.add_argument("--jobs", default="1", metavar="N",
797
+ help="process N files at once, or 'auto' for min(cpu_count, 4). Capped at "
798
+ "min(N, cpu_count, 8): every item is already an ffmpeg that threads "
799
+ "across cores, so more than a few contend rather than go faster. "
800
+ "Default 1, which is 1.16's behaviour exactly.")
801
+ ap.add_argument("--work", help="work directory for intermediates (default: <output_dir>/.work)")
802
+ add_common(ap)
803
+ add_hw_orchestrator_args(ap)
804
+ args = ap.parse_args()
805
+ apply_common(args)
806
+
807
+ started = time.time()
808
+ with _OWN_LOCK:
809
+ _OWN_OUTPUTS.clear()
810
+ _WATCHED.clear()
811
+ folder = Path(args.folder).resolve() # relative 'bdir' used to become bdir/bdir/out once joined with the default outdir
812
+ if not folder.is_dir():
813
+ die(f"not a folder: {folder}")
814
+ try:
815
+ recipe = read_json(args.recipe) # too deep is a ValueError too (A20)
816
+ except (OSError, ValueError) as exc:
817
+ die(f"cannot read recipe: {exc}", kind="input")
818
+ if not isinstance(recipe, dict):
819
+ die("cannot read recipe: not a JSON object", kind="input")
820
+ check_recipe_types(recipe)
821
+ if recipe.get("project") and not os.path.isabs(recipe["project"]):
822
+ recipe["project"] = str((Path(args.recipe).resolve().parent / recipe["project"]))
823
+ # a recipe error is the same for every item: refuse it once, before any item runs, rather than
824
+ # failing each item with it
825
+ if not recipe.get("project"):
826
+ if not recipe.get("steps"):
827
+ die("recipe needs steps or project")
828
+ for st in recipe["steps"]:
829
+ name = st[0] if isinstance(st, list) and st else st
830
+ if not isinstance(name, str) or name not in ALLOWED_STEP_SCRIPTS:
831
+ die(f"recipe step names a script that isn't one of this skill's own tools: {name!r} "
832
+ f"(must be a bare filename like 'silence.py', found in scripts/)")
833
+ if writes_nothing(recipe):
834
+ # a QC batch (check.py / probe.py on every file): its rows carry written: false, and its
835
+ # cache entries claim no file, so they are served rather than missed as output_missing (#415)
836
+ note("no recipe step names {out}: the steps only read each file, so no output is written "
837
+ "(each row says written: false; its output path is not created)")
838
+ outdir = Path(recipe.get("output_dir") or (folder / "out"))
839
+ if not outdir.is_absolute():
840
+ outdir = folder / outdir
841
+ # resolved, so an alias of the input folder ("sub/..", a symlink) is recognised as one: the
842
+ # input scan below excludes outdir's files by parentage, and the input check by resolved path
843
+ outdir = outdir.resolve()
844
+ if outdir == folder:
845
+ # the scan skips files under outdir, so it found nothing here, and with suffix "" a
846
+ # final path was the source itself, which --overwrite replaced (#428 review)
847
+ die(f"output_dir {recipe.get('output_dir')!r} is the input folder {folder}: its outputs would mix with "
848
+ "or replace the batch inputs -- set an \"output_dir\" outside it (the default is out/)", kind="input")
849
+ work = Path(args.work) if args.work else outdir / ".work"
850
+ # the children refuse an output whose directory does not exist, under --dry-run too, so the
851
+ # directories are created for the plan as well -- and removed again afterwards when a dry
852
+ # run created them and left them empty (a plan leaves nothing behind, sweep F15)
853
+ created = [d for d in (outdir, work) if not d.exists()]
854
+ outdir.mkdir(parents=True, exist_ok=True)
855
+ work.mkdir(parents=True, exist_ok=True)
856
+ # a real run that is refused before any item starts (--jobs, an output collision, a final path
857
+ # that is an input) leaves nothing behind either (A187, #465: it left out/ and out/.work)
858
+ item_started = {"item": False}
859
+ if created:
860
+ import atexit
861
+
862
+ def _remove_empty_dirs() -> None:
863
+ if not STATE.dry_run and item_started["item"]:
864
+ return
865
+ for d in sorted(created, key=lambda p: len(str(p)), reverse=True):
866
+ try:
867
+ if not any(d.iterdir()):
868
+ d.rmdir()
869
+ except OSError:
870
+ pass
871
+ atexit.register(_remove_empty_dirs)
872
+ cache_path = outdir / ".ffskill_cache.json"
873
+ cache: Dict[str, Any] = {}
874
+ if cache_path.exists() and not args.force:
875
+ try:
876
+ cache = json.loads(cache_path.read_text(encoding="utf-8"))
877
+ if not isinstance(cache, dict):
878
+ raise ValueError("not a JSON object")
879
+ except (OSError, ValueError) as exc:
880
+ # every entry is lost: each item runs again, and the next store rewrites the file
881
+ size = cache_path.stat().st_size if cache_path.exists() else None
882
+ warn(f"the batch cache {cache_path} could not be read ({exc}); starting with an empty cache, so every item runs again",
883
+ "batch_cache_reset", path=str(cache_path), size=size, error=str(exc))
884
+ audit("batch_cache_reset", {"path": str(cache_path), "size": size, "error": str(exc)},
885
+ default_path=str(outdir / ".ffskill-audit.jsonl"))
886
+ cache = {}
887
+ glob = recipe.get("glob") or "*"
888
+
889
+ # --jobs: every item is itself an ffmpeg that already threads across cores, so beyond a few
890
+ # concurrent encodes the jobs contend and wall-clock stops improving while memory does not.
891
+ # A number above the cap is clamped with a note, not refused: an optimistic number is not an
892
+ # error, and refusing one helps nobody.
893
+ cpus = os.cpu_count() or 1
894
+ requested = min(cpus, 4) if str(args.jobs).lower() == "auto" else None
895
+ if requested is None:
896
+ try:
897
+ requested = int(args.jobs)
898
+ except ValueError:
899
+ die(f"--jobs {args.jobs!r}: a whole number, or 'auto'", kind="input")
900
+ if requested < 1:
901
+ die("--jobs must be at least 1", kind="input")
902
+ jobs = max(1, min(requested, cpus, JOBS_CAP))
903
+ if jobs != requested:
904
+ info(f"--jobs {requested} capped to {jobs} (min of the request, {cpus} CPU(s) and the "
905
+ f"{JOBS_CAP}-job ceiling): each item is already a multi-threaded encode")
906
+ # One budget for the whole batch, not one per item -- but only where that cannot change what
907
+ # 1.16 did. A stated --timeout is a statement about this run, and asking for --jobs > 1 is
908
+ # asking for the batch to be treated as one piece of work; the default sequential path with
909
+ # the default timeout keeps 1.16's behaviour exactly, where each item got its own ceiling and
910
+ # a long folder was never cut off part-way.
911
+ shared_budget = bool(args.timeout) or jobs > 1
912
+ deadline = time.monotonic() + STATE.timeout if (shared_budget and STATE.timeout) else None
913
+ cache_lock = threading.Lock()
914
+ timed_out = {"hit": False}
915
+ interrupted: Dict[str, Any] = {"hit": False, "signal": None}
916
+ refused: Dict[str, Any] = {"hit": False} # a step wrote without naming {out}: no later item runs (#510)
917
+ _STOP.clear()
918
+ # Ctrl-C (and SIGTERM where it is delivered) stops the running steps and reports the table:
919
+ # the shared handler would exit with "nothing was written" and no rows, and inside an item it
920
+ # surfaced as that item's failure while the batch went on (spec 4.1)
921
+ import signal as _signal
922
+
923
+ def _interrupt(signum: int, frame: Any) -> None:
924
+ if interrupted["signal"] is not None:
925
+ # a second signal while the first one's stop runs (Ctrl-C reaches the whole group, and a
926
+ # parent then sends SIGTERM): raising again broke into the stop or the table, and the
927
+ # exit code became the second signal's (#510 review; runner._on_signal() does the same)
928
+ return
929
+ interrupted["signal"] = signum
930
+ _STOP.set()
931
+ stop_children()
932
+ raise KeyboardInterrupt
933
+ if threading.current_thread() is threading.main_thread():
934
+ for sig in (getattr(_signal, "SIGINT", None), getattr(_signal, "SIGTERM", None)):
935
+ if sig is not None:
936
+ try:
937
+ _signal.signal(sig, _interrupt)
938
+ except (ValueError, OSError):
939
+ pass
940
+
941
+ # --watch: each source's (size, mtime_ns) at the previous poll. A folder files are copied,
942
+ # downloaded or recorded into is read while they grow: a file processed mid-copy delivered a
943
+ # fraction of itself as ok (verified, for an MKV or TS), and once it settled every later pass
944
+ # met that output as someone else's and refused it. A source is processed once it is
945
+ # unchanged across one poll interval -- the same size and mtime as at the previous poll, or,
946
+ # first seen, last modified at least one interval ago; until then its row is
947
+ # skipped: "settling", not cached, and the next pass looks again.
948
+ last_seen: Dict[str, "tuple[int, int]"] = {}
949
+ shown_empty = {"done": False}
950
+
951
+ def settle_poll(files: List[Path]) -> "set":
952
+ if not args.watch:
953
+ return set()
954
+ unsettled = set()
955
+ now = time.time()
956
+ current: Dict[str, "tuple[int, int]"] = {}
957
+ for src in files:
958
+ try:
959
+ st = src.stat()
960
+ except OSError:
961
+ continue # gone since the scan: file_key() reports it as before
962
+ sig = (st.st_size, st.st_mtime_ns)
963
+ current[str(src)] = sig
964
+ before = last_seen.get(str(src))
965
+ if (before != sig) if before is not None else (now - st.st_mtime < args.watch):
966
+ unsettled.add(str(src))
967
+ last_seen.clear()
968
+ last_seen.update(current)
969
+ return unsettled
970
+
971
+ def one_pass() -> List[Dict[str, Any]]:
972
+ files = sorted(p for p in folder.glob(caseless_glob(glob)) if p.is_file() and p.suffix.lower() in MEDIA_EXT and outdir not in p.parents)
973
+ if not files and not shown_empty["done"]:
974
+ # a batch of nothing completed with total 0 and not a word (A82): say what matched nothing
975
+ shown_empty["done"] = True
976
+ note(f"no media file in {folder} matches the recipe's glob {glob!r} (matched without regard to case); "
977
+ "nothing was processed")
978
+ # Two different sources can compute the same final path (most often a fixed recipe "ext"
979
+ # collapsing e.g. clip.mp4 and clip.mov to the same clip_out.mp4) -- catch that before
980
+ # processing anything, rather than letting the later one silently overwrite the earlier
981
+ # one's finished output with the cache still recording both as "ok".
982
+ # Compared case-folded: Clip_out.mp4 and clip_out.mp4 are one file on macOS's and
983
+ # Windows' default filesystems, so a batch that only works on Linux is refused everywhere (#415).
984
+ by_final: Dict[str, List[Path]] = {}
985
+ for src in files:
986
+ by_final.setdefault(str(final_path(src, recipe, outdir)).casefold(), []).append(src)
987
+ collisions = {key: srcs for key, srcs in by_final.items() if len(srcs) > 1 and not writes_nothing(recipe)}
988
+ if collisions:
989
+ detail = "; ".join(" / ".join(sorted({final_path(s, recipe, outdir).name for s in srcs}))
990
+ + " <- " + ", ".join(s.name for s in srcs) for srcs in collisions.values())
991
+ die(f"{len(collisions)} output filename collision(s) in this batch (names that differ only in case are one "
992
+ f"file on macOS and Windows) -- rename the sources, "
993
+ f"or add a distinguishing \"suffix\"/\"ext\" per run, or split into separate globs: {detail}")
994
+ # A final path that is one of the inputs would replace a source -- an output_dir that is
995
+ # the input folder under another name ("sub/..") with suffix "" -- and --overwrite does
996
+ # not license that (#428 review). A recipe that writes nothing delivers no file.
997
+ if not writes_nothing(recipe):
998
+ inputs = {str(p.resolve()).casefold() for p in files}
999
+ hits = [s for s in files if str(final_path(s, recipe, outdir).resolve()).casefold() in inputs]
1000
+ if hits:
1001
+ die(f"{len(hits)} final output path(s) would replace a batch input ({', '.join(s.name for s in hits)}); "
1002
+ "the output_dir is the input folder -- set a different \"output_dir\" or a non-empty \"suffix\"",
1003
+ kind="input")
1004
+ def item_work(i: int, src: Path) -> Path:
1005
+ """Where this item's intermediates go: a new directory of its own under the work
1006
+ directory, removed with everything in it when the item ends (run_item()). The step
1007
+ file names are stem-derived, so two items with one stem (clip.mp4, clip.mov) sharing a
1008
+ directory refused each other's files, and a later run refused the files an earlier one
1009
+ left there as someone else's (#415); parallel items had their own directories since
1010
+ 1.17, serial ones now do too."""
1011
+ import tempfile
1012
+ # no stem in the name: a stem near the 255-byte limit made the directory name too long
1013
+ return Path(tempfile.mkdtemp(prefix=f"{i}-", dir=str(work)))
1014
+
1015
+ def run_item(i: int, src: Path) -> Dict[str, Any]:
1016
+ """process() in the item's own work directory, which goes when it ends, however it ends."""
1017
+ import shutil
1018
+ item_started["item"] = True
1019
+ iw = item_work(i, src)
1020
+ try:
1021
+ return process(src, recipe, outdir, iw, deadline)
1022
+ finally:
1023
+ shutil.rmtree(iw, ignore_errors=True)
1024
+
1025
+ def store(key: "Optional[str]", r: Dict[str, Any]) -> None:
1026
+ if not key or not (r["ok"] and not STATE.dry_run):
1027
+ return
1028
+ # the key was made before the item ran: a source or side input edited while it waited
1029
+ # or ran made an output the key does not describe, and a later restore of the old file
1030
+ # would have served it (#510 review). Made again here; not stored when it changed
1031
+ try:
1032
+ now = item_key(Path(r["file"]))
1033
+ except OSError:
1034
+ now = None
1035
+ if now != key:
1036
+ record_skip(f"{Path(r['file']).name}: its source or a side input changed while it was processed, so its "
1037
+ "output is not cached (the next run makes it again)", "batch_cache_inputs_changed", file=r["file"])
1038
+ return
1039
+ # The read-modify-write of the in-memory dict needs the lock even though the file
1040
+ # write is already atomic: two finishers could otherwise serialise from two different
1041
+ # snapshots and lose an entry.
1042
+ with cache_lock:
1043
+ # this run just rewrote r["output"]: an entry under another key (another recipe,
1044
+ # the other GPU setting) that names the same file now describes bytes that are gone
1045
+ for stale in [k for k, v in cache.items() if r["output"] and r.get("written", True) and k != key and isinstance(v, dict) and v.get("output") == r["output"]]:
1046
+ del cache[stale]
1047
+ # the output as this run left it: a later hit is served only while it is unchanged
1048
+ cache[key] = dict(r, output_identity=output_identity(r["output"]) if r["output"] and r.get("written", True) else None,
1049
+ output_checked=True) # every step's own output was checked (#510): see cached_output_changed()
1050
+ # write_text isn't atomic -- a process killed mid-write (or a --watch loop racing
1051
+ # a concurrent manual run) could leave a truncated file that json.loads() above
1052
+ # then silently treats as "no cache" (a ValueError -> {}), discarding every prior
1053
+ # entry. Write to a sibling temp file and rename into place: same-directory
1054
+ # renames are atomic on POSIX and os.replace() is atomic on Windows too, so a
1055
+ # reader only ever sees the old complete file or the new complete file.
1056
+ tmp = cache_path.parent / f"{cache_path.name}.tmp{os.getpid()}.{threading.get_ident()}"
1057
+ tmp.write_text(json.dumps(cache, indent=2), encoding="utf-8")
1058
+ os.replace(tmp, cache_path)
1059
+
1060
+ # ONE list, indexed by each file's position in the sorted `files`. A cached hit goes
1061
+ # into its own slot rather than being appended ahead of the items that still have to run:
1062
+ # appending in two passes reordered the per-item table whenever the cache was partially
1063
+ # warm, which happens at --jobs 1 too and contradicts the order this tool promises.
1064
+ slots: "List[Optional[Dict[str, Any]]]" = [None] * len(files)
1065
+ pending: List[tuple] = []
1066
+ cache_miss: Dict[int, Dict[str, Any]] = {}
1067
+ # read on every pass: a --watch loop serves nothing from an edited project.json, cue file or
1068
+ # music bed (computed once before the loop, it did: A81)
1069
+ pass_key = recipe_key(recipe) + gpu_key() + side_inputs_key(recipe)
1070
+
1071
+ def item_key(src: Path) -> "Optional[str]":
1072
+ """The cache key of one item as its files are now: file_key(src), the recipe, the GPU
1073
+ setting and the side inputs (literal and per item); None when one cannot be keyed.
1074
+ Recomputed by store(), so the side inputs are read again then (pass_key's included)."""
1075
+ per, why = item_side_inputs_key(recipe, src)
1076
+ if why:
1077
+ return None
1078
+ base = recipe_key(recipe) + gpu_key() + side_inputs_key(recipe)
1079
+ return f"{file_key(src)}:{base}" + (":" + per if per else "")
1080
+ polled = settle_poll(files)
1081
+ for i, src in enumerate(files):
1082
+ if str(src) in polled:
1083
+ info(f"skip (still being written) {src.name}: it changed since the last poll")
1084
+ slots[i] = {"file": str(src), **row_output(src, recipe, outdir), "ok": False, "verified": False,
1085
+ "seconds": 0.0, "skipped": "settling"}
1086
+ continue
1087
+ key = f"{file_key(src)}:{pass_key}"
1088
+ per_item, unkeyed = item_side_inputs_key(recipe, src)
1089
+ if unkeyed:
1090
+ # nothing can say the cached output still matches its side input: run it, unstored
1091
+ cache_miss[i] = unkeyed
1092
+ info(f"{src.name}: {unkeyed['message']}")
1093
+ pending.append((i, src, None))
1094
+ continue
1095
+ if per_item:
1096
+ key += ":" + per_item
1097
+ hit = cache.get(key)
1098
+ if isinstance(hit, dict) and not args.force:
1099
+ why = cached_output_changed(hit, recipe)
1100
+ if why is None:
1101
+ info(f"skip (cached) {src.name}")
1102
+ slots[i] = {**{k: v for k, v in hit.items() if k not in ("output_identity", "output_checked")}, "cached": True}
1103
+ continue
1104
+ cache_miss[i] = why
1105
+ facts = {k: v for k, v in why.items() if k not in ("reason", "message")}
1106
+ msg = f"{src.name}: the cached output {hit.get('output')} is not served ({why['message']}); the item runs again"
1107
+ if why["reason"] == "output_changed":
1108
+ warn(msg, "batch_cache_output_changed", file=str(src), **facts)
1109
+ elif why["reason"] == "entry_unverifiable":
1110
+ warn(msg, "batch_cache_entry_unverifiable", file=str(src), **facts)
1111
+ pending.append((i, src, key))
1112
+
1113
+ def timed_out_row(src: Path) -> "Dict[str, Any]":
1114
+ timed_out["hit"] = True
1115
+ return {"file": str(src), **row_output(src, recipe, outdir),
1116
+ "ok": False, "seconds": 0.0, "skipped": "timeout"}
1117
+
1118
+ def failed_row(src: Path, exc: BaseException) -> "Dict[str, Any]":
1119
+ """A worker that raised is a failed item, not a dead run. A die() inside a thread
1120
+ raises SystemExit through fut.result() and used to take the whole process down
1121
+ before the summary and the per-item table were printed -- so the one thing the user
1122
+ needed, which item failed and which succeeded, was the thing they did not get.
1123
+ `error` is structured: an ItemError's own, else what the exception says (its class
1124
+ in `exception`), never str(SystemExit) -- which was the exit code, "1"."""
1125
+ if isinstance(exc, ItemError):
1126
+ error = dict(exc.error)
1127
+ elif isinstance(exc, SystemExit):
1128
+ error = {"step": None, "tool": None, "exception": "SystemExit", "exit_code": exc.code,
1129
+ "message": f"the item stopped with exit code {exc.code}; its message is on stderr"}
1130
+ else:
1131
+ error = {"step": None, "tool": None, "exception": exc.__class__.__name__,
1132
+ "message": (str(exc) or exc.__class__.__name__)[:300]}
1133
+ log(f" failed: {error['message']}")
1134
+ return {"file": str(src), **row_output(src, recipe, outdir),
1135
+ "ok": False, "verified": False, "seconds": 0.0, "error": error}
1136
+
1137
+ def interrupted_row(src: Path, started: bool, r: "Optional[Dict[str, Any]]" = None) -> "Dict[str, Any]":
1138
+ """An item the interrupt reached: `interrupted: true` when it was running (its steps
1139
+ were stopped), `skipped: "interrupted"` when it had not started."""
1140
+ row = dict(r) if r else {"file": str(src), **row_output(src, recipe, outdir), "seconds": 0.0}
1141
+ row.update(ok=False, verified=False)
1142
+ if started:
1143
+ row["interrupted"] = True
1144
+ with _OWN_LOCK:
1145
+ watched = _WATCHED.pop(str(src), None)
1146
+ if watched and owned_identity(watched[0]) not in (None, watched[1]):
1147
+ # the stopped step had written the final file (export.py's --normalize pass keeps
1148
+ # its encode): it is there, unverified, without the step that was stopped (#510)
1149
+ row["kept"] = watched[0]
1150
+ row.setdefault("error", {"step": None, "tool": None, "kind": "interrupted",
1151
+ "message": "interrupted while this item was running; its running step was stopped"})
1152
+ else:
1153
+ row["skipped"] = "interrupted"
1154
+ return row
1155
+
1156
+ def refused_row(src: Path) -> "Dict[str, Any]":
1157
+ """An item not started because an earlier one's step wrote a file without naming {out}."""
1158
+ return {"file": str(src), **row_output(src, recipe, outdir), "ok": False, "verified": False,
1159
+ "seconds": 0.0, "skipped": "recipe_refused"}
1160
+
1161
+ def is_refusal(r: "Optional[Dict[str, Any]]") -> bool:
1162
+ return bool(r) and ((r or {}).get("error") or {}).get("reason") == STEP_WRITES_WITHOUT_OUT
1163
+
1164
+ def with_miss(i: int, r: Dict[str, Any]) -> Dict[str, Any]:
1165
+ if i in cache_miss:
1166
+ r["cache_miss"] = {k: v for k, v in cache_miss[i].items() if k != "message"}
1167
+ return r
1168
+
1169
+ if jobs == 1 or len(pending) < 2:
1170
+ for n, (i, src, key) in enumerate(pending):
1171
+ if deadline is not None and time.monotonic() >= deadline:
1172
+ slots[i] = timed_out_row(src)
1173
+ continue
1174
+ info(f"=== {src.name}")
1175
+ try:
1176
+ r = run_item(i, src)
1177
+ except KeyboardInterrupt:
1178
+ interrupted["hit"] = True
1179
+ # the running item, then every one not started: each keeps its row
1180
+ slots[i] = interrupted_row(src, True)
1181
+ for j, later, _k in pending[n + 1:]:
1182
+ slots[j] = interrupted_row(later, False)
1183
+ break
1184
+ except BaseException as exc: # noqa: BLE001 - reported, never swallowed
1185
+ if isinstance(exc, SystemExit) and not exc.code:
1186
+ raise
1187
+ slots[i] = with_miss(i, failed_row(src, exc))
1188
+ if is_refusal(slots[i]):
1189
+ refused["hit"] = True
1190
+ for j, later, _k in pending[n + 1:]:
1191
+ slots[j] = refused_row(later)
1192
+ break
1193
+ continue
1194
+ slots[i] = with_miss(i, r)
1195
+ store(key, r)
1196
+ return [r for r in slots if r is not None]
1197
+
1198
+ import concurrent.futures
1199
+
1200
+ def work_one(i: int, src: Path, key: str) -> Dict[str, Any]:
1201
+ _LOG.buffer = [f"=== {src.name}"]
1202
+ try:
1203
+ r = run_item(i, src)
1204
+ if not interrupted["hit"]: # a step the interrupt stopped is no result to keep
1205
+ store(key, r)
1206
+ return with_miss(i, r)
1207
+ finally:
1208
+ r_lines, _LOG.buffer = _LOG.buffer, None
1209
+ setattr(_LOG, "lines", r_lines)
1210
+
1211
+ # Submitted in the existing sorted order and written straight into each item's own slot,
1212
+ # so the summary and the per-item table are identical to a serial run's whatever order
1213
+ # the encodes actually finish in.
1214
+ lines: "Dict[int, List[str]]" = {}
1215
+ with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool:
1216
+ futures: "Dict[Any, tuple]" = {}
1217
+ queue = list(pending)
1218
+ in_flight: "set" = set()
1219
+ try:
1220
+ # The pool is topped up to `jobs` in flight and no further: submitting the whole
1221
+ # list up front would put every item past the deadline check before the first one
1222
+ # had finished, and the shared budget could then never stop anything.
1223
+ while queue or in_flight:
1224
+ while queue and len(in_flight) < jobs and not refused["hit"]:
1225
+ if deadline is not None and time.monotonic() >= deadline:
1226
+ break
1227
+ i, src, key = queue.pop(0)
1228
+ fut = pool.submit(_run_buffered, work_one, i, src, key)
1229
+ futures[fut] = (i, src)
1230
+ in_flight.add(fut)
1231
+ if not in_flight:
1232
+ break
1233
+ done_now, in_flight = concurrent.futures.wait(
1234
+ in_flight, return_when=concurrent.futures.FIRST_COMPLETED)
1235
+ in_flight = set(in_flight)
1236
+ for fut in done_now:
1237
+ i, src = futures[fut]
1238
+ try:
1239
+ slots[i], lines[i] = fut.result()
1240
+ except BaseException as exc: # noqa: BLE001 - reported, never swallowed
1241
+ slots[i] = failed_row(src, exc)
1242
+ lines[i] = [f"=== {src.name}", f" failed: {exc}"]
1243
+ if is_refusal(slots[i]):
1244
+ refused["hit"] = True # the items in flight finish; none is started after
1245
+ for i, src, key in queue:
1246
+ slots[i] = refused_row(src) if refused["hit"] else timed_out_row(src)
1247
+ except KeyboardInterrupt:
1248
+ # Spec 4.1: cancel what has not started, stop the running steps (the handler
1249
+ # already did), and REPORT every item -- exit 130 with the table, never a
1250
+ # traceback. The pool's exit waits for the stopped items; they are read below.
1251
+ interrupted["hit"] = True
1252
+ for fut in futures:
1253
+ fut.cancel()
1254
+ info("interrupted: reporting what had already finished")
1255
+ if interrupted["hit"]:
1256
+ for fut, (i, src) in futures.items():
1257
+ if slots[i] is not None:
1258
+ continue
1259
+ if fut.cancelled():
1260
+ slots[i] = interrupted_row(src, False)
1261
+ continue
1262
+ try:
1263
+ r, lines[i] = fut.result()
1264
+ except BaseException: # noqa: BLE001 - its row says it was interrupted
1265
+ r = None
1266
+ # finished in time: kept as it is; stopped by the interrupt: said so
1267
+ slots[i] = r if (r and r.get("ok")) else interrupted_row(src, True, r)
1268
+ for i, src, _key in queue:
1269
+ if slots[i] is None:
1270
+ slots[i] = interrupted_row(src, False)
1271
+ for i, src in enumerate(files):
1272
+ for line in lines.get(i, []):
1273
+ info(line)
1274
+ return [r for r in slots if r is not None]
1275
+
1276
+ results = one_pass()
1277
+ if args.watch and not refused["hit"]:
1278
+ info(f"watching {folder} every {args.watch:g}s (Ctrl-C to stop)")
1279
+ # the shared SIGINT handler (install_signal_handlers) exits 130 with "nothing was written",
1280
+ # which is wrong for a watch that already processed files: while idle between passes,
1281
+ # let Ctrl-C be a plain KeyboardInterrupt so the summary below prints (review 5)
1282
+ import signal
1283
+ try:
1284
+ while True:
1285
+ previous = signal.signal(signal.SIGINT, signal.default_int_handler)
1286
+ try:
1287
+ time.sleep(args.watch)
1288
+ finally:
1289
+ signal.signal(signal.SIGINT, previous)
1290
+ results = one_pass()
1291
+ if interrupted["hit"] or refused["hit"]:
1292
+ break # the pass reported its rows; a watch interrupted mid-pass stops here
1293
+ except KeyboardInterrupt:
1294
+ info("watch stopped")
1295
+ # the items' GPU facts (asked for, fell back and why) reach the top-level `hw`, as render.py's
1296
+ # stages' do; `used` stays null there, because this process encoded nothing itself
1297
+ for r in results:
1298
+ absorb_stage_hw(Path(r["file"]).name, r)
1299
+ done = sum(1 for r in results if r["ok"])
1300
+ info(f"{done}/{len(results)} processed, {sum(1 for r in results if r.get('cached'))} from cache")
1301
+ if not args.json:
1302
+ for r in results:
1303
+ print(f"{'OK ' if r['ok'] else 'FAIL'} {r['file']} -> {r['output'] or '(no output: the steps only read it)'}" + (" (cached)" if r.get("cached") else ""))
1304
+ if interrupted["hit"]:
1305
+ # Ctrl-C on a batch that already produced files: the user needs the partial table, not a
1306
+ # traceback and not "nothing was written". Exit 130 (143 for SIGTERM) with every item:
1307
+ # finished, interrupted while running, or not started.
1308
+ stopped = sum(1 for r in results if r.get("interrupted"))
1309
+ not_started = sum(1 for r in results if r.get("skipped") == "interrupted")
1310
+ kept = [r["kept"] for r in results if r.get("kept")]
1311
+ die(f"interrupted after {done} of {len(results)} item(s): {stopped} stopped while running and "
1312
+ f"{not_started} not started; the finished outputs are kept"
1313
+ + ((f", and {', '.join(kept)} " + ("was written by a step that was stopped and is" if len(kept) == 1 else
1314
+ "were written by steps that were stopped and are") + " kept, unverified")
1315
+ if kept else ""),
1316
+ code=128 + int(interrupted["signal"] or 2), kind="interrupted", output=None, dry_run=STATE.dry_run, results=results,
1317
+ processed=done, total=len(results), jobs=jobs, jobs_requested=requested,
1318
+ timed_out=timed_out["hit"])
1319
+ if refused["hit"]:
1320
+ rows = [r for r in results if ((r.get("error") or {}).get("reason")) == STEP_WRITES_WITHOUT_OUT]
1321
+ first = rows[0]["error"]
1322
+ files = [r["error"]["details"]["file"] for r in rows]
1323
+ written = [f for r, f in zip(rows, files) if r["error"]["details"].get("written")]
1324
+ not_run = sum(1 for r in results if r.get("skipped") == "recipe_refused")
1325
+ die(first["message"] + (f" ({len(rows)} items in flight wrote one each: {', '.join(written)})" if len(written) > 1 else "")
1326
+ + (f"; {not_run} item(s) not started" if not_run else ""),
1327
+ kind="input", hint=first.get("hint"), output=None, dry_run=STATE.dry_run, results=results,
1328
+ processed=done, total=len(results),
1329
+ error_extra={"reason": STEP_WRITES_WITHOUT_OUT,
1330
+ "details": dict(first["details"], files=files, written_files=written, not_started=not_run)})
1331
+ if timed_out["hit"]:
1332
+ skipped = [r["file"] for r in results if r.get("skipped") == "timeout"]
1333
+ die(f"the batch's {STATE.timeout:g} s budget ran out with {len(skipped)} item(s) not "
1334
+ f"started: {', '.join(os.path.basename(f) for f in skipped[:5])}"
1335
+ + (" ..." if len(skipped) > 5 else "")
1336
+ + ". --timeout is the whole run's limit, not each item's; raise it or split the folder.",
1337
+ code=124, kind="timeout", output=None, dry_run=STATE.dry_run, results=results,
1338
+ processed=done, total=len(results), jobs=jobs, jobs_requested=requested,
1339
+ timed_out=True)
1340
+ if done != len(results):
1341
+ failed_files = [r["file"] for r in results if not r["ok"]]
1342
+ settling = sum(1 for r in results if r.get("skipped") == "settling")
1343
+ die(f"{len(results) - done} of {len(results)} items failed: {', '.join(failed_files[:5])}" + (" ..." if len(failed_files) > 5 else "")
1344
+ + (f" ({settling} of them still being written when the watch stopped, skipped: settling, not processed)" if settling else ""),
1345
+ kind="verification", output=None, dry_run=STATE.dry_run, results=results, processed=done, total=len(results))
1346
+ # cut.py's own `reencoded`, rolled up across every cut.py step this batch ran: how much of the
1347
+ # folder landed on the fast lossless path (mode "copy") vs re-encoded on at least one range.
1348
+ # Keyframe placement, VFR sources, --accurate/--codec in the recipe and --segments joins all
1349
+ # cause it, so the summary counts cut.py's own `reencode_reason` values rather than guessing
1350
+ # one cause. Per cut.py call, not per --segments range.
1351
+ all_cuts = [r for res in results for r in (res.get("cut_reencoded") or [])]
1352
+ cut_summary = None
1353
+ # how many cut.py calls named each reason, beside cut_stream_copy (whose shape is 2.x's,
1354
+ # unchanged); null when no cut.py step ran
1355
+ reasons: Optional[Dict[str, int]] = None
1356
+ if all_cuts:
1357
+ copied = sum(1 for r in all_cuts if not r)
1358
+ cut_summary = {"calls": len(all_cuts), "stream_copy": copied, "reencoded": len(all_cuts) - copied,
1359
+ "stream_copy_rate": round(copied / len(all_cuts), 3)}
1360
+ reasons = {}
1361
+ for res in results:
1362
+ if "cut_reencode_reasons" not in res:
1363
+ # a row from a cache an earlier 2.x batch wrote: it says which calls re-encoded,
1364
+ # not why, so they count as "unknown" rather than leaving {} ("none re-encoded")
1365
+ unknown = sum(1 for r in res.get("cut_reencoded") or [] if r)
1366
+ if unknown:
1367
+ reasons["unknown"] = reasons.get("unknown", 0) + unknown
1368
+ for r in res.get("cut_reencode_reasons") or []:
1369
+ reasons[r] = reasons.get(r, 0) + 1
1370
+ why = (" (reencode_reason: " + ", ".join(f"{k} x{v}" for k, v in reasons.items()) + ")") if reasons else ""
1371
+ if STATE.dry_run:
1372
+ # a dry run's counts are cut.py's plans: a planned copy may still re-encode in a real run,
1373
+ # which measures where it lands (cut.py's possible_reencode_reason, #510). A row a real
1374
+ # run serves from the cache is served here too (cached: true, as that run reports it),
1375
+ # and its calls are what the run that stored it measured, not plans: said apart (#540)
1376
+ planned = [r for res in results if not res.get("cached") for r in (res.get("cut_reencoded") or [])]
1377
+ stored = [r for res in results if res.get("cached") for r in (res.get("cut_reencoded") or [])]
1378
+ parts = []
1379
+ if planned:
1380
+ p_copied = sum(1 for r in planned if not r)
1381
+ parts.append(f"{p_copied}/{len(planned)} call(s) planned as a lossless stream copy "
1382
+ f"({p_copied / len(planned):.0%}), which a real run may still re-encode (each planned row's "
1383
+ f"cut_possible_reencode_reason); {len(planned) - p_copied} planned to re-encode a range or its --segments join")
1384
+ if stored:
1385
+ s_copied = sum(1 for r in stored if not r)
1386
+ parts.append(f"{len(stored)} call(s) in rows a real run serves from the cache (cached: true), as the run that "
1387
+ f"stored them measured: {s_copied} stayed lossless stream-copy, {len(stored) - s_copied} re-encoded")
1388
+ info("cut.py: " + "; ".join(parts) + why)
1389
+ else:
1390
+ info(f"cut.py: {copied}/{len(all_cuts)} call(s) stayed fully lossless stream-copy "
1391
+ f"({cut_summary['stream_copy_rate']:.0%}), {len(all_cuts) - copied} re-encoded a range or its --segments join{why}")
1392
+ unverified = [shown(os.path.basename(r["file"])) for r in results if r.get("ok") and not r.get("verified")]
1393
+ if unverified and not STATE.dry_run:
1394
+ note(f"{len(unverified)} item(s) completed but did not verify everything they wrote (see each row's unverified): "
1395
+ + ", ".join(unverified[:5]) + (" ..." if len(unverified) > 5 else ""))
1396
+ # A successful watch summary is printed after Ctrl-C between passes. Keep the completed
1397
+ # item results without starting another round of probes after the user asked to stop.
1398
+ emit(None, verification=[{"step": "item", "file": r["file"], "ok": bool(r.get("verified"))} for r in results]
1399
+ if not STATE.dry_run else [],
1400
+ verification_paths=[] if args.watch else [r["file"] if r.get("written") is False else r["output"] for r in results],
1401
+ results=results, processed=done, total=len(results),
1402
+ jobs=jobs, jobs_requested=requested, wall_seconds=round(time.time() - started, 1),
1403
+ item_seconds_total=round(sum(float(r.get("seconds") or 0) for r in results), 1),
1404
+ timed_out=timed_out["hit"], cut_stream_copy=cut_summary, cut_reencode_reasons=reasons)
1405
+ return 0
1406
+
1407
+
1408
+ if __name__ == "__main__":
1409
+ sys.exit(main())