@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,729 @@
1
+ #!/usr/bin/env python3
2
+ """Fit a video to a target duration and/or aspect ratio.
3
+
4
+ Duration: --duration N with --method speed (retime video+audio, pitch-preserving
5
+ via atempo chaining) or --method trim (keep the first N seconds, or a centred
6
+ window with --from-center). A duration alone allows a small retime. Beyond
7
+ 1.15x in either direction, choose --method speed, --method trim, or an explicit
8
+ slow-motion filter. A large retime reports large_speed_change with the factor.
9
+ Aspect: --aspect 16:9|9:16|1:1|4:5|W:H with
10
+ --fit pad (letterbox/pillarbox with --pad-color, default black, or --pad-fill blur\nfor a blurred copy of the frame behind the picture), --fit crop, or --fit blur\n(the whole picture centred on a blurred, darkened copy of itself -- nothing\ncropped, no black bars).
11
+ --width and/or --height set the output size: give one and the other follows
12
+ the aspect (source aspect if --aspect is not also given); give both for an
13
+ exact frame. --rotate 90|180|270 (clockwise) and --flip h|v apply a new
14
+ rotation/mirror to the picture -- distinct from the rotation metadata a
15
+ source already carries (read automatically to compute the displayed size,
16
+ never altered by these flags unless asked). Both can be combined; rotate is
17
+ applied before flip.
18
+
19
+ Crop keeps the centre of the frame by default, which is a guess: going from
20
+ 16:9 to 9:16 throws away most of the width, and whatever isn't in the middle
21
+ third (a person at the edge, a product held to one side) is cut off. Say what
22
+ to keep with --crop-x / --crop-y (0=left/top, 0.5=centre, 1=right/bottom, or
23
+ a decimal in between) rather than accepting the default silently when the
24
+ subject isn't centred; --fit pad never loses anything if you don't know yet.
25
+ After a real --fit crop that cuts something away, the result's crop_check
26
+ measures where the source's luma motion (in a still shot, its edge detail)
27
+ sits against the kept window: a proxy sampled at 9 points, not subject
28
+ detection. A crop_content_off_centre warning names --crop-x/--crop-y with a
29
+ suggested value, or --fit pad / --fit blur, when most of it is cut away.
30
+ Advisory only: the output and the exit status are unchanged.
31
+
32
+ Examples:
33
+ python3 fit.py input.mp4 --duration 60 --method trim # keep the first 60s
34
+ python3 fit.py input.mp4 --duration 30 --method speed # retime the whole clip to exactly 30s
35
+ python3 fit.py input.mp4 --aspect 9:16 --fit pad --width 1080
36
+ python3 fit.py input.mp4 --aspect 9:16 --fit pad --pad-fill blur # the phone-editor look: blurred frame behind the bars
37
+ python3 fit.py input.mp4 --aspect 9:16 --fit blur # same look in one word (blurred + darkened fill)
38
+ python3 fit.py input.mp4 --aspect 1:1 --fit crop --duration 15 --method trim
39
+ python3 fit.py input.mp4 --aspect 9:16 --fit crop --crop-x 1 # keep the right edge (e.g. product held stage-right)
40
+ python3 fit.py input.mp4 --height 1080 # width follows the source aspect
41
+ python3 fit.py input.mp4 --width 1920 --height 1080 # exact frame, no aspect needed
42
+ python3 fit.py input.mp4 --rotate 90 # rotate 90 degrees clockwise
43
+ python3 fit.py input.mp4 --flip h # mirror horizontally
44
+ """
45
+ import argparse
46
+ import os
47
+ import sys
48
+ from fractions import Fraction
49
+ from typing import Any, List, Optional
50
+
51
+ from _common.runner import require_tool, run_analysis, with_mapped_chapters
52
+ from _common.decision import SEEK_MARGIN, enlarge_args, warn_mostly_cropped, atempo_chain_with_lead, line_matrix_filter, delivered_rate, frame_durations, frame_rate, grid_at_or_after, length_output_t, ntsc_rate, stream_starts
53
+ from _common.timeline import exact_rate, output_timecode_args
54
+ from _common import video_args, STATE, add_common, apply_common, emit, aac_args, aspect_ratio, cfr_args, cfr_filter, default_output, die, ffmpeg_base, info, probe, run, run_keeping_subtitles, validate_color, pad_filters, add_pad_fill_args, X264_PRESETS, time_arg, fmt_secs, frame_size, display_size, square_pixels, square_pixels_note, note
55
+ from _common.emit import input_length, own_length, refuse, refuse_still, warn
56
+ from _common.probe import fingerprint
57
+ BLUR_DARKEN = 0.15 # how much --fit blur dims the blurred background copy (eq brightness)
58
+ SPEED_WARN_FACTOR = 1.15 # a --method speed retime beyond this, in either direction, is
59
+ # reported in the result's diagnostics (large_speed_change): the whole picture and sound
60
+ # sped up or slowed down by more than 15% is easy to ask for by accident -- speed is the
61
+ # default method -- when what was wanted was a cut, so it is never silent
62
+
63
+ # crop_check (--fit crop): a luma motion/detail proxy, not subject detection. Provisional values
64
+ CROP_SAMPLES = 9 # sample points spread evenly over the kept source range, at (i + 0.5) / 9
65
+ CROP_SAMPLE_GAP = 0.2 # seconds between the two frames of a sample point (their difference is motion)
66
+ CROP_SAMPLE_LONG = 160 # sampled frames are scaled to this many pixels on their long axis
67
+ CROP_DETAIL_MIN = 16 # an 8-bit luma gradient counts as detail at or above this
68
+ CROP_MOTION_MIN = 8 # an 8-bit frame difference counts as motion at or above this
69
+ CROP_MOTION_FLOOR = 0.05 # mean counted difference per pixel per sample: below it nothing moved
70
+ CROP_DETAIL_FLOOR = 0.05 # mean counted gradient per pixel per sample: below it the frames are flat
71
+ CROP_MOTION_EXCESS_WARN = 0.15 # with motion: review when the motion share cut away exceeds the area share by this (#630)
72
+ CROP_DETAIL_EXCESS_WARN = 0.15 # no motion: review when the detail share cut away exceeds the area share by this
73
+
74
+
75
+ def parse_aspect(value: str) -> Fraction:
76
+ # the one aspect grammar, shared with render.py's frame and --export-timeline's sequence
77
+ ratio = aspect_ratio(value)
78
+ if ratio is None:
79
+ die(f"bad aspect '{value}', use W:H like 16:9")
80
+ return ratio
81
+
82
+
83
+ def atempo_chain(factor: float, sample_rate: Any = 0) -> str:
84
+ """atempo accepts 0.5..100 per instance; chain for extreme factors. The chain is led by the
85
+ samples atempo leaves out (atempo_chain_with_lead, at the track's `sample_rate`), so the
86
+ retimed sound keeps its timing against the retimed picture (#523: about 21 ms early in input
87
+ time without them)."""
88
+ parts: List[str] = []
89
+ remaining = factor
90
+ while remaining < 0.5:
91
+ parts.append("0.5")
92
+ remaining /= 0.5
93
+ while remaining > 100.0:
94
+ parts.append("100.0")
95
+ remaining /= 100.0
96
+ parts.append(f"{remaining:.6f}")
97
+ return atempo_chain_with_lead(parts, sample_rate)
98
+
99
+
100
+ def picture_output_t(target: float, meta: dict) -> str:
101
+ """The output `-t` of a trim from the start that has no sound to end: `{target:.3f}` as it
102
+ always was, unless that text keeps another number of frames than `target` does. The frames
103
+ kept are those that start before `target`. 37 frames of a 30000/1001 picture are 1.2345667 s:
104
+ `-t 1.235` is past the 38th frame's start and wrote it, and `-t 1.001` for 1.0014 s stopped
105
+ before the 31st. The limit is then written half a frame before the first frame left out.
106
+ Without a frame grid (no rate: a dry run's pending input; a variable rate, which the output's
107
+ -r regrids) the millisecond text stays."""
108
+ text = f"{target:.3f}"
109
+ rate = frame_rate(meta)
110
+ if not rate or (meta.get("video") or {}).get("variable_frame_rate_suspected"):
111
+ return text
112
+ out = grid_at_or_after(target, stream_starts(meta)[0], rate) # the first frame left out
113
+ if out - 1 / rate + 1e-6 < float(text) <= out + 1e-9:
114
+ return text
115
+ return f"{out - 0.5 / rate:.6f}"
116
+
117
+
118
+ def _picture_rows(path_meta: dict, chain: str, colour: str, sw: int, sh: int, size: int,
119
+ out_pix: "Optional[str]") -> "Optional[bytes]":
120
+ """One frame of `colour` at the source's displayed size and pixel format through `chain`, as
121
+ 8-bit grey bytes, or None when ffmpeg did not give exactly one frame of `size` bytes. The chain
122
+ ends in the written file's pixel format, as the encoder line makes it end: pad rounds its
123
+ offset and the picture's size to that format's chroma grid (a 203-row picture is padded as 202
124
+ rows of a 4:2:0 frame), and a chain ending in grey would pad in grey."""
125
+ pix = (path_meta.get("video") or {}).get("pix_fmt")
126
+ src = f"color=c={colour}:s={sw}x{sh}:r=1:d=1" + (f",format={pix}" if pix else "")
127
+ # one filter thread: with slice threads FFmpeg 8.0.1 once gave a white frame's band of rows
128
+ # (128-217 of 640, a fifth of the frame down to the picture) a value the black frame's did not
129
+ # have, and the picture was reported 90 rows taller than the file held it (#543 CI)
130
+ cmd = [require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin", "-filter_threads", "1",
131
+ "-f", "lavfi", "-i", src,
132
+ "-vf", chain + (f",format={out_pix}" if out_pix else "") + ",format=gray", "-frames:v", "1", "-f", "rawvideo", "-"]
133
+ proc = run_analysis(cmd, check=False, text=False)
134
+ return proc.stdout if proc.returncode == 0 and len(proc.stdout or b"") == size else None
135
+
136
+
137
+ def measure_picture(geometry, meta: dict, sw: int, sh: int, out_video: dict, sized: bool,
138
+ *, matrix_filter: "Optional[str]" = None) -> dict:
139
+ """Where the picture sits in the written frame (#519): measured, not judged. ffmpeg runs the
140
+ frame's own filters (the scale and pad, the blur graph with its background drawn black, or the
141
+ scale and crop) on one white and one black frame of the source's displayed size and pixel
142
+ format, after the colour conversion the encoder line adds; the picture is where the two
143
+ differ, and the frame is the written file's. No frame of the source is decoded. Whether the
144
+ subject is inside that rectangle is still a look (subject_framing stays unverified)."""
145
+ filters, crop_scale, cropped = geometry
146
+ W, H = int(out_video.get("width") or 0), int(out_video.get("height") or 0)
147
+ why = None
148
+ if not (sw and sh and W and H):
149
+ why = "the source or the written frame has no size"
150
+ else:
151
+ chain = ",".join(([matrix_filter] if matrix_filter else []) + list(filters))
152
+ out_pix = out_video.get("pix_fmt")
153
+ white = _picture_rows(meta, chain, "white", sw, sh, W * H, out_pix)
154
+ black = _picture_rows(meta, chain, "black", sw, sh, W * H, out_pix) if white is not None else None
155
+ if white is None or black is None:
156
+ why = f"ffmpeg did not give one {W}x{H} frame of the frame's filters (the written frame's size)"
157
+ if why:
158
+ note(f"picture: not measured: {why}")
159
+ return {"measured": False, "reason": why}
160
+ rows = [r for r in range(H) if white[r * W:(r + 1) * W] != black[r * W:(r + 1) * W]]
161
+ if not rows:
162
+ note("picture: not measured: no pixel of the frame changed with the picture")
163
+ return {"measured": False, "reason": "no pixel of the frame changed with the picture"}
164
+ left, right = W, -1
165
+ for r in rows:
166
+ # the row's difference as one integer: its leading zero bytes are the columns before the
167
+ # first differing pixel, its trailing ones those after the last (no per-pixel loop)
168
+ d = int.from_bytes(white[r * W:(r + 1) * W], "big") ^ int.from_bytes(black[r * W:(r + 1) * W], "big")
169
+ x0 = W - (d.bit_length() + 7) // 8
170
+ x1 = W - 1 - ((d & -d).bit_length() - 1) // 8
171
+ left, right = min(left, x0), max(right, x1)
172
+ x, y, w, h = left, rows[0], right - left + 1, rows[-1] - rows[0] + 1
173
+ scale = crop_scale if crop_scale is not None else w / sw
174
+ pic = {"measured": True, "x": x, "y": y, "width": w, "height": h, "frame_width": W, "frame_height": H,
175
+ "frame_share": round(w * h / (W * H), 4), "scale": round(scale, 4),
176
+ "cropped": cropped or {"left": 0, "right": 0, "top": 0, "bottom": 0}}
177
+ if scale < 1 and not sized:
178
+ note(f"picture: scaled to {scale:.1%} of the source's width ({w}x{h} in a {W}x{H} frame): with no --width or "
179
+ "--height the frame keeps the source's height or width (give --width/--height for a larger frame)")
180
+ return pic
181
+
182
+
183
+ def sample_crop_frames(path: str, orient: List[str], sw: int, sh: int, start: float,
184
+ length: float) -> "Optional[tuple]":
185
+ """The crop check's decode step: CROP_SAMPLES points evenly over the kept source range
186
+ [start, start + length] at (i + 0.5) / CROP_SAMPLES, two 8-bit grey frames CROP_SAMPLE_GAP s
187
+ apart at each, in the displayed frame the crop is cut from (autorotated, then the run's own
188
+ --rotate/--flip filters `orient`) scaled to CROP_SAMPLE_LONG px on the long axis. Returns
189
+ ([(seek_seconds, (first, second)), ...], width, height), or None when no point gave two whole frames. A
190
+ point that fails (past the end, a decode error) is left out; the others still count."""
191
+ if not (sw and sh) or length <= CROP_SAMPLE_GAP:
192
+ return None
193
+ if sw >= sh:
194
+ w, h = CROP_SAMPLE_LONG, max(2, round(CROP_SAMPLE_LONG * sh / sw / 2) * 2)
195
+ else:
196
+ w, h = max(2, round(CROP_SAMPLE_LONG * sw / sh / 2) * 2), CROP_SAMPLE_LONG
197
+ size = w * h
198
+ filters = [f"fps={1 / CROP_SAMPLE_GAP:g}"] + list(orient) + [f"scale={w}:{h}:flags=area", "format=gray"]
199
+ last = start + max(0.0, length - CROP_SAMPLE_GAP - 0.1) # room for the second frame
200
+ frames = []
201
+ previous_seek = None
202
+ for i in range(CROP_SAMPLES):
203
+ t = min(start + length * (i + 0.5) / CROP_SAMPLES, last)
204
+ seek = f"{t:.6f}"
205
+ if seek == previous_seek:
206
+ continue
207
+ previous_seek = seek
208
+ remaining = start + length - float(seek)
209
+ chain = ",".join([f"trim=end={remaining:.6f}"] + filters)
210
+ cmd = [require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin",
211
+ "-ss", seek, "-i", path, "-map", "0:V:0", "-an", "-sn", "-dn",
212
+ "-vf", chain, "-frames:v", "2", "-f", "rawvideo", "-"]
213
+ proc = run_analysis(cmd, check=False, text=False, timeout_is_fatal=False)
214
+ out = proc.stdout or b""
215
+ if proc.returncode == 0 and len(out) == 2 * size:
216
+ frames.append((float(seek), (out[:size], out[size:])))
217
+ return (frames, w, h) if frames else None
218
+
219
+
220
+ def crop_loss(frames, width: int, height: int, window, axis: str) -> dict:
221
+ """Where the luma motion and detail sit against a crop's kept window: a measurement, not a
222
+ judgement, and a proxy, not subject detection. Pure: `frames` is [(first, second), ...] of
223
+ `width` x `height` 8-bit grey bytes; `window` is (start, end) of the kept part as fractions
224
+ 0..1 of the frame along `axis` ("x": columns, "y": rows).
225
+
226
+ Per column (per row for y): detail D = sum of |luma gradient| (right and down neighbours) of
227
+ the first frame, counting only gradients >= CROP_DETAIL_MIN; motion M = sum of |first -
228
+ second|, counting only differences >= CROP_MOTION_MIN. motion_outside / detail_outside: the
229
+ energy share in the discarded part (a column the window edge cuts counts pro rata).
230
+ centroid: of M when its mean is at or above CROP_MOTION_FLOOR, else of D. suggested_anchor:
231
+ the --crop-x/--crop-y value (0..1) that centres the kept window on the centroid, clamped.
232
+ verdict: review when motion is present and motion_outside - discarded_fraction >=
233
+ CROP_MOTION_EXCESS_WARN (motion spread evenly over the frame is not off centre, #630), or
234
+ with no motion when detail_outside - discarded_fraction >= CROP_DETAIL_EXCESS_WARN; ok
235
+ otherwise; unmeasured when no whole pair was given or the frames are flat (no division by
236
+ zero, centroid and suggested_anchor null)."""
237
+ n = max(1, width if axis == "x" else height)
238
+ size = width * height
239
+ detail = [0] * n
240
+ motion = [0] * n
241
+ used = 0
242
+ for pair in frames or []:
243
+ a = pair[0] if len(pair) > 0 else b""
244
+ b = pair[1] if len(pair) > 1 else b""
245
+ if size <= 0 or len(a) != size or len(b) != size:
246
+ continue
247
+ used += 1
248
+ for r in range(height):
249
+ o = r * width
250
+ row, other = a[o:o + width], b[o:o + width]
251
+ below = a[o + width:o + 2 * width] if r + 1 < height else None
252
+ for c in range(width):
253
+ v = row[c]
254
+ k = c if axis == "x" else r
255
+ s = 0
256
+ if c + 1 < width:
257
+ g = abs(row[c + 1] - v)
258
+ if g >= CROP_DETAIL_MIN:
259
+ s += g
260
+ if below is not None:
261
+ g = abs(below[c] - v)
262
+ if g >= CROP_DETAIL_MIN:
263
+ s += g
264
+ if s:
265
+ detail[k] += s
266
+ m = abs(other[c] - v)
267
+ if m >= CROP_MOTION_MIN:
268
+ motion[k] += m
269
+ w0 = min(max(float(min(window)), 0.0), 1.0)
270
+ w1 = min(max(float(max(window)), 0.0), 1.0)
271
+ keep = w1 - w0
272
+ discarded = 1.0 - keep
273
+
274
+ def outside(profile):
275
+ total = sum(profile)
276
+ if total <= 0:
277
+ return None
278
+ lost = 0.0
279
+ for k, e in enumerate(profile):
280
+ if e:
281
+ inside = max(0.0, min((k + 1) / n, w1) - max(k / n, w0)) * n
282
+ lost += e * (1.0 - inside)
283
+ return lost / total
284
+
285
+ pixels = used * size
286
+ has_motion = bool(pixels) and sum(motion) / pixels >= CROP_MOTION_FLOOR
287
+ has_detail = bool(pixels) and sum(detail) / pixels >= CROP_DETAIL_FLOOR
288
+ m_out, d_out = outside(motion), outside(detail)
289
+ check = {"axis": axis, "discarded_fraction": round(discarded, 4),
290
+ "motion_outside": None if m_out is None else round(m_out, 4),
291
+ "detail_outside": None if d_out is None else round(d_out, 4),
292
+ "centroid": None, "suggested_anchor": None, "samples": used,
293
+ "basis": "luma_motion_proxy", "signal": None, "verdict": "unmeasured"}
294
+ if not (has_motion or has_detail):
295
+ return check
296
+ profile = motion if has_motion else detail
297
+ check["signal"] = "motion" if has_motion else "detail"
298
+ centroid = sum((k + 0.5) / n * e for k, e in enumerate(profile)) / sum(profile)
299
+ check["centroid"] = round(centroid, 4)
300
+ if discarded > 1e-9:
301
+ check["suggested_anchor"] = round(min(1.0, max(0.0, (centroid - keep / 2) / discarded)), 2)
302
+ if has_motion:
303
+ review = (m_out or 0.0) - discarded >= CROP_MOTION_EXCESS_WARN
304
+ else:
305
+ review = (d_out or 0.0) - discarded >= CROP_DETAIL_EXCESS_WARN
306
+ check["verdict"] = "review" if review else "ok"
307
+ return check
308
+
309
+
310
+ def check_crop(path: str, orient: List[str], sw: int, sh: int, window, start: float, length: float,
311
+ *, speed: float = 1.0, output_video: Optional[dict] = None) -> dict:
312
+ """crop_check for a --fit crop that cut something away: samples the kept source range,
313
+ measures it with crop_loss and records crop_content_off_centre when the verdict is review.
314
+ Advisory: nothing here changes the output or the exit status. A measurement that fails is
315
+ verdict unmeasured with a note, never another diagnostic code."""
316
+ axis, w0, w1 = window
317
+ output_video = output_video or {}
318
+ fps = output_video.get("fps")
319
+ video_length = own_length(output_video)
320
+ # A duration includes the last frame's hold. Accurate seeking past that frame's
321
+ # timestamp would find nothing, even when an audio tail keeps the container open.
322
+ last_seek = (video_length - 1 / ntsc_rate(fps)
323
+ if fps and video_length and not output_video.get("variable_frame_rate_suspected") else None)
324
+ points = []
325
+ measurement_error = None
326
+ try:
327
+ got = sample_crop_frames(path, orient, sw, sh, start, length)
328
+ samples, fw, fh = got if got else ([], 1, 1)
329
+ check = crop_loss([pair for _, pair in samples], fw, fh, (w0, w1), axis)
330
+ for source_time, pair in samples:
331
+ sample = crop_loss([pair], fw, fh, (w0, w1), axis)
332
+ if sample["verdict"] != "review":
333
+ continue
334
+ estimate = round(max(0.0, (source_time - start) / speed), 6)
335
+ point = {key: sample[key] for key in ("signal", "motion_outside", "detail_outside",
336
+ "centroid", "suggested_anchor")}
337
+ point["source_time"] = source_time
338
+ point["output_time_estimate"] = estimate if last_seek is not None and estimate <= last_seek else None
339
+ points.append(point)
340
+ except Exception as exc: # a measurement, never the run's failure
341
+ measurement_error = str(exc)
342
+ check = crop_loss([], 1, 1, (w0, w1), axis)
343
+ points = []
344
+ check["kept"] = {"start": round(w0, 6), "end": round(w1, 6)}
345
+ check["review_points"] = points
346
+ aggregate_review = check["verdict"] == "review"
347
+ if points:
348
+ check["verdict"] = "review"
349
+ if check["verdict"] == "unmeasured":
350
+ reason = measurement_error or ("no sample gave two frames" if not check["samples"]
351
+ else "the sampled frames have no luma motion or detail")
352
+ note(f"crop check: not measured: {reason}")
353
+ return check
354
+ if check["verdict"] == "review":
355
+ if aggregate_review:
356
+ signal = check["signal"]
357
+ share = check[f"{signal}_outside"]
358
+ advice = f"{share:.0%} of the sampled luma {signal} lies outside the kept window."
359
+ in_use = round(w0 / check["discarded_fraction"], 2) if check["discarded_fraction"] else None
360
+ # naming the anchor this run already used is no remedy (#630)
361
+ if check["suggested_anchor"] is not None and check["suggested_anchor"] != in_use:
362
+ advice += f" --crop-{axis} {check['suggested_anchor']:g} centres the window on the aggregate signal."
363
+ else:
364
+ advice = "Some samples have substantial luma motion or detail outside the kept window."
365
+ if points:
366
+ advice += f" Inspect {len(points)} flagged point(s) in crop_check.review_points."
367
+ warn(f"--fit crop ({axis} axis): {advice} --fit pad or --fit blur keeps the whole frame.",
368
+ "crop_content_off_centre", **{key: value for key, value in check.items() if key != "verdict"})
369
+ return check
370
+
371
+
372
+ def main() -> int:
373
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
374
+ ap.add_argument("input")
375
+ ap.add_argument("-o", "--output", help="output file (default: <name>_fit.<ext>)")
376
+ ap.add_argument("--audio-stream", type=int, default=0,
377
+ help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "
378
+ "audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "
379
+ "the first track, same as leaving it unset always did")
380
+ d = ap.add_argument_group("duration")
381
+ d.add_argument("--duration", help="target duration (seconds or mm:ss)")
382
+ d.add_argument("--method", choices=["speed", "trim"],
383
+ help="how to reach the duration (small retimes default to speed; larger changes need an explicit choice)")
384
+ d.add_argument("--from-center", action="store_true", help="with --method trim, keep the middle instead of the start")
385
+ d.add_argument("--max-speed", type=float, default=4.0, help="refuse speed factors above this (default 4x)")
386
+ d.add_argument("--smooth", choices=["none", "blend", "interpolate"], default="none",
387
+ help="slow-motion quality: blend (frame blending) or interpolate (motion-compensated, slow but fluid). default none = duplicate frames")
388
+ a = ap.add_argument_group("aspect")
389
+ a.add_argument("--aspect", help="target aspect ratio, e.g. 16:9, 9:16, 1:1, 4:5")
390
+ a.add_argument("--fit", choices=["pad", "crop", "blur"], default="pad",
391
+ help="the fit mode, how to reach the aspect: pad (letterbox), crop, or blur -- the whole picture centred on a "
392
+ "blurred, darkened copy of itself filling the rest (the phone-editor vertical, 1.14). "
393
+ "The darkening is applied to SDR sources only: on an HDR source the background is blurred "
394
+ "but left at its own levels, since an eq on PQ/HLG code values is not a -15%% perceptual dim")
395
+ a.add_argument("--width", type=int, help="output width in px, 1..16384 (default: keep source width or the width implied by the aspect); with --height also given, both are used directly")
396
+ a.add_argument("--height", type=int, help="output height in px, 1..16384 (default: keep source height or the height implied by the aspect); with --width also given, both are used directly")
397
+ a.add_argument("--pad-color", default="black", help="pad colour, e.g. black, white, 0x101010 (default black)")
398
+ add_pad_fill_args(a)
399
+ a.add_argument("--crop-x", type=float, default=0.5, help="with --fit crop, horizontal anchor 0=left, 0.5=centre (default), 1=right")
400
+ a.add_argument("--crop-y", type=float, default=0.5, help="with --fit crop, vertical anchor 0=top, 0.5=centre (default), 1=bottom")
401
+ a.add_argument("--fade-in", type=float, default=0.0, metavar="S", help="fade the picture and the sound in from black over this many seconds at the start")
402
+ a.add_argument("--fade-out", type=float, default=0.0, metavar="S", help="fade the picture and the sound out to black over this many seconds at the end")
403
+ r = ap.add_argument_group("rotate / flip")
404
+ r.add_argument("--rotate", type=int, choices=[90, 180, 270], help="rotate the picture clockwise by this angle in degrees")
405
+ r.add_argument("--flip", choices=["h", "v"], help="mirror the picture horizontally (h) or vertically (v)")
406
+ e = ap.add_argument_group("encoding")
407
+ e.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
408
+ e.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
409
+ e.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
410
+ add_common(ap)
411
+ args = ap.parse_args()
412
+ apply_common(args)
413
+ method_given = args.method is not None
414
+ args.method = args.method or "speed"
415
+
416
+ if args.fps is not None and args.fps <= 0:
417
+ die(f"--fps must be positive, got {args.fps:g}")
418
+ if not args.duration and not args.aspect and not args.width and not args.height and not args.fps and not args.rotate and not args.flip and not (args.fade_in or args.fade_out):
419
+ die("nothing to do: give --duration, --aspect, --width/--height, --rotate/--flip and/or --fps")
420
+ if not 0.0 <= args.crop_x <= 1.0:
421
+ die(f"--crop-x must be 0..1, got {args.crop_x}")
422
+ if not 0.0 <= args.crop_y <= 1.0:
423
+ die(f"--crop-y must be 0..1, got {args.crop_y}")
424
+ validate_color(args.pad_color, "--pad-color")
425
+ if args.pad_blur <= 0:
426
+ die(f"--pad-blur must be > 0, got {args.pad_blur}")
427
+
428
+ if STATE.plan and args.duration and os.path.isfile(args.input):
429
+ try:
430
+ source = fingerprint(args.input)
431
+ except OSError as exc:
432
+ die(f"cannot fingerprint the source for the duration plan: {exc}", kind="input")
433
+ STATE.measured_plan_inputs[source["path"]] = source
434
+ meta = probe(args.input, advise_deinterlace=True)
435
+ if not meta.get("video"):
436
+ die("input has no video stream")
437
+ audio_streams = meta.get("audio_streams") or []
438
+ if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):
439
+ die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")
440
+ if args.audio_stream and not audio_streams:
441
+ die("--audio-stream needs an input with audio streams")
442
+ src_dur = meta["duration"] or 0.0
443
+ # the displayed frame: rotation applied and non-square pixels squared (#411)
444
+ sw, sh = display_size(meta["video"])
445
+ if args.rotate in (90, 270):
446
+ sw, sh = sh, sw
447
+ has_audio = bool(meta.get("audio"))
448
+
449
+ vf: List[str] = []
450
+ af: List[str] = []
451
+ pre_input: List[str] = []
452
+ post: List[str] = []
453
+ factor = 1.0
454
+ retimed = False
455
+ extra = {}
456
+ tc_first = None # seconds from the source's first frame to the output's, when a trim moves it
457
+ regridded = False # a speed change already put the picture on the delivered grid
458
+ out_seek = 0.0 # the output-side -ss a --method trim drops its seek margin with
459
+ kept = None # (start, length) of the source a --method trim keeps; None: the whole source
460
+
461
+ # ---- rotate / flip
462
+ if args.rotate == 90:
463
+ vf.append("transpose=1")
464
+ elif args.rotate == 270:
465
+ vf.append("transpose=2")
466
+ elif args.rotate == 180:
467
+ vf.append("transpose=2,transpose=2")
468
+ if args.flip == "h":
469
+ vf.append("hflip")
470
+ elif args.flip == "v":
471
+ vf.append("vflip")
472
+ orient = list(vf) # the run's own rotate/flip filters: the crop check samples the frame they make
473
+
474
+ # ---- duration
475
+ if args.duration:
476
+ target = time_arg(args.duration, "--duration", meta["video"].get("fps") if meta.get("video") else None)
477
+ if target <= 0:
478
+ die("target duration must be > 0")
479
+ # speed refused it as "0.00x", and trim wrote one frame as verified (#531)
480
+ refuse_still(meta, args.input, "--duration retimes or trims the input's length, and a still has none")
481
+ # A dry run can plan the command even when the source's usable length is unknown.
482
+ src_dur = (meta.get("duration") or 0.0) if STATE.dry_run else input_length(meta)
483
+ length_unknown = STATE.dry_run and src_dur <= 0
484
+ # The output's -t is all that ends the kept track where the source's sound runs on past
485
+ # the target (a trim; a speed change too small to retime), so it is written to the sample
486
+ # of that track's rate, not to the millisecond: `-t 1.234` wrote 59244 samples (48 kHz)
487
+ # as 59232 and `-t 1.235` wrote 59261 as 59280 (length_output_t). No sound, or a dry
488
+ # run's pending input, has no rate and keeps the millisecond.
489
+ rate = (audio_streams[args.audio_stream].get("sample_rate") if has_audio and audio_streams else None)
490
+ if args.method == "speed":
491
+ factor = 1.0 if length_unknown else src_dur / target # >1 = speed up
492
+ if factor > args.max_speed or factor < 1 / args.max_speed:
493
+ die(f"required speed factor {factor:.2f}x exceeds --max-speed {args.max_speed}x; use --method trim or raise the limit")
494
+ if factor > SPEED_WARN_FACTOR or factor < 1 / SPEED_WARN_FACTOR:
495
+ change = dict(factor=round(factor, 3), threshold=SPEED_WARN_FACTOR,
496
+ source_duration=round(src_dur, 3), target_duration=round(target, 3))
497
+ if not method_given and not (factor < 1 and args.smooth != "none"):
498
+ refuse("input", "fit_method_required",
499
+ f"--duration {target:g} would retime the entire clip at {factor:.2f}x. Choose how to reach the target.",
500
+ hint="pass --method speed to retime, --method trim to keep the start, "
501
+ "or select what to keep with cut.py --segments or silence.py",
502
+ **change)
503
+ warn(f"speed {factor:.2f}x: retiming the entire picture and sound to {target:.2f}s",
504
+ "large_speed_change", **change)
505
+ retimed = abs(factor - 1.0) > 1e-4
506
+ if retimed:
507
+ vf.append(f"setpts={1/factor:.8f}*PTS")
508
+ src_fps = meta["video"].get("fps") or 30.0
509
+ if factor < 1.0 and args.smooth == "interpolate":
510
+ # the new frames are made at the rate delivered: made at the source's 30 and
511
+ # then put on --fps 60 by the fps filter below, every other frame of the slow
512
+ # motion was a repeat (#527). Without --fps it is the source's rate, as before
513
+ vf.append(f"minterpolate=fps={args.fps or src_fps:g}:mi_mode=mci:mc_mode=aobmc:me_mode=bidir:vsbmc=1")
514
+ elif factor < 1.0 and args.smooth == "blend":
515
+ vf.append(f"fps={src_fps:g}")
516
+ vf.append("tblend=all_mode=average")
517
+ elif not args.fps:
518
+ # the retimed frames are put back on the output's grid by the fps filter, the
519
+ # nearest frame for each slot: left to the encoder line's rate, a 1.11x speed-up
520
+ # showed every picture up to two frames late against its sound (#512's class).
521
+ # A rate the caller names is that grid (the conform below): conformed here to
522
+ # the source's 30 first, a 2x speed-up to --fps 60 dropped every other picture
523
+ # and the second fps filter repeated the rest
524
+ vf.append(frame_durations(meta, delivered_rate(meta) or frame_rate(meta) or src_fps))
525
+ regridded = True
526
+ if has_audio:
527
+ af.append(atempo_chain(factor, rate))
528
+ # atempo's sound is not the input's length over the factor (it comes out some
529
+ # milliseconds short or long), and the millisecond -t stays on a retimed track: padding
530
+ # it to the target's samples (apad after atempo in -af) never ended on FFmpeg 8.0.1
531
+ # (seen in CI: killed at the time limit), so the track keeps the length atempo gives.
532
+ # Where the sound is not retimed (a factor within 1e-4 of 1) the source's runs on and
533
+ # the -t ends it to the sample. A picture without sound that is not retimed either is
534
+ # a trim, counted in frames; one that is retimed, or regridded by --fps, keeps the
535
+ # millisecond
536
+ post += ["-t", f"{target:.3f}" if af else length_output_t(target, rate, runs_on=True) if rate
537
+ else f"{target:.3f}" if retimed or args.fps or has_audio else picture_output_t(target, meta)]
538
+ STATE.duration_hint = target
539
+ else:
540
+ if target < src_dur:
541
+ start = (src_dur - target) / 2 if args.from_center else 0.0
542
+ kept = (start, target)
543
+ # seek SEEK_MARGIN early and drop the margin on the output side, as cut.py does:
544
+ # an input seek straight to `start` can land on a keyframe whose picture comes
545
+ # after it (a B-frame HEVC source) and lose the frames before it, so the first
546
+ # picture would not be the one the start timecode below names
547
+ m = min(SEEK_MARGIN, round(start, 3))
548
+ # a trim from the start seeks nowhere: no -ss, so the timeline stays where it is and
549
+ # a subtitle/data track is kept below (`-ss 0.000` dropped it, A158)
550
+ pre_input += ["-ss", f"{start - m:.3f}"] if round(start, 3) > 0 else []
551
+ # without sound the -t only counts frames (picture_output_t). Not from the centre:
552
+ # there the output's clock starts at the seek, between two frames, and the encoder
553
+ # rounds each frame to its own tick
554
+ keep = (picture_output_t(target, meta) if not rate and not args.fps and not args.from_center
555
+ else length_output_t(target, rate, runs_on=True))
556
+ post += (["-ss", f"{m:.3f}"] if m > 0 else []) + ["-t", keep]
557
+ out_seek = round(m, 3) if m > 0 else 0.0
558
+ # the output starts on the first frame at or after the seek (a seek before a
559
+ # picture that starts after the file's origin: on its first frame): its start
560
+ # timecode is that frame's, not the source's first frame's
561
+ v0, rate = stream_starts(meta)[0], frame_rate(meta)
562
+ tc_first = grid_at_or_after(max(round(start, 3), v0), v0, rate) - v0
563
+ elif not length_unknown:
564
+ info(f"source ({src_dur:.2f}s) is already shorter than {target:.2f}s; trim does nothing")
565
+ speed_unknown = length_unknown and args.method == "speed"
566
+ extra["timing"] = {
567
+ "method": args.method,
568
+ "source_duration": None if length_unknown else src_dur,
569
+ "target_duration": target,
570
+ "speed_factor": None if speed_unknown else factor,
571
+ "retimed": None if speed_unknown else retimed,
572
+ }
573
+
574
+ # ---- the output's rate: after any retiming, ahead of the frame's own filters. --fit blur and
575
+ # --pad-fill blur are a split/overlay graph, and FFmpeg 6.1's overlay ends its output at its
576
+ # last frame's start, so an fps filter after it lost the last frame (#512's placement).
577
+ # A speed change without --fps has already been put on the delivered grid above
578
+ if args.fps:
579
+ vf.append(f"fps={args.fps:g}")
580
+ elif meta["video"].get("variable_frame_rate_suspected"):
581
+ # said whichever filter conforms it: a speed change's regrid above is that conform, and the
582
+ # line was missing there (#527)
583
+ info("source looks variable-frame-rate; conforming to constant fps automatically")
584
+ if not regridded:
585
+ # the conform is the fps filter, as --fps is: -fps_mode cfr alone let a frame run up to
586
+ # two frames late against the sound (#512), its grid laid from the output-side seek
587
+ # (#538: --from-center put the picture of a 27 fps average clip 24-37 ms late)
588
+ vf.append(cfr_filter(meta, seek=out_seek))
589
+
590
+ # ---- aspect / size
591
+ geometry = None # (the frame's filters with every fill drawn black, scale, cropped) for the picture measurement
592
+ crop_window = None # (axis, start, end) of the kept part, fractions of the displayed frame, for crop_check
593
+ if args.aspect or args.width or args.height:
594
+ # the one sizing rule, shared with render.py --export-timeline's sequence frame
595
+ out_w, out_h = frame_size(parse_aspect(args.aspect) if args.aspect else None, args.width, args.height, sw, sh)
596
+ post += enlarge_args(meta, out_w, out_h)
597
+ if args.aspect and not (args.width or args.height) and out_w * out_h < sw * sh and out_w < (usual := (1080, 1920)[out_w > out_h]):
598
+ note(f"the frame is {out_w}x{out_h}: --aspect alone keeps the source's size and never enlarges; --width {usual} gives the usual delivery frame of this shape (enlarged {usual / out_w:.2g}x)")
599
+ if args.fit == "crop" and sw and sh:
600
+ warn_mostly_cropped(meta.get("video"), out_w, out_h)
601
+ # The scaled frame's margin on each axis is a multiple of 4 and the offset is computed
602
+ # here, to even: crop floors an odd offset to the chroma grid of a 4:2:0 frame, so
603
+ # --crop-x 1 lost the source's last column and showed one column of the margin, and a
604
+ # centred crop sat a pixel left of / above the centre (#512). exact=1 would put the
605
+ # chroma half a sample off the luma instead. The size is the one
606
+ # force_original_aspect_ratio=increase gives (av_rescale rounds half away from zero),
607
+ # widened by at most 3 px on the cropped axis.
608
+ sc_w = max(out_w, (2 * out_h * sw + sh) // (2 * sh))
609
+ sc_h = max(out_h, (2 * out_w * sh + sw) // (2 * sw))
610
+ mx, my = (-(-(sc - o) // 4) * 4 for sc, o in ((sc_w, out_w), (sc_h, out_h)))
611
+ ox, oy = (int(m * f / 2 + 0.5) * 2 for m, f in ((mx, args.crop_x), (my, args.crop_y)))
612
+ for axis, m, f, got in (("x", mx, args.crop_x, ox), ("y", my, args.crop_y, oy)):
613
+ if abs(m * f - got) > 1e-9:
614
+ # the offset is kept even (the chroma grid); a caller who asked for another one
615
+ # is told which it got, as proxy.py says which width it wrote
616
+ note(f"--crop-{axis} {f:g}: crop offset {got}px, not {m * f:g}px: the offset is kept even "
617
+ f"(4:2:0 chroma), on a {m}px margin")
618
+ vf.append(f"scale={out_w + mx}:{out_h + my}")
619
+ vf.append(f"crop={out_w}:{out_h}:{ox}:{oy}")
620
+ # the source pixels the crop leaves out on each side, at the scale it was cut at: each
621
+ # axis by its own, since the margin widened to a multiple of 4 scales the two apart
622
+ kx, ky = sw / (out_w + mx), sh / (out_h + my)
623
+ geometry = (vf[-2:], (out_w + mx) / sw, {"left": round(ox * kx), "right": round((mx - ox) * kx),
624
+ "top": round(oy * ky), "bottom": round((my - oy) * ky)})
625
+ # the kept window from the same numbers the crop filter above was built from (the
626
+ # anchor's even offset included): fractions of the scaled frame, which is the displayed
627
+ # frame's proportions on each axis. No margin on either axis: nothing is cut, no check
628
+ rel_x, rel_y = mx / (out_w + mx), my / (out_h + my)
629
+ if rel_x > 0 or rel_y > 0:
630
+ crop_window = (("x", ox / (out_w + mx), (ox + out_w) / (out_w + mx)) if rel_x >= rel_y
631
+ else ("y", oy / (out_h + my), (oy + out_h) / (out_h + my)))
632
+ elif args.fit == "crop": # a dry run's pending input has no size: the expressions, planned only
633
+ vf.append(f"scale={out_w}:{out_h}:force_original_aspect_ratio=increase")
634
+ vf.append(f"crop={out_w}:{out_h}:(in_w-out_w)*{args.crop_x:g}:(in_h-out_h)*{args.crop_y:g}")
635
+ elif args.fit == "blur":
636
+ # nothing is cropped and nothing is a black bar: the picture keeps its own aspect in
637
+ # the middle of a blurred, dimmed copy of itself (BLUR_DARKEN) filling the frame.
638
+ # The dimming is an eq on the code values, which is a -15 % perceptual dim on an SDR
639
+ # (gamma-encoded) signal and something else entirely on a PQ/HLG one -- so an HDR
640
+ # source keeps its blurred background undimmed rather than being silently altered
641
+ # (review 12). The blur itself is neutral either way, and no tone mapping happens.
642
+ darken = 0.0 if meta["video"].get("bt2020_or_hdr") else BLUR_DARKEN
643
+ if not darken:
644
+ info("--fit blur: HDR source, so the blurred background is not dimmed "
645
+ "(an eq on PQ/HLG code values is not the -15% dim it is on SDR); "
646
+ "run color.py --to-sdr first for the SDR look")
647
+ vf.append(pad_filters(out_w, out_h, "blur", args.pad_color, args.pad_blur, darken))
648
+ geometry = ([pad_filters(out_w, out_h, "blur", args.pad_color, args.pad_blur, darken, blank=True)], None, None)
649
+ else:
650
+ vf.append(pad_filters(out_w, out_h, args.pad_fill, args.pad_color, args.pad_blur, meta=meta))
651
+ geometry = ([pad_filters(out_w, out_h, args.pad_fill, args.pad_color, args.pad_blur, meta=meta, blank=True)], None, None)
652
+ vf.append("setsar=1")
653
+ # a non-square-pixel source is made square at its display aspect before anything else
654
+ # (the size above is computed in that frame), so the fitted picture is not squashed
655
+ if square_pixels(meta["video"]):
656
+ vf.insert(0, square_pixels(meta["video"]))
657
+ note(square_pixels_note(meta["video"]))
658
+
659
+ # ---- fades: last, so they are drawn on the frame that is delivered, over its final length
660
+ total = min(target, src_dur) if args.duration and args.method == "trim" else target if args.duration else src_dur
661
+ for kind, secs, at in (("in", args.fade_in, 0.0), ("out", args.fade_out, total - args.fade_out)):
662
+ if secs > 0 and total > 0:
663
+ vf.append(f"fade=t={kind}:st={max(at, 0):.3f}:d={secs:g}")
664
+ af += [f"afade=t={kind}:st={max(at, 0):.3f}:d={secs:g}"] if has_audio else []
665
+
666
+ # the start timecode is counted at the rate the output is delivered at: a --fps that changes
667
+ # the rate relabels it (01:00:00:12 at 25 fps is 01:00:00:24 at 50) even with no trim, which
668
+ # is also how a render.py clip cut at its own rate reaches the project's frame.fps
669
+ out_rate = args.fps or delivered_rate(meta)
670
+ src_fps = meta["video"].get("fps")
671
+ rate_changed = bool(out_rate and src_fps and exact_rate(float(out_rate)) != exact_rate(float(src_fps)))
672
+ relabel = tc_first is not None or rate_changed
673
+ if relabel:
674
+ post += output_timecode_args(meta, tc_first or 0.0, out_rate)
675
+
676
+ output = args.output or default_output(args.input, "fit")
677
+ cmd = ffmpeg_base() + pre_input + ["-i", args.input]
678
+ if vf:
679
+ cmd += ["-vf", ",".join(vf)]
680
+ if af:
681
+ cmd += ["-af", ",".join(af)]
682
+ cmd += ["-map", "0:v:0"]
683
+ if has_audio:
684
+ cmd += ["-map", f"0:a:{args.audio_stream}"]
685
+ cmd += video_args(meta, args.crf, args.preset)
686
+ cmd += cfr_args(meta, args.fps) if not args.fps else []
687
+ if has_audio:
688
+ cmd += aac_args()
689
+ else:
690
+ cmd += ["-an"]
691
+ cmd += post
692
+ if retimed or kept:
693
+ # the chapters follow the retime or the trim (#470): FFmpeg kept them at the source's times
694
+ # (an output-side -ss is subtracted from them by FFmpeg, so it is added back here)
695
+ chap_lead = out_seek if kept else 0.0
696
+ cmd = with_mapped_chapters(cmd, meta, (lambda t: t / factor) if retimed else (lambda t: t - kept[0] + chap_lead),
697
+ target + chap_lead if kept else None)
698
+ if retimed or "-ss" in pre_input:
699
+ # A subtitle/data stream stream-copied by run_keeping_subtitles keeps the source's
700
+ # original timestamps; --method speed retimes video (setpts) and audio (atempo) but has
701
+ # no equivalent way to retime a copied subtitle track, so it would desync from the
702
+ # now-faster/slower picture. Drop them here rather than ship a captions track that lies
703
+ # about when a line is spoken. --method trim's -ss moves the timeline the same way: a copied
704
+ # track kept its cues at the source's times and doubled the output's length (review 5).
705
+ run(cmd + [output])
706
+ dropped_streams = bool(meta.get("subtitle_streams") or meta.get("data_streams"))
707
+ else:
708
+ dropped_streams = run_keeping_subtitles(cmd, output, relabel_timecode=relabel)
709
+
710
+ result = probe(output, role="output")
711
+ msg = f"wrote {output} ({fmt_secs(result['duration'])}, {result['video']['width']}x{result['video']['height']})"
712
+ if retimed:
713
+ msg += f", speed {factor:.3f}x"
714
+ info(msg)
715
+ if geometry and not STATE.dry_run:
716
+ extra["picture"] = measure_picture(geometry, meta, sw, sh, result["video"],
717
+ sized=bool(args.width or args.height), matrix_filter=line_matrix_filter(meta))
718
+ if crop_window and not STATE.dry_run:
719
+ # the source range the output shows: a trim's window, else the whole source (speed retimes all of it)
720
+ k0, klen = kept if kept else (0.0, src_dur or (meta.get("duration") or 0.0))
721
+ extra["crop_check"] = check_crop(
722
+ args.input, orient, sw, sh, crop_window, k0, klen,
723
+ speed=factor if abs(factor - 1.0) > 1e-4 else 1.0, output_video=result.get("video"))
724
+ emit(output, dropped_non_av_streams=dropped_streams, **extra)
725
+ return 0
726
+
727
+
728
+ if __name__ == "__main__":
729
+ sys.exit(main())