@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,475 @@
1
+ #!/usr/bin/env python3
2
+ """Give the agent eyes: pull frames or a contact sheet out of a video as PNG so
3
+ the result can be inspected (caption placement, logo position, crop, colour).
4
+
5
+ Examples:
6
+ python3 look.py final.mp4 # 12-tile contact sheet with timecodes -> final_sheet.png
7
+ python3 look.py final.mp4 --tiles 4x5 --width 1600
8
+ python3 look.py final.mp4 --at 2.5 --at 7 # single frames -> final_2.500s.png, final_7.000s.png
9
+ python3 look.py before.mp4 --compare after.mp4 --at 4 # side-by-side frame
10
+ python3 look.py source.mp4 --at 12.5 --compare cut.mp4 --compare-at 0 -o start.png
11
+ python3 look.py reel.mp4 --safe tiktok --at 3 # shade what TikTok's own UI covers
12
+ python3 look.py show.mp4 --guides title,action,4:3 --at 10 # broadcast safe-area outlines
13
+ Then view the PNG (Read tool / image viewer) and verify before reporting.
14
+ """
15
+ import argparse
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import List, Optional
20
+
21
+ from _platforms import PLATFORMS, PLATFORM_CHOICES, resolve as resolve_platform
22
+ from _common import still_input_args # noqa: E402
23
+ from _common import STATE, require_tool, add_common, apply_common, default_font_file, die, emit, escape_drawtext, ffmpeg_base, info, probe, run, run_analysis, time_arg
24
+ from _common import drawtext_fontfile # noqa: E402
25
+ from _common import ffmpeg_filters, filter_missing_hint # noqa: E402
26
+ from _common.emit import note, record_fallback # noqa: E402
27
+ from _common.color import bt709_label_filter, bt2020_sdr_to_bt709_chain, hdr_to_sdr_chain, is_bt2020_sdr # noqa: E402
28
+ from _common.probe import PROBED_VIDEO, display_size, is_still_input, square_pixels, square_pixels_note # noqa: E402
29
+ from _common.emit import input_length # noqa: E402
30
+
31
+ # --guides: broadcast safe areas as outlines, in fractions of the frame (a tile as much as a frame).
32
+ # Action and title safe are SMPTE ST 2046-1's 93 % and 90 % of a 16:9 picture; the 4:3 centre cut
33
+ # is the 4:3 window of a 16:9 frame with SD's own 90 % action / 80 % title safe inside it.
34
+ # the extensions an -o is taken verbatim with (one picture); any other -o is a stem
35
+ IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp")
36
+ GUIDES = {"action": 0.93, "title": 0.90}
37
+ GUIDE_43 = {"action": 0.90, "title": 0.80}
38
+ GUIDE_COLOURS = {"action": "yellow", "title": "cyan", "4:3": "white"}
39
+
40
+
41
+ def guide_boxes(names) -> "tuple":
42
+ """drawbox outlines for --guides and the fractions they stand for (the result's `guides`)."""
43
+ t = "max(1\\,ih/270)"
44
+ boxes, described = [], []
45
+ for name in names:
46
+ if name in GUIDES:
47
+ f = GUIDES[name]
48
+ m = (1 - f) / 2
49
+ boxes.append(f"drawbox=x=iw*{m:g}:y=ih*{m:g}:w=iw*{f:g}:h=ih*{f:g}:color={GUIDE_COLOURS[name]}@0.9:t={t}")
50
+ described.append({"guide": name, "fraction": f, "of": "frame"})
51
+ else: # "4:3": the centre-cut window, then its own action and title safe
52
+ w = "ih*4/3"
53
+ boxes.append(f"drawbox=x=(iw-{w})/2:y=0:w={w}:h=ih:color=white@0.9:t={t}")
54
+ for sub, f in GUIDE_43.items():
55
+ m = (1 - f) / 2
56
+ boxes.append(f"drawbox=x=(iw-{w})/2+{w}*{m:g}:y=ih*{m:g}:w={w}*{f:g}:h=ih*{f:g}:"
57
+ f"color={GUIDE_COLOURS[sub]}@0.6:t={t}")
58
+ described.append({"guide": "4:3", "window": "centre 4:3 of the frame", "action": GUIDE_43["action"],
59
+ "title": GUIDE_43["title"]})
60
+ return boxes, described
61
+
62
+
63
+ FONT = "fontcolor=white:fontsize=h/18:box=1:boxcolor=black@0.55:boxborderw=6:x=8:y=8"
64
+
65
+
66
+ def fmt_hms(sec: float) -> str:
67
+ h, rem = divmod(sec, 3600)
68
+ m, s_ = divmod(rem, 60)
69
+ return f"{int(h):02d}:{int(m):02d}:{s_:06.3f}"
70
+
71
+
72
+ def timecode_filter(font_prefix: str, offset: float = 0.0) -> str:
73
+ """Burned-in timecode. `offset` is added to each frame's pts: an input-side -ss resets
74
+ timestamps to 0 at the seek point, so a sheet that starts reading mid-slice must add the seek
75
+ back or every tile is labelled `offset` seconds early (the contact sheet below seeks step/2)."""
76
+ if offset > 0:
77
+ return f"drawtext=text='%{{pts\\:hms\\:{offset:.6f}}}':{font_prefix}{FONT}"
78
+ return f"drawtext=text='%{{pts\\:hms}}':{font_prefix}{FONT}"
79
+
80
+
81
+ def _refuse_past_end(t: str, sec: float, meta: dict, path: str, whose: str = "") -> None:
82
+ """--at past the end of the picture it is taken from is refused, kind input, before ffmpeg
83
+ writes nothing (kind output). A still has one picture, at 0: past it, it was not written
84
+ (#531). `whose` names the --compare clip; the main input's message is the one it always was.
85
+ --compare checked neither picture's length."""
86
+ if is_still_input(meta) and sec > 0:
87
+ die(f"--at {t} is beyond {'the ' + whose if whose else path}, a still picture: it has one picture and no "
88
+ "length of its own (--at 0 shows it)")
89
+ dur = meta.get("duration") or 0.0
90
+ if dur and sec > dur:
91
+ of = f"the {whose}'s " if whose else "the "
92
+ die(f"--at {t} is beyond {of}duration ({dur:.2f}s)")
93
+
94
+
95
+ def _seek(sec: float, meta: dict) -> List[str]:
96
+ """The input seek to `sec`, none for a still (its one picture is at 0): image2 given `-ss 0.000`
97
+ drops a TGA's only frame, which image2 gives a duration, and nothing was written (#531)."""
98
+ return [] if is_still_input(meta) else ["-ss", f"{sec:.3f}"]
99
+
100
+
101
+ def _half_height(half: int, size: "tuple") -> int:
102
+ """The even height a `half`-wide picture of displayed `size` scales to (16:9 when unknown)."""
103
+ w, h = size
104
+ return max(2, int(round(half * (h / w if w and h else 9 / 16) / 2)) * 2)
105
+
106
+
107
+ def _png_size(png_path: str) -> "Optional[tuple]":
108
+ # run_analysis(): the same wall-clock ceiling and #234 UTF-8 decoding as every other
109
+ # ffprobe/ffmpeg measurement in this codebase, check=False since a probe failure here is
110
+ # an unknown-metric result (has_ink: None), not a reason to die -- a stall still does,
111
+ # exactly like every other measurement's timeout.
112
+ proc = run_analysis([require_tool("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries",
113
+ "stream=width,height", "-of", "csv=p=0", png_path], check=False)
114
+ parts = proc.stdout.strip().split(",")
115
+ if len(parts) != 2:
116
+ return None
117
+ try:
118
+ return int(parts[0]), int(parts[1])
119
+ except ValueError:
120
+ return None
121
+
122
+
123
+ def _png_pixels(png_path: str, w: int, h: int) -> "Optional[bytes]":
124
+ proc = run_analysis([require_tool("ffmpeg"), "-v", "error", "-i", png_path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
125
+ check=False, text=False)
126
+ data = proc.stdout
127
+ return data if len(data) >= w * h * 3 else None
128
+
129
+
130
+ def measure_ink(png_path: str, *, box=None, margin_frac: float = 0.03, threshold: int = 28) -> dict:
131
+ """Non-background ink in `png_path` (or the `box` = (x0, y0, w, h) sub-region of it): a pixel-only
132
+ measurement, never a judgement of legibility. The background is estimated as the median RGB of a
133
+ thin strip around the region's own edge (so it works on any frame, not just a black synthetic one);
134
+ a pixel is "ink" when any channel differs from that estimate by more than `threshold`. Returns
135
+ {has_ink, bbox (x0,y0,x1,y1 within the region, or None), ink_fraction, row_bands} -- row_bands are
136
+ gap-merged bands of rows carrying ink, the same convention tests/_fixtures.py's _ass_ink_rows uses,
137
+ so a caption wrapped onto two lines shows as two bands without measuring any font."""
138
+ size = _png_size(png_path)
139
+ if not size:
140
+ return {"has_ink": None, "bbox": None, "ink_fraction": None, "row_bands": []}
141
+ full_w, full_h = size
142
+ data = _png_pixels(png_path, full_w, full_h)
143
+ if data is None:
144
+ return {"has_ink": None, "bbox": None, "ink_fraction": None, "row_bands": []}
145
+ if box:
146
+ bx, by, bw, bh = box
147
+ bx, by = max(0, bx), max(0, by)
148
+ bw, bh = min(bw, full_w - bx), min(bh, full_h - by)
149
+ else:
150
+ bx, by, bw, bh = 0, 0, full_w, full_h
151
+ if bw <= 0 or bh <= 0:
152
+ return {"has_ink": None, "bbox": None, "ink_fraction": None, "row_bands": []}
153
+
154
+ def px(x, y):
155
+ off = ((by + y) * full_w + (bx + x)) * 3
156
+ return data[off], data[off + 1], data[off + 2]
157
+
158
+ margin = max(1, int(min(bw, bh) * margin_frac))
159
+ border = []
160
+ for x in range(0, bw, max(1, bw // 40 or 1)):
161
+ border.append(px(x, 0))
162
+ border.append(px(x, bh - 1))
163
+ for y in range(0, bh, max(1, bh // 40 or 1)):
164
+ border.append(px(0, y))
165
+ border.append(px(bw - 1, y))
166
+ if not border:
167
+ border = [px(0, 0)]
168
+ bg = tuple(sorted(c[i] for c in border)[len(border) // 2] for i in range(3))
169
+
170
+ lit_rows = []
171
+ min_x = min_y = None
172
+ max_x = max_y = None
173
+ ink_count = 0
174
+ for y in range(bh):
175
+ row_lit = False
176
+ for x in range(bw):
177
+ r, g, b = px(x, y)
178
+ if abs(r - bg[0]) > threshold or abs(g - bg[1]) > threshold or abs(b - bg[2]) > threshold:
179
+ row_lit = True
180
+ ink_count += 1
181
+ min_x = x if min_x is None else min(min_x, x)
182
+ max_x = x if max_x is None else max(max_x, x)
183
+ min_y = y if min_y is None else min(min_y, y)
184
+ max_y = y if max_y is None else max(max_y, y)
185
+ if row_lit:
186
+ lit_rows.append(y)
187
+
188
+ bands = []
189
+ for y in lit_rows:
190
+ if bands and y - bands[-1][1] <= margin:
191
+ bands[-1][1] = y
192
+ else:
193
+ bands.append([y, y])
194
+
195
+ has_ink = min_x is not None
196
+ return {
197
+ "has_ink": has_ink,
198
+ "bbox": [min_x, min_y, max_x, max_y] if has_ink else None,
199
+ "ink_fraction": round(ink_count / (bw * bh), 4) if bw * bh else 0.0,
200
+ "row_bands": [list(b) for b in bands],
201
+ }
202
+
203
+
204
+ def display_conversion(meta: dict, what: str = "source") -> str:
205
+ """The filter that shows `meta`'s frames on an SDR BT.709 display, or "" for a picture that is
206
+ already one. HDR is tone-mapped so the agent judges representative colours, not raw HLG/PQ."""
207
+ v = meta.get("video") or {}
208
+ if not v.get("bt2020_or_hdr"):
209
+ return ""
210
+ # color.py --to-sdr's own chains at its defaults (hable, a 1000-nit PQ peak), so the sheet
211
+ # shows what that conversion gives. Through 3.6.0 this tone map linearised at npl=1000 and
212
+ # a sheet's white came out at about Y 151 of 235; a BT.2020 SDR source was tone-mapped
213
+ # too, where color.py only converts its gamut.
214
+ if is_bt2020_sdr(v):
215
+ info(f"BT.2020 SDR {what}: frames are converted to BT.709 for display")
216
+ return bt2020_sdr_to_bt709_chain(meta)
217
+ info(f"HDR {what}: frames are tone-mapped to SDR for display")
218
+ return hdr_to_sdr_chain({"video": dict(v, color_transfer=v.get("color_transfer") or "arib-std-b67")}, "hable")
219
+
220
+
221
+ def main() -> int:
222
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
223
+ ap.add_argument("input")
224
+ ap.add_argument("-o", "--output", help="output PNG (contact sheet / compare) or basename for --at frames")
225
+ ap.add_argument("--at", action="append", help="time of a frame to extract (repeatable)")
226
+ ap.add_argument("--tiles", default="4x3", help="contact sheet grid COLSxROWS, e.g. 4x3 for 12 frames (default 4x3)")
227
+ ap.add_argument("--width", type=int, default=1280, help="total width of the sheet / compare image in px, 2..16384 (default 1280); an --at frame is at most this wide and never enlarged")
228
+ ap.add_argument("--compare", help="second video: place its frame next to the first (needs --at)")
229
+ ap.add_argument("--compare-at", action="append", metavar="TIME",
230
+ help="seek time in the comparison file, one per --at. By default both use --at.")
231
+ ap.add_argument("--no-timecode", action="store_true", help="no burnt-in timecode stamps (a way out if drawtext itself is unusable, see doctor)")
232
+ ap.add_argument("--safe", choices=PLATFORM_CHOICES, help="shade the zones this platform's UI covers (its description bar, "
233
+ "like column, status bar) so you can see whether anything readable is under them")
234
+ ap.add_argument("--guides", metavar="LIST",
235
+ help="draw broadcast safe-area outlines on the PNG (a preview only; nothing is written into a video): "
236
+ "a comma list of action (93%%), title (90%%) and 4:3 (the 4:3 centre cut of a 16:9 frame, "
237
+ "with its 90%% action and 80%% title safe)")
238
+ ap.add_argument("--ink", action="store_true", help="measure non-background pixels in each written PNG (bbox, "
239
+ "ink_fraction, row_bands per tile for a contact sheet) instead of "
240
+ "just eyeballing it -- a pixel-only signal, not a legibility judgement")
241
+ add_common(ap)
242
+ args = ap.parse_args()
243
+ apply_common(args)
244
+ if args.compare_at and not args.compare:
245
+ die("--compare-at needs --compare FILE")
246
+ if args.compare and not args.at:
247
+ die("--compare needs --at TIME")
248
+ if args.compare_at and len(args.compare_at) != len(args.at):
249
+ die("give one --compare-at TIME per --at TIME")
250
+
251
+ meta = probe(args.input)
252
+ if not meta.get("video"):
253
+ die("input has no video stream")
254
+ dur = meta.get("duration") or 0.0
255
+ stem = Path(args.input).stem
256
+ outdir = str(Path(args.output).parent) if args.output else str(Path(args.input).parent)
257
+ # a resolvable font file, given as fontfile=, is the only form confirmed not to crash drawtext's
258
+ # own fontconfig resolution on some real Windows ffmpeg builds (#100); font= is the fallback when
259
+ # nothing can be resolved, unchanged from before this existed.
260
+ if not args.no_timecode and ffmpeg_filters() and "drawtext" not in ffmpeg_filters():
261
+ # a build without drawtext (Homebrew's plain ffmpeg) cannot stamp the timecodes, but the
262
+ # sheet itself only needs tile: draw it without them and say so, rather than failing the
263
+ # step every picture change ends with (#394)
264
+ args.no_timecode = True
265
+ record_fallback("this ffmpeg build has no drawtext filter, so the sheet has no timecode stamps "
266
+ "(the same as --no-timecode)", "look_no_drawtext")
267
+ note("no timecode stamps: this ffmpeg build has no drawtext filter (" + filter_missing_hint("drawtext") + ")")
268
+ if args.no_timecode:
269
+ font_prefix, tc = "", "" # nothing is drawn, so no font is resolved or copied
270
+ else:
271
+ default_font = default_font_file("DejaVu Sans")
272
+ font_prefix = f"{drawtext_fontfile(default_font)}:" if default_font else ""
273
+ tc = "," + timecode_filter(font_prefix)
274
+ # --safe: the platform's occluded zones, drawn as shaded boxes in fractions of the frame so
275
+ # the same filter is right at any scale (a tile of a contact sheet as much as a full frame).
276
+ safe_filter = ""
277
+ args.safe = resolve_platform(args.safe)
278
+ if args.safe and not PLATFORMS[args.safe].get("frame"):
279
+ info(f"--safe {args.safe}: this destination has no frame and no app chrome; nothing to shade")
280
+ args.safe = None
281
+ if args.safe:
282
+ z = PLATFORMS[args.safe]["safe"]
283
+ frame = PLATFORMS[args.safe]["frame"]
284
+ dw, dh = display_size(meta["video"])
285
+ if dw and dh and abs(dw / dh - frame["w"] / frame["h"]) > 0.02:
286
+ info(f"--safe {args.safe}: this source is {dw}x{dh}, not {args.safe}'s "
287
+ f"{frame['w']}x{frame['h']} -- the zones are drawn as fractions of the frame you gave, "
288
+ f"so reframe first (fit.py --aspect) to see what the app really covers")
289
+ boxes = []
290
+ for edge, frac in (("top", z["top"]), ("bottom", z["bottom"]), ("left", z["left"]), ("right", z["right"])):
291
+ if frac <= 0:
292
+ continue
293
+ if edge == "top":
294
+ boxes.append(f"drawbox=x=0:y=0:w=iw:h=ih*{frac:g}:color=red@0.35:t=fill")
295
+ elif edge == "bottom":
296
+ boxes.append(f"drawbox=x=0:y=ih*(1-{frac:g}):w=iw:h=ih*{frac:g}:color=red@0.35:t=fill")
297
+ elif edge == "left":
298
+ boxes.append(f"drawbox=x=0:y=0:w=iw*{frac:g}:h=ih:color=red@0.20:t=fill")
299
+ else:
300
+ boxes.append(f"drawbox=x=iw*(1-{frac:g}):y=0:w=iw*{frac:g}:h=ih:color=red@0.20:t=fill")
301
+ safe_filter = "," + ",".join(boxes) if boxes else ""
302
+ info(f"--safe {args.safe}: shaded top {z['top'] * 100:.0f}% / bottom {z['bottom'] * 100:.0f}% / "
303
+ f"left {z['left'] * 100:.0f}% / right {z['right'] * 100:.0f}% of the frame -- keep text out of those")
304
+ guides = None
305
+ if args.guides:
306
+ names = [g.strip() for g in args.guides.split(",") if g.strip()]
307
+ bad = [g for g in names if g not in ("action", "title", "4:3")]
308
+ if bad or not names:
309
+ die(f"--guides takes action, title and 4:3, got {args.guides!r}")
310
+ dw, dh = display_size(meta["video"])
311
+ if "4:3" in names and dw and dh and dw / dh < 4 / 3 + 0.01:
312
+ die(f"--guides 4:3 draws the 4:3 centre cut of a wider frame; this source is {dw}x{dh}")
313
+ boxes, guides = guide_boxes(list(dict.fromkeys(names)))
314
+ safe_filter += "," + ",".join(boxes)
315
+ tc = safe_filter + tc
316
+ marks = tc # the boxes and the stamp, without the display conversion (each --compare input has its own)
317
+ tm = display_conversion(meta)
318
+ if tm:
319
+ tc = "," + tm + tc
320
+ outputs: List[str] = []
321
+ comparisons = []
322
+ # An untagged SDR source is BT.709 (what players and every encoder line here take it as), but the
323
+ # conversion to the PNG's RGB reads "unknown" as BT.601: C03028 came out B31F28 (#410). Its
324
+ # frames are labelled first (tags only), so that conversion reads them as BT.709.
325
+ lab = bt709_label_filter(meta)
326
+ lab = lab + "," if lab else ""
327
+ # every picture is squared at its display aspect before it is scaled (#411): a DV or HDV
328
+ # frame's stored size is not the picture a player shows
329
+ square = square_pixels(meta["video"])
330
+ sq = square + "," if square else ""
331
+ if square:
332
+ note(square_pixels_note(meta["video"]))
333
+
334
+ if args.compare:
335
+ cmeta = probe(args.compare)
336
+ if not cmeta.get("video"):
337
+ die("--compare input has no video stream")
338
+ if guides and any(g.get("guide") == "4:3" for g in guides):
339
+ # the guides are drawn on both pictures: the second must be wider than 4:3 as well
340
+ cw, ch = display_size(cmeta.get("video") or {})
341
+ if cw and ch and cw / ch < 4 / 3 + 0.01:
342
+ die(f"--guides 4:3 draws the 4:3 centre cut of a wider frame; the --compare clip is {cw}x{ch}")
343
+ # the second picture is converted for display by its own tags: through 3.6.1 the first
344
+ # input's tone map ran on both, so an SDR clip beside a PQ one was read as PQ
345
+ tm2 = display_conversion(cmeta, "--compare clip")
346
+ lab2 = bt709_label_filter(cmeta)
347
+ lab2 = lab2 + "," if lab2 else ""
348
+ csq = (square_pixels(cmeta.get("video")) + ",") if square_pixels(cmeta.get("video")) else ""
349
+ pairs = []
350
+ for idx, t in enumerate(args.at):
351
+ sec = time_arg(t, "--at", meta["video"].get("fps") if meta.get("video") else None)
352
+ _refuse_past_end(t, sec, meta, args.input)
353
+ comparison = args.compare_at[idx] if args.compare_at else t
354
+ compare_sec = time_arg(comparison, "--compare-at", cmeta["video"].get("fps")) if args.compare_at else sec
355
+ _refuse_past_end(comparison, compare_sec, cmeta, args.compare, "--compare clip")
356
+ pairs.append((sec, compare_sec))
357
+ for idx, (sec, compare_sec) in enumerate(pairs):
358
+ if args.output and len(args.at) == 1 and Path(args.output).suffix.lower() in IMAGE_EXTS:
359
+ out = args.output # one frame, one named image file: the caller's -o is the contract
360
+ else:
361
+ # several frames, or -o given as a stem/prefix: an occurrence index keeps every
362
+ # requested --at its own file even when two round to the same millisecond
363
+ stem_part = (args.output and Path(args.output).stem) or stem
364
+ out = os.path.join(outdir, f"{stem_part}_vs_{Path(args.compare).stem}_{idx}_{sec:.3f}s.png")
365
+ half = args.width // 2
366
+ # the tone map and the --safe / --guides boxes go on each picture as scaled, before the
367
+ # pad: drawn after it, a picture letterboxed in the box got guides from the padded
368
+ # height (a 2:1 clip beside a 16:9 one); the timecode stamp is drawn on the box
369
+ pre = marks.replace("," + timecode_filter(font_prefix), "")
370
+ # each picture keeps its own aspect inside a half-width box as tall as the taller of the
371
+ # two (letterboxed, not stretched): through 3.1.3 scale2ref forced the first to the
372
+ # second's size, so a 4:3 beside a 16:9 came out squashed (#411)
373
+ box_h = max(_half_height(half, display_size(meta["video"])),
374
+ _half_height(half, display_size(cmeta.get("video"))))
375
+ def fit(conv, seek):
376
+ conv = "," + conv if conv else ""
377
+ stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(seek))}':{font_prefix}{FONT}"
378
+ # Each side starts at its own first selected frame, even if the frame grids differ.
379
+ return (f"scale={half}:{box_h}:force_original_aspect_ratio=decrease{conv}{pre},"
380
+ f"pad={half}:{box_h}:(ow-iw)/2:(oh-ih)/2:color=0x202020,setsar=1{stamp},setpts=PTS-STARTPTS")
381
+ fc = (f"[0:{PROBED_VIDEO}]{lab}{sq}{fit(tm, sec)}[a];[1:{PROBED_VIDEO}]{lab2}{csq}{fit(tm2, compare_sec)}[b];"
382
+ f"[a][b]hstack=inputs=2[out]")
383
+ cmd = ffmpeg_base() + [*_seek(sec, meta), *still_input_args(args.input), "-i", args.input, *_seek(compare_sec, cmeta), *still_input_args(args.compare), "-i", args.compare,
384
+ "-filter_complex", fc, "-map", "[out]", "-frames:v", "1", "-update", "1", out]
385
+ run(cmd)
386
+ outputs.append(out)
387
+ comparisons.append({"output": out, "input_seek": sec, "compare_seek": compare_sec})
388
+ elif args.at:
389
+ for t in args.at:
390
+ sec = time_arg(t, "--at", meta["video"].get("fps") if meta.get("video") else None)
391
+ _refuse_past_end(t, sec, meta, args.input)
392
+ if args.output and len(args.at) == 1 and Path(args.output).suffix.lower() in IMAGE_EXTS:
393
+ out = args.output # one frame, one named image file: the caller's -o is the contract
394
+ else:
395
+ # several frames, or -o given as a stem/prefix without an image extension
396
+ out = os.path.join(outdir, f"{args.output and Path(args.output).stem or stem}_{sec:.3f}s.png")
397
+ stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(sec))}':{font_prefix}{FONT}"
398
+ cmd = ffmpeg_base() + [*_seek(sec, meta), *still_input_args(args.input), "-i", args.input, "-map", f"0:{PROBED_VIDEO}", "-vf", f"{lab}{sq}scale='min({args.width},iw)':-2{tc.replace(',' + timecode_filter(font_prefix), '')}{stamp}", "-frames:v", "1", "-update", "1", out]
399
+ run(cmd)
400
+ outputs.append(out)
401
+ else:
402
+ try:
403
+ cols, rows = (int(x) for x in args.tiles.lower().split("x"))
404
+ except ValueError:
405
+ die("--tiles must look like 4x3")
406
+ if cols < 1 or rows < 1:
407
+ # A21: 0 columns or rows divided the length by zero (a traceback, no JSON) and a
408
+ # negative count reached ffmpeg's tile filter (kind ffmpeg)
409
+ die(f"--tiles must be COLSxROWS with both at least 1 (like 4x3), got {args.tiles}")
410
+ n = cols * rows
411
+ dur = input_length(meta) # the sheet is spread over the length: none stated is refused with the way out (#491)
412
+ if not dur:
413
+ die("cannot build a contact sheet without a known duration")
414
+ frames_avail = int((meta["video"].get("fps") or 0) * dur) or 1
415
+ if n > frames_avail:
416
+ # a 2x2 sheet from a one-frame clip: tile waits for frames that never come and writes nothing
417
+ cols, rows = min(cols, frames_avail), 1
418
+ n = cols * rows
419
+ info(f"only {frames_avail} frame(s) available; sheet reduced to {cols}x{rows}")
420
+ step = dur / n
421
+ tile_w = max(2, (args.width // cols) // 2 * 2)
422
+ # -o without an image extension is a stem here too (<stem>_sheet.png), as for --at and
423
+ # --compare: given verbatim, ffmpeg could not choose a muxer for it (kind ffmpeg, A159)
424
+ out = (args.output if args.output and Path(args.output).suffix.lower() in IMAGE_EXTS
425
+ else os.path.join(outdir, f"{(args.output and Path(args.output).stem) or stem}_sheet.png"))
426
+ # sample at the middle of each slice so the first/last tiles are not black lead-in/out frames
427
+ # with only a handful of frames a mid-slice seek skips past them all: start at 0 instead
428
+ seek = 0.0 if frames_avail < 4 else step / 2
429
+ # -copyts -start_at_zero keeps each frame's own timestamp through the seek, counted from
430
+ # the file's start, so the stamp is the frame's pts as it is. What an input -ss alone
431
+ # resets pts to differs by container: an MPEG-TS (which starts at 1.4 s) came out
432
+ # labelled one seek late when the seek was added back (#411)
433
+ tc_sheet = tc
434
+ vf = (f"select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,{step * 0.98:.6f})',{lab}{sq}scale={tile_w}:-2{tc_sheet},"
435
+ f"tile={cols}x{rows}:padding=2:margin=2:color=0x202020")
436
+ cmd = ffmpeg_base() + ["-copyts", "-start_at_zero", "-ss", f"{seek:.6f}", *still_input_args(args.input), "-i", args.input, "-map", f"0:{PROBED_VIDEO}", "-vf", vf, "-frames:v", "1", "-update", "1", out]
437
+ run(cmd)
438
+ outputs.append(out)
439
+ info(f"contact sheet: {n} frames every {step:.2f}s")
440
+
441
+ for o in outputs:
442
+ if STATE.dry_run or os.path.exists(o):
443
+ info(f"wrote {o}")
444
+
445
+ ink = None
446
+ if args.ink and not STATE.dry_run:
447
+ if outputs and args.at is None and not args.compare:
448
+ # contact sheet: one PNG holding a cols x rows grid (tile_w:padding=2:margin=2, as built above)
449
+ # -- split it back into per-tile boxes so each tile is measured on its own, not the whole sheet.
450
+ sheet = outputs[0]
451
+ size = _png_size(sheet)
452
+ if size:
453
+ full_w, full_h = size
454
+ margin, padding = 2, 2
455
+ th = (full_h - 2 * margin - (rows - 1) * padding) // rows if rows else full_h
456
+ tiles = []
457
+ for r in range(rows):
458
+ for c in range(cols):
459
+ bx = margin + c * (tile_w + padding)
460
+ by = margin + r * (th + padding)
461
+ tiles.append(measure_ink(sheet, box=(bx, by, tile_w, th)))
462
+ ink = {"tiles": tiles}
463
+ else:
464
+ ink = {"frames": [measure_ink(o) for o in outputs]}
465
+
466
+ emit(outputs[0] if len(outputs) == 1 else None, outputs=outputs, **({"ink": ink} if ink is not None else {}),
467
+ **({"guides": guides} if guides else {}), **({"comparisons": comparisons} if comparisons else {}))
468
+ if len(outputs) > 1 and not args.json:
469
+ for o in outputs:
470
+ print(o)
471
+ return 0
472
+
473
+
474
+ if __name__ == "__main__":
475
+ sys.exit(main())