@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,560 @@
1
+ """The alpha channel: reading it, keeping it through a re-encode, and checking it was kept.
2
+
3
+ export.py's alpha presets (#417) measured the alpha of a written master against its source's; the
4
+ helpers moved here so the tools that composite or grade (color.py, graphics.py, overlay.py) and
5
+ background.py's transparent canvas can do the same:
6
+
7
+ - `--keep-alpha` (color, graphics, overlay) writes the picture with its alpha plane, in one of the
8
+ ALPHA_CODECS lines (`--alpha-codec`, ProRes 4444 by default); background.py's `--transparent`
9
+ writes a fully transparent canvas in the same lines. `--alpha-mode straight|premultiplied` says
10
+ how the colour is stored, as export.py's does.
11
+ - An alpha line keeps the source's colour tags and converts no matrix, as `--codec prores` does
12
+ (`keeps_source_tags()` in decision.py): an alpha master is an editing master. An RGB source has
13
+ no matrix to keep: on a line that stores YUV (ProRes 4444, VP9) it is converted to BT.709 and
14
+ tagged so (`rgb_to_bt709_line()`, #496); on an RGB line (qtrle, PNG) it stays the RGB it was.
15
+ - Every completed run on a source whose alpha is really used (a frame below OPAQUE) gets an
16
+ `alpha` verification step. Without `--keep-alpha` the output's picture has no alpha and that step
17
+ fails (the output reported `verified: true` with the alpha gone before this module existed);
18
+ `--drop-alpha` says the flattening is wanted, and a note records it instead.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import re
25
+ import subprocess
26
+ import threading
27
+ from typing import Any, Dict, List, Optional
28
+
29
+ from _common import runner as _runner
30
+ from _common.color import carried_tag, hdr_line_matrix, hdr_rgb_matrix_filter, is_rgb, rgb_to_bt709_filter
31
+ from _common.runner import STATE, ffmpeg_encoders, require_tool, run
32
+
33
+ # A pixel format that carries an alpha plane (yuva*, rgba, argb, gbrap, ya8/ya16, ...).
34
+ ALPHA_PIX = re.compile(r"^(yuva|gbrap|ya\d|rgba|bgra|argb|abgr|rgba64|bgra64)")
35
+
36
+ ALPHA_TOLERANCE = 2.0 # of 255, per frame (or on the mean and the most transparent frame, below)
37
+ OPAQUE = 254.5 # a frame whose mean alpha is at least this is fully opaque
38
+
39
+ _MEASURE_W, _MEASURE_H = 64, 36 # the measuring copy: small enough to read every frame, large enough for exact edges
40
+
41
+ # The lines --keep-alpha / --transparent write. `pix_fmt` is what the encoder is asked for and is
42
+ # read back (the `alpha` step's `codec` field); `ext` are the containers that hold it.
43
+ ALPHA_CODECS: Dict[str, Dict[str, Any]] = {
44
+ "prores4444": {"video": ["-c:v", "prores_ks", "-profile:v", "4", "-vendor", "apl0", "-pix_fmt", "yuva444p10le",
45
+ "-alpha_bits", "16"],
46
+ "encoder": "prores_ks", "pix_fmt": "yuva444p10le", "ext": (".mov", ".mkv"),
47
+ "audio": ["-c:a", "pcm_s16le"], "desc": "ProRes 4444 with 16-bit alpha"},
48
+ "qtrle": {"video": ["-c:v", "qtrle", "-pix_fmt", "argb"], "encoder": "qtrle", "pix_fmt": "argb", "ext": (".mov",),
49
+ "audio": ["-c:a", "pcm_s16le"], "desc": "QuickTime Animation, lossless RGB + alpha"},
50
+ "png": {"video": ["-c:v", "png", "-pix_fmt", "rgba"], "encoder": "png", "pix_fmt": "rgba", "ext": (".mov", ".mkv"),
51
+ "audio": ["-c:a", "pcm_s16le"], "desc": "PNG frames in a .mov/.mkv, lossless RGB + alpha"},
52
+ "vp9": {"video": ["-c:v", "libvpx-vp9", "-pix_fmt", "yuva420p", "-crf", "20", "-b:v", "0", "-row-mt", "1"],
53
+ "encoder": "libvpx-vp9", "pix_fmt": "yuva420p", "ext": (".webm", ".mkv"),
54
+ "audio": ["-c:a", "libopus", "-b:a", "128k"], "desc": "VP9 with an alpha layer (CRF 20)"},
55
+ }
56
+ ALPHA_CODEC_DEFAULT = "prores4444"
57
+ ALPHA_MODES = ("straight", "premultiplied")
58
+
59
+
60
+ _DECODERS: "Optional[set]" = None
61
+
62
+
63
+ def ffmpeg_decoders() -> set:
64
+ """Names from `ffmpeg -decoders`, read once (empty when the list cannot be read), as
65
+ runner.ffmpeg_encoders() reads the encoders: the libvpx VP9 decoder is a build option of its
66
+ own, so the encoder list does not say whether it is there."""
67
+ global _DECODERS
68
+ if _DECODERS is None:
69
+ _DECODERS = _runner._read_ff_list("-decoders", r"^\s*[VAS][.\w]{5}\s+(\S+)")
70
+ return _DECODERS
71
+
72
+
73
+ def libvpx_vp9_decoder() -> bool:
74
+ """True when the build lists libvpx-vp9 among its decoders, or when the list could not be read
75
+ (unknown is not "missing": the explicit decoder is kept and ffmpeg itself says if it is absent).
76
+ False only when the list was read and does not have it."""
77
+ decoders = ffmpeg_decoders()
78
+ return not decoders or "libvpx-vp9" in decoders
79
+
80
+
81
+ def vp9_decoder_args(codec: Optional[str]) -> List[str]:
82
+ """The input option that decodes a VP9 stream with libvpx-vp9: FFmpeg's native vp9 decoder
83
+ drops the alpha layer (a WebM's yuva420p comes out yuv420p, fully opaque). [] for any other
84
+ codec, or when this build has no libvpx-vp9 decoder (decoder_args_for() refuses that case
85
+ where the alpha matters)."""
86
+ return ["-c:v", "libvpx-vp9"] if codec == "vp9" and libvpx_vp9_decoder() else []
87
+
88
+
89
+ def vp9_alpha_tagged(path: str) -> bool:
90
+ """True when the first video stream is VP9 stored with an alpha layer (Matroska/WebM's
91
+ ALPHA_MODE=1 stream tag): ffprobe reports such a stream as yuv420p, so the pixel format alone
92
+ does not show the alpha. A metadata read, so a dry run can decide without decoding."""
93
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries",
94
+ "stream=codec_name:stream_tags", "-of", "json", path], quiet=True)
95
+ try:
96
+ streams = json.loads(proc.stdout or "{}").get("streams") or []
97
+ except ValueError:
98
+ return False
99
+ s = streams[0] if streams else {}
100
+ return s.get("codec_name") == "vp9" and any(k.lower() == "alpha_mode" and str(v).strip() == "1"
101
+ for k, v in (s.get("tags") or {}).items())
102
+
103
+
104
+ def has_alpha_plane(meta: Dict[str, Any], path: str) -> bool:
105
+ """True when the first video stream of `path` (probed as `meta`) stores an alpha plane: a pixel
106
+ format with one, or a VP9 stream tagged with an alpha layer. Metadata only; whether the alpha
107
+ is used (any pixel below opaque) takes alpha_stats()."""
108
+ v = (meta or {}).get("video") or {}
109
+ # a palette (pal8: an indexed PNG/GIF) can carry transparency in the palette itself (tRNS),
110
+ # which the pixel format does not show; it is measured like an alpha plane
111
+ return (bool(ALPHA_PIX.match(v.get("pix_fmt") or "")) or v.get("pix_fmt") == "pal8"
112
+ or (v.get("codec") == "vp9" and vp9_alpha_tagged(path)))
113
+
114
+
115
+ def frame_means(cmd_head: List[str], path: str, chain: str) -> "Dict[str, object] | None":
116
+ """Every decoded frame of `path` through `chain` to a 64x36 grey copy: {mean (over every frame),
117
+ min (the lowest frame's mean), frames, per_frame (each frame's mean, in decode order)}. None
118
+ when no frame decodes."""
119
+ w, h = _MEASURE_W, _MEASURE_H
120
+ cmd = cmd_head + ["-i", path, "-map", "0:v:0", "-vf", f"{chain},scale={w}:{h}:flags=area,format=gray",
121
+ "-f", "rawvideo", "-"]
122
+ # Read frame by frame as ffmpeg writes them, not the whole pipe at once: the raw copy is 2304
123
+ # bytes a frame (~250 MB for an hour at 30 fps), the per-frame means a float each. The same
124
+ # wall-clock limit as run_analysis(), which this replaces here.
125
+ _runner._refuse_url_media(cmd)
126
+ cmd = _runner.guard_input_names(cmd)
127
+ limit = _runner._limit_for(cmd)
128
+ size = w * h
129
+ frames: List[float] = []
130
+ child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, **_runner.child_kwargs())
131
+ _runner._watch(child, cmd)
132
+ expired = threading.Event()
133
+
134
+ def _expire() -> None:
135
+ expired.set()
136
+ child.kill()
137
+
138
+ timer = threading.Timer(limit, _expire) if limit else None
139
+ if timer:
140
+ timer.daemon = True
141
+ timer.start()
142
+ try:
143
+ pending = b""
144
+ while True:
145
+ chunk = child.stdout.read(size * 64)
146
+ if not chunk:
147
+ break
148
+ pending += chunk
149
+ whole = len(pending) - len(pending) % size
150
+ for i in range(0, whole, size):
151
+ frames.append(sum(pending[i:i + size]) / size)
152
+ pending = pending[whole:]
153
+ child.wait()
154
+ finally:
155
+ if timer:
156
+ timer.cancel()
157
+ _runner._unwatch(child)
158
+ child.stdout.close()
159
+ if expired.is_set():
160
+ _runner._timed_out(cmd, limit or 0)
161
+ if child.returncode != 0 or not frames:
162
+ return None
163
+ return {"mean": sum(frames) / len(frames), "min": min(frames), "frames": len(frames), "per_frame": frames}
164
+
165
+
166
+ def alpha_stats(path: str, codec: Optional[str] = None) -> "Dict[str, object] | None":
167
+ """The alpha (0-255) of every decoded frame, on a 64x36 copy: {mean, min, frames, per_frame}.
168
+ 255.0 is fully opaque, and a picture with no alpha plane reads 255 too (format=rgba fills it).
169
+ Every frame, not the first: a clip that opens fully opaque and turns transparent later would
170
+ read as opaque from its first frame, in the source and in a written file that lost its alpha.
171
+ A VP9 file is decoded with libvpx-vp9 (vp9_decoder_args). None when no frame decodes."""
172
+ head = [require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin"] + vp9_decoder_args(codec)
173
+ return frame_means(head, path, "format=rgba,alphaextract")
174
+
175
+
176
+ def alpha_compare(written, source) -> Dict[str, object]:
177
+ """The written file's alpha against the source's. With the same number of frames, frame by
178
+ frame (frame i against frame i, each within ALPHA_TOLERANCE): an aggregate let a loss confined
179
+ to a few frames through (one of 200 frames turned opaque moves the mean by ~1). With a
180
+ different count (a variable-rate source conformed to a constant rate repeats or drops frames,
181
+ so indices no longer pair), the mean and the most transparent frame, and `paired: false`
182
+ says so. {ok, paired, worst_delta, worst_frame}."""
183
+ if written is None or source is None:
184
+ return {"ok": False, "paired": None, "worst_delta": None, "worst_frame": None}
185
+ w, s = written.get("per_frame") or [], source.get("per_frame") or []
186
+ if w and len(w) == len(s):
187
+ deltas = [abs(a - b) for a, b in zip(w, s)]
188
+ worst = max(range(len(deltas)), key=deltas.__getitem__)
189
+ return {"ok": deltas[worst] <= ALPHA_TOLERANCE, "paired": True, "worst_delta": round(deltas[worst], 2),
190
+ "worst_frame": worst}
191
+ delta = max(abs(written["mean"] - source["mean"]), abs(written["min"] - source["min"]))
192
+ return {"ok": delta <= ALPHA_TOLERANCE, "paired": False, "worst_delta": round(delta, 2), "worst_frame": None}
193
+
194
+
195
+ def rounded(st) -> "Dict[str, float] | None":
196
+ return None if st is None else {"mean": round(st["mean"], 2), "min": round(st["min"], 2), "frames": st["frames"]}
197
+
198
+
199
+ # source_alpha()'s answer for a source that stores an alpha plane whose alpha could not be read:
200
+ # not "opaque" (that would let an output that dropped it pass), so every check on it fails
201
+ UNMEASURED: Dict[str, Any] = {"unmeasured": True}
202
+
203
+
204
+ def _measured(st):
205
+ return None if st is None or st.get("unmeasured") else st
206
+
207
+
208
+ def uses_alpha(st) -> bool:
209
+ """True when a measured clip has a frame that is not fully opaque (its alpha is used), or when
210
+ a clip that stores an alpha plane could not be measured (UNMEASURED)."""
211
+ return st is not None and (bool(st.get("unmeasured")) or st["min"] < OPAQUE)
212
+
213
+
214
+ # --- the flags -----------------------------------------------------------------------------------
215
+
216
+ def add_alpha_args(ap, transparent: bool = False) -> None:
217
+ """--keep-alpha / --drop-alpha (or background.py's --transparent), --alpha-codec, --alpha-mode."""
218
+ g = ap.add_argument_group("alpha")
219
+ if transparent:
220
+ g.add_argument("--transparent", action="store_true",
221
+ help="write a fully transparent canvas (alpha 0 in every pixel) in an alpha line (--alpha-codec), "
222
+ "a base layer for graphics.py / overlay.py --keep-alpha; --color/--gradient do not apply")
223
+ else:
224
+ g.add_argument("--keep-alpha", action="store_true",
225
+ help="keep the source's alpha: write the output in an alpha line (--alpha-codec, default "
226
+ "prores4444; needs a .mov/.mkv, or .webm for vp9) with the source's colour tags kept, and "
227
+ "check the alpha after (the `alpha` verification step). Refused on a source without an alpha plane")
228
+ g.add_argument("--drop-alpha", action="store_true",
229
+ help="the source has alpha and an opaque output is wanted: the alpha is dropped on purpose and a note "
230
+ "says so. Without it (or --keep-alpha) an output that loses a used alpha fails the `alpha` step")
231
+ g.add_argument("--alpha-codec", choices=sorted(ALPHA_CODECS), default=None,
232
+ help="the alpha line: prores4444 (default; ProRes 4444, 16-bit alpha), qtrle (QuickTime Animation, "
233
+ ".mov), png (PNG frames, .mov/.mkv), vp9 (VP9 with alpha, .webm/.mkv)")
234
+ g.add_argument("--alpha-mode", choices=list(ALPHA_MODES), default=None,
235
+ help="how the colour is written beside the alpha: straight (default, as composited) or premultiplied "
236
+ "by the alpha; reported as alpha_mode")
237
+
238
+
239
+ def alpha_requested(args) -> bool:
240
+ return bool(getattr(args, "keep_alpha", False) or getattr(args, "transparent", False))
241
+
242
+
243
+ def check_alpha_args(args, output: Optional[str]) -> Optional[str]:
244
+ """Validates the alpha flags against each other and the output name; returns the alpha codec
245
+ (None when no alpha line was asked for). Sets STATE.alpha_line so the colour helpers keep the
246
+ source's tags (decision.keeps_source_tags)."""
247
+ from _common.emit import die # emit imports runner; imported here to keep this module light
248
+ flag = "--transparent" if hasattr(args, "transparent") else "--keep-alpha"
249
+ if not alpha_requested(args):
250
+ if args.alpha_codec or args.alpha_mode:
251
+ die(f"--alpha-codec and --alpha-mode apply with {flag}", kind="input")
252
+ return None
253
+ if getattr(args, "drop_alpha", False):
254
+ die("--keep-alpha and --drop-alpha ask for opposite things: give one", kind="input")
255
+ if STATE.codec:
256
+ die(f"{flag} writes its own alpha line (--alpha-codec); --codec {STATE.codec} cannot carry an alpha channel",
257
+ kind="input", hint=f"drop --codec, or drop {flag}")
258
+ codec = args.alpha_codec or ALPHA_CODEC_DEFAULT
259
+ line = ALPHA_CODECS[codec]
260
+ if output is not None:
261
+ ext = os.path.splitext(output)[1].lower()
262
+ if ext not in line["ext"]:
263
+ die(f"{flag} --alpha-codec {codec} needs a {' or '.join(line['ext'])} output; {output} cannot hold it",
264
+ kind="input", hint=f"pass -o NAME{line['ext'][0]}")
265
+ encoders = ffmpeg_encoders()
266
+ if encoders and line["encoder"] not in encoders:
267
+ die(f"--alpha-codec {codec} needs the {line['encoder']} encoder and this ffmpeg build has none",
268
+ kind="missing_tool", error_extra={"reason": "encoder_missing", "details": {"name": line["encoder"]}},
269
+ hint="python3 scripts/_contract.py doctor lists the encoders this build has; --alpha-codec prores4444 or png "
270
+ "need only FFmpeg's own encoders")
271
+ STATE.alpha_line = codec
272
+ return codec
273
+
274
+
275
+ def default_ext(codec: str) -> str:
276
+ return ALPHA_CODECS[codec]["ext"][0].lstrip(".")
277
+
278
+
279
+ def video_line(codec: str) -> List[str]:
280
+ return list(ALPHA_CODECS[codec]["video"])
281
+
282
+
283
+ def audio_line(codec: str) -> List[str]:
284
+ return list(ALPHA_CODECS[codec]["audio"])
285
+
286
+
287
+ _TAG_KEYS = (("colorspace", "color_space", "-colorspace"), ("color_primaries", "color_primaries", "-color_primaries"),
288
+ ("color_trc", "color_transfer", "-color_trc"))
289
+ # swscale's name for a tagged SDR matrix (scale=in_color_matrix / out_color_matrix)
290
+ _SWS_MATRIX = {"bt709": "bt709", "smpte170m": "bt601", "bt470bg": "bt601", "smpte240m": "smpte240m", "fcc": "fcc"}
291
+
292
+
293
+ def rgb_to_bt709_line(meta: Optional[Dict[str, Any]], codec: Optional[str] = None) -> bool:
294
+ """True when the alpha line being written (`codec`, default STATE.alpha_line) stores YUV
295
+ (ProRes 4444, VP9) and the source `meta` probes is RGB (qtrle, PNG in .mov/.mkv, an image).
296
+
297
+ An RGB source has no matrix for the line to keep, and the one FFmpeg picks where the graph
298
+ first needs YUV is BT.601, written with no tag on 6.1: a 1280x720 ProRes 4444 master of a
299
+ qtrle clip was read as BT.709 by every player and showed 30C050 as 26AB4D (#496). Such a
300
+ source is converted to BT.709 (source_format(); color.py's grade legs), RGB layers are
301
+ converted to match (decision.rgb_chain_to_bt709) and the line is tagged BT.709 (_source_tags),
302
+ as the H.264 line does for an RGB source. An RGB line (qtrle, PNG) is left as it was; an
303
+ HDR/BT.2020 source is not converted to BT.709 here (FFmpeg's own conversion makes its YUV, as
304
+ before)."""
305
+ codec = codec or STATE.alpha_line
306
+ v = (meta or {}).get("video") or {}
307
+ return bool(codec) and ALPHA_CODECS[codec]["pix_fmt"].startswith("yuv") and is_rgb(meta) and not v.get("bt2020_or_hdr")
308
+
309
+
310
+ def hdr_rgb_line(meta: Optional[Dict[str, Any]]) -> Optional[str]:
311
+ """The conversion of an HDR / BT.2020 RGB source on a YUV alpha line (#559): the matrix the line
312
+ tags, as the 10-bit line of a source without alpha makes it (hdr_rgb_matrix_filter), or None."""
313
+ codec = STATE.alpha_line
314
+ return hdr_rgb_matrix_filter(meta, alpha=True) if codec and ALPHA_CODECS[codec]["pix_fmt"].startswith("yuv") else None
315
+
316
+
317
+ def source_format(meta: Optional[Dict[str, Any]]) -> str:
318
+ """The filter that starts a compositing graph on an alpha line: the source at 4:4:4 with its
319
+ alpha plane. An RGB source on a YUV line gets there by an explicit BT.709 conversion
320
+ (rgb_to_bt709_line); a palette is expanded first, because swscale turns one into YUV with
321
+ BT.601 whatever matrix is asked for. Every other source: `format=yuva444p`, as before."""
322
+ if rgb_to_bt709_line(meta):
323
+ pal = ((meta or {}).get("video") or {}).get("pix_fmt") == "pal8"
324
+ return ("format=rgba," if pal else "") + rgb_to_bt709_filter("yuva444p")
325
+ return hdr_rgb_line(meta) or "format=yuva444p"
326
+
327
+
328
+ def rgb_line(codec: Optional[str] = None) -> bool:
329
+ """True when the alpha line being written stores RGB (qtrle, PNG)."""
330
+ codec = codec or STATE.alpha_line
331
+ return bool(codec) and not ALPHA_CODECS[codec]["pix_fmt"].startswith("yuv")
332
+
333
+
334
+ def matrix_label(meta: Optional[Dict[str, Any]]) -> str:
335
+ """",setparams=colorspace=<the source's matrix>" to end a YUV chain with that an RGB line
336
+ (qtrle, PNG) converts, or "" (a YUV line, an untagged or RGB source).
337
+
338
+ finish_chain() labels the frames after the last filter of the graph, but FFmpeg places the
339
+ conversion to an RGB line where the formats first differ, which in color.py is in front of
340
+ `alphamerge` and so in front of that label: the graded YUV of a BT.709-tagged source reached
341
+ it untagged (6.1) or carrying the grade legs' working matrix (7.1+) and was read as BT.601
342
+ (30C050 written as 3CD753). Labelled here, the conversion reads the matrix the samples are in."""
343
+ if not rgb_line() or is_rgb(meta):
344
+ return ""
345
+ space = [val for p, val, _ in _source_tags(meta, "setparams") if p == "colorspace"]
346
+ return f",setparams=colorspace={space[0]}" if space else ""
347
+
348
+
349
+ def _source_tags(meta: Optional[Dict[str, Any]], dest: str = "option") -> List[tuple]:
350
+ """(setparams name, value, output option) per source tag that is passed on, the value spelled
351
+ for `dest` (carried_tag: an RGB source's `gbr` is left out, #454). An RGB source on a YUV line
352
+ (rgb_to_bt709_line) is BT.709 YUV by then and says so: matrix bt709, and bt709 for a primaries
353
+ or transfer tag the source does not carry (the H.264 line's reading of an untagged picture)."""
354
+ v = (meta or {}).get("video") or {}
355
+ to_709 = rgb_to_bt709_line(meta)
356
+ # the matrix is the one the conversion used, whatever the RGB source's own tag says (a qtrle
357
+ # clip retagged smpte170m would label its BT.709 samples BT.601, an HDR one's `gbr` would be
358
+ # no tag); primaries and transfer are not converted, so the source's own are kept when it has them
359
+ matrix = "bt709" if to_709 else hdr_rgb_line(meta) and hdr_line_matrix(v)
360
+ tags = [(param, matrix if matrix and param == "colorspace"
361
+ else carried_tag(param, v.get(key), dest) or ("bt709" if to_709 else None), flag)
362
+ for param, key, flag in _TAG_KEYS]
363
+ return [t for t in tags if t[1]]
364
+
365
+
366
+ def finish_chain(codec: str, mode: Optional[str], meta: Optional[Dict[str, Any]] = None, *, wide: bool = False) -> str:
367
+ """The end of a filter chain that hands an alpha picture to the line: premultiplied colour
368
+ when asked, the source's colour tags put back on the frames (`setparams`: a grade's RGB legs
369
+ and an RGB layer's conversion relabel them, BT.601 or unknown), then the line's own pixel
370
+ format (so no later conversion can drop the plane)."""
371
+ tags = _source_tags(meta, "setparams")
372
+ label = ("setparams=" + ":".join(f"{p}={val}" for p, val, _ in tags) + ",") if tags else ""
373
+ pix = ALPHA_CODECS[codec]["pix_fmt"]
374
+ # premultiplied colour is colour x alpha in RGB: multiplied there (a YUV premultiply scales the
375
+ # limited-range offsets too), after the tags are back so both conversions use the same matrix
376
+ rgb = "gbrap16le" if wide else "gbrap"
377
+ pre = f"format={rgb},premultiply=inplace=1," if mode == "premultiplied" else ""
378
+ matrix = _SWS_MATRIX.get(next((val for p, val, _ in tags if p == "colorspace"), None))
379
+ if pre and matrix and pix.startswith("yuv"):
380
+ # ... which 6.1 does not do by itself on a tagged YUV line: the way to RGB is placed in
381
+ # front of color.py's alphamerge (so in front of the label, and reads BT.601) and the way
382
+ # back takes swscale's BT.601 default whatever the frames say, so an opaque 30C050 of a
383
+ # BT.709 line came back 3CD753 (color.py) or 25AC4E (overlay.py). Both legs name the matrix.
384
+ pre = f"scale=in_color_matrix={matrix},format={rgb},premultiply=inplace=1,scale=out_color_matrix={matrix},"
385
+ return label + pre + f"format={pix}"
386
+
387
+
388
+ def unpremultiply_leg(meta: Optional[Dict[str, Any]]) -> str:
389
+ # FFmpeg 9 skips division when the negotiated source mode is already straight.
390
+ mode = "setparams=alpha_mode=premultiplied," if _runner.ffmpeg_version() >= (9, 0) else ""
391
+ # Float RGB avoids rounding before the division. Use the same matrix on both conversions.
392
+ v = (meta or {}).get("video") or {}
393
+ matrix = None if is_rgb(meta) else _SWS_MATRIX.get(v.get("color_space"))
394
+ return ((f"scale=in_color_matrix={matrix}," if matrix else "") + f"format=gbrapf32le,{mode}unpremultiply=inplace=1,"
395
+ + (f"scale=out_color_matrix={matrix}," if matrix else "") + f"format={v.get('pix_fmt')},")
396
+
397
+
398
+ def tag_args(meta: Optional[Dict[str, Any]]) -> List[str]:
399
+ """The source's colour tags as output options, so the written stream says what the frames do
400
+ (an alpha line keeps the source's tags, as --codec prores does; an RGB source on a YUV line is
401
+ tagged the BT.709 it was converted to)."""
402
+ out: List[str] = []
403
+ for _p, val, flag in _source_tags(meta):
404
+ out += [flag, val]
405
+ return out
406
+
407
+
408
+ def written_line(output_meta: Dict[str, Any], output: str) -> Dict[str, Any]:
409
+ """What the written stream is: {codec, pix_fmt, alpha_plane} (alpha_plane: the stream stores one)."""
410
+ v = (output_meta or {}).get("video") or {}
411
+ return {"codec": v.get("codec"), "pix_fmt": v.get("pix_fmt"), "alpha_plane": has_alpha_plane(output_meta, output)}
412
+
413
+
414
+ def kept_step(output: str, output_meta: Dict[str, Any], source: "Dict[str, object] | None", *,
415
+ composite: bool, provenance: str = "input_premeasurement") -> Dict[str, Any]:
416
+ """The `alpha` verification step of a --keep-alpha / --transparent run.
417
+
418
+ `composite` False (color.py, background.py --transparent against an all-zero source): the
419
+ alpha is not touched by the operation, so the written alpha must equal the source's frame by
420
+ frame (alpha_compare). `composite` True (graphics.py, overlay.py): layers drawn over the
421
+ picture add coverage, so the written alpha may only be at or above the source's in every
422
+ frame, and must not have gone opaque in every frame the source was transparent in (what an
423
+ alpha dropped on the way reads as). In both, the written stream must store an alpha plane."""
424
+ unmeasured = bool(source and source.get("unmeasured"))
425
+ source = _measured(source)
426
+ line = written_line(output_meta, output)
427
+ written = alpha_stats(output, line["codec"])
428
+ step: Dict[str, Any] = {"step": "alpha", "property": "alpha_mean", "tolerance": ALPHA_TOLERANCE,
429
+ "expected": None if source is None else round(source["mean"], 2),
430
+ "measured": None if written is None else round(written["mean"], 2),
431
+ "frames": {"expected": rounded(source), "measured": rounded(written)},
432
+ "written": line, "provenance": provenance}
433
+ if unmeasured:
434
+ step["reason"] = "source_alpha_unmeasured"
435
+ if not composite:
436
+ cmp = alpha_compare(written, source)
437
+ step.update(comparison=cmp, ok=bool(cmp["ok"] and line["alpha_plane"]))
438
+ return step
439
+ step["property"] = "alpha_at_least_source"
440
+ if written is None or source is None:
441
+ step.update(ok=False, comparison={"ok": False, "paired": None, "worst_delta": None, "worst_frame": None})
442
+ return step
443
+ w, s = written["per_frame"], source["per_frame"]
444
+ paired = len(w) == len(s)
445
+ if paired:
446
+ deficits = [b - a for a, b in zip(w, s)]
447
+ worst = max(range(len(deficits)), key=deficits.__getitem__)
448
+ below = deficits[worst] > ALPHA_TOLERANCE
449
+ opaque_where_transparent = all(a >= OPAQUE for a, b in zip(w, s) if b < OPAQUE) and any(b < OPAQUE for b in s)
450
+ cmp = {"paired": True, "worst_delta": round(max(deficits[worst], 0.0), 2), "worst_frame": worst}
451
+ else:
452
+ below = written["min"] < source["min"] - ALPHA_TOLERANCE
453
+ opaque_where_transparent = written["min"] >= OPAQUE and source["min"] < OPAQUE
454
+ cmp = {"paired": False, "worst_delta": round(max(source["min"] - written["min"], 0.0), 2), "worst_frame": None}
455
+ ok = line["alpha_plane"] and not below and not opaque_where_transparent
456
+ cmp["ok"] = ok
457
+ if opaque_where_transparent:
458
+ step["reason"] = "opaque_everywhere"
459
+ elif below:
460
+ step["reason"] = "alpha_below_source"
461
+ elif not line["alpha_plane"]:
462
+ step["reason"] = "no_alpha_plane"
463
+ step.update(comparison=cmp, ok=ok)
464
+ return step
465
+
466
+
467
+ def lost_step(output: str, output_meta: Dict[str, Any], source: "Dict[str, object] | None") -> Dict[str, Any]:
468
+ """The `alpha` step of a run without --keep-alpha on a source whose alpha is used: the output
469
+ stores no alpha plane (every re-encoding line but the alpha ones is opaque), so it fails, with
470
+ the reason and the flag that keeps it. Measured, not assumed: a written file that does carry
471
+ the source's alpha passes. A source whose alpha could not be measured (UNMEASURED) fails
472
+ with reason source_alpha_unmeasured: nothing shows the output kept what it had."""
473
+ unmeasured = bool(source and source.get("unmeasured"))
474
+ source = _measured(source)
475
+ line = written_line(output_meta, output)
476
+ written = alpha_stats(output, line["codec"]) if line["alpha_plane"] else None
477
+ cmp = alpha_compare(written, source) if written is not None else {"ok": False, "paired": None,
478
+ "worst_delta": None, "worst_frame": None}
479
+ step: Dict[str, Any] = {"step": "alpha", "property": "alpha_mean", "ok": bool(cmp["ok"]), "comparison": cmp,
480
+ "tolerance": ALPHA_TOLERANCE,
481
+ "expected": None if source is None else round(source["mean"], 2),
482
+ "measured": round(written["mean"], 2) if written is not None else 255.0,
483
+ "frames": {"expected": rounded(source), "measured": rounded(written)},
484
+ "written": line, "provenance": "input_premeasurement"}
485
+ if not step["ok"]:
486
+ step.update(reason="source_alpha_unmeasured" if unmeasured and line["alpha_plane"] else "alpha_dropped",
487
+ attribution="artifact",
488
+ hint="pass --keep-alpha to write an alpha line, or --drop-alpha when an opaque output is wanted")
489
+ return step
490
+
491
+
492
+ def source_alpha(args, meta: Dict[str, Any], path: str) -> "Dict[str, object] | None":
493
+ """The source's alpha measured once, before the run, when it can matter: the source stores an
494
+ alpha plane and this is not a dry run. Refuses --keep-alpha on a source without one (nothing to
495
+ keep). Returns None when there is nothing to measure."""
496
+ from _common.emit import die
497
+ if STATE.dry_run and _runner.dry_run_input_pending(path):
498
+ # a planned input an earlier step will write (a --transparent canvas in a recipe): there is
499
+ # nothing to probe yet, so the alpha checks wait for the real run
500
+ return None
501
+ plane = has_alpha_plane(meta, path)
502
+ codec = ((meta or {}).get("video") or {}).get("codec")
503
+ if plane and codec == "vp9" and not libvpx_vp9_decoder():
504
+ _no_vp9_decoder(path)
505
+ if getattr(args, "keep_alpha", False) and not plane:
506
+ die(f"--keep-alpha keeps the source's alpha channel and {path} has none "
507
+ f"({((meta or {}).get('video') or {}).get('pix_fmt')}, fully opaque)", kind="input",
508
+ hint="background.py --transparent makes a transparent canvas to draw on; drop --keep-alpha for an opaque output")
509
+ if not plane or STATE.dry_run:
510
+ return None
511
+ return alpha_stats(path, codec) or UNMEASURED
512
+
513
+
514
+ def decoder_args_for(meta: Dict[str, Any], path: str) -> List[str]:
515
+ """The input options a source with alpha needs to arrive with it: libvpx-vp9 for a VP9 stream
516
+ tagged with an alpha layer (the native decoder drops it). [] for anything else."""
517
+ v = (meta or {}).get("video") or {}
518
+ if v.get("codec") != "vp9" or not vp9_alpha_tagged(path):
519
+ return []
520
+ if not libvpx_vp9_decoder():
521
+ # FFmpeg's own decoder would read it without the alpha, and a layer would cover what is
522
+ # under it: refused, not composited wrong
523
+ _no_vp9_decoder(path)
524
+ return ["-c:v", "libvpx-vp9"]
525
+
526
+
527
+ def _no_vp9_decoder(path: str) -> None:
528
+ from _common.emit import die
529
+ die(f"{path} is VP9 with an alpha layer, and this ffmpeg build has no libvpx-vp9 decoder to read it "
530
+ "(FFmpeg's own VP9 decoder drops the alpha)", kind="missing_tool",
531
+ error_extra={"reason": "decoder_missing", "details": {"name": "libvpx-vp9"}},
532
+ hint="use an ffmpeg built with libvpx, or a ProRes 4444 / qtrle / PNG source")
533
+
534
+
535
+ def report(args, codec: Optional[str], src: "Dict[str, object] | None", output: Optional[str],
536
+ extra: Dict[str, Any], composite: bool, provenance: str = "input_premeasurement") -> None:
537
+ """Adds the alpha fields and the `alpha` step to a result's `extra` (after the write)."""
538
+ from _common.emit import note, warn
539
+ from _common.probe import probe
540
+ if codec:
541
+ extra.update(alpha_mode=args.alpha_mode or "straight", alpha_codec=codec)
542
+ source_mode = {"source_alpha_mode": args.source_alpha_mode} if getattr(args, "source_alpha_mode", None) else {}
543
+ extra.update(source_mode) # color.py: the mode the grade read the colour in, on a dry run too
544
+ if output and not STATE.dry_run:
545
+ step = kept_step(output, probe(output, role="output"), src, composite=composite, provenance=provenance)
546
+ step.update(source_mode)
547
+ extra.setdefault("verification", []).append(step)
548
+ return
549
+ if not uses_alpha(src) or not output or STATE.dry_run:
550
+ return
551
+ if getattr(args, "drop_alpha", False):
552
+ note("the source's alpha channel was dropped (--drop-alpha): the output is opaque")
553
+ extra["alpha_dropped"] = True
554
+ return
555
+ step = lost_step(output, probe(output, role="output"), src)
556
+ extra.setdefault("verification", []).append(step)
557
+ if not step["ok"]:
558
+ extra["alpha_dropped"] = True
559
+ warn("the source has an alpha channel and this output does not keep it: pass --keep-alpha to keep it, "
560
+ "or --drop-alpha when an opaque output is wanted", "alpha_dropped")