@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,875 @@
1
+ """Fonts and scripts: the per-script font tables, script detection, fontconfig lookups
2
+ (fc-match / fc-list / fc-scan) and the font-for-this-text resolution the drawing tools use.
3
+ Split out of _common.text in the refactor after 1.17.3; every body is byte-identical.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import platform
9
+ import re
10
+ import struct
11
+ import subprocess
12
+ import unicodedata
13
+ from pathlib import Path
14
+ from typing import Dict, List, Optional, Sequence, Tuple
15
+ from _common.emit import die, info, record_fallback, warn
16
+ from _common.emoji import _is_emoji_char
17
+ from _common.runner import safe_which as _safe_which
18
+
19
+
20
+ def default_font_file(font_name: str) -> Optional[str]:
21
+ """Resolve `font_name` to a concrete on-disk font file, so a caller can tell drawtext
22
+ `fontfile=<path>` instead of `font=<name>`, when possible (resolve_font()'s `file`).
23
+
24
+ On some real Windows ffmpeg builds (winget's gyan.dev 9.x), drawtext's own fontconfig
25
+ resolution crashes with an access violation whenever it has to resolve a font by family name
26
+ -- with or without a valid fonts.conf on FONTCONFIG_FILE. `fontfile=` is the only form
27
+ confirmed not to crash (#100), since it never touches fontconfig at all. On Windows the
28
+ requested family is looked for by file name in the Fonts folder; a family that is not there
29
+ falls back to a CJK system font (for a CJK-looking request) or Arial, a near-universally-present
30
+ system font, instead of trying to resolve the requested family (which would crash the same way).
31
+
32
+ On Linux/macOS this is best-effort and uses the real requested family: `fc-match` reports the
33
+ same file fontconfig would resolve `font_name` to anyway, so a caller gets the identical font,
34
+ just already resolved to a path -- fontfile= skips a redundant fontconfig lookup and equally
35
+ sidesteps the same class of crash if it exists on some build there too, but the fallback below
36
+ (returning None) is exercised routinely there, not just on failure.
37
+
38
+ Returns None when nothing could be resolved (fc-match missing/unavailable, or no well-known
39
+ Windows font file present); the caller falls back to font=<font_name>, the prior behaviour.
40
+ """
41
+ return resolve_font(font_name)["file"]
42
+
43
+
44
+ # generic fontconfig aliases: resolving one to a concrete family is what they are for, not a substitution
45
+ _GENERIC_FAMILIES = {"sans", "sansserif", "serif", "mono", "monospace", "cursive", "fantasy", "systemui", "emoji"}
46
+
47
+
48
+ def _family_key(name: "Optional[str]") -> str:
49
+ return re.sub(r"[^a-z0-9]", "", (name or "").lower())
50
+
51
+
52
+ def resolve_font(font_name: str) -> "Dict[str, object]":
53
+ """default_font_file() with what it found: {file, family, substituted, via}. `substituted` is
54
+ True when the file is not the requested family -- a Windows machine without it (a CJK system
55
+ font or Arial instead), or fc-match answering with another family (fontconfig always answers
56
+ something). `via` is windows_fonts or fc-match; file and family are None when nothing resolved."""
57
+ none: "Dict[str, object]" = {"file": None, "family": None, "substituted": False, "via": None}
58
+ if platform.system() == "Windows":
59
+ windir = os.environ.get("WINDIR", "C:\\Windows")
60
+ fonts = Path(windir) / "Fonts"
61
+ # The requested family first: a file whose name starts with the family name with spaces
62
+ # removed (Noto Sans CJK JP -> NotoSansCJKjp-Regular.otf, Meiryo -> meiryo.ttc), then the
63
+ # common CJK system fonts when the request looks CJK (so Japanese text does not render as
64
+ # boxes in Arial), and Arial only as the last resort.
65
+ wanted = _family_key(font_name)
66
+ # The family's own file first, from the table of what Windows installs under which file
67
+ # name (#414): "Malgun Gothic" is malgun.ttf and "Times New Roman" times.ttf, which no
68
+ # file-name prefix finds -- the prefix rule resolved them to YuGothM.ttc and arial.ttf and
69
+ # reported a font that is installed as substituted.
70
+ for name in windows_family_files(wanted):
71
+ if (fonts / name).is_file():
72
+ return {"file": str(fonts / name), "family": font_name, "substituted": False, "via": "windows_fonts"}
73
+ try:
74
+ files = sorted(fonts.iterdir()) if fonts.is_dir() else []
75
+ except OSError:
76
+ files = []
77
+ if wanted:
78
+ for f in files:
79
+ stem = _family_key(f.stem)
80
+ if f.suffix.lower() in (".ttf", ".otf", ".ttc") and stem.startswith(wanted):
81
+ return {"file": str(f), "family": font_name, "substituted": False, "via": "windows_fonts"}
82
+ if any(k in wanted for k in ("cjk", "gothic", "mincho", "meiryo", "yugoth", "msgothic", "malgun", "simhei", "simsun", "jp", "kr", "sc", "tc")):
83
+ for name in ("NotoSansCJKjp-Regular.otf", "NotoSansCJK-Regular.ttc", "meiryo.ttc", "YuGothM.ttc", "msgothic.ttc", "malgun.ttf", "msyh.ttc"):
84
+ if (fonts / name).exists():
85
+ return {"file": str(fonts / name), "family": Path(name).stem, "substituted": bool(wanted), "via": "windows_fonts"}
86
+ candidate = fonts / "arial.ttf"
87
+ if candidate.exists():
88
+ return {"file": str(candidate), "family": "Arial",
89
+ "substituted": bool(wanted) and wanted != "arial" and wanted not in _GENERIC_FAMILIES, "via": "windows_fonts"}
90
+ return none
91
+ exe = _safe_which("fc-match")
92
+ if not exe:
93
+ return none
94
+ try:
95
+ proc = subprocess.run([exe, "--format=%{file}\n%{family}\n", font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=5)
96
+ except (subprocess.TimeoutExpired, OSError):
97
+ return none
98
+ if proc.returncode != 0:
99
+ return none
100
+ lines = proc.stdout.splitlines()
101
+ path = lines[0].strip() if lines else ""
102
+ if not (path and os.path.exists(path)):
103
+ return none
104
+ # fontconfig lists a face's family names comma-separated (localised names included); the
105
+ # request is met when one of them is the requested family, or the request names a style of it
106
+ families = [f.strip() for f in (lines[1] if len(lines) > 1 else "").split(",") if f.strip()]
107
+ wanted = _family_key(font_name)
108
+ met = (not wanted or wanted in _GENERIC_FAMILIES or not families
109
+ or any(_family_key(f) and (wanted.startswith(_family_key(f)) or _family_key(f).startswith(wanted)) for f in families))
110
+ return {"file": path, "family": families[0] if families else None, "substituted": not met, "via": "fc-match"}
111
+
112
+
113
+ def font_choice(asked: "Optional[str]", *, font_file: "Optional[str]" = None, script_file: "Optional[str]" = None,
114
+ script_family: "Optional[str]" = None, renderer: str = "drawtext",
115
+ bold: bool = False) -> "Dict[str, object]":
116
+ """The font a text-drawing tool draws with, as its result's `font_used`: {asked, file, family,
117
+ how, substituted}. `how`: font_file (the caller's own file), script (a font picked to cover the
118
+ text's script, 1.12), resolved (the asked family resolved to a file: fc-match, or the Windows
119
+ Fonts folder), by_name (no file resolved; ffmpeg/libass look the family up themselves, so the
120
+ file is not known here). For libass (`renderer="libass"`) a resolved file is the one fontconfig
121
+ picks for the family, which is what libass loads through fontconfig; on Windows libass is
122
+ given the family by name, so nothing is resolved for it.
123
+
124
+ `bold` (libass drawing a Bold style): libass asks fontconfig for the family at bold weight, so
125
+ the file reported is the one `fc-match FAMILY:bold` names -- the family's bold face where it
126
+ has one, its regular face (emboldened by libass) where it has none. The regular face was
127
+ reported whatever was drawn (A70, #457). Not on Windows, where nothing is resolved for libass."""
128
+ weight = ":bold" if bold and renderer == "libass" and platform.system() != "Windows" else ""
129
+ if font_file:
130
+ return {"asked": font_file, "file": font_file, "family": None, "how": "font_file", "substituted": False}
131
+ if script_file:
132
+ if weight and script_family:
133
+ face = resolve_font(script_family + weight)
134
+ if face["file"] and not face["substituted"]:
135
+ script_file = face["file"]
136
+ return {"asked": asked, "file": script_file, "family": script_family, "how": "script", "substituted": False}
137
+ if renderer == "libass" and platform.system() == "Windows":
138
+ return {"asked": asked, "file": None, "family": asked, "how": "by_name", "substituted": None}
139
+ found = resolve_font((asked or "") + weight)
140
+ if not found["file"]:
141
+ return {"asked": asked, "file": None, "family": asked, "how": "by_name", "substituted": None}
142
+ return {"asked": asked, "file": found["file"], "family": found["family"], "how": "resolved",
143
+ "substituted": bool(found["substituted"]), "via": found["via"]}
144
+
145
+
146
+ def record_font_choice(choice: "Dict[str, object]") -> "Dict[str, object]":
147
+ """Record a substituted font (`diagnostics.fallbacks`, `font_substituted`) and return `choice`
148
+ for the result's `font_used`: fontconfig answers every request with some font, and drawtext and
149
+ libass draw with it and exit 0, so without this the only trace was the picture."""
150
+ if choice.get("substituted"):
151
+ record_fallback(f"font: '{choice['asked']}' is not installed here; drawing with {choice.get('family') or '?'} "
152
+ f"({choice['file']}) instead", "font_substituted",
153
+ asked=choice["asked"], file=choice["file"], family=choice.get("family"), via=choice.get("via"))
154
+ return choice
155
+
156
+
157
+ # --------------------------------------------------------------------------- script detection
158
+ # 1.12: non-Latin caption/overlay text used to render as tofu (empty boxes) whenever the default
159
+ # family carried no glyphs for it -- silently, because fontconfig substitutes SOMETHING for every
160
+ # request and ffmpeg exits 0 either way. The tools now detect the script of the text they are about
161
+ # to draw and resolve a font file that actually covers it; nothing found is a failed job, not a
162
+ # warning (a video full of boxes is not a delivery).
163
+ # A65 (#457): gu, pa, te, kn, ml, si, km and my were in SHAPING_SCRIPTS but had no range
164
+ # below, so their text was detected as Latin, drawn in the Latin font and reported verified.
165
+ SCRIPTS = ("ja", "zh", "ko", "ar", "he", "hi", "bn", "pa", "gu", "ta", "te", "kn", "ml", "si", "th", "lo",
166
+ "km", "my", "ru", "el", "vi", "latin")
167
+
168
+
169
+ LANGUAGE_NAMES = {
170
+ "ja": "Japanese", "zh": "Chinese", "ko": "Korean", "ar": "Arabic", "he": "Hebrew",
171
+ "hi": "Devanagari (Hindi/Marathi/Nepali)", "th": "Thai", "ru": "Cyrillic (Russian and others)",
172
+ "el": "Greek", "latin": "Latin", "bn": "Bengali", "ta": "Tamil", "lo": "Lao",
173
+ "pa": "Gurmukhi (Punjabi)", "gu": "Gujarati", "te": "Telugu", "kn": "Kannada", "ml": "Malayalam",
174
+ "si": "Sinhala", "km": "Khmer", "my": "Myanmar (Burmese)",
175
+ "zh-hant": "Traditional Chinese", "vi": "Vietnamese",
176
+ }
177
+
178
+
179
+ # fontconfig's own :lang= codes for each script we detect (zh uses zh-cn, the Simplified subset
180
+ # every CJK font that claims zh carries; the rest are the plain two-letter codes).
181
+ FC_LANG = {"ja": "ja", "zh": "zh-cn", "ko": "ko", "ar": "ar", "he": "he", "hi": "hi", "th": "th", "ru": "ru", "el": "el",
182
+ "bn": "bn", "ta": "ta", "lo": "lo", "zh-hant": "zh-tw", "vi": "vi",
183
+ "pa": "pa", "gu": "gu", "te": "te", "kn": "kn", "ml": "ml", "si": "si", "km": "km", "my": "my"}
184
+
185
+
186
+ # Families tried in order, best first. The names are matched case-insensitively against the start
187
+ # of any family fontconfig reports for a file, so "Noto Sans CJK JP" also matches
188
+ # "Noto Sans CJK JP Black". Anything not listed still qualifies -- it just sorts after these.
189
+ PREFERRED_FAMILIES = {
190
+ "ja": ["Noto Sans CJK JP", "Noto Serif CJK JP", "Noto Sans JP", "Source Han Sans", "IPAPGothic", "IPAGothic", "IPA", "VL Gothic", "TakaoGothic", "WenQuanYi Zen Hei"],
191
+ "zh": ["Noto Sans CJK SC", "Noto Serif CJK SC", "Noto Sans SC", "Source Han Sans", "WenQuanYi Zen Hei", "WenQuanYi Micro Hei", "Droid Sans Fallback"],
192
+ "zh-hant": ["Noto Sans CJK TC", "Noto Serif CJK TC", "Noto Sans CJK HK", "Noto Sans TC", "Noto Sans HK", "Source Han Sans TW",
193
+ "Source Han Sans HC", "AR PL UMing TW", "AR PL UKai TW", "PingFang TC", "WenQuanYi Zen Hei", "Droid Sans Fallback"],
194
+ "ko": ["Noto Sans CJK KR", "Noto Serif CJK KR", "Noto Sans KR", "Source Han Sans K", "NanumGothic", "Nanum Gothic", "Malgun Gothic", "WenQuanYi Zen Hei"],
195
+ "ar": ["Noto Sans Arabic", "Noto Naskh Arabic", "Amiri", "Scheherazade", "DejaVu Sans", "FreeSans", "FreeSerif"],
196
+ "he": ["Noto Sans Hebrew", "Noto Serif Hebrew", "DejaVu Sans", "FreeSans", "FreeSerif"],
197
+ "hi": ["Noto Sans Devanagari", "Noto Serif Devanagari", "Lohit Devanagari", "Mangal", "Nirmala UI", "Samyak Devanagari", "FreeSans", "FreeSerif"],
198
+ "th": ["Noto Sans Thai", "Noto Serif Thai", "Loma", "Garuda", "Waree", "Umpush", "Norasi", "Sarabun", "Leelawadee UI", "FreeSerif"],
199
+ "bn": ["Noto Sans Bengali", "Noto Serif Bengali", "Lohit Bengali", "Mukti Narrow", "Vrinda", "Nirmala UI", "FreeSerif"],
200
+ "ta": ["Noto Sans Tamil", "Noto Serif Tamil", "Lohit Tamil", "Latha", "Nirmala UI", "FreeSerif"],
201
+ "lo": ["Noto Sans Lao", "Noto Serif Lao", "Phetsarath OT", "Souliyo Unicode", "Saysettha OT", "DokChampa", "Leelawadee UI"],
202
+ "pa": ["Noto Sans Gurmukhi", "Noto Serif Gurmukhi", "Lohit Gurmukhi", "Raavi", "Nirmala UI", "FreeSerif"],
203
+ "gu": ["Noto Sans Gujarati", "Noto Serif Gujarati", "Lohit Gujarati", "Shruti", "Nirmala UI", "FreeSerif"],
204
+ "te": ["Noto Sans Telugu", "Noto Serif Telugu", "Lohit Telugu", "Gautami", "Nirmala UI"],
205
+ "kn": ["Noto Sans Kannada", "Noto Serif Kannada", "Lohit Kannada", "Tunga", "Nirmala UI"],
206
+ "ml": ["Noto Sans Malayalam", "Noto Serif Malayalam", "Lohit Malayalam", "Kartika", "Nirmala UI"],
207
+ "si": ["Noto Sans Sinhala", "Noto Serif Sinhala", "LKLUG", "Iskoola Pota", "Nirmala UI"],
208
+ "km": ["Noto Sans Khmer", "Noto Serif Khmer", "Khmer OS", "Leelawadee UI", "Khmer UI"],
209
+ "my": ["Noto Sans Myanmar", "Noto Serif Myanmar", "Padauk", "Myanmar Text"],
210
+ "ru": ["Noto Sans", "DejaVu Sans", "Liberation Sans", "FreeSans", "FreeSerif"],
211
+ "el": ["Noto Sans", "DejaVu Sans", "Liberation Sans", "FreeSans", "FreeSerif"],
212
+ "vi": ["Noto Sans", "DejaVu Sans", "Arial", "Liberation Sans"],
213
+ }
214
+
215
+
216
+ # Windows has no fontconfig: the system fonts are looked up by file name instead, best first.
217
+ WINDOWS_FONTS = {
218
+ "ko": [("malgun.ttf", "Malgun Gothic"), ("gulim.ttc", "Gulim"), ("batang.ttc", "Batang")],
219
+ "zh": [("msyh.ttc", "Microsoft YaHei"), ("simhei.ttf", "SimHei"), ("simsun.ttc", "SimSun")],
220
+ "zh-hant": [("msjh.ttc", "Microsoft JhengHei"), ("mingliu.ttc", "MingLiU")],
221
+ "ja": [("meiryo.ttc", "Meiryo"), ("YuGothM.ttc", "Yu Gothic Medium"), ("YuGothR.ttc", "Yu Gothic"), ("msgothic.ttc", "MS Gothic")],
222
+ "ar": [("tahoma.ttf", "Tahoma"), ("arial.ttf", "Arial")],
223
+ "he": [("tahoma.ttf", "Tahoma"), ("arial.ttf", "Arial")],
224
+ # Windows 11 ships Nirmala UI as the collection Nirmala.ttc; there is no Nirmala.ttf (#339).
225
+ # The .ttf names stay first so a machine that still has them (older Windows, a copied font)
226
+ # keeps that file. Mangal, when present, stays the Devanagari face it always was.
227
+ "hi": [("mangal.ttf", "Mangal"), ("Nirmala.ttf", "Nirmala UI"), ("Nirmala.ttc", "Nirmala UI"), ("NirmalaB.ttf", "Nirmala UI")],
228
+ "th": [("leelawui.ttf", "Leelawadee UI"), ("leelawad.ttf", "Leelawadee"), ("tahoma.ttf", "Tahoma")],
229
+ "bn": [("Nirmala.ttf", "Nirmala UI"), ("Nirmala.ttc", "Nirmala UI"), ("vrinda.ttf", "Vrinda")],
230
+ "ta": [("Nirmala.ttf", "Nirmala UI"), ("Nirmala.ttc", "Nirmala UI"), ("latha.ttf", "Latha")],
231
+ "lo": [("leelawui.ttf", "Leelawadee UI"), ("DokChamp.ttf", "DokChampa")],
232
+ # Nirmala UI carries every Indic script Windows supports, Sinhala included
233
+ **{k: [("Nirmala.ttf", "Nirmala UI"), ("Nirmala.ttc", "Nirmala UI")] for k in ("pa", "gu", "te", "kn", "ml", "si")},
234
+ "km": [("leelawui.ttf", "Leelawadee UI"), ("KhmerUI.ttf", "Khmer UI")],
235
+ "my": [("mmrtext.ttf", "Myanmar Text")],
236
+ "ru": [("arial.ttf", "Arial"), ("segoeui.ttf", "Segoe UI")],
237
+ "el": [("arial.ttf", "Arial"), ("segoeui.ttf", "Segoe UI")],
238
+ "vi": [("arial.ttf", "Arial"), ("segoeui.ttf", "Segoe UI"), ("DejaVuSans.ttf", "DejaVu Sans")],
239
+ }
240
+
241
+
242
+ # Latin families Windows installs that WINDOWS_FONTS (a per-script table) does not name, by the
243
+ # file each one is installed as: a file name that does not start with the family's name
244
+ WINDOWS_LATIN_FONTS = [("arial.ttf", "Arial"), ("times.ttf", "Times New Roman"), ("cour.ttf", "Courier New"),
245
+ ("segoeui.ttf", "Segoe UI"), ("tahoma.ttf", "Tahoma"), ("verdana.ttf", "Verdana"),
246
+ ("georgia.ttf", "Georgia"), ("calibri.ttf", "Calibri"), ("cambria.ttc", "Cambria"),
247
+ ("consola.ttf", "Consolas"), ("trebuc.ttf", "Trebuchet MS"), ("comic.ttf", "Comic Sans MS"),
248
+ ("impact.ttf", "Impact"), ("seguiemj.ttf", "Segoe UI Emoji")]
249
+
250
+
251
+ def windows_family_files(wanted_key: str) -> "List[str]":
252
+ """The Windows Fonts file names of the family whose _family_key() is `wanted_key`, best first,
253
+ from WINDOWS_FONTS and WINDOWS_LATIN_FONTS ([] for a family neither names)."""
254
+ out: "List[str]" = []
255
+ for name, family in [e for entries in WINDOWS_FONTS.values() for e in entries] + WINDOWS_LATIN_FONTS:
256
+ if wanted_key and _family_key(family) == wanted_key and name not in out:
257
+ out.append(name)
258
+ return out
259
+
260
+
261
+ _SCRIPT_RANGES = (
262
+ ("ko", ((0x1100, 0x11FF), (0x3130, 0x318F), (0xA960, 0xA97F), (0xAC00, 0xD7FF))), # Hangul syllables + Jamo
263
+ ("kana", ((0x3040, 0x309F), (0x30A0, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F))), # hiragana/katakana
264
+ ("han", ((0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF), (0x20000, 0x2A6DF))),
265
+ ("ar", ((0x0600, 0x06FF), (0x0750, 0x077F), (0x08A0, 0x08FF), (0xFB50, 0xFDFF), (0xFE70, 0xFEFF))),
266
+ ("he", ((0x0590, 0x05FF), (0xFB1D, 0xFB4F))),
267
+ ("hi", ((0x0900, 0x097F), (0xA8E0, 0xA8FF))),
268
+ ("bn", ((0x0980, 0x09FF),)),
269
+ ("pa", ((0x0A00, 0x0A7F),)),
270
+ ("gu", ((0x0A80, 0x0AFF),)),
271
+ ("ta", ((0x0B80, 0x0BFF),)),
272
+ ("te", ((0x0C00, 0x0C7F),)),
273
+ ("kn", ((0x0C80, 0x0CFF),)),
274
+ ("ml", ((0x0D00, 0x0D7F),)),
275
+ ("si", ((0x0D80, 0x0DFF), (0x111E0, 0x111FF))),
276
+ ("th", ((0x0E00, 0x0E7F),)),
277
+ ("lo", ((0x0E80, 0x0EFF),)),
278
+ ("km", ((0x1780, 0x17FF), (0x19E0, 0x19FF))),
279
+ ("my", ((0x1000, 0x109F), (0xA9E0, 0xA9FF), (0xAA60, 0xAA7F))),
280
+ ("ru", ((0x0400, 0x04FF), (0x0500, 0x052F), (0x2DE0, 0x2DFF))),
281
+ ("el", ((0x0370, 0x03FF), (0x1F00, 0x1FFF))),
282
+ )
283
+
284
+
285
+ # The first bytes of the font files FreeType opens (drawtext and libass both load through it):
286
+ # TrueType, OpenType/CFF, Apple 'true'/'typ1', a collection, WOFF/WOFF2, PostScript Type 1 (PFA
287
+ # text, PFB segment marker), BDF and PCF bitmap fonts.
288
+ _FONT_MAGIC = (b"\x00\x01\x00\x00", b"OTTO", b"true", b"typ1", b"ttcf", b"wOFF", b"wOF2",
289
+ b"%!PS-AdobeFont", b"%!FontType1", b"\x80\x01", b"STARTFONT", b"\x01fcp")
290
+
291
+
292
+ def require_font_file(path: str, label: str = "--font-file") -> str:
293
+ """Refuse a font file that is not there or is not a font, before anything is drawn with it
294
+ (#510). drawtext that cannot load its `fontfile=` asks fontconfig for a default face instead
295
+ and exits 0, and libass given the file's directory finds no face in it and does the same, so a
296
+ text file named `brand.ttf` drew DejaVu Sans with `font_used.substituted: false`. Read by the
297
+ first bytes, not the extension; a gzipped PCF (`.pcf.gz`) and a Mac `.dfont` (no signature)
298
+ pass by name."""
299
+ shown_path = str(path)
300
+ if not os.path.isfile(shown_path):
301
+ die(f"{label} {shown_path}: no such file", kind="input")
302
+ try:
303
+ with open(shown_path, "rb") as fh:
304
+ head = fh.read(16)
305
+ except OSError as exc:
306
+ die(f"{label} {shown_path} cannot be read: {exc.strerror or exc}", kind="input")
307
+ lower = shown_path.lower()
308
+ if head.startswith(_FONT_MAGIC) or lower.endswith(".dfont") or (lower.endswith(".pcf.gz") and head.startswith(b"\x1f\x8b")):
309
+ return shown_path
310
+ die(f"{label} {shown_path} is not a font file (it starts with {head[:8]!r}, which no TrueType, OpenType, "
311
+ "WOFF, Type 1, BDF or PCF font does): drawing with it would fall back to another face without a word",
312
+ kind="input", hint="name a .ttf, .otf or .ttc file (fc-list lists the installed ones), or --font FAMILY")
313
+ return shown_path
314
+
315
+
316
+ def font_family_of_file(path: str) -> "Optional[str]":
317
+ """The family name of a font FILE -- what libass wants, given a --font-file. `fc-scan` reads
318
+ the file directly; without fontconfig the file stem is the honest best guess."""
319
+ if not path or not os.path.isfile(path):
320
+ return None
321
+ exe = _safe_which("fc-scan")
322
+ if exe:
323
+ try:
324
+ proc = subprocess.run([exe, "--format", "%{family[0]}", path], stdout=subprocess.PIPE,
325
+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)
326
+ if proc.returncode == 0 and proc.stdout.strip():
327
+ return proc.stdout.strip().splitlines()[0].strip()
328
+ except (subprocess.TimeoutExpired, OSError):
329
+ pass
330
+ return Path(path).stem
331
+
332
+
333
+ def char_script(ch: str) -> str:
334
+ """The script of one character: one of SCRIPTS, or "latin" for anything else (including
335
+ digits, punctuation and spaces -- they are measured and wrapped like Latin)."""
336
+ cp = ord(ch)
337
+ # 1.15: an emoji cluster is not Latin. detect_script() skips "emoji" the way it skips "latin",
338
+ # so font resolution still follows the letters around it.
339
+ if _is_emoji_char(ch):
340
+ return "emoji"
341
+ for name, ranges in _SCRIPT_RANGES:
342
+ for lo, hi in ranges:
343
+ if lo <= cp <= hi:
344
+ return "ja" if name == "kana" else ("zh" if name == "han" else name)
345
+ return "latin"
346
+
347
+
348
+ def detect_script(text: str, lang: "Optional[str]" = None) -> str:
349
+ """Which script `text` is written in, as one of SCRIPTS.
350
+
351
+ Hangul wins for Korean, any kana makes the whole string Japanese (Japanese mixes kana and
352
+ Han), Han alone is Chinese. Mixed text is decided by character count: the non-Latin script
353
+ with the most characters wins, ties going to whichever appeared first, and text with no
354
+ non-Latin characters at all is "latin". `lang` (a --lang/--language hint, or brand.json's
355
+ `lang`) only resolves the one ambiguity the characters genuinely cannot: Han with no kana
356
+ is Chinese by default but Japanese (or Korean hanja) when the caller says so.
357
+ """
358
+ counts: "Dict[str, int]" = {}
359
+ order: "List[str]" = []
360
+ kana = 0
361
+ for ch in text or "":
362
+ s = char_script(ch)
363
+ if s in ("latin", "emoji"):
364
+ continue
365
+ if ord(ch) in range(0x3040, 0x3100) or ord(ch) in range(0x31F0, 0x3200) or ord(ch) in range(0xFF66, 0xFFA0):
366
+ kana += 1
367
+ if s not in counts:
368
+ order.append(s)
369
+ counts[s] = counts.get(s, 0) + 1
370
+ if kana: # Japanese: the Han characters in the same string are Japanese too
371
+ counts["ja"] = counts.pop("ja", 0) + counts.pop("zh", 0)
372
+ order = [s for s in order if s != "zh"]
373
+ if not counts:
374
+ return "latin"
375
+ best = max(counts, key=lambda s: (counts[s], -order.index(s)))
376
+ hint = (lang or "").strip().lower().replace("_", "-").split("-")[0]
377
+ if not kana and best == "zh" and hint in ("ja", "zh", "ko"):
378
+ return hint # Han-only text: only the caller knows whether it is Chinese, Japanese or hanja
379
+ return best
380
+
381
+
382
+ # 2.19: Han-only text is Chinese, and Chinese is written in two standard forms whose glyphs differ
383
+ # (骨, 直, 角 are drawn differently in Taipei and Beijing). A Simplified face draws a Taiwanese
384
+ # caption in the wrong form, so a --lang naming Traditional Chinese resolves a Traditional face.
385
+ # The script stays "zh" for wrapping; only the font lookup changes.
386
+ HANT_TAGS = ("zh-tw", "zh-hk", "zh-mo", "zh-hant", "yue")
387
+
388
+
389
+ def font_key(script: str, lang: "Optional[str]" = None) -> str:
390
+ """The font-table key for `script` under the caller's `lang`: "zh-hant" for Chinese text the
391
+ caller says is Traditional (zh-TW, zh-HK, zh-MO, zh-Hant-*, yue), else `script` itself."""
392
+ tag = (lang or "").strip().lower().replace("_", "-")
393
+ if script == "zh" and any(tag == t or tag.startswith(t + "-") for t in HANT_TAGS):
394
+ return "zh-hant"
395
+ return script
396
+
397
+
398
+ _SCRIPT_FONT_CACHE: "Dict[Tuple[str, Optional[str]], Optional[Tuple[str, str]]]" = {}
399
+
400
+
401
+ def _fc_list_fonts(fc_lang: str) -> "Optional[List[Tuple[str, List[str]]]]":
402
+ """(file, families) for every font fontconfig says covers `fc_lang`.
403
+
404
+ `[]` means fontconfig answered and nothing covers the language; `None` means it could not be
405
+ asked at all (no `fc-list` on PATH, or it failed/timed out) -- the difference between
406
+ "missing" and "unknown", which the caller must not collapse: unknown is not a refusal.
407
+ """
408
+ exe = _safe_which("fc-list")
409
+ if not exe:
410
+ return None
411
+ try:
412
+ proc = subprocess.run([exe, f":lang={fc_lang}", "file", "family"],
413
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)
414
+ except (subprocess.TimeoutExpired, OSError):
415
+ return None
416
+ if proc.returncode != 0:
417
+ return None
418
+ out = []
419
+ for line in proc.stdout.splitlines():
420
+ if ": " not in line:
421
+ continue
422
+ path, _, families = line.partition(": ")
423
+ path = path.strip()
424
+ if not path or not os.path.exists(path):
425
+ continue
426
+ names = [f.replace("\\-", "-").strip() for f in families.split(",") if f.strip()]
427
+ out.append((path, names or [Path(path).stem]))
428
+ return out
429
+
430
+
431
+ def _family_rank(families: "Sequence[str]", preferred: "Sequence[str]") -> int:
432
+ for i, want in enumerate(preferred):
433
+ w = want.lower()
434
+ if any(f.lower().startswith(w) for f in families):
435
+ return i
436
+ return len(preferred)
437
+
438
+
439
+ def _script_font_entry(script: str, family_hint: "Optional[str]" = None) -> "Optional[Tuple[str, str]]":
440
+ key = (script, family_hint)
441
+ if key in _SCRIPT_FONT_CACHE:
442
+ return _SCRIPT_FONT_CACHE[key]
443
+ _SCRIPT_FONT_CACHE[key] = result = _script_font_uncached(script, family_hint)
444
+ return result
445
+
446
+
447
+ FC_UNKNOWN = "unknown" # sentinel: fontconfig could not be asked (absent or failing), not "no font"
448
+
449
+
450
+ def _script_font_uncached(script: str, family_hint: "Optional[str]" = None):
451
+ """(file, family), None when nothing covers `script`, or FC_UNKNOWN when it cannot be asked."""
452
+ if script not in FC_LANG:
453
+ return None
454
+ if platform.system() == "Windows":
455
+ fonts = Path(os.environ.get("WINDIR", "C:\\Windows")) / "Fonts"
456
+ entries = WINDOWS_FONTS.get(script, [])
457
+ if script == "vi" and family_hint:
458
+ entries = sorted(entries, key=lambda entry: entry[1].casefold() != family_hint.casefold())
459
+ for name, family in entries:
460
+ if (fonts / name).exists():
461
+ return str(fonts / name), family
462
+ if script == "vi":
463
+ return FC_UNKNOWN # no known system face; custom Windows fonts have not been measured
464
+ return None
465
+ preferred = list(PREFERRED_FAMILIES.get(script, []))
466
+ if family_hint:
467
+ preferred.insert(0, family_hint)
468
+ candidates = _fc_list_fonts(FC_LANG[script])
469
+ if candidates is None:
470
+ return FC_UNKNOWN
471
+ if not candidates:
472
+ return None
473
+ scored = []
474
+ for path, families in candidates:
475
+ joined = " ".join(families).lower()
476
+ if script == "vi" and "unifont" in joined:
477
+ continue
478
+ stem = Path(path).stem.lower()
479
+ # "Unifont Sample" is fontconfig's tofu-with-hex-digits fallback: it "covers" every script
480
+ # by drawing the code point, which is exactly the unreadable result this feature exists to
481
+ # avoid -- it is only ever chosen when nothing else covers the script at all. A *Mono* face
482
+ # is legible but wrong for a caption band, so it sorts after every proportional one.
483
+ last_resort = 1 if "unifont" in joined else 0
484
+ mono = 1 if "mono" in joined else 0
485
+ # regular weights before Bold/Italic/Oblique cuts, so a default caption is not bold by accident
486
+ styled = 1 if any(k in stem for k in ("bold", "italic", "oblique", "light", "thin", "black")) else 0
487
+ rank = _family_rank(families, preferred)
488
+ # a .ttc lists every face it holds (Noto CJK: JP, KR, SC, TC): name the one that ranked
489
+ family = next((f for f in families if rank < len(preferred) and f.lower().startswith(preferred[rank].lower())),
490
+ families[0])
491
+ scored.append((last_resort, rank, mono, styled, path, family))
492
+ scored.sort(key=lambda row: (row[0], row[1], row[2], row[3], row[4]))
493
+ if not scored:
494
+ return None
495
+ best = scored[0]
496
+ return best[4], best[5]
497
+
498
+
499
+ def font_for_script(script: str, family_hint: "Optional[str]" = None) -> "Optional[str]":
500
+ """A font FILE path that covers `script`, or None when this machine has none.
501
+
502
+ Linux/macOS ask fontconfig (`fc-list :lang=xx file family`) and rank what it reports by the
503
+ PREFERRED_FAMILIES table; Windows has no fontconfig, so the known system files are probed by
504
+ name. Cached per process: a caption job resolves the same script for every cue.
505
+ """
506
+ entry = _script_font_entry(script, family_hint)
507
+ return entry[0] if entry and entry is not FC_UNKNOWN else None
508
+
509
+
510
+ def font_family_for_script(script: str, family_hint: "Optional[str]" = None) -> "Optional[str]":
511
+ """The family NAME of font_for_script()'s file -- what libass wants in an ASS Fontname."""
512
+ entry = _script_font_entry(script, family_hint)
513
+ return entry[1] if entry and entry is not FC_UNKNOWN else None
514
+
515
+
516
+ def script_font_status(script: str) -> str:
517
+ """"available" (a font file covers `script`), "missing" (fontconfig answered, none does) or
518
+ "unknown" (there is no working fontconfig to ask). Only "missing" is a refusal."""
519
+ entry = _script_font_entry(script)
520
+ if entry is FC_UNKNOWN:
521
+ return "unknown"
522
+ return "available" if entry else "missing"
523
+
524
+
525
+ def _fontconfig_family_coverage(font_name: str, script: str) -> Optional[bool]:
526
+ """Whether the installed family `font_name` actually carries glyphs for `script`.
527
+
528
+ `fc-match` cannot answer this: given a family that IS installed it returns that family
529
+ whatever `:lang=` asks for (verified -- `fc-match "DejaVu Sans:lang=zh-cn"` answers
530
+ "DejaVu Sans", which has no Han glyphs at all). `fc-list :lang=xx:family=<name>` does: it
531
+ lists only files that satisfy BOTH, so an empty listing is the proof of no coverage.
532
+ None means there was no usable result.
533
+ """
534
+ if script not in FC_LANG or not font_name:
535
+ return None
536
+ exe = _safe_which("fc-list")
537
+ if not exe:
538
+ return None
539
+ try:
540
+ proc = subprocess.run([exe, f":lang={FC_LANG[script]}:family={font_name}", "file"],
541
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)
542
+ except (subprocess.TimeoutExpired, OSError):
543
+ return None
544
+ if proc.returncode != 0:
545
+ return None
546
+ return bool(proc.stdout.strip())
547
+
548
+
549
+ def font_covers_script(font_name: str, script: str) -> bool:
550
+ """Legacy callers warn only on a confirmed lack of coverage."""
551
+ return _fontconfig_family_coverage(font_name, script) is not False
552
+
553
+
554
+ def _installed_face_coverage(family: str, script: str, bold: bool) -> Optional[bool]:
555
+ """Ask fontconfig for the requested style without steering it toward the language."""
556
+ if platform.system() == "Windows":
557
+ return None # libass resolves the name through the Windows font backend
558
+ exe = _safe_which("fc-match")
559
+ if not exe:
560
+ return None
561
+ pattern = family + (":bold" if bold else "")
562
+ try:
563
+ proc = subprocess.run([exe, "--format", "%{family}\t%{lang}\n", pattern],
564
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
565
+ encoding="utf-8", errors="replace", timeout=10)
566
+ except (subprocess.TimeoutExpired, OSError):
567
+ return None
568
+ if proc.returncode != 0:
569
+ return None
570
+ families, separator, languages = proc.stdout.rstrip("\r\n").partition("\t")
571
+ if not (separator and families):
572
+ return None
573
+ names = {name.strip().casefold() for name in families.split(",")}
574
+ if _family_key(family) not in _GENERIC_FAMILIES and family.strip().casefold() not in names:
575
+ return None # a fallback family does not establish coverage of the requested one
576
+ return FC_LANG[script].lower() in languages.lower().split("|")
577
+
578
+
579
+ # Named flags differ per tool: overlay.py and graphics.py take a font FILE, caption.py takes a
580
+ # directory of faces plus the family name -- naming a flag the tool does not have is worse than
581
+ # naming none, so the hint says both (review 10).
582
+ FONT_FLAG_HINT = "pass a font file (--font-file on overlay.py/graphics.py, --fonts-dir with --font on caption.py)"
583
+
584
+
585
+ FONT_INSTALL_HINT = ("install fonts-noto-cjk / fonts-noto-core (apt), "
586
+ "brew install --cask font-noto-sans-cjk / font-noto-sans-arabic (mac), or "
587
+ + FONT_FLAG_HINT)
588
+
589
+
590
+ def fonts_dir_covers_script(fonts_dir: str, script: str) -> "Optional[bool]":
591
+ """Does any font under `fonts_dir` cover `script`? None when it cannot be checked.
592
+
593
+ `--fonts-dir` says "also look here", not "this exact face", so it must not switch the
594
+ coverage guarantee off. fontconfig's `fc-scan` reads the files directly (no cache, no
595
+ installed-font database), which is exactly the question: `%{lang}` lists the languages each
596
+ face claims.
597
+ """
598
+ if script not in FC_LANG or not fonts_dir or not os.path.isdir(fonts_dir):
599
+ return None
600
+ return _scan_font_coverage(fonts_dir, script)
601
+
602
+
603
+ def _scan_font_coverage(path: str, script: str, *, face_index: Optional[int] = None) -> Optional[bool]:
604
+ """Check coverage in one file or a directory of font files with fc-scan."""
605
+ exe = _safe_which("fc-scan")
606
+ if not exe:
607
+ return None
608
+ targets = [path]
609
+ if os.path.isdir(path):
610
+ # libass loads the files directly in the folder it is given, not its subfolders or
611
+ # hidden files, while fc-scan walks them all (review of #636)
612
+ try:
613
+ names = os.listdir(path)
614
+ except OSError:
615
+ return None # a folder that cannot be listed: coverage unknown, never a stop
616
+ targets = sorted(os.path.join(path, n) for n in names
617
+ if not n.startswith(".") and os.path.isfile(os.path.join(path, n)))
618
+ if not targets:
619
+ return False
620
+ try:
621
+ proc = subprocess.run([exe, "--format", "%{index}\t%{lang}\n", *targets],
622
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)
623
+ except (subprocess.TimeoutExpired, OSError):
624
+ return None
625
+ if proc.returncode != 0:
626
+ return None
627
+ want = FC_LANG[script].lower()
628
+ matched_face = False
629
+ for line in proc.stdout.splitlines():
630
+ index, separator, languages = line.partition("\t")
631
+ if not separator or (face_index is not None and index != str(face_index)):
632
+ continue
633
+ matched_face = True
634
+ if want in [tag.strip().lower() for tag in languages.split("|")]:
635
+ return True
636
+ return None if face_index is not None and not matched_face else False
637
+
638
+
639
+ # FreeType's font formats whose PostScript name libass 0.17 matches (`check_postscript`); for any
640
+ # other outline (TrueType) it matches the full name instead (`matches_full_or_postscript_name`)
641
+ _POSTSCRIPT_FORMATS = ("CFF", "Type 1", "CID Type 1")
642
+ # files per fc-scan call, so a large folder does not exceed the command line's length
643
+ _FC_SCAN_CHUNK = 200
644
+
645
+
646
+ def _sfnt_names(path: str, index: int) -> "Optional[Tuple[List[str], List[str], Optional[int]]]":
647
+ """(families, full names, usWeightClass) of face `index` of an sfnt file (TrueType, OpenType,
648
+ a collection) as libass 0.17 reads them for a font it loads itself: the Microsoft-platform
649
+ records of name ID 1 (family) and ID 4 (full name) only -- not ID 16, the typographic family
650
+ fontconfig also lists, so `Inter` is not a family of Inter-Black.otf to libass. None when the
651
+ file is not an sfnt this can read (WOFF, Type 1, a damaged table)."""
652
+ try:
653
+ with open(path, "rb") as fh:
654
+ data = fh.read()
655
+ base = 0
656
+ if data[:4] == b"ttcf":
657
+ (base,) = struct.unpack(">I", data[12 + 4 * index:16 + 4 * index])
658
+ elif index:
659
+ return None
660
+ if data[base:base + 4] not in (b"\x00\x01\x00\x00", b"OTTO", b"true"):
661
+ return None
662
+ (num_tables,) = struct.unpack(">H", data[base + 4:base + 6])
663
+ tables = {}
664
+ for i in range(num_tables):
665
+ tag, _sum, off, length = struct.unpack(">4sIII", data[base + 12 + 16 * i:base + 28 + 16 * i])
666
+ tables[tag] = (off, length)
667
+ if b"name" not in tables:
668
+ return None
669
+ off, _length = tables[b"name"]
670
+ _fmt, count, str_off = struct.unpack(">HHH", data[off:off + 6])
671
+ families, fullnames = [], []
672
+ for i in range(count):
673
+ pid, _eid, _lid, nid, length, noff = struct.unpack(">6H", data[off + 6 + 12 * i:off + 18 + 12 * i])
674
+ if pid != 3 or nid not in (1, 4):
675
+ continue
676
+ raw = data[off + str_off + noff:off + str_off + noff + length]
677
+ name = raw.decode("utf-16-be", errors="replace").strip()
678
+ if name:
679
+ (families if nid == 1 else fullnames).append(name)
680
+ weight = None
681
+ if b"OS/2" in tables:
682
+ os2 = tables[b"OS/2"][0]
683
+ (weight,) = struct.unpack(">H", data[os2 + 4:os2 + 6])
684
+ weight = weight * 100 if 1 <= weight <= 9 else (weight or None)
685
+ return families, fullnames, weight
686
+ except (OSError, struct.error, IndexError, ValueError):
687
+ return None
688
+
689
+
690
+ def fonts_dir_face(fonts_dir: str, family: str, bold: bool = False) -> "Tuple[Optional[str], Optional[bool]]":
691
+ """(file, found) for `family` in `fonts_dir`, naming a file only where libass's pick is certain
692
+ (#531). found False: no face of the folder has that name, so libass asks fontconfig as without
693
+ the folder. found True with a file: the folder holds a face of the asked family in exactly the
694
+ asked style (weight 400, or 700 with `bold`, which is what libass asks for an ASS Bold of -1;
695
+ upright), or a face whose full or PostScript name is the one asked: libass scores such a face
696
+ 0, the best there is, in every version, and an installed face that ties is of the same family
697
+ and style. found True with file None: the folder holds the family only in other styles, and
698
+ libass chooses among them and the installed faces by its own scoring, which this does not
699
+ repeat (it differs between libass versions). found None (file None): the folder could not be
700
+ read (no fc-scan, a failed scan).
701
+
702
+ libass loads the folder's own files, not its subfolders and not names starting with a dot, so
703
+ only those are scanned (`fc-scan`, given the files, opens them with FreeType as libass does; it
704
+ recurses into a folder it is given). Names are matched case-insensitively as libass 0.17
705
+ matches them: the family is name ID 1 of the Microsoft platform, read from the file (FreeType's
706
+ family name, here fontconfig's first, when the file has no such record); the full name counts
707
+ for a TrueType outline and the PostScript name for a PostScript one (CFF, Type 1), not the other
708
+ way round. Checked by drawing on libass 0.17.1."""
709
+ face, found = _fonts_dir_face(fonts_dir, family, bold)
710
+ return (face[0] if face else None), found
711
+
712
+
713
+ def _fonts_dir_face(fonts_dir: str, family: str, bold: bool) -> "Tuple[Optional[Tuple[str, int]], Optional[bool]]":
714
+ """The selected file and face index. A collection can hold faces with different coverage."""
715
+ exe = _safe_which("fc-scan")
716
+ if not exe or not fonts_dir or not os.path.isdir(fonts_dir):
717
+ return None, None
718
+ try:
719
+ files = sorted(os.path.join(fonts_dir, name) for name in os.listdir(fonts_dir)
720
+ if not name.startswith(".") and os.path.isfile(os.path.join(fonts_dir, name)))
721
+ except OSError:
722
+ return None, None
723
+ fmt = "%{file}\t%{index}\t%{family}\t%{postscriptname}\t%{fontformat}\t%{weight}\t%{slant}\t%{fullname}\t%{outline}\n"
724
+ lines = []
725
+ for at in range(0, len(files), _FC_SCAN_CHUNK):
726
+ try:
727
+ proc = subprocess.run([exe, "--format", fmt, *files[at:at + _FC_SCAN_CHUNK]],
728
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8",
729
+ errors="replace", timeout=10)
730
+ except (subprocess.TimeoutExpired, OSError):
731
+ return None, None
732
+ # fc-scan exits 1 with nothing printed when no file it was given is a face it can open
733
+ # (a text file named .ttf): libass, which opens them with the same FreeType, finds none
734
+ if proc.returncode != 0 and proc.stdout.strip():
735
+ return None, None
736
+ lines.extend(proc.stdout.splitlines())
737
+ wanted = (family or "").strip().lower()
738
+ want_weight = 700 if bold else 400
739
+ exact, named, other_styles = [], [], False
740
+ for line in lines:
741
+ cells = line.split("\t")
742
+ if len(cells) < 9 or cells[8].strip().lower() not in ("true", "false"):
743
+ return None, None
744
+ if not cells[0] or cells[8].strip().lower() != "true":
745
+ continue
746
+ path, index, fc_family, psname, fontformat, fc_weight, slant, fc_full = cells[:8]
747
+ try:
748
+ index = int(index or 0)
749
+ except ValueError:
750
+ continue
751
+ if index >> 16:
752
+ continue # a named instance of a variable font: libass loads the face itself only
753
+ read = _sfnt_names(path, index)
754
+ families, fullnames, weight = read if read is not None else ([], None, None)
755
+ if not families:
756
+ # no Microsoft-platform family record (Macintosh records only, Type 1, WOFF): libass
757
+ # takes FreeType's family name, which is fontconfig's first
758
+ families = fc_family.split(",")[:1]
759
+ if fullnames is None:
760
+ fullnames = fc_full.split(",")
761
+ if weight is None:
762
+ try:
763
+ weight = {80: 400, 200: 700}.get(int(float(fc_weight or 80)))
764
+ except ValueError:
765
+ weight = None
766
+ if wanted and wanted in {n.strip().lower() for n in families}:
767
+ upright = (slant or "0").strip() in ("", "0")
768
+ if upright and weight == want_weight:
769
+ exact.append((path, index))
770
+ else:
771
+ other_styles = True
772
+ continue
773
+ names = {psname.strip().lower()} if fontformat in _POSTSCRIPT_FORMATS else {n.strip().lower() for n in fullnames}
774
+ if wanted and wanted in names:
775
+ named.append((path, index))
776
+ if named or exact:
777
+ return (named or exact)[0], True
778
+ return None, (True if other_styles else False)
779
+
780
+
781
+ def _is_last_resort(entry: "Tuple[str, str]") -> bool:
782
+ """Unifont, fontconfig's code-point-box face: it covers every script and renders none."""
783
+ return "unifont" in " ".join(str(x) for x in entry).lower()
784
+
785
+
786
+ def script_font_for_text(text: str, *, lang: "Optional[str]" = None, font: "Optional[str]" = None,
787
+ font_explicit: bool = False, font_file: "Optional[str]" = None, font_bold: bool = False,
788
+ fonts_dir: "Optional[str]" = None
789
+ ) -> "Tuple[str, Optional[str], Optional[str]]":
790
+ """(script, font file, family) to draw `text` with, resolving by script when nothing explicit
791
+ was asked for.
792
+
793
+ Returns (script, None, None) when the caller's own choice stands: Latin text, an explicit
794
+ --font-file, an explicit --font (which is kept even when fontconfig says it does not cover
795
+ the script -- with one recorded warning saying so, `font_lacks_script`, because overriding a
796
+ user's stated font silently is worse than a warning), or a --fonts-dir that does carry the script. Otherwise the resolved
797
+ file is returned with ONE info line naming it.
798
+
799
+ A script fontconfig says nothing covers is a failed job (tofu is not a delivery). A machine
800
+ with no working fontconfig at all answers "unknown", not "missing": the job continues with
801
+ the caller's font -- libass and drawtext still have their own font backends -- and one recorded
802
+ warning (`font_coverage_unverified`) says the coverage could not be verified.
803
+ """
804
+ script = detect_script(text or "", lang)
805
+ key = font_key(script, lang)
806
+ if script == "latin":
807
+ tag = (lang or "").strip().lower().replace("_", "-").split("-", 1)[0]
808
+ normalized = unicodedata.normalize("NFC", text or "")
809
+ marked = re.search(r"[ƠơƯư\u1ea0-\u1ef9]", normalized)
810
+ # Breve-a and stroked d also occur separately in other languages. Their combination
811
+ # with each other or with Vietnamese tilde vowels is a stronger signal.
812
+ combined = re.search(r"[Đđ]", normalized) and re.search(r"[ĂăÃãĨĩŨũ]", normalized)
813
+ # an empty sample (a dry run before transcription) asks for no face; a language the
814
+ # caller names that is not Vietnamese (Igbo, Yoruba share these letters) keeps its own
815
+ # font: the letters cannot tell them apart, the tag can (review of #636)
816
+ tag = "vi" if tag == "vie" else tag # the three-letter form caption.py also accepts
817
+ if (tag == "vi" and normalized.strip()) or (tag in ("", "vi") and (marked or combined)):
818
+ key = "vi"
819
+ if key == "latin":
820
+ return script, None, None
821
+ if font_file:
822
+ return script, None, None
823
+ diagnostic_script = key if key == "vi" else script
824
+ if font_explicit and font:
825
+ if key == "vi":
826
+ local_face, local_found = _fonts_dir_face(fonts_dir, font, font_bold) if fonts_dir else (None, False)
827
+ if local_face:
828
+ path, index = local_face
829
+ coverage = _scan_font_coverage(path, key, face_index=index)
830
+ elif local_found is not False:
831
+ coverage = None # the selected folder face is ambiguous or the folder was unreadable
832
+ else:
833
+ coverage = _installed_face_coverage(font, key, font_bold)
834
+ else:
835
+ coverage = font_covers_script(font, key)
836
+ if coverage is None:
837
+ warn(f"font: could not verify Vietnamese coverage for '{font}'. Check the burned accents or "
838
+ f"{FONT_FLAG_HINT}.", "font_coverage_unverified", script=key)
839
+ elif coverage is False:
840
+ warn(f"font: '{font}' does not cover {LANGUAGE_NAMES[key]} text on this machine; keeping it as asked "
841
+ f"(drop --font, or {FONT_FLAG_HINT}, to pick one by script automatically)", "font_lacks_script",
842
+ font=font, script=diagnostic_script)
843
+ return script, None, None
844
+ if fonts_dir:
845
+ covered = fonts_dir_covers_script(fonts_dir, key)
846
+ if covered:
847
+ return script, None, None
848
+ if covered is None:
849
+ warn(f"font: could not verify that {fonts_dir} covers {LANGUAGE_NAMES[key]} text "
850
+ "(no fc-scan on this machine); using it as given", "font_coverage_unverified", fonts_dir=fonts_dir,
851
+ script=diagnostic_script)
852
+ return script, None, None
853
+ record_fallback(f"font: no face in {fonts_dir} covers {LANGUAGE_NAMES[key]} text; "
854
+ "picking one by script instead (the directory is still searched first)", "fonts_dir_lacks_script",
855
+ fonts_dir=fonts_dir, script=diagnostic_script)
856
+ entry = _script_font_entry(key)
857
+ if key == "zh-hant" and (not entry or (entry is not FC_UNKNOWN and _is_last_resort(entry))):
858
+ # no Traditional face (Unifont's code-point boxes are none): the Simplified one still
859
+ # has the characters, in the other form
860
+ simplified = _script_font_entry(script)
861
+ if simplified and simplified is not FC_UNKNOWN and (not entry or not _is_last_resort(simplified)):
862
+ entry = simplified
863
+ record_fallback(f"font: no {LANGUAGE_NAMES[key]} face is installed; drawing with {entry[0]}, a "
864
+ "Simplified Chinese face whose glyph forms differ in places "
865
+ "(install fonts-noto-cjk or a TC font)", "font_variant_missing", lang=lang, file=entry[0])
866
+ key = script
867
+ if entry is FC_UNKNOWN:
868
+ warn(f"font: could not verify that this machine can render {LANGUAGE_NAMES[key]} text "
869
+ "(no working fontconfig); rendering with the font as given -- "
870
+ "doctor --json .fonts.scripts reports what is known", "font_coverage_unverified", script=diagnostic_script)
871
+ return script, None, None
872
+ if not entry:
873
+ die(f"no installed font covers {LANGUAGE_NAMES[key]} text on this machine — {FONT_INSTALL_HINT}", kind="input")
874
+ info(f"font: {entry[0]} (covers {key})")
875
+ return script, entry[0], entry[1]