@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,1033 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Export with delivery presets. Scales/pads to the preset's frame (keeping
|
|
3
|
+
the source aspect inside it), constrains duration where the platform does,
|
|
4
|
+
sets BT.709 tags, and picks sensible codecs/bitrates.
|
|
5
|
+
|
|
6
|
+
Presets:
|
|
7
|
+
youtube 1920x1080 H.264 CRF 18 high profile, AAC 192k, 48 kHz, faststart
|
|
8
|
+
youtube4k 3840x2160 H.264 CRF 18, AAC 192k
|
|
9
|
+
reels 1080x1920 9:16 H.264 CRF 20, AAC 128k, max 90 s (Instagram Reels)
|
|
10
|
+
tiktok 1080x1920 9:16 H.264 CRF 20, AAC 128k, max 600 s
|
|
11
|
+
shorts 1080x1920 9:16 H.264 CRF 20, AAC 128k, max 180 s (YouTube Shorts)
|
|
12
|
+
linkedin 1080x1080 1:1 H.264 CRF 20, AAC 128k, max 600 s
|
|
13
|
+
facebook 1920x1080 16:9 H.264 CRF 21, AAC 128k
|
|
14
|
+
youtube-hdr HEVC Main10 keeping the source's HDR10/HLG tags (refuses an SDR source)
|
|
15
|
+
youtube-av1 1080p AV1 (libsvtav1, libaom fallback); missing_tool when neither is built
|
|
16
|
+
x 1280x720 H.264 CRF 22, AAC 128k, max 140 s (Twitter/X)
|
|
17
|
+
prores ProRes 422 HQ .mov, PCM 16-bit audio (editing master)
|
|
18
|
+
dnxhr-lb / dnxhr-sq / dnxhr-hq DNxHR 8-bit 4:2:2 .mov, PCM 16-bit audio
|
|
19
|
+
dnxhr-hqx DNxHR HQX 10-bit 4:2:2; dnxhr-444 DNxHR 444 10-bit 4:4:4
|
|
20
|
+
(editing masters at the source's size and rate, like prores)
|
|
21
|
+
key-fill fill + key pair (<out>, <out stem>_key.mov) from an alpha source
|
|
22
|
+
prores4444 / prores4444xq / qtrle / vp9-alpha / hap-alpha
|
|
23
|
+
masters that keep the source's alpha (refused without one);
|
|
24
|
+
--alpha-mode straight|premultiplied; alpha read back after
|
|
25
|
+
h265 HEVC CRF 24 (libx265) with hvc1 tag for Apple compatibility
|
|
26
|
+
gif 480px wide palette-optimised GIF at 12 fps (short previews)
|
|
27
|
+
copy stream copy, no re-encode: same codecs, container and colour
|
|
28
|
+
tags as the source (a delivery target with nothing to change)
|
|
29
|
+
|
|
30
|
+
Examples:
|
|
31
|
+
python3 export.py final.mp4 --preset youtube
|
|
32
|
+
python3 export.py final.mp4 --preset reels --fit crop
|
|
33
|
+
python3 export.py final.mp4 --preset reels --no-normalize # report the loudness, deliver the sound as it is
|
|
34
|
+
python3 export.py final.mp4 --preset prores -o master.mov
|
|
35
|
+
python3 export.py final.mp4 --preset dnxhr-hq -o master.mov
|
|
36
|
+
python3 export.py final.mp4 --preset copy -o delivered.mp4
|
|
37
|
+
python3 export.py --list
|
|
38
|
+
"""
|
|
39
|
+
import argparse
|
|
40
|
+
import json
|
|
41
|
+
import math
|
|
42
|
+
import re
|
|
43
|
+
import os
|
|
44
|
+
import sys
|
|
45
|
+
import tempfile
|
|
46
|
+
from fractions import Fraction
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
from typing import Dict, List, Optional
|
|
49
|
+
|
|
50
|
+
from _common.runner import carried_stream_maps, child_exit_code, fail_if_classified, kept_clause, mark_delivered
|
|
51
|
+
from _common.color import bt709_matrix_filter, hdr_rgb_matrix_args, hdr_rgb_matrix_filter
|
|
52
|
+
from _common import STATE, run_analysis, add_common, apply_common, bt709_label_filter, bt709_matrix_args, bt709_tag_args, child_args, emit, cfr_args, cfr_filter, default_output, die, encoder_args, ffmpeg_base, info, probe, require_tool, run, run_tool, validate_color, pad_filters, add_pad_fill_args, fmt_secs
|
|
53
|
+
from _common.decision import chain_with_rate, enlarge_args, hdr_tag_args, warn_mostly_cropped, hw_preset_video, restate_last_swap
|
|
54
|
+
from _common.emit import note, record_fallback, record_skip, refuse, stream_inventory_step, warn
|
|
55
|
+
from _common.probe import AUDIO_MEDIA_EXT, PROBED_AUDIO, PROBED_VIDEO, display_size, probed_maps, square_pixels, square_pixels_note
|
|
56
|
+
from _common.runner import ffmpeg_encoders, guard_sidecar, remember_written, replace_checked, replace_checked_together, reserve_sibling, subtitle_codec_for
|
|
57
|
+
from _common.emit import file_identity, input_length, own_length, refuse_still
|
|
58
|
+
from check import SPECS as PLATFORMS, measure_loudness
|
|
59
|
+
from fit import measure_picture
|
|
60
|
+
from _common.probe import SILENT_PEAK_DBFS, shorter_than_a_loudness_block
|
|
61
|
+
from _platforms import ALIASES as _ALIASES, PLATFORMS as PLATFORM_TABLE, TP_TOLERANCE_DB, UPLOAD_LIMITS_AS_OF, resolve as resolve_platform
|
|
62
|
+
# Frame and duration limit come from the one platform table (scripts/_platforms.py) rather than
|
|
63
|
+
# from a literal restated here: before 1.14 they were typed twice and the facebook preset had
|
|
64
|
+
# already drifted (no duration cap against the table's 14400 s).
|
|
65
|
+
|
|
66
|
+
def _loudness_step(ok: bool, platform: str, spec: dict, m: dict) -> dict:
|
|
67
|
+
"""export's loudness verification step: the platform's targets, what was measured, the
|
|
68
|
+
difference and the tolerance each was held to (docs/contract.md, 2.18 keys)."""
|
|
69
|
+
expected = {"lufs": spec["lufs"], "tp_max": spec["tp"]}
|
|
70
|
+
measured = {"lufs": m["lufs"], "tp": m["tp"]}
|
|
71
|
+
delta = {"lufs": round(m["lufs"] - spec["lufs"], 2) if math.isfinite(m["lufs"]) else None,
|
|
72
|
+
"tp": round(m["tp"] - spec["tp"], 2) if math.isfinite(m["tp"]) else None}
|
|
73
|
+
return {"step": "loudness", "ok": ok, "platform": platform, "property": "loudness",
|
|
74
|
+
"expected": expected, "measured": measured, "delta": delta,
|
|
75
|
+
"tolerance": {"lufs": spec["lufs_tol"], "tp": TP_TOLERANCE_DB}, "provenance": "specification"}
|
|
76
|
+
|
|
77
|
+
def _verify_delivery(args, preset: dict, source: dict, output: str, streams: dict,
|
|
78
|
+
encoder: Optional[str], extra: dict) -> None:
|
|
79
|
+
"""Enforce requested delivery properties using the final file, including after normalization."""
|
|
80
|
+
if STATE.dry_run:
|
|
81
|
+
return
|
|
82
|
+
written = probe(output, role="output")
|
|
83
|
+
video = written.get("video") or {}
|
|
84
|
+
steps = extra.setdefault("verification", [])
|
|
85
|
+
codec = preset.get("codec") or (preset.get("expect") or {}).get("codec")
|
|
86
|
+
codec = codec or {"libx264": "h264", "h264_videotoolbox": "h264", "libx265": "hevc",
|
|
87
|
+
"hevc_videotoolbox": "hevc"}.get(encoder)
|
|
88
|
+
if encoder == "copy":
|
|
89
|
+
codec = source["video"].get("codec")
|
|
90
|
+
if codec and not any(step["step"] == "codec" for step in steps):
|
|
91
|
+
measured = video.get("codec")
|
|
92
|
+
steps.append({"step": "codec", "property": "video_codec", "ok": measured == codec,
|
|
93
|
+
"expected": codec, "measured": measured, "provenance": "specification"})
|
|
94
|
+
if preset["w"] and preset["h"] and not args.no_scale:
|
|
95
|
+
expected = [preset["w"], preset["h"]]
|
|
96
|
+
measured = [video.get("width"), video.get("height")]
|
|
97
|
+
steps.append({"step": "frame_size", "property": "frame_size", "ok": measured == expected,
|
|
98
|
+
"expected": expected, "measured": measured, "provenance": "specification"})
|
|
99
|
+
if "-r" in preset["video"]:
|
|
100
|
+
expected = float(Fraction(preset["video"][preset["video"].index("-r") + 1]))
|
|
101
|
+
measured = video.get("fps")
|
|
102
|
+
tolerance = 0.005 # accommodate probe rounding while distinguishing 29.97 from 30
|
|
103
|
+
steps.append({"step": "frame_rate", "property": "fps",
|
|
104
|
+
"ok": measured is not None and abs(measured - expected) <= tolerance,
|
|
105
|
+
"expected": expected, "measured": measured, "tolerance": tolerance,
|
|
106
|
+
"provenance": "specification"})
|
|
107
|
+
inventory = stream_inventory_step(written, streams)
|
|
108
|
+
hard = {"streams", "codec", "frame_size", "frame_rate", "duration", "file_size"}
|
|
109
|
+
failed = [step["step"] for step in [*steps, inventory] if step["step"] in hard and step.get("ok") is not True]
|
|
110
|
+
if failed:
|
|
111
|
+
checked = [{**step, "attribution": step.get("attribution") or "unresolved"} if step.get("ok") is False
|
|
112
|
+
else step for step in [*steps, inventory]]
|
|
113
|
+
details = dict(extra, verification=checked, output=output, probe=written, verified=False,
|
|
114
|
+
dry_run=False, output_identity=file_identity(output))
|
|
115
|
+
die(f"export verification failed ({', '.join(failed)}); kept {output}", kind="verification", **details)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _from_table(dest: str, **over) -> Dict:
|
|
119
|
+
"""A preset's w/h/max read from PLATFORMS[dest], with the encoder settings given here.
|
|
120
|
+
|
|
121
|
+
`over` is for the two presets that are deliberately not the destination's own frame or cap:
|
|
122
|
+
`youtube4k` delivers to YouTube at 2160p, and neither youtube preset trims at YouTube's
|
|
123
|
+
12-hour limit (check.py reports it; export.py has never cut a long upload and does not start).
|
|
124
|
+
"""
|
|
125
|
+
frame = PLATFORM_TABLE[dest]["frame"] or {}
|
|
126
|
+
spec = PLATFORM_TABLE[dest]["spec"]
|
|
127
|
+
max_duration = spec.get("max_duration")
|
|
128
|
+
out = {"w": frame.get("w"), "h": frame.get("h"),
|
|
129
|
+
"max": float(max_duration) if max_duration is not None else None}
|
|
130
|
+
out.update(over)
|
|
131
|
+
return out
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _center_crop_geometry(sw: int, sh: int, w: int, h: int) -> tuple:
|
|
135
|
+
"""Source-pixel margins of the preset's scale-to-cover and centred 4:2:0 crop."""
|
|
136
|
+
# FFmpeg's scale rounds the non-binding side to nearest (halves up); crop floors the
|
|
137
|
+
# centred offsets to even pixels for chroma. Leave the existing encode filters unchanged.
|
|
138
|
+
scaled_w = max(w, (2 * h * sw + sh) // (2 * sh))
|
|
139
|
+
scaled_h = max(h, (2 * w * sh + sw) // (2 * sw))
|
|
140
|
+
mx, my = scaled_w - w, scaled_h - h
|
|
141
|
+
x, y = 2 * (mx // 4), 2 * (my // 4)
|
|
142
|
+
return scaled_w / sw, {
|
|
143
|
+
"left": round(x * sw / scaled_w), "right": round((mx - x) * sw / scaled_w),
|
|
144
|
+
"top": round(y * sh / scaled_h), "bottom": round((my - y) * sh / scaled_h),
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
_H264_HIGH = ["-c:v", "libx264", "-preset", "slow", "-crf", "18", "-profile:v", "high", "-pix_fmt", "yuv420p"]
|
|
149
|
+
_AAC_192 = ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"]
|
|
150
|
+
_AAC_128 = ["-c:a", "aac", "-b:a", "128k", "-ar", "48000"]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _social(crf: str = "20") -> List[str]:
|
|
154
|
+
return ["-c:v", "libx264", "-preset", "medium", "-crf", crf, "-profile:v", "high", "-pix_fmt", "yuv420p", "-r", "30"]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
PRESETS: Dict[str, Dict] = {
|
|
158
|
+
"youtube": dict(_from_table("youtube", max=None), ext="mp4", video=_H264_HIGH, audio=_AAC_192, desc="1080p H.264, AAC 192k"),
|
|
159
|
+
"youtube4k": dict(_from_table("youtube", w=3840, h=2160, max=None), ext="mp4", video=_H264_HIGH, audio=_AAC_192, desc="2160p H.264, AAC 192k"),
|
|
160
|
+
"reels": dict(_from_table("reels"), ext="mp4", video=_social(), audio=_AAC_128, desc="9:16 1080x1920, 30fps, max 90s (Instagram Reels)"),
|
|
161
|
+
"x": dict(_from_table("x"), ext="mp4", video=_social("22"), audio=["-c:a", "aac", "-b:a", "128k", "-ar", "44100"], desc="720p H.264, max 140s (Twitter/X)"),
|
|
162
|
+
"prores": {"w": None, "h": None, "ext": "mov", "video": ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0", "-pix_fmt", "yuv422p10le"], "audio": ["-c:a", "pcm_s16le"], "max": None, "intermediate": True,
|
|
163
|
+
"expect": {"codec": "prores", "profile": "HQ", "pix_fmt": "yuv422p10le"}, "desc": "ProRes 422 HQ master, PCM audio, source resolution"},
|
|
164
|
+
# DNxHR (the dnxhd encoder's resolution-independent profiles): editing masters like prores, at
|
|
165
|
+
# the source's size and rate; the written profile and pixel format are checked after the write
|
|
166
|
+
**{f"dnxhr-{name}": {"w": None, "h": None, "ext": "mov",
|
|
167
|
+
"video": ["-c:v", "dnxhd", "-profile:v", f"dnxhr_{name}", "-pix_fmt", pix],
|
|
168
|
+
"audio": ["-c:a", "pcm_s16le"], "max": None, "intermediate": True,
|
|
169
|
+
"expect": {"codec": "dnxhd", "profile": f"DNXHR {name.upper()}", "pix_fmt": pix},
|
|
170
|
+
"desc": f"DNxHR {name.upper()} master ({desc}), PCM audio, source resolution"}
|
|
171
|
+
for name, pix, desc in (("lb", "yuv422p", "8-bit 4:2:2, low bandwidth"), ("sq", "yuv422p", "8-bit 4:2:2, standard"),
|
|
172
|
+
("hq", "yuv422p", "8-bit 4:2:2, high quality"), ("hqx", "yuv422p10le", "10-bit 4:2:2"),
|
|
173
|
+
("444", "yuv444p10le", "10-bit 4:4:4"))},
|
|
174
|
+
# Alpha masters (#417): editing masters that keep the source's alpha channel; the alpha is read
|
|
175
|
+
# back from a written frame and compared with the source's. A source without alpha is refused.
|
|
176
|
+
"prores4444": {"w": None, "h": None, "ext": "mov", "alpha": True, "intermediate": True,
|
|
177
|
+
"video": ["-c:v", "prores_ks", "-profile:v", "4", "-vendor", "apl0", "-pix_fmt", "yuva444p10le", "-alpha_bits", "16"],
|
|
178
|
+
"audio": ["-c:a", "pcm_s16le"], "max": None, "expect": {"codec": "prores", "profile": "4444"},
|
|
179
|
+
"desc": "ProRes 4444 with alpha (16-bit alpha), PCM audio, source resolution"},
|
|
180
|
+
"prores4444xq": {"w": None, "h": None, "ext": "mov", "alpha": True, "intermediate": True,
|
|
181
|
+
"video": ["-c:v", "prores_ks", "-profile:v", "5", "-vendor", "apl0", "-pix_fmt", "yuva444p10le", "-alpha_bits", "16"],
|
|
182
|
+
"audio": ["-c:a", "pcm_s16le"], "max": None, "expect": {"codec": "prores", "profile": "XQ"},
|
|
183
|
+
"desc": "ProRes 4444 XQ with alpha (16-bit alpha), PCM audio, source resolution"},
|
|
184
|
+
"qtrle": {"w": None, "h": None, "ext": "mov", "alpha": True, "intermediate": True,
|
|
185
|
+
"video": ["-c:v", "qtrle", "-pix_fmt", "argb"], "audio": ["-c:a", "pcm_s16le"], "max": None,
|
|
186
|
+
"expect": {"codec": "qtrle", "pix_fmt": "argb"}, "desc": "QuickTime Animation (lossless RGB + alpha), PCM audio"},
|
|
187
|
+
"vp9-alpha": {"w": None, "h": None, "ext": "webm", "alpha": True, "intermediate": True,
|
|
188
|
+
"video": ["-c:v", "libvpx-vp9", "-pix_fmt", "yuva420p", "-crf", "20", "-b:v", "0", "-row-mt", "1"],
|
|
189
|
+
"audio": ["-c:a", "libopus", "-b:a", "128k"], "max": None, "expect": {"codec": "vp9"},
|
|
190
|
+
"desc": "WebM VP9 with alpha (CRF 20), Opus audio, source resolution"},
|
|
191
|
+
"hap-alpha": {"w": None, "h": None, "ext": "mov", "alpha": True, "intermediate": True,
|
|
192
|
+
"video": ["-c:v", "hap", "-format", "hap_alpha"], "audio": ["-c:a", "pcm_s16le"], "max": None,
|
|
193
|
+
"expect": {"codec": "hap"}, "desc": "HAP Alpha (needs an ffmpeg built with snappy; size a multiple of 4), PCM audio"},
|
|
194
|
+
# Key and fill for a switcher's downstream keyer (#418): two ProRes 422 HQ files from one alpha
|
|
195
|
+
# source, the fill (colour) and the key (the alpha as a luma matte), frame for frame.
|
|
196
|
+
"key-fill": {"w": None, "h": None, "ext": "mov", "alpha": True, "intermediate": True, "keyfill": True,
|
|
197
|
+
"video": ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0", "-pix_fmt", "yuv422p10le"],
|
|
198
|
+
"audio": ["-c:a", "pcm_s16le"], "max": None,
|
|
199
|
+
"desc": "fill + key pair (<out> and <out stem>_key.mov), ProRes 422 HQ, frame for frame, for a switcher's keyer"},
|
|
200
|
+
"h265": {"w": None, "h": None, "ext": "mp4", "video": ["-c:v", "libx265", "-preset", "medium", "-crf", "24", "-pix_fmt", "yuv420p", "-tag:v", "hvc1"], "audio": ["-c:a", "aac", "-b:a", "160k"], "max": None, "desc": "HEVC CRF 24, hvc1 tag, source resolution"},
|
|
201
|
+
"gif": {"w": 480, "h": None, "ext": "gif", "video": [], "audio": [], "max": None, "desc": "480px palette GIF, 12fps"},
|
|
202
|
+
"copy": {"w": None, "h": None, "ext": None, "video": ["-c:v", "copy"], "audio": ["-c:a", "copy"], "max": None, "desc": "stream copy, no re-encode (source codecs/container/colour tags unchanged)"},
|
|
203
|
+
# 1.14: the destinations that used to be aliases of reels/youtube are their own presets, each
|
|
204
|
+
# sized and length-limited from the one platform table (scripts/_platforms.py) rather than from
|
|
205
|
+
# a comment. `reels` keeps its historical settings byte-for-byte so existing calls are unchanged.
|
|
206
|
+
"tiktok": dict(_from_table("tiktok"), ext="mp4", video=_social(), audio=_AAC_128, desc="9:16 1080x1920, 30fps, max 600s (TikTok)"),
|
|
207
|
+
"shorts": dict(_from_table("shorts"), ext="mp4", video=_social(), audio=_AAC_128, desc="9:16 1080x1920, 30fps, max 180s (YouTube Shorts)"),
|
|
208
|
+
"linkedin": dict(_from_table("linkedin"), ext="mp4", video=_social(), audio=_AAC_128, desc="1:1 1080x1080, 30fps, max 600s (LinkedIn)"),
|
|
209
|
+
"facebook": dict(_from_table("facebook"), ext="mp4", video=_social("21"), audio=_AAC_128, desc="16:9 1920x1080, 30fps, max 14400s (Facebook feed)"),
|
|
210
|
+
# HDR and AV1 deliveries: the encoder line comes from encoder_args() so the source's own
|
|
211
|
+
# HDR tags survive (hevc) and the AV1 encoder is chosen/refused in one place.
|
|
212
|
+
"youtube-hdr": {"w": None, "h": None, "ext": "mp4", "codec": "hevc", "video": [], "audio": _AAC_192, "max": None, "hdr_only": True, "desc": "HEVC Main10, source HDR10/HLG tags kept, AAC 192k (refuses an SDR source)"},
|
|
213
|
+
"youtube-av1": dict(_from_table("youtube", max=None), ext="mp4", codec="av1", video=[], audio=_AAC_192, desc="1080p AV1 (libsvtav1, libaom fallback), AAC 192k"),
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# which check.py platform a preset targets (its loudness spec is measured after the write)
|
|
219
|
+
HERE = Path(__file__).resolve().parent
|
|
220
|
+
# broadcast's "preset" is prores, an editing master rather than a delivery: nothing is measured
|
|
221
|
+
# against a loudness spec after writing it, exactly as before 1.14.
|
|
222
|
+
_NOT_A_DELIVERY = frozenset({"broadcast"})
|
|
223
|
+
# Derived from the same table: a destination whose "preset" is this one is the compliance target
|
|
224
|
+
# its loudness is measured against (youtube4k and the two youtube variants deliver to youtube).
|
|
225
|
+
PLATFORM_OF: Dict[str, str] = {PLATFORM_TABLE[n]["preset"]: PLATFORM_TABLE[n]["check"]
|
|
226
|
+
for n in sorted(PLATFORM_TABLE)
|
|
227
|
+
if PLATFORM_TABLE[n].get("preset") in PRESETS and PLATFORM_TABLE[n]["frame"]
|
|
228
|
+
and n not in _NOT_A_DELIVERY}
|
|
229
|
+
PLATFORM_OF["youtube4k"] = PLATFORM_TABLE["youtube"]["check"]
|
|
230
|
+
# Aliases people write for a destination ('youtube-shorts', 'ig', 'twitter') name the same preset.
|
|
231
|
+
PRESET_CHOICES: List[str] = sorted(set(PRESETS) | {a for a in _ALIASES if resolve_platform(a) in PRESETS})
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# The alpha helpers (#417) live in _common.alpha since color.py, graphics.py, overlay.py and
|
|
235
|
+
# background.py write alpha lines too; the names this module has always had stay bound here.
|
|
236
|
+
from _common.alpha import (ALPHA_PIX as _ALPHA_PIX, ALPHA_TOLERANCE, OPAQUE, alpha_stats, # noqa: E402
|
|
237
|
+
alpha_compare as _alpha_compare, frame_means as _frame_means, rounded as _rounded,
|
|
238
|
+
decoder_args_for, vp9_alpha_tagged)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def key_path(fill: str) -> str:
|
|
242
|
+
stem, _ = os.path.splitext(fill)
|
|
243
|
+
return f"{stem}_key.mov"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _key_fill(args, p: Dict, meta: Dict, output: str, cmd: List[str], vf: List[str], has_audio: bool,
|
|
247
|
+
source_alpha, notes: List[str], subs: List[Dict], data: List[Dict]) -> int:
|
|
248
|
+
"""--preset key-fill: one decode split into the fill (the colour, straight or premultiplied)
|
|
249
|
+
and the key (alphaextract: alpha 255 is video white, 0 black), both ProRes 422 HQ in one ffmpeg
|
|
250
|
+
run so they hold the same frames; the source's start timecode is written on both. Checked
|
|
251
|
+
after: the same frame count, size, rate and length, the key's mean level against the source's
|
|
252
|
+
alpha, and both files hashed (output_identity, key.identity)."""
|
|
253
|
+
key = key_path(output)
|
|
254
|
+
# both files are this run's outputs, but ffmpeg's last argument (which run() guards and stages)
|
|
255
|
+
# is only the key: the fill is checked here the same way -- not the input under another
|
|
256
|
+
# spelling, not someone's file without --overwrite -- and written through a hidden temp file
|
|
257
|
+
guard_sidecar(output, args.input, siblings=[key])
|
|
258
|
+
guard_sidecar(key, args.input, siblings=[output])
|
|
259
|
+
if STATE.hw and "-c:v" in p["video"]:
|
|
260
|
+
note(f"--hw: --preset {args.preset} stays on {p['video'][p['video'].index('-c:v') + 1]}: one ffmpeg run writes "
|
|
261
|
+
"the fill and the key as a pair, and VideoToolbox's ProRes encoder is not used for it")
|
|
262
|
+
fill_chain = ",".join(vf + (["premultiply=inplace=1"] if args.alpha_mode == "premultiplied" else []) + ["format=yuv422p10le"])
|
|
263
|
+
# Alpha uses full range even when the source picture is tagged limited range.
|
|
264
|
+
key_chain = ",".join(vf + ["alphaextract", "scale=in_range=pc:out_range=tv", "format=yuv422p10le"])
|
|
265
|
+
tc = ((meta.get("timecode") or {}).get("value"))
|
|
266
|
+
tc_args = ["-timecode", tc] if tc else []
|
|
267
|
+
# a VFR source is conformed by the fps filter, once, ahead of the split: both files hold the same
|
|
268
|
+
# frames, and -fps_mode cfr alone let a frame run up to two frames late against the sound (#512)
|
|
269
|
+
conform = cfr_filter(meta)
|
|
270
|
+
cmd = cmd + ["-filter_complex", f"[0:{PROBED_VIDEO}]{conform + ',' if conform else ''}split[f][k];"
|
|
271
|
+
f"[f]{fill_chain}[fill];[k]{key_chain}[key]"]
|
|
272
|
+
cmd += ["-map", "[fill]"] + probed_maps(meta, video=False, audio=has_audio) + p["video"] + tc_args + cfr_args(meta)
|
|
273
|
+
# the fill is always written to a hidden sibling and moved into place only after the encode
|
|
274
|
+
# succeeds: run() stages and cleans up only ffmpeg's last output (the key), so a failed encode
|
|
275
|
+
# left a partial new fill (the retry was refused as output_exists) or truncated an existing one
|
|
276
|
+
# the key is staged the same way, and both are committed together: a fill refused at its
|
|
277
|
+
# replace never leaves a new key beside it (which a retry would then refuse as existing)
|
|
278
|
+
fill_tmp = key_tmp = None
|
|
279
|
+
if not STATE.dry_run:
|
|
280
|
+
d, base = os.path.split(output)
|
|
281
|
+
stem, ext = os.path.splitext(base)
|
|
282
|
+
fill_tmp = reserve_sibling(d, stem, ext, "fill") # created exclusively: never through a planted link
|
|
283
|
+
kd, kbase = os.path.split(key)
|
|
284
|
+
kstem, kext = os.path.splitext(kbase)
|
|
285
|
+
key_tmp = reserve_sibling(kd, kstem, kext, "key")
|
|
286
|
+
# this run's own placeholder: run()'s output check must not refuse it as someone's file
|
|
287
|
+
STATE.written.add(os.path.realpath(key_tmp))
|
|
288
|
+
cmd += (p["audio"] if has_audio else ["-an"]) + [fill_tmp or output]
|
|
289
|
+
cmd += ["-map", "[key]"] + p["video"] + tc_args + cfr_args(meta) + ["-an", key_tmp or key]
|
|
290
|
+
try:
|
|
291
|
+
run(cmd)
|
|
292
|
+
if fill_tmp and key_tmp:
|
|
293
|
+
# under both locks, and only while each is the file guard_sidecar() decided about
|
|
294
|
+
replace_checked_together([(fill_tmp, output), (key_tmp, key)])
|
|
295
|
+
finally:
|
|
296
|
+
for tmp, final in ((fill_tmp, output), (key_tmp, key)):
|
|
297
|
+
if tmp:
|
|
298
|
+
# the command is recorded with the path the caller asked for, not the temp name
|
|
299
|
+
STATE.commands[:] = [c.replace(tmp, final) for c in STATE.commands]
|
|
300
|
+
if os.path.exists(tmp):
|
|
301
|
+
os.remove(tmp)
|
|
302
|
+
remember_written(output, key)
|
|
303
|
+
extra: Dict[str, object] = {"alpha_mode": args.alpha_mode or "straight", "key": {"output": key}}
|
|
304
|
+
# a fill and a key for a switcher carry the picture and the sound; the source's subtitle and
|
|
305
|
+
# data streams are not written, and the document says so (as for a GIF)
|
|
306
|
+
non_av = _non_av_report(subs, [], data, ["subtitle", "data"], output, "key_fill")
|
|
307
|
+
extra["non_av_streams"] = non_av
|
|
308
|
+
extra["dropped_non_av_streams"] = bool(non_av["dropped"])
|
|
309
|
+
if non_av["dropped"]:
|
|
310
|
+
notes.append(f"a key/fill pair holds the picture and the sound only: the source's {len(non_av['dropped'])} "
|
|
311
|
+
"subtitle/data stream(s) were not written; non_av_streams lists them")
|
|
312
|
+
if STATE.dry_run:
|
|
313
|
+
emit(output, **extra, **({"notes": notes} if notes else {}))
|
|
314
|
+
return 0
|
|
315
|
+
fill_m, key_m = probe(output, role="output"), probe(key, role="output")
|
|
316
|
+
fv, kv = fill_m["video"], key_m["video"]
|
|
317
|
+
pair = {k: [fv.get(k), kv.get(k)] for k in ("width", "height", "nb_frames", "r_frame_rate")}
|
|
318
|
+
# the video streams' lengths: the fill's container also counts its sound, which may run longer
|
|
319
|
+
# than the picture, and the key has none
|
|
320
|
+
pair["duration"] = [round(own_length(v) or 0, 3) for v in (fv, kv)]
|
|
321
|
+
same = all(a == b and a not in (None, 0) for a, b in pair.values())
|
|
322
|
+
# the two written files against each other: no expected value, so no provenance (#403: it said
|
|
323
|
+
# "output_measurement", which is not one of the contract's values)
|
|
324
|
+
steps = [{"step": "key_fill_pair", "property": "frames_size_rate_length", "ok": same, "measured": pair}]
|
|
325
|
+
key_level = _luma_stats(key)
|
|
326
|
+
level = _alpha_compare(key_level, source_alpha)
|
|
327
|
+
steps.append({"step": "key_level", "property": "key_mean_vs_source_alpha", "ok": level["ok"], "comparison": level,
|
|
328
|
+
"expected": None if source_alpha is None else round(source_alpha["mean"], 2),
|
|
329
|
+
"measured": None if key_level is None else round(key_level["mean"], 2), "tolerance": ALPHA_TOLERANCE,
|
|
330
|
+
"frames": {"expected": _rounded(source_alpha), "measured": _rounded(key_level)},
|
|
331
|
+
"provenance": "input_premeasurement"})
|
|
332
|
+
extra["key"] = {"output": key, "identity": file_identity(key), "sha256": _sha256(key), "timecode": tc}
|
|
333
|
+
extra["fill_sha256"] = _sha256(output)
|
|
334
|
+
info(f"wrote {output} (fill) and {key} (key), {fv['width']}x{fv['height']}, {fv.get('nb_frames')} frames each")
|
|
335
|
+
emit(output, verification=steps, expect_streams={"video": 1, "audio": 1 if has_audio else 0}, **extra,
|
|
336
|
+
**({"notes": notes} if notes else {}))
|
|
337
|
+
return 0
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _sha256(path: str) -> str:
|
|
341
|
+
"""The whole file's SHA-256: a key/fill pair is handed to a playout system as two files that
|
|
342
|
+
must stay a pair, and the hashes let it check that neither was replaced."""
|
|
343
|
+
import hashlib
|
|
344
|
+
h = hashlib.sha256()
|
|
345
|
+
with open(path, "rb") as fh:
|
|
346
|
+
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
|
347
|
+
h.update(chunk)
|
|
348
|
+
return h.hexdigest()
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _luma_stats(path: str) -> "Dict[str, float] | None":
|
|
352
|
+
"""The level (0-255) of every frame of a file, on a 64x36 grey copy: {mean, min, frames}."""
|
|
353
|
+
return _frame_means([require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin"], path, "format=gray")
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _loudness_unmeasured(extra: Dict[str, object], notes: List[str], platform: str, spec: Dict, normalized: bool = False,
|
|
357
|
+
tp: Optional[float] = None) -> None:
|
|
358
|
+
"""The written file's loudness could not be read (ffmpeg's loudnorm JSON did not parse, or,
|
|
359
|
+
with `tp`, the audio is shorter than one 400 ms gating block and has only a true peak): the
|
|
360
|
+
platform's loudness was not verified, and the document says so -- a `loudness` block with null
|
|
361
|
+
values and a reason, a failing `loudness` verification step, a warning -- rather than leaving
|
|
362
|
+
the block out, which read as "nothing to check". check.py reports the same case as a WARN row."""
|
|
363
|
+
reason = "not_measured"
|
|
364
|
+
extra["loudness"] = {"lufs": None, "tp": tp, "target_lufs": spec["lufs"], "target_tp": spec["tp"], "ok": None,
|
|
365
|
+
"measured": False, "reason": reason, **({"too_short": True} if tp is not None else {}),
|
|
366
|
+
"normalized": normalized}
|
|
367
|
+
extra["verification"] = [{"step": "loudness", "ok": False, "platform": platform, "reason": reason}]
|
|
368
|
+
why = ("the audio is shorter than one 400 ms loudness block, so it has a true peak but no integrated loudness"
|
|
369
|
+
if tp is not None else "ffmpeg's loudnorm output did not parse")
|
|
370
|
+
msg = (f"the written file's loudness could not be measured{' after --normalize' if normalized else ''} "
|
|
371
|
+
f"({why}), so {platform}'s {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP was not "
|
|
372
|
+
"verified; run check.py on the file")
|
|
373
|
+
notes.append(msg)
|
|
374
|
+
warn(msg, "loudness_not_measured", platform=platform, normalized=normalized)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
# Text subtitle codecs ffmpeg can convert to the container's own text track: mov_text is the one
|
|
378
|
+
# text track MP4/MOV hold, Matroska holds SubRip/ASS/WebVTT as they are but not mov_text.
|
|
379
|
+
# the -c:s for one source subtitle stream (#380), shared with caption.py --mode mux (#414): copy
|
|
380
|
+
# when the output container holds it as it is, else the container's own text format (a bitmap
|
|
381
|
+
# track is tried as a copy; a container that refuses it is the fallback below)
|
|
382
|
+
_subtitle_codec = subtitle_codec_for
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _data_streams(path: str) -> List[Dict[str, object]]:
|
|
386
|
+
"""The data streams of a file ({index, codec}), without its attachments (probe()'s
|
|
387
|
+
data_streams counts both, and -map 0:d maps only the data streams) and without an MP4/MOV
|
|
388
|
+
chapter track, which the muxer writes again from the chapters (carried_stream_maps, A173)."""
|
|
389
|
+
proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "d", "-show_entries",
|
|
390
|
+
"stream=codec_name,codec_tag_string:chapter=id", "-of", "json", path], quiet=True)
|
|
391
|
+
try:
|
|
392
|
+
doc = json.loads(proc.stdout or "{}")
|
|
393
|
+
except ValueError:
|
|
394
|
+
# an unread list would map nothing and report nothing dropped
|
|
395
|
+
die(f"ffprobe's data-stream list for {path} did not parse", kind="ffmpeg")
|
|
396
|
+
streams = doc.get("streams") or []
|
|
397
|
+
chapter_track = bool(doc.get("chapters"))
|
|
398
|
+
return [{"index": n, "codec": s.get("codec_name") or s.get("codec_tag_string")} for n, s in enumerate(streams)
|
|
399
|
+
if not (chapter_track and str(s.get("codec_tag_string") or "").lower() == "text")]
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _run_keeping_non_av(cmd: List[str], output: str, sub_codecs: List[str], data: int) -> List[str]:
|
|
403
|
+
"""run_keeping_subtitles() for export: the subtitle streams go in the codec the container takes
|
|
404
|
+
(_subtitle_codec), and a refused data stream does not cost the subtitles. The rungs are
|
|
405
|
+
subtitles + data, subtitles alone, neither; each retry is a `non_av_streams_dropped` fallback
|
|
406
|
+
with the attempt's error. `cmd` already maps the picture and the sound and has no output.
|
|
407
|
+
Returns the stream types dropped ([] when everything mapped was written)."""
|
|
408
|
+
src = next((str(cmd[i + 1]) for i, a in enumerate(cmd[:-1]) if a == "-i"), None)
|
|
409
|
+
sub_args: List[str] = ["-map", "0:s"] if sub_codecs else []
|
|
410
|
+
for n, codec in enumerate(sub_codecs):
|
|
411
|
+
sub_args += [f"-c:s:{n}", codec]
|
|
412
|
+
if sub_codecs:
|
|
413
|
+
sub_args += carried_stream_maps(src, output, chapters=False) # the fonts the subtitles are drawn with (A256)
|
|
414
|
+
data_args = (["-map", "0:d"] + carried_stream_maps(src, output, attachments=False) + ["-c:d", "copy"]) if data else []
|
|
415
|
+
rungs = [(sub_args + data_args, [])]
|
|
416
|
+
if sub_codecs and data:
|
|
417
|
+
rungs.append((sub_args, ["data"]))
|
|
418
|
+
rungs.append(([], (["subtitle"] if sub_codecs else []) + (["data"] if data else [])))
|
|
419
|
+
for n, (extra, dropped) in enumerate(rungs):
|
|
420
|
+
if n == len(rungs) - 1:
|
|
421
|
+
run(cmd + extra + [output])
|
|
422
|
+
return dropped
|
|
423
|
+
attempt = run(cmd + extra + [output], check=False)
|
|
424
|
+
if attempt.returncode == 0:
|
|
425
|
+
return dropped
|
|
426
|
+
# a full disk or a missing encoder fails every rung the same way: that error, not a
|
|
427
|
+
# fallback that blames the subtitles and encodes again (#415, #389's rule)
|
|
428
|
+
fail_if_classified(attempt)
|
|
429
|
+
error = " | ".join([ln.strip() for ln in (attempt.stderr or "").splitlines() if ln.strip()][-3:])[-500:]
|
|
430
|
+
going = rungs[n + 1][1]
|
|
431
|
+
record_fallback(f"{os.path.basename(output)} could not hold the source's {' and '.join(t for t in ('subtitle', 'data') if t in going)} "
|
|
432
|
+
f"stream(s) ({error or 'ffmpeg exit ' + str(attempt.returncode)}); encoding again without them",
|
|
433
|
+
"non_av_streams_dropped", output=output, returncode=attempt.returncode, error=error, dropped=going)
|
|
434
|
+
return [] # not reached: the last rung either returns or exits
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _written_data_codec(n: int, sources: List[Dict], written: List[Dict]) -> bool:
|
|
438
|
+
"""True when the written file holds a data track for source data stream `n`: tracks are
|
|
439
|
+
matched by codec, never by position, so with k source streams of one codec and j tracks of it
|
|
440
|
+
written, the first min(j, k) of those sources count as kept (a muxer's own timecode track is
|
|
441
|
+
not credited to an unrelated stream, and two copied streams of one codec are both kept)."""
|
|
442
|
+
codec = sources[n].get("codec")
|
|
443
|
+
if not codec:
|
|
444
|
+
return False
|
|
445
|
+
rank = sum(1 for s in sources[:n] if s.get("codec") == codec)
|
|
446
|
+
return rank < sum(1 for w in written if w.get("codec") == codec)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _non_av_report(subs: List[Dict], sub_codecs: List[str], data: List[Dict], dropped: List[str],
|
|
450
|
+
output: str, reason: str) -> Dict[str, List[Dict]]:
|
|
451
|
+
"""`non_av_streams`: each source subtitle/data stream as kept (with the codec it was written in)
|
|
452
|
+
or dropped (with why), read back from the written file; under --dry-run, as planned."""
|
|
453
|
+
kept: List[Dict] = []
|
|
454
|
+
gone: List[Dict] = []
|
|
455
|
+
written_subs: List[Dict] = []
|
|
456
|
+
written_data: List[Dict] = []
|
|
457
|
+
if not STATE.dry_run and (subs or data):
|
|
458
|
+
written_subs = probe(output, role="output").get("subtitle_stream_details") or []
|
|
459
|
+
written_data = _data_streams(output)
|
|
460
|
+
for kind, streams, written in (("subtitle", subs, written_subs), ("data", data, written_data)):
|
|
461
|
+
for n, s in enumerate(streams):
|
|
462
|
+
# a data row keeps its n-th-of-type index in the source: the chapter text track is left
|
|
463
|
+
# out of the list, so a timecode track after it is data stream 1, not 0
|
|
464
|
+
row = {"type": kind, "index": s.get("index", n) if kind == "data" else n, "codec": s.get("codec")}
|
|
465
|
+
if kind == "subtitle":
|
|
466
|
+
row["language"] = s.get("language")
|
|
467
|
+
if STATE.dry_run and kind not in dropped:
|
|
468
|
+
planned = sub_codecs[n] if kind == "subtitle" else "copy"
|
|
469
|
+
kept.append(dict(row, output_codec=s.get("codec") if planned == "copy" else planned))
|
|
470
|
+
elif kind == "subtitle" and n < len(written):
|
|
471
|
+
kept.append(dict(row, output_codec=written[n].get("codec")))
|
|
472
|
+
elif kind == "data" and _written_data_codec(n, streams, written):
|
|
473
|
+
# read back, not assumed, and matched by codec: an MP4/MOV muxer writes a
|
|
474
|
+
# timecode (tmcd) track of its own from the source's timecode tag even when the
|
|
475
|
+
# copied one was refused
|
|
476
|
+
kept.append(dict(row, output_codec=s.get("codec")))
|
|
477
|
+
else:
|
|
478
|
+
gone.append(dict(row, reason=reason if kind in dropped else "not_in_output"))
|
|
479
|
+
return {"kept": kept, "dropped": gone}
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
# --repair (2.24): regenerate missing timestamps, drop packets flagged corrupt, keep demuxing past errors
|
|
483
|
+
REPAIR_INPUT_ARGS = ["-fflags", "+genpts+discardcorrupt", "-err_detect", "ignore_err"]
|
|
484
|
+
_TIMESTAMP_WARNING = re.compile(r"(?i)\b(dts|pts)\b|timestamp")
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def media_damage(path: str) -> Dict[str, int]:
|
|
488
|
+
"""One full decode of `path` at -v warning: lines about timestamps (non-monotonic DTS, invalid
|
|
489
|
+
PTS) and every other error line, counted. What --repair is measured by, before and after."""
|
|
490
|
+
# repeat+: every occurrence on its own line, not "Last message repeated N times", which hid
|
|
491
|
+
# N timestamp warnings and was itself counted as a decode error
|
|
492
|
+
# the streams a copy export writes (probed_maps), not the ones default selection would decode
|
|
493
|
+
proc = run_analysis([require_tool("ffmpeg"), "-hide_banner", "-nostdin", "-v", "repeat+warning", "-i", path,
|
|
494
|
+
"-map", f"0:{PROBED_VIDEO}?", "-map", f"0:{PROBED_AUDIO}?", "-f", "null", "-"],
|
|
495
|
+
check=False, record=True)
|
|
496
|
+
lines = [ln for ln in (proc.stderr or "").splitlines() if ln.strip()]
|
|
497
|
+
# "Packet corrupt (stream = 0, dts = ...)" names a dts but is damage, not a timestamp problem
|
|
498
|
+
stamps = sum(1 for ln in lines if _TIMESTAMP_WARNING.search(ln) and "corrupt" not in ln.lower())
|
|
499
|
+
return {"timestamp_warnings": stamps, "decode_errors": len(lines) - stamps}
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
MIB = 1024 * 1024
|
|
503
|
+
SIZE_HEADROOM = 0.97 # of the byte budget given to the streams; the rest is container overhead
|
|
504
|
+
SIZE_MIN_VIDEO_KBPS = 100 # below this the picture is not worth delivering; refused instead
|
|
505
|
+
SIZE_MAX_VIDEO_KBPS = 400_000 # 400 Mb/s: above any delivery line, and libx264 refuses far larger values
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _platform_rate_args(preset: str, meta: Dict) -> List[str]:
|
|
509
|
+
"""A platform preset that keeps the source's frame rate (the youtube family) conforms a source
|
|
510
|
+
faster than the platform's fps_max to the source rate divided by the smallest whole number that
|
|
511
|
+
brings it within the limit (120 -> 60, 119.88 -> 59.94, 100 -> 50), so every frame of the
|
|
512
|
+
output is one of the source's own. Through 3.8.8 a 120 fps source kept 120 fps and the
|
|
513
|
+
platform's own check FAILed the export (audit A115). [] when the preset has no limit or the
|
|
514
|
+
source is within it (cfr_args() then decides, as before)."""
|
|
515
|
+
platform = PLATFORM_OF.get(preset)
|
|
516
|
+
fps_max = (PLATFORMS.get(platform) or {}).get("fps_max") if platform else None
|
|
517
|
+
v = meta.get("video") or {}
|
|
518
|
+
src = v.get("fps")
|
|
519
|
+
if not fps_max or not src or src <= fps_max + 0.01:
|
|
520
|
+
return []
|
|
521
|
+
try:
|
|
522
|
+
exact = Fraction(v.get("avg_frame_rate") or "0")
|
|
523
|
+
except (ValueError, ZeroDivisionError):
|
|
524
|
+
exact = Fraction(0)
|
|
525
|
+
if not exact or abs(float(exact) - src) > 0.01:
|
|
526
|
+
exact = Fraction(src).limit_denominator(1001)
|
|
527
|
+
n = math.ceil(float(exact) / (fps_max + 0.01))
|
|
528
|
+
rate = exact / n
|
|
529
|
+
note(f"source is {src:g} fps, above {platform}'s limit of {fps_max:g}: exported at {float(rate):.6g} fps, "
|
|
530
|
+
f"one source frame in {n}")
|
|
531
|
+
return ["-fps_mode", "cfr", "-r", str(rate.numerator) if rate.denominator == 1 else f"{rate.numerator}/{rate.denominator}"]
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def size_video_args(args, video: List[str], p: Dict, meta: Dict, has_audio: bool) -> List[str]:
|
|
535
|
+
"""--max-mb: the preset's x264 line with its CRF replaced by the bitrate that fits the size,
|
|
536
|
+
for a two-pass encode. Refused where that cannot be done honestly: another codec, --crf, --hw,
|
|
537
|
+
a source with no duration, or a size too small for a watchable picture."""
|
|
538
|
+
if args.crf is not None:
|
|
539
|
+
die("--max-mb sets the bitrate from the size, --crf sets a quality: give one of them")
|
|
540
|
+
if "-c:v" not in video or video[video.index("-c:v") + 1] != "libx264" or "-crf" not in video:
|
|
541
|
+
die(f"--max-mb runs a two-pass x264 encode; --preset {args.preset} does not encode with x264"
|
|
542
|
+
+ (" (--hw puts it on VideoToolbox, which has no two-pass mode)" if STATE.hw else ""))
|
|
543
|
+
if not math.isfinite(args.max_mb) or args.max_mb <= 0:
|
|
544
|
+
die(f"--max-mb must be a positive number of MiB, got {args.max_mb:g}")
|
|
545
|
+
dur = input_length(meta) # the bitrate is the size over the length: no stated length is refused (#491)
|
|
546
|
+
if p["max"] and not args.allow_long:
|
|
547
|
+
dur = min(dur, float(p["max"]))
|
|
548
|
+
dur = min(dur, args.duration or dur)
|
|
549
|
+
if dur <= 0:
|
|
550
|
+
die("--max-mb needs the source's duration, which it does not report")
|
|
551
|
+
audio_kbps = 0.0
|
|
552
|
+
if has_audio and "-b:a" in p["audio"]:
|
|
553
|
+
audio_kbps = float(p["audio"][p["audio"].index("-b:a") + 1].rstrip("k"))
|
|
554
|
+
video_kbps = args.max_mb * MIB * 8 * SIZE_HEADROOM / dur / 1000 - audio_kbps
|
|
555
|
+
if video_kbps > SIZE_MAX_VIDEO_KBPS:
|
|
556
|
+
die(f"--max-mb {args.max_mb:g} allows {video_kbps / 1000:.0f} Mb/s over {dur:.1f}s, beyond any delivery bitrate; "
|
|
557
|
+
"a limit that large constrains nothing", hint="drop --max-mb (the preset's quality setting applies)")
|
|
558
|
+
if video_kbps < SIZE_MIN_VIDEO_KBPS:
|
|
559
|
+
die(f"--max-mb {args.max_mb:g} leaves {max(video_kbps, 0):.0f} kb/s for the picture over {dur:.1f}s "
|
|
560
|
+
f"(after {audio_kbps:.0f} kb/s of audio); under {SIZE_MIN_VIDEO_KBPS} kb/s it is not watchable",
|
|
561
|
+
hint="raise --max-mb, or cut the video shorter first")
|
|
562
|
+
out = list(video)
|
|
563
|
+
i = out.index("-crf")
|
|
564
|
+
out[i:i + 2] = ["-b:v", f"{video_kbps:.0f}k"]
|
|
565
|
+
info(f"--max-mb {args.max_mb:g}: {video_kbps:.0f} kb/s video + {audio_kbps:.0f} kb/s audio over {dur:.1f}s, two-pass")
|
|
566
|
+
return out
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def main() -> int:
|
|
570
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
571
|
+
ap.add_argument("input", nargs="?")
|
|
572
|
+
ap.add_argument("-o", "--output", help="output file (default: <name>_<preset>.<ext>)")
|
|
573
|
+
ap.add_argument("--preset", choices=PRESET_CHOICES, help="delivery preset (aliases: " + ", ".join(a for a in _ALIASES if resolve_platform(a) in PRESETS) + ")")
|
|
574
|
+
ap.add_argument("--fit", choices=["pad", "crop"], default="pad", help="how to reach the preset frame when aspect differs (default pad)")
|
|
575
|
+
ap.add_argument("--pad-color", default="black", help="pad colour when the picture is padded to the preset's frame, e.g. black, white, 0x101010 (default black)")
|
|
576
|
+
add_pad_fill_args(ap)
|
|
577
|
+
ap.add_argument("--no-scale", action="store_true", help="keep source resolution even for platform presets")
|
|
578
|
+
ap.add_argument("--allow-long", action="store_true", help="do not trim to the platform's max duration")
|
|
579
|
+
ap.add_argument("--crf", type=int, help="override CRF")
|
|
580
|
+
ap.add_argument("--repair", action="store_true",
|
|
581
|
+
help="--preset copy only: remux a damaged file -- timestamps regenerated, corrupt packets dropped, "
|
|
582
|
+
"negative timestamps shifted to zero -- and count the decode errors and timestamp warnings "
|
|
583
|
+
"before and after; the input is never touched")
|
|
584
|
+
ap.add_argument("--duration", type=float, metavar="S", help="keep only the first S seconds (a preset's own maximum still applies)")
|
|
585
|
+
ap.add_argument("--max-mb", type=float, metavar="MB",
|
|
586
|
+
help="the max size of the file: fit it under MB megabytes (MiB), a two-pass x264 encode at the video bitrate the "
|
|
587
|
+
"running time leaves after the audio, measured afterwards (H.264 presets; not with --crf or --hw)")
|
|
588
|
+
# 4.0.0 (#579): a platform preset promises the platform's loudness, so it meets it by default
|
|
589
|
+
norm = ap.add_mutually_exclusive_group()
|
|
590
|
+
norm.add_argument("--normalize", action="store_true",
|
|
591
|
+
help="platform presets: normalize audio when it misses the loudness spec (the default since 4.0.0). Video is copied.")
|
|
592
|
+
norm.add_argument("--no-normalize", action="store_true",
|
|
593
|
+
help="platform presets: measure and report the loudness but deliver the sound as it is (3.x's default)")
|
|
594
|
+
ap.add_argument("--alpha-mode", choices=["straight", "premultiplied"],
|
|
595
|
+
help="alpha presets (prores4444, prores4444xq, qtrle, vp9-alpha, hap-alpha): write the colour straight "
|
|
596
|
+
"(default, as decoded) or premultiplied by the alpha; written to the result as alpha_mode")
|
|
597
|
+
ap.add_argument("--list", action="store_true", help="list presets and exit")
|
|
598
|
+
add_common(ap, codec=False) # the preset decides the codec; --codec would only be refused
|
|
599
|
+
args = ap.parse_args()
|
|
600
|
+
apply_common(args)
|
|
601
|
+
if args.preset and args.preset not in PRESETS:
|
|
602
|
+
args.preset = resolve_platform(args.preset)
|
|
603
|
+
|
|
604
|
+
if args.list:
|
|
605
|
+
for name, p in PRESETS.items():
|
|
606
|
+
print(f"{name:10s} {p['desc']}")
|
|
607
|
+
return 0
|
|
608
|
+
if not args.input or not args.preset:
|
|
609
|
+
die("input and --preset are required (or use --list)")
|
|
610
|
+
validate_color(args.pad_color, "--pad-color")
|
|
611
|
+
if (args.normalize or args.no_normalize) and args.preset not in PLATFORM_OF:
|
|
612
|
+
flag = "--normalize" if args.normalize else "--no-normalize"
|
|
613
|
+
die(f"{flag} applies to the platform presets ({', '.join(sorted(PLATFORM_OF))}); --preset {args.preset} has no loudness spec to meet",
|
|
614
|
+
hint=f"drop {flag}, or run loudness.py with your own target")
|
|
615
|
+
args.normalize = args.preset in PLATFORM_OF and not args.no_normalize
|
|
616
|
+
|
|
617
|
+
p = PRESETS[args.preset]
|
|
618
|
+
meta = probe(args.input)
|
|
619
|
+
if not meta.get("video"):
|
|
620
|
+
die("input has no video stream")
|
|
621
|
+
# the presets tried delivered one frame of a still (0.04 s, verified; gif failed in its muxer): a
|
|
622
|
+
# delivery has a length, and insert.py times a still (#531)
|
|
623
|
+
refuse_still(meta, args.input, "a delivery is a clip with a length, and a still has none")
|
|
624
|
+
notes: List[str] = []
|
|
625
|
+
if p.get("hdr_only") and not meta["video"].get("bt2020_or_hdr"):
|
|
626
|
+
# The point of this preset is that the delivery stays HDR. Running it on an SDR source
|
|
627
|
+
# would write a 10-bit HEVC file labelled with SDR tags and call it an HDR delivery.
|
|
628
|
+
die(f"--preset {args.preset} delivers HDR and this source is SDR ({meta['video'].get('codec')}, "
|
|
629
|
+
f"{meta['video'].get('color_transfer') or 'untagged'})",
|
|
630
|
+
hint="use --preset youtube for an SDR delivery; there is no way to invent HDR range from an SDR master")
|
|
631
|
+
if meta["video"].get("bt2020_or_hdr") and not p.get("intermediate") and args.preset not in ("copy", "youtube-hdr"):
|
|
632
|
+
# 2.0: `hdr` is a real PQ/HLG/DV signal; bt2020_or_hdr also covers BT.2020 SDR, which is
|
|
633
|
+
# not HDR but still needs converting before BT.709 tags describe it (eval 24 h1)
|
|
634
|
+
kind = "HDR" if meta["video"].get("hdr") else "wide-gamut SDR, not HDR"
|
|
635
|
+
notes.append("source is %s (%s). This preset outputs SDR BT.709 tags without converting it; run color.py --to-sdr first for correct colours." % (kind, meta["video"].get("hdr_format")))
|
|
636
|
+
warn(notes[-1], "colour_not_converted", preset=args.preset, hdr_format=meta["video"].get("hdr_format"))
|
|
637
|
+
has_audio = bool(meta.get("audio"))
|
|
638
|
+
source_alpha = None
|
|
639
|
+
if p.get("alpha"):
|
|
640
|
+
encoder = p["video"][p["video"].index("-c:v") + 1]
|
|
641
|
+
encoders = ffmpeg_encoders()
|
|
642
|
+
if encoders and encoder not in encoders:
|
|
643
|
+
die(f"--preset {args.preset} needs the {encoder} encoder and this ffmpeg build has none"
|
|
644
|
+
+ (" (HAP needs an ffmpeg built with snappy)" if encoder == "hap" else ""),
|
|
645
|
+
kind="missing_tool", error_extra={"reason": "encoder_missing", "details": {"name": encoder}},
|
|
646
|
+
hint="python3 scripts/_contract.py doctor lists the encoders this build has")
|
|
647
|
+
if encoder == "hap" and (meta["video"]["width"] % 4 or meta["video"]["height"] % 4):
|
|
648
|
+
die(f"--preset hap-alpha needs a width and height that are multiples of 4 (HAP's texture blocks); "
|
|
649
|
+
f"this source is {meta['video']['width']}x{meta['video']['height']}",
|
|
650
|
+
hint="crop or pad it first (crop.py, pad.py)")
|
|
651
|
+
# a pixel format with an alpha plane, or a VP9 stream stored with one (probed as yuv420p);
|
|
652
|
+
# a dry run decides on these metadata reads alone and decodes nothing
|
|
653
|
+
has_alpha_plane = bool(_ALPHA_PIX.match(meta["video"].get("pix_fmt") or "")) or vp9_alpha_tagged(args.input)
|
|
654
|
+
# a VP9 source stored with alpha on a build whose decoder list was read without libvpx-vp9
|
|
655
|
+
# is refused (decoder_missing) before it is measured: FFmpeg's own VP9 decoder reads it
|
|
656
|
+
# opaque, so the source and the written line both measured 255 and the alpha step passed
|
|
657
|
+
# with the transparency gone (#433 review). An unreadable list keeps the decoder named.
|
|
658
|
+
dec_args = decoder_args_for(meta, args.input)
|
|
659
|
+
if not STATE.dry_run:
|
|
660
|
+
source_alpha = alpha_stats(args.input, meta["video"].get("codec"))
|
|
661
|
+
if not has_alpha_plane and (STATE.dry_run or source_alpha is None or source_alpha["min"] >= OPAQUE):
|
|
662
|
+
die(f"--preset {args.preset} keeps an alpha channel and this source has none "
|
|
663
|
+
f"({meta['video'].get('pix_fmt')}, fully opaque): use prores or dnxhr-* for an opaque master")
|
|
664
|
+
elif args.alpha_mode:
|
|
665
|
+
die("--alpha-mode applies only to the alpha presets (prores4444, prores4444xq, qtrle, vp9-alpha, hap-alpha)")
|
|
666
|
+
# copy keeps the source's container, so its default name keeps the source's extension (as
|
|
667
|
+
# metadata.py's does): default_output()'s .webm -> .mp4 is for the re-encoding presets
|
|
668
|
+
output = args.output or default_output(args.input, args.preset, p["ext"] or Path(args.input).suffix.lstrip(".") or None)
|
|
669
|
+
out_ext = Path(output).suffix.lstrip(".").lower()
|
|
670
|
+
# The runner's picture check looks for a video encoder. Copy and GIF do not name one.
|
|
671
|
+
if args.preset in ("copy", "gif") and "." + out_ext in AUDIO_MEDIA_EXT:
|
|
672
|
+
refuse("input", "output_extension_audio_only",
|
|
673
|
+
f"output {output!r}: .{out_ext} holds sound only, and --preset {args.preset} writes a picture",
|
|
674
|
+
hint="name a video file for this preset, or extract the sound with cut.py or audio.py",
|
|
675
|
+
output=output, extension="." + out_ext, encoders=["gif"] if args.preset == "gif" else [])
|
|
676
|
+
|
|
677
|
+
vf: List[str] = []
|
|
678
|
+
picture_filters: List[str] = []
|
|
679
|
+
# A GIF is RGB: an untagged SDR source is labelled BT.709 (tags only) for palettegen's conversion,
|
|
680
|
+
# which read "unknown" as BT.601 (C03028 came out B31F28, #410); a tagged one is read by its tag
|
|
681
|
+
gif_label = bt709_label_filter(meta) if args.preset == "gif" else None
|
|
682
|
+
if p["w"] and not args.no_scale:
|
|
683
|
+
if p["h"]:
|
|
684
|
+
if args.fit == "crop":
|
|
685
|
+
warn_mostly_cropped(meta.get("video"), p["w"], p["h"])
|
|
686
|
+
picture_filters = [f"scale={p['w']}:{p['h']}:force_original_aspect_ratio=increase", f"crop={p['w']}:{p['h']}"]
|
|
687
|
+
vf.extend(picture_filters)
|
|
688
|
+
else:
|
|
689
|
+
# a --pad-color with chroma is drawn in the BT.709 the line is tagged with; a GIF is
|
|
690
|
+
# not tagged, and palettegen reads the pad back with the same BT.601 it was drawn in
|
|
691
|
+
vf.append(pad_filters(p["w"], p["h"], args.pad_fill, args.pad_color, args.pad_blur,
|
|
692
|
+
meta=None if args.preset == "gif" else meta))
|
|
693
|
+
if not STATE.dry_run:
|
|
694
|
+
picture_filters = [pad_filters(p["w"], p["h"], args.pad_fill, args.pad_color,
|
|
695
|
+
args.pad_blur, meta=meta, blank=True)]
|
|
696
|
+
vf.append("setsar=1")
|
|
697
|
+
else:
|
|
698
|
+
vf.append(f"scale={p['w']}:-2")
|
|
699
|
+
# sized in square pixels: a non-square-pixel master is squared at its display aspect
|
|
700
|
+
# first, or the preset's frame would squash it (#411)
|
|
701
|
+
if square_pixels(meta["video"]):
|
|
702
|
+
vf.insert(0, square_pixels(meta["video"]))
|
|
703
|
+
note(square_pixels_note(meta["video"]))
|
|
704
|
+
if args.repair and args.preset != "copy":
|
|
705
|
+
die("--repair is a remux: use it with --preset copy (a re-encoding preset already rebuilds every frame)")
|
|
706
|
+
if args.max_mb is not None and args.preset == "gif":
|
|
707
|
+
# the GIF branch below returns before the size is ever applied or measured
|
|
708
|
+
die("--max-mb runs a two-pass x264 encode; --preset gif does not encode with x264 (shorten or shrink the GIF instead)")
|
|
709
|
+
if args.max_mb is not None and p.get("keyfill"):
|
|
710
|
+
# the key/fill branch below writes ProRes and returns before the size is applied or measured
|
|
711
|
+
die("--max-mb runs a two-pass x264 encode; --preset key-fill writes ProRes (a fill and a key), which has no size target")
|
|
712
|
+
# an alpha source in VP9 is decoded with libvpx-vp9, or its alpha never reaches the encoder
|
|
713
|
+
# (decoder_args_for, above: [] for anything that is not VP9 stored with alpha)
|
|
714
|
+
dec_args = dec_args if p.get("alpha") else []
|
|
715
|
+
cmd = ffmpeg_base() + (REPAIR_INPUT_ARGS if args.repair else []) + dec_args + ["-i", args.input]
|
|
716
|
+
# Subtitle and data streams (a soft-subtitle track muxed upstream, a camera's timecode) are
|
|
717
|
+
# kept where the container can hold them: ffmpeg's default stream selection takes one video
|
|
718
|
+
# and one audio stream only, and through 2.22.1 every preset dropped the rest without a word.
|
|
719
|
+
# The picture and the sound are mapped on every export, the same streams probe() describes:
|
|
720
|
+
# until A118 they were mapped only beside a subtitle or data stream, and without one ffmpeg's
|
|
721
|
+
# default selection took the larger picture and the track with the default disposition or the
|
|
722
|
+
# most channels, so which audio track an export kept depended on whether it had subtitles.
|
|
723
|
+
subs = meta.get("subtitle_stream_details") or []
|
|
724
|
+
data = _data_streams(args.input) if meta.get("data_streams") else []
|
|
725
|
+
sub_codecs = [_subtitle_codec(s.get("codec") or "", out_ext) for s in subs]
|
|
726
|
+
if args.preset != "gif" and not p.get("keyfill"):
|
|
727
|
+
cmd += probed_maps(meta, audio=has_audio)
|
|
728
|
+
|
|
729
|
+
if args.preset == "gif":
|
|
730
|
+
chain = ",".join(([gif_label] if gif_label else []) + ["fps=12"] + vf)
|
|
731
|
+
fc = f"[0:{PROBED_VIDEO}]{chain},split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle"
|
|
732
|
+
cmd += ["-filter_complex", fc, "-loop", "0", output]
|
|
733
|
+
run(cmd)
|
|
734
|
+
info(f"wrote {output}")
|
|
735
|
+
non_av = _non_av_report(subs, [], data, ["subtitle", "data"], output, "gif")
|
|
736
|
+
if non_av["dropped"]:
|
|
737
|
+
notes.append(f"a GIF holds no subtitle or data stream: the source's {len(non_av['dropped'])} were not written")
|
|
738
|
+
emit(output, non_av_streams=non_av, dropped_non_av_streams=bool(non_av["dropped"]), **({"notes": notes} if notes else {}))
|
|
739
|
+
return 0
|
|
740
|
+
|
|
741
|
+
if p.get("keyfill"):
|
|
742
|
+
return _key_fill(args, p, meta, output, cmd, vf, has_audio, source_alpha, notes, subs, data)
|
|
743
|
+
if p.get("alpha") and args.alpha_mode == "premultiplied":
|
|
744
|
+
vf.append("premultiply=inplace=1")
|
|
745
|
+
if vf:
|
|
746
|
+
cmd += ["-vf", ",".join(vf)]
|
|
747
|
+
video = list(p["video"])
|
|
748
|
+
if p.get("codec"):
|
|
749
|
+
# encoder_args() is the one place that turns a codec name into encoder options: it keeps
|
|
750
|
+
# the source's HDR tags for hevc and refuses (kind: missing_tool) when no AV1 encoder is
|
|
751
|
+
# built, which is exactly what these two presets promise.
|
|
752
|
+
video = encoder_args(p["codec"], args.crf if args.crf is not None else (20 if p["codec"] == "hevc" else 32),
|
|
753
|
+
"veryfast" if STATE.fast else "medium", meta)
|
|
754
|
+
# encoder_args() already applied --fast (its own preset scale per encoder: SVT-AV1 counts
|
|
755
|
+
# 1..12, not x264's names) and appends +faststart, which this tool adds again for mp4
|
|
756
|
+
as_built = list(video)
|
|
757
|
+
while "-movflags" in video:
|
|
758
|
+
i = video.index("-movflags")
|
|
759
|
+
del video[i:i + 2]
|
|
760
|
+
restate_last_swap(as_built, video)
|
|
761
|
+
if args.crf is not None and "-crf" in video:
|
|
762
|
+
video[video.index("-crf") + 1] = str(args.crf)
|
|
763
|
+
if STATE.fast and "-preset" in video and not p.get("codec"):
|
|
764
|
+
video[video.index("-preset") + 1] = "veryfast"
|
|
765
|
+
# a fixed preset's line is tagged BT.709 (prores and dnxhr, editing masters, keep the source's tags)
|
|
766
|
+
tag_bt709 = not p.get("intermediate") and not p.get("codec")
|
|
767
|
+
if p.get("alpha") and STATE.hw and video and video[video.index("-c:v") + 1] == "prores_ks":
|
|
768
|
+
# VideoToolbox's ProRes line is 422 HQ: under --hw a 4444 alpha master would come out
|
|
769
|
+
# opaque, so these presets stay on prores_ks and say so
|
|
770
|
+
note(f"--hw: --preset {args.preset} stays on prores_ks: VideoToolbox's ProRes encoder writes 422 HQ, "
|
|
771
|
+
"without the alpha this preset keeps")
|
|
772
|
+
elif not p.get("codec") and video:
|
|
773
|
+
# --hw (never $FFMPEG_SKILL_HW here) puts a fixed preset on VideoToolbox: the same codec,
|
|
774
|
+
# its CRF mapped to -q:v, the preset's frame rate kept; tags come with the VT line itself.
|
|
775
|
+
# A build without libx264/libx265 has no other encoder, so it goes there without --hw too
|
|
776
|
+
# (hw_preset_video returns the line untouched in every other case)
|
|
777
|
+
video = hw_preset_video(video, meta, bt709=tag_bt709)
|
|
778
|
+
if args.max_mb is not None:
|
|
779
|
+
video = size_video_args(args, video, p, meta, has_audio)
|
|
780
|
+
cmd += video + enlarge_args(meta, *((None, None) if args.no_scale else (p["w"], p["h"])))
|
|
781
|
+
if args.preset != "copy":
|
|
782
|
+
# a stream copy can't be frame-rate-conformed or retagged without decoding it — that would
|
|
783
|
+
# no longer be a copy, and would silently mislabel colour the agent never actually looked at
|
|
784
|
+
rate_args: List[str] = []
|
|
785
|
+
if "-r" not in video:
|
|
786
|
+
rate_args = _platform_rate_args(args.preset, meta) or cfr_args(meta)
|
|
787
|
+
cmd += rate_args
|
|
788
|
+
# the rate the line delivers (a preset's own -r, a platform's divided rate, or a VFR
|
|
789
|
+
# source's average) is reached by the fps filter, the nearest frame for each slot: the
|
|
790
|
+
# encoder line's -r alone let a frame run up to two frames late against the sound before
|
|
791
|
+
# it dropped one (#512)
|
|
792
|
+
rate_f = (f"fps={video[video.index('-r') + 1]}" if "-r" in video
|
|
793
|
+
else f"fps={rate_args[rate_args.index('-r') + 1]}" if "-r" in rate_args else "")
|
|
794
|
+
# it is placed as with_cfr() places it: first in a -vf that is a graph (a blur pad's
|
|
795
|
+
# split/overlay, a drawn pad's maskedmerge), whose last frame an fps filter after it lost
|
|
796
|
+
# on FFmpeg 6.1 (reels --pad-fill blur: 119 frames of a 4 s 30 fps picture)
|
|
797
|
+
if rate_f and "-vf" in cmd:
|
|
798
|
+
cmd[cmd.index("-vf") + 1] = chain_with_rate(cmd[cmd.index("-vf") + 1], rate_f)
|
|
799
|
+
elif rate_f:
|
|
800
|
+
cmd += ["-vf", rate_f]
|
|
801
|
+
if tag_bt709 and not video[video.index("-c:v") + 1].endswith("_videotoolbox"):
|
|
802
|
+
cmd += bt709_tag_args(video[video.index("-c:v") + 1])
|
|
803
|
+
hdr = bool(meta["video"].get("bt2020_or_hdr"))
|
|
804
|
+
if not p.get("intermediate") and not (p.get("codec") and hdr):
|
|
805
|
+
# every line but an editing master's (prores, dnxhr) says BT.709 (the fixed presets' tags above, an
|
|
806
|
+
# SDR hevc/av1 line's own): a BT.601 or RGB source's pixels are converted to match (an HDR RGB one
|
|
807
|
+
# too, #559), in front of the -vf above (run() folds the two); an untagged or BT.709 YUV source adds nothing
|
|
808
|
+
cmd += bt709_matrix_args(meta)
|
|
809
|
+
yuva = "-pix_fmt" in video and video[video.index("-pix_fmt") + 1].startswith("yuva")
|
|
810
|
+
master = bool(p.get("intermediate") and hdr and (yuva or not p.get("alpha"))) # qtrle and hap keep their RGB
|
|
811
|
+
if master:
|
|
812
|
+
# an editing master of a BT.2020 / HDR source keeps its primaries and transfer and says the matrix
|
|
813
|
+
# it converted with, as --codec prores does and as a YUV source's frames already did (#559)
|
|
814
|
+
cmd += hdr_tag_args(meta)
|
|
815
|
+
if p.get("codec") or master:
|
|
816
|
+
# encoder_args()' line for a BT.2020 / HDR source tags that source's matrix: an RGB
|
|
817
|
+
# one is made YUV with it, not with FFmpeg's BT.601 default (#544)
|
|
818
|
+
cmd += hdr_rgb_matrix_args(meta, alpha=yuva)
|
|
819
|
+
if out_ext == "mp4":
|
|
820
|
+
cmd += ["-movflags", "+faststart"]
|
|
821
|
+
if args.repair:
|
|
822
|
+
cmd += ["-avoid_negative_ts", "make_zero"]
|
|
823
|
+
cmd += (p["audio"] if has_audio else ["-an"])
|
|
824
|
+
trimmed = None
|
|
825
|
+
if p["max"] and not args.allow_long and (meta.get("duration") or 0) > p["max"]:
|
|
826
|
+
# the preset's promise (the platform's maximum), but the caller loses the tail: say how much
|
|
827
|
+
# in the document (`trimmed`, `notes`), not only on stderr. -t is an output option, so a
|
|
828
|
+
# kept subtitle track is cut at the same point (a cue after it is not written)
|
|
829
|
+
trimmed = {"from": round(float(meta["duration"]), 3), "to": round(float(p["max"]), 3)}
|
|
830
|
+
note(f"trimmed from {trimmed['from']:.3f}s to the {args.preset} maximum of {p['max']:.0f}s "
|
|
831
|
+
f"(this tool's table as of {UPLOAD_LIMITS_AS_OF}, and platforms change it: "
|
|
832
|
+
"use --allow-long to keep full length)")
|
|
833
|
+
cmd += ["-t", f"{p['max']:.3f}"]
|
|
834
|
+
if args.duration and not (trimmed and args.duration >= p["max"]):
|
|
835
|
+
cmd += ["-t", f"{args.duration:.3f}"]
|
|
836
|
+
damage_before = media_damage(args.input) if args.repair and not STATE.dry_run else None
|
|
837
|
+
with tempfile.TemporaryDirectory(prefix="ffskill_2pass_") as passdir:
|
|
838
|
+
if args.max_mb is not None:
|
|
839
|
+
# pass 1 only writes x264's statistics; pass 2 encodes against them
|
|
840
|
+
log = os.path.join(passdir, "x264")
|
|
841
|
+
run(cmd + ["-pass", "1", "-passlogfile", log, "-an", "-sn", "-dn", "-f", "null", "-"])
|
|
842
|
+
cmd += ["-pass", "2", "-passlogfile", log]
|
|
843
|
+
dropped = _run_keeping_non_av(cmd, output, sub_codecs, len(data)) if (subs or data) else []
|
|
844
|
+
if not (subs or data):
|
|
845
|
+
run(cmd + [output])
|
|
846
|
+
if not STATE.dry_run:
|
|
847
|
+
# the export is on disk: a stop in the reads and the --normalize pass that follow keeps it,
|
|
848
|
+
# and says so (#415)
|
|
849
|
+
mark_delivered(output)
|
|
850
|
+
result = probe(output, role="output")
|
|
851
|
+
v = result.get("video") or {}
|
|
852
|
+
if v:
|
|
853
|
+
info(f"wrote {output} ({fmt_secs(result['duration'])}, {v['width']}x{v['height']}, {v['codec']})")
|
|
854
|
+
extra: Dict[str, object] = {"trimmed": trimmed} if trimmed else {}
|
|
855
|
+
encoder = video[video.index("-c:v") + 1] if "-c:v" in video else None
|
|
856
|
+
if p.get("expect") and not STATE.dry_run and encoder == p["video"][p["video"].index("-c:v") + 1]:
|
|
857
|
+
# an editing master is asked for by codec, profile and pixel format: read all three back
|
|
858
|
+
# (a VideoToolbox prores line under --hw writes its own pixel format, so it is not compared)
|
|
859
|
+
measured = {k: v.get(k) for k in p["expect"]}
|
|
860
|
+
extra.setdefault("verification", []).append(
|
|
861
|
+
{"step": "codec", "property": "codec_profile_pix_fmt", "ok": measured == p["expect"],
|
|
862
|
+
"expected": dict(p["expect"]), "measured": measured, "provenance": "specification"})
|
|
863
|
+
if p.get("alpha"):
|
|
864
|
+
extra["alpha_mode"] = args.alpha_mode or "straight"
|
|
865
|
+
if not STATE.dry_run:
|
|
866
|
+
# the alpha survived when every written frame's alpha matches the source frame's (an
|
|
867
|
+
# encoder, decoder or muxer that drops it reads fully opaque); premultiplying changes
|
|
868
|
+
# colour, not alpha
|
|
869
|
+
written_alpha = alpha_stats(output, v.get("codec"))
|
|
870
|
+
cmp = _alpha_compare(written_alpha, source_alpha)
|
|
871
|
+
extra.setdefault("verification", []).append(
|
|
872
|
+
{"step": "alpha", "property": "alpha_mean", "ok": cmp["ok"], "comparison": cmp,
|
|
873
|
+
"expected": None if source_alpha is None else round(source_alpha["mean"], 2),
|
|
874
|
+
"measured": None if written_alpha is None else round(written_alpha["mean"], 2), "tolerance": ALPHA_TOLERANCE,
|
|
875
|
+
"frames": {"expected": _rounded(source_alpha), "measured": _rounded(written_alpha)},
|
|
876
|
+
"provenance": "input_premeasurement"})
|
|
877
|
+
platform = PLATFORM_OF.get(args.preset)
|
|
878
|
+
if platform and has_audio and not STATE.dry_run:
|
|
879
|
+
# Every eval run that exported for a platform then had to come back with loudness.py: the
|
|
880
|
+
# preset scales and tags but does not touch levels, and only check.py said so. Measure the
|
|
881
|
+
# written file here so the result names the gap and the caller plans one pass, not two.
|
|
882
|
+
spec = PLATFORMS[platform]
|
|
883
|
+
m = measure_loudness(output)
|
|
884
|
+
written_audio = probe(output, role="output").get("audio") or {}
|
|
885
|
+
if (m and not math.isfinite(m["lufs"]) and math.isfinite(m["tp"]) and m["tp"] > SILENT_PEAK_DBFS
|
|
886
|
+
and shorter_than_a_loudness_block(own_length(written_audio))):
|
|
887
|
+
# A257: too short for a gating block is not silent (it has a measured peak); a longer
|
|
888
|
+
# track under the gate is not "too short" and takes the path it took before
|
|
889
|
+
_loudness_unmeasured(extra, notes, platform, spec, tp=m["tp"])
|
|
890
|
+
m = {}
|
|
891
|
+
elif not m:
|
|
892
|
+
_loudness_unmeasured(extra, notes, platform, spec)
|
|
893
|
+
if m:
|
|
894
|
+
ok = abs(m["lufs"] - spec["lufs"]) <= spec["lufs_tol"] and m["tp"] <= spec["tp"] + TP_TOLERANCE_DB
|
|
895
|
+
extra["loudness"] = {"lufs": m["lufs"], "tp": m["tp"], "target_lufs": spec["lufs"],
|
|
896
|
+
"target_tp": spec["tp"], "ok": ok, "normalized": False}
|
|
897
|
+
extra["verification"] = [_loudness_step(ok, platform, spec, m)]
|
|
898
|
+
if not math.isfinite(m["lufs"]):
|
|
899
|
+
# a silent output measures -inf LUFS: no gain reaches the target, so recommending
|
|
900
|
+
# (or running, under --normalize) loudness.py only returns "nothing to normalise"
|
|
901
|
+
extra["loudness"]["silent"] = True
|
|
902
|
+
notes.append(f"output audio is silent (integrated loudness -inf, {platform} expects {spec['lufs']:g} LUFS); "
|
|
903
|
+
"check the source's audio or give the export a real track (audio.py --replace)")
|
|
904
|
+
warn(notes[-1], "output_audio_silent", platform=platform)
|
|
905
|
+
elif not ok and args.normalize:
|
|
906
|
+
# Eval 7: every platform job ran export -> loudness.py -> export again (two video
|
|
907
|
+
# encodes). The levels pass only re-encodes audio, so do it here on the written
|
|
908
|
+
# file and the caller gets one export that meets the spec.
|
|
909
|
+
info(f"loudness {m['lufs']:.1f} LUFS / {m['tp']:+.1f} dBTP is outside {platform}'s spec; normalising to {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP")
|
|
910
|
+
# a private name: <stem>_loudnorm.<ext> is loudness.py's own default output, so a
|
|
911
|
+
# real file of that name next to the export was overwritten and renamed away (review 7)
|
|
912
|
+
tmp = str(Path(output).with_name(f".{Path(output).stem}.normalize-{os.getpid()}{Path(output).suffix}"))
|
|
913
|
+
# under --max-mb the sound is re-encoded at the bitrate the size budget was built on
|
|
914
|
+
# (the preset's); loudness.py's own 192k, raised to 256k/320k on an overshoot, put
|
|
915
|
+
# the file over the limit it had been encoded to meet (through 3.8.8, audit A112)
|
|
916
|
+
pinned = (["--audio-bitrate", p["audio"][p["audio"].index("-b:a") + 1]]
|
|
917
|
+
if args.max_mb is not None and "-b:a" in p["audio"] else [])
|
|
918
|
+
proc = run_tool([str(HERE / "loudness.py"), output, "-I", f"{spec['lufs']:g}", "--tp", f"{spec['tp']:g}", "-o", tmp, "--json"]
|
|
919
|
+
+ pinned + child_args())
|
|
920
|
+
try:
|
|
921
|
+
child = json.loads(proc.stdout)
|
|
922
|
+
except ValueError:
|
|
923
|
+
child = {}
|
|
924
|
+
STATE.commands.extend(child.get("commands") or []) # the encode that changed the audio belongs in this run's log
|
|
925
|
+
if proc.returncode != 0 or child.get("status") != "completed":
|
|
926
|
+
err = child.get("error") or {}
|
|
927
|
+
if os.path.exists(tmp):
|
|
928
|
+
os.remove(tmp)
|
|
929
|
+
# the child's "nothing was written" is about its own temp file; this run's export is
|
|
930
|
+
# on disk, and the child's exit code (124 timeout, 130/143 interrupted) is the
|
|
931
|
+
# run's, as render.py and waveform.py pass a stage's on (#415)
|
|
932
|
+
why = (err.get("message") or proc.stderr.strip()[-300:]).replace("; nothing was written", "")
|
|
933
|
+
die(f"--normalize: loudness.py failed: {why} ({kept_clause()})",
|
|
934
|
+
code=child_exit_code(child, proc.returncode) if proc.returncode else 1,
|
|
935
|
+
kind=err.get("kind") or "ffmpeg", output=output, hint=err.get("hint"))
|
|
936
|
+
# the export this run wrote, unless another process replaced it during the pass
|
|
937
|
+
replace_checked(tmp, output)
|
|
938
|
+
m = measure_loudness(output)
|
|
939
|
+
if not m:
|
|
940
|
+
# the file changed: the measurement before --normalize no longer describes it
|
|
941
|
+
_loudness_unmeasured(extra, notes, platform, spec, normalized=True)
|
|
942
|
+
ok = True # nothing more to say about a level that was not measured
|
|
943
|
+
else:
|
|
944
|
+
ok = abs(m["lufs"] - spec["lufs"]) <= spec["lufs_tol"] and m["tp"] <= spec["tp"] + TP_TOLERANCE_DB
|
|
945
|
+
extra["loudness"] = {"lufs": m["lufs"], "tp": m["tp"], "target_lufs": spec["lufs"], "target_tp": spec["tp"], "ok": ok, "normalized": True}
|
|
946
|
+
extra["verification"] = [_loudness_step(ok, platform, spec, m)]
|
|
947
|
+
if not ok:
|
|
948
|
+
notes.append(f"loudness is still {m['lufs']:.1f} LUFS / {m['tp']:+.1f} dBTP after loudness.py (target {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP): {child.get('result', {}).get('note') or 'the encoder overshoots the ceiling'}")
|
|
949
|
+
warn(notes[-1], "loudness_outside_spec", platform=platform, lufs=m["lufs"], tp=m["tp"], normalized=True)
|
|
950
|
+
elif not ok:
|
|
951
|
+
notes.append(f"loudness {m['lufs']:.1f} LUFS / {m['tp']:+.1f} dBTP is outside {platform}'s {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP; "
|
|
952
|
+
f"run loudness.py -I {spec['lufs']:g} --tp {spec['tp']:g} on this file, or export with --normalize")
|
|
953
|
+
warn(notes[-1], "loudness_outside_spec", platform=platform, lufs=m["lufs"], tp=m["tp"], normalized=False)
|
|
954
|
+
if m:
|
|
955
|
+
correction = "after correction" if extra["loudness"]["normalized"] else "without export correction"
|
|
956
|
+
info(f"loudness measured {correction}: {m['lufs']:.1f} LUFS / {m['tp']:+.1f} dBTP "
|
|
957
|
+
f"(target {spec['lufs']:g} LUFS / {spec['tp']:g} dBTP)")
|
|
958
|
+
elif platform and not has_audio and not STATE.dry_run:
|
|
959
|
+
record_skip(f"no loudness check against {platform}'s spec: the source has no audio, so the export has none",
|
|
960
|
+
"loudness_no_audio", platform=platform)
|
|
961
|
+
elif platform and has_audio and args.normalize:
|
|
962
|
+
spec = PLATFORMS[platform]
|
|
963
|
+
notes.append(f"[dry-run] --normalize: loudness.py -I {spec['lufs']:g} --tp {spec['tp']:g} would run on the written file if it misses {platform}'s spec")
|
|
964
|
+
if p["max"] and not args.allow_long and not STATE.dry_run:
|
|
965
|
+
# the preset's length promise, measured the way check.py measures it (the container's
|
|
966
|
+
# duration, no tolerance): before 2.20 nothing re-read the length, and a --normalize pass
|
|
967
|
+
# that left the sound 0.1 s long shipped a 90.10 s Reels file as verified
|
|
968
|
+
written = probe(output, role="output").get("duration")
|
|
969
|
+
if written is not None:
|
|
970
|
+
step = {"step": "duration", "property": "duration", "ok": written <= p["max"],
|
|
971
|
+
"expected": {"max": p["max"]}, "measured": round(written, 3),
|
|
972
|
+
"delta": round(written - p["max"], 3), "tolerance": 0.0, "provenance": "specification"}
|
|
973
|
+
else:
|
|
974
|
+
# the preset promised a length; one that could not be read is not one that held
|
|
975
|
+
step = {"step": "duration", "property": "duration", "ok": False, "expected": {"max": p["max"]},
|
|
976
|
+
"reason": "not_measured: the written file reports no duration"}
|
|
977
|
+
extra.setdefault("verification", []).append(step)
|
|
978
|
+
if damage_before is not None:
|
|
979
|
+
after = media_damage(output)
|
|
980
|
+
extra["repair"] = {"before": damage_before, "after": after}
|
|
981
|
+
# judged on timestamp warnings, the part a remux rewrites: decode errors are counted in log
|
|
982
|
+
# lines, and the same damaged frame logs a different number of them demuxed from another
|
|
983
|
+
# container, so their before/after is reported, not compared
|
|
984
|
+
stamps = after["timestamp_warnings"]
|
|
985
|
+
extra.setdefault("verification", []).append(
|
|
986
|
+
{"step": "repair", "property": "timestamp_warnings", "ok": stamps <= damage_before["timestamp_warnings"],
|
|
987
|
+
"expected": {"max": damage_before["timestamp_warnings"]}, "measured": stamps,
|
|
988
|
+
"provenance": "input_premeasurement"})
|
|
989
|
+
if after["decode_errors"]:
|
|
990
|
+
notes.append(f"--repair: {after['decode_errors']} decode error(s) remain: a remux drops corrupt packets and "
|
|
991
|
+
"rewrites timestamps but cannot rebuild a damaged frame; a re-encoding preset decodes past them")
|
|
992
|
+
warn(notes[-1], "repair_incomplete", **after)
|
|
993
|
+
if args.max_mb is not None and not STATE.dry_run:
|
|
994
|
+
limit = int(args.max_mb * MIB)
|
|
995
|
+
size = os.path.getsize(output)
|
|
996
|
+
extra.setdefault("verification", []).append(
|
|
997
|
+
{"step": "file_size", "property": "size_bytes", "ok": size <= limit, "expected": {"max": limit},
|
|
998
|
+
"measured": size, "delta": size - limit, "tolerance": 0, "provenance": "user_specified"})
|
|
999
|
+
if size > limit:
|
|
1000
|
+
notes.append(f"--max-mb {args.max_mb:g}: the file is {size / MIB:.2f} MiB, over the limit; the encoder overshot "
|
|
1001
|
+
f"its target bitrate on this content: export again with a lower --max-mb")
|
|
1002
|
+
warn(notes[-1], "size_over_limit", size=size, limit=limit)
|
|
1003
|
+
# read back after --normalize, which rewrote the file
|
|
1004
|
+
non_av = _non_av_report(subs, sub_codecs, data, dropped, output, "write_failed")
|
|
1005
|
+
if non_av["dropped"]:
|
|
1006
|
+
notes.append(f"{len(non_av['dropped'])} subtitle/data stream(s) of the source are not in {os.path.basename(output)} "
|
|
1007
|
+
f"({', '.join(sorted({d['type'] + ': ' + d['reason'] for d in non_av['dropped']}))}); non_av_streams lists them")
|
|
1008
|
+
extra["non_av_streams"] = non_av
|
|
1009
|
+
extra["dropped_non_av_streams"] = bool(non_av["dropped"])
|
|
1010
|
+
if picture_filters and not STATE.dry_run:
|
|
1011
|
+
sw, sh = display_size(meta["video"])
|
|
1012
|
+
scale, cropped = (None, None)
|
|
1013
|
+
if args.fit == "crop" and sw and sh:
|
|
1014
|
+
scale, cropped = _center_crop_geometry(sw, sh, p["w"], p["h"])
|
|
1015
|
+
written_video = probe(output, role="output").get("video") or {}
|
|
1016
|
+
matrix = hdr_rgb_matrix_filter(meta) if p.get("codec") else None
|
|
1017
|
+
extra["picture"] = measure_picture((picture_filters, scale, cropped), meta, sw, sh, written_video,
|
|
1018
|
+
sized=True, matrix_filter=matrix or bt709_matrix_filter(meta))
|
|
1019
|
+
if notes:
|
|
1020
|
+
extra["notes"] = notes
|
|
1021
|
+
# the delivery keeps the source's picture and, except as a GIF, its sound
|
|
1022
|
+
streams = {"video": 1, "audio": int(has_audio)}
|
|
1023
|
+
_verify_delivery(args, p, meta, output, streams, encoder, extra)
|
|
1024
|
+
extra["expect_streams"] = streams
|
|
1025
|
+
extra["stream_reference"] = [meta]
|
|
1026
|
+
if trimmed: # only the kept 0..max of the source can have handed its gap to the output
|
|
1027
|
+
extra["stream_windows"] = [(0.0, float(p["max"]))]
|
|
1028
|
+
emit(output, **extra)
|
|
1029
|
+
return 0
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
if __name__ == "__main__":
|
|
1033
|
+
sys.exit(main())
|