@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,2452 @@
1
+ """Pure choices: given facts (a probe document, a codec name, a path, a flag value), return the
2
+ arguments or the value that follows from them.
3
+
4
+ Nothing here starts a subprocess or touches a media file, which is what makes the copy-vs-re-encode
5
+ and encoder-selection rules testable on their own.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import os
11
+ import re
12
+ from fractions import Fraction
13
+ from pathlib import Path, PurePosixPath, PureWindowsPath
14
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
15
+ from _common.color import (as_limited, bt709_label_filter, bt709_line_filter, bt709_matrix_args, bt709_matrix_filter, bt709_tag_args, drawn_stream_format,
16
+ hdr_line_matrix, hdr_rgb_matrix_args, hdr_rgb_matrix_filter, is_neutral_color, limited_range_filter, rgb_island, rgb_to_bt709_filter, _sdr_bt709)
17
+ from _common.alpha import rgb_to_bt709_line
18
+ from _common.emit import die, input_length, note, record_fallback, refuse, warn
19
+ from _common.runner import absent_word, file_arg, read_json
20
+ from _common.probe import AUDIO_MEDIA_EXT, display_size
21
+ from _common.runner import CODECS, STATE, ffmpeg_encoders, ffmpeg_list_error, ffmpeg_version, hw_platform_reason
22
+
23
+
24
+ def boxblur_chroma_radius(want: int) -> str:
25
+ """boxblur's chroma radius as an expression boxblur evaluates on the chroma planes' own size
26
+ (cw x ch, so a 4:1:1 or 4:1:0 frame's quarter-width planes are what is measured, not an assumed
27
+ 4:2:0): `want`, or the largest radius that plane holds, floor((min(cw, ch) - 1) / 2), or 0 on a
28
+ plane too small for 1. On 4:2:0 that is redact.py's earlier (min(w, h) // 2 - 1) // 2. boxblur
29
+ refuses a radius above half the plane (6.1); 7.1 also refuses 1 on a 2 px plane, which this
30
+ bound leaves out (#527)."""
31
+ return f"max(0\\,min({int(want)}\\,floor((min(cw\\,ch)-1)/2)))"
32
+
33
+
34
+ def pad_filters(out_w: int, out_h: int, fill: str, color: str, blur: int, darken: float = 0.0,
35
+ meta: Optional[Dict[str, Any]] = None, blank: bool = False) -> str:
36
+ """The letterbox/pillarbox step shared by fit.py and export.py, as one -vf segment.
37
+
38
+ fill="color": scale to fit, then pad with a solid colour (the historical behaviour).
39
+ fill="blur": the bars are a blurred, scaled-to-cover copy of the same frame -- what every
40
+ phone editor's "make it vertical" does with landscape footage (#139). Built as a small
41
+ graph inside the -vf chain: split, one branch scaled to cover and cropped to the frame
42
+ then boxblur'ed, the other scaled to fit, overlaid centred. Only `filter:boxblur` is
43
+ needed beyond the usual scale/pad set, and that is already required by redact.py.
44
+ `darken` > 0 also dims that background copy by that much brightness (eq), so the picture in
45
+ front reads as the subject instead of competing with a bright blurred copy of itself --
46
+ what `fit.py --fit blur` uses (1.14).
47
+ `meta`: the probe of the picture being padded, when the output is that picture's re-encode: a
48
+ --pad-color with chroma is then drawn in the BT.709 the line tags (drawn_chain()). Without it
49
+ (a still made RGB, an export to GIF) the pad is what it always was.
50
+ `blank` (fit.py's picture measurement, #519): the blurred copy is drawn black instead, so it
51
+ does not change with the picture; the graph is otherwise the same."""
52
+ if fill == "blur":
53
+ # boxblur rejects a radius larger than half the smaller dimension ("radius 20, must be
54
+ # <= 8" on a 16 px target); clamp instead of failing an otherwise valid request
55
+ radius = max(1, min(int(blur), max(1, min(out_w, out_h) // 2 - 1)))
56
+ # left unset, the chroma radius was the luma one, and a 4:2:0 68x120 frame's 34x60 chroma
57
+ # planes failed at 20 ("must be <= 17", #527). On a larger frame it is still the luma one
58
+ chroma = boxblur_chroma_radius(radius)
59
+ return (f"split[__fitfg][__fitbg];"
60
+ f"[__fitbg]scale={out_w}:{out_h}:force_original_aspect_ratio=increase,crop={out_w}:{out_h},"
61
+ + ("drawbox=c=black:t=fill" if blank else
62
+ f"boxblur={radius}:2:{chroma}:2" + (f",eq=brightness=-{darken:g}" if darken else "")) + "[__fitbgb];"
63
+ f"[__fitfg]scale={out_w}:{out_h}:force_original_aspect_ratio=decrease[__fitfgs];"
64
+ f"[__fitbgb][__fitfgs]overlay=(W-w)/2:(H-h)/2:format=auto")
65
+ # a picture of another shape is mostly bars in this frame (a 9:16 clip in 16:9 fills 32%): the
66
+ # file is what the frame asks for, and the caller may not have asked for that frame's shape
67
+ if meta is not None and not blank and all(d := display_size(meta.get("video"))) and (part := min(out_w / d[0], out_h / d[1]) ** 2 * d[0] * d[1] / (out_w * out_h)) < 0.5:
68
+ warn(f"the picture fills {part:.0%} of the {out_w}x{out_h} frame and the rest is bars: the source is {d[0]}x{d[1]}, another shape. --fit crop fills the frame; a frame of the source's shape keeps all of it (export.py: reels, shorts and tiktok are 9:16, youtube and facebook 16:9)", "picture_small_in_frame", fraction=round(part, 3), source=f"{d[0]}x{d[1]}", frame=f"{out_w}x{out_h}")
69
+ pad = f"pad={out_w}:{out_h}:(ow-iw)/2:(oh-ih)/2:color="
70
+ return (f"scale={out_w}:{out_h}:force_original_aspect_ratio=decrease,"
71
+ + (pad + color if meta is None else drawn_chain(pad + color, meta, [color], pad + "black", tag="pad")))
72
+
73
+
74
+ def warn_mostly_cropped(video: Optional[Dict[str, Any]], out_w: int, out_h: int) -> None:
75
+ """A crop to another shape that keeps less than half of the picture says so (#688), as a pad
76
+ that leaves the picture small does (picture_small_in_frame): a 1920x1080 clip cropped to 9:16
77
+ keeps the centre 32% of it. A warning only: a vertical crop of landscape footage is the usual
78
+ way to make a Short, and the file is what was asked for."""
79
+ if all(d := display_size(video)) and out_w and out_h and (part := min(out_w * d[1] / (out_h * d[0]), out_h * d[0] / (out_w * d[1]))) < 0.5:
80
+ warn(f"the crop keeps {part:.0%} of the picture: the source is {d[0]}x{d[1]} and the frame {out_w}x{out_h}, another shape. --fit pad keeps all of it with bars, --fit blur over a blurred copy", "picture_mostly_cropped", fraction=round(part, 3), source=f"{d[0]}x{d[1]}", frame=f"{out_w}x{out_h}")
81
+
82
+
83
+ def add_pad_fill_args(parser: "argparse.ArgumentParser") -> None:
84
+ parser.add_argument("--pad-fill", choices=["color", "blur"], default="color",
85
+ help="what fills the letterbox/pillarbox bars under --fit pad: a solid --pad-color (default) or a blurred, scaled-up copy of the frame")
86
+ parser.add_argument("--pad-blur", type=int, default=20, help="blur radius in pixels for --pad-fill blur (default 20)")
87
+
88
+
89
+ def aspect_ratio(value: Any) -> Optional[Fraction]:
90
+ """An aspect written W:H as an exact ratio, or None. fit.py --aspect and --export-timeline's
91
+ sequence frame read an aspect through this one function, so the export refuses `16/9` and
92
+ `2.39:1` where the render hands them to fit.py, which refuses them too (the timeline once
93
+ took them and wrote a sequence for a project whose render then failed in fit.py). Each side
94
+ is read with int(), as fit.py read it in 2.2.1, so a patch release refuses nothing fit.py
95
+ took: `+16:9` and `1_6:9` still parse, and `0:9` is a zero ratio, which frame_size() treats
96
+ as no aspect (2.2.1 kept the source frame). render.py's frame_from_preset() keeps 2.2.1's
97
+ looser match: it only picks the export preset's size."""
98
+ parts = str(value).split(":")
99
+ if len(parts) != 2:
100
+ return None
101
+ try:
102
+ w, h = int(parts[0]), int(parts[1])
103
+ ratio = Fraction(w, h)
104
+ except (ValueError, ZeroDivisionError):
105
+ return None
106
+ # a negative side (`-16:9`, `16:-9`) is no aspect anyone means: frame_size() made a negative
107
+ # frame of it, which fit.py's pad refused inside ffmpeg (kind ffmpeg) and the timeline wrote.
108
+ # Each side is looked at, not the ratio: `-16:-9` is a positive fraction
109
+ return None if w < 0 or h < 0 else ratio
110
+
111
+
112
+ def _even(n: float) -> int:
113
+ v = int(round(n))
114
+ return v if v % 2 == 0 else v + 1
115
+
116
+
117
+ # A frame larger than the picture is enlarged with Lanczos in place of swscale's default bicubic:
118
+ # fewer soft edges where a 720p clip is delivered at 1080x1920. Nothing is added when the frame is
119
+ # the picture's size or smaller, so those commands are the ones they were.
120
+ def enlarge_args(meta: Optional[Dict[str, Any]], w: Optional[int], h: Optional[int]) -> List[str]:
121
+ return ["-sws_flags", "lanczos"] if w and h and all(d := display_size((meta or {}).get("video"))) and (w > d[0] or h > d[1]) else []
122
+
123
+
124
+ def frame_size(ratio: Optional[Fraction], width: Optional[int], height: Optional[int],
125
+ src_w: int, src_h: int) -> Tuple[int, int]:
126
+ """The frame fit.py sizes for --aspect `ratio` (None: the source's own) and --width/--height,
127
+ from a src_w x src_h picture -- and so the sequence frame render.py --export-timeline writes
128
+ for the same project frame. Both sides given are used directly; one side takes the other from
129
+ the aspect. With neither, the canvas takes the new aspect without exceeding the source's
130
+ resolution in either dimension: a narrower/taller target than the source (e.g. 9:16 from a
131
+ 16:9 source) must be bounded by the source's HEIGHT, not its width -- bounding by width there
132
+ multiplies the height by src_ratio/ratio (a 1920x1080 source asked for 9:16 used to come out
133
+ 1920x3414, a ~3.16x upscale in both fit=pad and fit=crop, entirely unrequested). Every side is
134
+ rounded to even."""
135
+ src_ratio = Fraction(src_w, src_h) if src_h else None
136
+ if ratio is None:
137
+ ratio = src_ratio
138
+ if width and height:
139
+ return _even(width), _even(height)
140
+ if width:
141
+ out_w = _even(width)
142
+ return out_w, (_even(out_w / ratio) if ratio else width)
143
+ if height:
144
+ out_h = _even(height)
145
+ return (_even(out_h * ratio) if ratio else height), out_h
146
+ if ratio and src_ratio:
147
+ if ratio <= src_ratio:
148
+ out_h = _even(src_h)
149
+ return _even(out_h * ratio), out_h
150
+ out_w = _even(src_w)
151
+ return out_w, _even(out_w / ratio)
152
+ return _even(src_w), _even(src_h)
153
+
154
+
155
+ # x264 preset names mapped onto SVT-AV1's 0-13 speed scale (lower = slower / better)
156
+ SVT_PRESET = {"ultrafast": 12, "superfast": 11, "veryfast": 10, "faster": 9, "fast": 8, "medium": 6, "slow": 4, "slower": 3, "veryslow": 2, "placebo": 1}
157
+
158
+
159
+ # Source containers the tools' own encoders (x264/x265/SVT-AV1 and AAC) cannot be written into: WebM
160
+ # takes only VP8/VP9/AV1 and Vorbis/Opus. A default output name keeps the source's extension
161
+ # except for these, whose default is .mp4 (#415): the dry run planned `clip_loudnorm.webm` and the
162
+ # real run then failed in the muxer.
163
+ NO_DEFAULT_ENCODE_EXT = {".webm"}
164
+
165
+
166
+ def default_output(input_path: str, suffix: str, ext: Optional[str] = None) -> str:
167
+ p = Path(input_path)
168
+ if ext:
169
+ new_ext = ext
170
+ elif p.suffix.lower() in NO_DEFAULT_ENCODE_EXT:
171
+ new_ext = "mp4"
172
+ else:
173
+ new_ext = p.suffix.lstrip(".") or "mp4"
174
+ out = str(p.with_name(f"{p.stem}_{suffix}.{new_ext}"))
175
+ # an input named -take.mp4 (given as ./-take.mp4 or after `--`) has a default output that
176
+ # starts with a dash too, which run() refuses as option-shaped: name it as a file (#558)
177
+ return file_arg(out)
178
+
179
+
180
+ class MissingFpsError(ValueError):
181
+ """parse_time() saw an hh:mm:ss:ff SMPTE timecode but no fps was given to convert it -- distinct
182
+ from a plain ValueError so a caller that falls back to treating unparseable text as a literal
183
+ line (e.g. caption.py's free-text cue format) can still fail loudly on this one, instead of
184
+ silently swallowing a mistyped/missing --fps as an auto-timed line of digits."""
185
+
186
+
187
+ def _on_windows() -> bool:
188
+ """Whether a backslash in a path is a separator (Windows) or a character of the name."""
189
+ return os.name == "nt"
190
+
191
+
192
+ def concat_list_line(path: str) -> str:
193
+ """One `file '...'` line for the concat demuxer. The demuxer reads backslash as an escape
194
+ inside the quoted form, so a Windows path (C:\\Users\\...\\part000.mp4) must be written
195
+ with forward slashes -- ffmpeg opens either spelling on Windows -- and a single quote in the
196
+ name is closed, escaped and reopened. Shared by cut.py (multi-segment) and sequence.py.
197
+
198
+ A line break has no escape in this format: the demuxer reads each line as its own directive,
199
+ so a name containing one would add `file` entries to the list and pull in files the caller
200
+ never named. Such a path is refused."""
201
+ if "\n" in str(path) or "\r" in str(path):
202
+ refuse("input", "media_path_has_line_break",
203
+ f"{str(path)!r} contains a line break, which ffmpeg's concat list cannot hold (each line is a "
204
+ "directive of its own); rename the file", path=str(path))
205
+ # only on Windows: on POSIX the quoted form takes a backslash literally, and it is part of the name (#408)
206
+ escaped = (str(path).replace("\\", "/") if _on_windows() else str(path)).replace("'", "'\\''")
207
+ return f"file '{escaped}'"
208
+
209
+
210
+ def fmt_secs(value: Optional[float]) -> str:
211
+ """`12.345s`, or `?s` when the probe had no duration (MPEG-TS without a duration tag, a
212
+ stream whose container and streams all omit it). Every writing tool prints the duration
213
+ of what it wrote; formatting None with :.3f used to raise TypeError after a successful
214
+ encode, in 25+ scripts."""
215
+ return "?s" if value is None else f"{value:.3f}s"
216
+
217
+
218
+ def ntsc_rate(fps: float) -> float:
219
+ """`fps` as the rate it is a rounding of: 23.976, 29.97, 47.952, 59.94 and 119.88 (what
220
+ probe() reports, and what a caller types after `@`) are N * 1000 / 1001. Any other rate is
221
+ returned as it is. timeline.exact_rate() reads the same five rates the same way."""
222
+ whole = round(fps * 1.001)
223
+ if whole in (24, 30, 48, 60, 120) and abs(fps - whole / 1.001) < 0.01 and abs(fps - whole) > 0.01:
224
+ return whole * 1000 / 1001
225
+ return fps
226
+
227
+
228
+ def parse_time(value: str, fps: Optional[float] = None) -> float:
229
+ """Accept seconds ('12.5'), mm:ss ('1:30'), hh:mm:ss(.ms) ('00:01:30.250'), SRT '00:01:30,250',
230
+ or -- when `fps` is given -- SMPTE non-drop-frame timecode 'hh:mm:ss:ff' ('00:01:30:15')."""
231
+ v = value.strip().replace(",", ".")
232
+ if not v:
233
+ raise ValueError("empty time")
234
+ if "@" in v:
235
+ # 1.9: 'hh:mm:ss:ff@29.97' names the timecode's rate explicitly (docs/design-decisions.md,
236
+ # time grammar); it overrides the source fps a tool passed in, and is meaningless without
237
+ # the four-part form
238
+ v, _, rate = v.rpartition("@")
239
+ if "@" in v:
240
+ raise ValueError(f"'{value}': only one @fps suffix is allowed")
241
+ try:
242
+ fps = float(rate)
243
+ except ValueError:
244
+ raise ValueError(f"bad @fps suffix in '{value}' (expected a number such as @29.97)")
245
+ if not math.isfinite(fps) or fps <= 0:
246
+ raise ValueError(f"bad @fps suffix in '{value}': the rate must be a positive, finite number")
247
+ if len(v.split(":")) != 4:
248
+ raise ValueError(f"'{value}': the @fps suffix belongs to an hh:mm:ss:ff timecode, not to seconds or mm:ss")
249
+ parts = v.split(":")
250
+ if len(parts) == 4:
251
+ if fps is None or fps <= 0:
252
+ raise MissingFpsError(f"'{value}' looks like an hh:mm:ss:ff SMPTE timecode, but no fps was given to convert its frame count to seconds (append @fps, e.g. {value}@29.97, or use seconds / mm:ss / hh:mm:ss.ms)")
253
+ h, m, s, f = parts
254
+ if "." in f:
255
+ raise ValueError(f"bad SMPTE timecode: {value}")
256
+ frame, whole_fps = int(f), int(round(fps))
257
+ if not (0 <= frame < whole_fps):
258
+ raise ValueError(f"bad SMPTE timecode '{value}': frame {frame} is out of range for {fps:g} fps (0-{whole_fps - 1})")
259
+ # Non-drop-frame: the timecode counts whole_fps frames per timecode-second, so the real
260
+ # time is the total frame count over the true rate (at 29.97 an hour of timecode is
261
+ # 3596.4 s of video). This is exactly what fmt_smpte_time() inverts; before, the two
262
+ # disagreed by ~0.1 % on the fractional NTSC rates and drifted apart over long files.
263
+ total_frames = (int(h) * 3600 + int(m) * 60 + int(s)) * whole_fps + frame
264
+ # at the picture's exact rate: probe()'s `fps` is rounded to three decimals, and frame 37
265
+ # counted at 29.97 is 1.2345679 s, 1.2 microseconds past the frame at 37 * 1001 / 30000,
266
+ # so a start read from 00:00:01:07 was the frame after it (ntsc_rate)
267
+ return total_frames / ntsc_rate(fps)
268
+ if len(parts) > 3:
269
+ raise ValueError(f"bad time: {value}")
270
+ total = 0.0
271
+ for part in parts:
272
+ try:
273
+ total = total * 60 + float(part)
274
+ except ValueError:
275
+ # not the interpreter's "could not convert string to float: 'zz'" (review 9)
276
+ raise ValueError(f"'{value}': not a time")
277
+ # float() reads "nan", "inf" and "1e999": none of them is a time, and each got past the
278
+ # comparisons that bound a time (nan compares false with everything)
279
+ if not math.isfinite(total):
280
+ raise ValueError(f"'{value}': not a time (it is not finite)")
281
+ return total
282
+
283
+
284
+ def time_arg(value: str, flag: str, fps: Optional[float] = None,
285
+ source: Optional[Dict[str, Any]] = None) -> float:
286
+ """parse_time() for a command-line flag: SMPTE hh:mm:ss:ff resolves with the input's fps when
287
+ the caller has one, and every parse failure is a `kind: input` refusal naming the flag (so
288
+ `--json` callers get a failure document, never a traceback). `source` is the probe of the
289
+ input the time is in when that is not the first one (a B-roll's --from, an overlay layer's
290
+ --place range): the SMPTE hint then names that input's start timecode and length."""
291
+ try:
292
+ seconds = parse_time(value, fps)
293
+ except MissingFpsError as e:
294
+ die(f"{flag} {value!r}: {e}")
295
+ except ValueError as e:
296
+ die(f"{flag} {value!r}: {e} (use seconds, mm:ss, hh:mm:ss.ms, or hh:mm:ss:ff at the source's fps or with an explicit @fps suffix)")
297
+ _remember_smpte_hint(value, flag, fps, seconds, source)
298
+ return seconds
299
+
300
+
301
+ def _remember_smpte_hint(value: str, flag: str, fps: Optional[float], seconds: float,
302
+ source: Optional[Dict[str, Any]] = None) -> None:
303
+ """An hh:mm:ss:ff time counts from the file's first frame (00:00:00:00), not from a camera's
304
+ start timecode (docs/design-decisions.md, time grammar). When one reads past the end of a
305
+ source that carries a start timecode it was almost certainly typed off the source's own
306
+ burned-in or NLE timecode: keep a hint naming the frame it would be from the source's start,
307
+ which die() adds to the refusal a tool then raises for the out-of-range time (#411). The
308
+ grammar itself, and what a valid time means, are unchanged. A time in another input than the
309
+ first is judged against that input's own timecode and length (#416 review)."""
310
+ if source is not None:
311
+ own = (source.get("timecode") or {}).get("value")
312
+ tc = (own, source.get("duration")) if own else None
313
+ else:
314
+ tc = getattr(STATE, "source_timecode", None)
315
+ text = value.strip().rpartition("@")[0] if "@" in value else value.strip()
316
+ if not tc or len(text.split(":")) != 4:
317
+ return
318
+ start_tc, duration = tc
319
+ rate = fps
320
+ if "@" in value:
321
+ try:
322
+ rate = float(value.rpartition("@")[2])
323
+ except ValueError:
324
+ return
325
+ try:
326
+ start = parse_time(re.sub(r"[;.](\d+)$", r":\1", start_tc), rate)
327
+ except ValueError:
328
+ return
329
+ if not duration or seconds <= duration or seconds < start:
330
+ return
331
+ within = seconds - start
332
+ where = (f"{flag} {text} is {fmt_smpte_time(within, rate)} from the file's start"
333
+ if within <= duration else f"{flag} {text} is past the end of this {duration:.3f} s file even so")
334
+ prefix = (f"hh:mm:ss:ff times count from the file's first frame (00:00:00:00), not from the source's "
335
+ f"start timecode {start_tc}: ")
336
+ before = STATE.smpte_hint[len(prefix):] + "; " if STATE.smpte_hint and STATE.smpte_hint.startswith(prefix) else ""
337
+ STATE.smpte_hint = prefix + before + where
338
+
339
+
340
+ def signed_time_arg(value: str, flag: str, fps: Optional[float] = None) -> float:
341
+ """time_arg() for a flag that may also be negative (an offset, not a point in time): a single
342
+ leading '-'/'+' is taken as the sign and the rest goes through the ordinary time grammar, so
343
+ `--offset -00:00:02`, `--offset -1.5` and `--offset 0:02` all mean what they read as."""
344
+ text = (value or "").strip()
345
+ sign = 1.0
346
+ if text[:1] in "+-":
347
+ sign = -1.0 if text[0] == "-" else 1.0
348
+ text = text[1:].strip()
349
+ if not text:
350
+ die(f"{flag} {value!r}: not a time (use seconds, mm:ss, hh:mm:ss.ms, or hh:mm:ss:ff)")
351
+ return sign * time_arg(text, flag, fps)
352
+
353
+
354
+ def fmt_srt_time(seconds: float) -> str:
355
+ if seconds < 0:
356
+ seconds = 0.0
357
+ ms = int(round(seconds * 1000))
358
+ h, rem = divmod(ms, 3_600_000)
359
+ m, rem = divmod(rem, 60_000)
360
+ s, ms = divmod(rem, 1000)
361
+ return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
362
+
363
+
364
+ def fmt_smpte_time(seconds: float, fps: float) -> str:
365
+ """SMPTE non-drop-frame timecode 'hh:mm:ss:ff' for a real fps (not the fractional NTSC rates
366
+ -- 29.97/59.94 need drop-frame counting to stay wall-clock accurate, which this does not do)."""
367
+ if seconds < 0:
368
+ seconds = 0.0
369
+ whole_fps = int(round(fps))
370
+ # the frames are counted at the rate parse_time() reads the same text at (29.97 as
371
+ # 30000/1001): at 29.97 itself 06:00:00:00 came back as 05:59:59:29
372
+ total_frames = int(round(seconds * ntsc_rate(fps)))
373
+ frame = total_frames % whole_fps
374
+ secs_total = total_frames // whole_fps
375
+ h, rem = divmod(secs_total, 3600)
376
+ m, s = divmod(rem, 60)
377
+ return f"{h:02d}:{m:02d}:{s:02d}:{frame:02d}"
378
+
379
+
380
+ def escape_filter_path(path: str, *, bind: bool = True) -> str:
381
+ """Escape a file path for use as a filter option value (subtitles=, ass=, lut3d=file=, fontfile=, fontsdir=).
382
+
383
+ A filter option value is parsed twice: the graph parser splits filters on `,` / `;` and options
384
+ on `:`, then the filter's own option parser splits key=value pairs on `:` again. A character that
385
+ must survive both passes needs two levels of escaping, so a Windows drive letter `D:/x.srt` is
386
+ written `D\\\\:/x.srt`; with a single backslash the second pass still splits at the colon and
387
+ ffmpeg reads `/x.srt` as the next option (`Unable to parse "original_size" option value`).
388
+ On Windows backslashes are turned into forward slashes first (ffmpeg accepts them there); on
389
+ POSIX a backslash is part of the name and is escaped through both passes (#408); `,`, `;`, `[` and `]` are graph-level characters and survive with
390
+ one backslash. `'` is special: the graph parser also treats a quote as the start of a quoted
391
+ token, so a single `\\'` is consumed by the first pass and "Ryo's Mac/cues.srt" reaches the
392
+ filter as "Ryos Mac/cues.srt" (Unable to open ...). Three backslashes survive both passes
393
+ (measured on 6.1 and 7.1 with subtitles=, ass= and lut3d=file=).
394
+
395
+ `bind=False` escapes without recording the path as a plan input. The colour-emoji probe
396
+ uses that: its SRT lives in a temp directory that is gone before any plan is written.
397
+ """
398
+ if bind and os.path.isfile(path) and path not in STATE.plan_inputs:
399
+ STATE.plan_inputs.append(path) # a plan binds subtitle/LUT/font files too (review 6)
400
+ p = str(Path(path))
401
+ if _on_windows():
402
+ p = p.replace("\\", "/")
403
+ else:
404
+ # on POSIX a backslash is a character of the name (#408): turning it into `/` opened a
405
+ # different path, so it is escaped through both passes instead
406
+ p = p.replace("\\", "\\\\\\\\")
407
+ # A filter that opens its file through libavformat (subtitles=, metadata=print:file=) reads a
408
+ # relative `a:b.srt` or `d:e/c.srt` as protocol `a` or `d` ("Protocol not found"), and Path()
409
+ # above has dropped the `./` a caller wrote to say it is a file (#558). A relative path whose
410
+ # first segment has a colon gets it back; a filter that opens with fopen (lut3d, drawtext,
411
+ # ssim's stats_file) reads `./name` as the same file. An absolute path and a Windows path
412
+ # with a drive (`C:/x`, `C:x`) are left as they are: the drive's colon is not a scheme.
413
+ pure = PureWindowsPath(p) if _on_windows() else PurePosixPath(p)
414
+ if ":" in p.split("/", 1)[0] and not pure.is_absolute() and not pure.drive:
415
+ p = "./" + p
416
+ p = p.replace(":", "\\\\:")
417
+ p = p.replace("'", "\\\\\\'")
418
+ for ch in (",", ";", "[", "]"):
419
+ p = p.replace(ch, "\\" + ch)
420
+ # the graph parser trims unescaped whitespace at either end of a value (#408: a relative
421
+ # " lead.srt" opened "lead.srt"); both passes keep an escaped one
422
+ lead = len(p) - len(p.lstrip())
423
+ trail = len(p) - len(p.rstrip())
424
+ if lead or trail:
425
+ body = p[lead:len(p) - trail] if trail else p[lead:]
426
+ p = "".join("\\\\" + c for c in p[:lead]) + body + "".join("\\\\" + c for c in p[len(p) - trail:] if trail)
427
+ return p
428
+
429
+
430
+ # ------------------------------------------------------- both streams on one clock (#409)
431
+ #
432
+ # ffmpeg shifts every stream of an input by one constant (the file's start_time), so a filter graph
433
+ # sees a sound that starts 0.3 s after its picture at 0.3. A per-stream `PTS-STARTPTS` moved that
434
+ # sound 0.3 s early. cut.py's re-cut is the reference: both streams are cut on the same bounds,
435
+ # shifted by the same constant, and the audio is padded to the origin
436
+ # (docs/design-decisions.md, "Both streams of a segment shift by one constant").
437
+
438
+ def stream_starts(meta: Optional[Dict[str, Any]]) -> Tuple[float, float]:
439
+ """Where the video and the audio start on the clock a filter graph reads the input on (each
440
+ stream's start_time minus the file's); 0.0 for a stream whose start is unknown."""
441
+ from _common.emit import file_origin
442
+ meta = meta or {}
443
+ origin = file_origin(meta)
444
+ out = []
445
+ for kind in ("video", "audio"):
446
+ start = (meta.get(kind) or {}).get("start_time")
447
+ out.append(float(start) - origin if isinstance(start, (int, float)) else 0.0)
448
+ return out[0], out[1]
449
+
450
+
451
+ # Pads a sound that starts after the clock's 0 with silence from 0 (#409's rule for a re-encode),
452
+ # then cuts the result into frames of 4096 samples (p=0: the last one is not padded, so the length
453
+ # is the sound's). On FFmpeg 9 the pad handed the encoder the lead and the sound in one frame, and
454
+ # the FLAC encoder, which takes frames as they come, refused it ("invalid block size: 111305",
455
+ # #554's CI on 9.0.2; 6.1.1 splits the frames itself, so this was not seen locally)
456
+ PAD_SOUND_FROM_ZERO = "aresample=async=1:first_pts=0,asetnsamples=n=4096:p=0"
457
+
458
+
459
+ def late_sound_lead(meta: Optional[Dict[str, Any]]) -> float:
460
+ """How long after the file's origin the sound starts, when a sound-only output has to carry
461
+ that as silence: 0.0 for a lead of half a millisecond or less (sync.py's bound) and for a
462
+ source whose start is unknown. A WAV or FLAC has no start time, and an .m4a's is an edit a
463
+ decoder does not pad, so a sound-only output written without the lead plays that much early
464
+ against the picture it came from (audio.py, loudness.py; cut.py --accurate pads it too, A46)."""
465
+ lead = stream_starts(meta)[1]
466
+ return lead if lead > 0.0005 else 0.0
467
+
468
+
469
+ # The size of the decoded clip above which a tool that holds every frame (reverse, a boomerang)
470
+ # says `memory_heavy`.
471
+ HELD_FRAMES_WARN_BYTES = 2 * 1024 ** 3
472
+
473
+
474
+ def held_frames_bytes(v: Dict[str, Any], frames: float) -> int:
475
+ """About how many bytes `frames` decoded frames of the picture `v` (a probe()'s `video`) take:
476
+ the picture's size, its chroma planes (4:2:0 1.5x, 4:2:2 2x, 4:4:4 3x, an alpha plane one
477
+ more) and 2 bytes a sample above 8 bits. The one estimate reverse.py and loop.py --boomerang
478
+ warn from: reverse.py's was the clip's duration alone, so a 30 s 4K60 clip (tens of GB) got
479
+ no warning and a 61 s 320x180 one did (A174)."""
480
+ pix = str(v.get("pix_fmt") or "")
481
+ planes = 3.0 if "444" in pix or pix.startswith(("gbr", "rgb", "bgr")) else 2.0 if "422" in pix else 1.5
482
+ if pix.startswith(("yuva", "gbra", "rgba", "bgra", "argb", "abgr", "ya")):
483
+ planes += 1.0
484
+ depth = 2 if (v.get("bit_depth") or 8) > 8 else 1
485
+ return int((v.get("width") or 0) * (v.get("height") or 0) * planes * depth * max(0.0, frames))
486
+
487
+
488
+ def frame_rate(meta: Optional[Dict[str, Any]]) -> float:
489
+ """The video's frame rate as cut.py's grid takes it: r_frame_rate, else fps; 0.0 when unknown."""
490
+ v = (meta or {}).get("video") or {}
491
+ try:
492
+ num, _, den = str(v.get("r_frame_rate") or "").partition("/")
493
+ rate = float(num) / float(den or 1)
494
+ except (ValueError, ZeroDivisionError):
495
+ rate = 0.0
496
+ if not 0 < rate <= 240: # a time base (90000/1), not a rate
497
+ rate = float(v.get("fps") or 0.0)
498
+ return rate
499
+
500
+
501
+ def frame_durations(meta: Optional[Dict[str, Any]], rate: float) -> str:
502
+ """An `fps` filter at the video's own rate (r_frame_rate as a fraction when it is one), the
503
+ last filter of a graph whose frames sit on that rate's grid: it moves none of them, and gives
504
+ each frame its duration back. From FFmpeg 7.0 setpts sets every frame's duration to 0 and
505
+ leaves the frame rate unknown, so the last frame of a graph that ends after a setpts (av_trim)
506
+ was written with no duration and the picture read a frame short (3.967 s for 120 frames)."""
507
+ v = (meta or {}).get("video") or {}
508
+ try:
509
+ q = Fraction(str(v.get("r_frame_rate") or ""))
510
+ except (ValueError, ZeroDivisionError):
511
+ q = None
512
+ if q is not None and abs(float(q) - rate) < 1e-6:
513
+ return f"fps={q.numerator}/{q.denominator}"
514
+ return f"fps={rate:.6f}"
515
+
516
+
517
+ # a time written in milliseconds is the frame it reads back to (#653): the nearest frame when that
518
+ # is within half a millisecond either way, never one before the first; any other time is itself.
519
+ # For a position the caller names (a cut point, --at, a segment bound), not for a length
520
+ def on_frame(t: float, v0: float, rate: float) -> float:
521
+ return g if rate and (n := round((t - v0) * rate)) >= 0 and abs((g := v0 + n / rate) - t) <= 0.0005 else t
522
+
523
+
524
+ def grid_at_or_after(t: float, v0: float, rate: float) -> float:
525
+ """The time of the first frame at or after `t` on a constant-rate grid starting at `v0`."""
526
+ if not rate:
527
+ return t
528
+ return v0 + math.ceil((t - v0) * rate - 1e-6) / rate
529
+
530
+
531
+ def frame_window(start: Optional[float], end: Optional[float], meta: Optional[Dict[str, Any]],
532
+ half_open: bool = False) -> Optional[Tuple[Optional[float], Optional[float]]]:
533
+ """The two times a filter compares a frame's `t` with so that a window from `start` to `end`
534
+ seconds of `meta`'s picture holds the frames asked: half a frame before the first frame at or
535
+ after `start`, and half a frame after the last frame at or before `end` (`half_open`: half a
536
+ frame before the first frame at or after `end`, which is then outside). A bound written as
537
+ the time itself is compared with `t` on the frame it names: `{:.3f}` put frame 37 of a
538
+ 30000/1001 picture (1.234567 s) after a start of "1.235", and `t` is a double (pts x time
539
+ base) that is not always the number the text reads as (the frame at 1.4 s of a 25 fps MP4 is
540
+ not `<= 1.400`; FFmpeg 6.1.1). The grid is the one grid_at_or_after() counts on. None when
541
+ there is no grid to count on (no rate: a dry run's pending input; a picture probe() suspects
542
+ of a variable rate): the caller keeps the text it had. A bound of None stays None."""
543
+ v = (meta or {}).get("video") or {}
544
+ rate = frame_rate(meta)
545
+ if not rate or v.get("variable_frame_rate_suspected"):
546
+ return None
547
+ v0, half = stream_starts(meta)[0], 0.5 / rate
548
+ lo = None if start is None else grid_at_or_after(start, v0, rate) - half
549
+ if end is None:
550
+ hi = None
551
+ elif half_open:
552
+ hi = grid_at_or_after(end, v0, rate) - half
553
+ else:
554
+ hi = v0 + math.floor((end - v0) * rate + 1e-6) / rate + half
555
+ return lo, hi
556
+
557
+
558
+ def window_expr(start: Optional[float], end: Optional[float], meta: Optional[Dict[str, Any]],
559
+ half_open: bool = False) -> str:
560
+ """The expression that is true on the frames of frame_window(): `between(t,LO,HI)`, or
561
+ `gte(t,LO)` with no end. With no start the window opens at 0, as it always did. Without a
562
+ grid it is the millisecond text the tools wrote before."""
563
+ bounds = frame_window(start, end, meta, half_open)
564
+ if bounds is None:
565
+ lo = f"{start:.3f}" if start is not None else "0"
566
+ return f"gte(t,{lo})" if end is None else f"between(t,{lo},{end:.3f})"
567
+ lo = f"{bounds[0]:.6f}" if bounds[0] is not None else "0"
568
+ return f"gte(t,{lo})" if bounds[1] is None else f"between(t,{lo},{bounds[1]:.6f})"
569
+
570
+
571
+ def windowed_overlay_x(x: Any, window: str) -> str:
572
+ """An `overlay` x that puts the layer at `x` on the frames `window` is true on and off the
573
+ picture on every other frame. overlay's `enable` is not the main picture's alone: FFmpeg
574
+ evaluates it on each frame either input hands over, the layer's next one included, so a still
575
+ looped at 25 fps over a 30000/1001 picture was drawn from the frame before the window's
576
+ first to the frame before its last (36-66 for 37-67; FFmpeg 6.1.1). The position is
577
+ evaluated once per output frame with the main picture's `t`."""
578
+ return f"'if({window},{x},-w)'"
579
+
580
+
581
+ def av_trim(start: float, end: Optional[float], rate: float = 0.0, fill_gaps: bool = False) -> Tuple[str, str]:
582
+ """The video and the audio filters that cut one segment [start, end) of the graph clock out of
583
+ both streams and shift both by the same constant, so an offset between them survives; `end`
584
+ None runs to the stream's end. The picture's trim sits half a frame before each bound (the
585
+ bounds are frame times: grid_at_or_after), so no FFmpeg version rounds a boundary frame in or
586
+ out; the audio is padded to the segment's origin when it starts later. `fill_gaps` also fills
587
+ every later gap in the sound with silence, however short (aresample's default only fills one
588
+ longer than 0.1 s and stretches the sound by a sample a second for the rest)."""
589
+ half = 0.5 / rate if rate else 0.0
590
+ pad = "aresample=async=1:min_hard_comp=0.001:first_pts=0" if fill_gaps else "aresample=async=1:first_pts=0"
591
+ vend = f":end={end - half:.6f}" if end is not None else ""
592
+ aend = f":end={end:.6f}" if end is not None else ""
593
+ return (f"trim=start={start - half:.6f}{vend},setpts=PTS-{start:.6f}/TB",
594
+ f"atrim=start={start:.6f}{aend},asetpts=PTS-{start:.6f}/TB,{pad}")
595
+
596
+
597
+ def conform_filter(samples: int, rate: int) -> str:
598
+ """Pad with silence or trim to exactly `samples` at `rate` (#478): counted in samples, not in
599
+ seconds written to the millisecond, which left a result up to 24 samples (48 kHz) off. The
600
+ aformat pins the rate the count is in, so a resampler FFmpeg inserts sits ahead of the count."""
601
+ head = f"aformat=sample_rates={rate}," if rate else ""
602
+ return f"{head}apad=whole_len={samples},atrim=end_sample={samples}"
603
+
604
+
605
+ def conform_to_length(length: float, rate: int) -> str:
606
+ """Pad with silence or trim a track to `length` seconds of a timeline that starts at 0, to the
607
+ sample (#478, #493). The count is of samples, and sound that starts after 0 keeps its start
608
+ (apad and atrim=end_sample do not move timestamps): N samples from 0.3 s end 0.3 s past
609
+ `length`. The trim on the timestamp ends it there; half a sample of slack keeps the Nth sample
610
+ of a track that starts at 0. audio.py, grid.py, broll.py and multicam.py end their sound with
611
+ this; `atrim=duration={length:.3f}` cut 59244 samples (48 kHz) to 59232."""
612
+ return conform_filter(round(length * rate), rate) + f",atrim=end={length + 0.5 / rate:.6f}"
613
+
614
+
615
+ def conform_output_t(length: float, rate: int) -> str:
616
+ """The output `-t` beside conform_to_length(): `-t {length:.3f}` would cut the conformed sound
617
+ back to the millisecond, so the limit sits half a sample past the last one."""
618
+ return f"{length + 0.5 / rate:.6f}"
619
+
620
+
621
+ def length_output_t(length: float, rate: Optional[int], runs_on: bool = False) -> str:
622
+ """The output `-t` of a tool that leaves the sound's end to it (overlay.py, waveform.py,
623
+ loop.py, sync.py --replace-audio): the millisecond text they always wrote unless it cuts
624
+ samples off the track at `rate` (`-t 1.234` wrote 59244 samples at 48 kHz as 59232), and then
625
+ the length to the microsecond, which FFmpeg rounds to the nearest sample. `runs_on` is for
626
+ sound that goes on past the length (an endless apad, a loop's next repeat): there the
627
+ millisecond text is also left when it rounds up (`-t 1.235` wrote 59261 as 59280). No half
628
+ sample of slack as in conform_output_t(): this `-t` ends the picture too, and with the slack a
629
+ layer's frame that starts exactly at the end came through on a 1/60000 or 1/90000 time base
630
+ (FFmpeg 6.1.1). A rate of 0 or None (no sound, a dry run's pending input) keeps the
631
+ millisecond text."""
632
+ text = f"{length:.3f}"
633
+ if rate:
634
+ def names(micro: int) -> int:
635
+ # the samples FFmpeg makes of a -t of `micro` microseconds: a rescale that rounds a
636
+ # half up, where Python's round() takes it to the even count (0.005 s at 44.1 kHz is
637
+ # 220.5 samples: 221 written, round() says 220)
638
+ return (micro * rate + 500_000) // 1_000_000
639
+ written, asked = names(round(float(text) * 1_000_000)), round(length * rate)
640
+ if written < asked or (runs_on and written != asked):
641
+ # the microsecond text is a rounding too (2.00001042 s is 96001 samples at 48 kHz and
642
+ # "2.000010" names 96000): the microsecond nearest the length, moved by whole
643
+ # microseconds until it names the count asked. A microsecond is a twentieth of a
644
+ # sample at 48 kHz, so this is a step or two, not conform_output_t()'s half sample
645
+ micro = round(length * 1_000_000)
646
+ while names(micro) < asked:
647
+ micro += 1
648
+ while names(micro) > asked:
649
+ micro -= 1
650
+ return f"{micro // 1_000_000}.{micro % 1_000_000:06d}"
651
+ return text
652
+
653
+
654
+ def silence_filter(rate: Optional[int], lead: Optional[float] = None, tail: Optional[float] = None) -> str:
655
+ """Silence of `lead` seconds ahead of a track and/or `tail` seconds after it (pad.py,
656
+ freeze.py). An amount in whole milliseconds is written as it always was (`adelay=MS:all=1`,
657
+ `apad=pad_dur=S.mmm`), the millisecond rounded, not cut: int(1.001 * 1000) is 1000. One that
658
+ is not is counted in samples at `rate`, pinned by an aformat as in conform_filter():
659
+ `adelay=234` and `apad=pad_dur=0.234` for 0.23425 s left the sound 12 samples short at 48 kHz.
660
+ A rate of 0 or None (a dry run's pending input) keeps the millisecond form."""
661
+ amounts = [v for v in (lead, tail) if v is not None]
662
+ if rate and any(round(v * rate) != round(round(v, 3) * rate) for v in amounts):
663
+ parts = [f"aformat=sample_rates={rate}"]
664
+ if lead:
665
+ parts.append(f"adelay={round(lead * rate)}S:all=1")
666
+ if tail:
667
+ parts.append(f"apad=pad_len={round(tail * rate)}")
668
+ return ",".join(parts)
669
+ parts = []
670
+ if lead is not None:
671
+ parts.append(f"adelay={round(lead * 1000)}:all=1")
672
+ if tail is not None:
673
+ parts.append(f"apad=pad_dur={tail:.3f}")
674
+ return ",".join(parts)
675
+
676
+
677
+ def tpad_length(seconds: float, meta: Optional[Dict[str, Any]]) -> float:
678
+ """How long the picture `tpad=start_duration={seconds:.3f}` puts ahead of `meta`'s clip is:
679
+ tpad adds whole frames, the nearest count to the text it is given (0.23425 s at 25 fps is
680
+ written "0.234" and becomes 6 frames, 0.240 s). A sound delayed by `seconds` itself would
681
+ start up to half a frame before or after the picture it belongs to; delayed by this length it
682
+ moves with it (both streams of a clip shift by one constant: #409). `seconds` as it is when
683
+ there is no rate to count frames at (a dry run's pending input) or probe() suspects a
684
+ variable one."""
685
+ v = (meta or {}).get("video") or {}
686
+ rate = frame_rate(meta)
687
+ if not rate or v.get("variable_frame_rate_suspected"):
688
+ return seconds
689
+ try:
690
+ exact = Fraction(str(v.get("r_frame_rate") or ""))
691
+ except (ValueError, ZeroDivisionError):
692
+ exact = None
693
+ if exact is None or abs(float(exact) - rate) > 1e-6:
694
+ exact = Fraction(rate).limit_denominator(1001)
695
+ frames = math.floor(Fraction(f"{seconds:.3f}") * exact + Fraction(1, 2)) # a half rounds up, as av_rescale does
696
+ return float(frames / exact)
697
+
698
+
699
+ def av_clip_length(meta: Optional[Dict[str, Any]], fps: float) -> float:
700
+ """The one length a clip holds once both streams start at its first frame (av_trim from the
701
+ video's start): the video's, or where the sound ends when it runs more than a frame past the
702
+ picture (narration is never cut; an AAC tail adds no frame). The container duration is only the
703
+ fallback when the video's length is unknown (a pending input)."""
704
+ meta = meta or {}
705
+ v = (meta.get("video") or {}).get("duration")
706
+ a = (meta.get("audio") or {}).get("duration")
707
+ if not v:
708
+ return input_length(meta) # a file that states no length at all is refused, not 0 s long (#491)
709
+ if a:
710
+ v0, a0 = stream_starts(meta)
711
+ a = a + a0 - v0 # where the sound ends, counted from the first frame
712
+ if a and fps and a > v + 1.0 / fps:
713
+ return a
714
+ return v
715
+
716
+
717
+ def cfr_args(meta: Optional[Dict[str, Any]], fps: Optional[float] = None) -> List[str]:
718
+ """Force a constant frame rate on output when the source looks VFR (or fps is given).
719
+
720
+ VFR sources (phone/screen recordings) drift against audio after cuts and joins,
721
+ so every re-encoding script passes this to conform them automatically.
722
+ """
723
+ v = (meta or {}).get("video") or {}
724
+ if fps is None and not v.get("variable_frame_rate_suspected"):
725
+ return []
726
+ rate = fps or v.get("fps") or 30.0
727
+ rate = round(rate) if abs(rate - round(rate)) < 0.02 else rate
728
+ # a rate the caller asked for relabels the start timecode, counted at the new rate (#470:
729
+ # proxy/denoise/crop/redact/sphere/straighten --fps 50 kept 01:00:00:12, a 25 fps label)
730
+ from _common.timeline import output_timecode_args
731
+ relabel = output_timecode_args(meta, 0.0, rate) if fps and v.get("fps") and abs(float(fps) - float(v["fps"])) > 0.01 else []
732
+ return ["-fps_mode", "cfr", "-r", f"{rate:g}"] + relabel
733
+
734
+
735
+ def cfr_filter(meta: Optional[Dict[str, Any]], fps: Optional[float] = None, seek: float = 0.0) -> str:
736
+ """The `fps` filter that puts the picture on the grid cfr_args() delivers, as the last filter of
737
+ the video chain; "" when cfr_args() forces no rate. The encoder line's `-fps_mode cfr -r` alone
738
+ let a frame fall up to about two frames behind its slot before it dropped one, so a VFR clip
739
+ conformed at its average rate showed its picture up to 56 ms after its sound (#512); the
740
+ filter puts each frame on the slot its time rounds to (within half a frame of it; a slot in a
741
+ gap keeps the frame before it). The encoder line keeps cfr_args(), which then
742
+ moves no frame.
743
+
744
+ `seek` is an output-side `-ss` that follows the conform (cut.py's and fit.py --method trim's
745
+ margin after an input seek): the grid is laid from it instead (#538). The filter lays its grid
746
+ from the first frame on the clock, its output's time base is one frame, and the output seek
747
+ then landed between two slots, which the encoder line's rate rounded again: on a 27 fps
748
+ average clip `cut.py --start 0.45` put its picture 24 ms after its sound, 33 ms at 0.2. The
749
+ picture is moved so the seek is its 0, conformed from there (`start_time=0`: a frame takes the
750
+ slot its time rounds to and stays until the next frame's slot, so the last frame before the
751
+ seek fills the slots up to the first frame after it), and moved back on a
752
+ microsecond time base, so the seek lands on a slot and the output's frames sit on the grid
753
+ from 0. The setpts after the conform leaves its frames no duration from FFmpeg 7.0; the
754
+ encoder line's `-fps_mode cfr`, which cfr_args() always gives with this filter, sets each to
755
+ one frame."""
756
+ args = cfr_args(meta, fps)
757
+ if not args:
758
+ return ""
759
+ rate = args[args.index("-r") + 1]
760
+ if seek > 0:
761
+ return (f"setpts=PTS-{seek:.6f}/TB,fps={rate}:start_time=0,"
762
+ f"settb=AVTB,setpts=PTS+{seek:.6f}/TB")
763
+ return f"fps={rate}"
764
+
765
+
766
+ def with_cfr(chain: str, meta: Optional[Dict[str, Any]], fps: Optional[float] = None) -> str:
767
+ """`chain` (a -vf value or one filtergraph chain) with cfr_filter() appended when there is one.
768
+ A -vf value that is a graph of its own (drawn_chain()'s split/maskedmerge) gets it first
769
+ instead: maskedmerge, like overlay, ends its output at its last frame's start, and an fps
770
+ filter after it lost the last frame (graphics.py --template chapter: 3.963 s of 4)."""
771
+ return chain_with_rate(chain, cfr_filter(meta, fps))
772
+
773
+
774
+ def chain_with_rate(chain: str, rate_filter: str) -> str:
775
+ """`chain` with an `fps` filter `rate_filter` placed as with_cfr() places cfr_filter(): last in
776
+ a plain chain, first in a -vf that is a graph of its own (fit/export's blur pad, a drawn pad
777
+ with chroma), whose overlay or maskedmerge ends its output at its last frame's start on FFmpeg
778
+ 6.1 and lost the last frame to an fps filter after it. For a rate that is not cfr_args()'s
779
+ own (export.py's preset and platform rates)."""
780
+ if not rate_filter:
781
+ return chain
782
+ if ";" in chain:
783
+ return f"{rate_filter},{chain}"
784
+ return f"{chain},{rate_filter}" if chain else rate_filter
785
+
786
+
787
+ def graph_with_cfr(graph: str, label: str, meta: Optional[Dict[str, Any]],
788
+ fps: Optional[float] = None) -> Tuple[str, str]:
789
+ """A -filter_complex graph and the video output label to map, with cfr_filter() after that
790
+ label when there is one: (graph + ";[v]fps=R[vcfr]", "[vcfr]"), else both unchanged."""
791
+ f = cfr_filter(meta, fps)
792
+ if not f:
793
+ return graph, label
794
+ bare = label.strip("[]")
795
+ return f"{graph};[{bare}]{f}[{bare}cfr]", f"[{bare}cfr]"
796
+
797
+
798
+ def cfr_at_input(graph: str, meta: Optional[Dict[str, Any]], fps: Optional[float] = None, src: str = "[0:v]",
799
+ origin: Optional[float] = None) -> str:
800
+ """A -filter_complex graph with cfr_filter() on its main picture as it is decoded (`src`, which
801
+ the graph reads once), for a graph that composites onto that picture and moves no frame in
802
+ time. After an overlay the conform comes too late: FFmpeg 6.1's overlay ends its output at its
803
+ last frame's start, so an fps filter there lost the last frame (3.963 s of a 4 s picture).
804
+ With `origin` (where the picture starts on the graph's clock, stream_starts()) the picture is
805
+ moved to start at 0 ahead of the conform, so the grid is laid from its first frame, and the
806
+ conformed frames get a microsecond time base, for a graph that cuts the picture on that grid
807
+ (freeze.py, #523): the caller counts the picture's times from its own start. The fps
808
+ filter's grid starts at the clock's 0, so a picture that starts 50 ms in was cut a frame off
809
+ the times computed from its start, and its output's time base is one frame, to which `trim`
810
+ rescales its bound (a half-frame bound written to the microsecond, 3.907407 at 27 fps, became
811
+ the frame at 3.888889 and cut it). The picture is not moved back after the conform: from
812
+ FFmpeg 7.0 setpts leaves its output frames no duration and no rate, and a tpad after it (the
813
+ hold) cloned nothing: 109 frames for 135 on 7.1."""
814
+ f = cfr_filter(meta, fps)
815
+ if not f:
816
+ return graph
817
+ if graph.count(src) != 1:
818
+ # a graph that read the picture twice, or not at all, would go unconformed or not parse
819
+ raise ValueError(f"cfr_at_input: the graph reads {src} {graph.count(src)} times, not once")
820
+ if origin is not None:
821
+ f = f"setpts=PTS-{origin:.6f}/TB,{f},settb=AVTB" if origin else f"{f},settb=AVTB"
822
+ return f"{src}{f}[cfrin];" + graph.replace(src, "[cfrin]")
823
+
824
+
825
+ def atempo_lead(sample_rate: Any) -> int:
826
+ """How many samples of its input `atempo` leaves out at the start: half its window, which is
827
+ the power of two at or above sample_rate / 24 (2048 at 44.1 and 48 kHz, so 1024 samples, 21 ms
828
+ at 48 kHz). Its output opens on the sample half a window in (measured at 8, 22.05, 32, 44.1,
829
+ 48 and 96 kHz on FFmpeg 6.1.1), so every sound after it is that much early: speedramp.py's beeps
830
+ came 21 ms early at 1x and 40 ms at 0.5x, and fit.py --method speed's the same (#523). 0 when
831
+ the rate is not known (a dry run's pending input)."""
832
+ try:
833
+ rate = int(sample_rate or 0)
834
+ except (TypeError, ValueError):
835
+ return 0
836
+ window = rate // 24
837
+ if window < 1:
838
+ return 0
839
+ pot = 1 << (window.bit_length() - 1)
840
+ return (pot * 2 if pot < window else pot) // 2
841
+
842
+
843
+ def atempo_chain_with_lead(stages: List[str], sample_rate: Any) -> str:
844
+ """`atempo` stages (each value as written) led by silence and trimmed after, so the output
845
+ keeps the input's timing from its first sample: a beep at 0.5 s of a 1x stage came out at
846
+ 0.479 s (FFmpeg 6.1.1). Each stage leaves out atempo_lead() samples of its own input, which
847
+ are the earlier stages' tempo product times that many of the chain's input, so one lead of
848
+ their sum goes in front of the first stage: an `adelay` between two stages made FFmpeg 6.1.1
849
+ fail a graph that joins the result with `concat` ("Invalid data found when processing
850
+ input", speedramp.py with a 0.25x segment). That lead alone put the chain's first window,
851
+ which atempo fades in, over the input's first 21 ms: a 10 ms attack there came out 7 dB down
852
+ at 1x and was gone at 2x (#541 review). So one whole window more of silence goes in front
853
+ (as many of the chain's input samples as leave a window of it ahead of every stage), and
854
+ that much of the output, at the chain's tempo, is cut off again and its timestamps moved
855
+ back by it, so a track that starts after 0 keeps its start. The bare stages when the rate is
856
+ not known (a dry run's pending input)."""
857
+ lead = atempo_lead(sample_rate)
858
+ chain = ",".join(f"atempo={value}" for value in stages)
859
+ if not lead:
860
+ return chain
861
+ total, product, widest = 0.0, 1.0, 1.0
862
+ for value in stages:
863
+ total += lead * product
864
+ product *= float(value)
865
+ widest = max(widest, product)
866
+ extra = round(2 * lead * widest) # a window of silence ahead of the stage that shrinks it most
867
+ cut = round(extra / product)
868
+ return (f"adelay={round(total) + extra}S:all=1,{chain},"
869
+ f"atrim=start_sample={cut},asetpts=PTS-{cut}/SR/TB")
870
+
871
+
872
+ def delivered_rate(meta: Optional[Dict[str, Any]], fps: Optional[float] = None) -> Optional[float]:
873
+ """The constant rate cfr_args() forces on the output (its -r), or None when it forces none and
874
+ the output keeps the source's rate -- what a start timecode is counted at
875
+ (timeline.output_timecode_args)."""
876
+ args = cfr_args(meta, fps)
877
+ return float(args[-1]) if args else None
878
+
879
+
880
+ # how far before a cut an input seek lands, so a start inside the B-frame reorder delay before a
881
+ # keyframe still decodes from the keyframe BEFORE it; the margin is dropped on the output side
882
+ # (cut.py, sync.py --trim-second)
883
+ SEEK_MARGIN = 1.0
884
+
885
+
886
+ # ------------------------------------------------------- VideoToolbox (--hw)
887
+ #
888
+ # CRF -> VideoToolbox -q:v (1-100, higher = better): at each CRF the highest -q:v whose SSIM matched
889
+ # the CPU line's (x264/x265 medium) across the clips of tests/bench_vt.py -- synthetic CG, fractal
890
+ # and grain plus iPhone 17 Pro 1080p (M3, FFmpeg 9.0.2), so a GPU encode never measures below the
891
+ # CPU one. HDR has its own curve: its CPU line is x265 Main10 at CRF+2, and the Main10 VideoToolbox
892
+ # line needs ~11-15 less -q:v for that SSIM (the SDR curve wrote HLG phone footage at 6-8x x265's
893
+ # bytes). Matched quality costs 1.1-2.9x the bytes of x264/x265 on SDR and 1.9-3.5x on HDR --
894
+ # which is why --hw is opt-in and delivery presets stay on the CPU (docs/design-decisions.md).
895
+
896
+
897
+ def vt_quality(codec: str, crf: int, hdr: bool = False) -> int:
898
+ base, slope = (63.0, 1.6) if hdr else (75.0, 2.2) if codec == "h264" else (78.0, 2.0)
899
+ return max(1, min(100, int(round(base - slope * (crf - 18)))))
900
+
901
+
902
+ def _vt_bt709(codec: str) -> List[str]:
903
+ """BT.709 tags for a VideoToolbox SDR encode. From FFmpeg 7.1 the -colorspace output options
904
+ drive a real matrix conversion on an untagged source (see bt709_tag_args), and VideoToolbox has
905
+ no -x264-params VUI route; a bitstream filter writes the VUI after encoding, which the filter
906
+ graph never sees (measured: 49.9 dB PSNR tag-neutral vs 23.8 dB through the output options).
907
+ It is used on every version, not only >= 7.1: it is tag-only everywhere, and a git build of
908
+ 7.1 reads as (7, 0) from its libavutil major, which would otherwise take the converting path."""
909
+ return ["-bsf:v", f"{codec}_metadata=colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1"]
910
+
911
+
912
+ def source_transfer(v: Dict[str, Any]) -> str:
913
+ """The transfer a 10-bit re-encode of a BT.2020 / HDR source is tagged with: the source's own
914
+ tag, or, when it has none, what probe() read it as. BT.2020 primaries with no transfer tag are
915
+ `hdr_format` "BT.2020 SDR" (not an HDR signal), so they are tagged bt2020-10, the SDR curve
916
+ BT.2020 defines; through 3.8.8 every such re-encode came out tagged HLG (audit A153). An
917
+ HDR signal with no transfer tag (Dolby Vision whose base layer is untagged) keeps the HLG
918
+ default it always had."""
919
+ return v.get("color_transfer") or ("arib-std-b67" if v.get("hdr_signal") else "bt2020-10")
920
+
921
+
922
+ def _vt_args(codec: str, crf: int, meta: Optional[Dict[str, Any]], keep_bt709: bool) -> Optional[List[str]]:
923
+ """VideoToolbox encoder options for `codec`, or None (with a note in STATE.hw_notes) when the
924
+ request stays on the CPU: no VideoToolbox encoder for the codec, this machine cannot, or the
925
+ ffmpeg build lacks it."""
926
+ name = {"h264": "h264_videotoolbox", "hevc": "hevc_videotoolbox", "prores": "prores_videotoolbox"}.get(codec)
927
+ reason = None if name else f"no VideoToolbox encoder for {codec}"
928
+ reason = reason or hw_platform_reason()
929
+ if not reason and name not in ffmpeg_encoders():
930
+ unread = ffmpeg_list_error("encoders")
931
+ # an encoder list that could not be read says nothing about the build: name the read
932
+ # failure, not a missing encoder (the read itself is a ffmpeg_list_unreadable warning)
933
+ reason = (f"{name} could not be confirmed (this ffmpeg build's encoder list could not be read: {unread})" if unread
934
+ else f"this ffmpeg build has no {name}")
935
+ if reason:
936
+ note = f"{reason}; encoded on the CPU"
937
+ if note not in STATE.hw_notes:
938
+ STATE.hw_notes.append(note)
939
+ return None
940
+ v = (meta or {}).get("video") or {}
941
+ hdr = bool(v.get("bt2020_or_hdr"))
942
+ hdr_tags = ["-colorspace", hdr_line_matrix(v), "-color_primaries", v.get("color_primaries") or "bt2020",
943
+ "-color_trc", source_transfer(v)]
944
+ if codec == "prores":
945
+ return ["-c:v", name, "-profile:v", "hq", "-pix_fmt", "p210le"] + (hdr_tags if hdr else [])
946
+ # The HDR curve was fitted on the Main10 HEVC line; an 8-bit H.264 line (an export preset on
947
+ # an HDR source) replaces x264 at the same CRF and keeps the H.264 curve.
948
+ q = str(vt_quality(codec, crf, hdr and codec == "hevc"))
949
+ if codec == "h264":
950
+ return ["-c:v", name, "-q:v", q, "-profile:v", "high", "-pix_fmt", "yuv420p", "-movflags", "+faststart"] + \
951
+ (_vt_bt709("h264") if keep_bt709 else [])
952
+ if hdr:
953
+ # Measured on FFmpeg 9.0: HDR10 mastering-display and content-light side data carry through
954
+ # hevc_videotoolbox exactly as through libx265 (test_hw_hdr10_side_data_survives).
955
+ return ["-c:v", name, "-q:v", q, "-profile:v", "main10", "-pix_fmt", "p010le", "-tag:v", "hvc1"] + hdr_tags + ["-movflags", "+faststart"]
956
+ return ["-c:v", name, "-q:v", q, "-pix_fmt", "yuv420p", "-tag:v", "hvc1", "-movflags", "+faststart"] + \
957
+ (_vt_bt709("hevc") if keep_bt709 else [])
958
+
959
+
960
+ # An LGPL ffmpeg (the kind a desktop app ships) has VideoToolbox but neither libx264 nor libx265.
961
+ # There the CPU line cannot run at all, so VideoToolbox is the only encoder there is and takes the
962
+ # job without --hw (#314). Only when the encoder list was read and lacks the CPU encoder, and only
963
+ # where --hw would run; a build that has libx264 never gets here (docs/design-decisions.md).
964
+ _VT_FOR_CPU = {"libx264": "h264_videotoolbox", "libx265": "hevc_videotoolbox"}
965
+
966
+
967
+ def _vt_in_place_of(cpu_encoder: Optional[str]) -> Optional[str]:
968
+ """The VideoToolbox encoder that takes over from `cpu_encoder` because this ffmpeg build lacks
969
+ it, else None: not when --hw already decided, nor under an explicit --no-hw (the caller asked
970
+ for the CPU), nor on a machine VideoToolbox cannot run on. The platform is asked before the
971
+ encoder list, so Linux and Windows never read it for this. An empty list (ffmpeg's could not
972
+ be read) proves nothing is missing."""
973
+ vt = _VT_FOR_CPU.get(cpu_encoder or "")
974
+ if vt is None or STATE.hw or STATE.hw_source == "flag" or hw_platform_reason() is not None:
975
+ return None
976
+ have = ffmpeg_encoders()
977
+ return vt if have and cpu_encoder not in have and vt in have else None
978
+
979
+
980
+ def _note_vt_in_place_of(cpu_encoder: str, vt: str) -> None:
981
+ if cpu_encoder not in STATE.hw_auto:
982
+ STATE.hw_auto.append(cpu_encoder)
983
+ note = f"{cpu_encoder} is not in this ffmpeg build, so this encode ran on {vt} (VideoToolbox) instead"
984
+ if note not in STATE.hw_notes:
985
+ STATE.hw_notes.append(note)
986
+
987
+
988
+ def _maybe_hw(codec: str, crf: int, meta: Optional[Dict[str, Any]], keep_bt709: bool, cpu: List[str]) -> List[str]:
989
+ """`cpu` unchanged unless --hw / $FFMPEG_SKILL_HW is on and VideoToolbox can take `codec`, or
990
+ unless the build has no CPU encoder for it (_vt_in_place_of); the --hw swap is remembered so
991
+ run() can put the CPU line back if the GPU refuses the job. A build without the CPU encoder
992
+ has no line to put back, so nothing is remembered for it."""
993
+ cpu_encoder = cpu[cpu.index("-c:v") + 1] if "-c:v" in cpu else None
994
+ vt_name = _vt_in_place_of(cpu_encoder)
995
+ if not STATE.hw and vt_name is None:
996
+ return cpu
997
+ vt = _vt_args(codec, crf, meta, keep_bt709)
998
+ if vt is None:
999
+ return cpu
1000
+ if vt_name:
1001
+ _note_vt_in_place_of(cpu_encoder or "", vt_name)
1002
+ return vt
1003
+ # a copy: a caller that edits the returned line in place (export.py strips -movflags) must
1004
+ # not edit the recorded slice with it, or restate_last_swap() never sees the line as built
1005
+ STATE.hw_swaps.append((list(vt), cpu))
1006
+ return vt
1007
+
1008
+
1009
+ _CPU_TO_CODEC = {"libx264": "h264", "libx265": "hevc", "prores_ks": "prores"}
1010
+
1011
+
1012
+ def hw_preset_video(video: List[str], meta: Optional[Dict[str, Any]], *, bt709: bool) -> List[str]:
1013
+ """export.py's fixed-preset encoder line moved to VideoToolbox (same codec, the preset's -crf
1014
+ mapped to -q:v, its -r kept); unchanged -- with the reason noted -- when that cannot apply.
1015
+ Called under --hw, and for a preset whose libx264/libx265 this build lacks (_vt_in_place_of),
1016
+ where it is the only encoder there is; otherwise it returns `video` untouched.
1017
+
1018
+ `bt709`: whether export.py tags this preset's CPU line BT.709 (every fixed preset but prores,
1019
+ whose master keeps the source's tags). The VideoToolbox line writes the format the CPU preset
1020
+ writes: an h264/hevc preset is 8-bit with BT.709 tags whatever the source (on an HDR source it
1021
+ says so in a note, as without --hw), so it is built as for an SDR source -- not the Main10 HDR
1022
+ line, which would make the GPU file and its CPU fallback different formats."""
1023
+ enc = video[video.index("-c:v") + 1] if "-c:v" in video else None
1024
+ codec = _CPU_TO_CODEC.get(enc or "")
1025
+ if codec is None:
1026
+ return video
1027
+ vt_name = _vt_in_place_of(enc)
1028
+ if not STATE.hw and vt_name is None:
1029
+ return video
1030
+ crf = int(video[video.index("-crf") + 1]) if "-crf" in video else 18
1031
+ vt = _vt_args(codec, crf, meta if codec == "prores" else None, bt709)
1032
+ if vt is None:
1033
+ return video
1034
+ vt = strip_movflags(vt) # export adds it
1035
+ if "-r" in video:
1036
+ vt += ["-r", video[video.index("-r") + 1]]
1037
+ if vt_name:
1038
+ _note_vt_in_place_of(enc or "", vt_name)
1039
+ return vt
1040
+ # the CPU line export would have written: the preset's own options plus the BT.709 tags export
1041
+ # adds to it (only to the CPU line), so a GPU->CPU fallback is tagged exactly like a CPU run
1042
+ STATE.hw_swaps.append((list(vt), list(video) + (bt709_tag_args(enc) if bt709 else [])))
1043
+ return vt
1044
+
1045
+
1046
+ def strip_movflags(args: List[str]) -> List[str]:
1047
+ return [a for i, a in enumerate(args) if not (a == "-movflags" or (i and args[i - 1] == "-movflags"))]
1048
+
1049
+
1050
+ def restate_last_swap(before: List[str], after: List[str]) -> None:
1051
+ """A caller that edits an encoder line after encoder_args() returned it (export.py strips
1052
+ -movflags) restates the recorded swap, so run()'s GPU->CPU fallback still finds the slice."""
1053
+ if STATE.hw_swaps and STATE.hw_swaps[-1][0] == before:
1054
+ STATE.hw_swaps[-1] = (list(after), strip_movflags(STATE.hw_swaps[-1][1]))
1055
+
1056
+
1057
+ def hdr_tag_args(meta: Optional[Dict[str, Any]]) -> List[str]:
1058
+ """The colour tags a 10-bit line that keeps a BT.2020 / HDR source writes as output options: the
1059
+ matrix it converted with (hdr_line_matrix), and the source's primaries and transfer."""
1060
+ v = (meta or {}).get("video") or {}
1061
+ return ["-colorspace", hdr_line_matrix(v), "-color_primaries", v.get("color_primaries") or "bt2020", "-color_trc", source_transfer(v)]
1062
+
1063
+
1064
+ def encoder_args(codec: str, crf: int, preset: str, meta: Optional[Dict[str, Any]] = None, keep_bt709: bool = True) -> List[str]:
1065
+ """encoder options for `codec` (_cpu_encoder_args), on VideoToolbox when --hw asks and it can."""
1066
+ return _maybe_hw(codec, crf, meta, keep_bt709, _cpu_encoder_args(codec, crf, preset, meta, keep_bt709))
1067
+
1068
+
1069
+ def _cpu_encoder_args(codec: str, crf: int, preset: str, meta: Optional[Dict[str, Any]] = None, keep_bt709: bool = True) -> List[str]:
1070
+ """The one place that turns (--codec, --quality, --preset, source) into encoder options.
1071
+
1072
+ h264 -> x264 8-bit BT.709 (refuses HDR: 8-bit H.264 cannot carry it); hevc -> x265, Main10
1073
+ with the source's tags for HDR, 8-bit BT.709 otherwise; av1 -> SVT-AV1 (libaom fallback),
1074
+ 10-bit for HDR; prores -> ProRes 422 HQ, source tags kept. 1.8: chosen by --codec; without
1075
+ it video_args() does what it always did (x264 for SDR, x265 Main10 for HDR).
1076
+ """
1077
+ v = (meta or {}).get("video") or {}
1078
+ hdr = bool(v.get("bt2020_or_hdr"))
1079
+ cs = hdr_line_matrix(v)
1080
+ prim = v.get("color_primaries") or "bt2020"
1081
+ trc = source_transfer(v)
1082
+ hdr_tags = hdr_tag_args(meta)
1083
+ if codec == "h264":
1084
+ if hdr:
1085
+ die(f"--codec h264 cannot carry HDR ({v.get('hdr_format') or 'BT.2020'}): 8-bit H.264 is SDR only",
1086
+ hint="run color.py --to-sdr first, or use --codec hevc / av1 / prores, which keep the source's HDR")
1087
+ return _x264_raw(crf, preset, keep_bt709)
1088
+ if codec == "hevc":
1089
+ if hdr:
1090
+ x265 = f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}:range=limited:hdr10-opt=1{hdr10_x265_params(v)}" if trc == "smpte2084" else f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}"
1091
+ return ["-c:v", "libx265", "-preset", preset, "-crf", str(_clamped_crf("libx265", crf + 2, 51, crf)), "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1",
1092
+ "-x265-params", x265] + hdr_tags + ["-movflags", "+faststart"]
1093
+ params, extra = _sdr_bt709("libx265") if keep_bt709 else ("", [])
1094
+ return ["-c:v", "libx265", "-preset", preset, "-crf", str(crf), "-pix_fmt", "yuv420p", "-tag:v", "hvc1",
1095
+ "-x265-params", "log-level=error" + (":" + params if params else "")] + extra + ["-movflags", "+faststart"]
1096
+ if codec == "av1":
1097
+ pix = "yuv420p10le" if hdr else "yuv420p"
1098
+ if "libsvtav1" in ffmpeg_encoders():
1099
+ args = ["-c:v", "libsvtav1", "-preset", str(SVT_PRESET.get(preset, 6)), "-crf", str(_clamped_crf("libsvtav1", crf, 63, crf)), "-pix_fmt", pix]
1100
+ if hdr:
1101
+ svt = hdr10_svtav1_params(v)
1102
+ args += (["-svtav1-params", svt] if svt else []) + hdr_tags
1103
+ elif keep_bt709:
1104
+ params, extra = _sdr_bt709("libsvtav1")
1105
+ args += (["-svtav1-params", params] if params else []) + extra
1106
+ elif "libaom-av1" in ffmpeg_encoders():
1107
+ # recorded: libaom is the slower AV1 encoder with its own CRF scale and speed setting,
1108
+ # so the same --quality does not give the file SVT-AV1 would have
1109
+ record_fallback("--codec av1: this ffmpeg build has no libsvtav1 (SVT-AV1), so libaom-av1 encodes instead "
1110
+ "(slower; -cpu-used 6, its own CRF scale)", "av1_encoder_libaom", wanted="libsvtav1", used="libaom-av1")
1111
+ args = ["-c:v", "libaom-av1", "-crf", str(_clamped_crf("libaom-av1", crf, 63, crf)), "-b:v", "0", "-cpu-used", "6", "-row-mt", "1", "-pix_fmt", pix]
1112
+ args += hdr_tags if hdr else (_sdr_bt709("libaom-av1")[1] if keep_bt709 else [])
1113
+ else:
1114
+ _refuse_missing_encoder("av1", ["libsvtav1", "libaom-av1"], "an AV1 encoder (libsvtav1 or libaom-av1)",
1115
+ "install an ffmpeg built with SVT-AV1 (most distribution builds are), or use --codec hevc")
1116
+ return args + ["-movflags", "+faststart"]
1117
+ if codec == "prores":
1118
+ if "prores_ks" not in ffmpeg_encoders():
1119
+ _refuse_missing_encoder("prores", ["prores_ks"], "the prores_ks encoder", None)
1120
+ return ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0", "-pix_fmt", "yuv422p10le"] + (hdr_tags if hdr else [])
1121
+ die(f"unknown --codec {codec!r} (one of {', '.join(CODECS)})")
1122
+ return []
1123
+
1124
+
1125
+ def hdr10_x265_params(v: Dict[str, Any]) -> str:
1126
+ """The source's HDR10 static metadata as x265 options (":master-display=...:max-cll=..."), or "".
1127
+ FFmpeg before 7.0 does not pass the decoded frames' mastering-display / content-light side data
1128
+ to libx265, so without these a 6.1 re-encode wrote PQ video with neither (#401). Given on 7+ too,
1129
+ where they restate what FFmpeg would pass. x265 units: chromaticity 0.00002, luminance 0.0001 cd/m2."""
1130
+ md, cl = _hdr10_parts(v)
1131
+ out = ""
1132
+ if md:
1133
+ c = lambda k: round(md[k] * 50000)
1134
+ out += (f":master-display=G({c('green_x')},{c('green_y')})B({c('blue_x')},{c('blue_y')})R({c('red_x')},{c('red_y')})"
1135
+ f"WP({c('white_point_x')},{c('white_point_y')})L({round(md['max_luminance'] * 10000)},{round(md['min_luminance'] * 10000)})")
1136
+ if cl:
1137
+ out += f":max-cll={cl['max_content']},{cl['max_average']}"
1138
+ return out
1139
+
1140
+
1141
+ def hdr10_svtav1_params(v: Dict[str, Any]) -> str:
1142
+ """The same for SVT-AV1 (-svtav1-params), which takes chromaticities and cd/m2 as decimals."""
1143
+ md, cl = _hdr10_parts(v)
1144
+ parts = []
1145
+ if md:
1146
+ f = lambda k: f"{md[k]:.5f}".rstrip("0").rstrip(".")
1147
+ parts.append(f"mastering-display=G({f('green_x')},{f('green_y')})B({f('blue_x')},{f('blue_y')})R({f('red_x')},{f('red_y')})"
1148
+ f"WP({f('white_point_x')},{f('white_point_y')})L({f('max_luminance')},{f('min_luminance')})")
1149
+ if cl:
1150
+ parts.append(f"content-light={cl['max_content']},{cl['max_average']}")
1151
+ return ":".join(parts)
1152
+
1153
+
1154
+ def _hdr10_parts(v: Dict[str, Any]) -> "Tuple[Optional[Dict[str, float]], Optional[Dict[str, int]]]":
1155
+ st = v.get("hdr10_static") or {}
1156
+ if v.get("color_transfer") != "smpte2084":
1157
+ return None, None
1158
+ return st.get("mastering_display"), st.get("content_light")
1159
+
1160
+
1161
+ def _clamped_crf(encoder: str, value: int, top: int, requested: int) -> int:
1162
+ """`value` capped at the encoder's maximum CRF, the cap recorded (`crf_clamped`) when it
1163
+ bites: the HEVC HDR line asks x265 for CRF+2, so --quality 50 or 51 there is encoded at 51."""
1164
+ if value <= top:
1165
+ return value
1166
+ warn(f"{encoder}: CRF {value} (from {requested}) is above the encoder's maximum {top}; encoded at CRF {top}",
1167
+ "crf_clamped", encoder=encoder, requested=requested, asked=value, used=top)
1168
+ return top
1169
+
1170
+
1171
+ def _refuse_missing_encoder(codec: str, encoders: List[str], what: str, hint: Optional[str]) -> None:
1172
+ """--codec av1/prores with no encoder for it -- or with an encoder list that could not be read,
1173
+ which proves nothing about the build and is refused under its own reason rather than as a
1174
+ missing encoder (ffmpeg_list_error)."""
1175
+ unread = ffmpeg_list_error("encoders")
1176
+ if unread:
1177
+ refuse("ffmpeg", "encoder_list_unreadable",
1178
+ f"--codec {codec} needs {what}, and whether this ffmpeg build has one is unknown: its encoder list "
1179
+ f"could not be read ({unread})",
1180
+ hint="check that ffmpeg runs (python3 scripts/_contract.py doctor), then retry",
1181
+ codec=codec, encoders=encoders, error=unread)
1182
+ refuse("missing_tool", "encoder_missing", f"--codec {codec} needs {what} and this ffmpeg build has "
1183
+ + ("neither" if len(encoders) > 1 else "none"), hint=hint, codec=codec, encoders=encoders)
1184
+
1185
+
1186
+ def _x264_raw(crf: int, preset: str, keep_bt709: bool = True) -> List[str]:
1187
+ args = ["-c:v", "libx264", "-preset", preset, "-crf", str(crf), "-pix_fmt", "yuv420p", "-movflags", "+faststart"]
1188
+ if keep_bt709:
1189
+ args += bt709_tag_args("libx264")
1190
+ return args
1191
+
1192
+
1193
+ def keeps_source_tags() -> bool:
1194
+ """True when the line being written is an editing master that keeps the source's colour tags
1195
+ and converts no matrix: --codec prores, or an alpha line (--keep-alpha / --transparent,
1196
+ _common.alpha). The BT.709 conversions and labels below are for lines tagged BT.709."""
1197
+ return STATE.codec == "prores" or STATE.alpha_line is not None
1198
+
1199
+
1200
+ def x264_args(crf: int = 18, preset: str = "medium", keep_bt709: bool = True,
1201
+ source: Optional[Dict[str, Any]] = None) -> List[str]:
1202
+ """SDR H.264 encoder args -- or, when --codec named another encoder, that encoder's SDR args
1203
+ (color.py's --to-sdr path builds its own H.264 line; the flag still has to reach it).
1204
+
1205
+ `source`: the probe of the file being re-encoded, when the pixels reaching the encoder are
1206
+ still that file's. A BT.709-tagged line then carries the conversion of a non-BT.709 matrix
1207
+ (bt709_matrix_args); a caller whose graph already outputs BT.709 (--to-sdr) leaves it out."""
1208
+ if STATE.codec and STATE.codec != "h264":
1209
+ args = encoder_args(STATE.codec, crf, preset, None, keep_bt709)
1210
+ else:
1211
+ args = _maybe_hw("h264", crf, None, keep_bt709, _x264_raw(crf, preset, keep_bt709))
1212
+ return args + (bt709_matrix_args(source) if keep_bt709 and not keeps_source_tags() else [])
1213
+
1214
+
1215
+ def video_args(meta: Optional[Dict[str, Any]], crf: int = 18, preset: str = "medium", convert_matrix: bool = True,
1216
+ source: Optional[Dict[str, Any]] = None) -> List[str]:
1217
+ """Encoder args that preserve what the source is.
1218
+
1219
+ SDR sources -> H.264 8-bit tagged BT.709 (x264_args). HDR sources (HDR10/PQ, HLG,
1220
+ Dolby Vision base layer, BT.2020) -> HEVC Main10 with the source's own colour tags,
1221
+ so cutting/captioning/fitting an iPhone HDR clip stays HDR instead of becoming a
1222
+ washed-out file mislabelled as BT.709. Use color.py --to-sdr when SDR is wanted.
1223
+
1224
+ An SDR source tagged with a BT.601 (or another non-BT.709) matrix is converted to BT.709
1225
+ before it is tagged so: the line ends with the `-vf` of bt709_matrix_args(), which run()
1226
+ folds into the tool's own graph (color.fold_bt709_matrix). `convert_matrix=False` is for a
1227
+ tool that mixes several sources and converts each one in its own graph (join, multicam,
1228
+ broll, overlay --video). --codec prores keeps the source's tags, so it converts nothing.
1229
+ An RGB source (a PNG, an image sequence, a qtrle clip) is converted the same way.
1230
+
1231
+ `source`: the probe of the picture the encoder gets when the line is chosen without it
1232
+ (insert.py and sequence.py make a still or a PNG sequence into video on the SDR line,
1233
+ video_args(None)); its RGB or BT.601 pixels are converted to the BT.709 that line is tagged with.
1234
+ """
1235
+ v = (meta or {}).get("video") or {}
1236
+ fix = bt709_matrix_args(meta if source is None else source) if convert_matrix and not keeps_source_tags() else []
1237
+ if convert_matrix and source is None and STATE.alpha_line is None:
1238
+ # the BT.2020 / HDR line of an RGB source (--codec prores included: that line tags it too)
1239
+ fix = hdr_rgb_matrix_args(meta) or ([] if v.get("bt2020_or_hdr") else fix)
1240
+ if STATE.codec:
1241
+ return encoder_args(STATE.codec, crf, preset, meta) + fix
1242
+ if not v.get("bt2020_or_hdr"):
1243
+ return x264_args(crf, preset) + fix
1244
+ return _maybe_hw("hevc", crf, meta, True, _x265_hdr_default(v, crf, preset)) + fix
1245
+
1246
+
1247
+ def line_matrix_filter(meta: Optional[Dict[str, Any]]) -> Optional[str]:
1248
+ """The conversion video_args(meta)'s line ends with for this source, as a filter, or None: for
1249
+ a tool that needs it inside a graph of its own before run() folds it in (stabilize.py's pass
1250
+ 1, fit.py's picture measurement). bt709_matrix_filter() on a line tagged BT.709,
1251
+ hdr_rgb_matrix_filter() on a BT.2020 / HDR line; nothing on an alpha line, and nothing for an
1252
+ SDR source on --codec prores."""
1253
+ if STATE.alpha_line is not None:
1254
+ return None
1255
+ hdr = ((meta or {}).get("video") or {}).get("bt2020_or_hdr")
1256
+ return hdr_rgb_matrix_filter(meta) or (None if keeps_source_tags() or hdr else bt709_matrix_filter(meta))
1257
+
1258
+
1259
+ def matrix_chain(meta: Optional[Dict[str, Any]], line_meta: Optional[Dict[str, Any]]) -> str:
1260
+ """For a tool that mixes several sources in one graph and encodes it through
1261
+ video_args(line_meta, convert_matrix=False): the conversion one source's own chain starts
1262
+ with ("<filter>," -- bt709_matrix_filter), or "" when that source needs none or the line does
1263
+ not tag BT.709 (an HDR/BT.2020 line keeps its tags, --codec prores keeps the source's). On a
1264
+ BT.2020 / HDR line an RGB source that probes BT.2020 or HDR itself is made YUV with the matrix
1265
+ that line tags (hdr_rgb_matrix_filter, #544)."""
1266
+ if ((line_meta or {}).get("video") or {}).get("bt2020_or_hdr") and STATE.alpha_line is None:
1267
+ f = hdr_rgb_matrix_filter(meta, line_meta)
1268
+ return f + "," if f else ""
1269
+ if keeps_source_tags() or ((line_meta or {}).get("video") or {}).get("bt2020_or_hdr"):
1270
+ return ""
1271
+ f = bt709_line_filter(meta)
1272
+ return f + "," if f else ""
1273
+
1274
+
1275
+ def label_chain(meta: Optional[Dict[str, Any]], line_meta: Optional[Dict[str, Any]]) -> str:
1276
+ """For a picture that meets a converted one in a mixing filter (a still over the video, a grid
1277
+ cell beside a converted cell), encoded through video_args(line_meta): the BT.709 label an
1278
+ untagged one's chain starts with ("<setparams>," -- bt709_label_filter), or "" (a tagged, RGB or
1279
+ HDR picture, or a line that does not tag BT.709)."""
1280
+ if keeps_source_tags() or ((line_meta or {}).get("video") or {}).get("bt2020_or_hdr"):
1281
+ return ""
1282
+ f = bt709_label_filter(meta)
1283
+ return f + "," if f else ""
1284
+
1285
+
1286
+ def range_chain(meta: Optional[Dict[str, Any]], line_meta: Optional[Dict[str, Any]]) -> str:
1287
+ """For a picture that a mixing filter (concat, xfade, xstack, overlay) puts beside or under
1288
+ another, encoded through video_args(line_meta): the conversion to limited range its chain
1289
+ takes after its matrix_chain()/label_chain() ("<filter>," -- limited_range_filter), or "" (a
1290
+ limited, RGB or HDR picture, or a line that does not tag BT.709). Every SDR picture such a
1291
+ tool mixes is then limited range, whatever each one was: the filters mix samples, not colours."""
1292
+ if keeps_source_tags() or ((line_meta or {}).get("video") or {}).get("bt2020_or_hdr"):
1293
+ return ""
1294
+ f = limited_range_filter(meta)
1295
+ return f + "," if f else ""
1296
+
1297
+
1298
+ def mix_color_chains(metas: Sequence[Optional[Dict[str, Any]]], line_meta: Optional[Dict[str, Any]],
1299
+ *, draws_colour: bool = False) -> List[str]:
1300
+ """Per-input matrix and range before mixing. A BT.709 input, whether converted or
1301
+ already tagged, makes FFmpeg negotiate a matrix for its untagged neighbours (#696)."""
1302
+ matrices = [matrix_chain(m, line_meta) for m in metas]
1303
+ if draws_colour or any(matrices) or any(((m or {}).get("video") or {}).get("color_space") == "bt709" for m in metas):
1304
+ matrices = [c or label_chain(m, line_meta) for c, m in zip(matrices, metas)]
1305
+ return [c + range_chain(m, line_meta) for c, m in zip(matrices, metas)]
1306
+
1307
+
1308
+ def layer_base_chain(meta: Optional[Dict[str, Any]]) -> str:
1309
+ """The chain in front of the picture `meta` probes where converted RGB layers (rgb_chain_to_bt709:
1310
+ a still, an emoji PNG, a box of chroma) are overlaid on it: an untagged picture's BT.709 label
1311
+ (label_chain) and, for a full-range one, its conversion to the limited range the layers are
1312
+ made in (range_chain). "" when the line converts no layer (HDR, prores)."""
1313
+ if not rgb_chain_to_bt709(meta):
1314
+ return ""
1315
+ return label_chain(meta, meta) + range_chain(meta, meta)
1316
+
1317
+
1318
+ def rgb_chain_to_bt709(line_meta: Optional[Dict[str, Any]], pix_fmt: str = "yuva420p") -> str:
1319
+ """For a picture the tool's own graph has made RGB(A) -- a still's `format=rgba` chain
1320
+ (overlay.py --image, an emoji PNG) or an RGBA composite (waveform.py's --image plate) -- that
1321
+ is encoded through video_args(line_meta): "," + the conversion to BT.709 YUV to end that chain
1322
+ with (rgb_to_bt709_filter), or "" when the line does not tag BT.709 (the lines matrix_chain()
1323
+ leaves alone). Without it the graph's own RGB-to-YUV step used FFmpeg's BT.601 default."""
1324
+ v = (line_meta or {}).get("video") or {}
1325
+ if (STATE.alpha_line is not None and (v.get("color_space") == "bt709" or rgb_to_bt709_line(line_meta))
1326
+ and not v.get("bt2020_or_hdr")):
1327
+ # an alpha line keeps the source's tags: on a BT.709-tagged picture an RGB layer is made
1328
+ # BT.709 too (FFmpeg 6.1's own conversion is BT.601), in 4:4:4 with its alpha plane. An
1329
+ # RGB source on a YUV line is a BT.709 picture as well (alpha.rgb_to_bt709_line, #496)
1330
+ return "," + rgb_to_bt709_filter("yuva444p")
1331
+ if keeps_source_tags() or v.get("bt2020_or_hdr"):
1332
+ return ""
1333
+ return "," + rgb_to_bt709_filter(pix_fmt)
1334
+
1335
+
1336
+ def overlay_format(meta: Optional[Dict[str, Any]]) -> str:
1337
+ """":format=..." for an `overlay` whose main picture is the one `meta` probes, or "".
1338
+
1339
+ overlay's default format is `yuv420`, which is 8-bit, and `format=auto` picks an 8-bit one as
1340
+ soon as the layer is 8-bit, so through 3.6.0 a cutaway, a redaction, a graphics layer or a PiP
1341
+ over a 10-bit HDR or ProRes source took the whole picture to 8 bits (and `overlay --image`'s
1342
+ RGBA logo took it through 8-bit RGB) before the 10-bit encoder. On a line that keeps more than
1343
+ 8 bits (HDR/BT.2020, --codec prores) and a main picture deeper than 8 bits the overlay runs at
1344
+ 10 bits in the main's own chroma subsampling, and an 8-bit layer is widened to meet it (bit
1345
+ depth only, no matrix). An alpha line keeps the format its tool chose."""
1346
+ v = (meta or {}).get("video") or {}
1347
+ if STATE.alpha_line is not None or (v.get("bit_depth") or 8) <= 8:
1348
+ return ""
1349
+ if not (v.get("bt2020_or_hdr") or keeps_source_tags()):
1350
+ return ""
1351
+ pix = v.get("pix_fmt") or ""
1352
+ sub = "444" if "444" in pix else "422" if "422" in pix else "420"
1353
+ return f":format=yuv{sub}p10"
1354
+
1355
+
1356
+ def draws_chroma(colours: Sequence[Any], line_meta: Optional[Dict[str, Any]]) -> bool:
1357
+ """True when one of `colours` has chroma (is_neutral_color) and the line video_args(line_meta)
1358
+ tags the output BT.709 -- when a drawn colour needs drawn_chain() at all."""
1359
+ return (not all(is_neutral_color(c) for c in colours if c is not None) and not keeps_source_tags()
1360
+ and not ((line_meta or {}).get("video") or {}).get("bt2020_or_hdr"))
1361
+
1362
+
1363
+ def drawn_chain(colour_chain: str, meta: Optional[Dict[str, Any]], colours: Sequence[Any], neutral_chain: str = "null",
1364
+ line_meta: Any = "same", tag: str = "d", labelled: bool = False) -> str:
1365
+ """`colour_chain` -- filters that draw a colour into the picture `meta` probes (drawtext's
1366
+ font/box/border colours, pad/tpad's fill, rotate's fillcolor, libass) -- so that a colour of
1367
+ `colours` lands in the BT.709 the line video_args(line_meta) tags the output with (line_meta
1368
+ defaults to meta).
1369
+
1370
+ FFmpeg's drawing filters turn an RGB colour into YUV with a matrix of their own (ff_draw):
1371
+ BT.601 always up to 7.0, the link's colourspace from 7.1 on, "unknown" read as BT.601. Through
1372
+ 2.10.2 a drawn colour was BT.601 under a BT.709 tag on every build (pure red decoded as
1373
+ (255,24,0)), and on 5.1/6.1 for a BT.709-tagged source too. From 7.1 an untagged picture gets
1374
+ its BT.709 label (label_chain(): tags only) and the filters follow it; before 7.1 the drawing
1375
+ runs in RGB (rgb_island(), `neutral_chain` being the same filters with a black fill, or null).
1376
+
1377
+ Unchanged: a chain whose colours are all greys (the same YUV under every matrix: the default
1378
+ black pads and white text), a line that does not tag BT.709 (HDR, prores). `labelled`: the
1379
+ caller's graph already labels this picture (label_chain()) earlier in the same chain.
1380
+
1381
+ Before 7.1 `ff_draw` also takes the range from the pixel format alone: full for `yuvj`, limited
1382
+ for every other, so on a full-range picture in a plain format (VP9/AV1 full range, 10-bit full
1383
+ range) even black and white were drawn limited (pad black read 101010, #410), and 6.1's scale
1384
+ has often made such a picture limited before the drawing anyway. There the picture is first
1385
+ taken to limited range (range_chain(), which reads the range from the frames), and the
1386
+ drawing, the colours and rgb_island() all work in limited range. 7.1+ draws in the link's
1387
+ range and is left as it is."""
1388
+ line = meta if line_meta == "same" else line_meta
1389
+ pre = ""
1390
+ if ffmpeg_version() < (7, 1) and not str(((meta or {}).get("video") or {}).get("pix_fmt") or "").startswith("yuvj"):
1391
+ pre = range_chain(meta, line)
1392
+ if not draws_chroma(colours, line):
1393
+ return pre + colour_chain
1394
+ if ffmpeg_version() >= (7, 1):
1395
+ return ("" if labelled else label_chain(meta, line)) + colour_chain
1396
+ pix_fmt, full = drawn_stream_format(as_limited(meta) if pre else meta)
1397
+ return pre + rgb_island(colour_chain, neutral_chain, pix_fmt, full, tag)
1398
+
1399
+
1400
+ def source_codec_video_args(meta: Optional[Dict[str, Any]], crf: int = 18, preset: str = "medium",
1401
+ keep_hevc: bool = False) -> List[str]:
1402
+ """video_args(), except that with `keep_hevc` (cut.py --keep-hevc) an SDR HEVC source re-encodes
1403
+ to HEVC (8-bit, BT.709-tagged, on VideoToolbox when --hw asks) instead of H.264: a cut is a trim,
1404
+ so a re-encoded segment can come out in the codec the source (and any copied segment beside it)
1405
+ is in. Opt-in within 2.x, where an SDR re-encode stays x264 unless asked. An HDR or BT.2020
1406
+ source always takes video_args()'s Main10 line, and --codec always wins."""
1407
+ v = (meta or {}).get("video") or {}
1408
+ if keep_hevc and not STATE.codec and v.get("codec") == "hevc" and not v.get("bt2020_or_hdr"):
1409
+ return encoder_args("hevc", crf, preset, meta) + bt709_matrix_args(meta)
1410
+ return video_args(meta, crf, preset)
1411
+
1412
+
1413
+ def _x265_hdr_default(v: Dict[str, Any], crf: int, preset: str) -> List[str]:
1414
+ cs = hdr_line_matrix(v)
1415
+ prim = v.get("color_primaries") or "bt2020"
1416
+ trc = source_transfer(v)
1417
+ x265 = f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}:range=limited:hdr10-opt=1{hdr10_x265_params(v)}" if trc == "smpte2084" else f"log-level=error:colorprim={prim}:transfer={trc}:colormatrix={cs}"
1418
+ return ["-c:v", "libx265", "-preset", preset, "-crf", str(min(51, crf + 2)), "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1",
1419
+ "-x265-params", x265, "-colorspace", cs, "-color_primaries", prim, "-color_trc", trc, "-movflags", "+faststart"]
1420
+
1421
+
1422
+ def aac_args(bitrate: str = "192k") -> List[str]:
1423
+ return ["-c:a", "aac", "-b:a", bitrate]
1424
+
1425
+
1426
+ AUDIO_CODECS = {
1427
+ ".wav": ["-c:a", "pcm_s16le"],
1428
+ ".flac": ["-c:a", "flac"],
1429
+ ".mp3": ["-c:a", "libmp3lame", "-q:a", "0"],
1430
+ ".m4a": ["-c:a", "aac", "-b:a", "256k"],
1431
+ ".aac": ["-c:a", "aac", "-b:a", "256k"],
1432
+ ".ogg": ["-c:a", "libvorbis", "-q:a", "6"],
1433
+ ".opus": ["-c:a", "libopus", "-b:a", "128k"],
1434
+ # 16-bit PCM as for .wav, big-endian: the AIFF and CAF muxers' own default codec (#517)
1435
+ ".aif": ["-c:a", "pcm_s16be"],
1436
+ ".aiff": ["-c:a", "pcm_s16be"],
1437
+ ".caf": ["-c:a", "pcm_s16be"],
1438
+ ".mka": ["-c:a", "flac"],
1439
+ }
1440
+
1441
+
1442
+ LOSSLESS_AUDIO_EXT = {".wav", ".flac", ".aif", ".aiff", ".caf", ".mka"} # the AUDIO_CODECS whose codec takes no bitrate
1443
+
1444
+ # Every audio-only extension this skill reads (AUDIO_MEDIA_EXT) that has no codec above: a run
1445
+ # that would encode into an output named so is refused before ffmpeg runs, and only a stream copy
1446
+ # of WMA sound is written (runner.refuse_unwritten_output(), #517). That is .wma: FFmpeg's ASF
1447
+ # muxer took the tools' H.264 and AAC and wrote them under the name, verified.
1448
+ UNWRITTEN_AUDIO_EXT = frozenset(AUDIO_MEDIA_EXT - set(AUDIO_CODECS))
1449
+
1450
+
1451
+ def audio_codec_for(output_path: str, bitrate: Optional[str] = None) -> List[str]:
1452
+ """Pick an audio codec that the output container can actually hold.
1453
+
1454
+ `bitrate` is one the caller asked for: it replaces the rate or quality an audio extension
1455
+ names (`-q:a 0` for .mp3, 256k for .m4a), which through 3.8.8 it never reached (A143), and is
1456
+ the AAC rate of any other container (192k when it is None). A lossless extension takes none;
1457
+ the caller refuses a bitrate for it."""
1458
+ ext = os.path.splitext(output_path)[1].lower()
1459
+ if ext not in AUDIO_CODECS:
1460
+ return ["-c:a", "aac", "-b:a", bitrate or "192k"]
1461
+ args = list(AUDIO_CODECS[ext])
1462
+ if bitrate is None or ext in LOSSLESS_AUDIO_EXT:
1463
+ return args
1464
+ for flag in ("-b:a", "-q:a"):
1465
+ if flag in args:
1466
+ i = args.index(flag)
1467
+ del args[i:i + 2]
1468
+ return args + ["-b:a", bitrate]
1469
+
1470
+
1471
+ def is_audio_output(output_path: str) -> bool:
1472
+ """True when the output extension is an audio-only container this skill writes (AUDIO_CODECS:
1473
+ .wav, .flac, .mp3, .m4a, .aac, .ogg, .opus, .aif, .aiff, .caf, .mka).
1474
+
1475
+ Scripts use this to drop the picture (-vn) and to pick the output codec from the extension.
1476
+ """
1477
+ return os.path.splitext(output_path)[1].lower() in AUDIO_CODECS
1478
+
1479
+
1480
+ def db_to_linear(db: float) -> float:
1481
+ return 10 ** (db / 20.0)
1482
+
1483
+
1484
+ BRAND_DEFAULTS: Dict[str, Any] = {
1485
+ "font": "DejaVu Sans",
1486
+ "font_file": None,
1487
+ "colors": {"primary": "FFD200", "text": "FFFFFF", "outline": "000000", "background": "101418", "accent": "1E6F8E"},
1488
+ "logo": None,
1489
+ "logo_position": "top-right",
1490
+ "logo_scale": 160,
1491
+ "logo_opacity": 0.9,
1492
+ "safe_margin": 48,
1493
+ "caption": {"size": 26, "position": "bottom", "animate": "pop", "karaoke": False, "bold": True, "outline": 2},
1494
+ # 1.12: one place for the caption look every project shares. `styles.caption` is the documented
1495
+ # spelling (`{font, size, colour, box, position}`, British or American "colour"); the older
1496
+ # top-level `caption` block still works and `styles.caption` wins where both name the same key.
1497
+ "styles": {},
1498
+ "lang": None,
1499
+ "loudness": {"lufs": -14, "tp": -1},
1500
+ }
1501
+
1502
+
1503
+ # Every key a tool reads from a brand file, per block (#510). `styles.caption` is merged over the
1504
+ # top-level `caption` block (brand_caption_style()), so the two take the same keys. `colors.accent`
1505
+ # is a palette entry BRAND_DEFAULTS and examples/brand.json carry; `loudness` is read by no tool
1506
+ # (A107) and is kept out of the refusal, since the example shipped it until 3.8.8: it gets a note.
1507
+ BRAND_KEYS: Dict[str, frozenset] = {
1508
+ "": frozenset({"font", "font_file", "colors", "logo", "logo_position", "logo_scale", "logo_opacity",
1509
+ "safe_margin", "caption", "styles", "lang", "emoji_assets", "loudness"}),
1510
+ "colors": frozenset({"primary", "text", "outline", "background", "accent", "upcoming"}),
1511
+ "caption": frozenset({"size", "position", "animate", "karaoke", "bold", "outline", "box", "color", "colour",
1512
+ "font", "emoji_assets"}),
1513
+ "styles": frozenset({"caption"}),
1514
+ }
1515
+ BRAND_KEYS["styles.caption"] = BRAND_KEYS["caption"]
1516
+
1517
+
1518
+ def check_brand_keys(data: Dict[str, Any], path: str) -> None:
1519
+ """Refuse a brand file key no tool reads, as render.py refuses a project's (check_keys()): a
1520
+ misspelt `"safe_margn"` or `"colours"` was dropped without a word and the defaults drawn."""
1521
+ import difflib
1522
+ import json
1523
+ blocks = [("", data)]
1524
+ for name in ("colors", "caption", "styles"):
1525
+ if isinstance(data.get(name), dict):
1526
+ blocks.append((name, data[name]))
1527
+ if isinstance(data.get("styles"), dict) and isinstance(data["styles"].get("caption"), dict):
1528
+ blocks.append(("styles.caption", data["styles"]["caption"]))
1529
+ for block, obj in blocks:
1530
+ for key in obj:
1531
+ if key in BRAND_KEYS[block]:
1532
+ continue
1533
+ where = f"{block}.{key}" if block else str(key)
1534
+ near = difflib.get_close_matches(str(key), sorted(BRAND_KEYS[block]), n=1)
1535
+ # quoted as JSON: the key is the caller's text, and a quote or a line break in it stays one line
1536
+ die(f"brand file {path}: unknown key {json.dumps(where)}" + (f' (did you mean "{near[0]}"?)' if near else ""),
1537
+ kind="input", hint=f"the keys read{' in ' + block if block else ''}: " + ", ".join(sorted(BRAND_KEYS[block])))
1538
+ if "loudness" in data:
1539
+ note(f'brand file {path}: "loudness" is read by no tool and was ignored (a target is loudness.py -I, '
1540
+ 'export.py\'s preset, or a render project\'s "loudness")')
1541
+
1542
+
1543
+ BRAND_FILE_KEYS = ("logo", "font_file") # the brand keys that name a file a tool reads
1544
+
1545
+
1546
+ def brand_asset_files(path: str) -> List[Tuple[str, str]]:
1547
+ """(key, path) of each file a brand file names (logo, font_file), resolved as load_brand()
1548
+ resolves them: against the brand file's own directory. What a cache key must hash beside the
1549
+ brand file's own bytes, since a logo or a font replaced under its name changes the output
1550
+ (render.py --cache; batch.py's side inputs, #510 review). A brand file that cannot be read
1551
+ names nothing here; the tool refuses it when it runs."""
1552
+ try:
1553
+ data = read_json(path)
1554
+ except (OSError, ValueError):
1555
+ return []
1556
+ if not isinstance(data, dict):
1557
+ return []
1558
+ base = Path(path).resolve().parent
1559
+ out: List[Tuple[str, str]] = []
1560
+ for key in BRAND_FILE_KEYS:
1561
+ value = data.get(key)
1562
+ if isinstance(value, str) and value:
1563
+ out.append((key, value if os.path.isabs(value) else str(base / value)))
1564
+ return out
1565
+
1566
+
1567
+ def load_brand(path: Optional[str]) -> Dict[str, Any]:
1568
+ """Load brand.json (fonts, colours, logo, safe margins, caption defaults); missing keys fall back to defaults."""
1569
+ import copy
1570
+ brand = copy.deepcopy(BRAND_DEFAULTS)
1571
+ brand["_stated"] = {}
1572
+ if not path:
1573
+ return brand
1574
+ if not os.path.exists(path):
1575
+ die(f"brand file {absent_word(path)}: {path}", kind="input")
1576
+ try:
1577
+ data = read_json(path)
1578
+ except OSError as exc:
1579
+ die(f"brand file {path} cannot be read: {exc.strerror or exc}", kind="input")
1580
+ except ValueError as exc: # malformed, not UTF-8, or nested too deep (read_json)
1581
+ die(f"brand file is not valid JSON: {exc}", kind="input")
1582
+ if not isinstance(data, dict):
1583
+ die(f"brand file {path} must be a JSON object {{...}}, got {type(data).__name__}", kind="input")
1584
+ # the shapes the readers below and brand_caption_style() walk: a block that is not an object,
1585
+ # and a path that is not a string, were a traceback there
1586
+ for key, value in (*data.items(), ("styles.caption", (data.get("styles") or {}).get("caption")
1587
+ if isinstance(data.get("styles"), dict) else None)):
1588
+ if value is None:
1589
+ continue
1590
+ if (isinstance(BRAND_DEFAULTS.get(key), dict) or key == "styles.caption") and not isinstance(value, dict):
1591
+ die(f'brand file {path}: "{key}" must be an object {{...}}, got {type(value).__name__}', kind="input")
1592
+ if key in ("logo", "font_file", "font") and not isinstance(value, str):
1593
+ die(f'brand file {path}: "{key}" must be a string, got {type(value).__name__}', kind="input")
1594
+ check_brand_keys(data, path)
1595
+ base = Path(path).resolve().parent
1596
+ for k, v in data.items():
1597
+ if v is None and isinstance(brand.get(k), dict):
1598
+ continue # a null block keeps its defaults: readers walk it as an object (#483 review)
1599
+ if isinstance(v, dict) and isinstance(brand.get(k), dict):
1600
+ brand[k].update(v)
1601
+ else:
1602
+ brand[k] = v
1603
+ for key in ("logo", "font_file"):
1604
+ if brand.get(key) and not os.path.isabs(brand[key]):
1605
+ brand[key] = str(base / brand[key])
1606
+ # a file the run reads: a --plan binds it and is never written over it (review of #534's
1607
+ # sweep: caption.py hands libass the font's folder, so its plan named neither)
1608
+ if brand.get(key) and os.path.isfile(brand[key]) and brand[key] not in STATE.plan_inputs:
1609
+ STATE.plan_inputs.append(brand[key])
1610
+ brand["_path"] = str(path)
1611
+ # What the FILE said, separate from BRAND_DEFAULTS' filler: a brand.json that never mentions
1612
+ # a font must not read as "the caller chose a font" (which would switch font-by-script off).
1613
+ brand["_stated"] = data
1614
+ return brand
1615
+
1616
+
1617
+ # Every key of a render.py project that names a file. render.py reads each one relative to the
1618
+ # project file (its rel()); a copy of the project written anywhere else -- batch.py's per-item
1619
+ # project in its work directory, multicam.py --write-project -- has to carry them absolute, or
1620
+ # render looks for "bed.wav" beside the copy. A path is (section, key): section None is the
1621
+ # project's top level, "x[]" each entry of the list x. tests/test_contract.py checks that every
1622
+ # rel() in render.py reads one of these.
1623
+ PROJECT_PATH_KEYS = (
1624
+ (None, "output"), (None, "brand"), (None, "chapters"),
1625
+ ("clips[]", "src"), ("clips[].snap", "source"), ("snap", "source"),
1626
+ ("audio", "music"), ("audio", "replace"), ("audio", "effects"),
1627
+ ("captions", "text"), ("captions", "srt"), ("captions", "ass"),
1628
+ ("overlays[]", "image"), ("overlays[]", "video"), ("overlays[]", "font_file"),
1629
+ ("audiogram", "image"),
1630
+ )
1631
+
1632
+
1633
+ def rebase_project_paths(proj: Dict[str, Any], base: "os.PathLike[str] | str") -> Dict[str, Any]:
1634
+ """A copy of a render.py project whose relative file paths (PROJECT_PATH_KEYS) are joined onto
1635
+ `base`, the directory they were written relative to; absolute paths, URLs, non-strings, inline
1636
+ chapter lists and keys the project does not have are left as they are."""
1637
+ import copy
1638
+ out = copy.deepcopy(proj)
1639
+ base = Path(base)
1640
+
1641
+ def fix(obj: Any, key: str) -> None:
1642
+ value = obj.get(key) if isinstance(obj, dict) else None
1643
+ # a URL is left for the tool to refuse by what it is (waveform.py: no network access)
1644
+ if isinstance(value, str) and value and not os.path.isabs(value) and "://" not in value:
1645
+ obj[key] = str(base / value)
1646
+
1647
+ def nodes(section: "Optional[str]") -> List[Any]:
1648
+ found: List[Any] = [out]
1649
+ for part in (section.split(".") if section else []):
1650
+ name, many = (part[:-2], True) if part.endswith("[]") else (part, False)
1651
+ nxt: List[Any] = []
1652
+ for node in found:
1653
+ value = node.get(name) if isinstance(node, dict) else None
1654
+ nxt.extend(value if many and isinstance(value, list) else [] if many else [value])
1655
+ found = nxt
1656
+ return found
1657
+ for section, key in PROJECT_PATH_KEYS:
1658
+ for node in nodes(section):
1659
+ fix(node, key)
1660
+ return out
1661
+
1662
+
1663
+ def brand_states_font(brand: Dict[str, Any]) -> bool:
1664
+ """Did the brand FILE actually name a font (top-level `font`, `caption.font` or
1665
+ `styles.caption.font`)? BRAND_DEFAULTS always supplies one, so the merged document can never
1666
+ answer this -- and treating the default filler as the caller's choice switched font-by-script
1667
+ off for every branded job (review 10)."""
1668
+ stated = brand.get("_stated") or {}
1669
+ if stated.get("font"):
1670
+ return True
1671
+ for block in (stated.get("caption"), (stated.get("styles") or {}).get("caption")):
1672
+ if isinstance(block, dict) and block.get("font"):
1673
+ return True
1674
+ return False
1675
+
1676
+
1677
+ def brand_caption_style(brand: Dict[str, Any]) -> Dict[str, Any]:
1678
+ """The effective caption style of a brand file: the top-level `caption` block updated with
1679
+ `styles.caption`, with `colour` normalised to `color`. Explicit flags still beat both."""
1680
+ style: Dict[str, Any] = dict(brand.get("caption") or {})
1681
+ extra = (brand.get("styles") or {}).get("caption") or {}
1682
+ style.update(extra)
1683
+ if "colour" in style and "color" not in style:
1684
+ style["color"] = style.pop("colour")
1685
+ style.pop("colour", None)
1686
+ return style
1687
+
1688
+
1689
+ # ------------------------------------------------------------------- chapter proposal (1.16)
1690
+
1691
+ def fmt_chapter_time(t: float) -> str:
1692
+ """The YouTube description convention: `00:00`, `03:12`, `1:02:03` past the hour, always
1693
+ rounded DOWN to the second so the timestamp never lands after the moment it names."""
1694
+ total = max(0, int(t))
1695
+ h, rem = divmod(total, 3600)
1696
+ m, sec = divmod(rem, 60)
1697
+ if h:
1698
+ return f"{h}:{m:02d}:{sec:02d}"
1699
+ return f"{m:02d}:{sec:02d}"
1700
+
1701
+
1702
+ def _evidence_rank(ev: Dict[str, Any]) -> tuple:
1703
+ """How strong a candidate is, for the drop order: both detectors beat a silence, a silence
1704
+ beats a scene cut, and within a kind the longer pause / higher score wins."""
1705
+ kind = ev.get("kind")
1706
+ tier = {"start": 3, "silence+scene": 2, "silence": 1, "scene": 0}.get(kind, 0)
1707
+ within = float(ev.get("silence_length") or ev.get("score") or 0.0)
1708
+ return (tier, within)
1709
+
1710
+
1711
+ def propose_chapters(duration: float, silences: "Sequence", scene_cuts: "Sequence", *,
1712
+ min_chapter: float = 60.0, max_chapters: int = 0,
1713
+ source: str = "both") -> "List[Dict[str, Any]]":
1714
+ """Chapter markers proposed from measured structure. Pure: the detectors' outputs go in,
1715
+ a list of `{"at", "title", "evidence"}` comes out, and nothing is decoded here.
1716
+
1717
+ A chapter starts where speech RESUMES, so a silence contributes its `end`, not its midpoint.
1718
+ A scene cut within 1 s of such a point is the same event seen twice and is merged into one
1719
+ candidate with `kind: "silence+scene"`, which the `--max-chapters` cap never drops before a
1720
+ single-evidence one. Candidates closer than `min_chapter` to the one already kept are dropped,
1721
+ stronger evidence winning; so is anything inside `min_chapter` of the end of the file.
1722
+
1723
+ Every title is `Chapter N`. The function never looks at, and never invents, content: naming a
1724
+ chapter needs knowing what is said in it, which is the calling agent's job, not this skill's.
1725
+ """
1726
+ duration = float(duration or 0.0)
1727
+ min_chapter = max(0.0, float(min_chapter))
1728
+ candidates: "List[Dict[str, Any]]" = []
1729
+ if source in ("silence", "both"):
1730
+ for span in silences or []:
1731
+ start, end = float(span[0]), span[1]
1732
+ if end is None or end == float("inf"):
1733
+ continue
1734
+ end = float(end)
1735
+ candidates.append({"at": end, "evidence": {
1736
+ "kind": "silence", "silence": [round(start, 3), round(end, 3)],
1737
+ "silence_length": round(end - start, 3)}})
1738
+ if source in ("scenes", "both"):
1739
+ for cut in scene_cuts or []:
1740
+ cut = float(cut)
1741
+ if cut <= 0.0:
1742
+ continue # scenes.py always reports 0.0 as the first cut; that is the start
1743
+ candidates.append({"at": cut, "evidence": {"kind": "scene", "scene_at": round(cut, 3)}})
1744
+
1745
+ # merge a scene cut that stands within 1 s of a silence end: one event, two witnesses
1746
+ candidates.sort(key=lambda c: c["at"])
1747
+ merged: "List[Dict[str, Any]]" = []
1748
+ for cand in candidates:
1749
+ prior = merged[-1] if merged else None
1750
+ if prior and abs(cand["at"] - prior["at"]) <= 1.0 and \
1751
+ {prior["evidence"]["kind"], cand["evidence"]["kind"]} == {"silence", "scene"}:
1752
+ ev = dict(prior["evidence"])
1753
+ ev.update(cand["evidence"])
1754
+ ev["kind"] = "silence+scene"
1755
+ silence_first = prior["evidence"]["kind"] == "silence"
1756
+ prior["at"] = prior["at"] if silence_first else cand["at"]
1757
+ prior["evidence"] = ev
1758
+ continue
1759
+ merged.append(dict(cand))
1760
+
1761
+ kept: "List[Dict[str, Any]]" = [{"at": 0.0, "evidence": {"kind": "start"}}]
1762
+ for cand in merged:
1763
+ if duration and cand["at"] >= duration - min_chapter:
1764
+ continue
1765
+ last = kept[-1]
1766
+ if cand["at"] - last["at"] < min_chapter:
1767
+ # too close to the marker already kept: keep whichever the evidence supports better,
1768
+ # never replacing the 0.0 start
1769
+ if last["evidence"]["kind"] != "start" and \
1770
+ _evidence_rank(cand["evidence"]) > _evidence_rank(last["evidence"]) and \
1771
+ (len(kept) < 2 or cand["at"] - kept[-2]["at"] >= min_chapter):
1772
+ kept[-1] = dict(cand)
1773
+ continue
1774
+ kept.append(dict(cand))
1775
+
1776
+ if max_chapters and len(kept) > max_chapters:
1777
+ # drop the weakest evidence first, never index 0, then put the survivors back in order
1778
+ order = sorted(range(1, len(kept)),
1779
+ key=lambda i: (_evidence_rank(kept[i]["evidence"]), -kept[i]["at"]))
1780
+ drop = set(order[:len(kept) - max_chapters])
1781
+ kept = [c for i, c in enumerate(kept) if i not in drop]
1782
+
1783
+ for n, chapter in enumerate(kept, start=1):
1784
+ chapter["at"] = round(chapter["at"], 3)
1785
+ chapter["title"] = f"Chapter {n}"
1786
+ return kept
1787
+
1788
+
1789
+ def description_block(chapters: "Sequence") -> str:
1790
+ """The YouTube description form of a chapter list: `00:00 Chapter 1` per line."""
1791
+ return "\n".join(f"{fmt_chapter_time(c['at'])} {c['title']}" for c in chapters)
1792
+
1793
+
1794
+ # ------------------------------------------------------------------ the beat grid (1.17)
1795
+ #
1796
+ # A beat grid is a measurement of the music's periodicity -- not a statement about where a cut
1797
+ # belongs. Everything here is arithmetic on an RMS envelope somebody else decoded; nothing in this
1798
+ # module decides to cut anything, and nothing invents a beat the audio does not support.
1799
+
1800
+ BEAT_ONSET_K = 1.5 # peak threshold: median + k * MAD over the local window
1801
+ BEAT_WINDOW_S = 1.0 # +/- this many seconds is "local" for the threshold
1802
+ BEAT_REFRACTORY_S = 0.06 # two onsets closer than this are one onset
1803
+ BEAT_SUPPORT_DIVISOR = 4 # a grid point with no onset within interval/4 is "unsupported"
1804
+ BEAT_ALIGN_DIVISOR = 8 # an onset within interval/8 of a grid point counts as aligned
1805
+ BEAT_MIN_CONFIDENCE = 0.5 # the default below which a tool that CHANGES a file refuses to snap
1806
+ BEAT_OCTAVE_MARGIN = 1.2 # a half/double-tempo grid must explain this much more onset strength
1807
+ BEAT_Z_FLOOR = 2.0 # autocorrelation z-score at which periodicity starts counting
1808
+ BEAT_Z_SPAN = 4.0 # ... and the span over which it reaches 1.0
1809
+
1810
+
1811
+ def _onset_strength(envelope: "Sequence[float]") -> "List[float]":
1812
+ """Half-wave-rectified first difference of log(env), i.e. a compression-domain spectral-flux
1813
+ analogue. The log matters: the level-domain difference over-weights the loud sections, so a
1814
+ quiet verse contributes no onsets at all and the tempo is measured on the chorus alone."""
1815
+ import math as _math
1816
+ log_env = [_math.log(max(0.0, float(e)) + 1e-9) for e in envelope]
1817
+ return [0.0] + [max(0.0, log_env[i] - log_env[i - 1]) for i in range(1, len(log_env))]
1818
+
1819
+
1820
+ def _pick_onsets(strength: "Sequence[float]", step_s: float) -> "List[int]":
1821
+ """Indices of local maxima above median + k*MAD over a +/-BEAT_WINDOW_S window, with a
1822
+ refractory gap. A median/MAD threshold rather than a mean/stdev one because a handful of very
1823
+ strong hits would drag a mean-based threshold above every other onset in the piece."""
1824
+ n = len(strength)
1825
+ if n < 3:
1826
+ return []
1827
+ half = max(1, int(round(BEAT_WINDOW_S / max(step_s, 1e-9))))
1828
+ refractory = max(1, int(round(BEAT_REFRACTORY_S / max(step_s, 1e-9))))
1829
+ picked: "List[int]" = []
1830
+ for i in range(1, n - 1):
1831
+ s = strength[i]
1832
+ if s <= 0 or s < strength[i - 1] or s < strength[i + 1]:
1833
+ continue
1834
+ window = sorted(strength[max(0, i - half):min(n, i + half + 1)])
1835
+ if not window:
1836
+ continue
1837
+ med = window[len(window) // 2]
1838
+ devs = sorted(abs(x - med) for x in window)
1839
+ mad = devs[len(devs) // 2]
1840
+ if s < med + BEAT_ONSET_K * mad or s <= med:
1841
+ continue
1842
+ if picked and i - picked[-1] < refractory:
1843
+ if s > strength[picked[-1]]:
1844
+ picked[-1] = i
1845
+ continue
1846
+ picked.append(i)
1847
+ return picked
1848
+
1849
+
1850
+ def _autocorrelation_peak(strength: "Sequence[float]", step_s: float,
1851
+ bpm_range: "Sequence[float]") -> "tuple":
1852
+ """(best lag in samples, peak, mean, standard deviation) of the onset signal's
1853
+ autocorrelation over the lags `bpm_range` allows, or (None, 0.0, 0.0, 0.0).
1854
+
1855
+ The spread matters as much as the peak: every signal's autocorrelation has a maximum
1856
+ somewhere, so "the peak is above the mean" says nothing. How far above it stands relative to
1857
+ the spread of the other lags is what separates a pulse from noise.
1858
+ """
1859
+ n = len(strength)
1860
+ hi_bpm, lo_bpm = max(bpm_range), min(bpm_range)
1861
+ lag_min = max(1, int(round(60.0 / hi_bpm / max(step_s, 1e-9))))
1862
+ lag_max = int(round(60.0 / lo_bpm / max(step_s, 1e-9)))
1863
+ lag_max = min(lag_max, n - 1)
1864
+ if lag_max < lag_min:
1865
+ return (None, 0.0, 0.0, 0.0)
1866
+ mean = sum(strength) / n if n else 0.0
1867
+ centred = [s - mean for s in strength]
1868
+ best_lag, best = None, 0.0
1869
+ values = []
1870
+ for lag in range(lag_min, lag_max + 1):
1871
+ acc = sum(centred[i] * centred[i + lag] for i in range(n - lag))
1872
+ acc /= (n - lag)
1873
+ values.append(acc)
1874
+ if best_lag is None or acc > best:
1875
+ best_lag, best = lag, acc
1876
+ mean_acc = sum(values) / len(values) if values else 0.0
1877
+ var = sum((v - mean_acc) ** 2 for v in values) / len(values) if values else 0.0
1878
+ return (best_lag, best, mean_acc, math.sqrt(var))
1879
+
1880
+
1881
+ def _grid_score(onset_times: "Sequence[float]", strength_at: "Dict[int, float]",
1882
+ interval: float, phase: float) -> float:
1883
+ """Total onset strength landing within interval/BEAT_ALIGN_DIVISOR of the grid."""
1884
+ if interval <= 0:
1885
+ return 0.0
1886
+ tol = interval / BEAT_ALIGN_DIVISOR
1887
+ total = 0.0
1888
+ for i, t in enumerate(onset_times):
1889
+ off = (t - phase) % interval
1890
+ if min(off, interval - off) <= tol:
1891
+ total += strength_at.get(i, 1.0)
1892
+ return total
1893
+
1894
+
1895
+ BEAT_ZERO_TOL_S = 0.01 # a fitted grid point this little before 0 s is the beat at 0.0
1896
+ BEAT_REFINE_TOL_NATS = 1.0 # onset refinement: the latest time within this of the best log ratio
1897
+
1898
+
1899
+ def refine_onset_times(onset_times: "Sequence[float]", step_s: float, pcm: "Sequence[float]",
1900
+ rate: int) -> "List[float]":
1901
+ """Each envelope-step onset time placed at the sample where the sound starts. Pure.
1902
+
1903
+ An onset picked on the step_s envelope is only known to the step: it is the start of the block
1904
+ the level rose in, so a click is reported up to one step early (5 ms on average at 10 ms).
1905
+ Around each one, over [t - step, t + 2 step], every candidate time c is scored by
1906
+ log(energy of [c, c + step]) - log(energy of [c - step, c]) -- the rise from the step before c
1907
+ to the step after it, which is largest where the sound starts. Ahead of a hit out of digital
1908
+ silence that score is flat (the window before is silent wherever it ends), so the LATEST
1909
+ candidate within BEAT_REFINE_TOL_NATS of the best is taken: past the start, the window before
1910
+ fills with the hit's own attack and the score falls off at once. Candidates are 0.25 ms apart.
1911
+ A time the PCM does not cover is returned unchanged.
1912
+ """
1913
+ rate = int(rate)
1914
+ w = max(1, int(round(step_s * rate)))
1915
+ hop = max(1, int(round(rate * 0.00025)))
1916
+ n = len(pcm)
1917
+ out: "List[float]" = []
1918
+ for t in onset_times:
1919
+ centre = int(round(t * rate))
1920
+ lo, hi = centre - w, centre + 2 * w
1921
+ if lo - w < 0 or hi + w > n:
1922
+ out.append(t)
1923
+ continue
1924
+ base = lo - w
1925
+ prefix = [0.0]
1926
+ acc = 0.0
1927
+ for x in pcm[base:hi + w + 1]:
1928
+ acc += x * x
1929
+ prefix.append(acc)
1930
+ scored = []
1931
+ for c in range(lo, hi + 1, hop):
1932
+ k = c - base
1933
+ before = (prefix[k] - prefix[k - w]) / w
1934
+ after = (prefix[k + w] - prefix[k]) / w
1935
+ scored.append((math.log(after + 1e-12) - math.log(before + 1e-12), c))
1936
+ best = max(sc for sc, _ in scored)
1937
+ c_best = max(c for sc, c in scored if sc >= best - BEAT_REFINE_TOL_NATS)
1938
+ out.append(c_best / rate)
1939
+ return out
1940
+
1941
+
1942
+ def _refine_grid(onset_times: "Sequence[float]", strengths: "Sequence[float]", interval: float,
1943
+ phase: float, lo_bpm: float, hi_bpm: float) -> "tuple":
1944
+ """(interval, phase) refitted by weighted least squares to the onsets that land on the grid.
1945
+
1946
+ Each grid point k is paired with the STRONGEST onset within interval/BEAT_ALIGN_DIVISOR of it
1947
+ (one per point: the weak onsets noise and a hit's own decay leave around a beat must not pull
1948
+ it), and onset_time = phase + k * interval is solved for both unknowns with each pair weighted
1949
+ by its onset strength squared; the pairing is then redone against the refitted grid, until it
1950
+ stops moving (three passes at most). This only sharpens the grid the autocorrelation chose --
1951
+ the tempo cannot leave `bpm_range` (a fit beyond a bound is held on it), an octave cannot flip (a refit that moves the interval by
1952
+ more than interval/BEAT_ALIGN_DIVISOR is discarded), and fewer than four paired grid points
1953
+ keep the original: the fit needs evidence, and an onset-free stretch gives it none.
1954
+ Returns phase in [0, interval).
1955
+ """
1956
+ iv, ph = float(interval), float(phase)
1957
+ for _ in range(3):
1958
+ tol = iv / BEAT_ALIGN_DIVISOR
1959
+ best: "Dict[int, tuple]" = {}
1960
+ for t, st in zip(onset_times, strengths):
1961
+ k = round((t - ph) / iv)
1962
+ if abs(t - (ph + k * iv)) <= tol and (k not in best or st > best[k][1]):
1963
+ best[k] = (t, st)
1964
+ pairs = [(k, t, max(st, 1e-9) ** 2) for k, (t, st) in best.items()]
1965
+ if len(pairs) < 4:
1966
+ break
1967
+ sw = sum(w for _, _, w in pairs)
1968
+ mk = sum(w * k for k, _, w in pairs) / sw
1969
+ mt = sum(w * t for _, t, w in pairs) / sw
1970
+ sxx = sum(w * (k - mk) ** 2 for k, _, w in pairs)
1971
+ if sxx <= 0:
1972
+ break
1973
+ new_iv = sum(w * (k - mk) * (t - mt) for k, t, w in pairs) / sxx
1974
+ if abs(new_iv - interval) > interval / BEAT_ALIGN_DIVISOR:
1975
+ break
1976
+ # A146: a fit just outside `bpm_range` is held on its bound, not discarded. A tempo that
1977
+ # sits on the bound (90 BPM under --beat-range 60-90) fits a hair beyond it as often as
1978
+ # inside, and discarding the fit kept the step-rounded interval (89.76 BPM), whose grid
1979
+ # was 80 ms off a 30 s click track by its end
1980
+ new_iv = min(max(new_iv, 60.0 / hi_bpm), 60.0 / lo_bpm)
1981
+ new_ph = mt - new_iv * mk
1982
+ moved = abs(new_iv - iv) < 1e-9 and abs(new_ph - ph) < 1e-7
1983
+ iv, ph = new_iv, new_ph
1984
+ if moved:
1985
+ break
1986
+ return iv, ph % iv
1987
+
1988
+
1989
+ def beat_grid(envelope: "Sequence[float]", step_s: float, *,
1990
+ bpm_range: "Sequence[float]" = (60, 200),
1991
+ min_confidence: float = BEAT_MIN_CONFIDENCE,
1992
+ duration: "Optional[float]" = None,
1993
+ pcm: "Optional[Sequence[float]]" = None,
1994
+ pcm_rate: "Optional[int]" = None) -> "Dict[str, Any]":
1995
+ """A beat grid from an RMS envelope. Pure: numbers in, a dict out -- no ffmpeg, no I/O.
1996
+
1997
+ Returns {"beats": [t, ...], "tempo_bpm": float|None, "interval": float|None,
1998
+ "confidence": 0..1, "onsets": [t, ...], "phase": float,
1999
+ "supported": int, "unsupported": int, "usable": bool,
2000
+ "method": "rms-flux-autocorrelation", "step_s": step_s, "range_bpm": [lo, hi],
2001
+ "onset_refinement": "pcm-window-ratio" | None}
2002
+
2003
+ `step_s` must be the envelope's real step (block samples / rate), not the one asked for:
2004
+ every time below is index * step_s. `pcm` and `pcm_rate`, when given, are the samples the
2005
+ envelope was built from; each onset is then placed on them (refine_onset_times) instead of at
2006
+ the start of its envelope block.
2007
+
2008
+ The method, in full, so a report can quote it:
2009
+ 1. onset strength = half-wave-rectified first difference of log(env + 1e-9);
2010
+ 2. onsets = local maxima above median + 1.5 * MAD over a +/-1 s window, 60 ms refractory,
2011
+ each placed to 0.25 ms on `pcm` when it is given;
2012
+ 3. tempo = the best autocorrelation lag of the onset signal inside `bpm_range`, with its
2013
+ half and double checked and the one whose onsets align better preferred (octave
2014
+ disambiguation: 60, 120 and 240 BPM all autocorrelate on a 120 BPM track);
2015
+ 4. phase = the offset in [0, interval) at which the grid catches the most onset strength;
2016
+ then interval and phase are refitted by least squares to the onsets within interval/8 of
2017
+ the grid (_refine_grid), so the tempo is not rounded to a whole number of envelope steps
2018
+ (until 3.2.0, at 10 ms, 90 BPM was measured as 0.67 s and the grid drifted 40-90 ms off the
2019
+ music over 30 s);
2020
+ 5. beats = phase + n * interval across the duration (a point within BEAT_ZERO_TOL_S, 10 ms,
2021
+ before 0 s is reported at 0.0; one further before is not reported). A grid must be regular, so a grid
2022
+ point with no measured onset within interval/4 is still reported -- and counted in
2023
+ `unsupported`, so a caller can see how much of the grid the audio actually supports.
2024
+ `supported_beats` is the subset that a measured onset does support: it is what a tool
2025
+ that MOVES something must snap to, because a regular grid runs on through a passage with
2026
+ no music in it and a point moved there was moved to a time nothing in the audio marks;
2027
+ 6. confidence = 0.5 * clip((z - 2) / 4, 0, 1)
2028
+ + 0.5 * (fraction of onsets within interval/8 of a grid point),
2029
+ where z is how many standard deviations the winning autocorrelation lag stands above
2030
+ the mean of the others. The plain peak/mean ratio is not used: every signal's
2031
+ autocorrelation has a maximum somewhere, so a peak above the mean says nothing -- noise
2032
+ scores 2.9 on it, which would read as full confidence.
2033
+
2034
+ A flat or empty envelope has no pulse: confidence 0.0, tempo None, beats []. That is a
2035
+ measurement, not a failure -- the caller decides whether 0.0 is enough to act on.
2036
+ """
2037
+ step_s = float(step_s)
2038
+ env = list(envelope or [])
2039
+ lo_bpm, hi_bpm = float(min(bpm_range)), float(max(bpm_range))
2040
+ out: "Dict[str, Any]" = {
2041
+ "beats": [], "supported_beats": [], "tempo_bpm": None, "interval": None,
2042
+ "confidence": 0.0, "onsets": [],
2043
+ "phase": 0.0, "supported": 0, "unsupported": 0, "usable": False,
2044
+ "method": "rms-flux-autocorrelation", "step_s": step_s, "range_bpm": [lo_bpm, hi_bpm],
2045
+ "onset_refinement": None,
2046
+ }
2047
+ if len(env) < 4 or step_s <= 0:
2048
+ return out
2049
+ total_s = float(duration) if duration else len(env) * step_s
2050
+
2051
+ strength = _onset_strength(env)
2052
+ if not any(strength):
2053
+ return out
2054
+ idx = _pick_onsets(strength, step_s)
2055
+ onset_times = [i * step_s for i in idx]
2056
+ if pcm and pcm_rate:
2057
+ # the PCM the envelope came from places each onset to the sample (refine_onset_times)
2058
+ onset_times = refine_onset_times(onset_times, step_s, pcm, int(pcm_rate))
2059
+ out["onset_refinement"] = "pcm-window-ratio"
2060
+ out["onsets"] = [round(t, 4) for t in onset_times]
2061
+ if len(idx) < 2:
2062
+ return out
2063
+
2064
+ best_lag, peak, mean_acc, sd_acc = _autocorrelation_peak(strength, step_s, (lo_bpm, hi_bpm))
2065
+ if not best_lag or peak <= 0:
2066
+ return out
2067
+ interval = best_lag * step_s
2068
+ strength_at = {i: strength[j] for i, j in enumerate(idx)}
2069
+
2070
+ # Octave disambiguation: try half and double the candidate interval and keep the one whose
2071
+ # grid catches the most onset strength per grid point (per point, or a denser grid always wins).
2072
+ candidates = [interval]
2073
+ for factor in (0.5, 2.0):
2074
+ alt = interval * factor
2075
+ if 60.0 / hi_bpm <= alt <= 60.0 / lo_bpm:
2076
+ candidates.append(alt)
2077
+
2078
+ def best_phase(iv: float) -> "tuple":
2079
+ steps = max(4, int(round(iv / step_s)))
2080
+ best_ph, best_sc = 0.0, -1.0
2081
+ for k in range(steps):
2082
+ ph = k * iv / steps
2083
+ sc = _grid_score(onset_times, strength_at, iv, ph)
2084
+ if sc > best_sc:
2085
+ best_ph, best_sc = ph, sc
2086
+ return best_ph, best_sc
2087
+
2088
+ # The winner is the grid that explains the most measured onset strength -- "more onsets fall
2089
+ # on it", the standard octave rule. An alternative must explain appreciably more (a fifth
2090
+ # again) to displace the autocorrelation's own answer: a half-tempo grid catches a subset of
2091
+ # the same onsets and a double-tempo grid catches the same set plus empty points, so a bare
2092
+ # ">" would flip the answer on noise.
2093
+ base_phase, base_score = best_phase(interval)
2094
+ interval, phase = interval, base_phase
2095
+ for alt in candidates[1:]:
2096
+ alt_phase, alt_score = best_phase(alt)
2097
+ if alt_score > base_score * BEAT_OCTAVE_MARGIN:
2098
+ interval, phase, base_score = alt, alt_phase, alt_score
2099
+
2100
+ # The autocorrelation lag is a whole number of envelope steps, so the interval it gives is the
2101
+ # true one rounded to step_s: 90 BPM (0.6667 s) comes out as 0.67 s at 10 ms, 3.3 ms per beat
2102
+ # that a phase+n*interval grid accumulates to tens of ms within a bar or two of either end
2103
+ # (40-90 ms over 30 s). Refit interval and phase to the onsets themselves (_refine_grid).
2104
+ interval, phase = _refine_grid(onset_times, [strength[j] for j in idx], interval, phase,
2105
+ lo_bpm, hi_bpm)
2106
+
2107
+ beats = []
2108
+ # The first grid point at or after 0, where "at" allows BEAT_ZERO_TOL_S (one 10 ms envelope
2109
+ # step, the accuracy the grid had before the refit): a track that starts on the beat has no
2110
+ # measurable onset at 0 (there is no step before it), so its phase is fitted from the later
2111
+ # beats and lands a few ms either side of 0 -- that is the beat at 0.0, not a dropped one. A
2112
+ # point further before 0 is not moved there: 0.0 would then be a time the grid does not mark
2113
+ # (a 120 BPM grid with phase 0.46 has its point at -0.04 s), and an onset at 0.08 s would make
2114
+ # it a "supported" snap target. Indexing by n instead of adding the interval up keeps the
2115
+ # float error of a long file out of the last beats.
2116
+ n = -1 if phase - interval >= -BEAT_ZERO_TOL_S else 0
2117
+ while True:
2118
+ t = phase + n * interval
2119
+ if t > total_s + 1e-9:
2120
+ break
2121
+ beats.append(round(max(0.0, t), 4))
2122
+ n += 1
2123
+ support_tol = interval / BEAT_SUPPORT_DIVISOR
2124
+ supported_beats = [b for b in beats
2125
+ if any(abs(b - o) <= support_tol for o in onset_times)]
2126
+ supported = len(supported_beats)
2127
+ align_tol = interval / BEAT_ALIGN_DIVISOR
2128
+ aligned = sum(1 for o in onset_times
2129
+ if min((o - phase) % interval, interval - (o - phase) % interval) <= align_tol)
2130
+
2131
+ # How many spreads the best lag stands above the rest of them, mapped onto [0, 1]: a click
2132
+ # track measures z ~= 6, a jittery human performance ~= 5, pseudo-random levels ~= 2.4, so
2133
+ # the band [BEAT_Z_FLOOR, BEAT_Z_FLOOR + BEAT_Z_SPAN] = [2, 6] is where the answer changes.
2134
+ z = ((peak - mean_acc) / sd_acc) if sd_acc > 0 else 0.0
2135
+ periodicity = max(0.0, min(1.0, (z - BEAT_Z_FLOOR) / BEAT_Z_SPAN))
2136
+ alignment = aligned / len(onset_times) if onset_times else 0.0
2137
+ confidence = round(0.5 * periodicity + 0.5 * alignment, 3)
2138
+
2139
+ out.update({
2140
+ "beats": beats, "supported_beats": supported_beats,
2141
+ "interval": round(interval, 6), "tempo_bpm": round(60.0 / interval, 2),
2142
+ "phase": round(phase, 4), "confidence": confidence, "supported": supported,
2143
+ "unsupported": len(beats) - supported,
2144
+ "usable": confidence >= float(min_confidence),
2145
+ })
2146
+ return out
2147
+
2148
+
2149
+ def snap_points(points: "Sequence[float]", beats: "Sequence[float]",
2150
+ tolerance: float) -> "List[Dict[str, Any]]":
2151
+ """Move each given point to the nearest beat within `tolerance` seconds.
2152
+
2153
+ Pure. Returns [{"from": t, "to": t2, "delta": d, "snapped": bool, "beat_index": i|None}].
2154
+ A point with no beat inside `tolerance` is returned unchanged with snapped=False.
2155
+
2156
+ NEVER invents a point: len(out) == len(points), always, and every `to` is either a value that
2157
+ was in `beats` or the caller's own `from`. This is the whole no-fabrication rule for beat
2158
+ snapping -- a cut point may move to a measured grid point, and may not appear from one.
2159
+ """
2160
+ grid = sorted(float(b) for b in (beats or []))
2161
+ out: "List[Dict[str, Any]]" = []
2162
+ for p in points:
2163
+ p = float(p)
2164
+ best_i, best_d = None, None
2165
+ for i, b in enumerate(grid):
2166
+ d = abs(b - p)
2167
+ if best_d is None or d < best_d:
2168
+ best_i, best_d = i, d
2169
+ if best_i is not None and best_d is not None and best_d <= float(tolerance):
2170
+ out.append({"from": p, "to": grid[best_i], "delta": round(grid[best_i] - p, 6),
2171
+ "snapped": True, "beat_index": best_i})
2172
+ else:
2173
+ out.append({"from": p, "to": p, "delta": 0.0, "snapped": False, "beat_index": None})
2174
+ return out
2175
+
2176
+
2177
+ # ------------------------------------------------------------- filler words (1.17)
2178
+ #
2179
+ # A filler word is removed only when a speech engine measured a start/end pair for it. There is no
2180
+ # heuristic fallback -- no "cut the 0.3 s blips that look like an 'um'", no language guess from the
2181
+ # filename. Without timings there is nothing to cut, and the tool says so.
2182
+ #
2183
+ # What is NOT in these lists is the substance of the decision. "like", "tipo" and "cioè" are
2184
+ # discourse markers, not disfluencies: they are grammatical words in most sentences, and removing
2185
+ # them cuts meaning rather than noise. That is a judgement about content, which this skill does not
2186
+ # make. They are reachable with --filler-extra, and documented as what they are.
2187
+ FILLER_WORDS = {
2188
+ "en": frozenset({"um", "uh", "erm", "hmm", "mm", "mhm", "er", "ah"}),
2189
+ # なんか is the most common Japanese filler AND a pronoun/adverb spelled identically. It is in the
2190
+ # default list because leaving it out makes --filler useless for Japanese, and every run that
2191
+ # removes one warns that it is often a content word (--filler-keep なんか takes it out).
2192
+ "ja": frozenset({"えー", "えーと", "えっと", "あの", "あのー", "その", "そのー", "まあ", "なんか"}),
2193
+ "es": frozenset({"eh", "este", "esto", "mmm"}),
2194
+ "de": frozenset({"äh", "ähm", "hm"}),
2195
+ "fr": frozenset({"euh", "hein"}),
2196
+ "pt": frozenset({"é", "hum"}),
2197
+ "it": frozenset({"ehm"}),
2198
+ # 2.19: Korean is written with spaces, so a whisper word is a word and the list works as the
2199
+ # English one does. 그/저/뭐/이제 are fillers as often as they are "that"/"I"/"what"/"now":
2200
+ # discourse markers below, not defaults.
2201
+ "ko": frozenset({"음", "으음", "음음", "어", "어어", "에", "흠"}),
2202
+ # Chinese has no spaces: these match only as a whole token with a boundary on each side
2203
+ # (filler_spans), so the 额 of 金额 or the 呃 inside a word is never cut. 额 itself is left
2204
+ # out: it is a common character in its own right.
2205
+ "zh": frozenset({"嗯", "嗯嗯", "呃", "呃呃", "唔"}),
2206
+ "ru": frozenset({"э", "ээ", "эм", "эмм", "мм", "хм"}),
2207
+ "nl": frozenset({"eh", "ehm", "uh", "uhm", "hm"}),
2208
+ "pl": frozenset({"yyy", "yy", "eee", "ee", "em", "emm", "hmm"}),
2209
+ "tr": frozenset({"ıı", "ııı", "ee", "eee", "hmm"}),
2210
+ }
2211
+
2212
+ # Words in a default list that are also ordinary vocabulary: every run that removes one says so.
2213
+ FILLER_AMBIGUOUS = {
2214
+ "ja": frozenset({"なんか", "あの", "その", "まあ"}),
2215
+ "es": frozenset({"este", "esto"}),
2216
+ "pt": frozenset({"é"}),
2217
+ }
2218
+
2219
+ # Discourse markers people ask for by name. Not defaults; named here so --help and the docs can
2220
+ # say what adding one costs.
2221
+ FILLER_DISCOURSE_MARKERS = {
2222
+ "en": ("like", "you know"),
2223
+ "pt": ("tipo",),
2224
+ "it": ("cioè",),
2225
+ "ko": ("그", "저", "뭐", "이제", "약간", "막", "그니까"),
2226
+ "zh": ("那个", "这个", "就是", "然后"),
2227
+ "ru": ("ну", "типа", "короче", "как бы"),
2228
+ "nl": ("nou", "dus", "zeg maar"),
2229
+ "pl": ("no", "jakby", "wiesz", "znaczy"),
2230
+ "tr": ("şey", "yani", "işte"),
2231
+ }
2232
+
2233
+ FILLER_MAX_WORD = 1.2 # a longer "uhhh" is a held vowel someone meant
2234
+ FILLER_MIN_GAP = 0.05 # spans closer than this become one span
2235
+ FILLER_PAD = 0.02 # trimmed either side of the word
2236
+ FILLER_MAX_TOKENS = 4 # a listed word may span this many engine tokens ("えー" + "と", "you" + "know")
2237
+ FILLER_BOUNDARY_GAP = 0.1 # a pause this long between two tokens is a word boundary
2238
+
2239
+
2240
+ def _unspaced_script(text: str) -> bool:
2241
+ """True when `text` has a character of a script written without spaces between words (Han,
2242
+ kana, Thai, Lao, Myanmar, Khmer). Whisper splits those languages into tokens, not words, so a
2243
+ token boundary there says nothing about a word boundary. Hangul is spaced and not listed."""
2244
+ for ch in text:
2245
+ o = ord(ch)
2246
+ if (0x3040 <= o <= 0x30FF or 0x31F0 <= o <= 0x31FF or 0xFF66 <= o <= 0xFF9F # kana
2247
+ or 0x3400 <= o <= 0x4DBF or 0x4E00 <= o <= 0x9FFF or 0xF900 <= o <= 0xFAFF # Han
2248
+ or 0x20000 <= o <= 0x323AF # Han extensions B-H
2249
+ or 0x0E00 <= o <= 0x0EFF or 0x1000 <= o <= 0x109F or 0x1780 <= o <= 0x17FF): # Thai, Lao, Myanmar, Khmer
2250
+ return True
2251
+ return False
2252
+
2253
+
2254
+ def normalise_filler_token(word: str) -> str:
2255
+ """A spoken token stripped to what a word list can be compared against: case-folded, with
2256
+ surrounding punctuation and whitespace removed. Never a substring match -- "umbrella" must
2257
+ survive a list containing "um"."""
2258
+ import unicodedata as _ud
2259
+ text = str(word or "").strip()
2260
+ text = "".join(ch for ch in text
2261
+ if not _ud.category(ch).startswith("P") or ch in "-'’")
2262
+ return text.strip("-'’").casefold()
2263
+
2264
+
2265
+ def filler_spans(words, wordlist, *, pad: float = FILLER_PAD, min_gap: float = FILLER_MIN_GAP,
2266
+ max_word: float = FILLER_MAX_WORD, stats: "Optional[Dict[str, int]]" = None) -> "List[Dict[str, Any]]":
2267
+ """Time spans to remove, from measured word timings. Pure: no subprocess, no I/O.
2268
+
2269
+ `words` is [{"word", "start", "end"}] as whisper emits. A run of up to FILLER_MAX_TOKENS
2270
+ consecutive entries is removed only when the run, joined with or without spaces and
2271
+ normalised, is in `wordlist` AND every entry carries a real start < end pair AND the run is
2272
+ <= max_word long. The longest run wins. Adjacent spans closer than min_gap merge. Returns
2273
+ [{"start", "end", "word"}] sorted and non-overlapping.
2274
+
2275
+ Whisper splits Chinese, Japanese and Thai into tokens rather than words ("えーと" arrives as
2276
+ "えー" + "と", "金额" as "金" + "额"), so a run in such a script also needs a word boundary on
2277
+ each side: the start or end of the transcript, punctuation, a spaced-script neighbour, or a
2278
+ pause of FILLER_BOUNDARY_GAP. Without one the run is part of a longer word and is kept.
2279
+
2280
+ `stats`, when given, receives the listed words that were kept anyway, so the caller can say
2281
+ so: `matched_untimed` (no usable start < end: nothing to cut on) and `matched_too_long`
2282
+ (longer than max_word: a held vowel someone meant).
2283
+ """
2284
+ import unicodedata as _ud
2285
+ listed = {normalise_filler_token(w) for w in (wordlist or set())}
2286
+ listed.discard("")
2287
+ toks = []
2288
+ for entry in words or []:
2289
+ if not isinstance(entry, dict):
2290
+ continue
2291
+ raw = str(entry.get("word") or entry.get("text") or "").strip()
2292
+ try:
2293
+ start, end = float(entry["start"]), float(entry["end"])
2294
+ timed = end > start
2295
+ except (KeyError, TypeError, ValueError):
2296
+ start = end = 0.0
2297
+ timed = False
2298
+ toks.append({"norm": normalise_filler_token(raw), "start": start, "end": end, "timed": timed,
2299
+ "punct_before": bool(raw) and _ud.category(raw[0]).startswith("P"),
2300
+ "punct_after": bool(raw) and _ud.category(raw[-1]).startswith("P")})
2301
+
2302
+ def _bounded(i: int, j: int) -> bool:
2303
+ """A word boundary before toks[i] and after toks[j - 1]."""
2304
+ left = (i == 0 or toks[i]["punct_before"] or toks[i - 1]["punct_after"] or not toks[i - 1]["norm"]
2305
+ or not _unspaced_script(toks[i - 1]["norm"])
2306
+ or (toks[i - 1]["timed"] and toks[i]["start"] - toks[i - 1]["end"] >= FILLER_BOUNDARY_GAP - 1e-6))
2307
+ right = (j == len(toks) or toks[j - 1]["punct_after"] or toks[j]["punct_before"] or not toks[j]["norm"]
2308
+ or not _unspaced_script(toks[j]["norm"])
2309
+ or (toks[j]["timed"] and toks[j]["start"] - toks[j - 1]["end"] >= FILLER_BOUNDARY_GAP - 1e-6))
2310
+ return left and right
2311
+
2312
+ hits = []
2313
+ untimed = too_long = 0
2314
+ i = 0
2315
+ while i < len(toks):
2316
+ found = 0
2317
+ rejected = None
2318
+ for k in range(min(FILLER_MAX_TOKENS, len(toks) - i), 0, -1):
2319
+ run = toks[i:i + k]
2320
+ norms = [t["norm"] for t in run]
2321
+ if not all(norms):
2322
+ continue
2323
+ unspaced = any(_unspaced_script(n) for n in norms)
2324
+ joined = ("" if unspaced else " ").join(norms)
2325
+ if joined not in listed or (unspaced and not _bounded(i, i + k)):
2326
+ continue
2327
+ # punctuation inside the run ("えー、" + "と") ends the word: the shorter run decides
2328
+ if any(run[m]["punct_after"] or run[m + 1]["punct_before"] for m in range(k - 1)):
2329
+ continue
2330
+ # so does a pause inside an unspaced run: the tokens were two words
2331
+ if unspaced and any(run[m]["timed"] and run[m + 1]["timed"]
2332
+ and run[m + 1]["start"] - run[m]["end"] >= FILLER_BOUNDARY_GAP - 1e-6
2333
+ for m in range(k - 1)):
2334
+ continue
2335
+ # a run listed out of time order has no span to cut on
2336
+ if not all(t["timed"] for t in run) or run[-1]["end"] <= run[0]["start"]:
2337
+ rejected = rejected or ("untimed", k)
2338
+ continue
2339
+ if run[-1]["end"] - run[0]["start"] > max_word:
2340
+ rejected = rejected or ("too_long", k)
2341
+ continue
2342
+ hits.append({"start": max(0.0, run[0]["start"] - pad), "end": run[-1]["end"] + pad, "word": joined})
2343
+ found = k
2344
+ break
2345
+ if not found and rejected:
2346
+ # the longest listed run that could not be cut is the one reported. Its prefixes were
2347
+ # tried here; moving on by one token lets a listed word later in it be tried too
2348
+ untimed += rejected[0] == "untimed"
2349
+ too_long += rejected[0] == "too_long"
2350
+ found = 1
2351
+ i += found or 1
2352
+ hits.sort(key=lambda h: (h["start"], h["end"]))
2353
+ merged: "List[Dict[str, Any]]" = []
2354
+ for h in hits:
2355
+ if merged and h["start"] - merged[-1]["end"] <= min_gap:
2356
+ merged[-1]["end"] = max(merged[-1]["end"], h["end"])
2357
+ merged[-1]["word"] = merged[-1]["word"] + " " + h["word"]
2358
+ else:
2359
+ merged.append(dict(h))
2360
+ for m in merged:
2361
+ m["start"] = round(m["start"], 4)
2362
+ m["end"] = round(m["end"], 4)
2363
+ if stats is not None:
2364
+ stats["matched_untimed"] = untimed
2365
+ stats["matched_too_long"] = too_long
2366
+ return merged
2367
+
2368
+
2369
+ # --- 1.18.0: lightweight block-matching motion estimate (scenes.py --shots, cropdetect.py
2370
+ # --motion-centre) ---------------------------------------------------------------------------
2371
+
2372
+ MOTION_GRID = 4 # NxN anchor blocks per frame
2373
+ MOTION_SEARCH = 3 # +/- pixels searched per block, at the decoded (low) resolution
2374
+ MOTION_STATIC_PX = 0.35 # average per-frame displacement below this, at decode resolution, is "static"
2375
+ MOTION_PAN_SPREAD = 0.6 # block-to-block direction agreement above this (0..1) reads as a pan
2376
+
2377
+
2378
+ def _block_match(prev: bytes, cur: bytes, w: int, h: int, cx: int, cy: int, half: int, search: int) -> "Tuple[float, float]":
2379
+ """(dx, dy) that best aligns a `half*2` square centred at (cx, cy) in `prev` to `cur`,
2380
+ searched over +/- `search` px by sum-of-absolute-differences. Coordinates and the returned
2381
+ offset are in decoded-frame pixels (a handful of pixels a side at 1.18.0's sample size)."""
2382
+ x0, y0 = max(half, min(w - half - 1, cx)), max(half, min(h - half - 1, cy))
2383
+ ref = [prev[(y0 + dy) * w + (x0 + dx)] for dy in range(-half, half + 1) for dx in range(-half, half + 1)]
2384
+
2385
+ def sad_at(xx: int, yy: int) -> "Optional[int]":
2386
+ if xx - half < 0 or xx + half >= w or yy - half < 0 or yy + half >= h:
2387
+ return None
2388
+ sad = 0
2389
+ for dy in range(-half, half + 1):
2390
+ row = (yy + dy) * w
2391
+ for dx in range(-half, half + 1):
2392
+ sad += abs(ref[(dy + half) * (2 * half + 1) + (dx + half)] - cur[row + xx + dx])
2393
+ return sad
2394
+
2395
+ # Zero shift is the tie-break candidate, not the search order's first cell: on a textureless
2396
+ # block (a flat colour, sky, an out-of-focus background) every offset scores the same SAD, and
2397
+ # without an explicit tie towards "no motion" the scan used to report the search window's
2398
+ # first corner as the measured displacement -- a still frame with nothing to match against
2399
+ # read as steady motion in one direction, every time.
2400
+ best_sad, best = sad_at(x0, y0), (0.0, 0.0)
2401
+ if best_sad is None:
2402
+ best_sad = float("inf")
2403
+ for sy in range(-search, search + 1):
2404
+ for sx in range(-search, search + 1):
2405
+ if sx == 0 and sy == 0:
2406
+ continue
2407
+ sad = sad_at(x0 + sx, y0 + sy)
2408
+ if sad is not None and sad < best_sad:
2409
+ best_sad, best = sad, (float(sx), float(sy))
2410
+ return best
2411
+
2412
+
2413
+ def frame_flow(prev: bytes, cur: bytes, w: int, h: int, *, grid: int = MOTION_GRID,
2414
+ search: int = MOTION_SEARCH) -> "Dict[str, Any]":
2415
+ """One measurement between two consecutive decoded grayscale frames: the mean block
2416
+ displacement vector, its magnitude, and how consistently the blocks agree on direction
2417
+ (0 = every block moved a different way, 1 = every block agrees -- a pan or dolly moves the
2418
+ whole frame one way, on-screen motion inside a mostly-static frame does not)."""
2419
+ half = max(1, min(w, h) // (grid * 3))
2420
+ vecs: "List[Tuple[float, float]]" = []
2421
+ for gy in range(grid):
2422
+ for gx in range(grid):
2423
+ cx = int((gx + 0.5) * w / grid)
2424
+ cy = int((gy + 0.5) * h / grid)
2425
+ vecs.append(_block_match(prev, cur, w, h, cx, cy, half, search))
2426
+ mdx = sum(v[0] for v in vecs) / len(vecs)
2427
+ mdy = sum(v[1] for v in vecs) / len(vecs)
2428
+ magnitude = math.hypot(mdx, mdy)
2429
+ mean_len = sum(math.hypot(*v) for v in vecs) / len(vecs)
2430
+ agreement = (magnitude / mean_len) if mean_len > 1e-6 else 1.0 # 1.0 = every block agrees
2431
+ return {"dx": mdx, "dy": mdy, "magnitude": magnitude, "agreement": min(1.0, agreement)}
2432
+
2433
+
2434
+ def label_shot_flow(flows: "Sequence[Dict[str, Any]]") -> "Dict[str, Any]":
2435
+ """{label, flow_magnitude} for one shot from its per-frame-pair flow measurements.
2436
+
2437
+ static: mean displacement below MOTION_STATIC_PX. pan: above it, and blocks agree on
2438
+ direction (a camera move shifts the whole frame). motion: above it, blocks disagree (motion
2439
+ inside an otherwise still frame -- handheld jitter, or a subject moving across a static
2440
+ background). This is a measured proxy, the same spirit as scenes.py --rank-by: it reports
2441
+ what a coarse block match saw, not what is interesting about the shot."""
2442
+ if not flows:
2443
+ return {"label": "static", "flow_magnitude": 0.0}
2444
+ magnitude = sum(f["magnitude"] for f in flows) / len(flows)
2445
+ agreement = sum(f["agreement"] for f in flows) / len(flows)
2446
+ if magnitude < MOTION_STATIC_PX:
2447
+ label = "static"
2448
+ elif agreement >= MOTION_PAN_SPREAD:
2449
+ label = "pan"
2450
+ else:
2451
+ label = "motion"
2452
+ return {"label": label, "flow_magnitude": round(magnitude, 3)}