@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,2207 @@
1
+ #!/usr/bin/env python3
2
+ """Burn SRT/ASS subtitles into a video, or mux one in as a soft (toggleable)
3
+ subtitle stream, or generate an SRT from plain text.
4
+
5
+ Styling (font, size, colour, outline, position) applies to SRT input via
6
+ libass force_style. ASS files carry their own styles and are rendered as-is.
7
+ Styling and animation only apply to --mode burn (the default): they render
8
+ pixels, so they have no meaning for a soft subtitle stream.
9
+
10
+ --mode mux copies the video and audio streams untouched (see contract --json:
11
+ reencodes_video/reencodes_audio are "never" for this mode) and adds the SRT
12
+ as a separate subtitle stream a player can toggle -- the source is never
13
+ touched. It takes only a plain SRT (from --srt, --text or --transcribe), not
14
+ --ass: ASS styling has no equivalent soft-subtitle representation across
15
+ containers, so --mode mux --ass is refused with a pointer to --mode burn.
16
+ The subtitle codec is picked from the output container: mov_text for
17
+ .mp4/.m4v/.mov, srt for .mkv, webvtt for .webm.
18
+
19
+ Text-to-SRT input format (one cue per line, blank lines ignored):
20
+ 0:00-0:03 Hello and welcome
21
+ 00:00:03.500 --> 00:00:06 Second line | with a manual line break
22
+ 00:00:03:15 --> 00:00:06:00 SMPTE non-drop-frame timecode (hh:mm:ss:ff, needs --fps or an @fps suffix: 00:00:03:15@29.97)
23
+ Text without a time is auto-timed after the previous cue (--auto-seconds)
24
+
25
+ Examples:
26
+ python3 caption.py input.mp4 --srt subs.srt
27
+ python3 caption.py input.mp4 --text cues.txt --animate pop --karaoke # word-by-word highlight, TikTok style
28
+ python3 caption.py input.mp4 --text cues.txt --karaoke --karaoke-style word # active word scaled + emboldened, past/upcoming colours
29
+ python3 caption.py input.mp4 --srt subs.srt --font "Noto Sans CJK JP" --size 28 --position top
30
+ python3 caption.py --text cues.txt --write-srt cues.srt # only produce the SRT
31
+ python3 caption.py input.mp4 --text cues.txt # generate + burn in one go
32
+ python3 caption.py input.mp4 --text cues_ko.txt --lang ko # a font that covers the script is picked automatically
33
+ python3 caption.py input.mp4 --srt subs.srt --offset -0.4 --max-lines 2 --min-duration 1.2
34
+ """
35
+ import argparse
36
+ import json
37
+ import math
38
+ import os
39
+ import re
40
+ import sys
41
+ from pathlib import Path
42
+ from typing import Any, Dict, List, Optional, Tuple
43
+
44
+ from _platforms import (PLATFORMS, PLATFORM_CHOICES, ASS_SCRIPT_HEIGHT, ass_units,
45
+ resolve as resolve_platform)
46
+ from _ass_overlay import (EMOJI_SENTINEL, ass_base_encoding, emoji_placeholder, ass_escape_markup,
47
+ strip_srt_markup, reinsert_srt_markup, carry_srt_markup, srt_alignment)
48
+ from _common.emit import refuse # noqa: E402
49
+ from _common.emoji import emoji_missing_asset_note, emoji_mono_on_colour_note
50
+ from _common import require_filter, emoji_filter_chain, EMOJI_ASSET_HINT, emoji_asset_for, emoji_codepoint_name, emoji_support, resolve_emoji_assets, NO_SPACE_SCRIPTS, char_script, text_width_em, emoji_clusters, has_emoji, detect_script, BIDI_SCRIPTS, STATE, brand_states_font, script_font_for_text, signed_time_arg, brand_caption_style, color_hex, drawn_chain, layer_base_chain, load_brand, overlay_format, rgb_chain_to_bt709, video_args, add_common, apply_common, emit, aac_args, cfr_args, cfr_at_input, with_cfr, default_output, die, escape_filter_path, ffmpeg_base, fmt_smpte_time, info, MissingFpsError, parse_time, probe, run, X264_PRESETS, read_text_or_die, fmt_secs, refuse_existing_outputs, guard_sidecar
51
+ # The line breaker, lifted into _common/text.py in 1.16.0 so graphics.py can use the same rules.
52
+ # The ASR bridge and the SRT reader/writer live in _common.asr since 1.17 (silence.py --filler
53
+ # shares them). They stay caption.py's public names -- every caller and test that reached for
54
+ # caption.parse_srt / caption.transcribe / caption.whisper_word_timings before 1.17 still does.
55
+ from _common import asr as _asr
56
+ from _common.asr import ENGINE_CHOICES
57
+ from _common.decision import ntsc_rate
58
+ from _common.emit import note, warn
59
+ from _common.probe import display_size, square_pixels, square_pixels_note
60
+ from _common.runner import carried_stream_maps, refuse_output_is_input, same_file, subtitle_codec_for, subtitle_container_holds
61
+ from _common.fonts import font_choice, fonts_dir_face, record_font_choice, require_font_file
62
+ from _common import (ASR_INSTALL_HINT, die_no_engine, parse_srt, transcribe, whisper_word_timings,
63
+ write_srt)
64
+ from _common.asr import srt_blocks
65
+ from _common.runner import absent_word, normalize_text
66
+ from _common import (SAFE_WIDTH_FRACTION, ORPHAN_MIN_EM, WRAP_MODES, wrap_text, wrap_variants, best_break,
67
+ fit_size, line_em_for_size, MIN_CAPTION_FRACTION,
68
+ break_penalty, _is_weak_line, _atoms, _join, _break_spaced, _bare_word, _function_words,
69
+ _split_hyphens, _slice_atom, FUNCTION_WORDS, JA_PARTICLES, JA_SENTENCE_END, _fix_orphans, _rebalance)
70
+
71
+ # The breaker's names are caption.py's public surface as much as _common's: every caller and test
72
+ # that reached for `caption.wrap_text` before 1.16 still does.
73
+ __all__ = ["parse_srt", "write_srt", "transcribe", "whisper_word_timings", "die_no_engine",
74
+ "ASR_INSTALL_HINT",
75
+ "SAFE_WIDTH_FRACTION", "ORPHAN_MIN_EM", "WRAP_MODES", "wrap_text", "wrap_variants",
76
+ "fit_size", "line_em_for_size", "MIN_CAPTION_FRACTION",
77
+ "best_break", "break_penalty", "_is_weak_line", "_atoms", "_join", "_break_spaced",
78
+ "_bare_word", "_function_words", "_split_hyphens", "_slice_atom", "FUNCTION_WORDS", "JA_PARTICLES",
79
+ "JA_SENTENCE_END", "_fix_orphans", "_rebalance", "char_script", "NO_SPACE_SCRIPTS",
80
+ "text_width_em"]
81
+
82
+ ALIGN = {"bottom": 2, "top": 8, "center": 5, "bottom-left": 1, "bottom-right": 3, "top-left": 7, "top-right": 9}
83
+ # libass reads a force_style Alignment in the legacy SSA numbering (1-3 bottom, 5-7 top, 9-11
84
+ # middle), not the v4+ numpad one a Style line uses: only the bottom row is the same number in
85
+ # both. Through 3.2.3 the SRT burn passed the numpad value, so --position top landed mid-left,
86
+ # center top-left, top-left top-right (#436, measured on libass 0.17.1 and FFmpeg 9.0.2).
87
+ FORCE_STYLE_ALIGN = {"bottom": 2, "top": 6, "center": 10, "bottom-left": 1, "bottom-right": 3, "top-left": 5, "top-right": 7}
88
+
89
+ TIME_RE = re.compile(
90
+ r"^\s*(?P<a>[\d:;.,@]+)\s*(?P<sep>-->|-|–|to)\s*(?P<b>[\d:;.,@]+)\s+(?P<text>.+)$"
91
+ )
92
+ DROP_FRAME_CLOCK = r"\d+:\d+:\d+;"
93
+
94
+
95
+ def cue_times_match(line: str) -> "Optional[re.Match[str]]":
96
+ """TIME_RE's match of a --text line, or None when the line is caption text. The documented
97
+ separators are "-" and "-->", and with them bare seconds are times ("0-1.5 Hello"). "to" is
98
+ also an English word: "3 to 5 apples" is text, so with "to" both sides must be clock times
99
+ (a ':' in each, "0:03 to 0:05 Hello")."""
100
+ m = TIME_RE.match(line)
101
+ if m and m.group("sep") == "to" and not (":" in m.group("a") and ":" in m.group("b")):
102
+ return None
103
+ if m and any(";" in token and not re.match(DROP_FRAME_CLOCK, token) for token in (m.group("a"), m.group("b"))):
104
+ return None
105
+ return m
106
+
107
+
108
+ # an SRT timing line: the times alone, the cue text on the lines after it
109
+ DROP_FRAME_RE = re.compile(r"^\s*(?:\d[\d:.,]*(?:@[^\s-]+)?\s*(?:-->|-|–|to)\s*)?" + DROP_FRAME_CLOCK)
110
+ DROP_FRAME_LABEL = re.compile(r"(\d+):(\d{2}):(\d{2});(\d{2})")
111
+ SRT_TIMING_RE = re.compile(r"^\s*\d+:\d{2}:\d{2}[,.]\d+\s*-->\s*\d+:\d{2}:\d{2}[,.]\d+\s*$")
112
+ # the same line as WebVTT may write it, without the hours: `00:01.000 --> 00:02.000`
113
+ TIMING_ONLY_RE = re.compile(r"^\s*(?:\d+:)?\d{1,2}:\d{2}[,.]\d+\s*-->\s*(?:\d+:)?\d{1,2}:\d{2}[,.]\d+\s*$")
114
+ ASS_SECTIONS = ("[script info]", "[v4+ styles]", "[v4 styles]", "[events]")
115
+
116
+
117
+ def refuse_not_a_cue_file(path: str, lines: List[str]) -> None:
118
+ """--text given a file in another format (#404): read as a cue file, a WebVTT header, an ASS
119
+ section or a JSON document was burned in line by line, auto-timed 3 s apart. Named by what the
120
+ file starts with; the SRT timing-line check below catches a file with no such header."""
121
+ head = next((ln.strip() for ln in lines if ln.strip()), "")
122
+ cue_shape = "A cue file has one cue per line: `START-END text` (or text alone, timed --auto-seconds apart)"
123
+ if head.upper().startswith("WEBVTT"):
124
+ die(f"--text: {path} is a WebVTT subtitle file (it starts with {head[:20]!r}); pass it as --srt, which reads "
125
+ f"WebVTT (render.py: --srt, not --cues). {cue_shape}", kind="input")
126
+ if head.lower() in ASS_SECTIONS or head.startswith("Dialogue:"):
127
+ die(f"--text: {path} is an ASS/SSA subtitle file (it starts with {head[:20]!r}); pass it as --ass, which burns "
128
+ f"it with the styles inside it (in a render.py project, the captions stage's \"ass\" key). {cue_shape}",
129
+ kind="input")
130
+ if head[:1] in "{[":
131
+ try:
132
+ doc = json.loads("\n".join(lines))
133
+ except ValueError:
134
+ doc = None
135
+ if isinstance(doc, dict) or (isinstance(doc, list) and doc and isinstance(doc[0], (dict, list))):
136
+ die(f"--text: {path} is a JSON document, not a cue file. {cue_shape}. A whisper JSON is a transcript: "
137
+ "caption.py --transcribe writes the cues from the audio", kind="input")
138
+
139
+
140
+ def _cue_time(token: str, fps: Optional[float]) -> float:
141
+ if ";" not in token:
142
+ return parse_time(token, fps)
143
+ label, suffix, rate = token.replace(",", ".").partition("@")
144
+ match = DROP_FRAME_LABEL.fullmatch(label)
145
+ if not match:
146
+ raise ValueError(f"bad drop-frame timecode '{token}' (use hh:mm:ss;ff)")
147
+ if suffix:
148
+ fps = float(rate)
149
+ if not fps or not math.isfinite(fps) or fps <= 0:
150
+ raise MissingFpsError(f"drop-frame timecode '{token}' needs 29.97 or 59.94 fps")
151
+ exact = ntsc_rate(fps)
152
+ if exact not in (30000 / 1001, 60000 / 1001):
153
+ raise ValueError(f"drop-frame timecode '{token}' needs 29.97 or 59.94 fps, got {fps:g}")
154
+ h, m, s, frame = map(int, match.groups())
155
+ nominal = round(exact)
156
+ dropped = nominal // 15
157
+ if m > 59 or s > 59 or frame >= nominal or (s == 0 and m % 10 and frame < dropped):
158
+ raise ValueError(f"drop-frame timecode '{token}' is not a valid label at {fps:g} fps")
159
+ minutes = h * 60 + m
160
+ return ((minutes * 60 + s) * nominal + frame - dropped * (minutes - minutes // 10)) / exact
161
+
162
+
163
+ def parse_text_cues(path: str, auto_seconds: float, gap: float, fps: Optional[float] = None, *,
164
+ source_fps: Optional[float] = None, source_vfr: bool = False) -> List[Tuple[float, float, str]]:
165
+ cues: List[Tuple[float, float, str]] = []
166
+ mismatch = None
167
+ cursor = 0.0
168
+ # split at "\n" only: splitlines() also breaks a cue at U+2028, U+0085, \v and \f, which
169
+ # made the rest of the line an auto-timed cue of its own
170
+ lines = read_text_or_die(path, "--text").split("\n")
171
+ refuse_not_a_cue_file(path, lines)
172
+ for n, raw in enumerate(lines, 1):
173
+ if TIMING_ONLY_RE.match(raw) and not SRT_TIMING_RE.match(raw):
174
+ # WebVTT's short form (no hours), in a file without the WEBVTT header
175
+ die(f"--text: {path} is a subtitle file, not a cue file (line {n} is a timing line with no text: "
176
+ f"'{raw.strip()}'); pass it as --srt (render.py: --srt, not --cues)", kind="input")
177
+ if SRT_TIMING_RE.match(raw):
178
+ # a cue file puts the text on the line with its times; this line has the times alone, so
179
+ # the file is an SRT. Read as a cue file, its numbers and timing lines would be burned in
180
+ # as captions, auto-timed 3 s apart (#396)
181
+ die(f"--text: {path} is an SRT file (line {n} is a timing line with no text: "
182
+ f"'{raw.strip()}'); pass it as --srt (render.py: --srt, not --cues)", kind="input")
183
+ if DROP_FRAME_RE.match(raw) and not cue_times_match(raw):
184
+ die(f"--text: line {n} has malformed drop-frame timing; give two times and caption text", kind="input")
185
+ for line in lines:
186
+ if not line.strip():
187
+ continue
188
+ m = cue_times_match(line)
189
+ if m:
190
+ try:
191
+ start, end = _cue_time(m.group("a"), fps), _cue_time(m.group("b"), fps)
192
+ except MissingFpsError as e:
193
+ die(f"cue '{line}': {e} -- pass --fps, or --input's own fps is used automatically when given")
194
+ except ValueError as exc:
195
+ if ";" in m.group("a") or ";" in m.group("b"):
196
+ die(str(exc))
197
+ # TIME_RE matched (so m.group("text") is the real cue text, not the broken
198
+ # timestamp), but one of the two timestamps itself failed to parse (e.g. a
199
+ # malformed "00:00:03.15.999") -- falling back to `line.strip()` here used to
200
+ # burn the whole raw line, broken timestamp included, into the caption instead
201
+ # of just the text after it.
202
+ start, end, text = cursor, cursor + auto_seconds, m.group("text").strip()
203
+ else:
204
+ text = m.group("text").strip()
205
+ for token, chosen in ((m.group("a"), start), (m.group("b"), end)):
206
+ label, suffix, rate = token.replace(",", ".").partition("@")
207
+ if not source_fps or not (";" in label or label.count(":") == 3):
208
+ continue
209
+ cue_fps = float(rate) if suffix else fps
210
+ if not cue_fps or abs(ntsc_rate(cue_fps) - ntsc_rate(source_fps)) <= 0.005:
211
+ continue
212
+ if mismatch is None or chosen > mismatch[0]:
213
+ try:
214
+ drift = None if source_vfr else chosen - _cue_time(label, source_fps)
215
+ except ValueError:
216
+ drift = None
217
+ mismatch = (chosen, cue_fps, drift, label)
218
+ else:
219
+ start, end, text = cursor, cursor + auto_seconds, line.strip()
220
+ if end <= start:
221
+ die(f"cue '{line}': end must be after start")
222
+ text = text.replace(" | ", "\n").replace("|", "\n")
223
+ cues.append((start, end, text))
224
+ cursor = end + gap
225
+ if not cues:
226
+ die(f"no cues found in {path}")
227
+ if mismatch:
228
+ _, cue_fps, drift, label = mismatch
229
+ impact = (f"{drift:+.3f}s at {label} compared with the source-rate reading" if drift is not None
230
+ else f"no source-rate offset can be calculated for {label}")
231
+ warn(f"caption timecode uses {cue_fps:g} fps; input probes at {source_fps:g} fps ({impact})",
232
+ "caption_timecode_rate_mismatch", cue_fps=cue_fps, source_fps=source_fps,
233
+ cue_timecode=label, drift_seconds=round(drift, 6) if drift is not None else None)
234
+ return cues
235
+
236
+
237
+ def word_durations_from_audio(video: str, start: float, end: float, n_words: int, audio_stream: int = 0) -> List[int]:
238
+ """Split a cue's time across n_words in proportion to speech energy (centiseconds each).
239
+
240
+ Decodes the cue window to 8 kHz mono, builds a 10 ms RMS envelope, removes the noise floor,
241
+ and cuts at equal cumulative-energy quantiles: pauses get no words, loud stretches get more time.
242
+ Falls back to an even split when the window is silent or too short.
243
+ """
244
+ import struct
245
+ from _common import require_tool, run_analysis
246
+ total_cs = max(1, int(round((end - start) * 100)))
247
+ if n_words <= 1:
248
+ return [total_cs]
249
+ ffmpeg = require_tool("ffmpeg")
250
+ cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", "-ss", f"{start:.3f}", "-i", video,
251
+ "-map", f"0:a:{audio_stream}", "-t", f"{end - start:.3f}", "-vn",
252
+ # a sound that starts late is padded to its place on the file's clock (#414)
253
+ "-af", "aresample=async=1:first_pts=0", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"]
254
+ proc = run_analysis(cmd, check=False, text=False) # under --timeout like every other measurement
255
+ n = len(proc.stdout) // 2
256
+ if proc.returncode != 0 or n < 800:
257
+ per = total_cs // n_words
258
+ return [per] * (n_words - 1) + [total_cs - per * (n_words - 1)]
259
+ samples = struct.unpack(f"<{n}h", proc.stdout[: n * 2])
260
+ step = 80 # 10 ms
261
+ env = []
262
+ for i in range(0, n - step + 1, step):
263
+ block = samples[i:i + step]
264
+ env.append((sum(x * x for x in block) / step) ** 0.5)
265
+ floor = sorted(env)[len(env) // 5] # 20th percentile ~ noise floor
266
+ energy = [max(0.0, e - floor) for e in env]
267
+ total_e = sum(energy)
268
+ if total_e <= 0:
269
+ per = total_cs // n_words
270
+ return [per] * (n_words - 1) + [total_cs - per * (n_words - 1)]
271
+ # boundaries at cumulative-energy quantiles 1/n .. (n-1)/n
272
+ bounds = []
273
+ acc = 0.0
274
+ k = 1
275
+ for idx, e in enumerate(energy):
276
+ acc += e
277
+ while k < n_words and acc >= total_e * k / n_words:
278
+ bounds.append(idx + 1)
279
+ k += 1
280
+ while len(bounds) < n_words - 1:
281
+ bounds.append(len(energy))
282
+ prev = 0
283
+ out = []
284
+ for b in bounds:
285
+ cs = max(5, int(round((b - prev) * 1.0))) # 10 ms blocks -> centiseconds
286
+ out.append(cs)
287
+ prev = b
288
+ out.append(max(5, total_cs - sum(out)))
289
+ # normalise to the exact cue length. A cue too short for 5 cs per word (0.5 s, 20 words)
290
+ # used to push the remainder into the last word as a negative \kf; split evenly instead,
291
+ # and never let the last word go below 1 cs.
292
+ if total_cs < 5 * n_words:
293
+ per = max(1, total_cs // n_words)
294
+ out = [per] * (n_words - 1) + [max(1, total_cs - per * (n_words - 1))]
295
+ return out
296
+ scale = total_cs / max(1, sum(out))
297
+ out = [max(5, int(round(x * scale))) for x in out]
298
+ out[-1] += total_cs - sum(out)
299
+ while out[-1] < 1:
300
+ i = max(range(len(out) - 1), key=lambda j: out[j])
301
+ take = min(out[i] - 5, 1 - out[-1]) if out[i] > 5 else 0
302
+ if take <= 0:
303
+ break
304
+ out[i] -= take
305
+ out[-1] += take
306
+ return out
307
+
308
+
309
+
310
+ # --------------------------------------------------------------------------- emoji (1.15)
311
+ def _cue_lines(text: str) -> List[str]:
312
+ return [l for l in text.split("\n")]
313
+
314
+
315
+ def plan_emoji(cues, args, play_w, play_h, brand=None):
316
+ """Decide how this run draws the emoji in `cues`, and where each PNG goes.
317
+
318
+ Returns (cues, plan) where `cues` may have had its emoji replaced by EMOJI_SENTINEL (the PNG
319
+ route) or stripped (`--emoji none`), and `plan` is the `emoji` result key plus the overlay
320
+ entries the filter graph needs. `None` plan means "nothing to do": no emoji in the text.
321
+ """
322
+ clusters_all = [cl for _s, _e, t in cues for _i, cl in emoji_clusters(t)]
323
+ if not clusters_all:
324
+ return cues, None
325
+ assets = resolve_emoji_assets(getattr(args, "emoji_assets", None), None, brand)
326
+ want = getattr(args, "emoji", "auto")
327
+ support = emoji_support(assets, probe=True, fonts_dir=getattr(args, "fonts_dir", None))
328
+ mode = support["mode"] if want == "auto" else want
329
+ if want == "color" and not support["libass_color"]:
330
+ die("--emoji color: this ffmpeg renders emoji monochrome through libass "
331
+ f"({support['detail']}) -- pass --emoji-assets DIR for colour, or --emoji mono",
332
+ kind="input")
333
+ if want == "png" and not assets:
334
+ die("--emoji png: no emoji assets directory resolved -- " + EMOJI_ASSET_HINT, kind="input")
335
+ # --emoji mono asks for the font's glyph, and there is none: empty boxes (tofu) are a failed job
336
+ # (#395). An auto run takes mode "none" instead, as on a machine with no emoji face at all,
337
+ # and says why below; --emoji mono never uses assets, so they do not save it
338
+ if want == "mono" and support.get("libass_glyph") is False:
339
+ die(f"--emoji mono: this ffmpeg draws no emoji glyph through libass ({support['detail']}), so "
340
+ f"{len(clusters_all)} emoji would come out as empty boxes -- pass --emoji-assets DIR for colour, "
341
+ "or --emoji none to leave them out of the drawn text", kind="input")
342
+ if want == "mono" and support.get("libass_color"):
343
+ mode = "color"
344
+ warn(emoji_mono_on_colour_note(support), "emoji_mono_drawn_in_colour")
345
+ plan = {"mode": mode, "count": len(clusters_all),
346
+ "clusters": sorted({emoji_codepoint_name(cl) for cl in clusters_all}),
347
+ "assets": assets, "missing": [], "overlays": []}
348
+ if mode == "none":
349
+ out = []
350
+ for start, end, text in cues:
351
+ for cl in {cl for _i, cl in emoji_clusters(text)}:
352
+ text = text.replace(cl, "")
353
+ out.append((start, end, re.sub(r"[ \t]{2,}", " ", text).strip()))
354
+ if want == "auto":
355
+ why = ("libass draws no emoji glyph on this build (an empty box at best)"
356
+ if support.get("libass_glyph") is False else "no face here draws them")
357
+ msg = (f"emoji: {len(clusters_all)} left out of the drawn text: {why} -- pass --emoji-assets DIR "
358
+ "to draw them as PNGs")
359
+ warn(msg, "emoji_not_drawn", count=len(clusters_all), reason=support.get("detail"))
360
+ else:
361
+ info("emoji: stripped from the drawn text (--emoji none)")
362
+ return out, plan
363
+ if mode in ("color", "mono"):
364
+ if mode == "mono":
365
+ warn("emoji rendered monochrome (no colour path on this ffmpeg; "
366
+ "--emoji-assets DIR for colour). " + support["detail"], "emoji_monochrome")
367
+ return cues, plan
368
+ # --- the PNG overlay route -------------------------------------------------------------
369
+ if not play_w or not play_h:
370
+ return cues, plan
371
+ scale = float(getattr(args, "emoji_scale", 1.0) or 1.0)
372
+ # --animate moves the TEXT (\fad/\fscx in the ASS); the PNG has to move with it, or the emoji
373
+ # pops in against a line that is still fading up. These match the \fad values below.
374
+ fade_in, fade_out = (ms / 1000.0 for ms in ANIMATE_FADE_MS.get(getattr(args, "animate", None) or "none", (0, 0)))
375
+ size_px = args.size * play_h / 288.0
376
+ margin_px = args.margin * play_h / 288.0
377
+ line_h = size_px * 1.2
378
+ box_px = size_px * scale
379
+ # A62 (#457): libass lays a line out between the Style's MarginL and MarginR (margins_x, the
380
+ # horizontal safe zone), not --margin, which is the vertical distance: a left-aligned PNG was
381
+ # drawn over the first words and a right-aligned one left of its gap
382
+ margin_l, margin_r = margins_x(args, play_w)
383
+ out_cues = []
384
+ for start, end, text in cues:
385
+ lines = _cue_lines(text)
386
+ n = len(lines)
387
+ new_lines = []
388
+ align = srt_alignment(text) or ALIGN[args.position] # a cue's {\anN} moves its emoji too
389
+ for i, line in enumerate(lines):
390
+ if align in (7, 8, 9):
391
+ y_top = margin_px + i * line_h
392
+ elif align in (4, 5, 6):
393
+ y_top = play_h / 2.0 - (n * line_h) / 2.0 + i * line_h
394
+ else:
395
+ y_top = play_h - margin_px - (n - i) * line_h
396
+ line_w = text_width_em(strip_srt_markup(line), scale) * size_px
397
+ if align in (1, 4, 7):
398
+ x0 = float(margin_l)
399
+ elif align in (3, 6, 9):
400
+ x0 = play_w - margin_r - line_w
401
+ else:
402
+ x0 = margin_l + (play_w - margin_l - margin_r - line_w) / 2.0
403
+ # libass lays an RTL line out right-to-left, so the LOGICAL prefix of a cluster
404
+ # occupies the RIGHT end of the rendered line. Measuring the prefix from the left
405
+ # edge put the PNG on top of the text, mirrored, on every Arabic/Hebrew cue (1.15.0).
406
+ rtl = detect_script(strip_srt_markup(line)) in BIDI_SCRIPTS
407
+ rebuilt = ""
408
+ cursor = 0
409
+ for idx, cluster in emoji_clusters(line):
410
+ prefix = line[:idx]
411
+ asset = emoji_asset_for(cluster, assets)
412
+ name = emoji_codepoint_name(cluster)
413
+ if not asset:
414
+ if name not in plan["missing"]:
415
+ plan["missing"].append(name)
416
+ rebuilt += line[cursor:idx + len(cluster)]
417
+ cursor = idx + len(cluster)
418
+ continue
419
+ prefix = strip_srt_markup(prefix) # a tag before the emoji takes no room
420
+ if rtl:
421
+ x = x0 + line_w - text_width_em(prefix + cluster, scale) * size_px
422
+ else:
423
+ x = x0 + text_width_em(prefix, scale) * size_px
424
+ y = y_top + (line_h - box_px) / 2.0
425
+ plan["overlays"].append({
426
+ "asset": asset, "cluster": name,
427
+ "x": int(round(max(0.0, min(x, play_w - box_px)))),
428
+ "y": int(round(max(0.0, min(y, play_h - box_px)))),
429
+ "start": round(start, 3), "end": round(end, 3), "box": int(round(box_px)),
430
+ "fade_in": round(min(fade_in, max(0.0, (end - start) / 2.0)), 3),
431
+ "fade_out": round(min(fade_out, max(0.0, (end - start) / 2.0)), 3)})
432
+ rebuilt += line[cursor:idx] + EMOJI_SENTINEL
433
+ cursor = idx + len(cluster)
434
+ rebuilt += line[cursor:]
435
+ new_lines.append(rebuilt)
436
+ out_cues.append((start, end, "\n".join(new_lines)))
437
+ # `or 60` would swallow the one value that means "no overlays at all".
438
+ _max = getattr(args, "emoji_max", None)
439
+ limit = 60 if _max is None else int(_max)
440
+ if len(plan["overlays"]) > limit:
441
+ die(f"{len(plan['overlays'])} emoji overlays would be built for this job (limit {limit}, "
442
+ "--emoji-max raises it); ffmpeg's filter graph and the per-frame cost both grow "
443
+ "linearly -- split the job, or use --emoji none", kind="input")
444
+ if plan["missing"]:
445
+ warn(emoji_missing_asset_note(plan["missing"], support), "emoji_assets_missing", missing=list(plan["missing"]))
446
+ plan["box_px"] = int(round(box_px))
447
+ return out_cues, plan
448
+
449
+
450
+ def layout_cues(cues: List[Tuple[float, float, str]], *, max_em: Optional[float], max_lines: int,
451
+ min_duration: float, offset: float, wrap: str = "phrase",
452
+ lang: Optional[str] = None, per_cue_em: Optional[List[Optional[float]]] = None,
453
+ per_cue_size: Optional[List[int]] = None) -> Tuple[List[Tuple[float, float, str]], dict]:
454
+ """Shift, wrap, split and lengthen cues so they can actually be read.
455
+
456
+ `offset` moves every cue (a transcript that runs early/late); `max_em` wraps each cue to the
457
+ safe area at the chosen size (None when no video geometry is known, e.g. --write-srt alone);
458
+ a cue needing more than `max_lines` lines is split into consecutive cues sharing its time in
459
+ proportion to their text; a cue shorter than `min_duration` is lengthened, never past the next
460
+ cue's start. Returns the new cues and a count of what changed.
461
+
462
+ `per_cue_em` (--fit-size-scope cue) gives cue i its OWN line budget instead of the file's:
463
+ a cue drawn at a larger size has a narrower line in em, and wrapping it to the file-wide
464
+ budget -- which is the budget of the SMALLEST size -- produced lines that overflowed the
465
+ frame when they were then drawn large. `per_cue_size` rides along so the caller knows which
466
+ size each OUTPUT cue belongs to after splits have renumbered them; it comes back as
467
+ `stats["cue_sizes"]`, one entry per returned cue.
468
+ """
469
+ stats = {"shifted": 0, "wrapped": 0, "split": 0, "extended": 0, "dropped": 0, "rebalanced": 0,
470
+ "wrap": wrap, "phrase_breaks": 0}
471
+ # ass_units_local's floor + the escape hatch below mean an atom this loop hands to
472
+ # wrap_variants(..., slice_overlong=True) can still overflow only if a SINGLE character is
473
+ # wider than the column -- practically unreachable at any real --min-size. `overlong` stays
474
+ # in stats for that theoretical remainder; `broken_inside_word` is the count that matters now.
475
+ staged: List[Tuple[float, float, str]] = []
476
+ staged_sizes: List[Optional[int]] = []
477
+ for cue_index, (start, end, text) in enumerate(cues):
478
+ own_em = max_em
479
+ own_size = None
480
+ if per_cue_em is not None and cue_index < len(per_cue_em):
481
+ own_em = per_cue_em[cue_index]
482
+ if per_cue_size is not None and cue_index < len(per_cue_size):
483
+ own_size = per_cue_size[cue_index]
484
+ if offset:
485
+ start, end = start + offset, end + offset
486
+ if end <= 0:
487
+ stats["dropped"] += 1
488
+ continue
489
+ start = max(0.0, start)
490
+ stats["shifted"] += 1
491
+ if own_em and own_em > 0:
492
+ # one greedy fill per cue, three answers off it: what gets burnt in, what the
493
+ # greedy wrap would have given (`rebalanced`) and what 1.15's wrap would have
494
+ # given (`phrase_breaks`). Three wrap_text() calls re-ran the atomiser each time.
495
+ sliced_atoms: List[int] = []
496
+ # SRT markup (<i>, <font color>, {\an8}) is not text: the wrap measures and breaks
497
+ # the words a viewer reads, and the tags go back next to the characters they styled
498
+ plain = strip_srt_markup(text)
499
+ lines, greedy, measured = wrap_variants(plain, own_em, mode=wrap, lang=lang,
500
+ slice_overlong=True, sliced=sliced_atoms)
501
+ if lines != [l for l in plain.split("\n") if l.strip()]:
502
+ stats["wrapped"] += 1
503
+ if sliced_atoms:
504
+ # the escape hatch fired: a word or run with no break point the wrapper may use
505
+ # was still wider than the column alone, even at the size in force, so it was
506
+ # hard-sliced at the column edge (or after its own hyphen) instead of clipping
507
+ stats["broken_inside_word"] = stats.get("broken_inside_word", 0) + len(sliced_atoms)
508
+ if any(text_width_em(l) > own_em for l in lines):
509
+ # the escape hatch above could not make every piece fit -- only possible when a
510
+ # single character is wider than the column itself
511
+ stats["overlong"] = stats.get("overlong", 0) + 1
512
+ if lines != greedy:
513
+ stats["rebalanced"] += 1
514
+ if wrap != "measured" and lines != measured:
515
+ stats["phrase_breaks"] += 1
516
+ marked = reinsert_srt_markup(text, lines) if plain != text else lines
517
+ if len(lines) > max_lines:
518
+ chunks = [lines[i:i + max_lines] for i in range(0, len(lines), max_lines)]
519
+ weights = [max(1.0, sum(len(l) for l in c)) for c in chunks]
520
+ total_w = sum(weights)
521
+ pieces = carry_srt_markup(["\n".join(marked[i:i + max_lines])
522
+ for i in range(0, len(marked), max_lines)])
523
+ t = start
524
+ for piece, weight in zip(pieces, weights):
525
+ seg = (end - start) * weight / total_w
526
+ staged.append((t, min(end, t + seg), piece))
527
+ staged_sizes.append(own_size)
528
+ t += seg
529
+ stats["split"] += len(chunks) - 1
530
+ continue
531
+ text = "\n".join(marked)
532
+ staged.append((start, end, text))
533
+ staged_sizes.append(own_size)
534
+ out: List[Tuple[float, float, str]] = []
535
+ for i, (start, end, text) in enumerate(staged):
536
+ if min_duration and end - start < min_duration:
537
+ limit = staged[i + 1][0] if i + 1 < len(staged) else None
538
+ new_end = start + min_duration if limit is None else min(start + min_duration, limit)
539
+ if new_end > end:
540
+ stats["extended"] += 1
541
+ end = new_end
542
+ out.append((start, end, text))
543
+ if per_cue_size is not None:
544
+ stats["cue_sizes"] = staged_sizes
545
+ return out, stats
546
+
547
+
548
+ def report_layout(stats: dict) -> None:
549
+ """One info line, only when a cue actually changed."""
550
+ parts = [f"{stats[k]} {k}" for k in ("shifted", "wrapped", "rebalanced", "phrase_breaks", "split",
551
+ "extended", "dropped", "broken_inside_word", "overlong") if stats.get(k)]
552
+ if parts:
553
+ info("cues: " + ", ".join(parts))
554
+ if stats.get("broken_inside_word"):
555
+ info(f"{stats['broken_inside_word']} cue line(s) had a word or run with no break point "
556
+ "(Thai writes none inside a phrase) that was still wider than the column alone -- it "
557
+ "was sliced at the column edge (after its own hyphen when it has one) instead of "
558
+ "clipping past the frame; put a space or `|` where the line may break, or use a "
559
+ "smaller --size, to avoid the slice")
560
+ if stats.get("overlong"):
561
+ info(f"{stats['overlong']} cue line(s) wider than the safe width even after slicing: a "
562
+ "single character was wider than the column -- use a smaller --size")
563
+
564
+
565
+ def margins_x(args, play_w: Optional[int]) -> Tuple[int, int]:
566
+ """(MarginL, MarginR) in ASS script pixels -- the HORIZONTAL safe zone, never --margin.
567
+
568
+ 1.17.2. --margin is the vertical distance from the edge (the platform's bottom UI: TikTok's
569
+ description bar is 22 % of the frame, 63 ASS units, 420 px on a 1920-tall frame). Writing it
570
+ into MarginL/MarginR as well, as 1.14-1.17.1 did, left a 1080-wide frame with a 240 px text
571
+ column and libass wrapped "Hello world" onto two lines while the fitter -- which measures
572
+ against the horizontal safe width -- reported no wrap at all.
573
+
574
+ The left/right margins come from the destination's own horizontal safe zone (`safe.left` /
575
+ `safe.right` in scripts/_platforms.py; TikTok reserves 14 % on the right for the like/share
576
+ rail), and without a --platform from the conventional (1 - SAFE_WIDTH_FRACTION)/2 border --
577
+ the same 5 % per side the wrapper has always assumed. A run that writes no ASS of its own
578
+ (the SRT force_style burn) keeps that symmetric border, so its budget is unchanged at
579
+ SAFE_WIDTH_FRACTION and the fitter still agrees with what libass will do.
580
+ """
581
+ if not play_w:
582
+ return 0, 0
583
+ if getattr(args, "platform", None) and PLATFORMS[args.platform].get("frame") and draws_own_ass(args):
584
+ safe = PLATFORMS[args.platform]["safe"]
585
+ left, right = float(safe["left"]), float(safe["right"])
586
+ else:
587
+ left = right = (1.0 - SAFE_WIDTH_FRACTION) / 2.0
588
+ return int(round(left * play_w)), int(round(right * play_w))
589
+
590
+
591
+ def draws_own_ass(args) -> bool:
592
+ """True when this run generates its own ASS, and so sets its own Style margins.
593
+
594
+ An SRT burn goes through libass's force_style instead, which states MarginV only and leaves
595
+ the side margins at libass's own defaults -- that path's budget stays the historical
596
+ play_w * SAFE_WIDTH_FRACTION, unchanged by 1.17.2.
597
+ """
598
+ if getattr(args, "ass", None):
599
+ return False # the caller's own ASS: its Style is theirs, not ours
600
+ return (getattr(args, "animate", "none") or "none") != "none" or bool(getattr(args, "karaoke", False))
601
+
602
+
603
+ def safe_width_fraction(args, play_w: Optional[int]) -> float:
604
+ """The fraction of the frame width a caption line may use -- play_w minus the two margins.
605
+
606
+ The fitter and libass have to agree to the pixel, so this is derived from the SAME rounded
607
+ MarginL/MarginR that go into the ASS Style rather than from the raw fractions. On a run that
608
+ writes no ASS of its own the margins are the symmetric border, i.e. SAFE_WIDTH_FRACTION, so
609
+ the SRT force_style path keeps its historical budget.
610
+ """
611
+ if not play_w:
612
+ return SAFE_WIDTH_FRACTION
613
+ left, right = margins_x(args, play_w)
614
+ return max(0.05, (play_w - left - right) / float(play_w))
615
+
616
+
617
+ def line_fraction(args, play_w: Optional[int]) -> float:
618
+ """The width fraction one line is wrapped to: safe_width_fraction, narrowed under
619
+ --karaoke-style word by --karaoke-scale.
620
+
621
+ --karaoke-style word scales its active word up by --karaoke-scale and freezes the line break
622
+ (WrapStyle: 2 in write_ass) so libass can never re-wrap around that scale-up. The budget is
623
+ narrowed by the same factor so the longest wrapped line -- computed at the UNscaled width --
624
+ still fits once its active word is drawn --karaoke-scale%% larger; without this, a line that
625
+ exactly filled the safe width would overflow it the moment its emphasised word appears. The
626
+ size fit measures against the same budget, or a cue it reported as fitting was split by the
627
+ layout after it (A58, #457).
628
+ """
629
+ frac = safe_width_fraction(args, play_w)
630
+ if getattr(args, "karaoke", False) and getattr(args, "karaoke_style", "sweep") == "word":
631
+ frac = frac / max(1.0, getattr(args, "karaoke_scale", 112) / 100.0)
632
+ return frac
633
+
634
+
635
+ def max_line_em(args, play_w: Optional[int], play_h: Optional[int]) -> Optional[float]:
636
+ """How many em fit on one caption line at the chosen size, or None without video geometry.
637
+
638
+ --size is in ASS points against a 288-line script (what libass's force_style uses), so the
639
+ rendered pixel size is size * play_h / 288; the width is line_fraction's.
640
+ """
641
+ return line_em_for_size(args.size, play_w, play_h, safe_fraction=line_fraction(args, play_w))
642
+
643
+
644
+ def parse_ass_dialogue(path: str) -> str:
645
+ """The spoken text of an ASS file, for script detection -- style/override blocks stripped."""
646
+ text = []
647
+ for line in read_text_or_die(path, "--ass").split("\n"):
648
+ if not line.startswith("Dialogue:"):
649
+ continue
650
+ fields = line.split(",", 9)
651
+ if len(fields) == 10:
652
+ text.append(re.sub(r"\{[^}]*\}", "", fields[9]))
653
+ return "\n".join(text)
654
+
655
+
656
+ def parse_ass_cues(path: str, stats: Optional[dict] = None) -> List[Tuple[float, float, str]]:
657
+ """(start, end, drawn text) of every Dialogue line of an ASS file, override blocks stripped.
658
+ A Dialogue line with too few fields or an unreadable start/end is left out; `stats`, when
659
+ given, gets their number as `malformed` so the caller can say how many it could not count."""
660
+ def secs(stamp: str) -> float:
661
+ h, m, rest = stamp.strip().split(":")
662
+ return int(h) * 3600 + int(m) * 60 + float(rest)
663
+
664
+ cues: List[Tuple[float, float, str]] = []
665
+ malformed = 0
666
+ # the [Events] Format line names the columns; Text is always last (libass reads it the same
667
+ # way), and a file without one gets the standard ten
668
+ names = ["layer", "start", "end", "style", "name", "marginl", "marginr", "marginv", "effect", "text"]
669
+ for line in read_text_or_die(path, "--ass").split("\n"):
670
+ if line.startswith("Format:") and "text" in line.lower():
671
+ names = [n.strip().lower() for n in line.partition(":")[2].split(",")]
672
+ continue
673
+ if not line.startswith("Dialogue:"):
674
+ continue
675
+ fields = line.partition(":")[2].split(",", len(names) - 1)
676
+ if len(fields) < len(names) or "start" not in names or "end" not in names:
677
+ malformed += 1
678
+ continue
679
+ try:
680
+ start, end = secs(fields[names.index("start")]), secs(fields[names.index("end")])
681
+ except (ValueError, IndexError):
682
+ malformed += 1
683
+ continue
684
+ text = re.sub(r"\{[^}]*\}", "", fields[-1]).replace("\\N", "\n").replace("\\n", "\n").replace("\\h", " ")
685
+ cues.append((start, end, text))
686
+ if stats is not None:
687
+ stats["malformed"] = malformed
688
+ return cues
689
+
690
+
691
+ def cue_text_visible(text: str) -> bool:
692
+ return bool(strip_srt_markup(text or "").strip()) # `<i></i>` draws nothing
693
+
694
+
695
+ def count_visible_cues(cues, duration) -> Tuple[int, int]:
696
+ """(cues drawn inside [0, duration], non-blank cues entirely outside it). Blank cues count in
697
+ neither. With no known duration every non-blank cue is taken as drawn."""
698
+ burned = outside = 0
699
+ dur = float(duration) if duration else None
700
+ for start, end, text in cues:
701
+ if not cue_text_visible(text):
702
+ continue
703
+ if end > 0 and (dur is None or start < dur):
704
+ burned += 1
705
+ else:
706
+ outside += 1
707
+ return burned, outside
708
+
709
+
710
+ def shift_ass_file(src: str, dst: str, offset: float) -> Tuple[int, int]:
711
+ """Copy an ASS file with every Dialogue start/end moved by `offset` seconds; (lines shifted,
712
+ Dialogue lines copied unshifted because their timestamps could not be read)."""
713
+ # read as the dry run reads it: a file that is not UTF-8 is refused as kind input on both
714
+ text, n, unshifted = shift_ass_text(read_text_or_die(src, "--ass"), offset)
715
+ Path(dst).write_text(text, encoding="utf-8-sig")
716
+ return n, unshifted
717
+
718
+
719
+ def shift_ass_text(source: str, offset: float) -> Tuple[str, int, int]:
720
+ """shift_ass_file() on text: (shifted text, lines shifted, Dialogue lines left as they were).
721
+ Pure, so a dry run can report the counts without writing the copy."""
722
+ def shift(stamp: str) -> str:
723
+ h, m, rest = stamp.split(":")
724
+ secs = int(h) * 3600 + int(m) * 60 + float(rest) + offset
725
+ secs = max(0.0, secs)
726
+ cs = int(round(secs * 100))
727
+ hh, rem = divmod(cs, 360000)
728
+ mm, rem = divmod(rem, 6000)
729
+ ss, cc = divmod(rem, 100)
730
+ return f"{hh}:{mm:02d}:{ss:02d}.{cc:02d}"
731
+
732
+ n = unshifted = 0
733
+ out = []
734
+ # lines end at "\n" only (libass reads them so); a U+2028 inside a Dialogue's text is text
735
+ body = normalize_text(source)
736
+ for line in (body[:-1] if body.endswith("\n") else body).split("\n"):
737
+ if line.startswith("Dialogue:"):
738
+ head, sep, rest = line.partition(":")
739
+ fields = rest.split(",")
740
+ done = False
741
+ if len(fields) >= 3:
742
+ try:
743
+ fields[1], fields[2] = shift(fields[1].strip()), shift(fields[2].strip())
744
+ line = head + sep + ",".join(fields)
745
+ n += 1
746
+ done = True
747
+ except (ValueError, IndexError):
748
+ pass
749
+ if not done:
750
+ unshifted += 1 # copied as it was: counted and reported, not dropped unseen
751
+ out.append(line)
752
+ return "\n".join(out) + "\n", n, unshifted
753
+
754
+
755
+ def word_durations_from_timings(words: List[Tuple[float, float, str]], start: float, end: float,
756
+ n_words: int) -> Optional[Tuple[int, List[int]]]:
757
+ """(lead, centiseconds per word) for one cue from real word timings; None when they don't
758
+ cover it. `lead` is the silence between the cue's start and its first word: the highlight
759
+ waits for it rather than starting at the cue and running ahead of the speech by that much
760
+ (A59, #457)."""
761
+ inside = [w for w in words if w[1] > start + 0.01 and w[0] < end - 0.01]
762
+ if len(inside) != n_words or n_words <= 0:
763
+ return None
764
+ total_cs = max(1, int(round((end - start) * 100)))
765
+ first = min(end, max(start, inside[0][0]))
766
+ lead = int(round((first - start) * 100))
767
+ bounds = [first] + [max(first, min(end, w[1])) for w in inside]
768
+ out = [max(1, int(round((bounds[i + 1] - bounds[i]) * 100))) for i in range(n_words)]
769
+ out[-1] += total_cs - lead - sum(out)
770
+ if out[-1] < 1:
771
+ return None
772
+ return lead, out
773
+
774
+
775
+ def _karaoke_word_durations(args, video: Optional[str], start: float, end: float,
776
+ n_words: int) -> Tuple[int, List[int]]:
777
+ """(lead, centiseconds per word) for one cue, shared by --karaoke-style sweep and word.
778
+
779
+ Real word timings from the transcript beat both the energy estimate and the even split --
780
+ they are what the speaker actually did, not a proxy for it. Only they carry a lead (the
781
+ silence before the first word); the other two share the whole cue out from its start.
782
+ """
783
+ dur_cs = max(1, int(round((end - start) * 100)))
784
+ timed = word_durations_from_timings(getattr(args, "_word_timings", None) or [], start, end, n_words)
785
+ if timed is not None:
786
+ return timed
787
+ if getattr(args, "karaoke_timing", "even") == "energy" and video:
788
+ return 0, word_durations_from_audio(video, start, end, n_words, getattr(args, "audio_stream", 0))
789
+ per = max(1, dur_cs // max(1, n_words))
790
+ return 0, [per] * n_words
791
+
792
+
793
+ def shift_words(words: List[Tuple[float, float, str]], offset: float) -> List[Tuple[float, float, str]]:
794
+ """Word timings moved by --offset, as the cues they belong to are (#505): the offset corrects a
795
+ transcript that runs early or late against the sound, and its word timings come from the same
796
+ transcript."""
797
+ if not offset:
798
+ return list(words or [])
799
+ return [(s + offset, e + offset, w) for s, e, w in (words or [])]
800
+
801
+
802
+ # A `{...}` that ffmpeg's SRT reader passes on to libass as text, where it is an override block and
803
+ # draws nothing: not `{\...}` (ffmpeg removes those itself), not a MicroDVD `{y:i}` style code, not
804
+ # the `\{` escape
805
+ SRT_HIDDEN_BRACES_RE = re.compile(r"(?<!\\)\{(?!\\)(?![CcFfoPSsYy]:)[^{}]*\}")
806
+
807
+
808
+ # --animate's envelope in ms (fade in, fade out), and the slide's rise: one table for the ASS
809
+ # below and the emoji PNGs that ride it (plan_emoji)
810
+ ANIMATE_FADE_MS = {"fade": (200, 200), "pop": (80, 120), "slide": (150, 150)}
811
+ SLIDE_MS = 250
812
+
813
+
814
+ def line_anchor(align: int, play_w: int, play_h: int, margin: int, margin_l: int, margin_r: int) -> Tuple[int, int]:
815
+ """The point libass anchors a line of alignment `align` (numpad) at, from the Style's margins:
816
+ what a `\\move` has to end on so that --animate slide lands where the line is drawn without it
817
+ (A56, #457: the slide always ended at the bottom centre)."""
818
+ if align in (1, 4, 7):
819
+ x = margin_l
820
+ elif align in (3, 6, 9):
821
+ x = play_w - margin_r
822
+ else:
823
+ x = margin_l + (play_w - margin_l - margin_r) // 2
824
+ if align in (7, 8, 9):
825
+ y = margin
826
+ elif align in (4, 5, 6):
827
+ y = play_h // 2
828
+ else:
829
+ y = play_h - margin
830
+ return x, y
831
+
832
+
833
+ def animate_fx(kind: str, o: int, e: int, dur: int, anchor: Tuple[int, int], rise: int) -> str:
834
+ """The --animate override for an event shown from `o` to `e` ms into a cue `dur` ms long.
835
+
836
+ A whole cue (o == 0, e == dur) gets the envelope it always had. --karaoke-style word draws a
837
+ cue as one event per word: each gets the part of the cue's one envelope that falls inside it,
838
+ started where the event before left it, so the fade-out comes at the cue's end and not at the
839
+ end of the first word, and a slide or a pop does not restart or jump at a word (A57, #457)."""
840
+ if kind not in ANIMATE_FADE_MS:
841
+ return ""
842
+ fin, fout = ANIMATE_FADE_MS[kind]
843
+ x, y2 = anchor
844
+ y1 = y2 + rise
845
+ whole = o == 0 and e == dur
846
+ if whole:
847
+ fade = "\\fad(%d,%d)" % (fin, fout)
848
+ else:
849
+ out_at = dur - fout
850
+
851
+ def alpha(t: float) -> int:
852
+ a = 0.0
853
+ if t < fin:
854
+ a = 255.0 * (1.0 - t / float(fin))
855
+ if t > out_at and fout:
856
+ a = max(a, 255.0 * (t - out_at) / float(fout))
857
+ return int(round(min(255.0, max(0.0, a))))
858
+ if o >= fin and e <= out_at:
859
+ fade = ""
860
+ else:
861
+ a1 = alpha(o)
862
+ t2 = max(0, fin - o)
863
+ t3 = max(t2, out_at - o)
864
+ fade = "\\fade(%d,%d,255,0,%d,%d,%d)" % (a1, a1 if o > out_at else 0, t2, t3, max(t3, dur - o))
865
+ if kind == "fade":
866
+ tags = fade
867
+ elif kind == "pop":
868
+ if o == 0:
869
+ scale = "\\fscx60\\fscy60\\t(0,120,\\fscx110\\fscy110)\\t(120,200,\\fscx100\\fscy100)"
870
+ elif o < 120:
871
+ v = int(round(60 + 50 * o / 120.0))
872
+ scale = ("\\fscx%d\\fscy%d\\t(0,%d,\\fscx110\\fscy110)\\t(%d,%d,\\fscx100\\fscy100)"
873
+ % (v, v, 120 - o, 120 - o, 200 - o))
874
+ elif o < 200:
875
+ v = int(round(110 - 10 * (o - 120) / 80.0))
876
+ scale = "\\fscx%d\\fscy%d\\t(0,%d,\\fscx100\\fscy100)" % (v, v, 200 - o)
877
+ else:
878
+ scale = ""
879
+ tags = fade + scale
880
+ else:
881
+ if o == 0:
882
+ move = "\\move(%d,%d,%d,%d,0,%d)" % (x, y1, x, y2, SLIDE_MS)
883
+ elif o < SLIDE_MS:
884
+ move = "\\move(%d,%d,%d,%d,0,%d)" % (x, int(round(y1 + (y2 - y1) * o / float(SLIDE_MS))), x, y2, SLIDE_MS - o)
885
+ else:
886
+ move = "\\pos(%d,%d)" % (x, y2)
887
+ tags = fade + move
888
+ return "{" + tags + "}" if tags else ""
889
+
890
+
891
+ # an override block this file wrote (a converted SRT tag), not the escaped `\{` a user typed
892
+ _OVERRIDE_BLOCK_RE = re.compile(r"(?<!\\)\{\\[^{}]*\}")
893
+
894
+
895
+ def _karaoke_word(token: str) -> bool:
896
+ """Does this space-separated Dialogue token hold something a viewer reads? An emoji
897
+ placeholder does not, and neither does a lone converted tag (`{\\i1}` from `<i> Hello`):
898
+ neither gets a share of the cue's time or a highlight of its own."""
899
+ return bool(_OVERRIDE_BLOCK_RE.sub("", token).strip(EMOJI_SENTINEL))
900
+
901
+
902
+ def write_ass(cues: List[Tuple[float, float, str]], path: str, args, play_w: int, play_h: int, video: str = None) -> None:
903
+ """Write a styled ASS file with optional animation and word-by-word highlight."""
904
+ def t(sec: float) -> str:
905
+ cs = int(round(sec * 100))
906
+ h, rem = divmod(cs, 360000)
907
+ m, rem = divmod(rem, 6000)
908
+ s_, cs = divmod(rem, 100)
909
+ return f"{h}:{m:02d}:{s_:02d}.{cs:02d}"
910
+
911
+ scale = play_h / 288.0 # our --size is relative to a 288-line script like force_style
912
+ size = int(round(args.size * scale))
913
+ margin = int(round(args.margin * scale)) # vertical: MarginV, and the slide origin
914
+ margin_l, margin_r = margins_x(args, play_w) # horizontal: the frame's safe zone
915
+ # karaoke: PrimaryColour is the "sung" colour, SecondaryColour the "not yet sung" one
916
+ primary = ass_color(args.highlight_color if args.karaoke else args.color)
917
+ secondary = ass_color(args.color)
918
+ outline = ass_color(args.outline_color)
919
+ back_alpha = 0x80 # the --box colour is half transparent; an emoji placeholder restores it
920
+ back = ass_color(args.outline_color, back_alpha)
921
+ word_style = args.karaoke and getattr(args, "karaoke_style", "sweep") == "word"
922
+ word_past = ass_color(args.color)
923
+ word_active = ass_color(args.highlight_color)
924
+ word_upcoming = ass_color(args.upcoming_color)
925
+ word_bord = f"{args.outline * scale * (max(1.0, args.karaoke_scale) / 100.0):.2f}"
926
+ style_bord = f"{args.outline * scale:.2f}"
927
+ word_scale = int(round(args.karaoke_scale))
928
+ # --karaoke-style word emits one Dialogue per word carrying the WHOLE cue with explicit \N
929
+ # breaks (the layout's own fixed line list -- see max_line_em's docstring). WrapStyle: 2 tells
930
+ # libass to honour only those explicit breaks and never re-wrap: with WrapStyle: 0 (the sweep
931
+ # default, unchanged), scaling the active word up would re-flow the line and it would visibly
932
+ # jump every time the highlight advances (the trap the issue this implements is filed against).
933
+ encoding = ass_base_encoding(strip_srt_markup(text) for _, _, text in cues)
934
+ header = [
935
+ "[Script Info]", "ScriptType: v4.00+", f"PlayResX: {play_w}", f"PlayResY: {play_h}",
936
+ # YCbCr Matrix: None -- the colours are RGB, to be put in the video's own matrix: FFmpeg 8.x's
937
+ # ass filter reads an absent header as BT.601 whatever the picture is tagged (drawn_chain)
938
+ f"WrapStyle: {2 if word_style else 0}", "ScaledBorderAndShadow: yes", "YCbCr Matrix: None", "",
939
+ "[V4+ Styles]",
940
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
941
+ f"Style: Default,{ass_font_name(args.font)},{size},{primary},{secondary},{outline},{back},{-1 if args.bold else 0},0,0,0,100,100,0,0,{3 if args.box else 1},{args.outline * scale:.1f},{args.shadow * scale:.1f},{ALIGN[args.position]},{margin_l},{margin_r},{margin},{encoding}",
942
+ "", "[Events]", "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
943
+ ]
944
+ lines = []
945
+ for cue_index, (start, end, text) in enumerate(cues):
946
+ # ASS Dialogue text treats a literal `{...}` as an override block -- real style/animation
947
+ # commands, not literal characters. Cue text (from --text, an SRT, or ASR transcription --
948
+ # all effectively user-controlled) that happens to contain braces would otherwise be
949
+ # interpreted as those commands (\pos, \t, \fscx, ...), letting caption content reposition,
950
+ # rescale, or recolor itself or later text instead of just being read out. libass has real
951
+ # escapes for the braces, so 1.15 escapes them (ass_escape) rather than deleting them:
952
+ # a cue that says "use {curly} braces" is read out with its braces, and still cannot open
953
+ # an override block. Newlines become \N in the same pass.
954
+ # SRT markup is the exception (#X2): <i>/<b>/<u>/<s>, <font color> and {\anN} become the
955
+ # overrides ffmpeg's SRT reader gives them, so this route draws what the plain one draws
956
+ # the line's anchor for --animate slide: the cue's own {\anN} first, as libass reads it
957
+ anchor = line_anchor(srt_alignment(text) or ALIGN[args.position], play_w, play_h, margin, margin_l, margin_r)
958
+ text = ass_escape_markup(text, colour=not args.karaoke)
959
+ cue_ms = max(1, int(round((end - start) * 100))) * 10
960
+ fx = animate_fx(args.animate, 0, cue_ms, cue_ms, anchor, int(30 * scale))
961
+ size_fx = ""
962
+ body = text
963
+ # --fit-size-scope cue: one size per cue, as a leading {\fsN} override. Opt-in only --
964
+ # see fit_size()'s docstring for why a size that changes cue to cue is not the default.
965
+ # The size is the one THIS cue was laid out at, carried through layout_cues; re-measuring
966
+ # here would measure the post-layout text (already carrying the wrap's newlines), which
967
+ # is a different string from the one the fit was computed on.
968
+ own_sizes = getattr(args, "_fit_sizes_out", None) or []
969
+ own = own_sizes[cue_index] if cue_index < len(own_sizes) else None
970
+ if own and own != args.size:
971
+ size_fx = "{\\fs%d}" % int(round(own * scale))
972
+ fx += size_fx
973
+ if args.karaoke and word_style:
974
+ # One Dialogue event per WORD, each carrying the whole cue -- \k/\kf can only
975
+ # interpolate colour, so scaling/emboldening the active word (and a third "upcoming"
976
+ # colour) needs a real per-word override block instead. The line list is `body`'s own
977
+ # \N split, already frozen by layout_cues (this function never re-wraps it), so every
978
+ # event uses the identical break -- WrapStyle: 2 above stops libass re-wrapping around
979
+ # the active word's larger \fscx/\fscy, which is the jump the issue is filed against.
980
+ line_words = [[w for w in seg.split(" ") if w] for seg in body.split("\\N")]
981
+ flat = [w for lw in line_words for w in lw]
982
+ real_idx = [i for i, w in enumerate(flat) if _karaoke_word(w)]
983
+ if not real_idx:
984
+ # nothing to highlight (an all-emoji or empty cue) -- one plain event, same as
985
+ # today's karaoke-off rendering, rather than zero Dialogue lines for this cue
986
+ out_body = body
987
+ if EMOJI_SENTINEL in out_body:
988
+ out_body = out_body.replace(EMOJI_SENTINEL, emoji_placeholder(getattr(args, "_emoji_box_px", size), back_alpha))
989
+ lines.append(f"Dialogue: 0,{t(start)},{t(end)},Default,,0,0,0,,{fx}{out_body}")
990
+ continue
991
+ n_words = len(real_idx)
992
+ lead, durs = _karaoke_word_durations(args, video, start, end, n_words)
993
+ # (first cs, cs, active word): the silence before the first word is an event of its
994
+ # own in which no word is active yet (A59)
995
+ events, acc = ([(0, lead, -1)] if lead > 0 else []), lead
996
+ for j, d in enumerate(durs):
997
+ events.append((acc, d, j))
998
+ acc += d
999
+ span_ms = acc * 10 # the --animate envelope spans the events, first to last
1000
+ for ev_cs, ev_len, j in events:
1001
+ w_start = start + ev_cs / 100.0
1002
+ w_end = start + (ev_cs + ev_len) / 100.0
1003
+ # colour/scale each real word by its rank against the active one (j); an
1004
+ # emoji-placeholder token is never active and just keeps its plain text
1005
+ styled, flat_pos = [], 0
1006
+ for lw in line_words:
1007
+ styled_line = []
1008
+ for w in lw:
1009
+ if not _karaoke_word(w):
1010
+ styled_line.append(w)
1011
+ else:
1012
+ rank = real_idx.index(flat_pos)
1013
+ if rank < j:
1014
+ styled_line.append(f"{{\\c{word_past}}}{w}")
1015
+ elif rank == j:
1016
+ # put back what the active word changed, not {\r}: a reset would
1017
+ # also drop the cue's own <i>/<b>/colour and a --fit-size \fs
1018
+ styled_line.append(
1019
+ f"{{\\c{word_active}\\fscx{word_scale}\\fscy{word_scale}\\bord{word_bord}}}{w}"
1020
+ f"{{\\fscx100\\fscy100\\bord{style_bord}}}")
1021
+ else:
1022
+ styled_line.append(f"{{\\c{word_upcoming}}}{w}")
1023
+ flat_pos += 1
1024
+ styled.append(" ".join(styled_line))
1025
+ out_body = "\\N".join(styled)
1026
+ if EMOJI_SENTINEL in out_body:
1027
+ out_body = out_body.replace(EMOJI_SENTINEL, emoji_placeholder(getattr(args, "_emoji_box_px", size), back_alpha))
1028
+ # the size/fit override (\fsN) belongs on every event; --animate is the cue's one
1029
+ # envelope, and each event takes the part of it that falls inside the event: the
1030
+ # fade-out at the cue's end, the slide and the pop carried on, not restarted (A57)
1031
+ event_fx = animate_fx(args.animate, ev_cs * 10, (ev_cs + ev_len) * 10, span_ms, anchor,
1032
+ int(30 * scale)) + size_fx
1033
+ lines.append(f"Dialogue: 0,{t(w_start)},{t(w_end)},Default,,0,0,0,,{event_fx}{out_body}")
1034
+ continue
1035
+ if args.karaoke:
1036
+ # split each line into words and give every word an equal share of the cue (\k is in centiseconds)
1037
+ segments = body.split("\\N")
1038
+ words = [w for seg in segments for w in seg.split(" ") if w and _karaoke_word(w)]
1039
+ lead, durs = _karaoke_word_durations(args, video, start, end, len(words))
1040
+ it = iter(durs)
1041
+ out_segments = []
1042
+ for seg in segments:
1043
+ ws = [w for w in seg.split(" ") if w]
1044
+ # An emoji placeholder is its own ZERO-duration \kf segment: the highlight sweeps
1045
+ # past the reserved gap without spending cue time on a glyph nobody sees (rendered
1046
+ # and confirmed -- libass keeps the full gap inside a karaoke run).
1047
+ out_segments.append(" ".join(
1048
+ ("{\\kf0}" + w) if not _karaoke_word(w) else f"{{\\kf{next(it)}}}{w}" for w in ws))
1049
+ body = "\\N".join(out_segments)
1050
+ if lead > 0:
1051
+ # the silence before the first word: an empty \k syllable, so the fill starts
1052
+ # with the speech and not at the cue's start (A59)
1053
+ body = "{\\k%d}" % lead + body
1054
+ if EMOJI_SENTINEL in body:
1055
+ body = body.replace(EMOJI_SENTINEL, emoji_placeholder(getattr(args, "_emoji_box_px", size), back_alpha))
1056
+ lines.append(f"Dialogue: 0,{t(start)},{t(end)},Default,,0,0,0,,{fx}{body}")
1057
+ with open(path, "w", encoding="utf-8-sig") as fh:
1058
+ fh.write("\n".join(header + lines) + "\n")
1059
+
1060
+
1061
+ # ------------------------------------------------------- multi-language subtitle tracks (1.16)
1062
+
1063
+ class AppendPath(argparse.Action):
1064
+ """`--srt` repeated, without changing what the contract says `--srt` is.
1065
+
1066
+ `action="append"` would make the derived JSON Schema an array (`_contract._json_type`), and the
1067
+ 1.x guarantee says no argument changes type -- an MCP client that sends `{"srt": "subs.srt"}`
1068
+ must keep working exactly as it did. Subclassing Action directly keeps the schema a plain
1069
+ string while the CLI collects every occurrence, so repeating the flag is purely additive.
1070
+ """
1071
+
1072
+ def __call__(self, parser, namespace, values, option_string=None):
1073
+ current = getattr(namespace, self.dest, None)
1074
+ if not isinstance(current, list):
1075
+ current = [] if current is None else [current]
1076
+ current.append(values)
1077
+ setattr(namespace, self.dest, current)
1078
+
1079
+
1080
+ # BCP-47-ish: a 2-3 letter primary subtag, optionally followed by script/region/variant subtags.
1081
+ LANG_TOKEN_RE = re.compile(r"^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$")
1082
+
1083
+ # The name a player lists a track under, when the caller gives no --track-title. Data, not a
1084
+ # translation: a code that is not in the table gets the code itself, never an invented name.
1085
+ LANG_TITLES = {
1086
+ "en": "English", "es": "Espanol", "pt": "Portugues", "fr": "Francais", "de": "Deutsch",
1087
+ "it": "Italiano", "nl": "Nederlands", "pl": "Polski", "ru": "\u0420\u0443\u0441\u0441\u043a\u0438\u0439",
1088
+ "ja": "\u65e5\u672c\u8a9e", "zh": "\u4e2d\u6587", "ko": "\ud55c\uad6d\uc5b4",
1089
+ "ar": "\u0627\u0644\u0639\u0631\u0628\u064a\u0629", "he": "\u05e2\u05d1\u05e8\u05d9\u05ea",
1090
+ "hi": "\u0939\u093f\u0928\u094d\u0926\u0940", "th": "\u0e44\u0e17\u0e22",
1091
+ "tr": "Turkce", "id": "Bahasa Indonesia", "vi": "Tieng Viet", "sv": "Svenska",
1092
+ "da": "Dansk", "no": "Norsk", "fi": "Suomi", "cs": "Cestina", "uk": "\u0423\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a\u0430",
1093
+ }
1094
+
1095
+ # MP4/MOV store the language in an ISO-639-2/T box and silently drop anything that is not three
1096
+ # letters -- verified against ffmpeg 6.1: `-metadata:s:s:0 language=en` on an .mp4 writes NO
1097
+ # language tag at all, while `language=eng` writes one ffprobe reads back. Matroska stores the
1098
+ # code verbatim, so `en` survives there. Only the codes this table knows are converted; an
1099
+ # unknown one is passed through with a note rather than guessed at.
1100
+ ISO639_1_TO_2 = {
1101
+ "en": "eng", "es": "spa", "pt": "por", "fr": "fra", "de": "deu", "it": "ita", "nl": "nld",
1102
+ "pl": "pol", "ru": "rus", "ja": "jpn", "zh": "zho", "ko": "kor", "ar": "ara", "he": "heb",
1103
+ "hi": "hin", "th": "tha", "tr": "tur", "id": "ind", "vi": "vie", "sv": "swe", "da": "dan",
1104
+ "no": "nor", "fi": "fin", "cs": "ces", "uk": "ukr", "el": "ell", "hu": "hun", "ro": "ron",
1105
+ "bg": "bul", "ca": "cat", "fa": "fas", "ta": "tam", "bn": "ben", "ms": "msa", "fil": "fil",
1106
+ }
1107
+
1108
+
1109
+ def split_srt_lang(token: str) -> Tuple[str, Optional[str]]:
1110
+ """`file.srt:ja` -> ("file.srt", "ja"); anything else -> (token, None).
1111
+
1112
+ The split is on the LAST colon and only when the suffix is BCP-47-shaped AND the whole token
1113
+ is not itself a readable file -- so `C:\\subs\\en.srt` (a Windows path) and a file genuinely
1114
+ named `a:b.srt` are never mangled.
1115
+ """
1116
+ token = str(token)
1117
+ if ":" not in token or os.path.exists(token):
1118
+ return token, None
1119
+ head, _, tail = token.rpartition(":")
1120
+ if head and LANG_TOKEN_RE.match(tail):
1121
+ return head, tail
1122
+ # A tail that is clearly meant as a language code but is not one is a language error, not a
1123
+ # file called `en.srt:zzzz`: only say "file not found" when the whole token could be a path.
1124
+ if head and tail and not os.path.exists(token) and os.path.exists(head) \
1125
+ and re.match(r"^[A-Za-z][A-Za-z0-9-]*$", tail):
1126
+ die(f"--srt {token}: '{tail}' is not a language code (two or three letters, optionally "
1127
+ "with a region, e.g. en, ja, pt-BR)", kind="input")
1128
+ return token, None
1129
+
1130
+
1131
+ def container_language(code: str, output: str) -> str:
1132
+ """The spelling of `code` this container actually stores (see ISO639_1_TO_2)."""
1133
+ ext = Path(output).suffix.lower()
1134
+ if ext not in (".mp4", ".m4v", ".mov"):
1135
+ return code
1136
+ primary = code.split("-")[0].lower()
1137
+ return ISO639_1_TO_2.get(primary, code)
1138
+
1139
+
1140
+ def track_title_for(code: Optional[str], given: Optional[str]) -> Optional[str]:
1141
+ if given:
1142
+ return given
1143
+ if not code:
1144
+ return None
1145
+ return LANG_TITLES.get(code.split("-")[0].lower(), code)
1146
+
1147
+
1148
+ # a timing line in the grammar ffmpeg's SRT demuxer and parse_srt() read alike: hours, minutes,
1149
+ # seconds and three-digit milliseconds on both sides (ffmpeg allows position fields after it)
1150
+ _SHARED_SRT_TIMING = re.compile(r"^\s*\d{2,}:\d{2}:\d{2}[,.]\d{3}\s*-->\s*\d{2,}:\d{2}:\d{2}[,.]\d{3}(\s.*)?$")
1151
+
1152
+
1153
+ def srt_timings_shared_grammar(path: str) -> bool:
1154
+ """True when every timing line of the SRT at `path` reads the same to ffmpeg's SRT demuxer as
1155
+ to parse_srt(). ffmpeg refuses `00:01,000` (no hours) and reads `00:00:01,5` as 1.005 s, where
1156
+ parse_srt() reads 1.5 s (#414); such a file is handed to ffmpeg as a rewritten copy."""
1157
+ # the timing lines parse_srt() reads, grouped as it groups them (srt_blocks()): a later line
1158
+ # that only holds "-->" is dialogue, not a timing this check should judge
1159
+ return all(_SHARED_SRT_TIMING.match(times) for times, _body in srt_blocks(read_text_or_die(path, "--srt")))
1160
+
1161
+
1162
+ def mux_subtitle_codec(output: str) -> str:
1163
+ ext = Path(output).suffix.lower()
1164
+ if ext in (".mp4", ".m4v", ".mov"):
1165
+ return "mov_text"
1166
+ if ext == ".mkv":
1167
+ return "srt"
1168
+ if ext == ".webm":
1169
+ return "webvtt"
1170
+ die(f"--mode mux: don't know a soft-subtitle codec for '{ext}' output "
1171
+ "(know .mp4/.m4v/.mov, .mkv, .webm) -- use --mode burn, or pick one of those containers with -o")
1172
+
1173
+
1174
+ def ass_color(hex_rgb: str, alpha: int = 0) -> str:
1175
+ h = hex_rgb.lstrip("#")
1176
+ if len(h) != 6 or any(c not in "0123456789abcdefABCDEF" for c in h):
1177
+ die(f"colour must be six hex digits RRGGBB, got '{hex_rgb}'")
1178
+ r, g, b = h[0:2], h[2:4], h[4:6]
1179
+ return f"&H{alpha:02X}{b}{g}{r}".upper()
1180
+
1181
+
1182
+ def ass_font_name(name: str) -> str:
1183
+ """Sanitise a font name for embedding in an ASS [V4+ Styles] Style line (comma-delimited
1184
+ fields, no quoting mechanism) and in a `force_style='...'` option list (comma-separated
1185
+ Key=Value pairs, colon-separated from the rest of the -vf filter). No real font name uses
1186
+ `, : \\ '`, so rather than chase a per-context escape (a Style line and a force_style list
1187
+ have different delimiter rules), those characters -- and control characters, which are never
1188
+ meaningful in a font name either -- are dropped outright, the same "no escape proven safe
1189
+ everywhere it's used" call this codebase already makes for escape_drawtext()'s `'`/`%`."""
1190
+ name = re.sub(r"[\x00-\x1f\x7f]", "", name)
1191
+ for ch in ",:\\'":
1192
+ name = name.replace(ch, "")
1193
+ return name
1194
+
1195
+
1196
+ def _glue_negative_offset(argv: List[str]) -> List[str]:
1197
+ """`--offset -0:00:02` reads as a flag to argparse, not a value: only bare negative NUMBERS
1198
+ are exempt from the "starts with -" rule, and a negative timecode is not one. Join the pair
1199
+ into `--offset=-0:00:02` so the documented grammar works in the shape people type it."""
1200
+ out: List[str] = []
1201
+ i = 0
1202
+ while i < len(argv):
1203
+ nxt = argv[i + 1] if i + 1 < len(argv) else ""
1204
+ if argv[i] == "--offset" and nxt.startswith("-") and not nxt.startswith("--"):
1205
+ out.append(f"--offset={nxt}")
1206
+ i += 2
1207
+ continue
1208
+ out.append(argv[i])
1209
+ i += 1
1210
+ return out
1211
+
1212
+
1213
+ def main() -> int:
1214
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1215
+ ap.add_argument("input", nargs="?", help="video to burn captions into (omit with --write-srt to only generate)")
1216
+ ap.add_argument("-o", "--output", help="output video (default: <name>_captioned.<ext>)")
1217
+ ap.add_argument("--mode", choices=["burn", "mux"], default="burn",
1218
+ help="'burn' renders subtitles into the picture (default); "
1219
+ "'mux' copies video/audio untouched and adds the SRT as a soft, toggleable subtitle stream")
1220
+ ap.add_argument("--audio-stream", type=int, default=0,
1221
+ help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "
1222
+ "audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "
1223
+ "the first track, same as leaving it unset always did")
1224
+ src = ap.add_argument_group("subtitle source")
1225
+ src.add_argument("--srt", action=AppendPath, metavar="FILE[:LANG]",
1226
+ help="SRT to burn or (with --mode mux) add as a subtitle track. Repeat FILE:LANG per language "
1227
+ "for muxing. A single untagged file uses --language. Prefer .mkv for multiple tracks.")
1228
+ src.add_argument("--ass", help="ASS file to burn (styles inside the file are used)")
1229
+ src.add_argument("--text", help="plain text cue file to convert into SRT (see format above)")
1230
+ src.add_argument("--transcribe", action="store_true", help="generate the SRT from the audio with a local speech-to-text engine if one is installed (parakeet-mlx / parakeet.cpp / whisper-cli / whisper / faster-whisper); never required")
1231
+ src.add_argument("--language", "--lang", help="language code (e.g. en, ja, zh, ko): the language for --transcribe (default auto), "
1232
+ "the tag on the subtitle stream with --mode mux, and the hint that says whether Han-only "
1233
+ "text is Chinese, Japanese or Korean when a font is picked by script")
1234
+ src.add_argument("--track-title", action=AppendPath, metavar="TITLE",
1235
+ help="--mode mux: the name a player lists a track under, repeated in the same order as --srt "
1236
+ "(default: the language's display name from a frozen table, else the code itself -- the "
1237
+ "table is data, never a guessed or translated name)")
1238
+ src.add_argument("--default-track", metavar="LANG",
1239
+ help="--mode mux: mark this language's track `default` so a player selects it by itself "
1240
+ "(default: none, so no player burns in a language the viewer did not ask for)")
1241
+ src.add_argument("--offset", default="0", help="shift every cue by TIME (seconds, mm:ss, hh:mm:ss.ms or "
1242
+ "hh:mm:ss:ff; a leading - shifts earlier); works for --text, --srt and --ass")
1243
+ src.add_argument("--model", default=None,
1244
+ help="speech model for --transcribe: a whisper model name/path (default: $FFMPEG_SKILL_ASR_MODEL, "
1245
+ "else base), or a Parakeet model (an mlx-community/parakeet-* repo or a .gguf) for the "
1246
+ "Parakeet engines")
1247
+ src.add_argument("--engine", choices=ENGINE_CHOICES, default=None,
1248
+ help="speech engine for --transcribe (default: $FFMPEG_SKILL_ASR_ENGINE, else auto = Parakeet "
1249
+ "for English speech when installed, else whisper.cpp / faster-whisper / openai-whisper)")
1250
+ src.add_argument("--write-srt", help="where to save the generated SRT (default: <text>.srt)")
1251
+ src.add_argument("--auto-seconds", type=float, default=3.0, help="duration for cues without timing (default 3)")
1252
+ src.add_argument("--gap", type=float, default=0.0, help="gap after auto-timed cues in seconds")
1253
+ src.add_argument("--fps", type=float, default=None,
1254
+ help="frame rate for SMPTE cues in --text (hh:mm:ss:ff or hh:mm:ss;ff at 29.97 or 59.94); "
1255
+ "defaults to the input video's own fps when --input is given, required otherwise")
1256
+ sty = ap.add_argument_group("style (SRT only)")
1257
+ sty.add_argument("--brand", help="brand.json: font, colours, caption size/position/animation defaults")
1258
+ sty.add_argument("--font", default=None, help="font family, e.g. 'Noto Sans CJK JP' for Japanese (default DejaVu Sans or brand font)")
1259
+ sty.add_argument("--fonts-dir", help="directory with extra .ttf/.otf files")
1260
+ sty.add_argument("--font-size", "--size", dest="size", type=int, default=None, help="font size in ASS points (relative to a 288p script height, scales automatically)")
1261
+ sty.add_argument("--color", default=None, help="text colour RRGGBB (default FFFFFF or brand text colour)")
1262
+ sty.add_argument("--outline-color", default=None, help="outline colour RRGGBB")
1263
+ sty.add_argument("--outline", type=float, default=None, help="outline width (default 2)")
1264
+ sty.add_argument("--shadow", type=float, default=0.0, help="shadow depth (default 0)")
1265
+ sty.add_argument("--bold", action="store_true", help="bold caption text")
1266
+ sty.add_argument("--position", choices=sorted(ALIGN), default=None, help="on-screen placement (default bottom)")
1267
+ sty.add_argument("--margin", type=int, default=None, help="vertical margin from the edge in ASS units (default 30, or the --platform safe zone)")
1268
+ sty.add_argument("--platform", choices=PLATFORM_CHOICES, default=None,
1269
+ help="keep the captions out of this destination's UI: the margin becomes the platform's safe "
1270
+ "zone (TikTok's description bar, the Reels/Shorts chrome). An explicit --margin/--position wins")
1271
+ sty.add_argument("--box", action="store_true", help="draw an opaque box behind text instead of an outline")
1272
+ emo = ap.add_argument_group("emoji (1.15)")
1273
+ emo.add_argument("--emoji", choices=["auto", "color", "png", "mono", "none"], default="auto",
1274
+ help="how emoji in the cues are drawn: 'auto' picks the best this machine can do "
1275
+ "(doctor --json .fonts.emoji), 'color' insists on a colour-capable libass, "
1276
+ "'png' composites the --emoji-assets PNGs, 'mono' draws whatever glyph the text "
1277
+ "font has, 'none' strips them")
1278
+ emo.add_argument("--emoji-assets", metavar="DIR",
1279
+ help="directory of emoji PNGs named by code point (1f389.png, 1f1ef-1f1f5.png) -- "
1280
+ "Twemoji's assets/72x72 or Noto Emoji's png/128. Nothing is ever downloaded; "
1281
+ "also read from brand.json styles.caption.emoji_assets and FFMPEG_SKILL_EMOJI_ASSETS")
1282
+ emo.add_argument("--emoji-scale", type=float, default=1.0,
1283
+ help="emoji box as a multiple of the line's font size (default 1.0)")
1284
+ emo.add_argument("--emoji-max", type=int, default=60,
1285
+ help="most emoji overlays one run may build (default 60)")
1286
+ sty.add_argument("--max-lines", type=int, default=2, help="most lines one cue may occupy; a longer cue is split into consecutive cues (default 2)")
1287
+ sty.add_argument("--fit-size", choices=["auto", "on", "off"], default="auto",
1288
+ help="shrink the caption size until the cue fits --max-lines, BEFORE splitting it: "
1289
+ "'auto' (default) only when no --size was given, 'on' always, 'off' keeps --size and splits the cue instead")
1290
+ sty.add_argument("--min-size", type=int, default=None,
1291
+ help="smallest size --fit-size may use, in ASS points (default 13 = 4.5%% of the frame height, "
1292
+ "the legibility floor)")
1293
+ sty.add_argument("--fit-size-scope", choices=["file", "cue"], default="file",
1294
+ help="one fitted size for the whole file (default) or one per cue (a size that changes "
1295
+ "cue to cue reads as a mistake, so it is opt-in)")
1296
+ sty.add_argument("--min-duration", type=float, default=1.0, help="shortest time a cue stays on screen in seconds, never past the next cue (default 1.0)")
1297
+ sty.add_argument("--wrap", choices=list(WRAP_MODES), default="phrase",
1298
+ help="line breaking for wide cues: phrase-aware (phrase, default) or width-only (measured). "
1299
+ "Both preserve text, timing and line count.")
1300
+ anim = ap.add_argument_group("animation (generates ASS; needs --text or --srt input)")
1301
+ anim.add_argument("--animate", choices=["none", "fade", "pop", "slide"], default=None, help="per-cue entrance animation (default none, or brand caption.animate)")
1302
+ anim.add_argument("--karaoke", action="store_true", help="word-by-word highlight (fills from --color to --highlight-color across each cue)")
1303
+ anim.add_argument("--karaoke-style", choices=["sweep", "word"], default="sweep",
1304
+ help="'sweep' (default): today's \\kf colour fill, one Dialogue event per cue -- unchanged. "
1305
+ "'word': one Dialogue event per word, the active word scaled by --karaoke-scale and "
1306
+ "emboldened, past words in --color, upcoming words in --upcoming-color -- \\k/\\kf can only "
1307
+ "interpolate colour, so this is the only way to also scale/embolden the active word")
1308
+ anim.add_argument("--highlight-color", default=None, help="karaoke fill/active-word colour RRGGBB (default FFD200 or brand primary)")
1309
+ anim.add_argument("--upcoming-color", default=None,
1310
+ help="--karaoke-style word: colour RRGGBB for words not yet spoken (default B4B4B4)")
1311
+ anim.add_argument("--karaoke-scale", type=float, default=112.0,
1312
+ help="--karaoke-style word: the active word's size as a percentage of the caption size (default 112)")
1313
+ anim.add_argument("--karaoke-timing", choices=["even", "energy"], default="energy",
1314
+ help="how words are timed inside a cue: 'energy' follows the speech loudness in the audio (default), 'even' splits time equally")
1315
+ anim.add_argument("--write-ass", help="where to save the generated ASS (default: next to the output)")
1316
+ enc = ap.add_argument_group("encoding")
1317
+ enc.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
1318
+ enc.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
1319
+ add_common(ap)
1320
+ args = ap.parse_args(_glue_negative_offset(sys.argv[1:]))
1321
+ apply_common(args)
1322
+
1323
+ brand = load_brand(args.brand)
1324
+ bc, bcap = brand["colors"], brand_caption_style(brand)
1325
+ # A brand file that never names a font is not an explicit font: BRAND_DEFAULTS always
1326
+ # supplies one, so asking the merged document would turn font-by-script off for every job
1327
+ # that passes --brand at all.
1328
+ font_explicit = bool(args.font) or bool(args.brand and brand_states_font(brand))
1329
+ args.language = args.language or (brand.get("lang") if args.brand else None)
1330
+ if args.brand and bcap.get("box") and not args.box:
1331
+ args.box = True
1332
+ args.font = args.font or (bcap.get("font") if args.brand else None) or brand.get("font") or "DejaVu Sans"
1333
+ # --fit-size auto shrinks only a size the skill itself chose. An explicit --size is a
1334
+ # statement about the look and is never quietly overridden; a brand's caption size is the
1335
+ # same kind of statement, so it counts as explicit too.
1336
+ args._size_explicit = args.size is not None or bool(args.brand and bcap.get("size") is not None)
1337
+ args.size = args.size if args.size is not None else (bcap.get("size", 24) if args.brand else 24)
1338
+ args.color = color_hex(args.color or (bcap.get("color") if args.brand else None) or bc.get("text", "FFFFFF"))
1339
+ args.outline_color = color_hex(args.outline_color or bc.get("outline", "000000"))
1340
+ args.outline = args.outline if args.outline is not None else (float(bcap.get("outline", 2)) if args.brand else 2.0)
1341
+ args.position = args.position or (bcap.get("position", "bottom") if args.brand else "bottom")
1342
+ # --platform: the margin is the fraction of the frame that platform's own UI covers
1343
+ # (scripts/_platforms.py). An explicit --margin is the more specific statement and wins;
1344
+ # without either, the historical default 30 is unchanged.
1345
+ # every tool resolves the spellings people write ('youtube-shorts' is 'shorts') in one place
1346
+ args.platform = resolve_platform(args.platform)
1347
+ if args.margin is None and args.platform and PLATFORMS[args.platform].get("frame"):
1348
+ edge = PLATFORMS[args.platform]["safe"]["top" if args.position.startswith("top") else "bottom"]
1349
+ args.margin = ass_units(edge)
1350
+ info(f"--platform {args.platform}: caption margin {args.margin} ASS units ({edge * 100:.0f}% of the frame height, "
1351
+ f"clear of the app's own UI)")
1352
+ if args.margin is None:
1353
+ args.margin = 30
1354
+ if args.ass and (args.animate not in (None, "none") or args.karaoke):
1355
+ # A74: both are drawn by the ASS this tool writes from cues; a caller's own --ass is burned
1356
+ # as it stands, so the flag was accepted and nothing moved (a brand's caption.animate or
1357
+ # caption.karaoke is a default for generated captions and is not a request here)
1358
+ asked = "--animate " + args.animate if args.animate not in (None, "none") else "--karaoke"
1359
+ die(f"{asked} is drawn by the ASS this tool generates from --srt, --text or --transcribe; --ass burns "
1360
+ "the file as it is, with the animation and karaoke its own tags give it",
1361
+ hint=f"drop {asked.split()[0]}, or pass the cues as --srt/--text and let this tool write the ASS")
1362
+ # a brand's caption.animate is a burn-in default; over --mode mux (soft subtitles) it used
1363
+ # to be applied anyway and then refused as "animation is burn only" -- ignore it there
1364
+ args.animate = args.animate or (bcap.get("animate", "none") if args.brand and args.mode != "mux" else "none")
1365
+ args.highlight_color = color_hex(args.highlight_color or bc.get("primary", "FFD200"))
1366
+ args.upcoming_color = color_hex(args.upcoming_color or bc.get("upcoming", "B4B4B4"))
1367
+ if args.karaoke_scale <= 0:
1368
+ die("--karaoke-scale must be positive")
1369
+ if args.brand and bcap.get("bold") and not args.bold:
1370
+ args.bold = True
1371
+ if args.brand and bcap.get("karaoke") and not args.karaoke:
1372
+ args.karaoke = True
1373
+ if args.brand and brand.get("font_file") and not args.fonts_dir:
1374
+ # the brand's face is found in its directory by libass, so a file there that is no font
1375
+ # left libass to another face without a word (#510); a soft track (--mode mux) draws nothing,
1376
+ # and nor does a run with no input video, which only writes the SRT (review of #532)
1377
+ if args.mode != "mux" and args.input:
1378
+ require_font_file(brand["font_file"], "the --brand file's font_file")
1379
+ args.fonts_dir = str(Path(brand["font_file"]).parent)
1380
+ if not (args.srt or args.ass or args.text or args.transcribe):
1381
+ die("give one of --srt, --ass, --text or --transcribe")
1382
+ if args.mode == "mux":
1383
+ if args.ass:
1384
+ die("--mode mux takes --srt (or --text/--transcribe), not --ass -- "
1385
+ "ASS carries burn-only styling with no soft-subtitle equivalent; use --mode burn for an ASS file")
1386
+ if args.animate != "none" or args.karaoke:
1387
+ die("--animate/--karaoke render pixels into the picture and require --mode burn")
1388
+ if args.max_lines != 2 or args.wrap != "phrase":
1389
+ # A55: a soft track is wrapped by the player at the size it draws; this run does not wrap
1390
+ # or split it, so a layout flag would be accepted and do nothing
1391
+ asked = f"--max-lines {args.max_lines}" if args.max_lines != 2 else f"--wrap {args.wrap}"
1392
+ die(f"{asked} lays out burned captions; --mode mux adds the cues as they are and the player wraps "
1393
+ "a soft subtitle at the size it draws it", kind="input",
1394
+ hint=f"drop {asked.split()[0]}, or use --mode burn")
1395
+
1396
+ args.offset = signed_time_arg(str(args.offset), "--offset")
1397
+ if args.max_lines < 1:
1398
+ die("--max-lines must be at least 1")
1399
+ if args.min_size is not None and args.min_size < 1:
1400
+ die("--min-size must be at least 1", kind="input")
1401
+ if args.min_size is not None and args.min_size > args.size:
1402
+ die(f"--min-size {args.min_size} is larger than --size {args.size}: the floor cannot be "
1403
+ "above the size it is a floor for", kind="input")
1404
+ if args.min_duration < 0:
1405
+ die("--min-duration cannot be negative")
1406
+ if args.gap < 0:
1407
+ # A72: each auto-timed cue started before the one above it ended, and the first start
1408
+ # below 0 was clamped: the cues overlapped on screen
1409
+ die(f"--gap must be 0 or more seconds, got {args.gap:g}")
1410
+
1411
+ meta = None
1412
+ if args.input:
1413
+ meta = probe(args.input)
1414
+ if not meta.get("video"):
1415
+ die("input has no video stream")
1416
+ audio_streams = meta.get("audio_streams") or []
1417
+ if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):
1418
+ die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")
1419
+ if args.audio_stream and not audio_streams:
1420
+ die("--audio-stream needs an input with audio streams")
1421
+ if args.transcribe and not audio_streams:
1422
+ # refused before any engine runs, as silence.py refuses it, not an unclassified
1423
+ # "Stream map '0:a:0' matches no streams" from the WAV extraction (#414)
1424
+ die(f"--transcribe needs speech to transcribe, and {args.input} has no audio stream",
1425
+ kind="input", hint="pick the file that carries the sound, or write the cues with --text")
1426
+ if args.mode != "mux":
1427
+ # before any transcription or sidecar: a build without libass fails these at parse time
1428
+ # with a message that names no filter (#393), so ask the build first, dry run included
1429
+ require_filter("ass" if (args.ass or args.animate != "none" or args.karaoke) else "subtitles", "burning captions")
1430
+ fps_for_tc = args.fps
1431
+ if fps_for_tc is None and meta is not None:
1432
+ fps_for_tc = meta.get("video", {}).get("fps")
1433
+
1434
+ play_w = play_h = None
1435
+ if meta and meta.get("video"):
1436
+ # the displayed frame: rotation applied, non-square pixels squared (#411) -- the burn
1437
+ # below draws on the square-pixel picture, so a cue is not stretched by the player's SAR
1438
+ play_w, play_h = display_size(meta["video"])
1439
+ # A --plan or --dry-run written before the input exists has no geometry to fit against, and a
1440
+ # plan that describes a different FontSize from the run that executes it is not a plan. When
1441
+ # --platform names a destination, that destination's frame IS the geometry the real run will
1442
+ # have, so the fit is computed against it; with no platform there is nothing to stand in for
1443
+ # the frame, and size_used is reported as null rather than presenting the requested size as
1444
+ # the size that was used.
1445
+ planned_frame = False
1446
+ if not (play_w and play_h) and args.platform and PLATFORMS[args.platform].get("frame"):
1447
+ frame = PLATFORMS[args.platform]["frame"]
1448
+ play_w, play_h = frame["w"], frame["h"]
1449
+ planned_frame = True
1450
+ info(f"[plan] no geometry to measure yet; fitting the caption size against the "
1451
+ f"--platform {args.platform} frame ({play_w}x{play_h})")
1452
+
1453
+ args._fit_floor = args.min_size if args.min_size is not None else ass_units(MIN_CAPTION_FRACTION)
1454
+ fit_unmeasurable = not (play_w and play_h)
1455
+ fit_stats: dict = {"fit_size": args.fit_size, "size_requested": args.size,
1456
+ # A76: null until a fit (or a stated size) decides it; a --transcribe
1457
+ # dry run has no cues, so nothing is fitted and nothing is claimed
1458
+ "size_used": args.size if (args.fit_size == "off" or (args.fit_size == "auto" and args._size_explicit)) else None,
1459
+ "size_floor": args._fit_floor,
1460
+ "size_pct_height": round(args.size * 100.0 / ASS_SCRIPT_HEIGHT, 2),
1461
+ "shrunk": 0, "fit_scope": args.fit_size_scope, "fit_exhausted": False}
1462
+ caption_stats: dict = {"shifted": 0, "wrapped": 0, "split": 0, "extended": 0, "dropped": 0,
1463
+ "rebalanced": 0, "wrap": args.wrap, "phrase_breaks": 0}
1464
+ caption_stats.update(fit_stats)
1465
+
1466
+ def fit_params():
1467
+ return dict(size=fit_stats["size_requested"], min_size=args._fit_floor,
1468
+ max_lines=args.max_lines, play_w=play_w, play_h=play_h,
1469
+ mode=args.wrap, lang=args.language, scope=args.fit_size_scope,
1470
+ safe_fraction=line_fraction(args, play_w))
1471
+
1472
+ def fit_the_size(cue_list):
1473
+ """Shrink --size until every cue fits --max-lines, BEFORE the cue is split.
1474
+
1475
+ This is the whole point of the ordering: at a size the cue cannot fit, layout_cues splits
1476
+ the sentence into consecutive cues and half of it arrives late (eval 17). The text is never
1477
+ touched -- only the type size, and never below the legibility floor.
1478
+ """
1479
+ if args.fit_size == "off" or (args.fit_size == "auto" and args._size_explicit):
1480
+ fit_stats["size_used"] = args.size # a stated size IS the size used
1481
+ return
1482
+ if fit_unmeasurable:
1483
+ # Nothing to measure against: size_used stays null rather than presenting the
1484
+ # requested size as one that was fitted.
1485
+ return
1486
+ if args.mode == "mux":
1487
+ # Soft subtitles carry no size: the player picks it. Shrinking would change nothing a
1488
+ # viewer sees and would silently change the SRT this run writes, so the mux path is
1489
+ # left exactly as 1.16 wrote it.
1490
+ return
1491
+ fit = fit_size([(s, e, strip_srt_markup(t)) for s, e, t in cue_list], **fit_params())
1492
+ fit_stats["size_used"] = fit["size"]
1493
+ fit_stats["size_source"] = "platform-frame" if planned_frame else "input"
1494
+ fit_stats["shrunk"] = fit["shrunk"]
1495
+ fit_stats["fit_exhausted"] = bool(fit["shrunk"]) and not fit["fits"]
1496
+ fit_stats["size_pct_height"] = round(fit["size"] * 100.0 / ASS_SCRIPT_HEIGHT, 2)
1497
+ if fit["size"] != args.size:
1498
+ info(f"caption size {args.size} -> {fit['size']} ASS units "
1499
+ f"({fit_stats['size_pct_height']:.1f} % of frame height) so {fit['shrunk']} cue(s) "
1500
+ f"fit --max-lines {args.max_lines}; floor {args._fit_floor}")
1501
+ args.size = fit["size"]
1502
+ elif fit_stats["fit_exhausted"]:
1503
+ info(f"caption size stays {args.size} ASS units: {fit['shrunk']} cue(s) still need more "
1504
+ f"than {args.max_lines} line(s) at the floor {args._fit_floor} and are split "
1505
+ "(--min-size goes smaller; `|` sets the break yourself)")
1506
+ if args.fit_size_scope == "cue":
1507
+ # Each cue is laid out at ITS OWN size, not at the file minimum. A cue drawn larger
1508
+ # has a NARROWER line in em, so wrapping everything to the minimum size's (widest)
1509
+ # budget and then drawing some cues large put lines off the side of the frame.
1510
+ args._fit_cue_em = [line_em_for_size(fit["per_cue"].get(i, fit["size"]),
1511
+ play_w, play_h,
1512
+ safe_fraction=line_fraction(args, play_w))
1513
+ for i in range(len(cue_list))]
1514
+ args._fit_cue_size = [fit["per_cue"].get(i, fit["size"]) for i in range(len(cue_list))]
1515
+
1516
+ def lay_out(cue_list):
1517
+ """Wrap to the safe area, split past --max-lines, lengthen to --min-duration, shift by
1518
+ --offset -- the one place every cue source goes through, so an SRT, a cue file and a
1519
+ transcript all come out equally readable."""
1520
+ fit_the_size(cue_list)
1521
+ # A55 (#457): a soft subtitle is laid out by the player, at a size this run does not
1522
+ # know; wrapping it at the burn-in size split a cue on a portrait video into three
1523
+ out, stats = layout_cues(cue_list, max_em=None if args.mode == "mux" else max_line_em(args, play_w, play_h),
1524
+ max_lines=args.max_lines, min_duration=args.min_duration,
1525
+ offset=args.offset, wrap=args.wrap, lang=args.language,
1526
+ per_cue_em=getattr(args, "_fit_cue_em", None),
1527
+ per_cue_size=getattr(args, "_fit_cue_size", None))
1528
+ # which size each OUTPUT cue belongs to, after splits have renumbered them
1529
+ args._fit_sizes_out = stats.pop("cue_sizes", None)
1530
+ report_layout(stats)
1531
+ caption_stats.clear()
1532
+ caption_stats.update(stats)
1533
+ caption_stats.update(fit_stats)
1534
+ return out, any(v for k, v in stats.items() if k != "wrap")
1535
+
1536
+ # --srt is repeatable since 1.16 (one per language, each with an optional `:lang` suffix).
1537
+ # Every path below that burns, adjusts or transcribes works on the FIRST one, which is what
1538
+ # `--srt x.srt` has always meant; the extra tracks only exist for --mode mux.
1539
+ srt_tracks: List[Tuple[str, Optional[str]]] = []
1540
+ for token in (args.srt or []):
1541
+ path_part, lang_part = split_srt_lang(token)
1542
+ srt_tracks.append((path_part, lang_part))
1543
+ # --language tags the track only where there is a track to tag (A71, #457): a burn reads it as
1544
+ # the script and wrap hint, and refusing it as an --srt suffix named a flag nobody had given
1545
+ tagged_by_language = False
1546
+ if args.mode == "mux" and len(srt_tracks) == 1 and srt_tracks[0][1] is None and args.language:
1547
+ srt_tracks[0] = (srt_tracks[0][0], args.language)
1548
+ tagged_by_language = True
1549
+ if args.mode == "mux" and args.language and not srt_tracks and not LANG_TOKEN_RE.match(args.language):
1550
+ # the --text/--transcribe track is tagged with it too, and was tagged unchecked
1551
+ die(f"--language: '{args.language}' is not a language code (two or three letters, optionally with a "
1552
+ "region, e.g. en, ja, pt-BR)", kind="input")
1553
+ if srt_tracks and args.mode != "mux" and len(srt_tracks) > 1:
1554
+ die("burning renders pixels; only one language can be in the picture -- burn one and mux "
1555
+ "the rest (caption.py OUT --mode mux --srt en.srt:en --srt ja.srt:ja)", kind="input")
1556
+ seen_langs = [lang for _p, lang in srt_tracks if lang]
1557
+ for lang in seen_langs:
1558
+ if not LANG_TOKEN_RE.match(lang):
1559
+ die(f"{'--language' if tagged_by_language else '--srt'}: '{lang}' is not a language code (two or "
1560
+ "three letters, optionally with a "
1561
+ "region, e.g. en, ja, pt-BR)", kind="input")
1562
+ if len(set(seen_langs)) != len(seen_langs):
1563
+ dup = sorted({l for l in seen_langs if seen_langs.count(l) > 1})
1564
+ die(f"--srt: two tracks tagged '{', '.join(dup)}' -- a player cannot tell them apart; give "
1565
+ "each track its own code (and --track-title to name them)", kind="input")
1566
+ if args.track_title and len(args.track_title) > max(1, len(srt_tracks)):
1567
+ die(f"--track-title given {len(args.track_title)} times for {len(srt_tracks)} --srt file(s)",
1568
+ kind="input")
1569
+ args.srt = srt_tracks[0][0] if srt_tracks else None
1570
+ # 2.2.1: the extra --srt tracks (always inputs; the first may be written by --text or
1571
+ # --transcribe) are checked up front, every missing one named together, before any work.
1572
+ # Dry-run plans on files earlier steps have not written yet, as join.py does.
1573
+ missing_srt = [{"index": i, "path": p, "reason": "missing"}
1574
+ for i, (p, _l) in enumerate(srt_tracks) if i > 0 and not os.path.exists(p)]
1575
+ if missing_srt and not STATE.dry_run:
1576
+ die(f"{len(missing_srt)} SRT file(s) not found: " + ", ".join(m["path"] for m in missing_srt),
1577
+ kind="input", problems=missing_srt)
1578
+ if args.offset and args.mode == "mux":
1579
+ # --offset shifts every --srt track (A61); one it would leave with no cue is refused here,
1580
+ # before the first file of this run is written (the first track's empty copy used to reach
1581
+ # ffmpeg, which failed on it as kind ffmpeg and left the copy behind)
1582
+ for p, _l in srt_tracks:
1583
+ if os.path.exists(p) and not any(e + args.offset > 0 for _s, e, _t in parse_srt(p)):
1584
+ die(f"--offset {args.offset:+g} moves every cue of {p} before 0: the track would be empty",
1585
+ kind="input")
1586
+ srt_path = args.srt
1587
+ if args.transcribe and not args.input:
1588
+ die("--transcribe needs the input video")
1589
+ # 2.2.4: every file this run writes -- the video AND the .srt/.ass sidecars -- is checked
1590
+ # against --overwrite here, before speech recognition and before the first write, dry runs
1591
+ # included. Through 2.2.3 only ffmpeg's last argument was: a hand-corrected transcript or ASS
1592
+ # next to the output was replaced on a re-run, even one ffmpeg's check then refused.
1593
+ # Side files whose existence depends on the cues (an _adjusted.srt, an emoji-forced ASS) are
1594
+ # checked again where they are written, still before that write.
1595
+ claimed: Dict[str, str] = {} # real path -> which artifact of this run holds it
1596
+
1597
+ def claim(items) -> None:
1598
+ """Reserve (path, artifact) pairs: the same artifact claiming its path again is a no-op,
1599
+ another artifact of this run claiming it is refused (#413 review: --write-srt and
1600
+ --write-ass naming one file, the SRT then replaced by the ASS)."""
1601
+ todo = []
1602
+ for path, owner in items:
1603
+ if not path:
1604
+ continue
1605
+ real = os.path.realpath(path)
1606
+ held = claimed.get(real)
1607
+ if held is None and os.path.exists(real):
1608
+ # a second name for the same file (a hard link) is the same path (#413 review)
1609
+ held = next((o for r, o in claimed.items()
1610
+ if os.path.exists(r) and os.path.samefile(r, real)), None)
1611
+ if held is None:
1612
+ claimed[real] = owner
1613
+ todo.append(path)
1614
+ elif held != owner:
1615
+ refuse("input", "output_path_taken",
1616
+ f"{path!r} is named for both the {held} and the {owner} this run writes; give each its own path",
1617
+ output=path, other=held)
1618
+ refuse_existing_outputs(todo)
1619
+ # and the rest of the side-file guards (#408): never an input, the video, a missing
1620
+ # directory or an option-shaped name, even under --overwrite
1621
+ # a brand file's font_file and logo are read too (review of #534's sweep: --write-srt or
1622
+ # --write-ass naming the brand's font replaced it)
1623
+ side_inputs = [q for q in (args.input, getattr(args, "text", None), getattr(args, "ass", None),
1624
+ getattr(args, "brand", None), brand.get("font_file"), brand.get("logo"),
1625
+ *(t[0] for t in srt_tracks)) if isinstance(q, str) and q]
1626
+ for path in todo:
1627
+ guard_sidecar(path, *side_inputs)
1628
+
1629
+ planned_out = args.output or (default_output(args.input, "captioned") if args.input else None)
1630
+ up_front: List[Tuple[str, str]] = []
1631
+ if args.transcribe:
1632
+ up_front.append((args.write_srt or os.path.splitext(planned_out)[0] + ".srt", "SRT"))
1633
+ elif args.text:
1634
+ up_front.append((args.write_srt or (os.path.splitext(planned_out)[0] + ".srt" if args.input
1635
+ else os.path.splitext(args.text)[0] + ".srt"), "SRT"))
1636
+ if args.input:
1637
+ if (args.animate != "none" or args.karaoke) and not args.ass:
1638
+ up_front.append((args.write_ass or os.path.splitext(planned_out)[0] + ".ass", "ASS"))
1639
+ if args.ass and args.offset and os.path.exists(args.ass):
1640
+ up_front.append((os.path.splitext(planned_out)[0] + "_offset.ass", "offset ASS"))
1641
+ # -o naming the input (the same name, a hard link, another case on a case-insensitive
1642
+ # volume) is refused here, before any sidecar or transcript is written: run()'s own guard
1643
+ # came after the .srt was already beside it (review of #530)
1644
+ if same_file(planned_out, args.input):
1645
+ refuse_output_is_input(planned_out, args.input, why="the captioned video would replace the source")
1646
+ up_front.append((planned_out, "video"))
1647
+ claim(up_front)
1648
+ if args.transcribe:
1649
+ # the sidecar goes next to the output like the --text one, not into the source folder
1650
+ # where it silently replaced a hand-written <input>.srt (review 5)
1651
+ srt_path = args.write_srt or os.path.splitext(args.output or default_output(args.input, "captioned"))[0] + ".srt"
1652
+ if STATE.dry_run:
1653
+ cues = []
1654
+ info(f"[dry-run] would transcribe {args.input} and write {srt_path}")
1655
+ else:
1656
+ # the call's own result, not module state: engine, routing and words belong to this run
1657
+ asr_run = _asr.transcribe_result(args.input, srt_path, args.language, args.model, args.audio_stream,
1658
+ engine=args.engine)
1659
+ cues = asr_run.cues
1660
+ args._asr = dict(asr_run.facts)
1661
+ args._word_timings = shift_words(whisper_word_timings(srt_path) or sorted(
1662
+ (w["start"], w["end"], w["word"]) for w in asr_run.words), args.offset)
1663
+ cues, changed = lay_out(cues)
1664
+ if changed:
1665
+ write_srt(cues, srt_path)
1666
+ info(f"wrote {srt_path} ({len(cues)} cues)")
1667
+ args.text = None
1668
+ if args.text:
1669
+ video_clock = (meta or {}).get("video") or {}
1670
+ cues = parse_text_cues(args.text, args.auto_seconds, args.gap, fps_for_tc,
1671
+ source_fps=video_clock.get("fps"),
1672
+ source_vfr=bool(video_clock.get("variable_frame_rate_suspected")))
1673
+ cues, _ = lay_out(cues)
1674
+ if not cues:
1675
+ # --offset dropped every cue (one that ends at or before 0 goes): an empty SRT was
1676
+ # written, and with a frame rate known the report below indexed the empty list
1677
+ die(f"--offset {args.offset:+g} moves every cue of {args.text} before 0: no cue would be left",
1678
+ kind="input")
1679
+ if args.write_srt:
1680
+ srt_path = args.write_srt
1681
+ elif args.input:
1682
+ # keep generated files next to the output, not in the user's source folder
1683
+ out_guess = args.output or default_output(args.input, "captioned")
1684
+ srt_path = os.path.splitext(out_guess)[0] + ".srt"
1685
+ else:
1686
+ srt_path = os.path.splitext(args.text)[0] + ".srt"
1687
+ if not STATE.dry_run:
1688
+ write_srt(cues, srt_path)
1689
+ tc_range = f", {fmt_smpte_time(cues[0][0], fps_for_tc)}-{fmt_smpte_time(cues[-1][1], fps_for_tc)} @ {fps_for_tc:g}fps" if fps_for_tc else ""
1690
+ info(f"wrote {srt_path} ({len(cues)} cues{tc_range})")
1691
+ if not args.input:
1692
+ print(srt_path)
1693
+ return 0
1694
+
1695
+ if not args.input:
1696
+ die("input video is required unless you only use --text/--write-srt")
1697
+
1698
+ output = args.output or default_output(args.input, "captioned")
1699
+
1700
+ # An SRT or ASS the caller wrote is never edited in place: when --offset/--max-lines/
1701
+ # --min-duration change it, the adjusted copy is written next to the output and burned instead.
1702
+ # The path is repointed in BOTH modes: --dry-run/--plan must describe the job the real run
1703
+ # executes, so the planned command names the adjusted copy the real run burns. Only the
1704
+ # WRITING waits for a real run (the rule every side file in this tool follows), which is why
1705
+ # the cues are kept in hand below for the font sample and the ASS generator.
1706
+ planned_cues: Optional[List[Tuple[float, float, str]]] = None
1707
+ side_notes: List[str] = []
1708
+ ass_counts: dict = {} # --ass: ass_shifted / ass_unshifted (with --offset) and ass_malformed, into `caption`
1709
+ ass_sample_path = args.ass
1710
+ normalised_only = False # srt_path is a copy of the caller's SRT that only rewrites its timings
1711
+ if args.srt and not (args.text or args.transcribe) and os.path.exists(srt_path or ""):
1712
+ adjusted, changed = lay_out(parse_srt(srt_path))
1713
+ # ffmpeg's own SRT reader takes a narrower grammar than parse_srt(): a time without hours
1714
+ # is refused and ",5" is read as 5 ms where this tool reads 500. A file outside the grammar
1715
+ # both share goes to ffmpeg as the copy this tool writes, so it gets the cues counted
1716
+ # here (#414)
1717
+ normalised_only = not changed and not srt_timings_shared_grammar(srt_path)
1718
+ if changed or normalised_only:
1719
+ new_srt = os.path.splitext(output)[0] + "_adjusted.srt"
1720
+ claim([(new_srt, "adjusted SRT")])
1721
+ if STATE.dry_run:
1722
+ info(f"[dry-run] would write {new_srt} ({len(adjusted)} cues, adjusted from {os.path.basename(srt_path)})")
1723
+ else:
1724
+ write_srt(adjusted, new_srt)
1725
+ info(f"wrote {new_srt} ({len(adjusted)} cues, adjusted from {os.path.basename(srt_path)})")
1726
+ srt_path = new_srt
1727
+ planned_cues = adjusted
1728
+ why = ("--offset/--max-lines/--min-duration" if changed else
1729
+ "its timings rewritten as hh:mm:ss,mmm, which ffmpeg reads as this tool does")
1730
+ side_notes.append(f"the {'muxed' if args.mode == 'mux' else 'burned'} subtitles are {new_srt}, the adjusted copy of "
1731
+ f"{os.path.basename(args.srt)} this run writes ({why})"
1732
+ + ("; re-run this command without --dry-run to produce it" if STATE.dry_run else ""))
1733
+ if args.ass and args.offset and os.path.exists(args.ass):
1734
+ shifted = os.path.splitext(output)[0] + "_offset.ass"
1735
+ if STATE.dry_run:
1736
+ _text, n, unshifted = shift_ass_text(read_text_or_die(args.ass, "--ass"), args.offset)
1737
+ info(f"[dry-run] would write {shifted} ({n} cues shifted by {args.offset:+g} s)")
1738
+ else:
1739
+ n, unshifted = shift_ass_file(args.ass, shifted, args.offset)
1740
+ info(f"wrote {shifted} ({n} cues shifted by {args.offset:+g} s)")
1741
+ # the counts reach the document (caption.ass_shifted / ass_unshifted), and a line
1742
+ # whose timestamps could not be read -- copied unshifted -- is a warning, not a silence
1743
+ ass_counts.update(ass_shifted=n, ass_unshifted=unshifted)
1744
+ if unshifted:
1745
+ warn(f"{unshifted} Dialogue line(s) in {args.ass} have timestamps that could not be read, so they were not "
1746
+ f"shifted by {args.offset:+g} s (copied as they were)", "ass_lines_unshifted",
1747
+ path=args.ass, count=unshifted, offset=args.offset)
1748
+ args.ass = shifted
1749
+ side_notes.append(f"the burned subtitles are {shifted}, the offset copy of "
1750
+ f"{os.path.basename(ass_sample_path)} this run writes"
1751
+ + ("; re-run this command without --dry-run to produce it" if STATE.dry_run else ""))
1752
+ # a side file this run has planned but (under --dry-run) not written is still the file the
1753
+ # command names, so its absence must not be reported as a missing input
1754
+ planned_only = STATE.dry_run and planned_cues is not None
1755
+ planned_ass = STATE.dry_run and bool(args.ass) and args.ass != ass_sample_path
1756
+
1757
+ if args.mode == "mux":
1758
+ if not srt_path or (not os.path.exists(srt_path) and not planned_only
1759
+ and not (STATE.dry_run and (args.text or args.transcribe))):
1760
+ die(f"SRT file {absent_word(srt_path)}: {srt_path}")
1761
+ codec = mux_subtitle_codec(output)
1762
+ out_ext = Path(output).suffix.lower().lstrip(".")
1763
+ # The picture and the sound are copied: a WebM holds only VP8/VP9/AV1 and Opus/Vorbis, so
1764
+ # anything else is refused here, not left to fail unclassified in the muxer (#414)
1765
+ if out_ext == "webm":
1766
+ vcodec = (meta.get("video") or {}).get("codec")
1767
+ # the stream -map 0:a:N copies (--audio-stream), not always the first one
1768
+ audio_streams = meta.get("audio_streams") or []
1769
+ acodec = audio_streams[args.audio_stream].get("codec") if args.audio_stream < len(audio_streams) else None
1770
+ bad = [c for c in (vcodec,) if c and c not in ("vp8", "vp9", "av1")] + \
1771
+ [c for c in (acodec,) if c and c not in ("opus", "vorbis")]
1772
+ if bad:
1773
+ die(f"--mode mux copies the picture and the sound, and a .webm holds only VP8/VP9/AV1 video and "
1774
+ f"Opus/Vorbis audio; {args.input} carries {' and '.join(bad)}", kind="input",
1775
+ hint="write .mkv (any codec) or .mp4 instead, or re-encode first with export.py")
1776
+ # Keep any subtitle track(s) the input already has (e.g. chaining --mode mux once per
1777
+ # language to build a multi-language set): copied where the output container holds them as
1778
+ # they are, else converted to its own text format as export.py converts them (#380, #414);
1779
+ # a track the container cannot hold at all (a bitmap one in MPEG-4 or WebM) is refused.
1780
+ existing_subs = meta.get("subtitle_streams") or 0
1781
+ existing_details = list(meta.get("subtitle_stream_details") or [])
1782
+ existing_codecs = [(existing_details[i] if i < len(existing_details) else {}).get("codec") or ""
1783
+ for i in range(existing_subs)]
1784
+ unheld = sorted({c or "unknown" for c in existing_codecs if not subtitle_container_holds(c, out_ext)})
1785
+ if unheld:
1786
+ die(f"{args.input} already carries a subtitle track ({', '.join(unheld)}) that a .{out_ext} file cannot "
1787
+ "hold, and --mode mux keeps every existing track", kind="input",
1788
+ hint="write .mkv, which holds any subtitle codec")
1789
+ existing_out = [subtitle_codec_for(c, out_ext) for c in existing_codecs]
1790
+ # the first entry's path is srt_path, which --offset/--max-lines may have repointed at an
1791
+ # adjusted copy; the rest are taken as written
1792
+ added = [(srt_path, srt_tracks[0][1] if srt_tracks else args.language)] + \
1793
+ [(p, lang) for p, lang in srt_tracks[1:]]
1794
+ for path, _lang in added[1:]:
1795
+ if not os.path.exists(path) and not STATE.dry_run:
1796
+ die(f"SRT file {absent_word(path)}: {path}")
1797
+ for n in range(1, len(added)):
1798
+ path, lang = added[n]
1799
+ pending = not os.path.exists(path) # a dry run's pending track: an earlier step writes it
1800
+ if pending and not args.offset:
1801
+ continue
1802
+ if args.offset:
1803
+ # A61: --offset moved the first --srt only, so the other languages stayed where
1804
+ # they were against the sound. Every added track is shifted by the same rule
1805
+ # (a cue that ends at or before 0 is dropped, a start below 0 is clamped). A
1806
+ # pending track's copy is planned under the same name, so the planned command
1807
+ # reads the file the real run reads; only its cues wait for the file
1808
+ copy = f"{os.path.splitext(output)[0]}_track{n}.srt"
1809
+ claim([(copy, f"shifted SRT {n}")])
1810
+ if not pending and not STATE.dry_run:
1811
+ moved = [(max(0.0, s + args.offset), e + args.offset, t) for s, e, t in parse_srt(path)
1812
+ if e + args.offset > 0] # never empty: refused before the first write, above
1813
+ write_srt(moved, copy)
1814
+ info(f"wrote {copy} ({len(moved)} cues of {os.path.basename(path)} shifted by {args.offset:+g} s)")
1815
+ side_notes.append(f"subtitle track {n} is {copy}, a copy of {os.path.basename(path)} shifted by "
1816
+ f"--offset {args.offset:+g} s like the first track"
1817
+ + ("; re-run this command without --dry-run to produce it" if STATE.dry_run else ""))
1818
+ added[n] = (copy, lang)
1819
+ elif not srt_timings_shared_grammar(path):
1820
+ # the same rule as the first track (#414): ffmpeg is given what parse_srt() reads
1821
+ copy = f"{os.path.splitext(output)[0]}_track{n}.srt"
1822
+ claim([(copy, f"normalised SRT {n}")])
1823
+ if not STATE.dry_run:
1824
+ write_srt(parse_srt(path), copy)
1825
+ info(f"wrote {copy} (timings of {os.path.basename(path)} rewritten as hh:mm:ss,mmm)")
1826
+ side_notes.append(f"subtitle track {n} is {copy}, a copy of {os.path.basename(path)} with its timings "
1827
+ "rewritten as hh:mm:ss,mmm, which ffmpeg reads as this tool does")
1828
+ added[n] = (copy, lang)
1829
+ if len(added) > 1 and caption_stats.get("extended"):
1830
+ # --min-duration lengthens the first --srt's cues; the others keep their own durations,
1831
+ # and the result says so (no track is wrapped or split in a mux, A55)
1832
+ side_notes.append(f"--min-duration lengthened cues of the first --srt only: the other {len(added) - 1} "
1833
+ "added track(s) keep the cue lengths of their own files")
1834
+ titles = list(args.track_title or [])
1835
+ mp4_family = Path(output).suffix.lower() in (".mp4", ".m4v", ".mov")
1836
+ dropped_titles: List[str] = []
1837
+ notes = list(side_notes)
1838
+ maps = ["-map", "0:v:0"]
1839
+ cmd = ffmpeg_base() + ["-i", args.input]
1840
+ for path, _lang in added:
1841
+ cmd += ["-i", path]
1842
+ if meta.get("audio"):
1843
+ maps += ["-map", f"0:a:{args.audio_stream}"]
1844
+ if existing_subs:
1845
+ maps += ["-map", "0:s?"] + carried_stream_maps(args.input, output, chapters=False) # their fonts (A256)
1846
+ for n in range(len(added)):
1847
+ maps += ["-map", f"{n + 1}:0"]
1848
+ cmd += maps + ["-c:v", "copy"] + (["-c:a", "copy"] if meta.get("audio") else [])
1849
+ if mp4_family:
1850
+ cmd += ["-movflags", "+faststart"]
1851
+ for i in range(existing_subs):
1852
+ cmd += [f"-c:s:{i}", existing_out[i]]
1853
+ tracks: List[Dict[str, Any]] = []
1854
+ converted: List[str] = []
1855
+ # A60: a kept track is reported with the disposition the input gives it (the muxer copies
1856
+ # it), not False whatever the file says; when --default-track makes a new track the
1857
+ # default, the kept ones are cleared so the file does not carry two defaults
1858
+ new_default = bool(args.default_track and any(
1859
+ lang and lang.lower() == args.default_track.lower() for _p, lang in added))
1860
+ for i in range(existing_subs):
1861
+ detail = existing_details[i] if i < len(existing_details) else {}
1862
+ written = detail.get("codec") if existing_out[i] == "copy" else existing_out[i]
1863
+ if existing_out[i] != "copy":
1864
+ converted.append(f"{detail.get('codec')} -> {existing_out[i]}")
1865
+ kept_default = bool(detail.get("default")) and not new_default
1866
+ if new_default and detail.get("default"):
1867
+ # "-default" takes that one flag off; "0" would clear forced and the rest with it
1868
+ cmd += [f"-disposition:s:{i}", "-default"]
1869
+ tracks.append({"index": i, "file": None, "language": detail.get("language"),
1870
+ "title": detail.get("title"), "codec": written,
1871
+ "default": kept_default, "cues": None, "kept_from_input": True})
1872
+ for n, (path, lang) in enumerate(added):
1873
+ idx = existing_subs + n
1874
+ cmd += [f"-c:s:{idx}", codec]
1875
+ stored = container_language(lang, output) if lang else None
1876
+ if stored:
1877
+ cmd += [f"-metadata:s:s:{idx}", f"language={stored}"]
1878
+ title = track_title_for(lang, titles[n] if n < len(titles) else None)
1879
+ # `-metadata:s:s:N title=` is written for Matroska and silently dropped by the MPEG-4
1880
+ # muxer (verified on ffmpeg 6.1: ffprobe reads no title back), so an MP4 track is
1881
+ # reported with `title: null` rather than a name the file does not carry.
1882
+ if title and not mp4_family:
1883
+ cmd += [f"-metadata:s:s:{idx}", f"title={title}"]
1884
+ elif title:
1885
+ dropped_titles.append(title)
1886
+ title = None
1887
+ is_default = bool(args.default_track and lang
1888
+ and lang.lower() == args.default_track.lower())
1889
+ # ALWAYS stated, never only when it is "default": given two or more new subtitle
1890
+ # streams and nothing said, ffmpeg flags the first one `default` by itself -- which
1891
+ # is the opposite of what --default-track promises and made tracks[].default
1892
+ # disagree with the file it describes. An explicit 0 suppresses that.
1893
+ cmd += [f"-disposition:s:{idx}", "default" if is_default else "0"]
1894
+ cues_n = None
1895
+ if os.path.exists(path):
1896
+ try:
1897
+ cues_n = len(parse_srt(path))
1898
+ except SystemExit:
1899
+ cues_n = None
1900
+ tracks.append({"index": idx, "file": path, "language": stored, "title": title,
1901
+ "codec": codec, "default": is_default, "cues": cues_n,
1902
+ "kept_from_input": False})
1903
+ # asked of the tracks this run adds: a default the input already carried does not make
1904
+ # --default-track fr true when no --srt was tagged fr
1905
+ if args.default_track and not new_default:
1906
+ die(f"--default-track {args.default_track}: no --srt was tagged with that language",
1907
+ kind="input")
1908
+ # MPEG-4 has no way to say "no default subtitle track": the muxer sets the track-header
1909
+ # ENABLED flag on the first subtitle track whatever `-disposition:s:N 0` asks for
1910
+ # (verified on ffmpeg 6.1; `-disposition:s:N default` does move it to another track).
1911
+ # Matroska honours the explicit 0. Report what the file carries, not what was asked.
1912
+ if mp4_family and tracks and not any(t["default"] for t in tracks):
1913
+ tracks[0]["default"] = True
1914
+ notes.append("an MPEG-4 container always enables its first subtitle track, so "
1915
+ f"{tracks[0]['language'] or 'track 0'} is marked default even though none "
1916
+ "was asked for; .mkv is the container that can leave every track off")
1917
+ cmd += [output]
1918
+ total = existing_subs + len(added)
1919
+ if total > 2 and mp4_family:
1920
+ notes.append(f"{total} subtitle tracks in an MPEG-4 container: the tracks are all there, "
1921
+ "but many players only ever show the first -- write to .mkv for a "
1922
+ "deliverable a viewer can actually switch")
1923
+ if converted:
1924
+ notes.append(f"the input's own subtitle track(s) were converted to the .{out_ext} container's text format "
1925
+ f"({', '.join(converted)}): their text and timing are kept, styling a format cannot carry is not")
1926
+ if dropped_titles:
1927
+ notes.append("an MPEG-4 container has no per-track title this tool can write back "
1928
+ f"({', '.join(dropped_titles)} would be dropped), so the tracks are "
1929
+ "reported with no title; .mkv keeps the names")
1930
+ if mp4_family and any(
1931
+ t["language"] and len(t["language"]) != 3 for t in tracks if not t["kept_from_input"]):
1932
+ notes.append("MPEG-4 stores the language as a three-letter ISO-639-2 code and drops "
1933
+ "anything else; a code this tool has no conversion for was passed through "
1934
+ "as given and may not survive")
1935
+ run(cmd)
1936
+ result = probe(output, role="output")
1937
+ # the language and title each track carries in the written file: a converted track keeps
1938
+ # only what the container can store (MPEG-4 drops a two-letter code and every title)
1939
+ written = result.get("subtitle_stream_details") or []
1940
+ if len(written) == len(tracks):
1941
+ for track, detail in zip(tracks, written):
1942
+ track["language"] = detail.get("language")
1943
+ if track["kept_from_input"]:
1944
+ track["title"] = detail.get("title")
1945
+ info(f"wrote {output} ({fmt_secs(result.get('duration'))}, mux, {len(added)} "
1946
+ f"subtitle track(s) added, codec {codec})")
1947
+ emit(output, tracks=tracks, subtitle_tracks=total, **({"notes": notes} if notes else {}),
1948
+ **({"transcription": args._asr} if getattr(args, "_asr", None) else {}))
1949
+ return 0
1950
+
1951
+ # A font that covers the text, before anything is rendered: non-Latin cues in a Latin-only
1952
+ # family come out as empty boxes, and ffmpeg exits 0 all the same (see references/gotchas.md).
1953
+ if args.ass:
1954
+ sample = parse_ass_dialogue(ass_sample_path) if ass_sample_path and os.path.exists(ass_sample_path) else ""
1955
+ elif args.text or args.transcribe:
1956
+ sample = "\n".join(t for _, _, t in cues)
1957
+ elif planned_cues is not None:
1958
+ sample = "\n".join(t for _, _, t in planned_cues)
1959
+ else:
1960
+ sample = "\n".join(t for _, _, t in parse_srt(srt_path)) if os.path.exists(srt_path or "") else ""
1961
+ _script, font_file, font_family = script_font_for_text(
1962
+ sample, lang=args.language, font=args.font, font_explicit=font_explicit,
1963
+ fonts_dir=args.fonts_dir, font_bold=args.bold)
1964
+ # the font libass draws with, reported as `font_used`: a --fonts-dir (or a brand's font
1965
+ # file) is searched first for the family, by libass itself; otherwise fontconfig resolves it
1966
+ if args.ass:
1967
+ # the caller's own ASS names its fonts in its styles; this run does not choose them
1968
+ font_used = {"asked": None, "file": None, "family": None, "how": "ass_styles",
1969
+ "fonts_dir": args.fonts_dir or (os.path.dirname(font_file) if font_file else None), "substituted": None}
1970
+ elif font_file or not args.fonts_dir:
1971
+ # the family libass is given is the sanitised one (ass_font_name): that is what it resolves
1972
+ font_used = record_font_choice(font_choice(ass_font_name(args.font), script_file=font_file, script_family=font_family,
1973
+ renderer="libass", bold=bool(args.bold)))
1974
+ else:
1975
+ # A literal directory miss does not rule out a fontconfig alias to a loaded face.
1976
+ asked = ass_font_name(args.font)
1977
+ face, found = fonts_dir_face(args.fonts_dir, asked, bold=bool(args.bold))
1978
+ if found is False:
1979
+ note(f"font: no outline face in {args.fonts_dir} is named '{asked}'; libass may pick a directory face through a fontconfig alias, so the face is not established")
1980
+ elif found is None:
1981
+ note(f"font: whether {args.fonts_dir} holds a face named '{asked}' could not be read (fc-scan unavailable or incomplete metadata); "
1982
+ "font_used reports it as asked")
1983
+ elif face is None:
1984
+ note(f"font: {args.fonts_dir} holds '{asked}' only in other styles than the one asked "
1985
+ f"({'bold' if args.bold else 'regular'}, upright); libass picks among those and the installed "
1986
+ "faces of the family, so font_used names no file (not measured)")
1987
+ font_used = {"asked": asked, "file": face, "family": asked, "how": "fonts_dir",
1988
+ "fonts_dir": args.fonts_dir, "substituted": False if face else None} # no file, no measurement (#663)
1989
+ if font_file:
1990
+ args.font = font_family or args.font
1991
+ if not args.fonts_dir:
1992
+ args.fonts_dir = os.path.dirname(font_file)
1993
+
1994
+ # Emoji (1.15). Decided once, on the cues the burn will actually use: libass cannot place a
1995
+ # PNG, so the text keeps its place in the ASS (with the gap reserved) and each emoji becomes an
1996
+ # overlay composited after the ass= filter. A cue file that has no emoji costs nothing here.
1997
+ emoji_plan = None
1998
+ emoji_cues = None
1999
+ if not args.ass:
2000
+ if args.text or args.transcribe:
2001
+ src_cues = cues
2002
+ elif planned_cues is not None:
2003
+ src_cues = planned_cues
2004
+ elif os.path.exists(srt_path or ""):
2005
+ src_cues = parse_srt(srt_path)
2006
+ else:
2007
+ src_cues = []
2008
+ if src_cues and has_emoji("\n".join(t for _s, _e, t in src_cues)):
2009
+ emoji_cues, emoji_plan = plan_emoji(src_cues, args, play_w, play_h,
2010
+ brand if args.brand else None)
2011
+ # the PNG route and --emoji none both change the drawn text, so they need the generated ASS
2012
+ force_ass = bool(emoji_plan and (emoji_plan.get("overlays") or emoji_plan.get("mode") == "none"))
2013
+ if (not args.ass and not force_ass and args.animate == "none" and not args.karaoke
2014
+ and any(SRT_HIDDEN_BRACES_RE.search(t) for _s, _e, t in src_cues)):
2015
+ # A68 (#457): ffmpeg's SRT reader hands `{curly}` to libass as an override block, which
2016
+ # draws nothing of it, while the generated ASS draws the braces and their text; the cues
2017
+ # go the generated-ASS way, so the burned words are the words given
2018
+ force_ass = True
2019
+ info("cue text has braces that ffmpeg's SRT reader would hide; drawing the cues through the generated ASS")
2020
+ side_notes.append("the cues hold text in braces, which a plain SRT burn does not draw ({...} is an override "
2021
+ "block to libass), so they were drawn through the generated ASS, braces included")
2022
+ if emoji_plan and emoji_plan.get("box_px"):
2023
+ args._emoji_box_px = emoji_plan["box_px"]
2024
+
2025
+ if (args.animate != "none" or args.karaoke or force_ass) and not args.ass:
2026
+ # both sources are already laid out: `cues` above, and srt_path was rewritten in place of
2027
+ # the caller's file when --offset/--max-lines/--min-duration changed anything
2028
+ cues_for_ass = emoji_cues if emoji_cues is not None else (
2029
+ cues if (args.text or args.transcribe) else (
2030
+ planned_cues if planned_cues is not None else parse_srt(srt_path)))
2031
+ if args.karaoke and not getattr(args, "_word_timings", None):
2032
+ # Use the cue source's sidecar, even when layout rewrites the caller's SRT.
2033
+ args._word_timings = shift_words(whisper_word_timings(
2034
+ args.srt if args.srt and not (args.text or args.transcribe) else srt_path), args.offset)
2035
+ ass_path = args.write_ass or os.path.splitext(output)[0] + ".ass"
2036
+ claim([(ass_path, "ASS")])
2037
+ w, h = display_size(meta["video"])
2038
+ if not STATE.dry_run: # the generated ASS is an artifact of this run: a plan writes nothing
2039
+ write_ass(cues_for_ass, ass_path, args, w, h, video=args.input if meta.get("audio") else None)
2040
+ info(f"wrote {ass_path} ({len(cues_for_ass)} cues, animate={args.animate}, karaoke={args.karaoke})")
2041
+ args.ass = ass_path
2042
+ generated_ass = True
2043
+ else:
2044
+ generated_ass = False
2045
+ if not generated_ass and caption_stats.get("fit_scope") == "cue":
2046
+ # A67: one size per cue is a {\fsN} override in the generated ASS; the plain SRT burn
2047
+ # draws every cue at one FontSize, so the scope that was applied is the file's, and
2048
+ # saying "cue" described sizes nobody drew. A caller's own --ass sets its sizes itself
2049
+ # (styles, per-cue overrides): this tool decided none of them, so it claims no scope.
2050
+ if args.ass:
2051
+ caption_stats["fit_scope"] = None
2052
+ side_notes.append("--fit-size-scope cue was not applied: the --ass file sets its own sizes, "
2053
+ "which this tool does not read or change")
2054
+ else:
2055
+ caption_stats["fit_scope"] = "file"
2056
+ side_notes.append("--fit-size-scope cue applies on the generated-ASS route (--animate, --karaoke, emoji "
2057
+ "overlays); this burn draws every cue at one size (size_used), so the fit is file-scoped")
2058
+
2059
+ if args.ass:
2060
+ if not generated_ass and not os.path.exists(args.ass) and not planned_ass:
2061
+ die(f"ASS file {absent_word(args.ass)}: {args.ass}")
2062
+ # 2.2.6: a burn whose cues are all blank, or all outside the video, draws nothing -- and used
2063
+ # to report verified. Count the cues that can actually be seen; none is a refusal.
2064
+ if generated_ass:
2065
+ burn_cues: Optional[List[Tuple[float, float, str]]] = cues_for_ass
2066
+ elif args.ass and not os.path.exists(ass_sample_path):
2067
+ # a dry run's pending --ass (an earlier step writes it): nothing to count yet
2068
+ burn_cues = None
2069
+ elif args.ass:
2070
+ parsed: dict = {}
2071
+ if planned_ass: # dry run: the offset copy is not written yet, shift the caller's file
2072
+ burn_cues = [(s + args.offset, e + args.offset, t) for s, e, t in parse_ass_cues(ass_sample_path, parsed)]
2073
+ else:
2074
+ burn_cues = parse_ass_cues(args.ass, parsed)
2075
+ ass_counts["ass_malformed"] = parsed.get("malformed", 0)
2076
+ if ass_counts["ass_malformed"]:
2077
+ warn(f"{ass_counts['ass_malformed']} Dialogue line(s) in {ass_sample_path} could not be read (too few fields "
2078
+ "or an unreadable start/end) and are not counted as cues", "ass_lines_malformed",
2079
+ path=ass_sample_path, count=ass_counts["ass_malformed"])
2080
+ if not burn_cues:
2081
+ die(f"no Dialogue lines found in {ass_sample_path} -- nothing would be drawn", kind="input")
2082
+ elif planned_cues is not None:
2083
+ burn_cues = planned_cues
2084
+ elif args.text or args.transcribe:
2085
+ burn_cues = cues or None # empty under a --transcribe dry run: nothing to count yet
2086
+ elif srt_path and os.path.exists(srt_path):
2087
+ burn_cues = parse_srt(srt_path)
2088
+ else:
2089
+ burn_cues = None
2090
+ if burn_cues:
2091
+ burned, outside = count_visible_cues(burn_cues, meta.get("duration"))
2092
+ if not burned and not outside:
2093
+ die("every cue is blank -- nothing would be drawn", kind="input")
2094
+ if not burned:
2095
+ first = min(s for s, _e, t in burn_cues if cue_text_visible(t))
2096
+ die(f"no cue falls inside the video (0\u2013{float(meta['duration']):.1f} s); first cue "
2097
+ f"starts at {first:.1f} s -- check --offset or the cue file", kind="input")
2098
+ if outside:
2099
+ msg = (f"{outside} cue(s) fall outside the video (0\u2013{float(meta['duration']):.1f} s) "
2100
+ "and are not drawn")
2101
+ warn(msg, "cues_outside_video", count=outside, duration=float(meta["duration"]))
2102
+ side_notes.append(msg)
2103
+ caption_stats["cues_burned"] = burned
2104
+ caption_stats["cues_outside"] = outside
2105
+ require_filter("ass" if args.ass else "subtitles", "burning captions")
2106
+ # the path as a named option: with a positional first value a build without the filter fails at
2107
+ # parse time ("No option name near ...") instead of saying "No such filter" (#393)
2108
+ if args.ass:
2109
+ vf = f"ass=filename={escape_filter_path(args.ass)}"
2110
+ if args.fonts_dir:
2111
+ vf += f":fontsdir={escape_filter_path(args.fonts_dir)}"
2112
+ else:
2113
+ if not srt_path or (not os.path.exists(srt_path) and not planned_only
2114
+ and not (STATE.dry_run and (args.text or args.transcribe))):
2115
+ die(f"SRT file {absent_word(srt_path)}: {srt_path}")
2116
+ style = [
2117
+ f"FontName={ass_font_name(args.font)}",
2118
+ f"FontSize={args.size}",
2119
+ f"PrimaryColour={ass_color(args.color)}",
2120
+ f"OutlineColour={ass_color(args.outline_color)}",
2121
+ f"BackColour={ass_color(args.outline_color, 0x80)}",
2122
+ f"BorderStyle={3 if args.box else 1}",
2123
+ f"Outline={args.outline:g}",
2124
+ f"Shadow={args.shadow:g}",
2125
+ f"Bold={-1 if args.bold else 0}",
2126
+ f"Alignment={FORCE_STYLE_ALIGN[args.position]}",
2127
+ f"MarginV={args.margin}",
2128
+ ]
2129
+ if ass_base_encoding(strip_srt_markup(text) for _, _, text in (burn_cues or ())) == -1:
2130
+ style.append("Encoding=-1")
2131
+ force = ",".join(style).replace("\\", "\\\\").replace("'", "\\'")
2132
+ vf = f"subtitles=filename={escape_filter_path(srt_path)}:force_style='{force}'"
2133
+ if args.fonts_dir:
2134
+ vf += f":fontsdir={escape_filter_path(args.fonts_dir)}"
2135
+ if generated_ass or not args.ass:
2136
+ # a text/outline/karaoke colour with chroma lands in the BT.709 the output is tagged with
2137
+ # (drawn_chain). A caller's own --ass is burned as libass and FFmpeg read it: its colours,
2138
+ # and its YCbCr Matrix header, are the file's.
2139
+ vf = drawn_chain(vf, meta, [args.color, args.outline_color]
2140
+ + ([args.highlight_color, args.upcoming_color] if args.karaoke else []))
2141
+
2142
+ if square_pixels((meta or {}).get("video")):
2143
+ vf = square_pixels(meta["video"]) + "," + vf
2144
+ side_notes.append(square_pixels_note(meta["video"]))
2145
+ cmd = ffmpeg_base() + ["-i", args.input]
2146
+ chains, emoji_inputs = (emoji_filter_chain(emoji_plan or {}, "vsub", "vout", to_yuv=rgb_chain_to_bt709(meta),
2147
+ base_chain=layer_base_chain(meta), overlay_opts=overlay_format(meta))
2148
+ if emoji_plan else ([], []))
2149
+ if chains:
2150
+ for spec in emoji_inputs:
2151
+ cmd += spec
2152
+ asset = spec[-1]
2153
+ if asset not in STATE.plan_inputs:
2154
+ STATE.plan_inputs.append(asset)
2155
+ # the conform of a VFR source is the fps filter at the end of the chain (#512)
2156
+ graph = cfr_at_input(";".join([f"[0:v]{vf}[vsub]"] + chains), meta)
2157
+ cmd += ["-filter_complex", graph, "-map", "[vout]"]
2158
+ else:
2159
+ cmd += ["-map", "0:v:0", "-vf", with_cfr(vf, meta)]
2160
+ if meta.get("audio"):
2161
+ cmd += ["-map", f"0:a:{args.audio_stream}"]
2162
+ cmd += video_args(meta, args.crf, args.preset) + cfr_args(meta)
2163
+ cmd += (aac_args() if meta.get("audio") else ["-an"]) + [output]
2164
+ run(cmd)
2165
+ result = probe(output, role="output")
2166
+ info(f"wrote {output} ({fmt_secs(result.get('duration'))})")
2167
+ extra = {"notes": side_notes} if side_notes else {}
2168
+ # 1.17.1: say so when the words on screen are the words that were handed in. This tool never
2169
+ # rewrites, shortens or translates a cue -- only line breaks, timing and type size move -- so
2170
+ # the honest sentence in a report ("the text is yours, unchanged") needs no extra judgement.
2171
+ # Review 17 finding 5: a cue SPLIT across two consecutive cues, a dropped cue, transcription
2172
+ # and `--emoji none` (which str.replace()s glyphs out of the drawn text) all change what the
2173
+ # viewer reads, so none of them may be reported as unchanged. Wrapping, line breaks and
2174
+ # timing do not count -- the words are the same.
2175
+ caption_stats["text_unchanged"] = bool(
2176
+ not args.transcribe
2177
+ and not caption_stats.get("dropped")
2178
+ and not caption_stats.get("split")
2179
+ and (emoji_plan or {}).get("mode") != "none")
2180
+ if caption_stats["text_unchanged"]:
2181
+ info("caption text unchanged: the cues were burned exactly as given (line breaks, timing "
2182
+ "and type size only)")
2183
+ extra["caption"] = dict(caption_stats, **ass_counts)
2184
+ extra["font_used"] = font_used
2185
+ if getattr(args, "_asr", None):
2186
+ extra["transcription"] = args._asr
2187
+ if emoji_plan:
2188
+ notes = list(extra.get("notes") or [])
2189
+ if emoji_plan["mode"] == "mono":
2190
+ notes.append("emoji rendered monochrome (no colour path on this ffmpeg; "
2191
+ "--emoji-assets DIR for colour)")
2192
+ if emoji_plan["mode"] == "none":
2193
+ # --emoji none was asked for only when it was: an auto run that can draw none says that
2194
+ notes.append("emoji stripped from the drawn text (--emoji none)" if getattr(args, "emoji", "auto") == "none" else
2195
+ "emoji left out of the drawn text: nothing here draws them (--emoji auto; the emoji_not_drawn warning says why)")
2196
+ if emoji_plan["missing"]:
2197
+ notes.append("no PNG asset for " + ", ".join(emoji_plan["missing"]))
2198
+ if notes:
2199
+ extra["notes"] = notes
2200
+ extra["emoji"] = {k: v for k, v in emoji_plan.items() if k not in ("overlays", "box_px")}
2201
+ extra["emoji"]["overlays"] = len(emoji_plan.get("overlays") or [])
2202
+ emit(output, **extra)
2203
+ return 0
2204
+
2205
+
2206
+ if __name__ == "__main__":
2207
+ sys.exit(main())