@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,867 @@
1
+ #!/usr/bin/env python3
2
+ """Audio post: denoise, voice clean-up, typed dynamics (compressor, limiter,
3
+ gate), background music with auto-ducking, fades and stereo/mono handling.
4
+ Video is stream-copied; an audio output extension (.wav/.flac/.mp3/.m4a/...)
5
+ drops the picture, so `audio.py talk.mp4 -o talk.wav` is an extraction.
6
+
7
+ Examples:
8
+ python3 audio.py interview.mp4 --denoise # FFT noise reduction
9
+ python3 audio.py interview.mp4 --voice # highpass + de-esser + compressor + denoise
10
+ python3 audio.py interview.mp4 --voice light # highpass + gentle compression only (light|medium|strong)
11
+ python3 audio.py talk.mp4 --music bed.mp3 --duck # music under speech, auto-ducked
12
+ python3 audio.py talk.mp4 --music bed.mp3 --music-volume -18 --music-fade-out 3 # bed fades, voice does not
13
+ python3 audio.py clip.mp4 --fade-in 0.5 --fade-out 1 --stereo
14
+ python3 audio.py talk.mp4 --music bed.mp3 --duck --duck-threshold -30 --duck-release 250 # ducks earlier and recovers faster
15
+ python3 audio.py band.wav --stereo-widen 0.5 -o wide.wav # wider stereo image (a real stereo source; mono is refused)
16
+ python3 audio.py surround.mov --downmix # 5.1 -> stereo, ITU-R BS.775 weights, scaled not to clip
17
+ python3 audio.py clip.mp4 --replace narration.wav # swap the audio track entirely
18
+ python3 audio.py interview.mp4 -o interview.wav # extract the audio (no video in the output)
19
+ python3 audio.py multi.mkv --audio-stream 1 --voice -o lav.m4a # pick the second audio track, clean it, write M4A
20
+ python3 audio.py talk.wav --compress --comp-threshold -20 --comp-ratio 4 --limit --limit-ceiling -1 -o talk_dyn.wav
21
+ python3 audio.py line.wav --tempo 1.25 --length-samples 96000 -o line_fit.wav # faster, same pitch, exactly 2 s at 48 kHz
22
+ python3 audio.py room.wav --channel 2 --sample-rate 48000 -o mic3.wav # the third microphone alone, resampled to 48 kHz
23
+ python3 audio.py pic.mov --track music.wav --track fx.wav --track-name Dialogue --track-name Music --track-name FX --track-lang eng --track-lang eng --track-lang eng -o stems.mov # one stream per stem, named and tagged
24
+ """
25
+ import argparse
26
+ import json
27
+ import os
28
+ import re
29
+ import sys
30
+ from pathlib import Path
31
+ from typing import Any, Dict, List
32
+
33
+ from _common.probe import SILENT_PEAK_DBFS
34
+ from _common.runner import path_denied
35
+ from _common import STATE, add_common, dry_run_input_pending, require_tool, apply_common, audio_codec_for, db_to_linear, default_output, die, emit, ffmpeg_base, info, is_audio_output, measured_level_dbfs, probe, run, run_keeping_subtitles, fmt_secs
36
+ from _common.emit import file_origin, own_length, refuse, stream_end, warn
37
+ from _common.decision import LOSSLESS_AUDIO_EXT, PAD_SOUND_FROM_ZERO, atempo_chain_with_lead, conform_filter, conform_to_length, late_sound_lead
38
+
39
+ # --downmix: ITU-R BS.775 fold-down, renormalised by pan's '<' (see main()).
40
+ DOWNMIX_PAN = "pan=stereo|FL<FL+0.707*FC+0.707*BL+0.707*SL|FR<FR+0.707*FC+0.707*BR+0.707*SR"
41
+ VOICE_DENOISE = "afftdn=nf=-25:tn=1" # the denoise stage of the medium and strong chains
42
+ VOICE_CHAIN = f"highpass=f=80,deesser=i=0.4,{VOICE_DENOISE},acompressor=threshold=-18dB:ratio=3:attack=5:release=80:makeup=2"
43
+
44
+ # --voice [light|medium|strong] (1.13). "medium" is the chain --voice has always produced, so a
45
+ # bare --voice (and every existing call and MCP request) is byte-identical to before. "light"
46
+ # leaves the noise floor and the sibilance alone -- it only removes rumble and evens the level,
47
+ # which is what a good room recording needs; "strong" is for phone/laptop audio: a harder
48
+ # de-esser, a second compression stage and a soft limiter at -1 dBFS so the peaks stop there
49
+ # instead of at whatever the make-up gain produced.
50
+ VOICE_LIMITER = "alimiter=limit=0.891251:level=disabled:latency=1" # --voice strong's -1 dBFS ceiling
51
+ VOICE_LEVELS = {
52
+ "light": "highpass=f=80,acompressor=threshold=-18dB:ratio=2:attack=5:release=80:makeup=1",
53
+ "medium": VOICE_CHAIN,
54
+ "strong": VOICE_CHAIN + ",deesser=i=0.6,acompressor=threshold=-24dB:ratio=4:attack=5:release=120:makeup=3," + VOICE_LIMITER,
55
+ }
56
+
57
+
58
+
59
+ def voice_chain(level: str, denoise_strength: "float | None") -> str:
60
+ """The --voice chain, with --denoise in it when asked (A136). `light` has no denoise of its
61
+ own, so --voice light --denoise used to drop the denoise without a word: it goes after the
62
+ highpass, where the other levels have theirs. `medium` and `strong` already denoise at
63
+ nf=-25; with --denoise that stage runs at --denoise-strength (25 by default, so the chain
64
+ --voice medium --denoise has always produced is unchanged)."""
65
+ chain = VOICE_LEVELS[level]
66
+ if denoise_strength is None:
67
+ return chain
68
+ stage = f"afftdn=nf=-{denoise_strength:g}:tn=1"
69
+ if VOICE_DENOISE in chain:
70
+ return chain.replace(VOICE_DENOISE, stage)
71
+ return chain.replace("highpass=f=80,", f"highpass=f=80,{stage},", 1)
72
+
73
+
74
+ # The sidechain threshold the music bed has used since 1.4 is the linear 0.05 the filter takes;
75
+ # -26.0206 dBFS is that same number in the unit the flag speaks.
76
+ DUCK_THRESHOLD_DB = -26.0206
77
+
78
+ # the knee the filters take is a linear 1..8 (default 2.82843): in the dB the flag speaks that is
79
+ # 0..18.06 dB, default 9.03 dB. The flag used to accept 1..8 *dB* (linear 1.12..2.51), so no knee
80
+ # from 2.51 up to ffmpeg's own default could be asked for, and the help gave the default as 2.83 dB
81
+ KNEE_MAX_DB = 18.06 # 20*log10(8) = 18.0618, rounded down so the linear value stays inside 1..8
82
+
83
+ # --duck (A134): the bed is lowered by exactly --duck-amount dB while the speech is above the
84
+ # threshold. A sidechain gate keyed by the speech passes the bed where there is speech and nothing
85
+ # elsewhere; that part, scaled by -(1 - 10^(-amount/20)), is added back to the bed, which leaves
86
+ # 10^(-amount/20) of it under speech and all of it in the pauses. The sidechain compressor used
87
+ # through 3.8.8 took the amount as ratio = max(2, amount/3), and a compressor's depth is how far
88
+ # the speech rises over its threshold: on the test's speech 0 and 3 ducked the same 9.7 dB, 60 ducked 18.
89
+ # The key gets a DC offset far below any threshold (-120 dBFS) because agate's detector leaves the
90
+ # gate open on a key that is exact zeros from its first sample. The knee is hard (knee=1): agate's
91
+ # default soft knee (2.82843) opened the gate only about 2 dB over the threshold, so a key just
92
+ # over it left the bed at its level (measured: a sine 1.5 dB over -7.5 dBFS ducked 0 dB of 12).
93
+ DUCK_GATE_RATIO = 9000.0 # agate's largest: closed below the threshold
94
+ DUCK_KEY_DC = "dcshift=shift=0.000001"
95
+
96
+
97
+ # #671: since FFmpeg 7 the CLI reads each input on its own thread, and sidechaingate forwards the EOF of its
98
+ # first input without draining the second, so a bed that ended before the key lost the gate's tail and the duck
99
+ # lifted at a random point. The gated copy is padded (never ends first); the amix after it ends with the dry bed.
100
+ def duck_graph(threshold_db: float, amount_db: float, attack: float, release: float) -> List[str]:
101
+ """The filter-graph lines that turn `[music]` and the speech key `[sc]` into `[ducked]`."""
102
+ cut = 1.0 - 10 ** (-amount_db / 20.0)
103
+ return ["[music]asplit=2[mdry][mraw];[mraw]apad[mwet]",
104
+ f"[sc]{DUCK_KEY_DC}[key]",
105
+ f"[mwet][key]sidechaingate=threshold={db_to_linear(threshold_db):.6g}:ratio={DUCK_GATE_RATIO:g}:range=0:knee=1"
106
+ f":attack={attack:g}:release={release:g}[mspeech]",
107
+ f"[mspeech]volume={-cut:.6g}[mcut]",
108
+ "[mdry][mcut]amix=inputs=2:duration=first:normalize=0[ducked]"]
109
+
110
+
111
+ # Typed dynamics: every flag maps to one real option of one ffmpeg filter, validated against the
112
+ # range that filter documents (ffmpeg -h filter=acompressor / alimiter / agate). dB flags are
113
+ # converted to the linear value the filter takes, so no string reaches the graph unchecked.
114
+ DYNAMICS = {
115
+ "acompressor": {
116
+ "comp_threshold": ("threshold", "dB", -60.0, 0.0), # 0.000976563..1 linear
117
+ "comp_ratio": ("ratio", "x", 1.0, 20.0),
118
+ "comp_attack": ("attack", "ms", 0.01, 2000.0),
119
+ "comp_release": ("release", "ms", 0.01, 9000.0),
120
+ "comp_makeup": ("makeup", "dB", 0.0, 36.0), # 1..64 linear
121
+ "comp_knee": ("knee", "dB", 0.0, KNEE_MAX_DB), # 1..8 linear (A135: was 1..8 dB, linear 1.12..2.51)
122
+ },
123
+ "alimiter": {
124
+ "limit_ceiling": ("limit", "dB", -24.0, 0.0), # 0.0625..1 linear
125
+ "limit_attack": ("attack", "ms", 0.1, 80.0),
126
+ "limit_release": ("release", "ms", 1.0, 8000.0),
127
+ },
128
+ "agate": {
129
+ "gate_threshold": ("threshold", "dB", -60.0, 0.0), # 0..1 linear
130
+ "gate_ratio": ("ratio", "x", 1.0, 9000.0),
131
+ "gate_attack": ("attack", "ms", 0.01, 9000.0),
132
+ "gate_release": ("release", "ms", 0.01, 9000.0),
133
+ "gate_range": ("range", "dB", -90.0, 0.0), # 0..1 linear: how far the gate closes
134
+ "gate_knee": ("knee", "dB", 0.0, KNEE_MAX_DB), # 1..8 linear
135
+ },
136
+ }
137
+
138
+
139
+ def dynamics_filter(name: str, args: argparse.Namespace) -> str:
140
+ """One validated `acompressor=...` / `alimiter=...` / `agate=...` filter string from typed flags."""
141
+ opts = []
142
+ for flag, (opt, unit, lo, hi) in DYNAMICS[name].items():
143
+ value = getattr(args, flag)
144
+ if value is None:
145
+ continue
146
+ if not (lo <= value <= hi):
147
+ die(f"--{flag.replace('_', '-')} {value:g} is outside {lo:g}..{hi:g} {unit if unit != 'x' else ''}".rstrip()
148
+ + f" (the range ffmpeg's {name} accepts)")
149
+ if unit == "dB":
150
+ # the filters take linear amplitude (agate range: -90 dB -> 0.00003 closed, 0 dB -> 1 open)
151
+ opts.append(f"{opt}={db_to_linear(value):.6g}")
152
+ else:
153
+ opts.append(f"{opt}={value:g}")
154
+ if name == "alimiter":
155
+ opts.append("level=disabled") # keep the level: a limiter must not normalise the whole track upwards
156
+ # latency compensation: without it the output is the input delayed by the look-ahead
157
+ # (--limit-attack, 5 ms by default: 240 samples at 48 kHz) and drifts off the picture (#476)
158
+ opts.append("latency=1")
159
+ return name + ("=" + ":".join(opts) if opts else "")
160
+
161
+
162
+ def preflight_beds(args: argparse.Namespace) -> List[Dict[str, Any]]:
163
+ """Every problem with every --replace / --music / --effects file, found before anything runs:
164
+ missing, a directory, empty, unreadable, or readable but with no audio stream (a picture-only
165
+ clip given as a bed used to reach ffmpeg's `[1:a:0]` and fail there, as kind ffmpeg, one file
166
+ at a time). Under --dry-run a file that does not exist yet is an earlier stage's output and is
167
+ left to the plan, as join.py's preflight does; a real file is checked under --dry-run too."""
168
+ problems: List[Dict[str, Any]] = []
169
+ beds = [(f, v) for f, v in (("--replace", args.replace), ("--music", args.music),
170
+ ("--effects", args.effects)) if v] + [("--track", t) for t in args.track or []]
171
+ if not beds:
172
+ return problems
173
+ ffprobe = require_tool("ffprobe")
174
+ for flag, path in beds:
175
+ if dry_run_input_pending(path):
176
+ continue
177
+ reason = None
178
+ if path_denied(path) or not os.path.exists(path):
179
+ reason = "permission denied" if path_denied(path) else "missing"
180
+ elif os.path.isdir(path):
181
+ reason = "a directory, not a file"
182
+ elif os.path.getsize(path) == 0:
183
+ reason = "empty (0 bytes)"
184
+ else:
185
+ proc = run([ffprobe, "-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", path],
186
+ quiet=True, check=False)
187
+ kinds = {line.strip() for line in (proc.stdout or "").splitlines() if line.strip()}
188
+ if proc.returncode != 0 or not kinds:
189
+ reason = "unreadable: " + ((proc.stderr or "").strip().splitlines() or ["no streams"])[-1]
190
+ elif "audio" not in kinds:
191
+ reason = "no audio stream"
192
+ if reason:
193
+ problems.append({"flag": flag, "path": path, "reason": reason})
194
+ return problems
195
+
196
+
197
+ def find_silent_tracks(args: argparse.Namespace, problems: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
198
+ """Every extra file (and, under --duck, the voice track that keys the ducking) whose whole-file
199
+ peak is at or below --silence-threshold dBFS: a silent --music / --replace / --effects bed
200
+ used to be mixed and reported as verified, and a silent voice leaves --duck with nothing to
201
+ duck on. Files already named in `problems`, and files an earlier stage has not written yet
202
+ (--dry-run), are not measured; a real file is measured under --dry-run too, like the preflight."""
203
+ bad = {p["path"] for p in problems}
204
+ tracks = [(f, v, None) for f, v in (("--replace", args.replace), ("--music", args.music),
205
+ ("--effects", args.effects)) if v and v not in bad]
206
+ if args.duck and not args.replace:
207
+ tracks.append(("input", args.input, args.audio_stream))
208
+ silent: List[Dict[str, Any]] = []
209
+ if STATE.dry_run:
210
+ # a writing tool's dry run runs no ffmpeg (docs/contract.md); the real run measures
211
+ return silent
212
+ for flag, path, stream in tracks:
213
+ if dry_run_input_pending(path) or not os.path.isfile(path):
214
+ continue
215
+ level = measured_level_dbfs(path, seconds=None, audio_stream=stream)
216
+ if level is not None and level["peak_dbfs"] <= args.silence_threshold:
217
+ silent.append({"flag": flag, "path": path, "peak_db": level["peak_dbfs"]})
218
+ return silent
219
+
220
+
221
+ def main_track_channels(args: argparse.Namespace, meta: Dict[str, Any]) -> int:
222
+ """Channel count of the track audio.py processes: --replace's first audio track, else the
223
+ input's --audio-stream track; 0 when it is not known (a dry run's pending input)."""
224
+ if args.replace:
225
+ if dry_run_input_pending(args.replace) or not os.path.isfile(args.replace):
226
+ return 0
227
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "a:0", "-show_entries",
228
+ "stream=channels", "-of", "csv=p=0", args.replace], quiet=True, check=False)
229
+ first = (proc.stdout or "").strip().splitlines()[:1]
230
+ return int(first[0]) if first and first[0].strip().isdigit() else 0
231
+ streams = meta.get("audio_streams") or []
232
+ if 0 <= args.audio_stream < len(streams):
233
+ return streams[args.audio_stream].get("channels") or 0
234
+ return (meta.get("audio") or {}).get("channels") or 0
235
+
236
+
237
+ def main_track_lead(args: argparse.Namespace, meta: Dict[str, Any]) -> float:
238
+ """late_sound_lead() of the track audio.py processes: --replace's file, or the input's
239
+ --audio-stream N. probe() describes the first audio stream, so for another track its own start
240
+ is read (a second track that starts late beside a first that does not lost its lead, and the
241
+ other way round a pad was written that did nothing; #554 review). 0.0 when it cannot be read."""
242
+ if args.replace:
243
+ return 0.0 if dry_run_input_pending(args.replace) else late_sound_lead(probe(args.replace))
244
+ if not args.audio_stream or meta.get("dry_run"):
245
+ return late_sound_lead(meta)
246
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", f"a:{args.audio_stream}", "-show_entries",
247
+ "stream=start_time", "-of", "csv=p=0", args.input], quiet=True, check=False)
248
+ first = (proc.stdout or "").strip().splitlines()[:1]
249
+ try:
250
+ lead = float(first[0].strip().strip(",")) - file_origin(meta)
251
+ except (IndexError, ValueError):
252
+ return 0.0
253
+ return lead if lead > 0.0005 else 0.0
254
+
255
+
256
+ def main_track_rate(args: argparse.Namespace, meta: Dict[str, Any]) -> int:
257
+ """Sample rate of the track audio.py processes (as main_track_channels() picks it); 0 when it
258
+ is not known (a dry run's pending input)."""
259
+ if args.replace:
260
+ if dry_run_input_pending(args.replace) or not os.path.isfile(args.replace):
261
+ return 0
262
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "a:0", "-show_entries",
263
+ "stream=sample_rate", "-of", "csv=p=0", args.replace], quiet=True, check=False)
264
+ first = (proc.stdout or "").strip().splitlines()[:1]
265
+ return int(first[0]) if first and first[0].strip().isdigit() else 0
266
+ streams = meta.get("audio_streams") or []
267
+ track = streams[args.audio_stream] if 0 <= args.audio_stream < len(streams) else (meta.get("audio") or {})
268
+ try:
269
+ return int(track.get("sample_rate") or 0)
270
+ except (TypeError, ValueError):
271
+ return 0
272
+
273
+
274
+ # --tempo: atempo keeps the pitch; one stage is kept within 0.5..2.0 (above 2 it drops whole
275
+ # blocks of samples), so a factor outside that range is a chain of stages whose product is it (#486)
276
+ TEMPO_RANGE = (0.1, 10.0)
277
+ LOSSLESS_AUDIO = ("pcm_", "flac", "alac", "wavpack", "tta")
278
+ # samples per frame of the lossy encoders audio_codec_for() picks: a decoded length can differ from
279
+ # the samples written by the encoder's own padding, by at most one frame
280
+ CODEC_FRAME_SAMPLES = {"aac": 1024, "mp3": 1152, "opus": 960, "vorbis": 2048, "ac3": 1536, "eac3": 1536}
281
+
282
+
283
+ def atempo_steps(factor: float) -> List[float]:
284
+ """atempo stages, each in 0.5..2.0, whose product is `factor`."""
285
+ steps: List[float] = []
286
+ while factor > 2.0:
287
+ steps.append(2.0)
288
+ factor /= 2.0
289
+ while factor < 0.5:
290
+ steps.append(0.5)
291
+ factor /= 0.5
292
+ return steps + [factor]
293
+
294
+
295
+ def decoded_samples(path: str, stream: int = 0) -> "int | None":
296
+ """Samples per channel of audio track `stream` (the first by default), counted by decoding it
297
+ (astats); None when the count could not be read."""
298
+ proc = run([require_tool("ffmpeg"), "-hide_banner", "-nostats", "-i", path, "-map", f"0:a:{stream}", "-af",
299
+ "astats=measure_perchannel=none:measure_overall=Number_of_samples", "-f", "null", "-"],
300
+ quiet=True, check=False)
301
+ found = [line.rsplit(":", 1)[-1].strip() for line in (proc.stderr or "").splitlines() if "Number of samples:" in line]
302
+ return int(found[-1]) if proc.returncode == 0 and found and found[-1].isdigit() else None
303
+
304
+
305
+ def length_step(path: str, codec: str, expected: int) -> Dict[str, Any]:
306
+ """The `length_samples` verification step: the written track's decoded length against
307
+ --length-samples, exact for a lossless codec, within one codec frame for a lossy one."""
308
+ measured = decoded_samples(path)
309
+ lossless = codec.startswith(LOSSLESS_AUDIO)
310
+ tolerance = 0 if lossless else CODEC_FRAME_SAMPLES.get(codec, 2048)
311
+ step: Dict[str, Any] = {"step": "length_samples", "expected": expected, "measured": measured,
312
+ "tolerance_samples": tolerance, "codec": codec}
313
+ if measured is None:
314
+ return dict(step, ok=False, reason="not_measured")
315
+ return dict(step, ok=abs(measured - expected) <= tolerance)
316
+
317
+
318
+ SAMPLE_RATE_RANGE = (1000, 768000)
319
+ OPUS_DECODED_RATE = 48000 # what an Opus stream decodes at, whatever rate was encoded (measured: 16 kHz in, 48 kHz out)
320
+
321
+
322
+ def property_step(name: str, expected: int, measured: Any) -> Dict[str, Any]:
323
+ """A verification step comparing one probed property of the written track with the request
324
+ (#487: `sample_rate`, `channels`); `reason: not_measured` when probe could not read it."""
325
+ try:
326
+ value = int(measured)
327
+ except (TypeError, ValueError):
328
+ return {"step": name, "expected": expected, "measured": None, "ok": False, "reason": "not_measured"}
329
+ return {"step": name, "expected": expected, "measured": value, "ok": value == expected}
330
+
331
+
332
+ # --track (#420): the input's sound and each FILE's, one audio stream apiece, written as they are.
333
+ TRACK_CONTAINERS = (".mov", ".mkv", ".mp4")
334
+ # what rebuilds or re-times the sound: refused beside --track, which keeps every track as it is
335
+ TRACK_REFUSED = ("denoise", "voice", "mute", "gain", "music", "effects", "replace", "fade_in", "fade_out", "stereo", "mono",
336
+ "stereo_widen", "channel", "downmix", "tempo", "length_samples", "sample_rate", "compress", "limit", "gate",
337
+ "on_silent", "silence_threshold")
338
+ ISO639_2 = re.compile(r"^[a-z]{3}$")
339
+
340
+
341
+ def check_track_flags(ap: argparse.ArgumentParser, args: argparse.Namespace, output: str) -> None:
342
+ """What --track refuses before anything is probed: an output that holds one stream or cannot name
343
+ them, a flag that rebuilds the sound, a language that is not a three-letter code."""
344
+ ext = Path(output).suffix.lower()
345
+ if ext not in TRACK_CONTAINERS:
346
+ refuse("input", "track_container", f"--track writes one audio stream per track, and {output!r} cannot hold them with a name and a language each",
347
+ hint="write -o NAME.mov, .mkv or .mp4 (a WAV, FLAC or MP3 holds one stream; FFmpeg's MXF muxer writes no track names or languages "
348
+ "and cuts every track to the shortest)", output=output, extension=ext)
349
+ clash = [f"--{n.replace('_', '-')}" for n in TRACK_REFUSED if getattr(args, n) != ap.get_default(n)]
350
+ if clash:
351
+ refuse("input", "track_rebuilds_sound", f"{clash[0]} changes the sound, and --track writes every track as it is",
352
+ hint="run audio.py on each stem first (-o stem.wav), then add the results with --track", flags=clash)
353
+ if not args.track and (args.track_name or args.track_lang):
354
+ die("--track is off but --track-name / --track-lang was given; add --track FILE")
355
+ for code in args.track_lang or []:
356
+ if code and not ISO639_2.match(code):
357
+ refuse("input", "track_language", f"--track-lang {code!r} is not an ISO 639-2 language code (three lowercase letters)",
358
+ hint="eng, jpn, fra, deu, spa, or und for undetermined", language=code)
359
+ if args.bitrate is not None and ext != ".mp4":
360
+ die(f"--bitrate has no effect on the PCM tracks of a {ext} output; drop it, or write .mp4 (AAC)")
361
+
362
+
363
+ def read_tracks(output: str, titles: List[str]) -> List[Dict[str, Any]]:
364
+ """The audio streams of the written file as ffprobe reads them, in order: channels, language, name
365
+ (MOV and MP4 keep it as the handler name, read only where a name was asked) and the length the
366
+ decoder counts for each (None where it could not be counted)."""
367
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "a", "-show_entries",
368
+ "stream=channels,sample_rate:stream_tags=language,title,handler_name", "-of", "json", output], quiet=True, check=False)
369
+ try:
370
+ streams = json.loads(proc.stdout or "{}").get("streams") or []
371
+ except ValueError:
372
+ streams = []
373
+ found = []
374
+ for i, s in enumerate(streams):
375
+ tags, rate, samples = s.get("tags") or {}, int(s.get("sample_rate") or 0), decoded_samples(output, i)
376
+ # no language tag is ISO 639 "und": MOV writes an asked-for und as no tag
377
+ found.append({"title": tags.get("title") or (tags.get("handler_name") if i < len(titles) and titles[i] else None),
378
+ "language": tags.get("language") or "und", "channels": s.get("channels"),
379
+ "duration": round(samples / rate, 3) if samples is not None and rate else None})
380
+ return found
381
+
382
+
383
+ def write_tracks(args: argparse.Namespace, meta: Dict[str, Any], output: str) -> int:
384
+ """--track (#420): the input's sound (--audio-stream) and the first audio stream of each --track
385
+ FILE, one audio stream apiece after the picture (stream-copied), each with its own channels and
386
+ length and its --track-name / --track-lang, as PCM (AAC in .mp4). No filter runs."""
387
+ has_video, ext = bool(meta.get("video")), Path(output).suffix.lower()
388
+ sources = ([args.input] if meta.get("audio") else []) + list(args.track)
389
+ titles, langs = list(args.track_name or []), list(args.track_lang or [])
390
+ for flag, given in (("--track-name", titles), ("--track-lang", langs)):
391
+ if len(given) > len(sources):
392
+ refuse("input", "track_labels", f"{len(given)} {flag} values for {len(sources)} track(s)",
393
+ hint="the input's own sound is track 0, then each --track in order; an empty value leaves a track as it is",
394
+ flag=flag, given=len(given), tracks=len(sources))
395
+ titles, langs = (given + [""] * (len(sources) - len(given)) for given in (titles, langs))
396
+ cmd = ffmpeg_base() + ["-i", args.input] + [x for t in args.track for x in ("-i", t)]
397
+ cmd += (["-map", "0:v:0", "-c:v", "copy"] if has_video else []) + (["-map", f"0:a:{args.audio_stream}"] if meta.get("audio") else [])
398
+ cmd += [x for i in range(len(args.track)) for x in ("-map", f"{i + 1}:a:0")]
399
+ cmd += audio_codec_for(output, args.bitrate) if ext == ".mp4" else ["-c:a", "pcm_s24le"]
400
+ for i, (title, lang) in enumerate(zip(titles, langs)):
401
+ tags = {"title": title, "language": lang}
402
+ if ext != ".mkv":
403
+ tags["handler_name"] = title # FFmpeg's MOV/MP4 muxer writes no title atom: a track's name is its handler name
404
+ cmd += [x for k, v in tags.items() if v for x in (f"-metadata:s:a:{i}", f"{k}={v}")]
405
+ dropped = False
406
+ if has_video:
407
+ dropped = run_keeping_subtitles(cmd + (["-movflags", "+faststart"] if ext != ".mkv" else []), output)
408
+ else:
409
+ run(cmd + [output])
410
+ r = probe(output, role="output")
411
+ blank = {"title": None, "language": None, "channels": None, "duration": None}
412
+ found = [dict(blank, title=t or None, language=g or None) for t, g in zip(titles, langs)] if STATE.dry_run else read_tracks(output, titles)
413
+ found += [blank] * (len(sources) - len(found))
414
+ tracks = [{"index": i, "file": src, **found[i]} for i, src in enumerate(sources)]
415
+ info(f"wrote {output} ({len(sources)} audio track(s)" + (", video stream-copied" if has_video else "") + ")")
416
+ steps: List[Dict[str, Any]] = []
417
+ if not STATE.dry_run:
418
+ want = [{"index": i, **{k: v for k, v in (("title", titles[i]), ("language", langs[i])) if v}}
419
+ for i in range(len(sources)) if titles[i] or langs[i]]
420
+ got = [dict(w, **{k: tracks[w["index"]][k] for k in w if k != "index"}) for w in want]
421
+ if want:
422
+ steps.append({"step": "track_tags", "expected": want, "measured": got, "ok": got == want})
423
+ if any(t["duration"] is None for t in tracks):
424
+ steps.append({"step": "track_duration", "ok": False, "reason": "not_measured",
425
+ "tracks": [t["index"] for t in tracks if t["duration"] is None]})
426
+ picture, fps = own_length(r.get("video")), (r.get("video") or {}).get("fps")
427
+ over = [t["index"] for t in tracks if picture and t["duration"] is not None and t["duration"] > picture + (1 / fps if fps else 0.04)]
428
+ if over:
429
+ warn(f"track(s) {over} are longer than the picture ({picture:.3f} s); they are kept whole, not trimmed to it",
430
+ "track_longer_than_picture", tracks=over, picture_seconds=round(picture, 3))
431
+ emit(output, expect_streams={"video": int(has_video), "audio": len(sources)}, tracks=tracks, verification=steps,
432
+ video=has_video, audio_stream=args.audio_stream, dropped_non_av_streams=dropped)
433
+ return 0
434
+
435
+
436
+ def main() -> int:
437
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
438
+ ap.add_argument("input")
439
+ ap.add_argument("-o", "--output", help="output file (default: <name>_audio.<ext>)")
440
+ clean = ap.add_argument_group("clean-up")
441
+ clean.add_argument("--denoise", action="store_true", help="FFT noise reduction (afftdn, adaptive)")
442
+ clean.add_argument("--denoise-strength", type=float, default=25.0, help="afftdn noise floor in dB below full scale, 20..60 (default 25; ffmpeg accepts nf -80..-20, and tn=1 then tracks the floor from this starting point)")
443
+ clean.add_argument("--voice", nargs="?", const="medium", choices=["light", "medium", "strong"], default=None,
444
+ help="speech preset (default medium when the flag is given bare): light = highpass 80 Hz + gentle compression; "
445
+ "medium = highpass, de-esser, denoise, gentle compression; strong = medium plus a harder de-esser, a second "
446
+ "compressor and a soft limiter at -1 dBFS. MCP/JSON callers may still send the 1.12 boolean true, "
447
+ "which is the bare flag and so means medium")
448
+ clean.add_argument("--mute", action="store_true", help="write the picture with no sound track at all (the picture is copied, not re-encoded); nothing else is done")
449
+ clean.add_argument("--gain", type=float, help="gain in dB applied to the main track, -96..96")
450
+ music = ap.add_argument_group("music")
451
+ music.add_argument("--music", help="music file to mix underneath")
452
+ music.add_argument("--music-volume", type=float, default=-14.0, help="music level in dB relative to full scale (default -14)")
453
+ music.add_argument("--duck", action="store_true", help="auto-duck the music by --duck-amount dB while the main track has speech (a sidechain gate keyed by it)")
454
+ music.add_argument("--duck-amount", type=float, default=12.0, help="how many dB the music is lowered under speech, 0..60 (default 12)")
455
+ music.add_argument("--duck-threshold", type=float, default=DUCK_THRESHOLD_DB,
456
+ help="sidechain threshold in dBFS: the main track is heard as speech above this (default -26.02, the 0.05 linear used since 1.4)")
457
+ music.add_argument("--duck-attack", type=float, default=20.0, help="ms the bed takes to duck once speech starts (default 20)")
458
+ music.add_argument("--duck-release", type=float, default=400.0, help="ms the bed takes to come back up after speech (default 400)")
459
+ music.add_argument("--effects", help="a third track (sound effects/atmos) mixed in at --effects-volume; never ducked")
460
+ music.add_argument("--effects-volume", type=float, default=-14.0, help="effects level in dB relative to full scale (default -14)")
461
+ music.add_argument("--music-loop", action="store_true", help="loop the music if shorter than the video")
462
+ fades = ap.add_argument_group("fades / layout")
463
+ fades.add_argument("--fade-in", type=float, default=0.0, help="seconds")
464
+ fades.add_argument("--fade-out", type=float, default=0.0, help="seconds; fades the whole final mix (voice included)")
465
+ music.add_argument("--music-fade-out", type=float, default=0.0, help="seconds; fades only the music bed at the end, voice untouched")
466
+ channels = fades.add_mutually_exclusive_group()
467
+ channels.add_argument("--stereo", action="store_true", help="force 2-channel output (mono is mixed into both sides at about -3.01 dB each, including after --channel)")
468
+ channels.add_argument("--mono", action="store_true", help="force 1-channel output")
469
+ fades.add_argument("--stereo-widen", type=float, default=None, metavar="AMOUNT",
470
+ help="widen the stereo image, 0..1 (0 = untouched, 1 = maximum); needs a real stereo source: a mono input is "
471
+ "refused (duplicating it leaves both channels identical, so there is nothing to widen) and more than two "
472
+ "channels are refused unless --downmix folds them to stereo first")
473
+ fades.add_argument("--channel", type=int, default=None, metavar="N",
474
+ help="keep only channel N of the track (0-based, in the track's own order), as a 1-channel output "
475
+ "(--stereo duplicates it to both sides); checked on the output by probe")
476
+ fades.add_argument("--sample-rate", type=int, default=None, metavar="HZ",
477
+ help="resample the output to HZ (aresample); checked on the output by probe. Default: the track's own rate")
478
+ fades.add_argument("--downmix", action="store_true", help="downmix 5.1/7.1 to stereo with the ITU-R BS.775 weights (centre and surrounds -3 dB, LFE dropped), scaled so the fold-down cannot clip")
479
+ fades.add_argument("--replace", help="replace the audio with this file (trimmed/padded to the video)")
480
+ timing = ap.add_argument_group("timing (an audio output, or --replace beside a kept picture)")
481
+ timing.add_argument("--tempo", type=float, default=None, metavar="FACTOR",
482
+ help="change the tempo of the main track keeping its pitch (atempo; 2 = twice as fast, half as long), "
483
+ f"{TEMPO_RANGE[0]:g}..{TEMPO_RANGE[1]:g}; outside 0.5..2.0 it is a chain of atempo stages. "
484
+ "Refused on the input's own sound while its picture is stream-copied (use fit.py --method speed)")
485
+ timing.add_argument("--length-samples", type=int, default=None, metavar="N",
486
+ help="pad with silence or trim the output to exactly N samples per channel at the output rate "
487
+ "(an audio output only: beside a picture the sound is conformed to the picture)")
488
+ dyn = ap.add_argument_group("dynamics (typed; each flag is one option of ffmpeg's acompressor / alimiter / agate)")
489
+ dyn.add_argument("--compress", action="store_true", help="compressor (acompressor); order: gate -> compressor -> limiter")
490
+ dyn.add_argument("--comp-threshold", type=float, help="dBFS above which gain is reduced, -60..0 (ffmpeg default -18.06, its linear 0.125)")
491
+ dyn.add_argument("--comp-ratio", type=float, help="ratio 1..20 (default 2)")
492
+ dyn.add_argument("--comp-attack", type=float, help="ms 0.01..2000 (default 20)")
493
+ dyn.add_argument("--comp-release", type=float, help="ms 0.01..9000 (default 250)")
494
+ dyn.add_argument("--comp-makeup", type=float, help="make-up gain dB 0..36 (default 0)")
495
+ dyn.add_argument("--comp-knee", type=float, help="knee width dB 0..18.06 (ffmpeg's linear 1..8; default 9.03, its 2.82843)")
496
+ dyn.add_argument("--limit", action="store_true", help="look-ahead limiter (alimiter), level left as is")
497
+ dyn.add_argument("--limit-ceiling", type=float, help="ceiling dBFS -24..0 (default 0)")
498
+ dyn.add_argument("--limit-attack", type=float, help="ms 0.1..80 (default 5)")
499
+ dyn.add_argument("--limit-release", type=float, help="ms 1..8000 (default 50)")
500
+ dyn.add_argument("--gate", action="store_true", help="noise gate (agate)")
501
+ dyn.add_argument("--gate-threshold", type=float, help="dBFS below which the gate closes, -60..0 (default -18.06, ffmpeg's linear 0.125)")
502
+ dyn.add_argument("--gate-ratio", type=float, help="ratio 1..9000 (default 2)")
503
+ dyn.add_argument("--gate-attack", type=float, help="ms 0.01..9000 (default 20)")
504
+ dyn.add_argument("--gate-release", type=float, help="ms 0.01..9000 (default 250)")
505
+ dyn.add_argument("--gate-range", type=float, help="attenuation when closed, dB -90..0 (default -24.26, ffmpeg's linear 0.06125)")
506
+ dyn.add_argument("--gate-knee", type=float, help="knee width dB 0..18.06 (ffmpeg's linear 1..8; default 9.03, its 2.82843)")
507
+ ap.add_argument("--audio-stream", type=int, default=0, help="which audio stream of the input to process, 0-based in file order (probe lists them under audio_streams)")
508
+ tracks = ap.add_argument_group("tracks (one audio stream per source in one file; each is written as it is)")
509
+ tracks.add_argument("--track", action="append", metavar="FILE",
510
+ help="add FILE's sound as one more audio track after the input's own (repeatable); -o .mov, .mkv or .mp4")
511
+ tracks.add_argument("--track-name", "--track-title", action="append", metavar="NAME",
512
+ help="a track's name, in track order (the input's own sound first); empty keeps the source's")
513
+ tracks.add_argument("--track-lang", "--track-language", action="append", metavar="CODE",
514
+ help="a track's ISO 639-2 language code (eng, jpn ...), in track order")
515
+ ap.add_argument("--bitrate", default=None,
516
+ help="audio bitrate: AAC's beside a picture (default 192k), and the codec's of a lossy audio output "
517
+ "(.m4a/.aac default 256k, .mp3 -q:a 0, .ogg -q:a 6, .opus 128k); refused for .wav/.flac/.aif/.aiff/.caf/.mka")
518
+ ap.add_argument("--on-silent", choices=["warn", "fail"], default="warn",
519
+ help="a --music/--replace/--effects file (or, under --duck, the voice) whose peak is at or below "
520
+ "--silence-threshold: warn (default: mix it, report it under `silent`) or fail (refuse before ffmpeg runs)")
521
+ ap.add_argument("--silence-threshold", type=float, default=SILENT_PEAK_DBFS, metavar="DBFS",
522
+ help="peak level in dBFS at or below which a track counts as silent (default -50)")
523
+ add_common(ap)
524
+ args = ap.parse_args()
525
+ apply_common(args)
526
+ for flag_group, switch in (("acompressor", "compress"), ("alimiter", "limit"), ("agate", "gate")):
527
+ if not getattr(args, switch) and any(getattr(args, f) is not None for f in DYNAMICS[flag_group]):
528
+ die(f"--{switch} is off but one of its parameters was given; add --{switch}")
529
+
530
+ # Same rule as the typed dynamics above, for the ducking knobs: a parameter for a switch that
531
+ # is off does nothing, and a caller who says --duck-release 250 and gets the default 400 ms has
532
+ # no way to notice. --duck itself needs a bed to duck.
533
+ duck_params = [f"--duck-{name}" for name in ("threshold", "attack", "release")
534
+ if getattr(args, f"duck_{name}") != ap.get_default(f"duck_{name}")] + \
535
+ (["--duck-amount"] if args.duck_amount != ap.get_default("duck_amount") else [])
536
+ if not args.duck and duck_params:
537
+ die(f"--duck is off but {duck_params[0]} was given; add --duck")
538
+ if args.duck and not args.music:
539
+ die("--duck ducks the music bed under the main track, but no --music was given; add --music FILE")
540
+ # A141: the same rule for the other parameters of a switch that is off. Each was accepted and
541
+ # did nothing: --music-fade-out 2 without --music faded nothing, --denoise-strength 40 without
542
+ # --denoise (also under --voice, whose own denoise stayed at 25) removed nothing more
543
+ bed_params = [flag for flag, name in (("--music-volume", "music_volume"), ("--music-fade-out", "music_fade_out"))
544
+ if getattr(args, name) != ap.get_default(name)] + (["--music-loop"] if args.music_loop else [])
545
+ if not args.music and bed_params:
546
+ die(f"--music is off but {bed_params[0]} was given; add --music FILE")
547
+ if not args.effects and args.effects_volume != ap.get_default("effects_volume"):
548
+ die("--effects is off but --effects-volume was given; add --effects FILE")
549
+ if not args.denoise and args.denoise_strength != ap.get_default("denoise_strength"):
550
+ die("--denoise is off but --denoise-strength was given; add --denoise"
551
+ + (f" (--voice {args.voice} then denoises at that strength)" if args.voice else ""))
552
+ # afftdn's nf accepts -80..-20 only; 10..19.99 used to pass here and then fail inside ffmpeg.
553
+ for flag, value in (("--fade-in", args.fade_in), ("--fade-out", args.fade_out), ("--music-fade-out", args.music_fade_out)):
554
+ if value < 0: # a negative length reached afade, which refused it (kind ffmpeg)
555
+ die(f"{flag} must be 0 or more seconds, got {value:g}")
556
+
557
+ for flag, value, lo, hi in (("--duck-amount", args.duck_amount, 0.0, 60.0),
558
+ ("--duck-threshold", args.duck_threshold, -60.0, 0.0),
559
+ ("--duck-attack", args.duck_attack, 0.01, 2000.0),
560
+ ("--duck-release", args.duck_release, 0.01, 9000.0)):
561
+ if not (lo <= value <= hi):
562
+ die(f"{flag} {value:g} is outside {lo:g}..{hi:g}")
563
+
564
+ if args.track or args.track_name or args.track_lang:
565
+ check_track_flags(ap, args, args.output or default_output(args.input, "audio"))
566
+ problems = preflight_beds(args)
567
+ silent = find_silent_tracks(args, problems)
568
+ if args.on_silent == "fail":
569
+ problems += [{"flag": t["flag"], "path": t["path"], "reason": f"silent (peak {t['peak_db']:g} dBFS)"} for t in silent]
570
+ silent = []
571
+ if problems:
572
+ die(f"{len(problems)} of the extra audio files cannot be mixed: "
573
+ + "; ".join(f"{p['flag']} {p['path']}: {p['reason']}" for p in problems),
574
+ kind="input", problems=problems,
575
+ hint="each --music / --effects / --replace file must be a readable file with an audio stream"
576
+ + (f" and a peak above {args.silence_threshold:g} dBFS (--on-silent warn mixes a silent one anyway)"
577
+ if args.on_silent == "fail" else ""))
578
+ notes: List[str] = []
579
+ if silent:
580
+ notes.append("silent track(s) mixed anyway: " + "; ".join(
581
+ f"{t['flag']} {t['path']} peaks at {t['peak_db']:g} dBFS" for t in silent)
582
+ + f" (at or below --silence-threshold {args.silence_threshold:g}); pass --on-silent fail to refuse instead")
583
+ warn(notes[-1], "silent_track_mixed", tracks=[t["path"] for t in silent])
584
+
585
+ meta = probe(args.input)
586
+ dur = meta.get("duration") or 0.0
587
+ has_video = bool(meta.get("video"))
588
+ if not meta.get("audio") and not args.replace and not args.track:
589
+ die("input has no audio stream (use --replace to add one)")
590
+ output = args.output or default_output(args.input, "audio")
591
+ audio_out = is_audio_output(output)
592
+ if args.mute: # the picture and its subtitles as they are, copied; the sound tracks left out
593
+ if not has_video or audio_out:
594
+ die("--mute leaves nothing to write: it needs a picture and a video output", kind="input")
595
+ run(ffmpeg_base() + ["-i", args.input, "-map", "0:V", "-map", "0:s?", "-c", "copy", output])
596
+ emit(output, expect_streams={"video": 1, "audio": 0})
597
+ return 0
598
+ if args.bitrate is not None and Path(output).suffix.lower() in LOSSLESS_AUDIO_EXT:
599
+ # A143: the rate used to be dropped without a word for every audio extension
600
+ die(f"--bitrate has no effect on a lossless {Path(output).suffix.lower()} output; drop it, or write a lossy one (.m4a, .mp3, ...)")
601
+ streams = meta.get("audio_streams") or []
602
+ if streams and not (0 <= args.audio_stream < len(streams)) and not STATE.dry_run:
603
+ die(f"--audio-stream {args.audio_stream}: input has {len(streams)} audio stream(s), 0..{len(streams) - 1}")
604
+ if args.audio_stream and not streams and not STATE.dry_run:
605
+ die("--audio-stream needs an input with audio streams")
606
+ # the channels of the track the graph processes (main_src below): the --audio-stream track,
607
+ # or --replace's first track. meta["audio"] is the input's first track, so a mono a:0 left a
608
+ # stereo --audio-stream 1 unfolded by --mono, and a stereo a:0 halved a mono one (A128)
609
+ if args.track:
610
+ return write_tracks(args, meta, output)
611
+ in_channels = main_track_channels(args, meta)
612
+ keep_video = has_video and not audio_out
613
+ if args.tempo is not None:
614
+ if not (TEMPO_RANGE[0] <= args.tempo <= TEMPO_RANGE[1]):
615
+ die(f"--tempo must be {TEMPO_RANGE[0]:g}..{TEMPO_RANGE[1]:g}, got {args.tempo:g}")
616
+ if keep_video and not args.replace:
617
+ die("--tempo changes the length of the input's own sound, and its picture is stream-copied, so the two "
618
+ "would drift apart; write an audio output (-o NAME.wav), or retime both with fit.py --method speed",
619
+ kind="input")
620
+ if args.length_samples is not None:
621
+ if args.length_samples < 1:
622
+ die(f"--length-samples must be a positive number of samples, got {args.length_samples}")
623
+ if keep_video:
624
+ die("--length-samples needs an audio output: beside a stream-copied picture the sound is conformed to "
625
+ "the picture's length; write -o NAME.wav (or .flac, .m4a, ...)", kind="input")
626
+ if args.sample_rate is not None and not (SAMPLE_RATE_RANGE[0] <= args.sample_rate <= SAMPLE_RATE_RANGE[1]):
627
+ die(f"--sample-rate must be {SAMPLE_RATE_RANGE[0]}..{SAMPLE_RATE_RANGE[1]} Hz, got {args.sample_rate}")
628
+ if args.channel is not None:
629
+ if args.channel < 0:
630
+ die(f"--channel is a 0-based channel index, got {args.channel}")
631
+ if args.downmix:
632
+ die("--channel and --downmix contradict each other: --channel keeps one channel, --downmix folds them all to stereo")
633
+ if in_channels and args.channel >= in_channels:
634
+ die(f"--channel {args.channel}: the track has {in_channels} channel(s), 0..{in_channels - 1}",
635
+ kind="input", channels=in_channels)
636
+ in_channels = 1 # what every later stage sees: the one channel kept
637
+ if args.stereo_widen is not None:
638
+ if args.mono:
639
+ die("--stereo-widen and --mono contradict each other: there is no stereo image in a 1-channel output")
640
+ # Widening scales the side signal (L-R). Duplicating a mono track to two channels leaves
641
+ # L == R, so the side signal is exactly zero and scaling it changes nothing: --stereo is
642
+ # not a way in, it is a way to a file that measures mono no matter the amount asked for.
643
+ if in_channels == 1:
644
+ die("--stereo-widen needs a real stereo source: mono has no stereo image to widen; keep it mono or "
645
+ "use --stereo to duplicate it, but widening needs a real stereo source")
646
+ if in_channels > 2 and not args.downmix:
647
+ die(f"--stereo-widen needs a stereo track; this input has {in_channels} channels. Add --downmix to fold it "
648
+ "to stereo first (the widening then happens after the downmix), or leave the channels alone.")
649
+
650
+ inputs: List[str] = ["-i", args.input]
651
+ main_src = f"0:a:{args.audio_stream}"
652
+ idx = 1
653
+ if args.replace:
654
+ inputs += ["-i", args.replace]
655
+ main_src = f"{idx}:a:0"
656
+ idx += 1
657
+
658
+ fx: List[str] = []
659
+ if not keep_video:
660
+ # A sound-only output of a track that starts after its file's origin (late against its
661
+ # picture): the lead is written as silence, first, so every stage after it works on the
662
+ # file's clock from 0 (--tempo retimes the lead with the sound). .wav and .flac have no
663
+ # start time and lost it, .m4a kept it as an edit a decoder does not pad, so the
664
+ # extraction played that much early (#539). Beside a copied picture the container holds
665
+ # the start, and nothing is padded.
666
+ if main_track_lead(args, meta):
667
+ fx.append(PAD_SOUND_FROM_ZERO)
668
+ if args.channel is not None:
669
+ # #487: one channel by index, first, so every later stage works on it alone
670
+ fx.append(f"pan=mono|c0=c{args.channel}")
671
+ if args.downmix:
672
+ # ITU-R BS.775: centre and surrounds at -3 dB (0.707), LFE dropped. pan's '<' scales each
673
+ # output so its gains sum to 1 over the channels the input has (1/2.414 on 5.1, 1/3.121 on
674
+ # 7.1), so in-phase channels at full scale cannot clip; '=' summed 2.7x and clipped a loud
675
+ # 5.1 while the run said verified.
676
+ fx.append(DOWNMIX_PAN)
677
+ # A129: a limiter is the ceiling of what is delivered, so with a bed mixed in it runs after the
678
+ # mix: on the voice alone, the music and effects added on top of it peaked over the ceiling
679
+ # (--limit-ceiling -6 delivered 0 dBFS, --voice strong's -1 dBFS -0.2)
680
+ limit_after_mix = bool(args.music or args.effects)
681
+ post_limit: List[str] = []
682
+ if args.voice:
683
+ chain = voice_chain(args.voice, args.denoise_strength if args.denoise else None)
684
+ if limit_after_mix and chain.endswith("," + VOICE_LIMITER):
685
+ chain = chain[: -len("," + VOICE_LIMITER)]
686
+ post_limit.append(VOICE_LIMITER)
687
+ fx.append(chain)
688
+ elif args.denoise:
689
+ fx.append(f"afftdn=nf=-{args.denoise_strength:g}:tn=1")
690
+ if args.gain:
691
+ fx.append(f"volume={args.gain:g}dB")
692
+ if args.gate:
693
+ fx.append(dynamics_filter("agate", args))
694
+ if args.compress:
695
+ fx.append(dynamics_filter("acompressor", args))
696
+ if args.limit:
697
+ (post_limit if limit_after_mix else fx).append(dynamics_filter("alimiter", args))
698
+ if args.mono:
699
+ # after --downmix the track is the stereo fold-down, whatever the source had
700
+ in_ch = 2 if args.downmix else (in_channels or 2)
701
+ if in_ch == 2:
702
+ fx.append("pan=mono|c0=0.5*c0+0.5*c1")
703
+ elif in_ch > 2:
704
+ fx.append("aformat=channel_layouts=mono") # swresample's standard downmix (centre/LFE weighted)
705
+ # 1 channel: already mono; the stereo pan used to halve it (-6 dB) because c1 was silence
706
+ elif args.stereo:
707
+ fx.append("aformat=channel_layouts=stereo")
708
+ if args.stereo_widen is not None:
709
+ # extrastereo widens by scaling the side (L-R) signal: m=1 is the input, m=3 is as wide
710
+ # as it goes before the centre collapses. It runs after the channel layout is settled, so
711
+ # a --downmix 5.1 source is widened on the stereo fold-down rather than on six channels.
712
+ fx.append(f"extrastereo=m={1 + 2 * args.stereo_widen:g}")
713
+ tempo_steps = atempo_steps(args.tempo) if args.tempo is not None and args.tempo != 1.0 else []
714
+ if tempo_steps:
715
+ # led by the samples atempo leaves out, at the rate the track has there (the source's:
716
+ # --sample-rate resamples after the chain), or it opened 21 ms in (#523)
717
+ fx.append(atempo_chain_with_lead([f"{f:.10g}" for f in tempo_steps], main_track_rate(args, meta)))
718
+ # the main track's length in the output: the source's, or the source's / --tempo on an audio
719
+ # output of the input's own sound (beside a picture, or for --replace, it is the picture's)
720
+ main_dur = dur / args.tempo if dur and tempo_steps and not (keep_video or args.replace) else dur
721
+ rate = args.sample_rate or main_track_rate(args, meta)
722
+ # where the output ends, which is where a fade-out has to end: --length-samples when it is
723
+ # given (a fade timed on the source's length sat past the trim and was never heard)
724
+ end_dur = args.length_samples / rate if args.length_samples is not None and rate else main_dur
725
+ if args.length_samples is not None and rate and rate != OPUS_DECODED_RATE and "libopus" in audio_codec_for(output, args.bitrate):
726
+ # An Opus stream decodes at 48 kHz whatever rate went in (a 16 kHz track too), so the
727
+ # decoded track has N * 48000 / rate samples and the count asked for is not the file's
728
+ die(f"--length-samples counts at {rate} Hz, and an Opus output decodes at {OPUS_DECODED_RATE} Hz: "
729
+ f"the file would not hold {args.length_samples} samples",
730
+ kind="input", hint="add --sample-rate 48000 and give the length in 48 kHz samples, or write .wav/.flac")
731
+
732
+ graph: List[str] = []
733
+ graph.append(f"[{main_src}]{','.join(fx) if fx else 'anull'}[main]")
734
+ last = "main"
735
+
736
+ if args.music:
737
+ if args.music_loop:
738
+ inputs += ["-stream_loop", "-1", "-i", args.music]
739
+ else:
740
+ inputs += ["-i", args.music]
741
+ m = f"{idx}:a:0"
742
+ idx += 1
743
+ mfx = [f"volume={args.music_volume:g}dB", f"atrim=0:{main_dur:.6f}" if main_dur else "anull"]
744
+ # A142: a bed shorter than the output (and not looped) stops at its own end, so its fade
745
+ # ends there: timed on the output's end it started after the bed had stopped at full level
746
+ # ... and at the main track's end when the output runs past it (--length-samples): the
747
+ # atrim above has cut the bed there. All three are timestamps, which is what afade reads:
748
+ # a bed whose sound starts late in its file (2 to 5 s) keeps those, so its fade ends at 5,
749
+ # not at its 3 s length (that fade ran over the bed's first second)
750
+ ends = [t for t in (end_dur, main_dur) if t]
751
+ if args.music_fade_out and not args.music_loop and not dry_run_input_pending(args.music):
752
+ bed_meta = probe(args.music)
753
+ bed_stop = stream_end(bed_meta, "audio")
754
+ if bed_stop is not None and bed_stop - file_origin(bed_meta) > 0:
755
+ ends.append(bed_stop - file_origin(bed_meta))
756
+ bed_end = min(ends) if ends else None
757
+ if args.music_fade_out and bed_end:
758
+ # a fade longer than the bed is cut to it, so the bed still ends silent (a 5 s fade on
759
+ # a 2 s bed started at 0 and stopped at 60% gain)
760
+ m_fade = min(args.music_fade_out, bed_end)
761
+ mfx.append(f"afade=t=out:st={bed_end - m_fade:.3f}:d={m_fade:g}")
762
+ graph.append(f"[{m}]{','.join(mfx)}[music]")
763
+ if args.duck:
764
+ graph.append("[main]asplit=2[mainA][sc]")
765
+ graph += duck_graph(args.duck_threshold, args.duck_amount, args.duck_attack, args.duck_release)
766
+ graph.append("[mainA][ducked]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[mix]")
767
+ else:
768
+ graph.append("[main][music]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[mix]")
769
+ last = "mix"
770
+
771
+ if args.effects:
772
+ # A third bed, mixed in at its own level and deliberately never ducked: effects are cut
773
+ # to the picture, so dipping them under speech would move them off their own frames.
774
+ inputs += ["-i", args.effects]
775
+ e = f"{idx}:a:0"
776
+ idx += 1
777
+ efx = [f"volume={args.effects_volume:g}dB", f"atrim=0:{main_dur:.6f}" if main_dur else "anull"]
778
+ graph.append(f"[{e}]{','.join(efx)}[effects]")
779
+ graph.append(f"[{last}][effects]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[mixfx]")
780
+ last = "mixfx"
781
+
782
+ post: List[str] = list(post_limit)
783
+ if args.fade_in:
784
+ post.append(f"afade=t=in:st=0:d={args.fade_in:g}")
785
+ if args.fade_out and end_dur:
786
+ fade_out = min(args.fade_out, end_dur) # cut to the output, so it still ends silent
787
+ post.append(f"afade=t=out:st={end_dur - fade_out:.3f}:d={fade_out:g}")
788
+ # The audio track is conformed to the source duration whenever it is known: padded with
789
+ # silence if the graph came out short, trimmed if long. A mixed track can come out a few
790
+ # hundredths short (amix's dropout_transition, a looped bed's atrim boundary), and with
791
+ # -shortest below that used to shorten the *video* to match: 12.00 s in, 11.925 s out, four
792
+ # frames of a stream-copied picture gone (#164). Padding the audio, not cutting the picture,
793
+ # is the only correct answer for a tool whose contract says the video is never touched.
794
+ if args.sample_rate:
795
+ # #487: resampled after the mix and the fades, ahead of the sample count, which is in this rate
796
+ post.append(f"aresample={args.sample_rate}")
797
+ conform_samples = None
798
+ if args.length_samples is not None:
799
+ # #486: an exact length asked for, counted at the track's rate (unknown only for a dry
800
+ # run's pending input, whose real run pins it)
801
+ conform_samples = args.length_samples
802
+ post.append(conform_filter(conform_samples, rate))
803
+ elif main_dur and (args.replace or args.music or keep_video):
804
+ if rate:
805
+ conform_samples = round(main_dur * rate)
806
+ # counted in samples and ended on the timestamp, so sound that starts after the picture
807
+ # still ends with it (conform_to_length, shared with grid, broll and multicam since #493)
808
+ post.append(conform_to_length(main_dur, rate))
809
+ else:
810
+ # a dry run's pending input: no rate to count in yet; the real run counts samples
811
+ post.append(f"apad,atrim=0:{main_dur:.6f}")
812
+ if post:
813
+ graph.append(f"[{last}]{','.join(post)}[out]")
814
+ last = "out"
815
+
816
+ # the picture is mapped first, so it stays stream 0 as in the source (#470: the sound was 0)
817
+ cmd = ffmpeg_base() + inputs + ["-filter_complex", ";".join(graph)] + (["-map", "0:v:0"] if keep_video else []) + ["-map", f"[{last}]"]
818
+ if keep_video:
819
+ cmd += ["-c:v", "copy"]
820
+ if Path(output).suffix.lower() in (".mp4", ".mov", ".m4v"):
821
+ cmd += ["-movflags", "+faststart"]
822
+ elif has_video:
823
+ cmd += ["-vn"] # audio extension: the picture is dropped, not copied into a container that cannot hold it
824
+ cmd += audio_codec_for(output, args.bitrate)
825
+ if not keep_video:
826
+ # audio-only outputs: a looped music bed is infinite, -shortest ends the run with the main track
827
+ cmd.append("-shortest")
828
+ if keep_video:
829
+ dropped_streams = run_keeping_subtitles(cmd, output)
830
+ else:
831
+ dropped_streams = bool(has_video and (meta.get("subtitle_streams") or meta.get("data_streams")))
832
+ run(cmd + [output])
833
+ r = probe(output, role="output")
834
+ a = r["audio"]
835
+ if r.get("video") and audio_out and not STATE.dry_run:
836
+ die(f"{output} unexpectedly contains a video stream")
837
+ info(f"wrote {output} ({fmt_secs(r['duration'])}, audio {a['codec']} {a['channels']}ch {a['sample_rate']}Hz"
838
+ + (", video stream-copied" if has_video and not audio_out else ", video dropped" if has_video else "") + ")")
839
+ audio_block: Dict[str, Any] = {"voice": args.voice, "stereo_widen": args.stereo_widen,
840
+ "effects": bool(args.effects), "effects_volume": args.effects_volume if args.effects else None}
841
+ if args.music:
842
+ audio_block["music_volume"] = args.music_volume
843
+ audio_block["duck"] = ({"amount_db": args.duck_amount, "threshold_db": round(args.duck_threshold, 4),
844
+ "threshold_linear": float(f"{db_to_linear(args.duck_threshold):.6g}"),
845
+ "ratio": DUCK_GATE_RATIO,
846
+ "attack_ms": args.duck_attack, "release_ms": args.duck_release}
847
+ if args.duck else None)
848
+ verification: List[Dict[str, Any]] = []
849
+ if args.length_samples is not None and not STATE.dry_run:
850
+ verification.append(length_step(output, str(a.get("codec") or ""), args.length_samples))
851
+ if args.sample_rate is not None and not STATE.dry_run:
852
+ verification.append(property_step("sample_rate", args.sample_rate, a.get("sample_rate")))
853
+ if args.channel is not None and not STATE.dry_run:
854
+ verification.append(property_step("channels", 2 if args.stereo else 1, a.get("channels")))
855
+ audio_block["channel"] = args.channel
856
+ audio_block["sample_rate"] = args.sample_rate
857
+ timing_block = {"tempo": args.tempo, "atempo": tempo_steps, "length_samples": args.length_samples,
858
+ "sample_rate": rate or None}
859
+ emit(output, audio=audio_block, timing=timing_block, **({"verification": verification} if verification else {}), video=bool(has_video and not audio_out), audio_stream=args.audio_stream,
860
+ dynamics=[f for f in (args.gate and "agate", args.compress and "acompressor", args.limit and "alimiter") if f],
861
+ dropped_non_av_streams=dropped_streams,
862
+ **({"silent": silent, "notes": notes} if silent else {}))
863
+ return 0
864
+
865
+
866
+ if __name__ == "__main__":
867
+ sys.exit(main())