@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.
- package/README.md +62 -2
- package/cli.mjs +149 -0
- package/lib/dependencies.mjs +384 -0
- package/lib/run.mjs +114 -0
- package/lib/workspace.mjs +167 -0
- package/package.json +240 -3
- package/workspace/.agents/skills/cleoedits/SKILL.md +29 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/audiogram.json +41 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/facebook.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/linkedin.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/podcast.json +23 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/reels.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/shorts.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/tiktok.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/x.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube-shorts.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube.json +48 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/LICENSE-SimpleIcons +30 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/logos.json +1 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Anton-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/ArchivoBlack-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/InstrumentSerif-Italic.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Inter.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/LICENSE-PermanentMarker.txt +202 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Montserrat.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Anton.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-ArchivoBlack.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-InstrumentSerif.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Inter.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Montserrat.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-PlayfairDisplay.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Poppins.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-SpaceMono.txt +93 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PermanentMarker-Regular.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay-Italic.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Black.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Bold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-ExtraBold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/SpaceMono-Bold.ttf +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-MediaPipe +218 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-YuNet +21 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/NOTICE.md +4 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/selfie_segmenter.tflite +0 -0
- package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/yunet.onnx +0 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/LICENSE +21 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/audio-app-ui/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/STYLE.md +53 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/index.html +328 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/index.html +575 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/design-app-ui/STYLE.md +68 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editor-ui/STYLE.md +73 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/STYLE.md +54 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/index.html +189 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/STYLE.md +64 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/index.html +620 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/STYLE.md +55 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/index.html +238 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/STYLE.md +66 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/index.html +602 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/STYLE.md +66 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/index.html +777 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/STYLE.md +56 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/index.html +186 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/motion-app-ui/STYLE.md +68 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/STYLE.md +56 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/index.html +244 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/STYLE.md +67 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/index.html +663 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/STYLE.md +59 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/index.html +395 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/STYLE.md +52 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/index.html +194 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/STYLE.md +58 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/index.html +242 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/STYLE.md +53 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/index.html +138 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/studio.js +57 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/STYLE.md +63 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/index.html +599 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/STYLE.md +65 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/index.html +1297 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/STYLE.md +69 -0
- package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/index.html +674 -0
- package/workspace/.agents/skills/cleoedits/references/audio-clearervoice-elevenlabs.md +11 -0
- package/workspace/.agents/skills/cleoedits/references/ffmpeg-and-reels.md +15 -0
- package/workspace/.agents/skills/cleoedits/references/hyperframes-workflows.md +13 -0
- package/workspace/.agents/skills/cleoedits/references/kdenlive-cli-and-mcp.md +12 -0
- package/workspace/.agents/skills/cleoedits/references/motion-design-pipeline.md +7 -0
- package/workspace/.agents/skills/cleoedits/references/motion-taste-emil.md +5 -0
- package/workspace/.agents/skills/cleoedits/references/playwright-demo-capture.md +9 -0
- package/workspace/.agents/skills/cleoedits/references/remotion-workflows.md +13 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/LICENSE +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_ass_overlay.py +399 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/__init__.py +235 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/alpha.py +560 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/asr.py +1237 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/color.py +540 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/decision.py +2452 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/drawtext.py +290 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emit.py +1309 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emoji.py +518 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/fonts.py +875 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing.py +263 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing_edit.py +432 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/probe.py +1613 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/runner.py +3994 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/text.py +73 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/timeline.py +721 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/wrap.py +981 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_contract.py +2454 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_platforms.py +258 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.html +754 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.py +258 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_smartcut.py +450 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/audio.py +867 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/background.py +136 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/batch.py +1409 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/broll.py +282 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/caption.py +2207 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/check.py +815 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/color.py +695 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/crop.py +91 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cropdetect.py +214 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cut.py +2076 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/deinterlace.py +90 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/denoise.py +94 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/export.py +1033 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/fit.py +729 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/freeze.py +197 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/graphics.py +920 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/grid.py +235 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/insert.py +142 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/join.py +1083 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/look.py +475 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loop.py +395 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loudness.py +397 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/metadata.py +416 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/multicam.py +414 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/overlay.py +766 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/pad.py +121 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/probe.py +145 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/proxy.py +93 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/redact.py +162 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/render.py +2424 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/report.py +354 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/reverse.py +114 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/scenes.py +439 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sequence.py +285 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/silence.py +945 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/speedramp.py +193 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sphere.py +137 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/stabilize.py +141 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/straighten.py +120 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sync.py +500 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/verify.py +411 -0
- package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/waveform.py +502 -0
- package/workspace/.agents/skills/cleoedits/scripts/kdenlive_builder.py +284 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-claude-motion +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-motion-design +21 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/_media.py +43 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/pacing_check.py +90 -0
- package/workspace/.agents/skills/cleoedits/scripts/motion/storyboard.py +77 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/LICENSE +26 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/fx.py +2717 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/logos.py +194 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/sfx.py +105 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/trim.py +99 -0
- package/workspace/.agents/skills/cleoedits/scripts/reel_effects/words.py +60 -0
- package/workspace/.claude/commands/blender-3d.md +12 -0
- package/workspace/.claude/commands/business-short-form-reels.md +12 -0
- package/workspace/.claude/commands/color-grade.md +12 -0
- package/workspace/.claude/commands/cutout-grid-reel.md +12 -0
- package/workspace/.claude/commands/depth-ui-reel.md +12 -0
- package/workspace/.claude/commands/explainer-panel-reel.md +12 -0
- package/workspace/.claude/commands/freeze-frame.md +12 -0
- package/workspace/.claude/commands/glass-graph.md +12 -0
- package/workspace/.claude/commands/over-the-shoulder.md +12 -0
- package/workspace/.claude/commands/personal-short-form-reels.md +12 -0
- package/workspace/.claude/commands/ranking-format.md +12 -0
- package/workspace/.claude/commands/relight.md +12 -0
- package/workspace/.claude/commands/reverse-engineer.md +12 -0
- package/workspace/.claude/commands/text-behind.md +12 -0
- package/workspace/.claude/commands/tier-list.md +12 -0
- package/workspace/.claude-plugin/plugin.json +8 -0
- package/workspace/.npmignore +15 -0
- package/workspace/AGENTS.md +30 -0
- package/workspace/README.md +63 -0
- package/workspace/assets/fonts/TikTokSans-OFL.txt +93 -0
- package/workspace/assets/fonts/TikTokSans-Variable.ttf +0 -0
- package/workspace/assets/luts/clean_warm.cube +4917 -0
- package/workspace/assets/luts/golden_hour.cube +4917 -0
- package/workspace/assets/luts/moody_dark.cube +4917 -0
- package/workspace/assets/luts/teal_orange.cube +4917 -0
- package/workspace/assets/sfx/NOTICE.txt +1 -0
- package/workspace/assets/sfx/click.wav +0 -0
- package/workspace/assets/sfx/pop.wav +0 -0
- package/workspace/assets/sfx/riser.wav +0 -0
- package/workspace/assets/sfx/whoosh.wav +0 -0
- package/workspace/generators/hyperframes/index.html +39 -0
- package/workspace/generators/hyperframes/package.json +15 -0
- package/workspace/generators/hyperframes/pnpm-lock.yaml +1181 -0
- package/workspace/generators/hyperframes/pnpm-workspace.yaml +10 -0
- package/workspace/generators/remotion/eslint.config.mjs +3 -0
- package/workspace/generators/remotion/package.json +36 -0
- package/workspace/generators/remotion/pnpm-lock.yaml +4179 -0
- package/workspace/generators/remotion/pnpm-workspace.yaml +10 -0
- package/workspace/generators/remotion/remotion.config.ts +13 -0
- package/workspace/generators/remotion/src/Root.tsx +52 -0
- package/workspace/generators/remotion/src/index.css +1 -0
- package/workspace/generators/remotion/src/index.ts +4 -0
- package/workspace/generators/remotion/tsconfig.json +15 -0
- package/workspace/pipeline/scripts/_codec.py +28 -0
- package/workspace/pipeline/scripts/ai_media_api.py +109 -0
- package/workspace/pipeline/scripts/blender_render.py +166 -0
- package/workspace/pipeline/scripts/composite.py +49 -0
- package/workspace/pipeline/scripts/melt.sh +68 -0
- package/workspace/pipeline/scripts/normalize_audio.py +39 -0
- package/workspace/pipeline/scripts/person_matte.py +216 -0
- package/workspace/pipeline/scripts/record_demo.py +69 -0
- package/workspace/pipeline/scripts/whisper_cut.py +98 -0
- package/workspace-manifest.json +908 -0
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Composite a logo/image or a text title onto a video with position, timing,
|
|
3
|
+
opacity and fade in/out.
|
|
4
|
+
|
|
5
|
+
Positions: top-left, top, top-right, left, center, right, bottom-left, bottom,
|
|
6
|
+
bottom-right, or explicit "X,Y" pixels (negative counts from the far edge).
|
|
7
|
+
|
|
8
|
+
--video composites a second VIDEO as a picture-in-picture layer (position,
|
|
9
|
+
scale, opacity, time-range -- same knobs as --image), instead of a still
|
|
10
|
+
image or text. --place SRC_START-SRC_END@AT (repeatable, with --video) shows only
|
|
11
|
+
that range of the layer, starting at AT on the main timeline: one pass lays
|
|
12
|
+
several pieces of a layer (say, graphics rendered back to back) at their own
|
|
13
|
+
times, and the main picture shows untouched everywhere else. Only the main input's audio is kept; the PiP layer's own
|
|
14
|
+
audio track, if any, is dropped -- mixing two audio tracks is a job for
|
|
15
|
+
audio.py, not this tool. --chromakey COLOR (with --video) turns that colour
|
|
16
|
+
transparent first (green-screen removal) before compositing.
|
|
17
|
+
|
|
18
|
+
Examples:
|
|
19
|
+
python3 overlay.py input.mp4 --image logo.png --position top-right --scale 200 --opacity 0.8
|
|
20
|
+
python3 overlay.py input.mp4 --image lower_third.png --position bottom-left --start 2 --end 8 --fade 0.5
|
|
21
|
+
python3 overlay.py input.mp4 --text "Episode 12" --position bottom --font-size 48 --start 1 --end 5 --fade 0.3
|
|
22
|
+
python3 overlay.py input.mp4 --text "こんにちは" --font-file /path/NotoSansCJK-Bold.ttc --box
|
|
23
|
+
python3 overlay.py input.mp4 --video webcam.mp4 --position bottom-right --scale 480 --opacity 0.9
|
|
24
|
+
python3 overlay.py bg.mp4 --video greenscreen.mp4 --chromakey 0x00ff00 --chromakey-similarity 0.15
|
|
25
|
+
python3 overlay.py talk.mp4 --video cues.mov --position 0,0 --margin 0 --place 0-2.5@12 --place 2.5-6@40
|
|
26
|
+
python3 overlay.py canvas.mov --image logo.png --position center --keep-alpha -o logo_layer.mov
|
|
27
|
+
|
|
28
|
+
A VP9 --video layer stored with an alpha layer (a WebM from export.py --preset vp9-alpha) is decoded
|
|
29
|
+
with libvpx-vp9, so its transparency reaches the composite (FFmpeg's own VP9 decoder drops it).
|
|
30
|
+
"""
|
|
31
|
+
import argparse
|
|
32
|
+
import ast
|
|
33
|
+
import re
|
|
34
|
+
import sys
|
|
35
|
+
from typing import Any, Dict, List, Optional
|
|
36
|
+
|
|
37
|
+
from _platforms import PLATFORMS, PLATFORM_CHOICES, safe_margins_px, resolve as resolve_platform
|
|
38
|
+
from _common import still_input_args # noqa: E402
|
|
39
|
+
from _common import STATE, script_font_for_text, drawtext_clean, drawtext_line_metrics, drawtext_text_opts, drawtext_draws_newline_glyph, is_multiline, needs_shaping, LANGUAGE_NAMES, has_emoji, detect_script, emoji_clusters, load_brand, drawn_chain, label_chain, layer_base_chain, matrix_chain, overlay_format, range_chain, rgb_chain_to_bt709, video_args, add_common, apply_common, emit, aac_args, cfr_args, cfr_filter, cfr_at_input, with_cfr, default_output, die, escape_drawtext, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, X264_PRESETS, time_arg, fmt_secs
|
|
40
|
+
from _common.emit import note, warn
|
|
41
|
+
from _common.color import is_rgb
|
|
42
|
+
from _common.decision import length_output_t, window_expr, windowed_overlay_x
|
|
43
|
+
from _common.alpha import (add_alpha_args, audio_line, check_alpha_args, decoder_args_for, default_ext, finish_chain,
|
|
44
|
+
has_alpha_plane, report as alpha_report, source_alpha, source_format, tag_args, video_line)
|
|
45
|
+
from _common.probe import display_size, refuse_not_a_still, square_pixels, square_pixels_note
|
|
46
|
+
from _common.drawtext import shaping_refusal
|
|
47
|
+
from _common.wrap import wrap_text
|
|
48
|
+
from _common import text_width_em, refuse_output_is_input
|
|
49
|
+
from _common.fonts import font_choice, record_font_choice, require_font_file
|
|
50
|
+
from _common import drawtext_fontfile # noqa: E402
|
|
51
|
+
|
|
52
|
+
# Per-edge margins: a platform's UI does not cover the same fraction of every edge (TikTok's
|
|
53
|
+
# like column is 14 % of the width, its description block 22 % of the height), so a position
|
|
54
|
+
# names the edges it is measured from rather than one --margin for all four.
|
|
55
|
+
POS = {
|
|
56
|
+
"top-left": ("{left}", "{top}"),
|
|
57
|
+
"top": ("(W-w)/2", "{top}"),
|
|
58
|
+
"top-right": ("W-w-{right}", "{top}"),
|
|
59
|
+
"left": ("{left}", "(H-h)/2"),
|
|
60
|
+
"center": ("(W-w)/2", "(H-h)/2"),
|
|
61
|
+
"right": ("W-w-{right}", "(H-h)/2"),
|
|
62
|
+
"bottom-left": ("{left}", "H-h-{bottom}"),
|
|
63
|
+
"bottom": ("(W-w)/2", "H-h-{bottom}"),
|
|
64
|
+
"bottom-right": ("W-w-{right}", "H-h-{bottom}"),
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def position_exprs(pos: str, margin: int, text_mode: bool, margins: Optional[dict] = None):
|
|
69
|
+
edges = margins or {}
|
|
70
|
+
m = {edge: int(edges.get(edge, margin)) for edge in ("top", "bottom", "left", "right")}
|
|
71
|
+
if pos in POS:
|
|
72
|
+
x, y = (e.format(**m) for e in POS[pos])
|
|
73
|
+
else:
|
|
74
|
+
try:
|
|
75
|
+
xs, ys = pos.split(",")
|
|
76
|
+
xv, yv = int(xs), int(ys)
|
|
77
|
+
except ValueError:
|
|
78
|
+
die(f"bad --position '{pos}': use X,Y in pixels or one of {', '.join(POS)}")
|
|
79
|
+
x = f"W-w{xv}" if xv < 0 else str(xv)
|
|
80
|
+
y = f"H-h{yv}" if yv < 0 else str(yv)
|
|
81
|
+
if text_mode:
|
|
82
|
+
# drawtext uses w/h for the text box but lower-case main dims differ: W/H -> w/h, w/h -> text_w/text_h
|
|
83
|
+
x = x.replace("W", "main_w").replace("w", "text_w").replace("H", "main_h").replace("h", "text_h")
|
|
84
|
+
y = y.replace("W", "main_w").replace("w", "text_w").replace("H", "main_h").replace("h", "text_h")
|
|
85
|
+
x = x.replace("main_text_w", "main_w").replace("main_text_h", "main_h")
|
|
86
|
+
y = y.replace("main_text_w", "main_w").replace("main_text_h", "main_h")
|
|
87
|
+
return x, y
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _scaled_height(w: int, src_w: int, src_h: int, factor: int) -> int:
|
|
91
|
+
"""The height scale=W:-1 (factor 1) or scale=W:-2 (factor 2) gives a src_w x src_h picture:
|
|
92
|
+
av_rescale(w, ih, iw * factor) * factor, rounded half away from zero as FFmpeg rounds it."""
|
|
93
|
+
den = src_w * factor
|
|
94
|
+
return max(factor, (2 * w * src_h + den) // (2 * den) * factor)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def on_grid(x: str, y: str, main: "tuple", layer: "tuple") -> "Optional[tuple]":
|
|
98
|
+
"""Where the layer goes so its top-left pixel is at (x, y) in luma, x and y being the overlay
|
|
99
|
+
expressions position_exprs() gives, as overlay evaluates them (the integer part).
|
|
100
|
+
|
|
101
|
+
overlay places a layer on a 4:2:0 picture on the chroma grid: an odd x or y is taken down to
|
|
102
|
+
the even one before it (#512: --position 11,13 drew the logo at 10,12, and a centred or
|
|
103
|
+
right-aligned layer whose position came out odd moved the same way). So the layer gets one
|
|
104
|
+
transparent column/row on the left/top where x/y is odd, and is overlaid at the even position
|
|
105
|
+
before it: its luma lands where it was asked, and the chroma sample on that edge is shared
|
|
106
|
+
with the pixel outside it. Returns (x_even, y_even, pad filter or ""), or None when a size is
|
|
107
|
+
unknown (a dry run's pending input): the overlay then gets the expressions, as before."""
|
|
108
|
+
(mw, mh), (lw, lh) = main, layer
|
|
109
|
+
if not (mw and mh and lw and lh):
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
def arith(node: Any) -> float:
|
|
113
|
+
# the four operations on whole numbers position_exprs() writes, and nothing else
|
|
114
|
+
if isinstance(node, ast.Expression):
|
|
115
|
+
return arith(node.body)
|
|
116
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, int):
|
|
117
|
+
return float(node.value)
|
|
118
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
|
|
119
|
+
return -arith(node.operand) if isinstance(node.op, ast.USub) else arith(node.operand)
|
|
120
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)):
|
|
121
|
+
a, b = arith(node.left), arith(node.right)
|
|
122
|
+
return {ast.Add: a + b, ast.Sub: a - b, ast.Mult: a * b}.get(type(node.op), a / b if b else 0.0)
|
|
123
|
+
raise ValueError(f"not a position: {ast.dump(node)}")
|
|
124
|
+
|
|
125
|
+
def value(expr: str, big: int, small: int, axis: str) -> Optional[int]:
|
|
126
|
+
num = re.sub(axis.upper(), str(big), re.sub(axis, str(small), expr))
|
|
127
|
+
try:
|
|
128
|
+
return int(arith(ast.parse(num, mode="eval"))) # the integer part, as overlay's (int) cast takes it
|
|
129
|
+
except (SyntaxError, ValueError):
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
px, py = value(x, mw, lw, "w"), value(y, mh, lh, "h")
|
|
133
|
+
if px is None or py is None:
|
|
134
|
+
return None
|
|
135
|
+
ox, oy = px & 1, py & 1 # two's complement: -3 is one column right of -4
|
|
136
|
+
pad = f"pad=iw+{ox}:ih+{oy}:{ox}:{oy}:color=black@0" if ox or oy else ""
|
|
137
|
+
return px - ox, py - oy, pad
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _wrap_to_frame(args, frame_w: int, margins: Optional[dict], frame_h: int = 0) -> str:
|
|
141
|
+
"""--text broken into lines that fit between the frame's side margins at --font-size, by the
|
|
142
|
+
same phrase rules graphics.py and caption.py wrap with; text that fits comes back unchanged.
|
|
143
|
+
drawtext never wraps, so through 3.1.3 a long line ran off the frame with no word (#411). The
|
|
144
|
+
width is the averaged advance table's estimate, so a wrapped run says so in its notes."""
|
|
145
|
+
text = args.text or ""
|
|
146
|
+
if not (frame_w and text and args.font_size > 0):
|
|
147
|
+
return text
|
|
148
|
+
m = {edge: int((margins or {}).get(edge, args.margin)) for edge in ("left", "right")}
|
|
149
|
+
left, right = m["left"], m["right"]
|
|
150
|
+
if args.position not in POS:
|
|
151
|
+
try:
|
|
152
|
+
xv = int(args.position.split(",")[0])
|
|
153
|
+
left, right = (xv, right) if xv >= 0 else (0, -xv)
|
|
154
|
+
except ValueError:
|
|
155
|
+
pass
|
|
156
|
+
inset = 2 * args.border + (24 if args.box else 0) # the border on both sides, boxborderw=12
|
|
157
|
+
room = frame_w - left - right - inset
|
|
158
|
+
if room <= args.font_size:
|
|
159
|
+
# a position this close to the edge leaves no room to wrap in: say the text runs off
|
|
160
|
+
# rather than draw it past the edge without a word (#416 review)
|
|
161
|
+
if max(text_width_em(ln) for ln in text.split("\n")) * args.font_size > max(room, 0):
|
|
162
|
+
note(f"--text does not fit: --position {args.position} leaves {max(room, 0)} px to the frame's edge "
|
|
163
|
+
f"at --font-size {args.font_size}, so the text runs past it")
|
|
164
|
+
return text
|
|
165
|
+
lines: List[str] = []
|
|
166
|
+
for para in text.split("\n"):
|
|
167
|
+
lines.extend(wrap_text(para, room / float(args.font_size), lang=getattr(args, "lang", None),
|
|
168
|
+
slice_overlong=True) if para.strip() else [para])
|
|
169
|
+
wrapped = "\n".join(lines)
|
|
170
|
+
if wrapped != text:
|
|
171
|
+
note(f"--text is wider than the frame at --font-size {args.font_size} "
|
|
172
|
+
f"({frame_w} px, {left}/{right} px margins): wrapped to {len(lines)} lines")
|
|
173
|
+
# the wrap only measures width: a block taller than the frame loses the lines past its
|
|
174
|
+
# edge (at a bottom position, the first ones), so that is said too (#416 review)
|
|
175
|
+
tall = args.font_size + (len(lines) - 1) * int(args.font_size * 1.2)
|
|
176
|
+
if frame_h and tall > frame_h:
|
|
177
|
+
note(f"the {len(lines)} wrapped lines are about {tall} px tall, taller than the {frame_h} px frame: "
|
|
178
|
+
f"the lines past its edge are not drawn -- lower --font-size or shorten --text")
|
|
179
|
+
return wrapped
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def enable_expr(start: Optional[float], end: Optional[float], meta: Optional[dict] = None) -> str:
|
|
183
|
+
"""True on the main picture's frames from --start to --end, both inclusive (window_expr):
|
|
184
|
+
the bounds sit half a frame from the frames they select, not on a frame's own time."""
|
|
185
|
+
if start is None and end is None:
|
|
186
|
+
return ""
|
|
187
|
+
return window_expr(start, end, meta)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def fade_out_length(start: float, end: float, fade: float) -> float:
|
|
191
|
+
"""The fade-out of a layer shown from `start` to `end`: --fade, cut to the window when the window
|
|
192
|
+
is shorter, so the fade still ends at `end` (audio.py and cut.py cap theirs the same way)."""
|
|
193
|
+
return min(fade, end - start)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def alpha_expr(opacity: float, start: Optional[float], end: Optional[float], fade: float) -> str:
|
|
197
|
+
"""Time-varying alpha with linear fade in/out inside [start, end]."""
|
|
198
|
+
if fade <= 0 or (start is None and end is None):
|
|
199
|
+
return f"{opacity:g}"
|
|
200
|
+
s = start if start is not None else 0.0
|
|
201
|
+
parts = [f"{opacity:g}"]
|
|
202
|
+
fin = f"min(1,(t-{s:.3f})/{fade:g})"
|
|
203
|
+
parts.append(fin)
|
|
204
|
+
if end is not None and end > s:
|
|
205
|
+
parts.append(f"min(1,({end:.3f}-t)/{fade_out_length(s, end, fade):g})")
|
|
206
|
+
return "max(0," + "*".join(parts) + ")"
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _num(v: float) -> str:
|
|
210
|
+
"""A measured pixel value as an expression literal (no exponent form)."""
|
|
211
|
+
return f"{v:.6f}".rstrip("0").rstrip(".")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def per_line_drawtext(lines: List[str], x: str, y: str, font_opt: str, args: argparse.Namespace,
|
|
215
|
+
box: List[str], timing: List[str]) -> str:
|
|
216
|
+
"""The drawtext chain for a multi-line --text on a release whose drawtext draws a box at each
|
|
217
|
+
line break (drawtext_draws_newline_glyph): one drawtext per line, each line alone, placed
|
|
218
|
+
where one multi-line drawtext puts it on a fixed release.
|
|
219
|
+
|
|
220
|
+
That block's layout is drawtext's own (measure_text/draw_text): text_w is the widest line,
|
|
221
|
+
text_h = lh*(lines-1) + the first line's top_a + the last line's bottom_d, the lines are
|
|
222
|
+
left-aligned at x, and line i's baseline is y + top_a + i*lh. Each line is measured alone
|
|
223
|
+
(drawtext_line_metrics), so the box the bug adds is in no number; x and y keep the caller's
|
|
224
|
+
position expressions with text_w/text_h replaced by the block's values, and each line is
|
|
225
|
+
drawn with y_align=baseline at its own baseline. The outlines of every line are drawn before
|
|
226
|
+
any line's text, as one drawtext draws them, so a descender's outline never covers the next
|
|
227
|
+
line's glyphs; the --box is drawn once, by the first line, at the block's size (boxw/boxh).
|
|
228
|
+
Bit-identical to one multi-line drawtext on 8.1.3 for every named position, with and without
|
|
229
|
+
--box; a font whose glyph boxes are not whole pixels (no hinting) can sit one row lower, since
|
|
230
|
+
drawtext reports top_a rounded up."""
|
|
231
|
+
m = drawtext_line_metrics(lines, font_opt, args.font_size)
|
|
232
|
+
seen = [d for d in m if d]
|
|
233
|
+
lh = seen[0]["lh"]
|
|
234
|
+
width = max(d["w"] for d in seen)
|
|
235
|
+
# an empty first/last line has no glyphs: drawtext's -32000/64 start values, as it measures them
|
|
236
|
+
top = m[0]["top"] if m[0] else -500.0
|
|
237
|
+
bottom = m[-1]["bottom"] if m[-1] else -500.0
|
|
238
|
+
height = lh * (len(lines) - 1) + top + bottom
|
|
239
|
+
|
|
240
|
+
def block(expr: str) -> str:
|
|
241
|
+
return re.sub(r"\btext_h\b", _num(height), re.sub(r"\btext_w\b", _num(width), expr))
|
|
242
|
+
|
|
243
|
+
bx, by = block(x), block(y)
|
|
244
|
+
passes = ([[f"borderw={args.border}", f"bordercolor={args.border_color}", "fontcolor=black@0"],
|
|
245
|
+
["fontcolor=" + args.font_color]] if args.border else [["fontcolor=" + args.font_color]])
|
|
246
|
+
filters = []
|
|
247
|
+
for n, paint in enumerate(passes):
|
|
248
|
+
for i, line in enumerate(lines):
|
|
249
|
+
if not line:
|
|
250
|
+
continue
|
|
251
|
+
opts = [drawtext_text_opts(line), f"fontsize={args.font_size}", f"x={bx}", f"y={by}+{_num(top + i * lh)}",
|
|
252
|
+
"y_align=baseline", font_opt] + paint + timing[:1]
|
|
253
|
+
if box and n == 0 and not filters:
|
|
254
|
+
opts += box + [f"boxw={_num(width)}", f"boxh={_num(height)}"]
|
|
255
|
+
filters.append("drawtext=" + ":".join(opts + timing[1:]))
|
|
256
|
+
return ",".join(filters)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
# one time inside --place: seconds, mm:ss, hh:mm:ss.ms or hh:mm:ss:ff with an optional @fps
|
|
260
|
+
# suffix (the time grammar's own); times are never negative, so '-' only separates the range
|
|
261
|
+
_PLACE_TIME = r"[^@\-]+(?:@[0-9.]+)?"
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def parse_placements(specs: List[str], main_fps: Optional[float], layer_fps: Optional[float],
|
|
265
|
+
layer_meta: Optional[dict] = None, main_meta: Optional[dict] = None) -> List[tuple]:
|
|
266
|
+
"""--place SRC_START-SRC_END@AT -> [(src_start, src_end, at)], refusing empty, negative or
|
|
267
|
+
overlapping placements (two pieces on screen at once would stack in an order nobody asked for).
|
|
268
|
+
SRC_START/SRC_END are positions in the layer, so an hh:mm:ss:ff timecode there counts the
|
|
269
|
+
layer's frames; AT is a position on the main timeline and counts the main video's."""
|
|
270
|
+
out = []
|
|
271
|
+
for spec in specs:
|
|
272
|
+
m = re.fullmatch(rf"\s*({_PLACE_TIME})-({_PLACE_TIME})@({_PLACE_TIME})\s*", spec)
|
|
273
|
+
if not m:
|
|
274
|
+
die(f"--place {spec!r}: use SRC_START-SRC_END@AT, e.g. 0-2.5@12 (times are not negative)")
|
|
275
|
+
a = time_arg(m.group(1), "--place", layer_fps, source=layer_meta)
|
|
276
|
+
b = time_arg(m.group(2), "--place", layer_fps, source=layer_meta)
|
|
277
|
+
at = time_arg(m.group(3), "--place", main_fps, source=main_meta)
|
|
278
|
+
if b <= a:
|
|
279
|
+
die(f"--place {spec!r}: the layer range ends before it starts")
|
|
280
|
+
out.append((a, b, at))
|
|
281
|
+
spans = sorted((at, at + (b - a)) for a, b, at in out)
|
|
282
|
+
for (s1, e1), (s2, _e2) in zip(spans, spans[1:]):
|
|
283
|
+
if s2 < e1 - 1e-6:
|
|
284
|
+
die(f"--place: pieces overlap on the main timeline ({s1:g}-{e1:g} s and from {s2:g} s)")
|
|
285
|
+
return out
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def main() -> int:
|
|
289
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
290
|
+
ap.add_argument("input")
|
|
291
|
+
ap.add_argument("-o", "--output", help="output file (default: <name>_overlay.<ext>)")
|
|
292
|
+
ap.add_argument("--audio-stream", type=int, default=0,
|
|
293
|
+
help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "
|
|
294
|
+
"audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "
|
|
295
|
+
"the first track, same as leaving it unset always did")
|
|
296
|
+
src = ap.add_mutually_exclusive_group()
|
|
297
|
+
src.add_argument("--image", help="PNG/JPG (alpha respected) to composite")
|
|
298
|
+
src.add_argument("--text", help="text to draw (drawtext)")
|
|
299
|
+
src.add_argument("--logo", action="store_true", help="composite the brand logo from --brand (position/scale/opacity from brand.json)")
|
|
300
|
+
src.add_argument("--video", help="a second video to composite as a picture-in-picture layer")
|
|
301
|
+
ap.add_argument("--place", action="append", default=[], metavar="SRC_START-SRC_END@AT",
|
|
302
|
+
help="with --video, repeatable: show this range of the layer starting at AT on the main "
|
|
303
|
+
"timeline (e.g. 0-2.5@12); the layer is hidden outside its placed ranges. Times in "
|
|
304
|
+
"seconds or HH:MM:SS. Not with --start/--end/--fade")
|
|
305
|
+
ck = ap.add_argument_group("chroma key (with --video)")
|
|
306
|
+
ck.add_argument("--chromakey", help="colour to key out (green-screen removal), e.g. 0x00ff00 or green")
|
|
307
|
+
ck.add_argument("--chromakey-similarity", type=float, default=0.15, help="how close a pixel must be to --chromakey to become transparent, 0..1 (default 0.15)")
|
|
308
|
+
ck.add_argument("--chromakey-blend", type=float, default=0.05, help="soften the key edge, 0..1 (default 0.05)")
|
|
309
|
+
ap.add_argument("--brand", help="brand.json (logo, font, colours, safe margin)")
|
|
310
|
+
ap.add_argument("--position", default="top-right", help="named position or X,Y (default top-right)")
|
|
311
|
+
ap.add_argument("--margin", type=int, default=24, help="margin from the edges in px (default 24)")
|
|
312
|
+
ap.add_argument("--platform", choices=PLATFORM_CHOICES, default=None,
|
|
313
|
+
help="keep the overlay out of this destination's UI: each edge's margin becomes that "
|
|
314
|
+
"platform's safe zone (scripts/_platforms.py), so a top-left logo clears TikTok's "
|
|
315
|
+
"status bar and a right-hand one clears the like column. An explicit --margin wins")
|
|
316
|
+
ap.add_argument("--start", help="show from this time (default: whole video)")
|
|
317
|
+
ap.add_argument("--end", help="hide after this time")
|
|
318
|
+
ap.add_argument("--fade", type=float, default=0.0, help="fade-in duration in seconds (at --start or 0); the fade-out happens only at --end")
|
|
319
|
+
ap.add_argument("--opacity", type=float, default=1.0, help="0..1 (default 1)")
|
|
320
|
+
img = ap.add_argument_group("image options")
|
|
321
|
+
img.add_argument("--scale", type=int, help="width in px for an image, logo or video layer (keeps aspect); text size is --font-size")
|
|
322
|
+
img.add_argument("--scale-percent", type=float,
|
|
323
|
+
help="width as a %% of the displayed frame for an image, logo or video layer (keeps aspect); "
|
|
324
|
+
"a 90 or 270 degree rotation uses the stored height; text size is --font-size")
|
|
325
|
+
txt = ap.add_argument_group("text options")
|
|
326
|
+
txt.add_argument("--font", default="DejaVu Sans", help="fontconfig font name")
|
|
327
|
+
txt.add_argument("--font-file", help="explicit .ttf/.otf/.ttc path (use this for CJK fonts)")
|
|
328
|
+
txt.add_argument("--font-size", type=int, default=42, help="text size in px, 1..2000 (default 42)")
|
|
329
|
+
txt.add_argument("--font-color", default="white", help="text colour (default white)")
|
|
330
|
+
txt.add_argument("--border", type=int, default=2, help="text outline width (default 2)")
|
|
331
|
+
txt.add_argument("--border-color", default="black", help="text outline colour (default black)")
|
|
332
|
+
txt.add_argument("--box", action="store_true", help="draw a translucent box behind the text")
|
|
333
|
+
emo = ap.add_argument_group("emoji (1.15)")
|
|
334
|
+
emo.add_argument("--emoji", choices=["auto", "color", "png", "mono", "none"], default="auto",
|
|
335
|
+
help="how emoji in --text are drawn. overlay.py draws through drawtext, which cannot load "
|
|
336
|
+
"a colour emoji font at all, so only 'mono'/'none' render here -- 'png'/'color' name "
|
|
337
|
+
"caption.py/graphics.py instead")
|
|
338
|
+
emo.add_argument("--emoji-assets", metavar="DIR", help="directory of emoji PNGs named by code point "
|
|
339
|
+
"(used by caption.py/graphics.py; overlay.py has no PNG route)")
|
|
340
|
+
emo.add_argument("--emoji-scale", type=float, default=1.0, help="emoji box as a multiple of the font size")
|
|
341
|
+
emo.add_argument("--emoji-max", type=int, default=60, help="most emoji overlays one run may build")
|
|
342
|
+
txt.add_argument("--box-color", default="black@0.5", help="colour of the --box behind the text, optionally @alpha (default black@0.5)")
|
|
343
|
+
enc = ap.add_argument_group("encoding")
|
|
344
|
+
enc.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
|
|
345
|
+
enc.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
|
|
346
|
+
add_alpha_args(ap)
|
|
347
|
+
add_common(ap)
|
|
348
|
+
args = ap.parse_args()
|
|
349
|
+
apply_common(args)
|
|
350
|
+
|
|
351
|
+
brand = load_brand(args.brand)
|
|
352
|
+
if args.logo:
|
|
353
|
+
if not brand.get("logo"):
|
|
354
|
+
die("--logo needs a brand.json with a 'logo' entry")
|
|
355
|
+
args.image = brand["logo"]
|
|
356
|
+
if args.position == ap.get_default("position"):
|
|
357
|
+
args.position = brand.get("logo_position", "top-right")
|
|
358
|
+
if args.scale is None and args.scale_percent is None: # a given 0 is refused below, not replaced
|
|
359
|
+
args.scale = int(brand.get("logo_scale", 160))
|
|
360
|
+
if args.opacity == 1.0:
|
|
361
|
+
args.opacity = float(brand.get("logo_opacity", 1.0))
|
|
362
|
+
if args.text is not None and not args.text.strip():
|
|
363
|
+
die("--text is blank -- give the words to draw", kind="input")
|
|
364
|
+
if not (args.image or args.text or args.video):
|
|
365
|
+
die("give --image, --text, --logo or --video")
|
|
366
|
+
# --scale is a layer width. On a text draw it used to be accepted and ignored (fontsize stayed
|
|
367
|
+
# at --font-size), so a project that asked for 200 px text completed with the 42 px default.
|
|
368
|
+
if args.text and not (args.image or args.video) and (args.scale is not None or args.scale_percent is not None):
|
|
369
|
+
die("--scale and --scale-percent size an image, logo or video layer; text size is --font-size", kind="input")
|
|
370
|
+
font_file_from = "--font-file" # what the refusal of a font file that is not one names
|
|
371
|
+
if args.brand:
|
|
372
|
+
if args.margin == ap.get_default("margin"):
|
|
373
|
+
args.margin = int(brand.get("safe_margin", args.margin))
|
|
374
|
+
if args.font == ap.get_default("font"):
|
|
375
|
+
args.font = brand.get("font", args.font)
|
|
376
|
+
if not args.font_file and brand.get("font_file"):
|
|
377
|
+
args.font_file = brand["font_file"]
|
|
378
|
+
font_file_from = "the --brand file's font_file"
|
|
379
|
+
if args.text:
|
|
380
|
+
# 1.15: drawtext never reorders or re-clusters (no harfbuzz), so Devanagari matras and
|
|
381
|
+
# Thai/Lao mark stacking come out wrong on EVERY build. A wrong frame is not a delivery:
|
|
382
|
+
# refuse and name the two tools that render the script correctly through libass.
|
|
383
|
+
_sc = detect_script(args.text, getattr(args, "lang", None))
|
|
384
|
+
if needs_shaping(_sc):
|
|
385
|
+
die(f"{LANGUAGE_NAMES.get(_sc, _sc)} text {shaping_refusal(_sc)}: draw it with "
|
|
386
|
+
"caption.py (--text cues, burned through libass) or graphics.py (--template with "
|
|
387
|
+
"--text-render ass) instead", kind="input")
|
|
388
|
+
if has_emoji(args.text):
|
|
389
|
+
if args.emoji in ("png", "color"):
|
|
390
|
+
die(f"--emoji {args.emoji}: overlay.py draws text with drawtext, which cannot load a colour "
|
|
391
|
+
"emoji font and cannot place a PNG inside a line -- use caption.py (--emoji-assets) for "
|
|
392
|
+
"cues or graphics.py (--template) for a title card", kind="input")
|
|
393
|
+
if args.emoji == "none":
|
|
394
|
+
for _i, _cl in list(reversed(emoji_clusters(args.text))):
|
|
395
|
+
args.text = args.text[:_i] + args.text[_i + len(_cl):]
|
|
396
|
+
warn("emoji: stripped from the drawn text (--emoji none)", "emoji_stripped", mode="none")
|
|
397
|
+
else:
|
|
398
|
+
# not "drawn by the text font": drawtext loads that one font and has no fallback, so
|
|
399
|
+
# a font without the glyph (DejaVu Sans, every script font) draws an empty box (#403)
|
|
400
|
+
warn("emoji are left to the text font here: drawtext loads that one font and has no fallback, so "
|
|
401
|
+
"a font without the glyph draws an empty box (monochrome at best with one). --emoji none "
|
|
402
|
+
"leaves them out; caption.py/graphics.py composite colour PNGs with --emoji-assets",
|
|
403
|
+
"emoji_monochrome")
|
|
404
|
+
if args.text and args.font_file:
|
|
405
|
+
require_font_file(args.font_file, font_file_from)
|
|
406
|
+
script_file = script_family = None
|
|
407
|
+
if args.text and not args.font_file:
|
|
408
|
+
# 1.12: non-Latin overlay text picks a font by script, so a title in Japanese, Korean,
|
|
409
|
+
# Arabic ... draws glyphs instead of boxes. drawtext does not shape or reorder RTL text --
|
|
410
|
+
# see references/gotchas.md#fonts-by-script.
|
|
411
|
+
_script, script_file, script_family = script_font_for_text(
|
|
412
|
+
args.text, font=args.font, font_explicit=args.font != ap.get_default("font"), font_file=args.font_file)
|
|
413
|
+
# the font drawtext gets, reported as `font_used` and recorded when it is not the one asked for
|
|
414
|
+
font_used = font_choice(args.font, font_file=args.font_file, script_file=script_file, script_family=script_family)
|
|
415
|
+
args.font_file = font_used["file"]
|
|
416
|
+
if args.text:
|
|
417
|
+
record_font_choice(font_used)
|
|
418
|
+
meta = probe(args.input)
|
|
419
|
+
if not meta.get("video"):
|
|
420
|
+
die("input has no video stream")
|
|
421
|
+
# --keep-alpha: composited onto the main input's alpha (a transparent canvas from background.py
|
|
422
|
+
# --transparent, or any alpha clip) and written in an alpha line with the source's tags kept
|
|
423
|
+
alpha_codec = check_alpha_args(args, args.output)
|
|
424
|
+
src_alpha = source_alpha(args, meta, args.input)
|
|
425
|
+
audio_streams = meta.get("audio_streams") or []
|
|
426
|
+
if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):
|
|
427
|
+
die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")
|
|
428
|
+
if args.audio_stream and not audio_streams:
|
|
429
|
+
die("--audio-stream needs an input with audio streams")
|
|
430
|
+
# the -t that ends a layer at the main input's length: to the sample of the kept track when the
|
|
431
|
+
# millisecond would cut it (length_output_t); no sound, or a pending input, keeps the millisecond
|
|
432
|
+
kept_track = audio_streams[args.audio_stream] if audio_streams else (meta.get("audio") or {})
|
|
433
|
+
main_t = length_output_t(meta["duration"], kept_track.get("sample_rate")) if meta.get("duration") else None
|
|
434
|
+
# ffmpeg applies display rotation before the filter graph, so the frame this overlay is
|
|
435
|
+
# composited on is the displayed one. A 320x180 phone file tagged 90 degrees is 180 wide here.
|
|
436
|
+
# A non-square-pixel source is made square at its display aspect first (#411), so a logo or
|
|
437
|
+
# a line of text is not drawn stretched by the player's SAR.
|
|
438
|
+
vw, vh = display_size(meta["video"])
|
|
439
|
+
square = square_pixels(meta["video"])
|
|
440
|
+
if square:
|
|
441
|
+
note(square_pixels_note(meta["video"]))
|
|
442
|
+
# --platform: the edges this destination's own UI covers, in pixels of this frame. An
|
|
443
|
+
# explicit --margin (or a brand safe_margin, applied above) is the more specific statement
|
|
444
|
+
# and wins; without either, the historical 24 px default is unchanged.
|
|
445
|
+
safe_margins = None
|
|
446
|
+
args.platform = resolve_platform(args.platform)
|
|
447
|
+
if args.platform and args.margin == ap.get_default("margin") and PLATFORMS[args.platform].get("frame"):
|
|
448
|
+
# a dry run has no real frame to measure (the probe is stubbed rather than guessed), so
|
|
449
|
+
# fall back to the destination's own delivery frame -- which is what the fitted
|
|
450
|
+
# intermediate this stage runs on will be anyway
|
|
451
|
+
frame = PLATFORMS[args.platform]["frame"]
|
|
452
|
+
pw, ph = vw or frame["w"], vh or frame["h"]
|
|
453
|
+
safe_margins = safe_margins_px(args.platform, pw, ph)
|
|
454
|
+
info(f"--platform {args.platform}: safe margins top {safe_margins['top']} / bottom {safe_margins['bottom']} / "
|
|
455
|
+
f"left {safe_margins['left']} / right {safe_margins['right']} px (clear of the app's own UI)")
|
|
456
|
+
fps = meta["video"].get("fps")
|
|
457
|
+
start = time_arg(args.start, "--start", fps) if args.start else None
|
|
458
|
+
end = time_arg(args.end, "--end", fps) if args.end else None
|
|
459
|
+
if start is not None and end is not None and end <= start:
|
|
460
|
+
die("--end must be after --start")
|
|
461
|
+
main_len = (meta.get("video") or {}).get("duration") or meta.get("duration")
|
|
462
|
+
if start is not None and main_len and start >= main_len:
|
|
463
|
+
# A172: an overlay that starts after the picture ends draws nothing, and the run said
|
|
464
|
+
# verified: true; --place already refuses the same case
|
|
465
|
+
die(f"--start {start:g} is at or after the end of the video ({main_len:.3f} s): nothing would be drawn",
|
|
466
|
+
hint="give a --start inside the clip")
|
|
467
|
+
# A190: a size of 0 or below drew nothing (--font-size -10 completed, verified: true, with no
|
|
468
|
+
# text in the picture; --scale -1 is ffmpeg's "keep the size") and a negative fade was no fade
|
|
469
|
+
if args.scale is not None and args.scale < 1:
|
|
470
|
+
die(f"--scale must be a positive width in px, got {args.scale}")
|
|
471
|
+
if args.scale_percent is not None and args.scale_percent <= 0:
|
|
472
|
+
die(f"--scale-percent must be more than 0, got {args.scale_percent:g}")
|
|
473
|
+
if args.fade < 0:
|
|
474
|
+
die(f"--fade must be 0 or more seconds, got {args.fade:g}")
|
|
475
|
+
if args.border < 0:
|
|
476
|
+
die(f"--border must be 0 or more px, got {args.border}")
|
|
477
|
+
if args.chromakey and not args.video:
|
|
478
|
+
die("--chromakey needs --video")
|
|
479
|
+
if args.chromakey:
|
|
480
|
+
validate_color(args.chromakey, "--chromakey")
|
|
481
|
+
validate_color(args.font_color, "--font-color")
|
|
482
|
+
validate_color(args.border_color, "--border-color")
|
|
483
|
+
validate_color(args.box_color, "--box-color")
|
|
484
|
+
if not 0 < args.chromakey_similarity <= 1:
|
|
485
|
+
die("--chromakey-similarity must be within (0, 1]")
|
|
486
|
+
if args.place and not args.video:
|
|
487
|
+
die("--place needs --video")
|
|
488
|
+
if args.place and (args.start or args.end or args.fade):
|
|
489
|
+
die("--place sets when each piece shows: drop --start / --end / --fade")
|
|
490
|
+
if args.video and args.fade:
|
|
491
|
+
# A171: the fade is built for an image, logo or text layer; a video layer was composited
|
|
492
|
+
# with a hard edge and the result said nothing
|
|
493
|
+
die(f"--fade {args.fade:g} fades an image, logo or text layer; a video layer (--video) is shown "
|
|
494
|
+
"from --start to --end without a fade", hint="drop --fade for the video layer")
|
|
495
|
+
|
|
496
|
+
output = args.output or default_output(args.input, "overlay", default_ext(alpha_codec) if alpha_codec else None)
|
|
497
|
+
# the brand file and a text layer's font file are read here and by drawtext's fontfile=, never
|
|
498
|
+
# as an -i, so run()'s guard did not see them (#522's sweep)
|
|
499
|
+
refuse_output_is_input(output, *[q for q in (args.brand, args.font_file if args.text else None) if isinstance(q, str) and q])
|
|
500
|
+
enable = enable_expr(start, end, meta)
|
|
501
|
+
cmd = ffmpeg_base() + ["-i", args.input]
|
|
502
|
+
|
|
503
|
+
if args.image:
|
|
504
|
+
image_meta = probe(args.image)
|
|
505
|
+
refuse_not_a_still(args.image, image_meta, "--image",
|
|
506
|
+
"--video composites a moving layer; `look.py FILE --at T` writes one frame of it as a PNG")
|
|
507
|
+
chain: List[str] = ["format=rgba"]
|
|
508
|
+
# a still that stores non-square pixels (a PNG's pHYs, a JPEG's density) is made square at
|
|
509
|
+
# its display aspect first, as a --video layer is: its size and position are computed in
|
|
510
|
+
# that frame, and placed from it at its stored size a 100x100 PNG at SAR 2:1 drew 100 px
|
|
511
|
+
# wide at x=120 of a 320 px main for top-right, 100 px short of the edge
|
|
512
|
+
if square_pixels(image_meta.get("video")):
|
|
513
|
+
chain.append(square_pixels(image_meta.get("video")))
|
|
514
|
+
note(square_pixels_note(image_meta.get("video"), "the --image"))
|
|
515
|
+
iw, ih = display_size(image_meta.get("video"))
|
|
516
|
+
lw = int(vw * args.scale_percent / 100) if args.scale_percent else args.scale or iw
|
|
517
|
+
lh = _scaled_height(lw, iw, ih, 1) if lw != iw and iw and ih else ih
|
|
518
|
+
if args.scale_percent:
|
|
519
|
+
chain.append(f"scale={lw}:-1")
|
|
520
|
+
elif args.scale:
|
|
521
|
+
chain.append(f"scale={args.scale}:-1")
|
|
522
|
+
if args.opacity < 1:
|
|
523
|
+
chain.append(f"colorchannelmixer=aa={args.opacity:g}")
|
|
524
|
+
if args.fade > 0:
|
|
525
|
+
# no --start: fade in at 0. The fade-out only exists when --end names a moment the
|
|
526
|
+
# overlay leaves; without --end it stays to the last frame ("fade in at the start" is
|
|
527
|
+
# the common ask, and a matching fade-out at the very end surprised every eval run)
|
|
528
|
+
s = start if start is not None else 0.0
|
|
529
|
+
chain.append(f"fade=t=in:st={s:.3f}:d={args.fade:g}:alpha=1")
|
|
530
|
+
if end is not None and end > s:
|
|
531
|
+
# a fade-out longer than the layer's window is cut to it, so the layer still leaves
|
|
532
|
+
# at --end fully faded (#517: with --end at or before --fade it was left out, and the
|
|
533
|
+
# layer vanished at full opacity); the text layer's alpha_expr() caps it the same way
|
|
534
|
+
out = fade_out_length(s, end, args.fade)
|
|
535
|
+
chain.append(f"fade=t=out:st={end - out:.3f}:d={out:g}:alpha=1")
|
|
536
|
+
x, y = position_exprs(args.position, args.margin, text_mode=False, margins=safe_margins)
|
|
537
|
+
grid = on_grid(x, y, (vw, vh), (lw, lh))
|
|
538
|
+
if grid:
|
|
539
|
+
# padded in RGBA, where a one-pixel offset is exact, before the layer is made YUV
|
|
540
|
+
x, y = grid[0], grid[1]
|
|
541
|
+
chain += [grid[2]] if grid[2] else []
|
|
542
|
+
# a 10-bit main on a 10-bit line is composited at 10 bits in YUV: format=auto with an RGBA
|
|
543
|
+
# still took the whole picture through 8-bit RGB (overlay_format)
|
|
544
|
+
# a --start/--end window is in the layer's position, which is evaluated on the main
|
|
545
|
+
# picture's frames; overlay's enable is evaluated on the layer's frames too
|
|
546
|
+
ov = f"overlay={windowed_overlay_x(x, enable) if enable else x}:{y}" + (overlay_format(meta) or ":format=auto")
|
|
547
|
+
if not meta.get("duration"):
|
|
548
|
+
# nothing to bound by -t: the overlay ends with the main picture. -shortest alone never
|
|
549
|
+
# ended a still main (one picture, no duration): overlay kept repeating it under the
|
|
550
|
+
# looped layer and the run went on until its timeout (#510)
|
|
551
|
+
ov += ":shortest=1"
|
|
552
|
+
# -loop 1 turns the still into a timed stream so fade/enable expressions see real timestamps
|
|
553
|
+
cmd = ffmpeg_base() + ["-i", args.input, "-loop", "1", *still_input_args(args.image), "-i", args.image]
|
|
554
|
+
# the RGBA still is converted to the BT.709 the output is tagged with (overlay's own
|
|
555
|
+
# RGB-to-YUV step used BT.601), and an untagged main is labelled BT.709 (tags only) so
|
|
556
|
+
# 7.1+'s negotiation does not convert one picture to the other's "unknown" matrix
|
|
557
|
+
base = layer_base_chain(meta)
|
|
558
|
+
fc = (f"[1:v]{','.join(chain)},setpts=PTS-STARTPTS{rgb_chain_to_bt709(meta)}[ov];"
|
|
559
|
+
+ (f"[0:v]{base}null[base];[base]" if base else "[0:v]") + f"[ov]{ov}[out]")
|
|
560
|
+
cmd += ["-filter_complex", fc, "-map", "[out]", "-map", f"0:a:{args.audio_stream}?"]
|
|
561
|
+
if meta.get("duration"):
|
|
562
|
+
# An explicit -t is exact and, unlike -shortest, only bounds the *main* input's
|
|
563
|
+
# streams -- a preserved subtitle/data stream that ends earlier (run_keeping_subtitles)
|
|
564
|
+
# must not be allowed to cut the whole output short via -shortest's "stop at whichever
|
|
565
|
+
# mapped stream finishes first" semantics.
|
|
566
|
+
cmd += ["-t", main_t]
|
|
567
|
+
else:
|
|
568
|
+
# No known duration to bound by -t (e.g. probe found no video duration): -shortest is
|
|
569
|
+
# the only thing stopping the looped still from running forever. FFmpeg 7+'s
|
|
570
|
+
# shortest_buf_duration slack (up to 10s) is an accepted imprecision here since there is
|
|
571
|
+
# no better bound available.
|
|
572
|
+
cmd += ["-shortest"]
|
|
573
|
+
elif args.video:
|
|
574
|
+
pip_meta = probe(args.video)
|
|
575
|
+
if not pip_meta.get("video"):
|
|
576
|
+
die(f"--video {args.video} has no video stream")
|
|
577
|
+
layer_fps = pip_meta["video"].get("fps")
|
|
578
|
+
placements = parse_placements(args.place, fps, layer_fps, pip_meta, meta) if args.place else []
|
|
579
|
+
# bounds from the video streams (a longer audio track would let a range run past the last
|
|
580
|
+
# picture); the container duration only when a stream has none
|
|
581
|
+
layer_dur = pip_meta["video"].get("duration") or pip_meta.get("duration")
|
|
582
|
+
main_dur = meta["video"].get("duration") or meta.get("duration")
|
|
583
|
+
# half a layer frame of slack absorbs a hand-typed end that rounds the last frame's end
|
|
584
|
+
# (2.033 for 61 frames at 30 fps); anything longer asks for pictures the layer does not have
|
|
585
|
+
slack = 0.5 / layer_fps if layer_fps else 0.02
|
|
586
|
+
for a, b, at in placements:
|
|
587
|
+
if layer_dur and a >= layer_dur:
|
|
588
|
+
# the slack below is for an end rounded past the last frame; a start there selects
|
|
589
|
+
# no picture at all and the "placed" piece would silently never show
|
|
590
|
+
die(f"--place {a:g}-{b:g}@{at:g}: starts at or after the layer's end ({layer_dur:.3f} s)")
|
|
591
|
+
if layer_dur and b > layer_dur + slack:
|
|
592
|
+
die(f"--place {a:g}-{b:g}@{at:g}: the layer is only {layer_dur:.3f} s long")
|
|
593
|
+
if main_dur and at >= main_dur:
|
|
594
|
+
die(f"--place {a:g}-{b:g}@{at:g}: starts after the main video ends ({main_dur:.3f} s)")
|
|
595
|
+
chain = [square_pixels(pip_meta["video"])] if square_pixels(pip_meta["video"]) else []
|
|
596
|
+
iw, ih = display_size(pip_meta["video"])
|
|
597
|
+
lw = int(vw * args.scale_percent / 100) if args.scale_percent else args.scale or iw
|
|
598
|
+
lh = _scaled_height(lw, iw, ih, 2) if (args.scale_percent or args.scale) and iw and ih else ih
|
|
599
|
+
if args.scale_percent:
|
|
600
|
+
chain.append(f"scale={lw}:-2")
|
|
601
|
+
elif args.scale:
|
|
602
|
+
chain.append(f"scale={args.scale}:-2")
|
|
603
|
+
# an alpha line composites at 4:4:4: the layer is not taken through 4:2:0 on the way
|
|
604
|
+
# a 10-bit layer over a main overlay_format() composites at 10 bits stays 10-bit
|
|
605
|
+
deep = bool(overlay_format(meta)) and (pip_meta["video"].get("bit_depth") or 8) > 8
|
|
606
|
+
keyed_601 = False
|
|
607
|
+
if alpha_codec and is_rgb(pip_meta) and rgb_chain_to_bt709(meta):
|
|
608
|
+
# an RGB layer (qtrle, PNG in .mov) on an alpha line that is BT.709 (a BT.709-tagged
|
|
609
|
+
# main, or an RGB main on a ProRes 4444/VP9 line): matrix_chain() converts nothing on
|
|
610
|
+
# an alpha line, so the layer became YUV with FFmpeg's BT.601 default and pure red
|
|
611
|
+
# read FF1800 under the line's tag (#496's sweep)
|
|
612
|
+
pal = "format=rgba," if pip_meta["video"].get("pix_fmt") == "pal8" else ""
|
|
613
|
+
if args.chromakey:
|
|
614
|
+
# chromakey turns its RGB key into YUV with BT.601 whatever the frames say, so the
|
|
615
|
+
# layer is keyed as BT.601 YUV (what it was before #496, and what the key is
|
|
616
|
+
# computed in) and taken to the line's BT.709 after the key
|
|
617
|
+
chain.append(pal + "scale=out_color_matrix=bt601:out_range=tv,format=yuva444p")
|
|
618
|
+
keyed_601 = True
|
|
619
|
+
else:
|
|
620
|
+
chain.append(pal + rgb_chain_to_bt709(meta).lstrip(","))
|
|
621
|
+
else:
|
|
622
|
+
chain.append("format=yuva444p" if alpha_codec else "format=yuva420p10le" if deep else "format=yuva420p")
|
|
623
|
+
if args.chromakey:
|
|
624
|
+
chain.append(f"chromakey={args.chromakey}:{args.chromakey_similarity:g}:{args.chromakey_blend:g}")
|
|
625
|
+
if keyed_601:
|
|
626
|
+
chain.append("scale=in_color_matrix=bt601:out_color_matrix=bt709:in_range=tv:out_range=tv,format=yuva444p")
|
|
627
|
+
if args.opacity < 1:
|
|
628
|
+
# the alpha is scaled in YUV: colorchannelmixer takes RGB only, so FFmpeg converted the
|
|
629
|
+
# layer to RGB and overlay=format=auto then composited the whole main picture in RGB,
|
|
630
|
+
# which came back BT.601 under the BT.709 tag (#333's defect, on this path)
|
|
631
|
+
chain.append(f"lut=y=val:u=val:v=val:a=val*{args.opacity:g}")
|
|
632
|
+
x, y = position_exprs(args.position, args.margin, text_mode=False, margins=safe_margins)
|
|
633
|
+
grid = on_grid(x, y, (vw, vh), (lw, lh))
|
|
634
|
+
if grid:
|
|
635
|
+
x, y = grid[0], grid[1]
|
|
636
|
+
if grid[2]:
|
|
637
|
+
# padded at 4:4:4, where a one-pixel offset is exact; overlay takes the layer back
|
|
638
|
+
# to the main's 4:2:0 on its own grid, as the layer is now aligned with it
|
|
639
|
+
if not any(c.endswith("yuva444p") or c.endswith("yuva444p10le") for c in chain):
|
|
640
|
+
chain.append("format=yuva444p10le" if deep else "format=yuva444p")
|
|
641
|
+
chain.append(grid[2])
|
|
642
|
+
# a --start/--end window is in the layer's position, which is evaluated on the main
|
|
643
|
+
# picture's frames; overlay's enable is evaluated on the layer's frames too
|
|
644
|
+
ov = f"overlay={windowed_overlay_x(x, enable) if enable else x}:{y}" + (overlay_format(meta) or ":format=auto")
|
|
645
|
+
# a VP9 layer stored with an alpha layer is decoded with libvpx-vp9: FFmpeg's own decoder
|
|
646
|
+
# drops the alpha, and the layer covered the picture as an opaque rectangle
|
|
647
|
+
cmd = ffmpeg_base() + ["-i", args.input] + decoder_args_for(pip_meta, args.video) + ["-i", args.video]
|
|
648
|
+
# both pictures converted by their own colour tags to the BT.709 the output is tagged with;
|
|
649
|
+
# beside a converted one an untagged one gets its BT.709 label, tags only, so 7.1+'s
|
|
650
|
+
# overlay does not convert one to the other's "unknown" (BT.601) matrix
|
|
651
|
+
base, pip = matrix_chain(meta, meta), matrix_chain(pip_meta, meta)
|
|
652
|
+
if pip and has_alpha_plane(pip_meta, args.video):
|
|
653
|
+
# an RGB layer with alpha (qtrle, PNG in .mov, a graphics.py/background.py alpha line) is
|
|
654
|
+
# converted to BT.709 YUV with its alpha plane: the 4:4:4 the conversion ends in had none,
|
|
655
|
+
# and the layer covered the picture as an opaque rectangle
|
|
656
|
+
pip = pip.replace("format=yuv444p", "format=yuva444p")
|
|
657
|
+
# an untagged picture is labelled beside a converted one, and beside a tagged one too: FFmpeg
|
|
658
|
+
# 8.0's overlay negotiates one colorspace for both inputs, and a BT.709-tagged main under an
|
|
659
|
+
# untagged PiP was converted to the PiP's "unknown" (BT.601) matrix, away from the PiP too
|
|
660
|
+
# (C03028 at 80/110/192 came back 88/103/192 on 8.0.1). Two untagged pictures agree as they are.
|
|
661
|
+
def tagged(m: Dict[str, Any]) -> bool:
|
|
662
|
+
return ((m.get("video") or {}).get("color_space") or "unknown") not in ("unknown", "unspecified")
|
|
663
|
+
if base or pip or tagged(meta) != tagged(pip_meta):
|
|
664
|
+
base, pip = base or label_chain(meta, meta), pip or label_chain(pip_meta, meta)
|
|
665
|
+
# overlay mixes samples: a full-range picture is taken to limited range (#410)
|
|
666
|
+
base, pip = base + range_chain(meta, meta), pip + range_chain(pip_meta, meta)
|
|
667
|
+
if placements:
|
|
668
|
+
# each placed piece: its range of the layer, re-timed to start at AT; eof_action=pass shows
|
|
669
|
+
# the main picture untouched once a piece ends (the default would freeze its last frame)
|
|
670
|
+
pieces = len(placements)
|
|
671
|
+
# trim selects by timestamp: start the layer's at 0 so SRC_START/SRC_END count from its
|
|
672
|
+
# first picture even when its video stream starts later than the file (audio first)
|
|
673
|
+
fc = f"[1:v]setpts=PTS-STARTPTS,{pip}{','.join(chain)},split={pieces}" + "".join(f"[p{i}]" for i in range(pieces)) + ";"
|
|
674
|
+
for i, (a, b, at) in enumerate(placements):
|
|
675
|
+
fc += f"[p{i}]trim=start={a:.6f}:end={b:.6f},setpts=PTS-STARTPTS+{at:.6f}/TB[q{i}];"
|
|
676
|
+
prev = f"[0:v]{base}null[m]" if base else None
|
|
677
|
+
if prev:
|
|
678
|
+
fc += prev + ";"
|
|
679
|
+
cur = "[m]" if base else "[0:v]"
|
|
680
|
+
for i in range(pieces):
|
|
681
|
+
nxt = "[out]" if i == pieces - 1 else f"[m{i}]"
|
|
682
|
+
fc += f"{cur}[q{i}]{ov}:eof_action=pass{nxt}" + ("" if i == pieces - 1 else ";")
|
|
683
|
+
cur = nxt
|
|
684
|
+
else:
|
|
685
|
+
fc = (f"[1:v]{pip}{','.join(chain)}[ov];"
|
|
686
|
+
+ (f"[0:v]{base}null[base];[base]" if base else "[0:v]") + f"[ov]{ov}[out]")
|
|
687
|
+
cmd += ["-filter_complex", fc, "-map", "[out]", "-map", f"0:a:{args.audio_stream}?"]
|
|
688
|
+
if meta.get("duration"):
|
|
689
|
+
# See the --image branch above: -t (exact, bounds only the main input) instead of
|
|
690
|
+
# -shortest (would also stop at a preserved subtitle/data stream that ends earlier).
|
|
691
|
+
cmd += ["-t", main_t]
|
|
692
|
+
else:
|
|
693
|
+
cmd += ["-shortest"]
|
|
694
|
+
else:
|
|
695
|
+
args.text = _wrap_to_frame(args, vw, safe_margins, vh)
|
|
696
|
+
x, y = position_exprs(args.position, args.margin, text_mode=True, margins=safe_margins)
|
|
697
|
+
# 1.15: the text goes in a FILE with expansion off, so `'` and `%` survive verbatim
|
|
698
|
+
# (they used to be dropped by escape_drawtext) and no character can reach the graph parser.
|
|
699
|
+
font_opt = (drawtext_fontfile(args.font_file) if args.font_file
|
|
700
|
+
else f"font='{escape_drawtext(args.font)}'")
|
|
701
|
+
alpha = alpha_expr(args.opacity, start if start is not None else (0.0 if args.fade > 0 else None), end, args.fade)
|
|
702
|
+
timing = ([f"alpha='{alpha}'"] if alpha != "1" else []) + ([f"enable='{enable}'"] if enable else [])
|
|
703
|
+
box = ["box=1", f"boxcolor={args.box_color}", "boxborderw=12"] if args.box else []
|
|
704
|
+
if is_multiline(args.text) and drawtext_draws_newline_glyph():
|
|
705
|
+
# this release's drawtext draws the font's missing-glyph box at every line break and
|
|
706
|
+
# counts it in text_w: one drawtext per line, placed where one block would put it
|
|
707
|
+
drawing = per_line_drawtext(drawtext_clean(args.text).split("\n"), x, y, font_opt, args, box, timing)
|
|
708
|
+
else:
|
|
709
|
+
opts = [drawtext_text_opts(args.text), f"fontsize={args.font_size}", f"x={x}", f"y={y}",
|
|
710
|
+
f"borderw={args.border}", f"bordercolor={args.border_color}", font_opt,
|
|
711
|
+
f"fontcolor={args.font_color}"] + timing[:1] + box + timing[1:]
|
|
712
|
+
drawing = "drawtext=" + ":".join(opts)
|
|
713
|
+
# a font/border/box colour with chroma lands in the BT.709 the output is tagged with
|
|
714
|
+
colours = [args.font_color] + ([args.border_color] if args.border else []) + ([args.box_color] if args.box else [])
|
|
715
|
+
cmd += ["-vf", (square + "," if square else "") + drawn_chain(drawing, meta, colours), "-map", "0:v:0"]
|
|
716
|
+
if meta.get("audio"):
|
|
717
|
+
cmd += ["-map", f"0:a:{args.audio_stream}"]
|
|
718
|
+
|
|
719
|
+
if square and "-filter_complex" in cmd:
|
|
720
|
+
i = cmd.index("-filter_complex") + 1
|
|
721
|
+
cmd[i] = f"[0:v]{square}[sq];" + cmd[i].replace("[0:v]", "[sq]")
|
|
722
|
+
if alpha_codec:
|
|
723
|
+
# the main picture keeps its alpha plane at 4:4:4, every layer is overlaid at 4:4:4 (overlay
|
|
724
|
+
# composites the alpha when the main picture has one) and drawtext draws into the alpha too;
|
|
725
|
+
# the line's pixel format ends the graph so nothing after it can drop the plane
|
|
726
|
+
finish = finish_chain(alpha_codec, args.alpha_mode, meta)
|
|
727
|
+
first = cmd.index("-i")
|
|
728
|
+
cmd[first:first] = decoder_args_for(meta, args.input)
|
|
729
|
+
if "-filter_complex" in cmd:
|
|
730
|
+
i = cmd.index("-filter_complex") + 1
|
|
731
|
+
cmd[i] = (f"[0:v]{source_format(meta)}[ka0];" + cmd[i].replace("[0:v]", "[ka0]").replace(":format=auto", ":format=yuv444")
|
|
732
|
+
+ f";[out]{finish}[ka_v]")
|
|
733
|
+
cmd[cmd.index("[out]")] = "[ka_v]"
|
|
734
|
+
else:
|
|
735
|
+
i = cmd.index("-vf") + 1
|
|
736
|
+
cmd[i] = f"{source_format(meta)},{cmd[i]},{finish}"
|
|
737
|
+
cmd += video_line(alpha_codec) + tag_args(meta) + cfr_args(meta)
|
|
738
|
+
cmd += audio_line(alpha_codec) if meta.get("audio") else ["-an"]
|
|
739
|
+
if STATE.hw:
|
|
740
|
+
note(f"--hw: --alpha-codec {alpha_codec} stays on the CPU (no VideoToolbox encoder writes it with its alpha)")
|
|
741
|
+
else:
|
|
742
|
+
cmd += video_args(meta, args.crf, args.preset, convert_matrix=not args.video) + cfr_args(meta)
|
|
743
|
+
cmd += aac_args() if meta.get("audio") else ["-an"]
|
|
744
|
+
if cfr_filter(meta):
|
|
745
|
+
# the conform of a VFR source is the fps filter (in a graph, on the main picture as it is
|
|
746
|
+
# decoded): the encoder line's -fps_mode cfr alone let a frame run up to two frames late (#512)
|
|
747
|
+
if "-filter_complex" in cmd:
|
|
748
|
+
i = cmd.index("-filter_complex") + 1
|
|
749
|
+
cmd[i] = cfr_at_input(cmd[i], meta)
|
|
750
|
+
else:
|
|
751
|
+
i = cmd.index("-vf") + 1
|
|
752
|
+
cmd[i] = with_cfr(cmd[i], meta)
|
|
753
|
+
dropped_streams = run_keeping_subtitles(cmd, output)
|
|
754
|
+
if not STATE.dry_run:
|
|
755
|
+
result = probe(output, role="output")
|
|
756
|
+
info(f"wrote {output} ({fmt_secs(result['duration'])})")
|
|
757
|
+
extra = {"dropped_non_av_streams": dropped_streams, **({"font_used": font_used} if args.text else {})}
|
|
758
|
+
# a layer adds coverage: with --keep-alpha the written alpha is at or above the main input's in
|
|
759
|
+
# every frame; without it, an output that lost the main input's used alpha fails the `alpha` step
|
|
760
|
+
alpha_report(args, alpha_codec, src_alpha, output, extra, composite=True)
|
|
761
|
+
emit(output, **extra)
|
|
762
|
+
return 0
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
if __name__ == "__main__":
|
|
766
|
+
sys.exit(main())
|