@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,2424 @@
1
+ #!/usr/bin/env python3
2
+ """Declarative edits: describe the whole edit in one project.json and render it
3
+ in one command. Change a number, re-render. Non-destructive: sources are never
4
+ touched, intermediates live in a work directory.
5
+
6
+ Project format (all keys optional except clips):
7
+ {
8
+ "output": "final.mp4",
9
+ "frame": {"aspect": "9:16", "width": 1080, "fps": 30},
10
+ "clips": [
11
+ {"src": "a.mp4", "in": "0:05", "out": "0:20"},
12
+ {"src": "b.mp4", "in": 3, "out": 12, "speed": 1.25},
13
+ {"src": "c.mp4"}
14
+ ],
15
+ "transition": {"type": "fade", "duration": 0.5},
16
+ "silence": {"threshold": -38, "min_silence": 0.8},
17
+ "captions": {"text": "cues.txt", "srt": null, "animate": "pop", "karaoke": true, "font": "Noto Sans CJK JP", "size": 28, "position": "bottom"},
18
+ "brand": "brand.json",
19
+ "graphics": [
20
+ {"template": "title", "title": "Episode 12", "subtitle": "The math of video", "start": 0, "end": 4},
21
+ {"template": "lower-third", "name": "Ada Lovelace", "title": "Analyst", "start": 5, "end": 11}
22
+ ],
23
+ "overlays": [
24
+ {"logo": true},
25
+ {"text": "Episode 12", "position": "bottom", "start": 1, "end": 5, "fade": 0.3, "box": true},
26
+ {"video": "webcam.mp4", "position": "bottom-right", "scale": 480, "chromakey": "0x00ff00"}
27
+ ],
28
+ "audio": {"voice": "medium", "music": "bed.mp3", "music_volume": -16, "duck": true, "music_fade_out": 2,
29
+ "effects": "sfx.wav", "stems": {"dialogue": 0, "music": -18, "effects": -22}},
30
+ "loudness": {"lufs": -14, "tp": -1},
31
+ "fit": {"duration": 60},
32
+ "export": {"preset": "reels", "normalize": true}, (default for platform presets; false opts out)
33
+ "check": {"platform": "reels"}, ("content": true adds check.py --content's black/frozen/silence rows)
34
+ "chapters": "chapters.txt" (or [{"at": "0:00", "title": "Intro"}, ...])
35
+ }
36
+
37
+ Stages run in this order: clips (cut) → join → silence → fit → captions →
38
+ graphics → overlays → audio → loudness → export → chapters → check. Missing stages are
39
+ skipped. "brand" points caption/graphics/overlay at a brand.json (fonts,
40
+ colours, logo, safe margin); {"logo": true} in overlays places the brand logo.
41
+ An overlay entry draws one of logo, image, text or video (a picture-in-picture
42
+ layer, overlay.py --video; "chromakey", "chromakey_similarity" and
43
+ "chromakey_blend" key a colour out of that video and need "video"). "scale"
44
+ is that layer's width in px for a logo, image or video; a text entry's size
45
+ is "font_size", and "scale" on a text entry is refused.
46
+
47
+ "check" mirrors check.py's own exit code: a delivery-spec FAIL (or check.py
48
+ itself failing to run) exits 1, same as running check.py directly would --
49
+ the render is not silently reported as successful just because every stage
50
+ up to it completed. The output file is still written and `--json`'s
51
+ `check` field still carries the full row-by-row result either way. A check
52
+ stage with only "content": true runs check.py --content without a platform.
53
+ `verified` is every stage's: a stage that completed unverified (an export that
54
+ missed its loudness) leaves the render verified false, its steps and notes in
55
+ the result.
56
+
57
+ Examples:
58
+ python3 render.py --init project.json # write a commented starter project
59
+ python3 render.py project.json # render
60
+ python3 render.py project.json --dry-run # show every command without rendering
61
+ python3 render.py project.json --fast # preview quality
62
+ """
63
+ import argparse
64
+ import difflib
65
+ import hashlib
66
+ import re
67
+ import json
68
+ import os
69
+ import shutil
70
+ import sys
71
+ import tempfile
72
+ import time
73
+ from pathlib import Path
74
+ from typing import Any, Dict, List, Optional, Sequence
75
+
76
+ from export import PRESETS, PLATFORM_OF
77
+ from _platforms import PLATFORMS, caption_defaults, resolve as resolve_platform
78
+ from _common import AUDIO_CODECS, guard_sidecar, STATE, add_common, aspect_ratio, display_size, frame_size, brand_caption_style, load_brand, apply_common, child_args, die, emit as _emit, info, option_args, probe, require_tool, run, run_tool, place_output, refuse_output_is_input, refuse_unwritten_output, _check_existing_output, _check_output_path, fingerprint, PLAN_VERSION, ffmpeg_version, X264_PRESETS
79
+ from _common.runner import absent_word, path_denied, HW_ENV, HW_FORCED_ENV, add_hw_orchestrator_args, child_exit_code, found_exe, kept_clause, kept_deliverables, mark_delivered, owned_identity, read_json, refuse_missing_components_first, remember_written, with_flags, kept_output, unwatch_destination, watch_destination
80
+ from _common.emit import absorb_stage, audit, is_output_shape_flag, record_fallback, record_skip, refuse, stderr_records, warn
81
+ from _common.decision import brand_asset_files, rebase_project_paths
82
+ from _common.probe import AUDIO_MEDIA_EXT
83
+ import subprocess
84
+ from _contract import CONTRACT_VERSION
85
+ from batch import file_key
86
+
87
+
88
+ def _skill_version() -> str:
89
+ """The shipped version, from package.json -- in the cache key so a stage whose implementation
90
+ changed cannot serve back an artifact the old one wrote."""
91
+ try:
92
+ return str(json.loads((Path(__file__).resolve().parent.parent / "package.json")
93
+ .read_text(encoding="utf-8")).get("version") or "?")
94
+ except (OSError, ValueError):
95
+ return "?"
96
+
97
+
98
+ SKILL_VERSION = _skill_version()
99
+
100
+ HERE = Path(__file__).resolve().parent
101
+ TEMPLATE_DIR = HERE.parent / "templates"
102
+ # The placeholders a delivery template carries; a block whose placeholder has no value
103
+ # (no --logo, no --title, no cues) is dropped from the filled project rather than rendered empty.
104
+ PLACEHOLDERS = ("$INPUT", "$OUTPUT", "$CUES", "$SRT", "$LOGO", "$TITLE", "$BRAND", "$CHAPTERS", "$IMAGE")
105
+ # Intermediates follow the delivery's own media kind: an audio-only project (the podcast
106
+ # template) must not carry its stages through .mp4 containers.
107
+ AUDIO_EXT = frozenset(AUDIO_CODECS) # the audio-only outputs the tools write, one list (#517)
108
+
109
+ TEMPLATE = {
110
+ "output": "final.mp4",
111
+ "frame": {"aspect": "16:9", "width": 1920, "fps": 30},
112
+ "clips": [{"src": "REPLACE_ME.mp4", "in": "0:00", "out": "0:30"}],
113
+ "transition": {"type": "fade", "duration": 0.5},
114
+ "silence": None,
115
+ "brand": None,
116
+ "captions": None,
117
+ "graphics": [],
118
+ "overlays": [],
119
+ "audio": None,
120
+ "loudness": {"lufs": -14, "tp": -1},
121
+ "fit": None,
122
+ "export": {"preset": "youtube", "normalize": True},
123
+ "chapters": None,
124
+ "check": {"platform": "youtube"},
125
+ }
126
+
127
+
128
+ # Every key render.py reads, per object. Anything else is a refusal rather than a silent no-op:
129
+ # a clip "start"/"end" (the spelling titles, graphics and overlays use) rendered the whole clip
130
+ # untrimmed, and a mistyped stage name dropped the stage -- both reported as a success (review 9).
131
+ OBJECT_KEYS: Dict[str, frozenset] = {
132
+ "project": frozenset({"output", "frame", "clips", "transition", "silence", "brand", "captions",
133
+ "graphics", "overlays", "audio", "loudness", "fit", "export", "check", "chapters",
134
+ "audiogram", "template", "snap"}),
135
+ "clips[]": frozenset({"src", "in", "out", "speed", "snap"}),
136
+ # 1.17: beat snapping, forwarded to cut.py for any clip that has in/out
137
+ "snap": frozenset({"to", "tolerance", "min_confidence", "source"}),
138
+ "frame": frozenset({"aspect", "width", "height", "fps", "fit"}),
139
+ "transition": frozenset({"type", "duration"}),
140
+ "silence": frozenset({"threshold", "min_silence", "margin", "margin_lead", "margin_tail"}),
141
+ # 1.16: the picture an audio-only source gets before the rest of the chain can work on it
142
+ "audiogram": frozenset({"image", "image_fit", "style", "position", "vis_height", "opacity",
143
+ "platform", "title", "color", "background", "width", "height", "fps"}),
144
+ # 1.17.1: fit_size / min_size / fit_size_scope, so a project can state the fit policy the
145
+ # templates now default to (eval 18 cs1 hit "unknown key 'fit_size'" and hand-ran the stages).
146
+ "captions": frozenset({"text", "srt", "ass", "font", "size", "color", "position", "margin",
147
+ "animate", "highlight_color", "outline", "karaoke", "bold", "box",
148
+ "lang", "offset", "max_lines", "min_duration",
149
+ "fit_size", "min_size", "fit_size_scope"}),
150
+ # the 1.14 social templates (sticker/hook/meme) take their own text and timing, so a
151
+ # graphics[] entry can carry them too -- a template that only works from the CLI is not
152
+ # "usable inside a render.py graphics[] entry" (review 12)
153
+ "graphics[]": frozenset({"template", "name", "title", "subtitle", "start", "end", "position",
154
+ "from", "scale", "primary", "text_color", "lang",
155
+ "text", "top", "bottom", "duration", "margin", "platform"}),
156
+ # #326: "video" is a fourth layer kind (overlay.py --video), keyed with the chromakey* keys
157
+ "overlays[]": frozenset({"logo", "image", "text", "position", "start", "end", "fade", "opacity",
158
+ "scale", "font_size", "font", "font_file", "margin", "box", "platform",
159
+ "video", "chromakey", "chromakey_similarity", "chromakey_blend"}),
160
+ "audio": frozenset({"music", "replace", "music_volume", "fade_in", "fade_out", "music_fade_out",
161
+ "gain", "duck_amount", "duck_threshold", "duck_attack", "duck_release",
162
+ "voice", "denoise", "duck", "music_loop", "stereo", "mono", "downmix",
163
+ "stereo_widen", "effects", "effects_volume", "stems"}),
164
+ "audio.stems": frozenset({"dialogue", "music", "effects"}),
165
+ "chapters[]": frozenset({"at", "title"}),
166
+ "loudness": frozenset({"lufs", "tp"}),
167
+ "fit": frozenset({"duration", "method", "aspect", "fit", "width", "height", "fps", "smooth"}),
168
+ "export": frozenset({"preset", "fit", "crf", "normalize"}),
169
+ "check": frozenset({"platform", "content"}),
170
+ }
171
+ # Typos difflib cannot see: a clip is trimmed with in/out, not the start/end that time a title.
172
+ NEAR_KEYS: Dict[str, Dict[str, str]] = {"clips[]": {"start": "in", "end": "out", "from": "in", "to": "out"},
173
+ "audio.stems": {"voice": "dialogue", "speech": "dialogue", "sfx": "effects", "bed": "music"},
174
+ "chapters[]": {"start": "at", "time": "at", "name": "title"}}
175
+
176
+
177
+ def template_names() -> List[str]:
178
+ """Every templates/<name>.json that ships with the skill."""
179
+ return sorted(p.stem for p in TEMPLATE_DIR.glob("*.json"))
180
+
181
+
182
+ def load_template(name: str) -> Dict[str, Any]:
183
+ path = TEMPLATE_DIR / f"{name}.json"
184
+ if not path.is_file():
185
+ die(f"unknown template {name!r}", hint="templates: " + ", ".join(template_names()) + " (or 'all')")
186
+ try:
187
+ return read_json(path)
188
+ except (OSError, ValueError) as exc:
189
+ die(f"cannot read template {path}: {exc}")
190
+ return {}
191
+
192
+
193
+ def fill_template(node: Any, values: Dict[str, Any]) -> "tuple":
194
+ """Substitute the $PLACEHOLDERS a template carries; return (filled, complete).
195
+
196
+ complete=False means a placeholder in this node had no value, and the caller drops the
197
+ whole block: a template's overlay entry is `{"image": "$LOGO"}`, so a run without --logo
198
+ must lose the overlay entirely rather than render an overlay of nothing."""
199
+ if isinstance(node, str):
200
+ if node in PLACEHOLDERS:
201
+ value = values.get(node)
202
+ return value, value is not None
203
+ return node, True
204
+ if isinstance(node, list):
205
+ kept = []
206
+ for item in node:
207
+ filled, ok = fill_template(item, values)
208
+ if ok:
209
+ kept.append(filled)
210
+ return kept, True
211
+ if isinstance(node, dict):
212
+ out: Dict[str, Any] = {}
213
+ complete = True
214
+ for key, value in node.items():
215
+ filled, ok = fill_template(value, values)
216
+ if not ok:
217
+ complete = False
218
+ continue
219
+ out[key] = filled
220
+ return out, complete
221
+ return node, True
222
+
223
+
224
+ def brand_states_caption_size(path: Optional[str]) -> bool:
225
+ """True only when a brand file actually names a caption size. `--brand` alone says nothing
226
+ about type size -- brand_caption_style() applies no defaults -- so the presence of the flag
227
+ must not switch caption.py's `--fit-size auto` off (review 17 finding 1)."""
228
+ if not path or not os.path.isfile(path):
229
+ return False
230
+ try:
231
+ stated = load_brand(path).get("_stated") or {}
232
+ except SystemExit:
233
+ raise
234
+ except Exception:
235
+ return False
236
+ # BRAND_DEFAULTS always supplies caption.size, so only what the FILE said can answer this
237
+ # (the same reason brand_states_font() exists).
238
+ return brand_caption_style(stated).get("size") is not None
239
+
240
+
241
+ def template_project(name: str, args) -> Dict[str, Any]:
242
+ """One template plus the run's arguments as a ready-to-render project."""
243
+ tpl = load_template(name)
244
+ dest = str((tpl.get("check") or {}).get("platform") or name)
245
+ if args.srt and isinstance(tpl.get("captions"), dict) and "text" in tpl["captions"]:
246
+ cap = {("srt" if k == "text" else k): ("$SRT" if k == "text" else v) for k, v in tpl["captions"].items()}
247
+ tpl["captions"] = cap
248
+ # The caption block's size and margin are the table's, not a literal restated in the JSON:
249
+ # change a destination's safe zone in scripts/_platforms.py and every template follows.
250
+ if isinstance(tpl.get("captions"), dict) and dest in PLATFORMS and PLATFORMS[dest].get("frame"):
251
+ defaults = caption_defaults(dest)
252
+ tpl["captions"]["size"] = defaults["size"]
253
+ tpl["captions"]["margin"] = defaults["margin"]
254
+ for key in ("position", "animate", "outline"):
255
+ tpl["captions"].setdefault(key, defaults[key])
256
+ # 1.17.1: that size is the table's default, not a size anyone asked for, so it must not
257
+ # switch off caption.py's `--fit-size auto` the way a stated --size does -- eval 18 saw a
258
+ # long cue split across two consecutive cues instead of the type shrinking to fit. A
259
+ # template that states "fit_size" wins, and so does a brand file that STATES a caption
260
+ # size (that size is a statement about the look). A brand of colours or a font alone
261
+ # states no size, so it must not stand the fitter down: review 17 finding 1.
262
+ if not brand_states_caption_size(args.brand):
263
+ tpl["captions"].setdefault("fit_size", "on")
264
+ output = args.output or str(template_output(args.input, name, dest))
265
+ values = {
266
+ "$INPUT": os.path.abspath(args.input),
267
+ "$OUTPUT": os.path.abspath(output),
268
+ "$CUES": os.path.abspath(args.cues) if args.cues else None,
269
+ "$SRT": os.path.abspath(args.srt) if args.srt else None,
270
+ "$LOGO": os.path.abspath(args.logo) if args.logo else None,
271
+ "$BRAND": os.path.abspath(args.brand) if args.brand else None,
272
+ "$CHAPTERS": os.path.abspath(args.chapters) if args.chapters else None,
273
+ "$TITLE": args.title,
274
+ "$IMAGE": os.path.abspath(args.image) if args.image else None,
275
+ }
276
+ for flag, path in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),
277
+ ("--brand", args.brand), ("--chapters", args.chapters), ("--image", args.image)):
278
+ if path and not os.path.isfile(path):
279
+ die(f"{flag}: file {absent_word(path)}: {path}")
280
+ audiogram = tpl.get("audiogram")
281
+ if isinstance(audiogram, dict) and "$IMAGE" in audiogram.values() and not args.image and not args.write_project:
282
+ # A89: without --image the whole audiogram block was dropped as an unfilled placeholder,
283
+ # so the dry run planned a render with no picture and the real one failed at the export
284
+ # ("input has no video stream"). --write-project still writes the project to edit.
285
+ die(f"--template {name} draws the sound over a still picture and needs --image FILE "
286
+ "(a local file: nothing is fetched and no cover art is invented)",
287
+ hint='for a plain colour behind the waveform, write the project with --write-project and give it '
288
+ '"audiogram": {"background": COLOUR}')
289
+ proj, _ = fill_template(tpl, values)
290
+ if args.fit:
291
+ proj.setdefault("frame", {})["fit"] = args.fit
292
+ return proj
293
+
294
+
295
+ def template_ext(dest: str) -> str:
296
+ """A destination with no frame delivers audio: the podcast template writes .m4a, not .mp4."""
297
+ return ".mp4" if (PLATFORMS.get(dest) or {}).get("frame") else ".m4a"
298
+
299
+
300
+ def template_output(input_path: str, name: str, dest: str) -> Path:
301
+ """Where a template writes when no -o was given: next to the input, named after it and the
302
+ template. One rule for a single template and for a pack, so `--template tiktok` and
303
+ `--template tiktok,x` put their files in the same place (review 12)."""
304
+ stem = Path(input_path).with_suffix("").name
305
+ return Path(input_path).resolve().parent / f"{stem}_{name}{template_ext(dest)}"
306
+
307
+
308
+ def list_templates() -> None:
309
+ """The templates, the destination each delivers to, and the zones its UI covers: a table, or
310
+ under --json one row per template in `templates` (A102: the table was printed under --json)."""
311
+ rows: List[Dict[str, Any]] = []
312
+ if not STATE.json:
313
+ print("%-15s %-11s %-5s %7s %-10s %s" % ("template", "frame", "fit", "max", "loudness", "safe zones (fraction of the frame)"))
314
+ for name in template_names():
315
+ tpl = load_template(name)
316
+ dest = str((tpl.get("check") or {}).get("platform") or name)
317
+ plat = PLATFORMS.get(dest) or {}
318
+ frame = plat.get("frame")
319
+ spec = plat.get("spec") or {}
320
+ safe = plat.get("safe") or {}
321
+ dur = spec.get("max_duration")
322
+ zones = ", ".join("%s %.2f" % (edge, safe.get(edge, 0)) for edge in ("top", "bottom", "left", "right") if safe.get(edge))
323
+ size = "%dx%d" % (frame["w"], frame["h"]) if frame else "audio"
324
+ fit = str((tpl.get("frame") or {}).get("fit") or "-")
325
+ loud = ("%g LUFS" % spec["lufs"]) if spec.get("lufs") is not None else "-"
326
+ rows.append({"template": name, "destination": dest, "frame": {"width": frame["w"], "height": frame["h"]} if frame else None,
327
+ "fit": None if fit == "-" else fit, "max_duration": dur, "lufs": spec.get("lufs"),
328
+ "safe": {edge: safe.get(edge, 0) for edge in ("top", "bottom", "left", "right")}})
329
+ if not STATE.json:
330
+ print("%-15s %-11s %-5s %7s %-10s %s" % (name, size, fit, ("%gs" % dur) if dur else "-", loud, zones or "none"))
331
+ if STATE.json:
332
+ emit(None, templates=rows, stages=[], check=None)
333
+
334
+
335
+ # `--template all`: every destination a single edit is normally posted to. The podcast template
336
+ # is audio-only and youtube-shorts is an alias of shorts, so neither belongs in a video pack.
337
+ PACK_DEFAULT = ["tiktok", "reels", "shorts", "youtube", "x", "linkedin", "facebook"]
338
+
339
+
340
+ def expand_templates(value: str) -> List[str]:
341
+ if value.strip() == "all":
342
+ return list(PACK_DEFAULT)
343
+ names = [n.strip() for n in value.split(",") if n.strip()]
344
+ if not names:
345
+ die("--template needs a name, a comma-separated list, or 'all'")
346
+ known = template_names()
347
+ seen: List[str] = []
348
+ for name in names:
349
+ # the spellings people write resolve to the destination they mean, the same way
350
+ # check.py --platform and export.py --preset take them (scripts/_platforms.py)
351
+ if name not in known:
352
+ name = resolve_platform(name) or name
353
+ if name not in known:
354
+ die(f"unknown template {name!r}", hint="templates: " + ", ".join(known) + " (or 'all')")
355
+ if name not in seen:
356
+ seen.append(name)
357
+ return seen
358
+
359
+
360
+ def md_line(text: Any) -> str:
361
+ """Caller text on one Markdown line: each line break (any str.splitlines() boundary) and other
362
+ control character becomes a space, so a file name cannot start a line of its own (A263)."""
363
+ return "".join(" " if (ch in "\x85\u2028\u2029" or ord(ch) < 32 or ord(ch) == 127) else ch for ch in str(text))
364
+
365
+
366
+ def md_cell(text: Any) -> str:
367
+ """Caller text in one cell of a GFM table row: on one line (md_line()), a backslash doubled
368
+ and a '|' escaped as '\\|', so `a | b.mp4` stays in its column. report.py --pack reads the
369
+ escapes back (A263: the columns shifted and passing destinations were reported failed)."""
370
+ return md_line(text).replace("\\", "\\\\").replace("|", "\\|")
371
+
372
+
373
+ def render_pack(names: List[str], args) -> int:
374
+ """The social pack: one edit delivered to every named destination, plus a table of what
375
+ was written. Each destination is a full render (its own frame, captions, loudness, export
376
+ and platform check), so the pack reports per-platform results rather than one verdict."""
377
+ stem = Path(args.input).with_suffix("").name
378
+ outdir = Path(args.output).parent if args.output else Path(args.input).resolve().parent
379
+ # the table is a file this run writes itself (#408): an existing one is refused without
380
+ # --overwrite, before the first destination renders
381
+ if outdir.is_dir(): # a missing folder is the destinations' own refusal (and a dry run's plan)
382
+ side = [v for k, v in vars(args).items() if k != "output" and isinstance(v, str) and os.path.isfile(v)]
383
+ guard_sidecar(str(outdir / f"{stem}_pack.md"), args.input, *side)
384
+ dests = {name: str((load_template(name).get("check") or {}).get("platform") or name) for name in names}
385
+ rows: List[Dict[str, Any]] = []
386
+ outputs: List[str] = []
387
+ failed: List[str] = []
388
+ stopped: List[Dict[str, Any]] = [] # destinations a timeout stopped: {kind, exit_code}
389
+ for name in names:
390
+ # the destination decides the container: an audio-only destination in a pack must not be
391
+ # handed a .mp4 name the single-template form would never have written (review 12)
392
+ dest_out = str(outdir / (stem + "_" + name + template_ext(dests[name])))
393
+ argv = [str(HERE / "render.py"), args.input, "--template", name, "-o", dest_out]
394
+ for flag, value in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),
395
+ ("--title", args.title), ("--brand", args.brand), ("--fit", args.fit),
396
+ ("--chapters", args.chapters), ("--image", args.image),
397
+ ("--intermediate-preset", args.intermediate_preset)):
398
+ if value:
399
+ argv += option_args(flag, value)
400
+ if STATE.audit_log:
401
+ argv += option_args("--audit-log", STATE.audit_log) # every destination's records, in the one file asked for
402
+ info(f"→ pack: {name}")
403
+ proc = run_tool(argv + child_args() + ["--json"])
404
+ try:
405
+ doc = json.loads(proc.stdout.strip() or "{}")
406
+ except ValueError:
407
+ doc = {}
408
+ # the child ran with --json, so its planned commands come back in the document: the pack
409
+ # is the one path that writes seven files, and --dry-run has to show all of them
410
+ STATE.commands.extend(text for is_command, text in stderr_records(proc.stderr) if is_command)
411
+ STATE.commands.extend(str(c) for c in (doc.get("commands") or []))
412
+ absorb_stage(name, doc)
413
+ out = doc.get("output") or dest_out
414
+ chk = doc.get("check") or {}
415
+ ok = proc.returncode == 0 and doc.get("status") == "completed"
416
+ probe_doc = doc.get("probe") or {}
417
+ if STATE.dry_run:
418
+ # A dry run encoded nothing and verified nothing. Reading a size off a file left over
419
+ # from an earlier real run, or calling an unrun check "pass", reports a verification
420
+ # result for a run that never happened (review 12).
421
+ rows.append({"platform": name, "file": os.path.basename(out), "path": out,
422
+ "size_bytes": None, "duration": None, "check": "planned", "ok": bool(ok)})
423
+ continue
424
+ size = os.path.getsize(out) if os.path.exists(out) else 0
425
+ rows.append({"platform": name, "file": os.path.basename(out), "path": out,
426
+ "size_bytes": size, "duration": probe_doc.get("duration"),
427
+ # a destination whose check did not run is "not checked", not "pass" (the class of A113)
428
+ "check": ("pass" if chk.get("ok") else ("%d FAIL" % chk["failed"]) if chk.get("failed") else ("not checked" if ok else "failed")),
429
+ # #485: a destination over the table's upload limit passes its check with a
430
+ # WARN; the pack keeps which, so the row is not a bare "pass"
431
+ "guidance": guidance_warns(chk),
432
+ "ok": bool(ok)})
433
+ outputs.append(out)
434
+ if not ok:
435
+ failed.append(name)
436
+ err = doc.get("error") or {}
437
+ if err.get("kind") in ("timeout", "interrupted"):
438
+ stopped.append({"kind": err["kind"], "exit_code": child_exit_code(doc, proc.returncode)})
439
+ pack = str(outdir / f"{stem}_pack.md")
440
+ lines = [f"# Social pack — {md_line(stem)}", "",
441
+ "| platform | file | size | duration | check |", "|---|---|---|---|---|"]
442
+ for r in rows:
443
+ dur = f"{r['duration']:.2f} s" if r.get("duration") else "-"
444
+ mb = f"{r['size_bytes'] / 1024 / 1024:.1f} MB" if r.get("size_bytes") else "-"
445
+ verdict = r["check"] + (f" (upload-limit guidance: {'; '.join(r['guidance'])})" if r.get("guidance") else "")
446
+ lines.append("| " + " | ".join(md_cell(c) for c in (r["platform"], r["file"], mb, dur, verdict)) + " |")
447
+ lines += ["", f"{len(rows)} destinations from one edit ({md_line(os.path.basename(args.input))}).",
448
+ "Rendered by ffmpeg-skill; `report.py --pack` turns this table into an HTML report."]
449
+ if not STATE.dry_run:
450
+ if not outdir.is_dir():
451
+ die(f"pack: the output folder {outdir} does not exist, so the table was not written", kind="input",
452
+ pack=rows, outputs=outputs)
453
+ Path(pack).write_text("\n".join(lines) + "\n", encoding="utf-8")
454
+ info(("[dry-run] would write " if STATE.dry_run else "wrote ") + pack)
455
+ if failed:
456
+ # a destination that was stopped makes the pack a stopped run: its kind and exit code (124,
457
+ # 130/143), as a stage's are render.py's (docs/contract.md); otherwise a verification failure
458
+ die(f"pack: {len(failed)} of {len(rows)} destinations failed: {', '.join(failed)}",
459
+ code=stopped[0]["exit_code"] if stopped else 1, kind=stopped[0]["kind"] if stopped else "verification",
460
+ output=pack, dry_run=STATE.dry_run, pack=rows, outputs=outputs)
461
+ emit(pack, pack=rows, outputs=outputs, stages=["pack"],
462
+ # a destination whose check did not run has no check step: "not checked" is not ok: true
463
+ verification=[{"step": "check", "ok": True, "platform": r["platform"]} for r in rows if r["check"] == "pass"])
464
+ return 0
465
+
466
+
467
+ def check_keys(obj: Any, schema: str, label: str) -> None:
468
+ """Refuse an unrecognised key, naming the object, the key and the nearest valid one. A value
469
+ that is not an object is require_object()'s to refuse, and only where the run reads it."""
470
+ if not isinstance(obj, dict):
471
+ return
472
+ valid = OBJECT_KEYS[schema]
473
+ for key in obj:
474
+ if key in valid:
475
+ continue
476
+ near = NEAR_KEYS.get(schema, {}).get(str(key)) or next(iter(difflib.get_close_matches(str(key), sorted(valid), n=1, cutoff=0.6)), None)
477
+ die(f"{label}: unknown key {key!r}" + (f" (did you mean {near!r}?)" if near
478
+ else f" (valid keys: {', '.join(sorted(valid))})"))
479
+
480
+
481
+ def check_overlay(ov: Any, label: str, rendered: bool = True) -> None:
482
+ """#326: a video layer is one kind of overlay, as overlay.py's --image/--text/--logo/--video
483
+ are one mutually exclusive choice, and the chromakey* keys only act on it. A logo, image and
484
+ text in one entry still draw the first of them, as before; only a combination with the new
485
+ "video" key is refused, so no project 2.8.6 rendered is refused now."""
486
+ if not isinstance(ov, dict):
487
+ return
488
+ if ov.get("video"):
489
+ others = [k for k in ("logo", "image", "text") if ov.get(k)]
490
+ if others:
491
+ die(f"{label}: give one of logo, image, text or video per entry, not video and {others[0]} "
492
+ "(add a second overlays[] entry for the other layer)")
493
+ else:
494
+ keyed = [k for k in ("chromakey", "chromakey_similarity", "chromakey_blend") if ov.get(k) is not None]
495
+ if keyed:
496
+ die(f"{label}: {keyed[0]} keys a colour out of a video layer and needs \"video\" (overlay.py --chromakey needs --video)")
497
+ if rendered and ov.get("video") and ov.get("fade"):
498
+ # A171: overlay.py --video has no fade; the layer was composited with a hard edge. Only a
499
+ # run that composites the layer refuses it: an export or a preview that stops before the
500
+ # overlays never read the entry, and completed
501
+ die(f"{label}: fade fades an image, logo or text layer; a video layer is shown from start to end "
502
+ "without one (drop \"fade\" from this entry)", kind="input")
503
+ if ov.get("chromakey") is None:
504
+ tuned = [k for k in ("chromakey_similarity", "chromakey_blend") if ov.get(k) is not None]
505
+ if tuned:
506
+ die(f"{label}: {tuned[0]} tunes \"chromakey\", which this entry does not set")
507
+ # scale is a layer width (overlay.py --scale). A text entry that carries it used to complete
508
+ # with the default font size, because the text branch never reads the flag.
509
+ if ov.get("text") and not any(ov.get(k) for k in ("logo", "image", "video")) and ov.get("scale") is not None:
510
+ die(f"{label}: scale sizes an image, logo or video layer; text size is font_size", kind="input")
511
+
512
+
513
+ def project_input_files(proj: Dict[str, Any], rel: Any) -> List[str]:
514
+ """Every file a project names as an input: clip sources, music/replace/effects, the brand,
515
+ caption files (a --text value that names an existing file), overlay images, videos and fonts, the
516
+ audiogram image, a beat grid's source and the chapters file. Values of the wrong type are left
517
+ to the stage that reads them."""
518
+ found: List[str] = []
519
+
520
+ def add(value: Any, must_exist: bool = False) -> None:
521
+ if isinstance(value, str) and value:
522
+ p = rel(value)
523
+ if not must_exist or os.path.isfile(p):
524
+ found.append(p)
525
+
526
+ clips = proj.get("clips")
527
+ for c in clips if isinstance(clips, list) else []: # a wrong type is validate_project()'s to refuse
528
+ if isinstance(c, dict):
529
+ add(c.get("src"))
530
+ if isinstance(c.get("snap"), dict):
531
+ add(c["snap"].get("source"))
532
+ for key in ("audio", "captions", "audiogram", "snap"):
533
+ if not isinstance(proj.get(key), dict):
534
+ continue
535
+ obj = proj[key]
536
+ if key == "audio":
537
+ for k in ("music", "replace", "effects"):
538
+ add(obj.get(k))
539
+ elif key == "captions":
540
+ add(obj.get("srt"))
541
+ add(obj.get("ass"))
542
+ add(obj.get("text"), must_exist=True) # inline cue text is not a path
543
+ elif key == "audiogram":
544
+ add(obj.get("image"))
545
+ else:
546
+ add(obj.get("source"))
547
+ add(proj.get("brand"))
548
+ brand = proj.get("brand")
549
+ if isinstance(brand, str) and brand:
550
+ # the brand's own logo and font_file are read by the overlay and caption stages, resolved
551
+ # against the brand file as load_brand() resolves them; an unreadable brand is left to them
552
+ try:
553
+ data = read_json(rel(brand))
554
+ except (OSError, ValueError):
555
+ data = None
556
+ if isinstance(data, dict):
557
+ base = Path(rel(brand)).resolve().parent
558
+ for k in ("logo", "font_file"):
559
+ v = data.get(k)
560
+ if isinstance(v, str) and v and "://" not in v:
561
+ found.append(v if os.path.isabs(v) else str(base / v))
562
+ add(proj.get("chapters"), must_exist=True)
563
+ overlays = proj.get("overlays")
564
+ for ov in (overlays if isinstance(overlays, list) else []): # any other type is the overlay stage's to refuse
565
+ if isinstance(ov, dict):
566
+ add(ov.get("image"))
567
+ add(ov.get("video"))
568
+ add(ov.get("font_file"))
569
+ return found
570
+
571
+
572
+ def require_object(obj: Any, label: str) -> None:
573
+ """Refuse a value that is not an object where the run reads it with .get(): "export": "reels"
574
+ in a render, a string frame, a clip written as a bare path. 2.2.1 died there with a traceback
575
+ and nothing on stdout under --json. null, false and {} still ask for nothing."""
576
+ if obj and not isinstance(obj, dict):
577
+ die(f"{label}: must be an object {{...}}, got {type(obj).__name__} {obj!r:.60}")
578
+
579
+
580
+ # the stage that first reads each section; --stop-after before it means the run never reads it
581
+ READ_AT = {"transition": "join", "silence": "silence", "fit": "fit", "captions": "captions",
582
+ "graphics": "graphics", "overlays": "overlays", "loudness": "loudness", "export": "export",
583
+ "check": "check"}
584
+ _READ_ORDER = ["clips", "join", "silence", "fit", "captions", "graphics", "overlays", "audio", "loudness", "export", "check"]
585
+
586
+
587
+ def _reaches(stage: str, stop_after: Optional[str]) -> bool:
588
+ return not stop_after or _READ_ORDER.index(stage) <= _READ_ORDER.index(stop_after)
589
+
590
+
591
+ def validate_project(proj: Dict[str, Any], timeline: bool = False, stop_after: Optional[str] = None) -> None:
592
+ """Every project error the run would hit, before the first ffmpeg call. A value that is not
593
+ an object is refused only where this run reads it (require_object()): a full render reads
594
+ every stage's section, a transition only between two or more clips and a clip's snap only
595
+ on a clip it cuts; --export-timeline (`timeline`) reads the clips, frame, audio and a
596
+ transition between clips, and only names the other sections in not_exported. 2.2.1 rendered
597
+ a single clip with "transition": "none" and exported "captions": "subs.srt", reading neither,
598
+ and a patch release does not refuse them."""
599
+ check_keys(proj, "project", "project")
600
+ clips = proj.get("clips")
601
+ # the join (or the timeline's dissolves) reads the transition; an audiogram render joins nothing
602
+ several = isinstance(clips, list) and len(clips) > 1 and (timeline or not proj.get("audiogram"))
603
+ read = {"frame", "audio"} | ({"transition"} if several else set())
604
+ if not timeline:
605
+ read |= {"silence", "audiogram", "captions", "loudness", "fit", "export", "check", "snap"}
606
+ # --stop-after ends the run before later stages read their sections: 2.2.1 completed a
607
+ # `--stop-after fit` preview of a project with "captions": "subs.srt", never reading it
608
+ read = {n for n in read if n not in READ_AT or _reaches(READ_AT[n], stop_after)}
609
+ for name in ("frame", "transition", "silence", "audiogram", "captions", "audio", "loudness", "fit", "export", "check", "snap"):
610
+ if name in read:
611
+ require_object(proj.get(name), name)
612
+ check_keys(proj.get(name), name, name)
613
+ check_keys((proj.get("audio") or {}).get("stems"), "audio.stems", "audio.stems")
614
+ # the values the run reads with .get() or as a dict key: a list there was a traceback (A13)
615
+ audio = proj.get("audio")
616
+ if "audio" in read and isinstance(audio, dict):
617
+ require_object(audio.get("stems"), "audio.stems")
618
+ export = proj.get("export")
619
+ if "export" in read and isinstance(export, dict) and export.get("preset") and not isinstance(export["preset"], str):
620
+ die(f"export.preset: must be a preset name (a string), got {type(export['preset']).__name__} "
621
+ f"{export['preset']!r:.60}")
622
+ if isinstance(proj.get("chapters"), list):
623
+ # Every other project error is raised here, before the first ffmpeg call; a chapter typo
624
+ # found inside the last stage costs a whole render and leaves an unchaptered file behind.
625
+ for i, item in enumerate(proj["chapters"]):
626
+ if isinstance(item, dict):
627
+ check_keys(item, "chapters[]", f"chapters[{i}]")
628
+ if not isinstance(item, dict) or item.get("at") is None or not str(item.get("title") or "").strip():
629
+ die(f'chapters[{i}]: needs {{"at": TIME, "title": STR}}')
630
+ # the chapters stage writes one `TIME TITLE` line per chapter for metadata.py, which
631
+ # reads a line break as the end of the chapter (a CR too: the file is read as text) and
632
+ # FFmpeg ends a title at NUL: "Intro\n0:01 Evil" was two chapters, verified (A260)
633
+ bad = next((ch for ch in str(item["title"]) if ch in "\n\r\x00"), None)
634
+ if bad is not None:
635
+ die(f"chapters[{i}].title: holds U+{ord(bad):04X} ({'NUL' if bad == chr(0) else 'a line break'}), which "
636
+ "a chapter title cannot carry -- a title is one line of text; remove it", kind="input")
637
+ for name in ("clips", "graphics", "overlays"):
638
+ items = proj.get(name)
639
+ if name == "clips" or (not timeline and _reaches(READ_AT[name], stop_after)): # the export reads only the clips
640
+ if items and not isinstance(items, list):
641
+ die(f"{name}: must be a list of objects [{{...}}], got {type(items).__name__} {items!r:.60}")
642
+ for i, item in enumerate(items or []):
643
+ if not isinstance(item, dict):
644
+ die(f"{name}[{i}]: must be an object {{...}}, got {type(item).__name__} {item!r:.60}")
645
+ for i, item in enumerate(items if isinstance(items, list) else []):
646
+ check_keys(item, f"{name}[]", f"{name}[{i}]")
647
+ if name == "overlays":
648
+ check_overlay(item, f"overlays[{i}]",
649
+ rendered=not timeline and _reaches(READ_AT["overlays"], stop_after))
650
+ if name != "clips":
651
+ continue
652
+ # every clip stage starts from rel(c["src"]): without one it was a KeyError traceback
653
+ if not item.get("src"):
654
+ die(f"clips[{i}]: no src")
655
+ if item.get("speed") and not timeline:
656
+ # the clips stage reads float(speed): "fast" or [2] was a traceback there (A13)
657
+ try:
658
+ spd = float(item["speed"])
659
+ except (TypeError, ValueError):
660
+ spd = float("nan")
661
+ if not (0 < spd < float("inf")):
662
+ die(f"clips[{i}]: speed must be a positive number, got {item['speed']!r:.60}")
663
+ if item.get("snap") is not None:
664
+ # the render reads a clip's snap only on a clip it cuts (in/out), the export never
665
+ if not timeline and (item.get("in") is not None or item.get("out") is not None):
666
+ require_object(item["snap"], f"clips[{i}].snap")
667
+ # A93: only the project's own snap.to was checked, so a clip's "beat" (or an
668
+ # unsupported grid) was read as "not beats" and the cut rendered unsnapped
669
+ check_snap_to(item["snap"], f"clips[{i}].snap")
670
+ check_keys(item["snap"], "snap", f"clips[{i}].snap")
671
+ if not timeline and "audiogram" in read and proj.get("audiogram") and isinstance(clips, list) and len(clips) > 1:
672
+ # A92: the audiogram stage draws the first clip's sound and the render carries on from
673
+ # that one file: every other clip was cut and then left out of the output without a word
674
+ die(f"audiogram: an audiogram is drawn from one audio source, and this project has {len(clips)} clips "
675
+ "(only the first would be in the output); join them first (join.py) and name the joined file as the one clip")
676
+ chapters = proj.get("chapters")
677
+ if chapters and not isinstance(chapters, (str, list)):
678
+ # A94: a number or an object was handed to metadata.py as a file name by the last stage,
679
+ # after the whole render ("chapters file not found: .../5"). false and 0 are "no chapters",
680
+ # as the stage's own `if ch:` reads them, and stay that
681
+ die(f'chapters: must be a chapters file path or a list of {{"at": TIME, "title": STR}}, got '
682
+ f"{type(chapters).__name__} {chapters!r:.60}")
683
+
684
+
685
+ def check_snap_to(snap: Any, label: str) -> None:
686
+ """Refuse a snap grid other than beats, for the project's `snap` and for a clip's own."""
687
+ if isinstance(snap, dict) and str(snap.get("to") or "") not in ("", "none", "beats"):
688
+ die(f'{label}.to: only "beats" (or "none") is a beat grid this skill can measure, got '
689
+ f'{snap.get("to")!r}', kind="input")
690
+
691
+
692
+ _LAST_DOC: Dict[str, Any] = {} # the JSON document the most recent sh() child printed
693
+
694
+ # source_carry for a render (A255): the one picture/sound source of a project with one, and what
695
+ # each stage that ran said about the start timecode ("kept", "dropped", None: a stage that compared
696
+ # nothing, "unknown": a cache hit whose entry did not keep it). main() resets both.
697
+ PROJECT_SOURCE: Dict[str, Any] = {"src": None, "timecode": []}
698
+
699
+
700
+ def _timecode_verdict(doc: Any) -> Optional[str]:
701
+ """What a stage's document says about the start timecode: "kept", "dropped", or None when its
702
+ source_carry compared none."""
703
+ carry = doc.get("source_carry") if isinstance(doc, dict) else None
704
+ if not isinstance(carry, dict):
705
+ return None
706
+ return "dropped" if "timecode" in (carry.get("dropped") or []) else "kept" if "timecode" in (carry.get("kept") or []) else None
707
+
708
+
709
+ def project_source(proj: Dict[str, Any], rel) -> Optional[str]:
710
+ """The project's single picture/sound source -- its clips all one file, and no music,
711
+ replacement or effects track, no video layer and no audiogram picture beside it -- or None,
712
+ when the output mixes several (source_carry is then not compared, as for any tool with two
713
+ sources)."""
714
+ srcs = {os.path.realpath(rel(c["src"])) for c in proj.get("clips") or [] if isinstance(c, dict) and isinstance(c.get("src"), str)}
715
+ audio = proj.get("audio") if isinstance(proj.get("audio"), dict) else {}
716
+ others = [audio.get(k) for k in ("music", "replace", "effects") if audio.get(k)]
717
+ overlays = proj.get("overlays") if isinstance(proj.get("overlays"), list) else []
718
+ others += [ov.get("video") for ov in overlays if isinstance(ov, dict) and ov.get("video")]
719
+ if proj.get("audiogram"):
720
+ others.append("audiogram") # the picture is the waveform over an image, not the clip's
721
+ return next(iter(srcs)) if len(srcs) == 1 and not others else None
722
+
723
+
724
+ def emit(output: Optional[str], **extra: Any) -> None:
725
+ """emit(), with render.py's source_carry: the stages run as children, so this process never
726
+ probed the project's source as an input and its result carried no source_carry at all, even
727
+ for a one-clip render that lost the source's subtitle track (A255). The source is probed here
728
+ (after the stages' intermediates, which are not sources), so emit() compares it with the
729
+ delivered file. A stage that moves the picture's start writes the label of the frame it starts
730
+ on, which is not the source's: the timecode counts as kept when every stage that compared it
731
+ kept it, as dropped when one dropped it, and is compared with the source's own label when no
732
+ stage said (nothing ran, or a cache entry written before stages' source_carry was kept)."""
733
+ src = PROJECT_SOURCE.get("src")
734
+ if src and output and not STATE.dry_run and os.path.isfile(src) and os.path.isfile(output) \
735
+ and os.path.realpath(src) != os.path.realpath(output) and "source_carry" not in extra:
736
+ STATE.first_input, STATE.video_inputs, STATE.audio_inputs = None, set(), set()
737
+ probe(src)
738
+ said = PROJECT_SOURCE["timecode"]
739
+ if "dropped" in said:
740
+ STATE.expected_timecode = ""
741
+ elif "kept" in said and "unknown" not in said:
742
+ STATE.expected_timecode = (probe(output, role="output").get("timecode") or {}).get("value") or ""
743
+ else:
744
+ STATE.expected_timecode = None
745
+ _emit(output, **extra)
746
+
747
+
748
+ def _refuse_uncached_earlier_stage(stage: str) -> None:
749
+ """--from STAGE promises the earlier stages come from the cache. When one does not, say so
750
+ rather than quietly re-encoding the thing the caller asked to skip."""
751
+ target = CACHE.get("from")
752
+ if not target or stage not in STAGE_ORDER or target not in STAGE_ORDER:
753
+ return
754
+ if STAGE_ORDER.index(stage) < STAGE_ORDER.index(target):
755
+ die(f"--from {target}: the {stage} stage is not in {CACHE['dir']} for this project and "
756
+ "these inputs, so there is nothing to start from. Render once without --from to fill "
757
+ "the cache (note that a different ffmpeg build or skill version never reuses one).",
758
+ kind="input")
759
+
760
+
761
+ def sh(script: str, *argv: Any, extra: List[str] = None, stage: str = None) -> str:
762
+ """Run a sibling script, forwarding --fast / --dry-run, returning its printed output path.
763
+
764
+ With --cache and a named `stage`, an identical stage that ran before is served from the
765
+ cache instead of re-encoded. `stages_done` is unchanged either way: a cached stage is still
766
+ a stage that happened.
767
+ """
768
+ if (INTERMEDIATE["preset"] and script in _X264_STAGES
769
+ and "--preset" not in [str(a) for a in argv] + (extra or [])):
770
+ extra = (extra or []) + ["--preset", INTERMEDIATE["preset"]]
771
+ if not INTERMEDIATE["applied"]:
772
+ info(f"intermediate stages: preset {INTERMEDIATE['preset']} (the export re-encodes them; "
773
+ "--intermediate-preset medium for the stages' own default)")
774
+ INTERMEDIATE["applied"] = True
775
+ full = [str(a) for a in argv] + (extra or [])
776
+ dest = full[full.index("-o") + 1] if "-o" in full[:-1] else None
777
+ key = None
778
+ if stage and CACHE.get("dir") and dest:
779
+ inputs = [a for a in full if os.path.exists(a) and a != dest]
780
+ # The destination is where this stage's answer goes, not part of the question: hashing it
781
+ # would make a second run with the first run's output already on disk miss every time.
782
+ key_args = ["<out>" if a == dest else a for a in full]
783
+ key_files = {a for a in key_args if os.path.exists(a)} # the files the key hashes, again at the store
784
+ key = cache_key(stage, script, key_args, inputs, dest, key_files)
785
+ _LAST_DOC.clear()
786
+ if cache_lookup(stage, key, dest, Path(script).stem):
787
+ CACHE["hits"].append(stage)
788
+ info(f"→ {script} {stage}: served from --cache")
789
+ # No child ran; the sidecar carries only the recorded fields we can replay.
790
+ _LAST_DOC["cached"] = True
791
+ if not STATE.dry_run:
792
+ remember_written(dest) # placed by this run, as a stage's own write would be (#415)
793
+ _record_own_stage_file(dest)
794
+ return dest
795
+ CACHE["misses"].append(stage)
796
+ _refuse_uncached_earlier_stage(stage)
797
+ elif stage and CACHE.get("dir"):
798
+ CACHE["misses"].append(stage)
799
+ _cache_miss(stage, "no_output_path") # nothing names where the artifact goes, so there is nothing to keep
800
+ started = time.time()
801
+ # an earlier render's own stage file in this --work (A98): replaced as this run's own would be.
802
+ # After the cache key, which this does not change.
803
+ own = ["--overwrite"] if not STATE.overwrite and _earlier_own_stage_file(dest) else []
804
+ if own:
805
+ info(f" {os.path.basename(str(dest))} is an earlier render's own stage file in {_OWN_STAGES['dir']}, unchanged since: replaced")
806
+ cmd = [str(HERE / script)] + [str(a) for a in argv] + (extra or []) + own + child_args() + ["--json"]
807
+ info("→ " + " ".join(os.path.basename(c) if i < 1 else c for i, c in enumerate(cmd[:-1])))
808
+ # a stage that writes outside the work directory (the export writes the delivery itself): what
809
+ # is there now, so a stop while it runs reports a file the stage wrote as kept, not "nothing
810
+ # was written", and never claims the caller's own file (#510)
811
+ # the delivery itself is watched wherever --work is (a --work that holds the output's folder
812
+ # made the export look like an intermediate, #510 review)
813
+ outside = bool(dest) and (not _in_work(dest) or _is_delivery(dest))
814
+ if outside:
815
+ watch_destination(dest)
816
+ proc = run_tool(cmd)
817
+ for is_command, line in stderr_records(proc.stderr):
818
+ if is_command:
819
+ STATE.commands.append(line)
820
+ elif line.strip():
821
+ info(" " + line)
822
+ try:
823
+ doc = json.loads(proc.stdout.strip() or "{}")
824
+ except ValueError:
825
+ doc = {}
826
+ if proc.returncode != 0:
827
+ # Re-raise the stage's own failure: its kind, exit code and hint are what the caller
828
+ # needs (a timeout inside audio.py is a timeout, not an "input" error of render.py).
829
+ err = doc.get("error") or {}
830
+ extra_fields = {"hint": err["hint"]} if err.get("hint") else {}
831
+ error_extra = absorb_stage(Path(script).stem, doc) # the stage's reason/details and records ride along
832
+ extra_fields.update(_stage_failure_hw(doc))
833
+ why = err.get('message') or (proc.stderr.strip().splitlines() or ['?'])[-1][:300]
834
+ if kept_deliverables() and err.get("kind") in ("timeout", "interrupted"):
835
+ # a stage after the delivery (chapters, check): the stage's own "nothing was written"
836
+ # is about its own file, while the delivery is on disk (#415)
837
+ why = why.replace("; nothing was written", "") + f" ({kept_clause()})"
838
+ extra_fields.setdefault("output", kept_output())
839
+ elif err.get("kind") in ("timeout", "interrupted") and doc.get("output") and os.path.isfile(str(doc["output"])):
840
+ # the stage was stopped after writing its own deliverable and kept it (export.py's
841
+ # --normalize pass): its message says so, and the file is this run's output too
842
+ extra_fields.setdefault("output", str(doc["output"]))
843
+ die(f"{script} failed: {why}",
844
+ code=int(doc.get("exit_code") or 1), kind=err.get("kind") or "input", stage=script, error_extra=error_extra, **extra_fields)
845
+ _LAST_DOC.clear()
846
+ _LAST_DOC.update(doc if isinstance(doc, dict) else {})
847
+ PROJECT_SOURCE["timecode"].append(_timecode_verdict(doc))
848
+ absorb_stage(Path(script).stem, doc) # a stage's GPU facts (ran on VideoToolbox, fell back and why) and its diagnostics reach this result
849
+ out_path = str(doc.get("output") or "")
850
+ if not STATE.dry_run:
851
+ # A file a stage of this run wrote is this run's, not someone else's: the chapters stage
852
+ # places its tagged copy over the export's delivery, which the output guard would
853
+ # otherwise refuse as an existing file without --overwrite (#415).
854
+ remember_written(out_path, dest)
855
+ _record_own_stage_file(dest)
856
+ if outside:
857
+ unwatch_destination(dest)
858
+ if key and not STATE.dry_run:
859
+ # the key was made before the child ran: an input, a --brand file's logo or font edited
860
+ # while it ran made an artifact the key does not describe, and putting the old file back
861
+ # (a copy that keeps its mtime) would have served it (#540, as batch's store() does since #537)
862
+ if cache_key(stage, script, key_args, inputs, dest, key_files) != key:
863
+ record_skip(f"cache: the {stage} stage's inputs changed while it ran, so its artifact is not stored "
864
+ "(the next run makes it again)", "cache_inputs_changed", stage=stage)
865
+ else:
866
+ cache_store(stage, key, out_path or (dest or ""), time.time() - started, doc)
867
+ return out_path
868
+
869
+
870
+ WORK_DIR: Dict[str, Optional[str]] = {"path": None}
871
+ DELIVERY: Dict[str, Optional[str]] = {"path": None} # the render's output path, set in main()
872
+
873
+
874
+ def _is_delivery(path: str) -> bool:
875
+ return bool(DELIVERY["path"]) and os.path.realpath(path) == os.path.realpath(str(DELIVERY["path"]))
876
+
877
+
878
+ def _in_work(path: str) -> bool:
879
+ """Whether `path` is inside this render's work directory."""
880
+ work = WORK_DIR["path"]
881
+ if not work:
882
+ return False
883
+ return os.path.realpath(path).startswith(os.path.realpath(work) + os.sep)
884
+
885
+
886
+ SRT_TRIM_TOLERANCE = 0.25 # seconds the delivery may be shorter than the captioned stage before its SRT is called off-timeline
887
+
888
+
889
+ def deliver_caption_srt(target: Optional[str], made: Optional[Dict[str, Any]], output: str) -> Optional[str]:
890
+ """Put the captions stage's generated SRT at `target` (<output>.srt, guarded before the first
891
+ stage) and return the path, or None with a skip record when it is not delivered: the stage was
892
+ served from the cache (the cache keeps the video only), or a later stage changed the timeline
893
+ (the export trimmed the delivery to a platform's maximum), where the SRT's times are no longer
894
+ the delivery's (#510). Under --dry-run the planned path."""
895
+ if not target or not made:
896
+ return None
897
+ if STATE.dry_run:
898
+ info(f"[dry-run] would deliver the captions' SRT as {target}")
899
+ return target
900
+ if made.get("cached") or not os.path.isfile(made["srt"]):
901
+ record_skip(f"the captions stage's SRT is not delivered: the stage was served from --cache, which keeps its video only",
902
+ "caption_srt_not_delivered", reason="cached", path=target)
903
+ return None
904
+ trimmed = _LAST_DOC.get("trimmed") if _LAST_DOC.get("trimmed") else None
905
+ if not trimmed:
906
+ before = (probe(made["video"], role="output").get("duration") if os.path.isfile(made["video"]) else None) or 0.0
907
+ after = probe(output, role="output").get("duration") or 0.0
908
+ if before and after and before - after > SRT_TRIM_TOLERANCE:
909
+ trimmed = {"from": round(before, 3), "to": round(after, 3)}
910
+ if trimmed:
911
+ record_skip(f"the captions stage's SRT is not delivered: a later stage changed the timeline (the delivery was trimmed: "
912
+ f"{trimmed}), so its cue times are not the delivery's", "caption_srt_not_delivered",
913
+ reason="timeline_changed", path=target, trimmed=trimmed)
914
+ return None
915
+ place_output(made["srt"], target)
916
+ mark_delivered(target, side=True) # kept after a stop, but not the run's `output` (#510 review)
917
+ info(f"delivered the captions' SRT as {target}")
918
+ return target
919
+
920
+
921
+ def _stage_failure_hw(doc: Any) -> Dict[str, Any]:
922
+ """A failed stage's `encoder` -- the command that failed -- for render's own failure document
923
+ (absorb_stage() has already joined the stage's `hw` to the earlier stages'; a fallback before
924
+ the failure is not lost). die() then adds `hw` for a kind: ffmpeg failure, as a tool's own
925
+ run() failure carries it."""
926
+ if not isinstance(doc, dict):
927
+ return {}
928
+ return {"encoder": doc["encoder"]} if doc.get("encoder") else {}
929
+
930
+
931
+ # ------------------------------------------------------------------ the stage cache (1.17)
932
+ #
933
+ # Opt-in only: --cache DIR. There is no default directory -- a cache that appears on someone's
934
+ # disk without being asked for is a surprise, and this tool's posture is that a plan leaves
935
+ # nothing behind.
936
+
937
+ STAGE_ORDER = ("clips", "audiogram", "join", "silence", "fit", "captions", "graphics",
938
+ "overlays", "audio", "loudness", "export", "chapters")
939
+
940
+ def _fresh_cache() -> "Dict[str, Any]":
941
+ return {"dir": None, "ffmpeg": None, "hits": [], "misses": [], "miss_reasons": [], "saved_seconds": 0.0,
942
+ "entries": 0, "would_hit": [], "from": None}
943
+
944
+
945
+ # Module-level so sh() can reach it without threading a parameter through every stage. main()
946
+ # resets it on entry, so two renders in one process (a test session, an embedding caller) do not
947
+ # inherit each other's hit/miss lists.
948
+ CACHE: Dict[str, Any] = _fresh_cache()
949
+
950
+ # The stages whose x264 encode (x265 on the HDR path, which takes the same --preset) is an
951
+ # intermediate when an encoding export follows: export.py
952
+ # re-encodes their output, so their own `medium` pass bought nothing the delivery keeps. Measured
953
+ # on a 30 s 1080p reels render (4 cores): fit 18 s and captions 27 s of a 70 s run at `medium`;
954
+ # `veryfast` at the same CRF encodes in about half the time (SSIM 0.997 against `medium`) and
955
+ # the export, still `medium`, sets the delivered quality. 2.16: `superfast` (the default since): on
956
+ # FFmpeg 8.0.1 the same render took 30 s instead of 33 s with veryfast, SSIM against a lossless
957
+ # reference 0.9868 vs 0.9863 (the export decides what is kept); on 6.1 the two took the same time.
958
+ # `ultrafast` was faster still (26 s) but measurably worse (0.9814). `--intermediate-preset medium`
959
+ # restores the stages' own default.
960
+ _X264_STAGES = frozenset({"cut.py", "fit.py", "join.py", "silence.py", "caption.py", "graphics.py", "overlay.py", "waveform.py"})
961
+ INTERMEDIATE: Dict[str, Any] = {"preset": None, "applied": False}
962
+
963
+
964
+ def _intermediate_used() -> Optional[str]:
965
+ """The preset `intermediate_preset` reports: only once a stage actually received it (a project
966
+ whose only encode is the export reports null)."""
967
+ return INTERMEDIATE["preset"] if INTERMEDIATE["applied"] else None
968
+
969
+
970
+ # Small files this run writes itself and hands to a stage (the inline chapters list's chapters.txt):
971
+ # keyed by their whole content, not by file_key()'s mtime, since a new run writes them anew and
972
+ # their stage could never hit the cache (A100).
973
+ CONTENT_KEYED: set = set()
974
+
975
+
976
+ def _content_hash(path: str) -> str:
977
+ """The same cheap content fingerprint batch.py caches on: name, size, mtime, first and last
978
+ MB. Reused rather than reinvented so one file has one identity across the skill. A file that
979
+ cannot be read keys as "missing" -- recorded (cache_input_unreadable), since two unreadable
980
+ files then share that part of the key. A file in CONTENT_KEYED is keyed by its bytes."""
981
+ try:
982
+ if os.path.abspath(path) in CONTENT_KEYED:
983
+ return "content:" + hashlib.sha1(Path(path).read_bytes(), usedforsecurity=False).hexdigest()
984
+ return file_key(Path(path))
985
+ except (OSError, ValueError) as exc:
986
+ entry = {"code": "cache_input_unreadable", "path": str(path)}
987
+ if not any(all(w.get(k) == v for k, v in entry.items()) for w in STATE.warnings):
988
+ warn(f"cache: could not fingerprint {path} ({exc}); it is keyed as \"missing\"", "cache_input_unreadable",
989
+ path=str(path), error=str(exc))
990
+ return "missing"
991
+
992
+
993
+ def ffmpeg_banner() -> str:
994
+ """The whole `ffprobe -version` first line, not just major.minor.
995
+
996
+ Two 7.1.x builds with different libx264 produce different bytes from the same command, and
997
+ the cache exists to hand back bytes. major.minor cannot tell them apart, so the banner --
998
+ which carries the build string and the configuration's version suffix -- is what goes in the
999
+ key. Unreadable falls back to the parsed pair, which still separates the major releases.
1000
+ """
1001
+ try:
1002
+ out = subprocess.run([found_exe("ffprobe"), "-version"], stdout=subprocess.PIPE,
1003
+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=20).stdout
1004
+ first = (out or "").strip().splitlines()
1005
+ if first:
1006
+ return first[0].strip()
1007
+ why = "ffprobe -version printed nothing"
1008
+ except (OSError, subprocess.SubprocessError) as exc:
1009
+ why = str(exc)
1010
+ pair = ".".join(str(n) for n in ffmpeg_version())
1011
+ # two builds of one major.minor now share cache entries: say so
1012
+ record_fallback(f"cache: the ffmpeg build banner could not be read ({why}); keying on ffmpeg {pair} instead, so builds "
1013
+ "of the same major.minor share entries", "cache_ffmpeg_banner_unreadable", used=pair, error=why)
1014
+ return pair
1015
+
1016
+
1017
+ def cache_key(stage: str, script: str, argv: "Sequence[Any]", inputs: "Sequence[str]",
1018
+ dest: "Optional[str]" = None, files: "Optional[set]" = None) -> str:
1019
+ """sha1 of a canonical description of exactly what this stage is about to do.
1020
+
1021
+ The ffmpeg build banner and the skill version are IN the key, deliberately: a different build
1022
+ simply misses rather than being asked to trust an artifact it did not write, and a stage whose
1023
+ implementation changed must not serve an old one back.
1024
+
1025
+ `child_args()` is in the key too, and that is not a detail. render.py appends it to every
1026
+ stage command AFTER the arguments the stage itself built, and it carries `--fast` -- which
1027
+ rewrites the child's preset to veryfast. Without it in the key, `render --cache C --fast`
1028
+ stored a draft and the next `render --cache C` served that draft back as the delivery, with
1029
+ `cache.hits` presenting it as a legitimate reuse.
1030
+
1031
+ The output's extension is in the key as well (#15): the artifact is stored as `<key><ext>`
1032
+ while the sidecar is `<key>.json`, so two runs differing only in container would otherwise
1033
+ share one sidecar and invalidate each other on every run.
1034
+
1035
+ `files`: the arguments hashed as files (default: those that exist now). sh() passes the set it
1036
+ keyed before the stage ran when it makes the key again after, so a file the stage itself wrote
1037
+ beside its output does not change the key (#540).
1038
+ """
1039
+ payload = {
1040
+ "stage": stage, "tool": script,
1041
+ "args": [_content_hash(str(a)) if (str(a) in files if files is not None else os.path.exists(str(a))) else str(a)
1042
+ for a in argv],
1043
+ "inputs": [{"hash": _content_hash(p)} for p in inputs],
1044
+ "child": [a for a in child_args() if a != "--dry-run"],
1045
+ "codec": STATE.codec, "ext": Path(dest).suffix if dest else None,
1046
+ # what a stage's encoder resolves from: $FFMPEG_SKILL_HW (inherited) and whether the outer
1047
+ # command made it explicit (--hw/--no-hw, which reaches export.py too). A GPU encode is not
1048
+ # the CPU's bytes, so a --hw artifact is never served to a CPU run or the other way round.
1049
+ "hw": [os.environ.get(HW_ENV, "").strip().lower() in ("1", "true", "yes", "on"), os.environ.get(HW_FORCED_ENV) == "1"],
1050
+ "ffmpeg": CACHE.get("ffmpeg"), "skill": SKILL_VERSION, "contract": CONTRACT_VERSION,
1051
+ }
1052
+ named = _brand_files_key(argv)
1053
+ if named:
1054
+ payload["brand_files"] = named # only with --brand: every other stage's key is unchanged
1055
+ return hashlib.sha1(json.dumps(payload, sort_keys=True, ensure_ascii=False).encode(), usedforsecurity=False).hexdigest()
1056
+
1057
+
1058
+ def _brand_files_key(argv: "Sequence[Any]") -> List[Any]:
1059
+ """The files a stage's --brand file names (its logo and font_file, resolved as load_brand()
1060
+ resolves them): the key hashes the brand file's own bytes, so a font or a logo replaced under
1061
+ the same name was served from the cache with the old one drawn (#510's sweep)."""
1062
+ out: List[Any] = []
1063
+ args = [str(a) for a in argv]
1064
+ for i, a in enumerate(args[:-1]):
1065
+ if a != "--brand" or not os.path.isfile(args[i + 1]):
1066
+ continue
1067
+ for key, path in brand_asset_files(args[i + 1]):
1068
+ out.append([key, _content_hash(path) if os.path.isfile(path) else None])
1069
+ return out
1070
+
1071
+
1072
+ def _cache_miss(stage: str, reason: str, **facts: Any) -> bool:
1073
+ """Record why `stage` was not served from the cache (`cache.miss_reasons`); a damaged entry
1074
+ (unreadable sidecar, artifact of the wrong size) is also a warning and an audit line in the
1075
+ cache directory, because something rewrote or truncated a file this tool wrote."""
1076
+ CACHE["miss_reasons"].append(dict({"stage": stage, "reason": reason}, **facts))
1077
+ if reason in ("sidecar_corrupt", "artifact_truncated"):
1078
+ msg = f"cache: the {stage} entry is damaged ({reason.replace('_', ' ')}); the stage runs again"
1079
+ warn(msg, "cache_entry_damaged", stage=stage, reason=reason, **facts)
1080
+ audit("cache_entry_damaged", dict({"stage": stage, "reason": reason}, **facts),
1081
+ default_path=str(Path(CACHE["dir"]) / ".ffskill-audit.jsonl"))
1082
+ return False
1083
+
1084
+
1085
+ def cache_lookup(stage: str, key: str, dest: str, tool: Optional[str] = None) -> bool:
1086
+ """Put the cached artifact for `key` at `dest` and return True, or return False on any
1087
+ mismatch. A miss is not an error, it is work to do, but it is not silent either: why each
1088
+ stage missed is in `cache.miss_reasons` (not_cached, sidecar_missing, artifact_missing,
1089
+ sidecar_corrupt, artifact_truncated). A hit replays the stage's recorded result (its
1090
+ verification, notes and diagnostics) into this run, as a stage that ran would have."""
1091
+ cdir = CACHE.get("dir")
1092
+ if not cdir:
1093
+ return False
1094
+ side = Path(cdir) / f"{key}.json"
1095
+ art = Path(cdir) / f"{key}{Path(dest).suffix or '.bin'}"
1096
+ if not side.exists() and not art.exists():
1097
+ return _cache_miss(stage, "not_cached", key=key)
1098
+ if not side.exists():
1099
+ return _cache_miss(stage, "sidecar_missing", key=key, artifact=str(art))
1100
+ if not art.exists():
1101
+ return _cache_miss(stage, "artifact_missing", key=key, sidecar=str(side))
1102
+ try:
1103
+ meta = json.loads(side.read_text(encoding="utf-8"))
1104
+ if not isinstance(meta, dict):
1105
+ raise ValueError("not a JSON object")
1106
+ expected = int(meta.get("size") or -1)
1107
+ except (OSError, ValueError, TypeError) as exc:
1108
+ return _cache_miss(stage, "sidecar_corrupt", key=key, sidecar=str(side), error=str(exc))
1109
+ actual = art.stat().st_size
1110
+ if expected != actual:
1111
+ return _cache_miss(stage, "artifact_truncated", key=key, artifact=str(art), expected_size=expected, actual_size=actual)
1112
+ if STATE.dry_run:
1113
+ CACHE["would_hit"].append(stage)
1114
+ return True
1115
+ if Path(dest).exists() and not STATE.overwrite and not _earlier_own_stage_file(dest):
1116
+ # a file in --work that is not this render's own (the caller's, or one they edited): a hit
1117
+ # would unlink it without --overwrite. Run the stage instead, which refuses it by its rule
1118
+ return _cache_miss(stage, "destination_not_owned", key=key, destination=str(dest))
1119
+ Path(dest).parent.mkdir(parents=True, exist_ok=True)
1120
+ try:
1121
+ if Path(dest).exists():
1122
+ Path(dest).unlink()
1123
+ os.link(art, dest) # a hardlink where the filesystem allows it ...
1124
+ except OSError:
1125
+ shutil.copy2(art, dest) # ... and a copy where it does not. Never a move: the cache
1126
+ CACHE["saved_seconds"] += float(meta.get("seconds") or 0.0)
1127
+ result = meta.get("result")
1128
+ # what the stage said about the start timecode, for render's source_carry; an entry written
1129
+ # before its source_carry was kept does not say
1130
+ PROJECT_SOURCE["timecode"].append(_timecode_verdict(result) if isinstance(result, dict) and "source_carry" in result
1131
+ else "unknown")
1132
+ if isinstance(result, dict):
1133
+ if isinstance(result.get("picture"), dict):
1134
+ _LAST_DOC["picture"] = result["picture"]
1135
+ absorb_stage(tool or stage, dict(result, status="completed", dry_run=False)) # tagged as the stage's tool, as a live run is
1136
+ else:
1137
+ # an entry written before the stage's result was kept: what the stage verified is unknown
1138
+ record_skip(f"cache: the {stage} entry predates recorded results, so what that stage verified is not "
1139
+ "known; rerun without --cache to see it", "cache_result_unrecorded", stage=stage)
1140
+ return True
1141
+
1142
+
1143
+ def _stage_result(doc: Any) -> Dict[str, Any]:
1144
+ """What a cache entry keeps of the stage's own --json document, replayed on a hit."""
1145
+ if not isinstance(doc, dict):
1146
+ return {}
1147
+ kept = {k: doc[k] for k in ("verified", "verification", "notes", "diagnostics", "picture") if k in doc}
1148
+ kept["source_carry"] = doc.get("source_carry") # None too: the stage compared nothing (render's source_carry)
1149
+ return kept
1150
+
1151
+
1152
+ def cache_store(stage: str, key: str, produced: str, seconds: float, doc: Any = None) -> None:
1153
+ """Keep `produced` for the next run. Never under --dry-run: a plan writes nothing. A store
1154
+ that fails is a warning (cache_store_failed), never a failure of the run."""
1155
+ cdir = CACHE.get("dir")
1156
+ if not cdir or STATE.dry_run or not produced or not os.path.exists(produced):
1157
+ return
1158
+ art = Path(cdir) / f"{key}{Path(produced).suffix or '.bin'}"
1159
+ try:
1160
+ shutil.copy2(produced, art)
1161
+ Path(cdir, f"{key}.json").write_text(json.dumps({
1162
+ "stage": stage, "ffmpeg": CACHE.get("ffmpeg"), "skill": SKILL_VERSION,
1163
+ "created": time.time(), "size": art.stat().st_size, "seconds": round(seconds, 2),
1164
+ "artifact": art.name, "result": _stage_result(doc)}, indent=2), encoding="utf-8")
1165
+ CACHE["entries"] += 1
1166
+ except OSError as exc:
1167
+ warn(f"cache: could not store the {stage} artifact ({exc}); the run is unaffected", "cache_store_failed",
1168
+ stage=stage, error=str(exc))
1169
+
1170
+
1171
+ def _utc_now() -> str:
1172
+ import datetime
1173
+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
1174
+
1175
+
1176
+ def _plan_sha256(path: str) -> Optional[str]:
1177
+ try:
1178
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
1179
+ except OSError:
1180
+ return None
1181
+
1182
+
1183
+ def _reject_plan(path: str, plan_sha256: Optional[str], reason: str, msg: str, *, hint: Optional[str] = None,
1184
+ **details: Any) -> None:
1185
+ """Refuse a plan: one audit record (the plan's `<plan>.audit.jsonl`, or --audit-log), then
1186
+ the failure document with `error.reason` and `error.details` -- the plan, its sha256, when it
1187
+ was checked, the facts below, and where the audit record went."""
1188
+ details = dict({"plan": path, "plan_sha256": plan_sha256, "checked_at": _utc_now()}, **details)
1189
+ details["audit_log"] = audit("plan_rejected", dict(details, reason=reason), default_path=path + ".audit.jsonl",
1190
+ plan_sha256=plan_sha256)
1191
+ refuse("input", reason, msg, hint=hint, extra={"plan": path}, **details)
1192
+
1193
+
1194
+ def plan_input_status(inputs: Sequence[Any]) -> List[Dict[str, Any]]:
1195
+ """Each fingerprinted plan input against the file as it is now: {path, status: unchanged |
1196
+ changed | missing, expected: {size, sha256_head_tail[, sha256_full]}, actual: the same keys
1197
+ or "missing"}."""
1198
+ rows: List[Dict[str, Any]] = []
1199
+ for inp in inputs:
1200
+ inp = inp if isinstance(inp, dict) else {"path": inp}
1201
+ p = inp.get("path")
1202
+ expected = {"size": inp.get("size"), "sha256_head_tail": inp.get("sha256_head_tail")}
1203
+ if "sha256_full" in inp:
1204
+ expected["sha256_full"] = inp["sha256_full"]
1205
+ if not p or not os.path.isfile(str(p)):
1206
+ rows.append({"path": p, "status": "missing", "expected": expected, "actual": "missing"})
1207
+ continue
1208
+ try:
1209
+ now = fingerprint(str(p), complete=True) if "sha256_full" in expected else fingerprint(str(p))
1210
+ except OSError:
1211
+ rows.append({"path": p, "status": "missing", "expected": expected, "actual": "missing"})
1212
+ continue
1213
+ actual = {key: now[key] for key in expected}
1214
+ rows.append({"path": p, "status": "unchanged" if actual == expected else "changed", "expected": expected, "actual": actual})
1215
+ return rows
1216
+
1217
+
1218
+ def run_check(output: str, platform: Optional[str], content: bool) -> Dict[str, Any]:
1219
+ """check.py on `output` for a project's "check" stage or a plan's check step: `platform`
1220
+ (or none: check.py's youtube assumption, judgement rows WARN) and `content` (--content).
1221
+ Returns check.py's own document; when check.py printed none that parses, a failure document
1222
+ in its shape -- status failed, error {kind, reason: check_output_unparsed, message,
1223
+ exit_code, stderr_tail} -- so a caller never reads a bare string."""
1224
+ cp = run_tool([str(HERE / "check.py"), output] + (["--platform", str(platform)] if platform else [])
1225
+ + (["--content"] if content else []) + ["--json"] + child_args())
1226
+ try:
1227
+ doc = json.loads(cp.stdout)
1228
+ except ValueError:
1229
+ doc = None
1230
+ if isinstance(doc, dict):
1231
+ return doc
1232
+ tail = cp.stderr.strip()[-300:]
1233
+ msg = "check.py printed no JSON document" + (f": {tail.splitlines()[-1]}" if tail else "")
1234
+ warn(f"check: {msg}", "check_output_unparsed", exit_code=cp.returncode)
1235
+ return {"status": "failed", "platform": platform, "ok": False,
1236
+ "error": {"kind": "timeout" if cp.returncode == 124 else "verification", "reason": "check_output_unparsed",
1237
+ "message": msg, "exit_code": cp.returncode, "stderr_tail": tail}}
1238
+
1239
+
1240
+ def _from_plan_cwd(output: Any) -> Any:
1241
+ """A plan's output as an absolute path. execute_plan() has moved into the plan's cwd, so a
1242
+ relative one named a file there, and the result reported it to a caller in another directory
1243
+ as if it were in theirs (A96)."""
1244
+ return os.path.abspath(str(output)) if isinstance(output, str) and output else output
1245
+
1246
+
1247
+ def check_not_run(check_result: Optional[Dict[str, Any]]) -> Optional[str]:
1248
+ """Why check.py graded nothing, or None when it did: a document with no FAIL count that is
1249
+ failed or carries an error is a check that could not run (an unparsed document, check.py's own
1250
+ refusal), not a check the delivery failed (#403: both were reported as "check failed")."""
1251
+ if not check_result or check_result.get("failed"):
1252
+ return None
1253
+ err = check_result.get("error")
1254
+ if not err and check_result.get("status") != "failed":
1255
+ return None
1256
+ return str((err.get("message") if isinstance(err, dict) else err) or "check.py reported status failed with no rows")
1257
+
1258
+
1259
+ def execute_plan(plan: Dict[str, Any], path: str) -> int:
1260
+ """Run a plan written by `<tool> --plan FILE`: refuse if any fingerprinted input changed since
1261
+ the plan was made (the plan's commands would then describe a different edit), run the tool
1262
+ with the planned argv, then the plan's verify steps. --dry-run prints the planned commands.
1263
+
1264
+ Every refusal is `kind: input` with `error.reason` and `error.details` and appends one audit
1265
+ record (docs/design-decisions.md, "Nothing happens silently")."""
1266
+ digest = _plan_sha256(path)
1267
+ audit_path = os.path.abspath(path)
1268
+ if plan.get("plan_version") != PLAN_VERSION:
1269
+ _reject_plan(path, digest, "plan_version_unsupported",
1270
+ f"{path}: plan_version {plan.get('plan_version')!r} is not {PLAN_VERSION}",
1271
+ plan_version=plan.get("plan_version"), supported=[PLAN_VERSION])
1272
+ # the fields below are walked as lists of objects or strings: a wrong type was a traceback
1273
+ # with no audit record (A14), and is refused like every other plan error
1274
+ for field, want, item in (("inputs", list, None), ("unbound_inputs", list, None), ("verify", list, dict),
1275
+ ("commands", list, str), ("cwd", str, None)):
1276
+ value = plan.get(field)
1277
+ if value is None:
1278
+ continue
1279
+ bad = not isinstance(value, want) or (item is not None and not all(isinstance(v, item) for v in value))
1280
+ if bad:
1281
+ shape = {"inputs": "a list", "unbound_inputs": "a list", "verify": "a list of objects",
1282
+ "commands": "a list of strings", "cwd": "a string"}[field]
1283
+ _reject_plan(path, digest, "plan_field_invalid", f"{path}: {field} must be {shape}, got {type(value).__name__}",
1284
+ field=field, field_type=type(value).__name__)
1285
+ tool = str(plan.get("tool") or "")
1286
+ script = HERE / f"{tool}.py"
1287
+ if not re.fullmatch(r"[a-z][a-z0-9_]*", tool) or not script.exists() or tool == "render":
1288
+ _reject_plan(path, digest, "plan_unknown_tool", f"{path}: unknown tool {tool!r}", tool=tool)
1289
+ unbound = [str(u) for u in (plan.get("unbound_inputs") or [])]
1290
+ rows = plan_input_status(plan.get("inputs") or [])
1291
+ bad = [r for r in rows if r["status"] != "unchanged"]
1292
+ if bad:
1293
+ lines = [f"{r['path']}: missing" if r["status"] == "missing" else f"{r['path']}: content changed since the plan was made"
1294
+ for r in bad]
1295
+ _reject_plan(path, digest, "plan_inputs_changed",
1296
+ "plan inputs differ from what was planned; re-run the tool with --plan to make a new plan:\n " + "\n ".join(lines),
1297
+ hint="plans are bound to the exact input files they were made from",
1298
+ inputs=rows, unbound_inputs=unbound)
1299
+ if unbound:
1300
+ warn(f"{len(unbound)} plan input(s) did not exist when the plan was made, so nothing checks that they are the files "
1301
+ "it was made for: " + ", ".join(unbound), "plan_unbound_inputs", paths=unbound)
1302
+ if plan.get("cwd"):
1303
+ if not os.path.isdir(plan["cwd"]):
1304
+ _reject_plan(path, digest, "plan_cwd_missing",
1305
+ f"plan cwd {plan['cwd']} no longer exists; relative paths in the plan would resolve elsewhere -- re-plan",
1306
+ cwd=plan["cwd"])
1307
+ os.chdir(plan["cwd"])
1308
+ if not isinstance(plan.get("argv"), list):
1309
+ _reject_plan(path, digest, "plan_argv_invalid", f"{path}: argv must be a list", argv_type=type(plan.get("argv")).__name__)
1310
+ # a plan an earlier version recorded with --json-brief (A181): the tool is run for its full
1311
+ # document, as every plan written now asks for
1312
+ argv = [str(a) for a in plan["argv"] if not is_output_shape_flag(str(a))]
1313
+ expected_frames = plan.get("sequence_frames_sha256")
1314
+ replay_env = None
1315
+ if tool == "silence" and "cut_plan" in plan:
1316
+ from _common.pacing_edit import plan_digest
1317
+ replay_env = dict(os.environ, FFMPEG_SKILL_PACING_PLAN_SHA256=plan_digest(plan["cut_plan"]))
1318
+ if tool == "sequence" and expected_frames is None:
1319
+ warn("this older sequence plan does not bind the ordered frame list; make a new plan to check it",
1320
+ "plan_sequence_unbound")
1321
+ elif tool == "sequence":
1322
+ if not isinstance(expected_frames, str) or not re.fullmatch(r"[0-9a-f]{64}", expected_frames):
1323
+ _reject_plan(audit_path, digest, "plan_field_invalid",
1324
+ "sequence_frames_sha256 must be a SHA-256 digest", field="sequence_frames_sha256")
1325
+ from sequence import SEQUENCE_PLAN_ENV, replay_frame_digest
1326
+ if STATE.dry_run:
1327
+ actual_frames = replay_frame_digest(argv)
1328
+ if actual_frames != expected_frames:
1329
+ _reject_plan(audit_path, digest, "plan_inputs_changed",
1330
+ "the ordered sequence frames differ from what was planned; make a new plan",
1331
+ expected_frame_digest=expected_frames, actual_frame_digest=actual_frames)
1332
+ else:
1333
+ replay_env = dict(os.environ, **{SEQUENCE_PLAN_ENV: expected_frames})
1334
+ if STATE.dry_run:
1335
+ for c in plan.get("commands") or []:
1336
+ STATE.commands.append(c)
1337
+ info("[dry-run] " + c)
1338
+ for step in plan.get("verify") or []:
1339
+ if step.get("tool") == "check" and (step.get("platform") or step.get("content") is True):
1340
+ record_skip("[dry-run] the plan's check step is not run: there is no output to check yet",
1341
+ "check_dry_run", platform=step.get("platform"), content=step.get("content") is True)
1342
+ emit(_from_plan_cwd(plan.get("output")), plan=path, plan_sha256=digest, tool=tool, stages=[tool], check=None,
1343
+ unbound_inputs=unbound)
1344
+ return 0
1345
+ info(f"executing plan {path}: {tool} " + " ".join(argv))
1346
+ proc = run_tool([str(script)] + with_flags(argv, child_args() + ["--json"]),
1347
+ env=replay_env) # before a `--` in the plan's argv
1348
+ for is_command, line in stderr_records(proc.stderr):
1349
+ if is_command and not line.startswith("[dry-run]"):
1350
+ STATE.commands.append(line)
1351
+ elif line.strip():
1352
+ info(" " + line)
1353
+ try:
1354
+ doc = json.loads(proc.stdout.strip() or "{}")
1355
+ except ValueError:
1356
+ doc = {}
1357
+ if proc.returncode != 0 or doc.get("status") != "completed":
1358
+ err = doc.get("error") or {}
1359
+ if replay_env is not None and err.get("reason") == "plan_inputs_changed":
1360
+ _reject_plan(audit_path, digest, "plan_inputs_changed", err["message"],
1361
+ **(err.get("details") or {}))
1362
+ error_extra = absorb_stage(tool, doc) # the tool's reason/details and records ride along
1363
+ # the tool's exit code is the plan's (124 timeout, 130/143 interrupted), as sh() passes a stage's on
1364
+ die(f"{tool} failed while executing the plan: {err.get('message') or proc.stderr.strip()[-300:]}",
1365
+ code=child_exit_code(doc, proc.returncode), kind=err.get("kind", "ffmpeg"), plan=path, tool=tool,
1366
+ error_extra=error_extra, **_stage_failure_hw(doc))
1367
+ absorb_stage(tool, doc) # the tool's GPU facts (fell back and why, ran on VideoToolbox) and diagnostics reach this result
1368
+ output = _from_plan_cwd(doc.get("output") or plan.get("output"))
1369
+ check_result = None
1370
+ exit_code = 0
1371
+ for step in plan.get("verify") or []:
1372
+ # a check step names a platform, asks for check.py --content's black/frozen/silence rows
1373
+ # ("content": true), or both -- the same keys a project's "check" stage takes
1374
+ if step.get("tool") == "check" and (step.get("platform") or step.get("content") is True) and output:
1375
+ check_result = run_check(output, step.get("platform"), step.get("content") is True)
1376
+ if check_result.get("failed") or check_result.get("status") == "failed" or check_result.get("error"):
1377
+ exit_code = 1
1378
+ elif step.get("tool") == "check" and not output:
1379
+ record_skip("the plan's check step is not run: the tool reported no output", "check_no_output",
1380
+ platform=step.get("platform"))
1381
+ # a failed platform check is reported the way the direct path reports it: the tool completed,
1382
+ # verified is false, the rows say what to fix (review 6: a plan must not fail harder than the
1383
+ # same command run by hand)
1384
+ if exit_code:
1385
+ failed_rows = [r["check"] for r in (check_result or {}).get("checks", []) if r.get("status") == "FAIL"]
1386
+ unrun = check_not_run(check_result)
1387
+ info(f"plan done: {output}, but the {check_result.get('platform') or 'content'} check "
1388
+ + (f"could not run, so nothing was checked: {unrun}" if unrun else "failed" + (f": {', '.join(failed_rows)}" if failed_rows else "")))
1389
+ else:
1390
+ advised = guidance_warns(check_result)
1391
+ info(f"plan done: {output}" + (" — upload-limit guidance, the uploader checks the current limit: "
1392
+ + "; ".join(advised) if advised else ""))
1393
+ # the tool's own steps (export's loudness, ...) come in through absorb_stage() above, tagged
1394
+ # with `stage`, so `verified` is theirs and the check's together
1395
+ emit(output, plan=path, plan_sha256=digest, unbound_inputs=unbound, tool=tool, stages=[tool] + (["check"] if check_result else []), check=check_result, tool_result=doc,
1396
+ verification=([dict({"step": "check", "ok": not exit_code, "platform": check_result.get("platform")},
1397
+ **({"reason": "not_measured: " + check_not_run(check_result)} if check_not_run(check_result) else {}))]
1398
+ if check_result else []))
1399
+ return 0
1400
+
1401
+
1402
+ def frame_from_preset(frame: Dict[str, Any], export: Dict[str, Any]) -> None:
1403
+ """Fill frame.width/height from the export preset when the project gave only an aspect.
1404
+ Eval 7 (j08 twice, e01 by hand): "frame": {"aspect": "9:16"} with a reels export fitted a
1405
+ 1280x720 source to 406x720, captions were burned at that size, and export.py upscaled them
1406
+ soft. A preset that names a delivery frame of the same aspect is that frame.
1407
+ The match is 2.2.1's, looser than aspect_ratio(): `16/9` and `1.78:1` still take a 16:9
1408
+ preset's size. A render that hands such a frame.aspect to fit.py fails there, as in 2.2.1;
1409
+ one whose own fit.aspect replaces it, or that stops before fit, is sized by this match, and
1410
+ a patch release does not change a render 2.2.1 completed."""
1411
+ if not frame.get("aspect") or frame.get("width") or frame.get("height"):
1412
+ return
1413
+ preset = PRESETS.get(str(export.get("preset") or ""), {})
1414
+ if not (preset.get("w") and preset.get("h")):
1415
+ return
1416
+ m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*[:/]\s*(\d+(?:\.\d+)?)\s*", str(frame["aspect"]))
1417
+ if not m or float(m.group(2)) == 0:
1418
+ return
1419
+ if abs(float(m.group(1)) / float(m.group(2)) - preset["w"] / preset["h"]) > 0.01:
1420
+ return
1421
+ frame["width"], frame["height"] = preset["w"], preset["h"]
1422
+ warn(f"frame: {preset['w']}x{preset['h']} from the {export['preset']} export preset (captions and overlays are sized for delivery)",
1423
+ "frame_from_export_preset", preset=export["preset"], width=preset["w"], height=preset["h"])
1424
+
1425
+
1426
+ def export_timeline(proj: Dict[str, Any], rel, dest: str) -> int:
1427
+ """--export-timeline: the project's cut as an editor timeline, nothing rendered (_common.timeline)."""
1428
+ from _common import timeline as tlmod
1429
+ fmt = tlmod.FORMATS.get(Path(dest).suffix.lower())
1430
+ if not fmt:
1431
+ die(f"--export-timeline {dest}: unknown timeline format", kind="input",
1432
+ hint="name the file .fcpxml, .edl or .otio")
1433
+ paths = [rel(c["src"]) for c in proj.get("clips") or [] if c.get("src")]
1434
+ if (proj.get("audio") or {}).get("music"):
1435
+ paths.append(rel(proj["audio"]["music"]))
1436
+ probes: Dict[str, Dict[str, Any]] = {}
1437
+ for path in paths:
1438
+ if path in probes:
1439
+ continue # one ffprobe per file: ten clips of one recording are one probe (A267)
1440
+ if not os.path.exists(path):
1441
+ die(f"timeline source {absent_word(path)}: {path}")
1442
+ probes[path] = probe(path) # a timeline needs real durations and rates, dry run or not
1443
+ # the sequence frame is the one the render would deliver: an aspect-only frame takes its size
1444
+ # from the export preset exactly as the render's own frame does. An export that is not an
1445
+ # object names no preset here: 2.2.1's export never read it, and validate_project() refuses
1446
+ # it only in the render, which reads it.
1447
+ frame = dict(proj.get("frame") or {})
1448
+ export = proj.get("export")
1449
+ frame_from_preset(frame, export if isinstance(export, dict) else {})
1450
+ fit = proj.get("fit")
1451
+ if isinstance(fit, dict):
1452
+ # the render's fit stage reframes the picture with the fit object's aspect, mode, sides
1453
+ # and rate, the frame's only where the fit object has none (the render's setdefault), so
1454
+ # the sequence takes them by the same rule (#506: frame 16:9 with fit 1:1 rendered a
1455
+ # square and exported 1920x1080). One rule for any number of clips (#526): several clips
1456
+ # are joined and then fitted by that same fit.py call, and their sequence was the frame's
1457
+ # (frame 16:9 with fit 1:1 over two 160x120 clips rendered 120x120 and exported 160x90)
1458
+ if fit.get("aspect") and aspect_ratio(str(fit["aspect"])) is None:
1459
+ die(f"--export-timeline: fit.aspect {fit['aspect']!r}: use W:H with whole numbers, like 16:9 "
1460
+ "(fit.py refuses it too)", kind="input")
1461
+ if fit.get("fit") is not None and fit["fit"] not in ("pad", "crop", "blur"):
1462
+ die(f"--export-timeline: fit.fit {fit['fit']!r}: use pad, crop or blur (fit.py's --fit)", kind="input")
1463
+ frame.update({k: fit[k] for k in ("aspect", "fit", "width", "height", "fps") if fit.get(k) is not None})
1464
+ try:
1465
+ tl = tlmod.build(dict(proj, frame=frame), probes, rel)
1466
+ text = tlmod.WRITERS[fmt](tl) # a writer refuses what its format cannot hold (EDL: 999 events, 24 h)
1467
+ except tlmod.TimelineError as exc:
1468
+ die(f"--export-timeline: {exc}", kind="input")
1469
+ report = tlmod.summary(tl, fmt)
1470
+ _check_output_path(["ffmpeg", dest])
1471
+ _check_existing_output(["ffmpeg", dest])
1472
+ verification: List[Dict[str, Any]] = []
1473
+ if not STATE.dry_run:
1474
+ try:
1475
+ Path(dest).write_text(text, encoding="utf-8")
1476
+ except OSError as exc:
1477
+ die(f"cannot write {dest}: {exc}", kind="output")
1478
+ verification.append({"step": "parse", "ok": tlmod.parses(dest, fmt)})
1479
+ for line in report["not_exported"]:
1480
+ info(f"not exported: {line}")
1481
+ info(("[dry-run] would write " if STATE.dry_run else "wrote ") +
1482
+ f"{dest} ({fmt}, {report['clips']} clips, {report['duration']}s at {report['rate']} fps)")
1483
+ emit(dest, timeline=report, verification=verification)
1484
+ return 0
1485
+
1486
+
1487
+ def _has_sound(current: str, proj: Dict[str, Any], rel: Any) -> bool:
1488
+ """Whether the render carries sound at this point: measured on the intermediate when it
1489
+ exists, otherwise (a dry run) from the sources: a clip with an audio stream, music or a
1490
+ replacement track."""
1491
+ if os.path.exists(current) and not STATE.dry_run: # a dry run may find an earlier render's file there
1492
+ return bool((probe(current).get("audio") or {}).get("codec"))
1493
+ au = proj.get("audio") or {}
1494
+ if au.get("music") or au.get("replace"):
1495
+ return True
1496
+ for c in proj.get("clips") or []:
1497
+ src = rel(c["src"]) if isinstance(c, dict) and c.get("src") else None
1498
+ if not src or not os.path.exists(src) or (probe(src).get("audio") or {}).get("codec"):
1499
+ return True
1500
+ return False
1501
+
1502
+
1503
+ def cache_report(cache_dir: Optional[str]) -> Optional[Dict[str, Any]]:
1504
+ """The result's `cache` object (None without --cache), with its stderr summary line."""
1505
+ if not cache_dir:
1506
+ return None
1507
+ report = {"dir": CACHE["dir"], "ffmpeg": CACHE["ffmpeg"],
1508
+ "hits": CACHE["hits"], "misses": CACHE["misses"], "miss_reasons": CACHE["miss_reasons"],
1509
+ "saved_seconds": round(CACHE["saved_seconds"], 1),
1510
+ "entries": CACHE["entries"]}
1511
+ if STATE.dry_run:
1512
+ report["would_hit"] = CACHE["would_hit"]
1513
+ info(f"cache: {len(CACHE['hits'])} hit(s) ({', '.join(CACHE['hits']) or '-'}), "
1514
+ f"{len(CACHE['misses'])} miss(es) ({', '.join(CACHE['misses']) or '-'})")
1515
+ return report
1516
+
1517
+
1518
+ # One container family: a copy of an MP4 file named .mov (or .m4v, .m4a, .3gp) is the bytes that
1519
+ # name says. Every other pair of extensions names two different containers.
1520
+ ISO_BMFF_EXT = frozenset({".mp4", ".mov", ".m4v", ".m4a", ".3gp"})
1521
+
1522
+
1523
+ def refuse_copied_container(have: str, output: str) -> None:
1524
+ """Refuse delivering a file of container `have` (an extension) by copying it to `output`
1525
+ under another container's name: with no export stage nothing converts it (A84)."""
1526
+ want = Path(output).suffix.lower()
1527
+ if have == want or (have in ISO_BMFF_EXT and want in ISO_BMFF_EXT):
1528
+ return
1529
+ die(f"output {output}: this project has no \"export\" stage, so the delivery is the last stage's "
1530
+ f"{have or 'extension-less'} file copied as it is, which the name {want or '(no extension)'} would mislabel -- "
1531
+ f"name the output {have or 'with that extension'}, or add an \"export\" stage, which writes the container "
1532
+ "its preset names", kind="input", hint=f"\"output\": \"{Path(output).with_suffix(have).name}\"" if have else None)
1533
+
1534
+
1535
+ # A98: the stage files a render with an explicit --work wrote there, {real path: owned_identity()},
1536
+ # kept in <work>/.ffskill-render-stages.json. A later run with the same --work replaces one of them
1537
+ # without --overwrite while it is still that file (the overwrite rule's "this run's own file",
1538
+ # extended to an earlier render of the same work directory); one edited, replaced or never
1539
+ # written by render is refused as before.
1540
+ _OWN_STAGES: Dict[str, Any] = {"dir": None, "files": {}, "manifest": None}
1541
+
1542
+
1543
+ def own_stage_files(work: Path, load: bool) -> None:
1544
+ """Start this run's record of its stage files in `work`, reading an earlier render's when
1545
+ `load` (an explicit --work; the default directory is new every run)."""
1546
+ _OWN_STAGES.update(dir=os.path.realpath(str(work)), files={}, manifest=str(work / ".ffskill-render-stages.json") if load else None)
1547
+ if load:
1548
+ try:
1549
+ doc = json.loads(Path(_OWN_STAGES["manifest"]).read_text(encoding="utf-8"))
1550
+ except (OSError, ValueError):
1551
+ doc = {}
1552
+ files = doc.get("files") if isinstance(doc, dict) else None
1553
+ if isinstance(files, dict):
1554
+ _OWN_STAGES["files"] = {k: v for k, v in files.items() if isinstance(k, str) and isinstance(v, dict)}
1555
+
1556
+
1557
+ def _earlier_own_stage_file(dest: Optional[str]) -> bool:
1558
+ """Whether `dest`, a stage's output in the work directory, is a file an earlier render with
1559
+ this --work wrote there and nothing has changed since."""
1560
+ if not dest or not _OWN_STAGES["manifest"] or not os.path.isfile(dest):
1561
+ return False
1562
+ real = os.path.realpath(dest)
1563
+ if os.path.dirname(real) != _OWN_STAGES["dir"]:
1564
+ return False
1565
+ expected = _OWN_STAGES["files"].get(real)
1566
+ return isinstance(expected, dict) and owned_identity(real) == expected
1567
+
1568
+
1569
+ def _record_own_stage_file(dest: Optional[str]) -> None:
1570
+ """Remember a stage file this run put in the --work directory, as it is now. A manifest that
1571
+ cannot be written only means the next run refuses that file as before."""
1572
+ if STATE.dry_run or not dest or not _OWN_STAGES["manifest"] or not os.path.isfile(dest):
1573
+ return
1574
+ real = os.path.realpath(dest)
1575
+ if os.path.dirname(real) != _OWN_STAGES["dir"]:
1576
+ return
1577
+ ident = owned_identity(real)
1578
+ if ident:
1579
+ _OWN_STAGES["files"][real] = ident
1580
+ try:
1581
+ Path(_OWN_STAGES["manifest"]).write_text(json.dumps({"files": _OWN_STAGES["files"]}, indent=1), encoding="utf-8")
1582
+ except OSError:
1583
+ pass
1584
+
1585
+
1586
+ def guidance_warns(check_doc: Optional[Dict[str, Any]]) -> List[str]:
1587
+ """The rows of a check result that are over the platform table's upload limit (#485): WARN,
1588
+ `basis: guidance`. The check passes with them, so each place that says a check passed names
1589
+ them, with the limit, for whoever uploads to compare with the platform's current one."""
1590
+ return [f"{r['check']}={r['value']} (expected {r['expected']})" for r in (check_doc or {}).get("checks", [])
1591
+ if r.get("basis") == "guidance" and r.get("status") == "WARN"]
1592
+
1593
+
1594
+ def planned_clip_length(clip: Dict[str, Any], src: str, index: int) -> float:
1595
+ """A dry run's length of clip `index` before its speed stage: the source's measured length,
1596
+ or its in..out range of it (the cut a real run measures does not exist yet). Only when neither
1597
+ can be read is the speed planned on a stand-in 10 s, and that is recorded (A97): a plan that
1598
+ gave no sign its fit.py --duration came from an invented number read as a measured one."""
1599
+ from _common.decision import parse_time
1600
+ length = fps = None
1601
+ if os.path.isfile(src):
1602
+ meta = probe(src)
1603
+ length = meta.get("duration") or None
1604
+ # hh:mm:ss:ff needs the source's rate, which the real cut reads from the same place
1605
+ fps = (meta.get("video") or {}).get("fps") or None
1606
+ try:
1607
+ start = parse_time(str(clip["in"]), fps) if clip.get("in") is not None else 0.0
1608
+ end = parse_time(str(clip["out"]), fps) if clip.get("out") is not None else length
1609
+ except ValueError:
1610
+ start, end = 0.0, None
1611
+ if end is not None and end - start > 0:
1612
+ return end - start
1613
+ record_skip(f"[dry-run] clip {index}: its length could not be read before the cut exists, so the speed stage is "
1614
+ "planned on a stand-in 10 s; a real run measures the cut", "speed_length_placeholder",
1615
+ stage="clips", clip=index, path=src, placeholder_seconds=10.0)
1616
+ return 10.0
1617
+
1618
+
1619
+ def main() -> int:
1620
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1621
+ ap.add_argument("project", nargs="?", help="project.json, or a plan.json written by <tool> --plan")
1622
+ ap.add_argument("--init", metavar="FILE", help="write a starter project file and exit")
1623
+ ap.add_argument("--work", help="work directory for intermediates (default: <output>_work)")
1624
+ ap.add_argument("--keep", action="store_true", help="keep intermediates (default: kept only when --work is given)")
1625
+ ap.add_argument("--cache", metavar="DIR",
1626
+ help="reuse the artifacts of identical stages from a previous run. Opt-in: "
1627
+ "there is no default directory. The ffmpeg version and the skill version "
1628
+ "are part of every key, so a cache never crosses either.")
1629
+ ap.add_argument("--from", dest="from_stage", metavar="STAGE",
1630
+ choices=list(STAGE_ORDER),
1631
+ help="start at this stage, taking every earlier one from --cache; refuses if "
1632
+ "one of them is not there")
1633
+ ap.add_argument("--export-timeline", metavar="FILE",
1634
+ help="export an editor timeline (.fcpxml, .edl or .otio) without rendering media. "
1635
+ "The result lists the project elements omitted by the format.")
1636
+ ap.add_argument("--audit-log", metavar="FILE",
1637
+ help="append the audit records of this run (a refused plan, a lock taken over, ...) to FILE as JSON lines; "
1638
+ "default for a refused plan: <plan>.audit.jsonl next to it. A record that cannot be written is a "
1639
+ "warning, never a failure")
1640
+ ap.add_argument("--intermediate-preset", default="superfast", choices=X264_PRESETS,
1641
+ help="x264/x265 preset of the stages before an encoding export (default superfast: the export "
1642
+ "re-encodes them, and its own preset sets the delivered quality); medium = the stages' own default. "
1643
+ "Not used without an export stage, with --stop-after before it, with --fast, or for a copy export")
1644
+ ap.add_argument("--stop-after", choices=["clips", "join", "silence", "fit", "captions", "graphics", "overlays", "audio", "loudness", "export"], help="stop after this stage (for iterating)")
1645
+ tpl = ap.add_argument_group("delivery templates (one command per destination)")
1646
+ tpl.add_argument("--template", metavar="NAME", help="render INPUT with a shipped template: " + ", ".join(template_names())
1647
+ + ", a comma-separated list, or 'all' (the social pack)")
1648
+ tpl.add_argument("--list-templates", action="store_true", help="print the templates with their frames, limits and safe zones, and exit")
1649
+ tpl.add_argument("--cues", help="cue file for the template's captions (caption.py --text format)")
1650
+ tpl.add_argument("--srt", help="SRT file for the template's captions instead of --cues")
1651
+ tpl.add_argument("--logo", help="logo image the template overlays")
1652
+ tpl.add_argument("--title", help="title text for the template's opening card / lower third")
1653
+ tpl.add_argument("--brand", help="brand.json the template's captions, graphics and overlays use")
1654
+ tpl.add_argument("--chapters", help="chapter file (podcast template)")
1655
+ tpl.add_argument("--image", help="still image behind the visualisation (audiogram template); a local file, nothing is fetched")
1656
+ tpl.add_argument("--fit", choices=["crop", "pad", "blur"], help="override how the template reaches its aspect")
1657
+ tpl.add_argument("-o", "--output", help="output file (default: next to the input, <input>_<template>.mp4, "
1658
+ "or .m4a for an audio-only destination); for a list of templates "
1659
+ "or 'all' its directory is where the pack is written")
1660
+ tpl.add_argument("--write-project", metavar="FILE", help="write the filled project.json for editing and stop (no render)")
1661
+ add_common(ap)
1662
+ add_hw_orchestrator_args(ap)
1663
+ args = ap.parse_args()
1664
+ apply_common(args)
1665
+ PROJECT_SOURCE.update(src=None, timecode=[])
1666
+ WORK_DIR["path"] = None
1667
+ DELIVERY["path"] = None
1668
+ STATE.audit_log = os.path.abspath(args.audit_log) if args.audit_log else None
1669
+
1670
+ if args.list_templates:
1671
+ list_templates()
1672
+ return 0
1673
+ if args.init:
1674
+ guard_sidecar(args.init)
1675
+ Path(args.init).write_text(json.dumps(TEMPLATE, indent=2) + "\n", encoding="utf-8")
1676
+ info(f"wrote {args.init}; edit clips/src and run: render.py {args.init}")
1677
+ # the path alone, or under --json the document every other mode prints (A102)
1678
+ emit(args.init, stages=[], check=None)
1679
+ return 0
1680
+ if not args.project:
1681
+ die("give a project.json (or --init FILE, or --template NAME INPUT)")
1682
+ if STATE.plan:
1683
+ die("render.py has no --plan: the project file is the plan (use --dry-run to preview it)")
1684
+ if args.template:
1685
+ # `render.py --template tiktok talk.mp4 ...`: the positional is the footage, not a project.
1686
+ args.input = args.project
1687
+ if not os.path.isfile(args.input):
1688
+ die(f"input {absent_word(args.input)}: {args.input}")
1689
+ names = expand_templates(args.template)
1690
+ if len(names) > 1:
1691
+ if args.write_project:
1692
+ die("--write-project writes one project; name a single template")
1693
+ # A85: a pack runs one full render per destination and handed none of these to them,
1694
+ # so --stop-after did not stop, --cache was not read and --work/--keep kept nothing
1695
+ for flag, value in (("--stop-after", args.stop_after), ("--cache", args.cache), ("--from", args.from_stage),
1696
+ ("--work", args.work), ("--keep", args.keep), ("--export-timeline", args.export_timeline)):
1697
+ if value:
1698
+ die(f"{flag} applies to one render, and --template {args.template} is a pack of {len(names)} "
1699
+ f"({', '.join(names)}), each a full render of its own: name a single template to use {flag}")
1700
+ return render_pack(names, args)
1701
+ proj: Dict[str, Any] = template_project(names[0], args)
1702
+ base = Path.cwd()
1703
+ else:
1704
+ for flag, value in (("--cues", args.cues), ("--srt", args.srt), ("--logo", args.logo),
1705
+ ("--title", args.title), ("--brand", args.brand), ("--chapters", args.chapters),
1706
+ ("--image", args.image), ("--fit", args.fit), ("--write-project", args.write_project)):
1707
+ if value:
1708
+ die(f"{flag} belongs to --template NAME INPUT; a project.json states it in the project itself")
1709
+ try:
1710
+ # read_json(): nesting too deep is a ValueError too, refused here, not a RecursionError
1711
+ proj = read_json(args.project)
1712
+ except (OSError, ValueError) as exc:
1713
+ die(f"cannot read project: {exc}", kind="input")
1714
+ if not isinstance(proj, dict):
1715
+ die(f"{args.project}: not a project or plan object (top level is {type(proj).__name__})")
1716
+ if "plan_version" in proj:
1717
+ return execute_plan(proj, os.path.abspath(args.project))
1718
+ base = Path(args.project).resolve().parent
1719
+ validate_project(proj, timeline=bool(args.export_timeline), stop_after=args.stop_after)
1720
+ if args.write_project:
1721
+ # Only the filled project: the point is to edit it before rendering, so nothing runs.
1722
+ # the project file and every clip it names are inputs the JSON must not replace
1723
+ where = Path(args.project).resolve().parent if args.project else Path.cwd()
1724
+ srcs = [c["src"] for c in proj.get("clips") or [] if isinstance(c, dict) and isinstance(c.get("src"), str)]
1725
+ # every file the project reads, not only its clips: a template's brand, its font_file and
1726
+ # logo, the cue or SRT file, the chapters (review of #534's sweep: --write-project naming
1727
+ # the brand's font or logo replaced it with the JSON)
1728
+ guard_sidecar(args.write_project, args.project, *[str(where / s) for s in srcs],
1729
+ *project_input_files(proj, lambda p: p if os.path.isabs(str(p)) else str(where / str(p))))
1730
+ try:
1731
+ Path(args.write_project).write_text(json.dumps(proj, indent=2) + "\n", encoding="utf-8")
1732
+ except OSError as exc:
1733
+ die(f"cannot write {args.write_project}: {exc}", kind="output")
1734
+ info(f"wrote {args.write_project}; edit it and run: render.py {args.write_project}")
1735
+ emit(args.write_project, template=args.template, stages=[], check=None)
1736
+ return 0
1737
+
1738
+ # every file the project names is read against the project file's directory (a template's,
1739
+ # the working directory): the same keys batch.py and multicam.py rebase on a copy they write
1740
+ # elsewhere, including the two rel() below never saw (audiogram.image, overlays[].font_file
1741
+ # were read against the working directory)
1742
+ proj = rebase_project_paths(proj, base)
1743
+
1744
+ def rel(p: Any) -> str:
1745
+ p = str(p)
1746
+ return p if os.path.isabs(p) else str(base / p)
1747
+
1748
+ if isinstance(proj.get("chapters"), str) and not os.path.exists(rel(proj["chapters"])):
1749
+ die(f"chapters file {absent_word(rel(proj['chapters']))}: {rel(proj['chapters'])}")
1750
+
1751
+ if args.export_timeline:
1752
+ return export_timeline(proj, rel, args.export_timeline)
1753
+
1754
+ clips = proj.get("clips") or []
1755
+ if not clips:
1756
+ die("project.clips is empty")
1757
+ output = rel(proj.get("output") or "final.mp4")
1758
+ # the final stage is a copy from the work dir, so run()'s own guard never sees the sources
1759
+ # (review 5): every file the project names is passed here, not only the clips, or --overwrite
1760
+ # replaced a music bed or a brand file named as the output
1761
+ if not args.stop_after or args.stop_after == "export":
1762
+ # only a run that ends in the final copy writes `output`; a --stop-after preview writes
1763
+ # its stage file inside the work directory and leaves `output` alone
1764
+ refuse_output_is_input(output, *([os.path.abspath(args.project)] if args.project else []), *project_input_files(proj, rel))
1765
+ if _reaches("overlays", args.stop_after):
1766
+ # #326: an overlay video is the caller's file, never an earlier stage's output, so a
1767
+ # missing one is refused here, under --dry-run too, not after every stage before it ran
1768
+ for i, ov in enumerate(proj.get("overlays") or []):
1769
+ if ov.get("video"):
1770
+ layer = rel(ov["video"])
1771
+ refuse_output_is_input(output, layer)
1772
+ if not os.path.isfile(layer):
1773
+ die(f"overlays[{i}].video: file {absent_word(layer)}: {layer}", kind="input")
1774
+ # 2.0 refuses an existing output without --overwrite; the final place_output() would, but
1775
+ # only after every stage had run -- say so before the first one instead
1776
+ _check_existing_output(["ffmpeg", output])
1777
+ # The default work dir name comes only from the output path, with no PID or timestamp --
1778
+ # two concurrent render.py runs targeting the same output (a batch.py "project" recipe
1779
+ # processing several files in parallel, or simply running render.py twice by mistake) shared
1780
+ # the same work directory and clobbered each other's same-named intermediates (clip00.mp4,
1781
+ # fit.mp4, ...) mid-run. An explicit --work is left as given (the caller asked for that exact,
1782
+ # shared path, e.g. to inspect intermediates across runs); only the auto-derived default is
1783
+ # made unique per process, since it's the one that's also auto-deleted at the end.
1784
+ # Intermediates keep the delivery's media kind: a .mp4 project is unchanged (every stage file
1785
+ # is still clipNN.mp4 / fit.mp4 / loudnorm.mp4), while an audio-only delivery (the podcast
1786
+ # template) carries its stages through the audio container instead of a video one.
1787
+ mid = Path(output).suffix.lower() if Path(output).suffix.lower() in AUDIO_EXT else ".mp4"
1788
+ ex_cfg = proj.get("export")
1789
+ # .wma, before the copied-container rule below names .mp4 for it (#517). Only a run that reaches
1790
+ # the delivery: a --stop-after preview writes no file under the name. A single uncut clip is
1791
+ # left to the stages (each refuses its own encode into .wma) and to the copy at the end, which
1792
+ # checks what the source really is -- a WMA source no stage touches is delivered as it was.
1793
+ c_only = clips[0] if len(clips) == 1 and isinstance(clips[0], dict) else None
1794
+ if (not args.stop_after or args.stop_after == "export") and not (
1795
+ c_only is not None and c_only.get("in") is None and c_only.get("out") is None):
1796
+ refuse_unwritten_output(output)
1797
+ if (not args.stop_after or args.stop_after == "export") and not (isinstance(ex_cfg, dict) and ex_cfg.get("preset")):
1798
+ # A84: with no export stage the delivery is the last stage's file copied as it is, so a
1799
+ # .webm/.mkv name was MP4 bytes, completed and verified. Refused before the first stage
1800
+ # when the last file is certainly an intermediate; a single uncut clip that no stage
1801
+ # touches is the source itself, and the copy below checks what it really is.
1802
+ c0 = clips[0] if len(clips) == 1 and isinstance(clips[0], dict) else None
1803
+ passthrough = c0 is not None and c0.get("in") is None and c0.get("out") is None
1804
+ if not passthrough:
1805
+ refuse_copied_container(mid, output)
1806
+ # #510: a filter or an encoder this build lacks is found by the stage that needs it; the dry run
1807
+ # finds it before anything is encoded, so a real render runs its own dry run first
1808
+ refuse_missing_components_first(str(HERE / "render.py"), "stage's filters and encoders")
1809
+ # A77: the default work directory is new for every run (mkdtemp), not named by the PID alone and
1810
+ # reused with exist_ok -- a later run that got the same PID deleted an earlier run's kept preview.
1811
+ # An explicit --work is the caller's: created when missing, never emptied.
1812
+ created_work = bool(args.work) and not Path(args.work).exists()
1813
+ try:
1814
+ if args.work:
1815
+ work = Path(args.work)
1816
+ work.mkdir(parents=True, exist_ok=True)
1817
+ else:
1818
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
1819
+ work = Path(tempfile.mkdtemp(prefix=f"{Path(output).with_suffix('').name}_work_{os.getpid()}_",
1820
+ dir=str(Path(output).parent)))
1821
+ created_work = True
1822
+ except OSError as e:
1823
+ die(f"cannot create the work directory {args.work or Path(output).parent}: {e}")
1824
+ own_stage_files(work, load=bool(args.work))
1825
+ # --stop-after before the export reports a stage file inside the work directory as its output:
1826
+ # removing the directory at exit deleted the file the result named (and its output_identity)
1827
+ previewing = bool(args.stop_after) and args.stop_after != "export" and not STATE.dry_run
1828
+ if previewing and not args.keep and not args.work:
1829
+ info(f"--stop-after {args.stop_after}: keeping the work directory {work}, since the result's output is in it")
1830
+ if (not args.keep and not args.work and not previewing) or (STATE.dry_run and created_work):
1831
+ # a failed or dry run used to leave <output>_work_<pid>/ behind (sweep F15): the
1832
+ # auto-named directory is ours alone, so remove it on every exit path; a dry run removes
1833
+ # a --work directory it created too, --keep or not (A99: a plan leaves nothing behind)
1834
+ import atexit
1835
+ atexit.register(lambda: shutil.rmtree(work, ignore_errors=True))
1836
+ STATE.temp_dirs.append(str(work)) # removed at exit: a stop does not call its files kept (#510)
1837
+ WORK_DIR["path"] = str(work)
1838
+ DELIVERY["path"] = output
1839
+ # #510: the captions stage's generated SRT is delivered beside the output, so its guards are
1840
+ # the output's, once the output's folder exists (created above, as for the output) and
1841
+ # before the first stage: an existing one, an input, the output itself
1842
+ caption_srt = None
1843
+ cap_cfg = proj.get("captions")
1844
+ if (isinstance(cap_cfg, dict) and cap_cfg.get("text") and _reaches("captions", args.stop_after)
1845
+ and (not args.stop_after or args.stop_after == "export")):
1846
+ caption_srt = os.path.splitext(output)[0] + ".srt"
1847
+ guard_sidecar(caption_srt, *([os.path.abspath(args.project)] if args.project else []), *project_input_files(proj, rel),
1848
+ siblings=(output,))
1849
+ frame = dict(proj.get("frame") or {})
1850
+ trans = proj.get("transition") or {}
1851
+ frame_from_preset(frame, proj.get("export") or {})
1852
+ brand_args: List[str] = ["--brand", rel(proj["brand"])] if proj.get("brand") else []
1853
+ # A project written from a delivery template names its destination, so the caption and
1854
+ # graphics stages are told which zones that app's UI covers; the template's own explicit
1855
+ # margin/size still win inside those tools. A hand-written project (no "template" key) is
1856
+ # unchanged -- it never gets a --platform it did not ask for.
1857
+ dest = str(((proj.get("check") or {}).get("platform") or "")) if proj.get("template") else ""
1858
+ platform_args: List[str] = ["--platform", dest] if dest in PLATFORMS and PLATFORMS[dest].get("frame") else []
1859
+ # a malformed "export" is refused by the export stage with its own message; here it only means
1860
+ # "no encoding export", never a traceback before that refusal
1861
+ ex_preset = str(ex_cfg.get("preset") or "") if isinstance(ex_cfg, dict) else ""
1862
+ if (ex_preset and "copy" not in PRESETS.get(ex_preset, {}).get("video", [])
1863
+ and args.stop_after in (None, "export") and args.intermediate_preset != "medium" and not STATE.fast):
1864
+ INTERMEDIATE["preset"] = args.intermediate_preset
1865
+ stages_done: List[str] = []
1866
+ captioned_srt: Optional[Dict[str, Any]] = None
1867
+ # what the caption stage reported (wrapped/split counts and the fit-size keys), so a caller
1868
+ # reading render.py's JSON can see whether the type was shrunk to fit or a cue was split.
1869
+ caption_report: Optional[Dict[str, Any]] = None
1870
+ stage_pictures: Dict[str, Any] = {}
1871
+ picture_fields: Dict[str, Any] = {}
1872
+
1873
+ CACHE.clear()
1874
+ CACHE.update(_fresh_cache())
1875
+ CONTENT_KEYED.clear()
1876
+ PROJECT_SOURCE.update(src=project_source(proj, rel), timecode=[])
1877
+ if args.cache:
1878
+ cdir = Path(args.cache)
1879
+ try:
1880
+ if STATE.dry_run:
1881
+ if (cdir.exists() or cdir.is_symlink()) and not cdir.is_dir():
1882
+ raise NotADirectoryError(cdir)
1883
+ else:
1884
+ cdir.mkdir(parents=True, exist_ok=True)
1885
+ with tempfile.NamedTemporaryFile(prefix=".ffskill-cache-", dir=cdir):
1886
+ pass
1887
+ except OSError as exc:
1888
+ die(f"--cache {args.cache}: not a writable directory ({exc})", kind="output")
1889
+ CACHE["dir"] = str(cdir)
1890
+ CACHE["ffmpeg"] = ffmpeg_banner()
1891
+ CACHE["entries"] = len(list(cdir.glob("*.json")))
1892
+ CACHE["from"] = args.from_stage
1893
+ if args.from_stage and not args.cache:
1894
+ die(f"--from {args.from_stage} needs --cache DIR with a previous run's stages: without a "
1895
+ "cache there is no earlier artifact to start from, so every stage would run anyway.",
1896
+ kind="input")
1897
+
1898
+ # A project may ask for its clip boundaries to land on the music's beat. The measurement and
1899
+ # the refusal both live in cut.py -- render forwards the request and reports what came back,
1900
+ # so a project that does not name "snap" builds the command line 1.16 built.
1901
+ snap_spec = proj.get("snap") or {}
1902
+ snap_reports: List[Dict[str, Any]] = []
1903
+ check_snap_to(snap_spec, "snap")
1904
+
1905
+ # ---- clips
1906
+ # 2.2.1: every clip source is checked before the first one is cut, and every problem is named
1907
+ # in one refusal -- before, clip 7's missing file surfaced after clips 0-6 had been cut, and
1908
+ # only the first of several missing sources was reported per run.
1909
+ problems: List[Dict[str, Any]] = []
1910
+ for i, c in enumerate(clips):
1911
+ src = rel(c["src"])
1912
+ if path_denied(src) or not os.path.exists(src): # under --dry-run too: a plan for a missing file is no plan
1913
+ problems.append({"index": i, "path": src, "reason": "permission denied" if path_denied(src) else "missing"})
1914
+ elif os.path.isdir(src):
1915
+ problems.append({"index": i, "path": src, "reason": "a directory, not a file"})
1916
+ elif os.path.getsize(src) == 0:
1917
+ problems.append({"index": i, "path": src, "reason": "empty (0 bytes)"})
1918
+ elif not STATE.dry_run:
1919
+ # 2.2.4: readable, too -- one ffprobe per source, nothing decoded, the same test
1920
+ # join.py's preflight makes. Before, a real run probed the sources one by one and
1921
+ # stopped at the first unreadable file; the dry run already named every one via join.
1922
+ proc = run([require_tool("ffprobe"), "-v", "error", "-show_entries", "stream=codec_type",
1923
+ "-of", "csv=p=0", src], quiet=True, check=False)
1924
+ kinds = {line.strip() for line in (proc.stdout or "").splitlines() if line.strip()}
1925
+ if proc.returncode != 0 or not kinds & {"audio", "video"}:
1926
+ first = ((proc.stderr or "").strip().splitlines() or ["no audio or video stream"])[-1]
1927
+ problems.append({"index": i, "path": src, "reason": f"unreadable: {first}"})
1928
+ if problems:
1929
+ die(f"{len(problems)} of {len(clips)} clip sources unusable: "
1930
+ + "; ".join(f"clip {p['index']}: {p['reason']}: {p['path']}" for p in problems),
1931
+ kind="input", problems=problems,
1932
+ hint="fix or remove these clips in the project; nothing was cut")
1933
+
1934
+ parts: List[str] = []
1935
+ for i, c in enumerate(clips):
1936
+ src = rel(c["src"])
1937
+ needs_cut = c.get("in") is not None or c.get("out") is not None
1938
+ part = str(work / f"clip{i:02d}{mid}")
1939
+ if needs_cut:
1940
+ argv: List[Any] = [src, "-o", part, "--accurate"]
1941
+ if c.get("in") is not None:
1942
+ argv += option_args("--start", c["in"])
1943
+ if c.get("out") is not None:
1944
+ argv += option_args("--end", c["out"])
1945
+ clip_snap = dict(snap_spec)
1946
+ clip_snap.update(c.get("snap") or {})
1947
+ if str(clip_snap.get("to") or "none") == "beats":
1948
+ argv += ["--snap", "beats"]
1949
+ if clip_snap.get("tolerance") is not None:
1950
+ argv += option_args("--snap-tolerance", clip_snap["tolerance"])
1951
+ if clip_snap.get("min_confidence") is not None:
1952
+ argv += option_args("--min-confidence", clip_snap["min_confidence"])
1953
+ if clip_snap.get("source"):
1954
+ argv += ["--snap-source", rel(clip_snap["source"])]
1955
+ sh("cut.py", *argv, stage="clips")
1956
+ if _LAST_DOC.get("snap"):
1957
+ snap_reports.append({"clip": i, **_LAST_DOC["snap"]})
1958
+ elif _LAST_DOC.get("cached") and str(clip_snap.get("to") or "none") == "beats":
1959
+ # The cut is the one the cache holds, so it WAS snapped -- the moves are simply
1960
+ # not re-measured. Saying `snap: null` here would report the opposite.
1961
+ snap_reports.append({"clip": i, "mode": "beats", "source": "cache",
1962
+ "note": "this clip came from --cache; it was snapped when "
1963
+ "it was first rendered and the moves are in that "
1964
+ "run's result"})
1965
+ else:
1966
+ part = src
1967
+ if c.get("speed"):
1968
+ spd = float(c["speed"])
1969
+ if not (spd > 0) or spd != spd or spd == float("inf"):
1970
+ die(f"clip {i}: speed must be a positive number, got {c['speed']!r}")
1971
+ if abs(spd - 1.0) > 1e-6: # speed 1.0 used to cost a full re-encode for nothing
1972
+ dur = (probe(part).get("duration") or 0.0) if not STATE.dry_run else planned_clip_length(c, src, i)
1973
+ fitted = str(work / f"clip{i:02d}_speed{mid}")
1974
+ sh("fit.py", part, "--duration", f"{dur / spd:.3f}", "--method", "speed", "-o", fitted, stage="clips")
1975
+ part = fitted
1976
+ parts.append(part)
1977
+ stages_done.append("clips")
1978
+ current = parts[0]
1979
+
1980
+ # ---- audiogram: the picture an audio-only source needs before anything else can work on it
1981
+ ag = proj.get("audiogram")
1982
+ if ag:
1983
+ if not ag.get("image") and not ag.get("background"):
1984
+ die('audiogram: give an "image" (a local file) or a "background" colour -- this skill '
1985
+ "never fetches a picture and never invents cover art", kind="input")
1986
+ nxt = str(work / f"audiogram{mid}")
1987
+ argv = [current, "-o", nxt]
1988
+ for key, flag in (("image", "--image"), ("image_fit", "--image-fit"), ("style", "--style"),
1989
+ ("position", "--position"), ("vis_height", "--vis-height"),
1990
+ ("opacity", "--opacity"), ("platform", "--platform"), ("title", "--title"),
1991
+ ("color", "--color"), ("background", "--background"),
1992
+ ("width", "--width"), ("height", "--height"), ("fps", "--fps")):
1993
+ if ag.get(key) is not None:
1994
+ value = ag[key]
1995
+ if key == "image" and isinstance(value, str) and "://" not in value:
1996
+ # against the project file, as every other path here and as the output guard
1997
+ # checks it; it used to reach waveform.py as written, against the cwd
1998
+ value = rel(value)
1999
+ argv += option_args(flag, value)
2000
+ argv += brand_args
2001
+ sh("waveform.py", *argv, stage="audiogram")
2002
+ current = nxt
2003
+ parts = [current]
2004
+ stages_done.append("audiogram")
2005
+
2006
+ if args.stop_after == "clips":
2007
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
2008
+ return 0
2009
+
2010
+ # ---- join
2011
+ join_crop_size = None
2012
+ if len(parts) > 1:
2013
+ current = str(work / f"joined{mid}")
2014
+ argv = list(parts) + ["-o", current, "--transition", trans.get("type", "fade"), "--duration", str(trans.get("duration", 0.5))]
2015
+ own_fit = proj.get("fit") if isinstance(proj.get("fit"), dict) else {}
2016
+ geometry = {**frame, **{k: v for k, v in own_fit.items() if v is not None}}
2017
+ jw, jh = frame.get("width"), frame.get("height")
2018
+ if geometry.get("fit") == "crop":
2019
+ # Crop each source into the delivery frame before it can acquire bars in the join.
2020
+ # Size it from the same source and effective frame as the exported timeline.
2021
+ aspect = geometry.get("aspect")
2022
+ ratio = aspect_ratio(str(aspect)) if aspect else None
2023
+ width, height = geometry.get("width"), geometry.get("height")
2024
+ if (not aspect or ratio is not None) and all(
2025
+ side is None or (str(side).isdecimal() and int(side) > 0) for side in (width, height)):
2026
+ fw, fh = display_size(probe(rel(clips[0]["src"])).get("video") or {})
2027
+ if fw and fh:
2028
+ size = frame_size(ratio, int(width) if width else None, int(height) if height else None, fw, fh)
2029
+ if min(size) > 0:
2030
+ join_crop_size = jw, jh = size
2031
+ argv += ["--fit", "crop"]
2032
+ if join_crop_size is None and bool(jw) != bool(jh):
2033
+ # the fit object's own value for that side wins (#526), so the join is sized from it:
2034
+ # frame {width 100} with fit {width 200} joined at 100x76 and was then fitted to
2035
+ # 200x152 (from the rounded canvas) against a 200x150 sequence (from the clip)
2036
+ if jw and own_fit.get("width") is not None and own_fit.get("height") is None:
2037
+ jw = own_fit["width"]
2038
+ elif jh and own_fit.get("height") is not None and own_fit.get("width") is None:
2039
+ jh = own_fit["height"]
2040
+ side = jw or jh
2041
+ if bool(jw) != bool(jh) and str(side).isdigit():
2042
+ # one side: the other follows the first clip's displayed aspect, rounded to even as
2043
+ # fit.py and the exported sequence round it (frame_size()). join.py rounds it down,
2044
+ # so {width 100} over 4:3 clips joined at 100x74 against a 100x76 sequence (#526).
2045
+ # A side join.py's argparse refuses is handed to it as written, to be refused there.
2046
+ fw, fh = display_size(probe(rel(clips[0]["src"])).get("video") or {})
2047
+ if fw and fh:
2048
+ jw, jh = frame_size(None, int(jw) if jw else None, int(jh) if jh else None, fw, fh)
2049
+ if jw:
2050
+ argv += option_args("--width", jw)
2051
+ if jh:
2052
+ argv += option_args("--height", jh)
2053
+ # the rate the render delivers: the fit object's where it gives one (#526). Joined at the
2054
+ # frame's and conformed again by fit.py, each clip was rounded twice: two 0.7 s clips
2055
+ # under frame 25 fps with fit 24 fps rendered 35 frames against a 34-frame sequence,
2056
+ # which rounds each clip once, at the delivered rate
2057
+ join_fps = own_fit.get("fps") or frame.get("fps")
2058
+ if join_fps:
2059
+ argv += option_args("--fps", join_fps)
2060
+ sh("join.py", *argv, stage="join")
2061
+ stages_done.append("join")
2062
+ if args.stop_after == "join":
2063
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
2064
+ return 0
2065
+
2066
+ # ---- silence
2067
+ sil = proj.get("silence")
2068
+ if sil:
2069
+ nxt = str(work / f"tight{mid}")
2070
+ argv = [current, "-o", nxt]
2071
+ for k, flag in (("threshold", "--threshold"), ("min_silence", "--min-silence"), ("margin", "--margin"),
2072
+ ("margin_lead", "--margin-lead"), ("margin_tail", "--margin-tail")):
2073
+ if sil.get(k) is not None:
2074
+ argv += option_args(flag, sil[k])
2075
+ sh("silence.py", *argv, stage="silence")
2076
+ current = nxt
2077
+ stages_done.append("silence")
2078
+ if args.stop_after == "silence":
2079
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used())
2080
+ return 0
2081
+
2082
+ # ---- fit (duration and/or frame)
2083
+ # a key the fit object gives as null is a key it does not give, as --export-timeline reads it:
2084
+ # frame 320x180 with fit {aspect 1:1, width null} rendered 180x180 against a 320x180 sequence
2085
+ fit = {k: v for k, v in (proj.get("fit") or {}).items() if v is not None}
2086
+ if frame.get("aspect"):
2087
+ fit.setdefault("aspect", frame["aspect"])
2088
+ if frame.get("fit"):
2089
+ fit.setdefault("fit", frame["fit"])
2090
+ # The fit object wins, for any number of clips (#526): fit.py gets its aspect, mode, sides and
2091
+ # rate, and the frame's only where it has none, so the delivered size is the one
2092
+ # --export-timeline states. Several clips were fitted inside the join, which join.py sizes
2093
+ # from the frame first, with the frame's sides only when the fit object gave no side or
2094
+ # aspect of its own: frame 16:9 with fit 1:1 over two 160x120 clips rendered 120x120 against
2095
+ # a 160x90 sequence, and fit {width 36} under a 72x128 frame rendered 36x64 where one clip
2096
+ # renders 36x128.
2097
+ # A join with no fit stage of its own already has the frame's sides and rate, and is not
2098
+ # re-encoded to state them again.
2099
+ if fit or len(parts) == 1:
2100
+ for key in ("width", "height"):
2101
+ if frame.get(key):
2102
+ fit.setdefault(key, frame[key])
2103
+ if frame.get("fps") and len(parts) == 1: # several clips: join.py has conformed them to it
2104
+ fit.setdefault("fps", frame["fps"])
2105
+ if join_crop_size is not None:
2106
+ # Reuse the rounded canvas instead of deriving its second side from the joined file.
2107
+ fit["width"], fit["height"] = join_crop_size
2108
+ if fit:
2109
+ nxt = str(work / f"fit{mid}")
2110
+ argv = [current, "-o", nxt]
2111
+ for k, flag in (("duration", "--duration"), ("method", "--method"), ("aspect", "--aspect"), ("fit", "--fit"), ("width", "--width"), ("height", "--height"), ("fps", "--fps"), ("smooth", "--smooth")):
2112
+ if fit.get(k) is not None:
2113
+ argv += option_args(flag, fit[k])
2114
+ sh("fit.py", *argv, stage="fit")
2115
+ if isinstance(_LAST_DOC.get("picture"), dict):
2116
+ stage_pictures["fit"] = _LAST_DOC["picture"]
2117
+ picture_fields.update(picture=stage_pictures["fit"], stage_pictures=stage_pictures)
2118
+ current = nxt
2119
+ stages_done.append("fit")
2120
+ if args.stop_after == "fit":
2121
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used(), **picture_fields)
2122
+ return 0
2123
+
2124
+ # ---- captions
2125
+ cap = proj.get("captions")
2126
+ if cap:
2127
+ nxt = str(work / f"captioned{mid}")
2128
+ argv = [current, "-o", nxt]
2129
+ if cap.get("text"):
2130
+ argv += ["--text", rel(cap["text"])]
2131
+ elif cap.get("srt"):
2132
+ argv += ["--srt", rel(cap["srt"])]
2133
+ elif cap.get("ass"):
2134
+ argv += ["--ass", rel(cap["ass"])]
2135
+ else:
2136
+ die("captions needs text, srt or ass")
2137
+ for k, flag in (("font", "--font"), ("size", "--size"), ("color", "--color"), ("position", "--position"), ("margin", "--margin"), ("animate", "--animate"), ("highlight_color", "--highlight-color"), ("outline", "--outline"), ("lang", "--lang"), ("offset", "--offset"), ("max_lines", "--max-lines"), ("min_duration", "--min-duration"),
2138
+ ("fit_size", "--fit-size"), ("min_size", "--min-size"), ("fit_size_scope", "--fit-size-scope")):
2139
+ if cap.get(k) is not None:
2140
+ argv += option_args(flag, cap[k])
2141
+ for k, flag in (("karaoke", "--karaoke"), ("bold", "--bold"), ("box", "--box")):
2142
+ if cap.get(k):
2143
+ argv.append(flag)
2144
+ sh("caption.py", *(argv + brand_args + platform_args), stage="captions")
2145
+ # the SRT caption.py generated from the cue file, beside its intermediate (#510); a cache hit
2146
+ # places the video only, so there is none then
2147
+ captioned_srt = {"srt": os.path.splitext(nxt)[0] + ".srt", "video": nxt, "cached": bool(_LAST_DOC.get("cached"))}
2148
+ if isinstance(_LAST_DOC.get("caption"), dict):
2149
+ caption_report = dict(_LAST_DOC["caption"])
2150
+ current = nxt
2151
+ stages_done.append("captions")
2152
+ if args.stop_after == "captions":
2153
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used(), **picture_fields)
2154
+ return 0
2155
+
2156
+ # ---- graphics
2157
+ for i, g in enumerate(proj.get("graphics") or []):
2158
+ nxt = str(work / f"graphics{i:02d}{mid}")
2159
+ if not g.get("template"):
2160
+ die(f"graphics[{i}] needs a template")
2161
+ argv = [current, "-o", nxt] + option_args("--template", g["template"])
2162
+ for k, flag in (("name", "--name"), ("title", "--title"), ("subtitle", "--subtitle"), ("start", "--start"), ("end", "--end"), ("position", "--position"), ("from", "--from"), ("scale", "--scale"), ("primary", "--primary"), ("text_color", "--text-color"), ("lang", "--lang"),
2163
+ ("text", "--text"), ("top", "--top"), ("bottom", "--bottom"), ("duration", "--duration"), ("margin", "--margin"), ("platform", "--platform")):
2164
+ if g.get(k) is not None:
2165
+ argv += option_args(flag, g[k])
2166
+ # the entry's own "platform" is the more specific statement than the template's destination
2167
+ sh("graphics.py", *(argv + brand_args + ([] if g.get("platform") else platform_args)), stage="graphics")
2168
+ current = nxt
2169
+ if "graphics" not in stages_done:
2170
+ stages_done.append("graphics")
2171
+ if args.stop_after == "graphics":
2172
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used(), **picture_fields)
2173
+ return 0
2174
+
2175
+ # ---- overlays
2176
+ for i, ov in enumerate(proj.get("overlays") or []):
2177
+ nxt = str(work / f"overlay{i:02d}{mid}")
2178
+ argv = [current, "-o", nxt]
2179
+ if ov.get("logo"):
2180
+ argv.append("--logo")
2181
+ elif ov.get("image"):
2182
+ argv += ["--image", rel(ov["image"])]
2183
+ elif ov.get("text"):
2184
+ argv += option_args("--text", ov["text"])
2185
+ elif ov.get("video"):
2186
+ # #326: sized and placed here, after fit, against the frame that ships
2187
+ argv += ["--video", rel(ov["video"])]
2188
+ else:
2189
+ die(f"overlays[{i}] needs logo, image, text or video")
2190
+ for k, flag in (("position", "--position"), ("start", "--start"), ("end", "--end"), ("fade", "--fade"), ("opacity", "--opacity"), ("scale", "--scale"), ("font_size", "--font-size"), ("font", "--font"), ("font_file", "--font-file"), ("margin", "--margin"), ("platform", "--platform"),
2191
+ ("chromakey", "--chromakey"), ("chromakey_similarity", "--chromakey-similarity"), ("chromakey_blend", "--chromakey-blend")):
2192
+ if ov.get(k) is not None:
2193
+ # font_file is a path: the same one project_input_files() guards
2194
+ argv += option_args(flag, rel(ov[k]) if k == "font_file" and ov[k] else ov[k])
2195
+ if ov.get("box"):
2196
+ argv.append("--box")
2197
+ # review 12: the overlay stage was the one stage that never heard which destination this
2198
+ # is, so a template's top-left logo landed 24 px in -- under TikTok's own status bar.
2199
+ sh("overlay.py", *(argv + brand_args + ([] if ov.get("platform") else platform_args)), stage="overlays")
2200
+ current = nxt
2201
+ if "overlays" not in stages_done:
2202
+ stages_done.append("overlays")
2203
+ if args.stop_after == "overlays":
2204
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used(), **picture_fields)
2205
+ return 0
2206
+
2207
+ # ---- audio
2208
+ au = dict(proj.get("audio") or {})
2209
+ if au:
2210
+ # "stems": one level per element of the mix, the way a mixing desk names them. Each maps
2211
+ # to the flag that already exists (dialogue = the main track's gain, music = the bed's
2212
+ # level, effects = the third file's level), so a stems block is a vocabulary, not a
2213
+ # second code path -- and an explicit flag next to it wins, since it is the more specific
2214
+ # statement of the same thing.
2215
+ stems = au.pop("stems", None) or {}
2216
+ if stems.get("effects") is not None and not au.get("effects"):
2217
+ die('audio.stems.effects sets the level of "audio": {"effects": "sfx.wav"}, which this project does not have')
2218
+ if stems.get("music") is not None and not au.get("music"):
2219
+ die('audio.stems.music sets the level of "audio": {"music": "bed.mp3"}, which this project does not have')
2220
+ for stem, key in (("dialogue", "gain"), ("music", "music_volume"), ("effects", "effects_volume")):
2221
+ if stems.get(stem) is not None:
2222
+ au.setdefault(key, stems[stem])
2223
+ nxt = str(work / f"audio{mid}")
2224
+ argv = [current, "-o", nxt]
2225
+ for k, flag in (("music", "--music"), ("replace", "--replace"), ("effects", "--effects")):
2226
+ if au.get(k):
2227
+ argv += [flag, rel(au[k])]
2228
+ for k, flag in (("music_volume", "--music-volume"), ("effects_volume", "--effects-volume"), ("fade_in", "--fade-in"), ("fade_out", "--fade-out"), ("music_fade_out", "--music-fade-out"), ("gain", "--gain"), ("duck_amount", "--duck-amount"), ("duck_threshold", "--duck-threshold"), ("duck_attack", "--duck-attack"), ("duck_release", "--duck-release"), ("stereo_widen", "--stereo-widen")):
2229
+ if au.get(k) is not None:
2230
+ argv += option_args(flag, au[k])
2231
+ # "voice": true is the medium chain; "voice": "light"|"medium"|"strong" names one
2232
+ if au.get("voice") is not None and au.get("voice") is not False:
2233
+ argv += ["--voice"] if au["voice"] is True else option_args("--voice", au["voice"])
2234
+ for k, flag in (("denoise", "--denoise"), ("duck", "--duck"), ("music_loop", "--music-loop"), ("stereo", "--stereo"), ("mono", "--mono"), ("downmix", "--downmix")):
2235
+ if au.get(k):
2236
+ argv.append(flag)
2237
+ sh("audio.py", *argv, stage="audio")
2238
+ current = nxt
2239
+ stages_done.append("audio")
2240
+ if args.stop_after == "audio":
2241
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used(), **picture_fields)
2242
+ return 0
2243
+
2244
+ # ---- loudness
2245
+ ld = proj.get("loudness")
2246
+ if ld and not _has_sound(current, proj, rel):
2247
+ # a template's loudness stage on a silent source (screen recording, timelapse, drone) used
2248
+ # to fail the render after the picture stages had run, while the dry run said it would work
2249
+ record_skip("the loudness stage is not run: the video has no audio", "loudness_no_audio", stage="loudness")
2250
+ ld = None
2251
+ if ld:
2252
+ nxt = str(work / f"loudnorm{mid}")
2253
+ argv = [current, "-o", nxt]
2254
+ if ld.get("lufs") is not None:
2255
+ argv += option_args("--lufs", ld["lufs"])
2256
+ if ld.get("tp") is not None:
2257
+ argv += option_args("--tp", ld["tp"])
2258
+ sh("loudness.py", *argv, stage="loudness")
2259
+ current = nxt
2260
+ stages_done.append("loudness")
2261
+ if args.stop_after == "loudness":
2262
+ emit(current, stages=stages_done, intermediate_preset=_intermediate_used(), **picture_fields)
2263
+ return 0
2264
+
2265
+ # ---- export
2266
+ ex = proj.get("export")
2267
+ if ex and ex.get("preset"):
2268
+ argv = [current, "--preset", ex["preset"], "-o", output]
2269
+ if ex.get("fit"):
2270
+ argv += option_args("--fit", ex["fit"])
2271
+ if ex.get("crf") is not None:
2272
+ argv += option_args("--crf", ex["crf"])
2273
+ normalize = ex.get("normalize")
2274
+ if normalize is None and resolve_platform(ex["preset"]) in PLATFORM_OF and not proj.get("loudness"):
2275
+ # eval 8: a reels project without the key rendered fully, failed the loudness check and
2276
+ # was rendered again; a platform preset with no loudness stage of its own gets the
2277
+ # one-export behaviour by default ("normalize": false opts out)
2278
+ normalize = True
2279
+ warn(f"export: --normalize on by default for the {ex['preset']} preset (set \"normalize\": false to skip)",
2280
+ "normalize_on_by_default", preset=ex["preset"])
2281
+ if normalize:
2282
+ argv += ["--normalize"] # one export that meets the platform's loudness (export.py --normalize)
2283
+ elif resolve_platform(ex["preset"]) in PLATFORM_OF: # an alias (youtube-shorts) too
2284
+ # export.py normalises a platform preset by default since 4.0.0 (#579): an opt-out, or a
2285
+ # loudness stage of the project's own, has to say so or its level is overwritten
2286
+ argv += ["--no-normalize"]
2287
+ sh("export.py", *argv, stage="export")
2288
+ preset = PRESETS.get(ex["preset"]) or PRESETS[resolve_platform(ex["preset"])]
2289
+ if preset["w"]:
2290
+ # An older cached export (or a width-only preset) can resize without a report.
2291
+ # Keep the fit-stage report, but never claim it measures that delivery.
2292
+ picture_fields.pop("picture", None)
2293
+ if isinstance(_LAST_DOC.get("picture"), dict):
2294
+ stage_pictures["export"] = _LAST_DOC["picture"]
2295
+ picture_fields.update(picture=stage_pictures["export"], stage_pictures=stage_pictures)
2296
+ stages_done.append("export")
2297
+ else:
2298
+ if stages_done != ["clips"]:
2299
+ refuse_unwritten_output(output) # a stage's file, not the WMA source itself (#517)
2300
+ # A container match alone lets an MPEG-4 picture be delivered under a .m4a name.
2301
+ # In a dry run only an original input is evidence of what the copy will contain.
2302
+ out_ext = Path(output).suffix.lower()
2303
+ is_original = c_only is not None and current == rel(c_only["src"])
2304
+ if out_ext in AUDIO_MEDIA_EXT and (is_original or not STATE.dry_run):
2305
+ video = probe(current).get("video")
2306
+ if video:
2307
+ refuse("input", "output_extension_audio_only",
2308
+ f"output {output!r}: {out_ext} holds sound only, and this render would copy "
2309
+ f"the picture ({video.get('codec')}) from {current}",
2310
+ hint="name a video file of the source's container, or extract the sound with cut.py or audio.py",
2311
+ output=output, extension=out_ext, encoders=[])
2312
+ refuse_copied_container(Path(current).suffix.lower(), output) # what the copy really is (A84)
2313
+ if not STATE.dry_run:
2314
+ place_output(current, output)
2315
+ info(("[dry-run] would copy" if STATE.dry_run else "copied") + f" final stage to {output}")
2316
+ current = output
2317
+ if not STATE.dry_run:
2318
+ mark_delivered(output) # the chapters and check stages run on it: a stop from here keeps it, and says so (#415)
2319
+ caption_srt = deliver_caption_srt(caption_srt, captioned_srt, output)
2320
+ if args.stop_after == "export":
2321
+ # A87: the chapters and check stages ran after "--stop-after export", and a "check" this
2322
+ # run never reads (validate_project() skips it) was then read with .get(): a traceback
2323
+ if not args.keep and not args.work:
2324
+ shutil.rmtree(work, ignore_errors=True)
2325
+ emit(output, stages=stages_done, check=None, cache=cache_report(args.cache),
2326
+ intermediate_preset=_intermediate_used(), caption_srt=caption_srt, **picture_fields)
2327
+ return 0
2328
+
2329
+ # ---- chapters (metadata.py on the delivered file: streams copied, markers written)
2330
+ ch = proj.get("chapters")
2331
+ if ch:
2332
+ # Planned exactly like the audio stage: the metadata.py command names the export's output,
2333
+ # which a dry run has not written either. The plan is the run, so --dry-run shows the
2334
+ # command and lists the stage (the child's own --dry-run prints rather than writes).
2335
+ if isinstance(ch, list):
2336
+ # a dry run writes nothing into the work directory (A99): its metadata.py --dry-run
2337
+ # still reads the list, from a temporary directory removed at exit
2338
+ if STATE.dry_run:
2339
+ import atexit
2340
+ tmp_dir = tempfile.mkdtemp(prefix="ffskill_render_chapters_")
2341
+ atexit.register(lambda: shutil.rmtree(tmp_dir, ignore_errors=True))
2342
+ chapter_file = os.path.join(tmp_dir, "chapters.txt")
2343
+ else:
2344
+ chapter_file = str(work / "chapters.txt")
2345
+ lines = [f"{entry['at']} {entry['title']}" for entry in ch]
2346
+ Path(chapter_file).write_text("\n".join(lines) + "\n", encoding="utf-8")
2347
+ CONTENT_KEYED.add(os.path.abspath(chapter_file)) # rewritten every run: keyed by what it says (A100)
2348
+ else:
2349
+ chapter_file = rel(ch)
2350
+ tagged = str(work / ("chapters" + Path(output).suffix))
2351
+ sh("metadata.py", output, "--chapters", chapter_file, "-o", tagged, stage="chapters")
2352
+ if not STATE.dry_run:
2353
+ place_output(tagged, output)
2354
+ stages_done.append("chapters")
2355
+
2356
+ # ---- check
2357
+ ck = proj.get("check")
2358
+ check_result = None
2359
+ exit_code = 0
2360
+ # a platform, --content's rows, or both: the same rule a plan's check step follows (a
2361
+ # {"content": true} stage without a platform used to be skipped without a word)
2362
+ wants_check = bool(ck) and (bool(ck.get("platform")) or ck.get("content") is True)
2363
+ check_label = ck.get("platform") if ck and ck.get("platform") else "content"
2364
+ if wants_check and STATE.dry_run:
2365
+ record_skip("[dry-run] the check stage is not run: a dry run writes no output to check",
2366
+ "check_dry_run", platform=ck.get("platform"), content=ck.get("content") is True)
2367
+ elif wants_check:
2368
+ check_result = run_check(output, ck.get("platform"), ck.get("content") is True)
2369
+ if check_result.get("failed"):
2370
+ info(f"check: {check_result['failed']} FAIL — " + "; ".join(f"{r['check']}={r['value']} ({r['fix']})" for r in check_result["checks"] if r["status"] == "FAIL"))
2371
+ exit_code = 1
2372
+ elif check_result.get("error") or check_result.get("status") == "failed":
2373
+ err = check_result.get("error")
2374
+ if isinstance(err, dict) and err.get("kind") in ("timeout", "interrupted"):
2375
+ # stopped, not failed: the run exits with check.py's own code (124, 130/143), as a
2376
+ # stage that stopped does, and says the delivery it had written is kept (#415)
2377
+ why = str(err.get("message") or "").replace("; nothing was written", "")
2378
+ die(f"check.py failed: {why} ({kept_clause()})",
2379
+ code=int(check_result.get("exit_code") or err.get("exit_code") or 1), kind=err["kind"],
2380
+ stage="check.py", output=output, stages=stages_done)
2381
+ info(f"check: could not run check.py — {err.get('message') if isinstance(err, dict) else err}")
2382
+ exit_code = 1
2383
+ else:
2384
+ # #485: over the table's upload limit is a WARN the check passes with; say it here too
2385
+ advised = guidance_warns(check_result)
2386
+ info(f"check: OK for {check_label}" + (" — upload-limit guidance, the uploader checks the current limit: "
2387
+ + "; ".join(advised) if advised else ""))
2388
+ stages_done.append("check")
2389
+ elif "check" in proj:
2390
+ record_skip('the check stage names neither "platform" nor "content": true, so nothing was checked',
2391
+ "check_nothing_to_check", keys=sorted(ck or {}))
2392
+
2393
+ if not args.keep and not args.work:
2394
+ # Also clean up on --dry-run: a dry run still creates this directory (and some steps,
2395
+ # e.g. caption.py's .ass sidecar, write into it even under --dry-run), and now that the
2396
+ # default name carries this process's PID, nothing else will ever reuse -- and so
2397
+ # implicitly clean up -- a leftover dry-run directory the way a same-named real run used
2398
+ # to before the PID suffix was added.
2399
+ shutil.rmtree(work, ignore_errors=True)
2400
+ if exit_code:
2401
+ # The deliverable is written and verified, but it does not meet the requested platform
2402
+ # spec (or the check itself could not run): a failed delivery, reported as one.
2403
+ failed_rows = [r["check"] for r in (check_result or {}).get("checks", []) if r.get("status") == "FAIL"]
2404
+ unrun = check_not_run(check_result)
2405
+ die(f"rendered {output} but the {check_label} check "
2406
+ + (f"could not run, so nothing was checked: {unrun}" if unrun else "failed" + (f": {', '.join(failed_rows)}" if failed_rows else "")),
2407
+ kind="verification", output=output, dry_run=STATE.dry_run, stages=stages_done, check=check_result,
2408
+ probe=probe(output, role="output"))
2409
+ info(f"rendered {output} via {' → '.join(stages_done)}")
2410
+ # One entry per snapped clip, `clip` naming which. A single-clip project keeps the shape a
2411
+ # caller reads today by also carrying the first entry's keys at the top level.
2412
+ snap_report: Optional[Dict[str, Any]] = None
2413
+ if snap_reports:
2414
+ snap_report = dict(snap_reports[0])
2415
+ snap_report["clips"] = snap_reports
2416
+ emit(output, stages=stages_done, check=check_result, snap=snap_report, cache=cache_report(args.cache),
2417
+ caption=caption_report, intermediate_preset=_intermediate_used(), caption_srt=caption_srt,
2418
+ verification=[{"step": "check", "ok": True, "platform": ck.get("platform")}] if check_result else [],
2419
+ **picture_fields)
2420
+ return 0
2421
+
2422
+
2423
+ if __name__ == "__main__":
2424
+ sys.exit(main())