@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,540 @@
1
+ """Colour: the bt709 tagging arguments and the HDR-to-SDR conversion path, plus colour-token
2
+ validation for the tools that take a `--color`.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
8
+ from _common.emit import die
9
+ from _common.runner import ffmpeg_version
10
+
11
+
12
+ def bt709_tag_args(encoder: str = "libx264") -> List[str]:
13
+ """Tag an SDR output as BT.709 without touching its pixels.
14
+
15
+ Up to FFmpeg 7.0 the output options -colorspace/-color_primaries/-color_trc were tags only.
16
+ 7.1 added colourspace negotiation to libavfilter and feeds those options into the graph's
17
+ output constraints, so on a source whose bitstream carries no colour tags (test sources,
18
+ screen recordings, many cameras) the CLI now auto-inserts a *real* matrix conversion (its
19
+ guess for "unknown" is bt601) into every SDR re-encode: a --lut-strength 0 no-op grade
20
+ came back ~24 dB PSNR from its source on 7.1. From 7.1 on, the tags therefore go through
21
+ the encoder's own VUI parameters instead, which libavfilter never sees.
22
+
23
+ These tags are a label on every FFmpeg version: they never convert the pixels. A source
24
+ whose matrix is not BT.709 (a BT.601 `smpte170m`/`bt470bg` file) gets its pixels converted
25
+ separately, by bt709_matrix_filter() in the filter graph; through 2.10.0 nothing did, and
26
+ such a source came out labelled BT.709 over BT.601 pixels (measured on 6.1: 48.5 dB YUV
27
+ PSNR against the source, i.e. untouched, tagged bt709/bt709/bt709).
28
+ """
29
+ if ffmpeg_version() < (7, 1):
30
+ return ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"]
31
+ if encoder == "libx265":
32
+ return ["-x265-params", "colorprim=bt709:transfer=bt709:colormatrix=bt709"]
33
+ return ["-x264-params", "colorprim=bt709:transfer=bt709:colormatrix=bt709"]
34
+
35
+
36
+ def _sdr_bt709(encoder: str) -> "Tuple[str, List[str]]":
37
+ """BT.709 SDR tags for `encoder` as (encoder-params string, extra output options): the two
38
+ spellings bt709_tag_args() picks between, split so a caller that already builds an encoder
39
+ params string can merge them (the option given twice keeps only the last)."""
40
+ if ffmpeg_version() < (7, 1):
41
+ return "", ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"]
42
+ if encoder == "libsvtav1":
43
+ return "color-primaries=1:transfer-characteristics=1:matrix-coefficients=1", []
44
+ if encoder == "libaom-av1":
45
+ return "", [] # no VUI params option; an untagged 8-bit stream reads as BT.709 everywhere
46
+ return "colorprim=bt709:transfer=bt709:colormatrix=bt709", []
47
+
48
+
49
+ # The SDR matrices (ffprobe's names) whose pixels an output tagged BT.709 has to convert:
50
+ # BT.601 (`smpte170m` 525-line, `bt470bg` 625-line: the same coefficients) and the two rare
51
+ # pre-BT.709 ones the colorspace filter also reads. bt2020nc/c sources take the HDR/BT.2020 path.
52
+ NON_BT709_MATRICES = ("smpte170m", "bt470bg", "fcc", "smpte240m")
53
+
54
+ # RGB pictures (ffprobe's pix_fmt names: PNG rgb24/rgba/pal8/rgb48be, qtrle, gbrp...). Their
55
+ # conversion to YUV is wherever the graph first needs YUV, and FFmpeg's default for it is BT.601
56
+ # (5.1, 6.1, 7.0; 7.1+ follows the link's tag, unspecified = BT.601). Gray has no matrix.
57
+ _RGB_PIX_FMT_RE = re.compile(r"^(?:rgb|bgr|argb|abgr|0rgb|0bgr|gbr|x2rgb|x2bgr|pal8)")
58
+
59
+
60
+ # A probed colour tag passed back to FFmpeg (#454). ffprobe prints av_color_*_name(), which is
61
+ # also the setparams filter's table; the output options -colorspace/-color_primaries/-color_trc
62
+ # parse an older one that differs on three names (6.1, measured): -colorspace refuses `gbr` (its
63
+ # name is `rgb`) and -color_trc refuses `bt470m` and `bt470bg` (its names: `gamma22`, `gamma28`).
64
+ # `gbr` is not carried over at all: it says the stored samples are RGB, which is the pixel
65
+ # format's to say (the PNG encoder tags it itself), and a tool that converts the picture to YUV on
66
+ # the way (a grade's legs, a 4:4:4 alpha line) would label YUV samples as RGB with it.
67
+ _TAG_KIND = {"-colorspace": "colorspace", "-color_primaries": "color_primaries", "-color_trc": "color_trc"}
68
+ _OPTION_NAMES = {"color_trc": {"bt470m": "gamma22", "bt470bg": "gamma28"}}
69
+
70
+
71
+ def carried_tag(kind: str, name: Optional[str], dest: str = "option") -> Optional[str]:
72
+ """The probed tag `name` of `kind` (colorspace, color_primaries, color_trc) spelled the way
73
+ `dest` ("option": -colorspace & co; "setparams") accepts it, or None when it is not to be
74
+ passed on: unknown, unspecified, reserved, or the RGB `gbr`/`rgb`."""
75
+ if not name or name in ("unknown", "unspecified", "reserved") or (kind == "colorspace" and name in ("gbr", "rgb")):
76
+ return None
77
+ return _OPTION_NAMES.get(kind, {}).get(name, name) if dest == "option" else name
78
+
79
+
80
+ def carried_tag_args(pairs: Sequence[Tuple[str, Optional[str]]]) -> List[str]:
81
+ """[flag, value, ...] for each (flag, probed name) whose tag carried_tag() passes on."""
82
+ out: List[str] = []
83
+ for flag, name in pairs:
84
+ value = carried_tag(_TAG_KIND.get(flag, flag.lstrip("-")), name)
85
+ if value:
86
+ out += [flag, value]
87
+ return out
88
+
89
+
90
+ def rgb_to_bt709_filter(pix_fmt: str = "yuv444p") -> str:
91
+ """An RGB picture converted to BT.709 limited-range YUV right here, in `pix_fmt`, so no later
92
+ conversion (an auto-inserted one, with FFmpeg's BT.601 default) decides the matrix. 4:4:4 by
93
+ default: the tool's own scaling and the encoder's 4:2:0 come after, as they did on the RGB."""
94
+ return f"scale=out_color_matrix=bt709:out_range=tv,format={pix_fmt}"
95
+
96
+
97
+ def is_rgb(meta: Optional[Dict[str, Any]]) -> bool:
98
+ """True when the probed picture is RGB (a PNG/still, a qtrle/png-in-mov clip, an image sequence)."""
99
+ return bool(_RGB_PIX_FMT_RE.match(str(((meta or {}).get("video") or {}).get("pix_fmt") or "")))
100
+
101
+
102
+ # The matrices (ffprobe's names) swscale can be told to make YUV with, by its own name for each
103
+ # (scale's out_color_matrix). A BT.2020/HDR line tags one of these on an RGB source (#544).
104
+ _SWS_OUT_MATRIX = {"bt2020nc": "bt2020", "bt709": "bt709", "smpte170m": "bt601", "bt470bg": "bt601",
105
+ "fcc": "fcc", "smpte240m": "smpte240m"}
106
+
107
+
108
+ def hdr_line_matrix(v: Optional[Dict[str, Any]]) -> str:
109
+ """The matrix tag (ffprobe's name) a 10-bit line that keeps a BT.2020 / HDR source's colour
110
+ writes for the probed video `v`: a YUV source's own, or bt2020nc when it has none, as always.
111
+
112
+ An RGB source has no matrix: its tag is `gbr` (FFV1, PNG, qtrle, libx264rgb and most RGB
113
+ codecs write it) or nothing, and the YUV the line stores is made by a conversion. Through
114
+ 3.10.0 the line passed the tag on (`-colorspace gbr`, which no encoder parses: every re-encode
115
+ of such a source failed inside ffmpeg) or wrote bt2020nc over FFmpeg's default conversion,
116
+ BT.601 (#544). For an RGB source the tag is the matrix hdr_rgb_matrix_filter() converts with:
117
+ the source's own when it names one swscale can make (a mislabelled RGB file, whose frames
118
+ FFmpeg 6.1 already converted by that tag), else bt2020nc."""
119
+ v = v or {}
120
+ cs = v.get("color_space")
121
+ if _RGB_PIX_FMT_RE.match(str(v.get("pix_fmt") or "")):
122
+ return cs if cs in _SWS_OUT_MATRIX else "bt2020nc"
123
+ return cs or "bt2020nc"
124
+
125
+
126
+ def hdr_rgb_matrix_filter(meta: Optional[Dict[str, Any]], line_meta: Optional[Dict[str, Any]] = None, alpha: bool = False) -> Optional[str]:
127
+ """For an RGB source that probes BT.2020 or HDR, written on a line that keeps that colour
128
+ (video_args' Main10 / 10-bit lines; `line_meta`: the probe the line was chosen for when it is
129
+ another picture's, as in a join; `alpha`: an alpha line, which keeps the plane): the filter that makes its YUV with the matrix the line tags
130
+ (hdr_line_matrix), limited range, 4:4:4 at the line's 10 bits, so no later conversion (an
131
+ auto-inserted one, with FFmpeg's BT.601 default) decides the matrix. None for every other
132
+ source, and when the line's matrix is one swscale cannot be told to make (bt2020c, ICtCp).
133
+
134
+ Only the matrix is named. Primaries and transfer are the source's and stay as they are (the
135
+ line tags them), so the picture is the source's RGB read back by the output's own tags
136
+ (measured on FFmpeg 6.1.1: C03028 came back 196/52/35 before, 192/48/40 after)."""
137
+ v = (meta or {}).get("video") or {}
138
+ if not v.get("bt2020_or_hdr") or not is_rgb(meta):
139
+ return None
140
+ line_v = v if line_meta is None else (line_meta.get("video") or {})
141
+ if not line_v.get("bt2020_or_hdr"):
142
+ return None
143
+ matrix = _SWS_OUT_MATRIX.get(hdr_line_matrix(line_v))
144
+ if matrix is None:
145
+ return None
146
+ # a palette is turned into YUV with fixed BT.601 coefficients whatever out_color_matrix says
147
+ return ("format=rgb24," if v.get("pix_fmt") == "pal8" else "") + f"scale=out_color_matrix={matrix}:out_range=tv,format=yuv{'a' * alpha}444p10le"
148
+
149
+
150
+ # An odd-sized BT.601 source is padded to even for the colorspace filter and cropped back to its
151
+ # own size after it (bt709_matrix_filter): both wrap the conversion in the one -vf the merge finds.
152
+ _EVEN_PAD = "pad=ceil(iw/2)*2:ceil(ih/2)*2:0:0,"
153
+ _BT709_RELABEL = "setparams=color_primaries=bt709:color_trc=bt709"
154
+ _MATRIX_FILTER_RE = re.compile(r"^(?:(?:(?:%s)?colorspace=ispace=(?:%s):iprimaries=bt709:itrc=bt709:space=bt709:primaries=bt709:trc=bt709(?:,crop=iw-[01]:ih-[01]:0:0:exact=1)?|(?:format=rgb24,)?%s"
155
+ r"|(?:format=rgb24,)?scale=out_color_matrix=(?:%s):out_range=tv,format=yuva?444p10le)(?:,%s)?|%s)$"
156
+ % (re.escape(_EVEN_PAD), "|".join(NON_BT709_MATRICES), re.escape(rgb_to_bt709_filter()),
157
+ "|".join(sorted(set(_SWS_OUT_MATRIX.values()))), re.escape(_BT709_RELABEL), re.escape(_BT709_RELABEL)))
158
+ # [N:v], [N:v:0] and [N:V:0] (PROBED_VIDEO: the motion picture, not an attached cover)
159
+ _INPUT_VIDEO_REF = re.compile(r"\[(\d+):[vV](?::0)?\]")
160
+
161
+
162
+ def bt709_matrix_filter(meta: Optional[Dict[str, Any]]) -> Optional[str]:
163
+ """The filter that turns the probed source's pixels into BT.709 ones before an output is
164
+ tagged BT.709, or None when nothing needs converting: a source tagged with a non-BT.709 matrix
165
+ (NON_BT709_MATRICES) or an RGB one. An untagged or BT.709 source, an HDR/BT.2020 YUV one (it
166
+ keeps its own tags, or color.py --to-sdr converts it) and a missing probe get None, so their
167
+ commands are what they were.
168
+
169
+ The matrix is converted and nothing else: primaries and transfer are passed through
170
+ (iprimaries/itrc = the output's), so the picture a player that decodes with the source's
171
+ matrix showed is the picture the BT.709 output shows. The `colorspace` filter is in every
172
+ FFmpeg build (no zscale needed) and takes explicit input properties, so the conversion does
173
+ not depend on how a build reads or negotiates the frames' own tags. The range is left as it is.
174
+
175
+ An RGB source (is_rgb: a PNG/still, an image sequence, a qtrle clip) has no matrix of its own
176
+ but gets one where the graph first needs YUV, and FFmpeg's default there is BT.601: through
177
+ 2.10.1 such a source came out labelled BT.709 over BT.601-encoded pixels (pure red decoded as
178
+ (255,24,0), pure green as (0,216,0), on 5.1.1 to 8.1). It is converted to BT.709 YUV here
179
+ (rgb_to_bt709_filter), an HDR or BT.2020 RGB one too (#559): the tag names the matrix whatever
180
+ the primaries and transfer are (the HDR line's own conversion is hdr_rgb_matrix_filter). A JPEG
181
+ (yuvj, tagged bt470bg) is a BT.601 source like any other."""
182
+ v = (meta or {}).get("video") or {}
183
+ matrix = v.get("color_space")
184
+ if v.get("bt2020_or_hdr") and not is_rgb(meta):
185
+ return None
186
+ if is_rgb(meta):
187
+ # a palette is turned into YUV with fixed BT.601 coefficients whatever out_color_matrix
188
+ # says (5.1.1, 6.1): expand it to RGB first
189
+ return ("format=rgb24," if v.get("pix_fmt") == "pal8" else "") + rgb_to_bt709_filter()
190
+ if matrix not in NON_BT709_MATRICES:
191
+ return None
192
+ # the colorspace filter refuses an odd width or height outright ("Invalid odd size"), and a
193
+ # 4:2:0 JPEG can have one (a phone screenshot, #437). The frame is padded by one row and/or
194
+ # column, converted, and cropped back to its own size: no source pixel is lost or resampled
195
+ # (a 4:2:0 frame's chroma planes are the same size either way), so a caller's own crop or
196
+ # scale sees the frame it measured. Nothing changes for an even-sized source. FFmpeg rotates
197
+ # a rotated source before the graph, so the odd axis is read after the same swap.
198
+ w, h = int(v.get("width") or 0), int(v.get("height") or 0)
199
+ if int(v.get("rotation") or 0) % 180 == 90:
200
+ w, h = h, w
201
+ conv = f"colorspace=ispace={matrix}:iprimaries=bt709:itrc=bt709:space=bt709:primaries=bt709:trc=bt709"
202
+ if w % 2 or h % 2:
203
+ return f"{_EVEN_PAD}{conv},crop=iw-{w % 2}:ih-{h % 2}:0:0:exact=1"
204
+ return conv
205
+
206
+
207
+ def bt709_label_filter(meta: Optional[Dict[str, Any]]) -> Optional[str]:
208
+ """For an UNTAGGED SDR YUV picture that meets a converted (BT.709-tagged) one in a filter that
209
+ mixes pictures (overlay, xstack): its BT.709 label, tags only (setparams), or None for any
210
+ other picture (tagged, RGB, HDR, no probe).
211
+
212
+ FFmpeg 7.1+ negotiates one colourspace for all of a mixing filter's inputs and converts the
213
+ others to it, taking "unknown" as BT.601: the untagged main under a converted logo, or an
214
+ untagged grid cell beside a converted one, was shifted (7.08 mean / 25 max RGB on 7.1.1 and
215
+ 8.1.3), or the converted picture converted back. Labelled as what the output says it is, the
216
+ inputs agree and nothing is converted; on 5.1-7.0 the label changes nothing. The pixels are not
217
+ touched, as for the untagged source of a one-input re-encode (bt709_tag_args)."""
218
+ v = (meta or {}).get("video") or {}
219
+ if (not v.get("pix_fmt") or v.get("bt2020_or_hdr") or is_rgb(meta)
220
+ or (v.get("color_space") or "unknown") not in ("unknown", "unspecified")):
221
+ return None
222
+ return "setparams=colorspace=bt709" + ("" if v.get("color_range") == "pc" else ":range=tv")
223
+
224
+
225
+ # FFmpeg's named colours that are greys (libavutil/parseutils.c's table): R = G = B.
226
+ _GREY_NAMES = frozenset(("black", "white", "gray", "grey", "silver", "darkgray", "darkgrey", "dimgray", "dimgrey",
227
+ "gainsboro", "lightgray", "lightgrey", "whitesmoke"))
228
+
229
+
230
+ def _yuv8(rgb: Sequence[int], kr: float, kb: float) -> "Tuple[int, int, int]":
231
+ """8-bit limited-range YUV of an RGB colour under the matrix (kr, kb), rounded as FFmpeg's
232
+ drawing code rounds it (ff_draw_color)."""
233
+ r, g, b = (c / 255 for c in rgb)
234
+ y = kr * r + (1 - kr - kb) * g + kb * b
235
+ return (int(16 + 219 * y + 0.5), int(128 + 224 * (b - y) / (2 * (1 - kb)) + 0.5),
236
+ int(128 + 224 * (r - y) / (2 * (1 - kr)) + 0.5))
237
+
238
+
239
+ def is_neutral_color(value: Any) -> bool:
240
+ """True for a colour whose 8-bit YUV is the same under BT.601 and BT.709, however translucent: a
241
+ grey (R = G = B; black and white included), or one so near grey that both round to the same
242
+ bytes (graphics.py's default background 101418). Only another colour lands differently, so only
243
+ it needs drawn_chain(). A name counts only if it is one of FFmpeg's greys; anything else
244
+ (`red`, `random`) is not neutral."""
245
+ v = str(value or "").strip().split("@")[0].lower()
246
+ if v in _GREY_NAMES:
247
+ return True
248
+ v = v[1:] if v.startswith("#") else v[2:] if v.startswith("0x") else v
249
+ if re.fullmatch(r"[0-9a-f]{6}(?:[0-9a-f]{2})?", v):
250
+ rgb = (int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16))
251
+ return _yuv8(rgb, 0.299, 0.114) == _yuv8(rgb, 0.2126, 0.0722)
252
+ return False
253
+
254
+
255
+ def is_full_range(meta: Optional[Dict[str, Any]]) -> bool:
256
+ """True when the probed YUV picture is full range: a `yuvj` format, or any other YUV format
257
+ tagged `pc` (VP9 and AV1 full range decode as plain `yuv420p` tagged pc, 10-bit full range as
258
+ `yuv420p10le` tagged pc). An RGB picture is not: bt709_matrix_filter() makes it limited YUV."""
259
+ v = (meta or {}).get("video") or {}
260
+ if is_rgb(meta) or not v.get("pix_fmt"):
261
+ return False
262
+ return str(v["pix_fmt"]).startswith("yuvj") or v.get("color_range") == "pc"
263
+
264
+
265
+ def limited_range_filter(meta: Optional[Dict[str, Any]]) -> Optional[str]:
266
+ """The filter that takes a full-range SDR YUV picture (is_full_range) to limited range, or None
267
+ for any other picture (limited, RGB, HDR/BT.2020, no probe).
268
+
269
+ A tool that puts several pictures in one frame or one stream (concat, xfade, xstack, overlay)
270
+ passes their samples through as they are, so a full-range clip beside a limited one was shown
271
+ with the other's range: C03028 came out C9251B (#410). The input range is left to `scale`,
272
+ which reads it from each frame (FFmpeg 6.1 already converts a full-range non-`yuvj` frame to
273
+ limited at any resize, so a stated `in_range=pc` would convert some frames twice); only the
274
+ output range is stated. A `yuvj` format is full range by name, so it is also given its limited
275
+ name (`format=`), or swscale would write full range under the limited tag."""
276
+ v = (meta or {}).get("video") or {}
277
+ if v.get("bt2020_or_hdr") or not is_full_range(meta):
278
+ return None
279
+ pf = str(v["pix_fmt"])
280
+ return "scale=out_range=tv" + (f",format=yuv{pf[4:]}" if pf.startswith("yuvj") else "")
281
+
282
+
283
+ def as_limited(meta: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
284
+ """`meta` as it reads after limited_range_filter(): the same probe with a limited-range format and
285
+ tag, for the code that plans what is drawn on the converted picture (drawn_stream_format)."""
286
+ if not limited_range_filter(meta):
287
+ return meta
288
+ v = dict((meta or {}).get("video") or {})
289
+ pf = str(v["pix_fmt"])
290
+ v.update(pix_fmt="yuv" + pf[4:] if pf.startswith("yuvj") else pf, color_range="tv")
291
+ return {**(meta or {}), "video": v}
292
+
293
+
294
+ def drawn_stream_format(meta: Optional[Dict[str, Any]]) -> "Tuple[str, bool]":
295
+ """(pix_fmt, full range) of the picture a tool draws on, for rgb_island(): the probed source's own
296
+ 8-bit planar YUV format (an RGB source has become yuv444p, BT.709 limited, through
297
+ bt709_matrix_filter), or yuv420p for anything else (the format the encoder line takes it to)."""
298
+ v = (meta or {}).get("video") or {}
299
+ if is_rgb(meta):
300
+ return "yuv444p", False
301
+ pf = str(v.get("pix_fmt") or "yuv420p")
302
+ full = is_full_range(meta)
303
+ if pf not in ("yuv420p", "yuv422p", "yuv444p", "yuvj420p", "yuvj422p", "yuvj444p"):
304
+ pf = "yuv420p"
305
+ return pf, full
306
+
307
+
308
+ def rgb_island(colour_chain: str, neutral_chain: str = "null", pix_fmt: str = "yuv420p", full: bool = False,
309
+ tag: str = "d") -> str:
310
+ """`colour_chain` (filters that draw a colour: drawtext, pad, tpad, rotate's fill, libass) run on
311
+ an RGB copy of the picture, as one simple filtergraph (one input, one output; `tag` keeps its
312
+ labels unique in a bigger graph). For FFmpeg < 7.1, whose drawing filters turn every colour into
313
+ YUV with BT.601 whatever the picture is tagged (`ff_draw_init`), and drawbox on every version:
314
+ in RGB a colour is written as it is, and the copy goes back to YUV with BT.709.
315
+
316
+ Only the pixels the drawing touched come from that copy. The same round trip without the colour
317
+ (`neutral_chain`: `null`, or the same pad/tpad/rotate with a black fill, which is the same under
318
+ every matrix) is compared with it plane by plane, and maskedmerge takes the drawn copy where
319
+ the two differ and the untouched picture (`neutral_chain` on the YUV itself) everywhere else:
320
+ the RGB round trip is not lossless, so a picture that only passes through keeps its pixels."""
321
+ rng = "pc" if full else "tv"
322
+ to_rgb = f"scale=in_color_matrix=bt709:in_range={rng},format=rgb24"
323
+ to_yuv = f"scale=out_color_matrix=bt709:out_range={rng},format={pix_fmt}"
324
+ keep = "'255*gt(val,0)'"
325
+ t = f"_{tag}"
326
+ return (f"split=3[{t}p][{t}c][{t}n];[{t}p]format={pix_fmt},{neutral_chain}[{t}p1];"
327
+ f"[{t}c]{to_rgb},{colour_chain},{to_yuv},split[{t}c1][{t}c2];"
328
+ f"[{t}n]{to_rgb},{neutral_chain},{to_yuv}[{t}n1];"
329
+ f"[{t}c1][{t}n1]blend=all_mode=difference,lut=c0={keep}:c1={keep}:c2={keep}[{t}m];"
330
+ f"[{t}p1][{t}c2][{t}m]maskedmerge")
331
+
332
+
333
+ def bt709_matrix_args(meta: Optional[Dict[str, Any]]) -> List[str]:
334
+ """["-vf", bt709_matrix_filter(meta)] for an encoder line that tags its output BT.709, or [].
335
+
336
+ It rides on the encoder line (decision.video_args() and friends) so every tool that
337
+ re-encodes through that line converts without building it into its own graph. That -vf is
338
+ valid as it stands for a command with no other filter; run() folds it into the tool's own
339
+ -vf or -filter_complex (fold_bt709_matrix()) before the command is recorded or run."""
340
+ f = bt709_line_filter(meta)
341
+ return ["-vf", f] if f else []
342
+
343
+
344
+ # bt709_matrix_filter(), and on FFmpeg 9+ for an HDR source a relabel: FFmpeg 9 writes mp4/mov's colr box
345
+ # from the frames, which keep its primaries and transfer under a bt709 VUI (#711). It converts nothing.
346
+ def bt709_line_filter(meta: Optional[Dict[str, Any]]) -> Optional[str]:
347
+ f = bt709_matrix_filter(meta)
348
+ if ((meta or {}).get("video") or {}).get("bt2020_or_hdr") and ffmpeg_version() >= (9, 0):
349
+ f = ",".join(x for x in (f, _BT709_RELABEL) if x)
350
+ return f
351
+
352
+
353
+ def hdr_rgb_matrix_args(meta: Optional[Dict[str, Any]], alpha: bool = False) -> List[str]:
354
+ """["-vf", hdr_rgb_matrix_filter(meta)] for an encoder line that keeps a BT.2020 / HDR source's
355
+ colour, or []: bt709_matrix_args()'s counterpart for that line, folded by run() the same way."""
356
+ f = hdr_rgb_matrix_filter(meta, alpha=alpha)
357
+ return ["-vf", f] if f else []
358
+
359
+
360
+ def fold_bt709_matrix(cmd: Sequence[str]) -> List[str]:
361
+ """`cmd` with the conversion bt709_matrix_args() appended to its encoder line moved into the
362
+ tool's own filter graph, where it runs first, on the decoded source:
363
+
364
+ - no other filter: unchanged (the -vf is the graph);
365
+ - a -vf: the conversion is prepended to that chain;
366
+ - a -filter_complex: every `[N:v]` / `[N:v:0]` / `[N:V:0]` reference to an input that reads the same file
367
+ as input 0 (the file the encoder line was built for; cut.py's segment join opens it once
368
+ per segment) reads that input through the conversion instead. Other inputs are untouched.
369
+
370
+ A -filter_complex with no such reference is refused rather than run with two graphs (ffmpeg
371
+ would refuse it anyway, less clearly). Every other command is returned as it is."""
372
+ out: List[str] = []
373
+ conv, at = None, -1
374
+ i = 0
375
+ while i < len(cmd):
376
+ if cmd[i] == "-vf" and i + 1 < len(cmd) and _MATRIX_FILTER_RE.match(str(cmd[i + 1])):
377
+ conv, at = conv or str(cmd[i + 1]), (at if at >= 0 else len(out))
378
+ i += 2
379
+ continue
380
+ out.append(cmd[i])
381
+ i += 1
382
+ if conv is None:
383
+ return list(cmd)
384
+ graph_at = next((k for k, a in enumerate(out[:-1]) if a in ("-filter_complex", "-lavfi")), None)
385
+ if graph_at is not None:
386
+ inputs = [out[k + 1] for k in range(len(out) - 1) if out[k] == "-i"]
387
+ source = {n for n, p in enumerate(inputs) if p == inputs[0]} if inputs else set()
388
+ refs: Dict[int, List[str]] = {} # input index -> [its first reference, the labels standing in for it]
389
+
390
+ def through(m: "re.Match[str]") -> str:
391
+ n = int(m.group(1))
392
+ if n not in source:
393
+ return m.group(0)
394
+ label = f"[bt709src{sum(len(v) - 1 for v in refs.values())}]"
395
+ refs.setdefault(n, [m.group(0)]).append(label)
396
+ return label
397
+
398
+ graph = _INPUT_VIDEO_REF.sub(through, str(out[graph_at + 1]))
399
+ if not refs:
400
+ die("internal: a BT.709 matrix conversion was requested for a -filter_complex that never reads "
401
+ "input 0's video as [0:v] or [0:V:0]", kind="ffmpeg")
402
+ # one conversion per input, split when the graph reads that input more than once
403
+ # (speedramp.py trims [0:v] once per segment)
404
+ chains = [f"{ref}{conv}" + (f",split={len(labels)}" if len(labels) > 1 else "") + "".join(labels)
405
+ for ref, *labels in refs.values()]
406
+ out[graph_at + 1] = ";".join(chains + [graph])
407
+ return out
408
+ vf_at = next((k for k, a in enumerate(out[:-1]) if a == "-vf"), None)
409
+ if vf_at is not None:
410
+ out[vf_at + 1] = f"{conv},{out[vf_at + 1]}"
411
+ return out
412
+ return out[:at] + ["-vf", conv] + out[at:]
413
+
414
+
415
+ _HEX6 = re.compile(r"^[0-9A-Fa-f]{6}$")
416
+
417
+
418
+ def color_hex(value: str) -> str:
419
+ """Normalise '#ffd200' / 'ffd200' / '0xFFD200' to 'FFD200'. Six hex digits only: the result is
420
+ written into libass styles and drawtext/color options, so a six-letter colour name ("yellow")
421
+ used to pass the length check and draw black, reported verified, and a quote or comma reached
422
+ the filter graph."""
423
+ v = str(value).strip().lstrip("#")
424
+ if v.lower().startswith("0x"):
425
+ v = v[2:]
426
+ if not _HEX6.match(v):
427
+ die(f"colour must be six hex digits RRGGBB (e.g. FFD200 or #ffd200), got '{value}'; colour names are not "
428
+ "accepted here")
429
+ return v.upper()
430
+
431
+
432
+ # Six or eight hex digits, with 0x, with # or bare (#535: bare ones starting with a digit, 0B1D2A,
433
+ # were refused, and seven passed with a prefix and failed inside ffmpeg), or a word that starts
434
+ # with a letter; alpha is 0..1 ("red@2" used to reach ffmpeg). Nothing else reaches the graph.
435
+ _HEX_DIGITS = r"(?:[0-9A-Fa-f]{8}|[0-9A-Fa-f]{6})"
436
+ _COLOR_TOKEN_RE = re.compile(r"^((?:0[xX]|#)?%s|[A-Za-z][A-Za-z0-9]*)(@(?:0(?:\.\d+)?|1(?:\.0+)?|\.\d+))?$" % _HEX_DIGITS)
437
+
438
+
439
+ def validate_color(value: str, flag: str = "--color") -> str:
440
+ """Refuse a colour argument that isn't a plain ffmpeg colour token (named colour, RRGGBB[AA],
441
+ 0xRRGGBB[AA], #RRGGBB[AA], optionally with an @alpha suffix). Every caller that string-formats a colour flag
442
+ straight into a filter graph (color=c=..., tpad=...:color=..., rotate=...:fillcolor=...) must
443
+ validate it first -- ffmpeg filter options are comma/colon-delimited, so an unvalidated value
444
+ containing those characters lets a caller splice in an entirely different filter (a real,
445
+ demonstrated filter-graph injection: --color "black,drawtext=text=..." renders arbitrary burnt-in
446
+ text), not just an odd colour. This is the same "no filter graph accepted from the caller"
447
+ invariant every other typed flag in this codebase already holds to."""
448
+ m = _COLOR_TOKEN_RE.match(value)
449
+ if not m:
450
+ die(f"{flag} must be a plain colour (a name, or six or eight hex digits RRGGBB[AA], bare or after 0x or #, "
451
+ f"optionally @alpha), got '{value}'")
452
+ word = m.group(1)
453
+ if word[0].isalpha() and word.lower() not in FFMPEG_COLOR_NAMES and not _BARE_HEX.match(word):
454
+ # A189 (#465): any word passed, and an unknown name failed inside ffmpeg ("Cannot find
455
+ # color") as kind ffmpeg, after a dry run that had said completed. ffmpeg reads a word as
456
+ # one of its names, or else as bare hex digits.
457
+ die(f"{flag} {value!r}: {word!r} is not a colour name ffmpeg knows (`ffmpeg -colors` lists them) "
458
+ "nor six or eight hex digits; use a name such as white, or 0xRRGGBB")
459
+ return value
460
+
461
+
462
+ # The names av_parse_color() looks up, case-insensitively (`ffmpeg -colors`, the same list in 6.1
463
+ # through 8), plus the two it treats as a random colour. A word that is none of them is read as
464
+ # hex digits without a prefix, which works for six or eight of them.
465
+ FFMPEG_COLOR_NAMES = frozenset((
466
+ "aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown "
467
+ "burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan "
468
+ "darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred "
469
+ "darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray "
470
+ "dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green "
471
+ "greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon "
472
+ "lightblue lightcoral lightcyan lightgoldenrodyellow lightgreen lightgrey lightpink lightsalmon "
473
+ "lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon "
474
+ "mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen "
475
+ "mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive "
476
+ "olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff "
477
+ "peru pink plum powderblue purple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell "
478
+ "sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise "
479
+ "violet wheat white whitesmoke yellow yellowgreen random bikeshed").split())
480
+ _BARE_HEX = re.compile(r"^(?:[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$")
481
+
482
+
483
+ # The tonemap filter reads linear light in units of 100 nits (1.0 = SDR white; its default peak,
484
+ # 10, is 1000 nits), so the linearising zscale uses npl=100. Through 3.6.0 it used npl=--peak:
485
+ # a 1000-nit pixel came out as 1.0, which tonemap took as 100 nits, so nothing reached SDR white
486
+ # (PQ 1000 nits and HLG 100 % -> Y 151 of 235, HLG reference white 91) and raising --peak to a
487
+ # brighter master's darkened the picture further. zimg's HLG decode assumes a 1000-nit display,
488
+ # so an HLG picture always peaks at 1000 nits there, whatever --peak says.
489
+ TONEMAP_REFERENCE_NITS = 100.0
490
+ HLG_PEAK_NITS = 1000.0
491
+
492
+
493
+ def hdr_to_sdr_chain(meta: dict, tonemap: str, peak: float = 1000.0, desat: float = 0.0) -> str:
494
+ """PQ / HLG / Dolby Vision to BT.709 SDR: linearise at 100 nits per unit, tone-map the source
495
+ peak (`peak` nits for PQ, 1000 for HLG) to SDR white, re-encode as BT.709 limited range."""
496
+ v = meta["video"]
497
+ trc = v.get("color_transfer") or "smpte2084"
498
+ prim = v.get("color_primaries") or "bt2020"
499
+ space = v.get("color_space") or "bt2020nc"
500
+ source_peak = HLG_PEAK_NITS if trc == "arib-std-b67" else peak
501
+ # zscale needs explicit input tags when the file lacks them, and on 6.1 its `pin` does not
502
+ # reach a frame whose own primaries are unspecified ("no path between colorspaces", kind
503
+ # ffmpeg: --to-sdr --force on an untagged file failed through 3.8.8), so a frame missing a tag
504
+ # is labelled with what the chain reads it as first
505
+ missing = not (v.get("color_transfer") and v.get("color_primaries") and v.get("color_space"))
506
+ label = [f"setparams=color_primaries={prim}:color_trc={trc}:colorspace={space}"] if missing else []
507
+ chain: List[str] = label + [
508
+ f"zscale=tin={trc}:pin={prim}:min={space}:rin={v.get('color_range') or 'tv'}:t=linear"
509
+ f":npl={TONEMAP_REFERENCE_NITS:g}",
510
+ "format=gbrpf32le",
511
+ "zscale=p=bt709",
512
+ f"tonemap=tonemap={tonemap}:desat={desat:g}:peak={source_peak / TONEMAP_REFERENCE_NITS:g}",
513
+ "zscale=t=bt709:m=bt709:r=tv",
514
+ "format=yuv420p",
515
+ ]
516
+ return ",".join(chain)
517
+
518
+
519
+ def bt2020_sdr_to_bt709_chain(meta: dict) -> str:
520
+ """Gamut conversion only, for BT.2020 primaries on an SDR transfer (probe: `bt2020_or_hdr`
521
+ true, `hdr_signal` false). Such a file is already display-referred SDR: linearising it with
522
+ its own transfer, mapping the primaries to BT.709 and re-applying the BT.709 transfer keeps
523
+ white at white and grey at grey. The tone map the HDR chain adds would treat 100 % SDR white
524
+ as a fraction of a 1000-nit peak and darken the picture (white Y 235 -> 151, grey 126 -> 90)."""
525
+ v = meta["video"]
526
+ trc = v.get("color_transfer") or "bt709"
527
+ space = v.get("color_space") or "bt2020nc"
528
+ return ",".join([
529
+ f"zscale=tin={trc}:pin=bt2020:min={space}:rin={v.get('color_range') or 'tv'}:t=linear",
530
+ "format=gbrpf32le",
531
+ "zscale=p=bt709",
532
+ "zscale=t=bt709:m=bt709:r=tv",
533
+ "format=yuv420p",
534
+ ])
535
+
536
+
537
+ def is_bt2020_sdr(v: dict) -> bool:
538
+ """BT.2020 primaries on a non-HDR transfer and no Dolby Vision: gamut-only --to-sdr."""
539
+ return bool(v.get("bt2020_or_hdr")) and not v.get("hdr_signal") and not v.get("dolby_vision") \
540
+ and v.get("color_transfer") not in ("smpte2084", "arib-std-b67")