@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,3994 @@
|
|
|
1
|
+
"""Process execution for ffmpeg-skill: locating the tools, running them under a wall-clock
|
|
2
|
+
ceiling, signal handling, output locking and staging, and the drawtext text-file spool.
|
|
3
|
+
|
|
4
|
+
Nothing here decides *what* to encode -- that is decision.py -- and nothing here formats a result
|
|
5
|
+
document -- that is emit.py. Imported through the `_common` facade by every script.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import platform
|
|
12
|
+
import argparse
|
|
13
|
+
import contextlib
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
INSTALL_HINTS = {
|
|
22
|
+
"Darwin": (" brew install ffmpeg-full; export PATH=\"$(brew --prefix ffmpeg-full)/bin:$PATH\""
|
|
23
|
+
" # keg-only, so installing it does not put it on PATH: keep the export in your shell profile;"
|
|
24
|
+
" the plain ffmpeg formula lacks subtitles/drawtext/zscale"),
|
|
25
|
+
"Linux": (
|
|
26
|
+
" Debian/Ubuntu: sudo apt install ffmpeg\n"
|
|
27
|
+
" Fedora: sudo dnf install ffmpeg\n"
|
|
28
|
+
" Arch: sudo pacman -S ffmpeg"
|
|
29
|
+
),
|
|
30
|
+
"Windows": (
|
|
31
|
+
" winget install Gyan.FFmpeg\n"
|
|
32
|
+
" or: choco install ffmpeg\n"
|
|
33
|
+
" or download a build from https://ffmpeg.org/download.html and add it to PATH"
|
|
34
|
+
),
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
MCP_PROGRESS_ENV = "FFMPEG_SKILL_MCP_PROGRESS"
|
|
38
|
+
_PROGRESS_PREFIX = "[ffmpeg-skill progress] "
|
|
39
|
+
|
|
40
|
+
# For an FFmpeg that is on PATH but older than MIN_FFMPEG (#467 A226): reinstalling the
|
|
41
|
+
# distribution's package gives the same old version back (Ubuntu 22.04's is 4.4, Debian 12's 5.1),
|
|
42
|
+
# so the hint names a newer build instead.
|
|
43
|
+
UPGRADE_HINTS = {
|
|
44
|
+
"Darwin": " brew upgrade ffmpeg-full # or ffmpeg, whichever formula is installed",
|
|
45
|
+
"Linux": (
|
|
46
|
+
" Your distribution's own package may be older than that (Ubuntu 22.04 ships 4.4, Debian 12 ships 5.1).\n"
|
|
47
|
+
" Use a release whose package is new enough (Ubuntu 24.04, Debian 13), or a static build\n"
|
|
48
|
+
" from https://ffmpeg.org/download.html put ahead of the old one on PATH"
|
|
49
|
+
),
|
|
50
|
+
"Windows": (
|
|
51
|
+
" winget upgrade Gyan.FFmpeg\n"
|
|
52
|
+
" or download a newer build from https://ffmpeg.org/download.html and put it ahead of the old one on PATH"
|
|
53
|
+
),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# `kind` (below) is the machine-readable failure axis: input / missing_tool / ffmpeg / output
|
|
58
|
+
# since 0.1, plus timeout (1.3), verification (1.4.3) and interrupted (1.4.10). `ERROR_CODE` is an
|
|
59
|
+
# additive, purely informational refinement layered on top for agents that want a stable enum to
|
|
60
|
+
# switch on instead of pattern-matching `kind` strings -- a static 1:1 relabelling of the same
|
|
61
|
+
# buckets, not a new taxonomy. It intentionally does NOT introduce categories this codebase cannot actually
|
|
62
|
+
# distinguish today (e.g. a separate ffprobe-vs-ffmpeg code, or an environment-vs-content-cause
|
|
63
|
+
# split of ffmpeg failures): every ffmpeg subprocess failure is currently one undifferentiated
|
|
64
|
+
# bucket regardless of whether ffmpeg rejected a bad filter argument or died from a full disk,
|
|
65
|
+
# and every "kind": "input" failure covers both a missing file and a bad flag value alike. Adding
|
|
66
|
+
# codes for distinctions the code can't actually make would be guessing, not reporting -- if a
|
|
67
|
+
# future call site can genuinely tell capability-missing apart from bad-argument (see doctor()'s
|
|
68
|
+
# available/missing/unknown states, which already model this for detection but aren't wired into
|
|
69
|
+
# any die() call), split ERROR_CODE then, with evidence, not speculatively now.
|
|
70
|
+
ERROR_CODE = {
|
|
71
|
+
"input": "INPUT_INVALID",
|
|
72
|
+
"missing_tool": "DEPENDENCY_MISSING",
|
|
73
|
+
"ffmpeg": "FFMPEG_EXECUTION_FAILED",
|
|
74
|
+
"output": "OUTPUT_INVALID",
|
|
75
|
+
"timeout": "TIMEOUT",
|
|
76
|
+
"verification": "VERIFICATION_FAILED",
|
|
77
|
+
"interrupted": "INTERRUPTED",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# Wall-clock ceiling for one ffmpeg/ffprobe invocation, in seconds. A hung ffmpeg (a build
|
|
82
|
+
# that deadlocks on a filter combination, a stalled network mount, an input that never ends)
|
|
83
|
+
# used to hang the calling agent with it, with no error document and no way out short of
|
|
84
|
+
# killing the process by hand. The ceiling is generous on purpose: it exists to turn a hang
|
|
85
|
+
# into a reported failure, not to police slow encodes. --timeout and FFMPEG_SKILL_TIMEOUT
|
|
86
|
+
# override it; 0 disables it.
|
|
87
|
+
DEFAULT_TIMEOUT = 1800.0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
PROBE_TIMEOUT = 120.0
|
|
91
|
+
|
|
92
|
+
# The largest per-call limit a run accepts (A8). subprocess's communicate() waits in poll(), whose
|
|
93
|
+
# timeout is a C int of milliseconds: past 2147483.647 s (24.8 days) it raised OverflowError after
|
|
94
|
+
# the child had started, so the tool died with a traceback while its ffmpeg ran on (measured on
|
|
95
|
+
# Linux with Python 3.11: `--timeout 1e8` and `1e300` both did). The outer ceiling a run_tool()
|
|
96
|
+
# child gets is 4x the per-call limit plus 60 s (child_limit()), so the per-call limit stops well
|
|
97
|
+
# below a quarter of that: 500000 s, about 5.8 days. 0 is "no limit" and is what a longer job passes.
|
|
98
|
+
MAX_TIMEOUT = 500000.0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _env_timeout() -> float:
|
|
102
|
+
return _read_env_timeout()[0]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _read_env_timeout() -> "Tuple[float, Optional[str]]":
|
|
106
|
+
"""(the per-call limit FFMPEG_SKILL_TIMEOUT sets, why its value was not taken as written or
|
|
107
|
+
None). Unset or blank is the default with nothing to say. A value that is not a number (or is
|
|
108
|
+
NaN) is the default, and a negative one is 0 (no limit) as it always was; both used to pass
|
|
109
|
+
without a word, and apply_common() now records them (`timeout_env_invalid`)."""
|
|
110
|
+
raw = os.environ.get("FFMPEG_SKILL_TIMEOUT")
|
|
111
|
+
if raw is None or not raw.strip():
|
|
112
|
+
return DEFAULT_TIMEOUT, None
|
|
113
|
+
try:
|
|
114
|
+
value = float(raw)
|
|
115
|
+
if value != value:
|
|
116
|
+
raise ValueError("NaN")
|
|
117
|
+
except ValueError:
|
|
118
|
+
return DEFAULT_TIMEOUT, f"FFMPEG_SKILL_TIMEOUT={raw!r} is not a number of seconds; using the default {DEFAULT_TIMEOUT:g} s"
|
|
119
|
+
if value < 0:
|
|
120
|
+
return 0.0, f"FFMPEG_SKILL_TIMEOUT={raw!r} is negative; read as 0, which means no time limit"
|
|
121
|
+
if value > MAX_TIMEOUT:
|
|
122
|
+
# inf, 1e300: longer than a wait can be on this platform, which was an OverflowError
|
|
123
|
+
# traceback once the first child had started
|
|
124
|
+
return 0.0, (f"FFMPEG_SKILL_TIMEOUT={raw!r} is longer than a run can wait for here ({MAX_TIMEOUT:.0f} s); "
|
|
125
|
+
"read as 0, which means no time limit")
|
|
126
|
+
return value, None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# None of the four kinds above are retryable in practice: an "input"/"missing_tool" failure is
|
|
130
|
+
# always deterministic (the same bad path or absent binary fails identically every time), and a
|
|
131
|
+
# "ffmpeg"/"output" failure -- while it COULD in principle be caused by a transient environment
|
|
132
|
+
# condition (full disk, OOM) rather than a bad command -- is never distinguishable from a
|
|
133
|
+
# deterministic content-cause failure without exit-code/stderr sniffing this codebase does not do.
|
|
134
|
+
# Reporting retryable=True for a code we can't actually back up would invite an agent into a blind
|
|
135
|
+
# retry loop against a command that will fail the same way every time; false-for-everything is the
|
|
136
|
+
# honest answer until real sniffing exists to justify anything else.
|
|
137
|
+
ERROR_RETRYABLE = False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
_FFMPEG_VERSION: "Optional[Tuple[int, int]]" = None
|
|
141
|
+
_FFMPEG_VERSION_IS_RELEASE = False # ffmpeg_version() read a release number, not the libavutil major
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _probe_limit() -> float:
|
|
145
|
+
"""The ceiling for a short read-only ffprobe/ffmpeg query run outside run(): PROBE_TIMEOUT, or
|
|
146
|
+
the caller's --timeout when that is lower (#415). Never unlimited: a version or stream-list read
|
|
147
|
+
that hangs is a stall, whatever --timeout 0 asks of the encodes."""
|
|
148
|
+
return min(PROBE_TIMEOUT, STATE.timeout) if STATE.timeout else PROBE_TIMEOUT
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _ffprobe(*args: str) -> "subprocess.CompletedProcess[str]":
|
|
152
|
+
# every short ffprobe question this module asks: text out, stderr dropped, the probe time limit
|
|
153
|
+
return subprocess.run([found_exe("ffprobe"), *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
|
|
154
|
+
encoding="utf-8", errors="replace", timeout=_probe_limit())
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def ffmpeg_version() -> "Tuple[int, int]":
|
|
158
|
+
"""(major, minor) of the FFmpeg build on PATH, parsed once from `ffprobe -version`; (0, 0)
|
|
159
|
+
when it cannot be read. ffprobe rather than ffmpeg because --dry-run promises never to run
|
|
160
|
+
ffmpeg (docs/contract.md: ffmpeg_execution "none") while ffprobe always may, and the two
|
|
161
|
+
ship from the same build. Used only to pick between two spellings of an option where FFmpeg
|
|
162
|
+
changed behaviour between releases (the tools otherwise never branch on the version: doctor's
|
|
163
|
+
capability listing is the source of truth for what a build can do)."""
|
|
164
|
+
global _FFMPEG_VERSION, _FFMPEG_VERSION_IS_RELEASE
|
|
165
|
+
if _FFMPEG_VERSION is None:
|
|
166
|
+
_FFMPEG_VERSION = (0, 0)
|
|
167
|
+
try:
|
|
168
|
+
out = _ffprobe("-version").stdout
|
|
169
|
+
m = re.search(r"ffprobe version\s+n?(\d+)\.(\d+)", out)
|
|
170
|
+
if m:
|
|
171
|
+
_FFMPEG_VERSION = (int(m.group(1)), int(m.group(2)))
|
|
172
|
+
_FFMPEG_VERSION_IS_RELEASE = True
|
|
173
|
+
else:
|
|
174
|
+
# git / vendor builds print "N-115000-g..." or a date, never major.minor; the
|
|
175
|
+
# libavutil major is still there and maps one-to-one onto the FFmpeg major
|
|
176
|
+
# (56=4, 57=5, 58=6, 59=7, 60=8). Without this every version branch took the
|
|
177
|
+
# oldest spelling on such builds: on 7.1 that skipped bt709_tag_args()'s
|
|
178
|
+
# workaround and an untagged source got a real matrix conversion.
|
|
179
|
+
m = re.search(r"^libavutil\s+(\d+)\.", out, re.M)
|
|
180
|
+
if m:
|
|
181
|
+
major = int(m.group(1)) - 52
|
|
182
|
+
if major >= 4:
|
|
183
|
+
_FFMPEG_VERSION = (major, 0)
|
|
184
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
185
|
+
# (0, 0) = unknown: every version branch then takes the older, universally accepted
|
|
186
|
+
# spelling, the same "unknown is not missing" stance doctor takes.
|
|
187
|
+
pass
|
|
188
|
+
return _FFMPEG_VERSION
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
_FFMPEG_RELEASE: "Optional[Tuple[int, int, int]]" = None
|
|
192
|
+
_FFMPEG_RELEASE_READ = False
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def ffmpeg_release() -> "Optional[Tuple[int, int, int]]":
|
|
196
|
+
"""(major, minor, patch) of a tagged FFmpeg release on PATH ("8.0.1-3ubuntu2", "n8.1" ->
|
|
197
|
+
(8, 1, 0)), or None for a git/vendor build or an unreadable one. ffmpeg_version()'s
|
|
198
|
+
major.minor is the right test for an option spelling; this is for a bug that one point
|
|
199
|
+
release introduced and the next one fixed, which major.minor cannot tell apart. Read from
|
|
200
|
+
ffprobe for the same dry-run reason; cached per process."""
|
|
201
|
+
global _FFMPEG_RELEASE, _FFMPEG_RELEASE_READ
|
|
202
|
+
if not _FFMPEG_RELEASE_READ:
|
|
203
|
+
_FFMPEG_RELEASE_READ = True
|
|
204
|
+
try:
|
|
205
|
+
out = _ffprobe("-version").stdout
|
|
206
|
+
m = re.search(r"ffprobe version\s+n?(\d+)\.(\d+)(?:\.(\d+))?", out)
|
|
207
|
+
if m:
|
|
208
|
+
_FFMPEG_RELEASE = (int(m.group(1)), int(m.group(2)), int(m.group(3) or 0))
|
|
209
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
210
|
+
pass
|
|
211
|
+
return _FFMPEG_RELEASE
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _homebrew_full_build(path: str, name: str) -> str:
|
|
215
|
+
"""On macOS, the keg-only `ffmpeg-full` binary that should replace `path`, or "".
|
|
216
|
+
|
|
217
|
+
Homebrew splits FFmpeg in two: the `ffmpeg` formula is lean (no freetype, libass, fontconfig,
|
|
218
|
+
harfbuzz, so no drawtext/subtitles/ass) and the keg-only `ffmpeg-full` is not linked onto
|
|
219
|
+
PATH. `brew install ffmpeg-full` therefore changes nothing for a user whose PATH still reaches
|
|
220
|
+
the lean one (#317). The swap happens only when `path` resolves into THIS Homebrew prefix's
|
|
221
|
+
Cellar as `ffmpeg` / `ffmpeg@N` and the same prefix has `opt/ffmpeg-full/bin/<name>`; a tap
|
|
222
|
+
build, MacPorts, a static download or a custom prefix is left exactly as the user put it."""
|
|
223
|
+
if platform.system() != "Darwin":
|
|
224
|
+
return ""
|
|
225
|
+
real = os.path.realpath(path)
|
|
226
|
+
prefix, sep, rest = real.partition("/Cellar/")
|
|
227
|
+
if not sep:
|
|
228
|
+
return ""
|
|
229
|
+
formula = rest.split("/", 1)[0]
|
|
230
|
+
if formula != "ffmpeg" and not re.fullmatch(r"ffmpeg@\d+", formula):
|
|
231
|
+
return ""
|
|
232
|
+
full = os.path.join(prefix, "opt", "ffmpeg-full", "bin", name)
|
|
233
|
+
return full if os.path.isfile(full) and os.access(full, os.X_OK) else ""
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _real_dir(path: str) -> str:
|
|
237
|
+
"""`path` with symlinks resolved, so a PATH entry that links to the working directory is
|
|
238
|
+
recognised as the working directory."""
|
|
239
|
+
return os.path.normcase(os.path.realpath(path))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _cwd_on_path(entries: List[str]) -> bool:
|
|
243
|
+
cwd = _real_dir(os.getcwd())
|
|
244
|
+
return any(e and os.path.isabs(e) and _real_dir(e) == cwd for e in entries)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _which_on_path(name: str, entries: List[str]) -> Optional[str]:
|
|
248
|
+
"""The first `name` in an absolute PATH entry that is not the working directory."""
|
|
249
|
+
cwd = _real_dir(os.getcwd())
|
|
250
|
+
exts = [""]
|
|
251
|
+
if os.name == "nt" and not os.path.splitext(name)[1]:
|
|
252
|
+
exts = [e for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep) if e] + [""]
|
|
253
|
+
for entry in entries:
|
|
254
|
+
if not entry or not os.path.isabs(entry) or _real_dir(entry) == cwd:
|
|
255
|
+
continue
|
|
256
|
+
for ext in exts:
|
|
257
|
+
candidate = os.path.join(entry, name + ext)
|
|
258
|
+
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
|
|
259
|
+
return candidate
|
|
260
|
+
return None
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def safe_which(name: str, which: Optional[Any] = None) -> Optional[str]:
|
|
264
|
+
"""shutil.which() without the working directory. On Windows it looks in the current directory
|
|
265
|
+
before PATH (and so does a bare name handed to subprocess), and a `.` or relative PATH entry
|
|
266
|
+
does the same elsewhere: an `ffmpeg.exe` in a folder the skill is run from would run instead
|
|
267
|
+
of the real one. A hit there (or in a directory that links to it) is dropped and PATH searched
|
|
268
|
+
again, unless the working directory is on PATH as an absolute entry, which is the caller's own
|
|
269
|
+
choice. `which` lets a test pass
|
|
270
|
+
its own lookup."""
|
|
271
|
+
found = (which or shutil.which)(name)
|
|
272
|
+
if not found:
|
|
273
|
+
return found
|
|
274
|
+
entries = os.environ.get("PATH", "").split(os.pathsep)
|
|
275
|
+
if _real_dir(os.path.dirname(os.path.abspath(found))) != _real_dir(os.getcwd()):
|
|
276
|
+
return found
|
|
277
|
+
if _cwd_on_path(entries):
|
|
278
|
+
return os.path.abspath(found) # Windows answers `.\ffmpeg.EXE`; a later chdir must not change what runs
|
|
279
|
+
return _which_on_path(name, entries)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class SafeShutil:
|
|
283
|
+
"""A shutil stand-in whose which() is safe_which(); the transcription code takes a `shutil`
|
|
284
|
+
argument (tests pass their own), so the real one is wrapped where it is handed in."""
|
|
285
|
+
|
|
286
|
+
def __init__(self, inner: Any) -> None:
|
|
287
|
+
self._inner = inner
|
|
288
|
+
|
|
289
|
+
def which(self, name: str) -> Optional[str]:
|
|
290
|
+
return safe_which(name, self._inner.which)
|
|
291
|
+
|
|
292
|
+
def __getattr__(self, attr: str) -> Any:
|
|
293
|
+
return getattr(self._inner, attr)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def ffmpeg_exe(name: str) -> Tuple[str, str]:
|
|
297
|
+
"""`(path, source)` of the ffmpeg/ffprobe the tools run; `("", "")` when none is on PATH.
|
|
298
|
+
|
|
299
|
+
`source` is "path" (what PATH resolves) or "homebrew-ffmpeg-full" (see _homebrew_full_build).
|
|
300
|
+
Not cached: PATH is read every time, as `shutil.which` was before this existed."""
|
|
301
|
+
found = safe_which(name)
|
|
302
|
+
if not found:
|
|
303
|
+
return "", ""
|
|
304
|
+
full = _homebrew_full_build(found, name)
|
|
305
|
+
return (full, "homebrew-ffmpeg-full") if full else (found, "path")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def found_exe(name: str) -> str:
|
|
309
|
+
"""ffmpeg_exe()'s path, or FileNotFoundError when there is none: never the bare name, which
|
|
310
|
+
the OS would look up in the working directory (Windows) or through a relative PATH entry."""
|
|
311
|
+
path = ffmpeg_exe(name)[0]
|
|
312
|
+
if not path:
|
|
313
|
+
raise FileNotFoundError(f"{name} not on PATH")
|
|
314
|
+
return path
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def require_tool(name: str) -> str:
|
|
318
|
+
"""Return the absolute path of ffmpeg/ffprobe or exit with install steps."""
|
|
319
|
+
path = ffmpeg_exe(name)[0] if name in ("ffmpeg", "ffprobe") else safe_which(name)
|
|
320
|
+
if path and name in ("ffmpeg", "ffprobe"):
|
|
321
|
+
# 3.0.0 removed FFmpeg 5.x (deprecated in 2.14.0) and the workarounds that kept it running:
|
|
322
|
+
# an older build that reports its version is refused before it can fail some other way.
|
|
323
|
+
# (0, 0) is an unreadable version and is not refused; a git/vendor build gives only the
|
|
324
|
+
# libavutil major, which cannot tell 6.0 from 6.1, so it is refused only below 6. The
|
|
325
|
+
# version is ffprobe's (ffmpeg is never run for it: --dry-run promises no ffmpeg run);
|
|
326
|
+
# both ship from one build, and doctor reads each binary's own.
|
|
327
|
+
found = ffmpeg_version()
|
|
328
|
+
if found != (0, 0) and (found[0] < MIN_FFMPEG[0] or (_FFMPEG_VERSION_IS_RELEASE and found < MIN_FFMPEG)):
|
|
329
|
+
system = platform.system()
|
|
330
|
+
hint = UPGRADE_HINTS.get(system, " See https://ffmpeg.org/download.html")
|
|
331
|
+
floor = f"{MIN_FFMPEG[0]}.{MIN_FFMPEG[1]}"
|
|
332
|
+
refuse("missing_tool", "ffmpeg_unsupported",
|
|
333
|
+
f"FFmpeg {found[0]}.{found[1]} (read from ffprobe -version) is not supported since ffmpeg-skill 3.0.0 (5.x was deprecated in "
|
|
334
|
+
f"2.14.0): a newer build is needed, FFmpeg {floor} or later. On {system}:\n{hint}",
|
|
335
|
+
code=127, version=f"{found[0]}.{found[1]}", required=floor)
|
|
336
|
+
if path:
|
|
337
|
+
return path
|
|
338
|
+
system = platform.system()
|
|
339
|
+
hint = INSTALL_HINTS.get(system, " See https://ffmpeg.org/download.html")
|
|
340
|
+
die(
|
|
341
|
+
f"'{name}' was not found on PATH.\n"
|
|
342
|
+
f"Install FFmpeg (which includes ffprobe) for {system}:\n{hint}",
|
|
343
|
+
code=127, kind="missing_tool",
|
|
344
|
+
)
|
|
345
|
+
return "" # unreachable
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
MIN_FFMPEG = (6, 1) # requirements.ffmpeg since 3.0.0 (_contract.MIN_FFMPEG is the same floor)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
X264_PRESETS = ("ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
CODECS = ("h264", "hevc", "av1", "prores")
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
_ENCODERS: Optional[set] = None
|
|
358
|
+
_BSFS: Optional[set] = None
|
|
359
|
+
_FILTERS: Optional[set] = None
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
class Context:
|
|
363
|
+
"""Per-process settings that the shared flags (--dry-run, --json, --progress, --fast) set once.
|
|
364
|
+
|
|
365
|
+
Scripts read it as attributes (``STATE.dry_run``); the dict-style shims that once served
|
|
366
|
+
older call sites are gone. Keeping it a single explicit object rather than module globals
|
|
367
|
+
makes it obvious what run()/emit() depend on and lets tests reset it with ``STATE.reset()``.
|
|
368
|
+
"""
|
|
369
|
+
|
|
370
|
+
__slots__ = ("parser", "dry_run", "json", "json_brief", "progress", "fast", "duration_hint", "commands", "timeout", "overwrite", "written", "preexisting", "checked", "plan", "plan_written", "plan_inputs", "codec", "alpha_line",
|
|
371
|
+
"hw", "hw_source", "hw_notes", "hw_swaps", "hw_fallback", "hw_env_ignored", "hw_stages", "hw_auto",
|
|
372
|
+
"notes", "warnings", "fallbacks", "skipped", "audit_log", "stage_verification", "first_input", "audio_inputs", "video_inputs",
|
|
373
|
+
"source_timecode", "smpte_hint", "delivered", "expected_timecode", "time_mapped", "watched", "temp_dirs", "side_deliveries",
|
|
374
|
+
"_stream_copy_outputs", "_encoded_media", "measured_plan_inputs", "plan_generated_inputs",
|
|
375
|
+
"sequence_frames_sha256")
|
|
376
|
+
|
|
377
|
+
def __init__(self) -> None:
|
|
378
|
+
self.reset()
|
|
379
|
+
|
|
380
|
+
def reset(self) -> None:
|
|
381
|
+
self.dry_run = False # print ffmpeg commands, run nothing (ffprobe still runs)
|
|
382
|
+
self.json = False # emit() prints a JSON document instead of the output path
|
|
383
|
+
self.first_input = None # (path, audio track count) of the first input probed: emit() reports tracks the output left out
|
|
384
|
+
self.video_inputs = set() # real paths of the inputs probed that have a picture: with two or more, which one the output shows is the tool's choice (sync --trim-second, a join)
|
|
385
|
+
self.source_timecode = None # (start timecode, duration) of the first input probed that carries one (time_arg's SMPTE hint)
|
|
386
|
+
self.expected_timecode = None # the start timecode a tool that moved the picture's start wrote (timeline.output_timecode_args; "" for none): source_carry compares it
|
|
387
|
+
self.time_mapped = None # how a tool that changed the output's length moved its chapters (declare_time_map)
|
|
388
|
+
self.smpte_hint = None # what die() says when an hh:mm:ss:ff flag read past the end looks like a source timecode (#411)
|
|
389
|
+
self.delivered: List[str] = [] # deliverables written before a later step (export --normalize, render's chapters/check): a stop then keeps them (#415)
|
|
390
|
+
self.watched: Dict[str, Any] = {} # a path a running child writes (render's export stage): its owned_identity() before the child started (watch_destination)
|
|
391
|
+
self.temp_dirs: List[str] = [] # directories this run removes when it exits (render's work directory): nothing in them is kept
|
|
392
|
+
self.side_deliveries: set = set() # delivered files that are not the run's output (render's <output>.srt): never `output` after a stop
|
|
393
|
+
self.audio_inputs = set() # real paths of the inputs probed that have sound: with two or more, whose tracks an output should keep is the tool's choice (grid --audio-from, a mix)
|
|
394
|
+
self.json_brief = False # --json-brief: the same document trimmed to the fields a caller acts on
|
|
395
|
+
self.progress = False # run() streams percent / ETA to stderr for ffmpeg
|
|
396
|
+
self.fast = False # x264 preset forced to veryfast
|
|
397
|
+
self.duration_hint: Optional[float] = None # expected output length, for the progress percent
|
|
398
|
+
self.commands: List[str] = [] # every ffmpeg command line, for --json and --dry-run
|
|
399
|
+
self._stream_copy_outputs: Dict[str, Dict[str, int]] = {}
|
|
400
|
+
self._encoded_media = False
|
|
401
|
+
self.timeout: float = _env_timeout() # seconds per ffmpeg invocation, 0 = none
|
|
402
|
+
self.overwrite = False # --overwrite: an existing output may be replaced
|
|
403
|
+
self.written: set = set() # output paths this process has written itself
|
|
404
|
+
self.preexisting: dict = {} # output path -> (size, mtime_ns) of a file that was there before we ran
|
|
405
|
+
self.checked: dict = {} # real output path -> owned_identity() at its output check (None: absent), or as this run left it; refuse_changed_output() compares it at the replace
|
|
406
|
+
self.plan: Optional[str] = None # --plan FILE: write the dry-run as a plan document (implies --dry-run)
|
|
407
|
+
self.plan_written = False # write_plan() ran (emit or the exit hook), so the hook does not write twice
|
|
408
|
+
self.plan_inputs: List[str] = [] # side inputs (srt/ass/lut/font files) a tool named through escape_filter_path
|
|
409
|
+
self.plan_generated_inputs: set[str] = set() # temporary inputs reconstructed by the tool
|
|
410
|
+
self.sequence_frames_sha256: Optional[str] = None
|
|
411
|
+
self.measured_plan_inputs: Dict[str, Dict[str, Any]] = {} # fingerprints taken before plan measurements
|
|
412
|
+
self.codec: Optional[str] = None # --codec: encoder for the re-encode (None = x264 for SDR, x265 for HDR)
|
|
413
|
+
self.alpha_line: Optional[str] = None # --keep-alpha / --transparent: the alpha line written (_common.alpha.ALPHA_CODECS)
|
|
414
|
+
self.hw = False # --hw / $FFMPEG_SKILL_HW: VideoToolbox encoders where they apply
|
|
415
|
+
self.hw_source: Optional[str] = None # "flag" (--hw/--no-hw given) or "env" (FFMPEG_SKILL_HW), None = off by default
|
|
416
|
+
self.hw_notes: List[str] = [] # why an encode stayed on (or fell back to) the CPU, for the result document
|
|
417
|
+
self.hw_swaps: List[Tuple[List[str], List[str]]] = [] # (VideoToolbox args, the CPU args they replaced) for run()'s fallback
|
|
418
|
+
self.hw_fallback = False # run() re-encoded a job VideoToolbox refused on the CPU (or a stage reported one)
|
|
419
|
+
self.hw_env_ignored = False # $FFMPEG_SKILL_HW=1 was set but this tool's delivery preset does not take it (export.py)
|
|
420
|
+
self.hw_stages: List[Dict[str, Any]] = [] # render.py: the `hw` facts each stage (a child process) reported
|
|
421
|
+
self.hw_auto: List[str] = [] # CPU encoders (libx264/libx265) this ffmpeg build lacks, whose encodes ran on VideoToolbox without --hw
|
|
422
|
+
# The collector (docs/design-decisions.md, "Nothing happens silently"): what this run
|
|
423
|
+
# decided on its own -- a warning, a fallback, a step it skipped -- recorded as it happens
|
|
424
|
+
# by warn()/record_fallback()/record_skip() (stderr too) and merged by emit()/die() into
|
|
425
|
+
# the document: `notes` (strings) and `diagnostics: {warnings, fallbacks, skipped}`.
|
|
426
|
+
self.notes: List[str] = []
|
|
427
|
+
self.warnings: List[Dict[str, Any]] = []
|
|
428
|
+
self.fallbacks: List[Dict[str, Any]] = []
|
|
429
|
+
self.skipped: List[Dict[str, Any]] = []
|
|
430
|
+
self.audit_log: Optional[str] = None # render.py --audit-log FILE: where audit() appends; None = the event's own default
|
|
431
|
+
# render.py (stages, an executed plan, a pack's renders): the verification steps each child
|
|
432
|
+
# tool reported, tagged with `stage`, which emit() adds to this result's own so that
|
|
433
|
+
# `verified` is the conjunction of every stage's (absorb_stage())
|
|
434
|
+
self.stage_verification: List[Dict[str, Any]] = []
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
STATE = Context()
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def finite_float(text: str) -> float:
|
|
441
|
+
"""argparse's `float`, minus nan and inf. Python's float() reads "nan", "inf" and "1e999", and
|
|
442
|
+
no flag here means any of them: they reached int() as a traceback, ffmpeg as "Invalid
|
|
443
|
+
argument" (kind ffmpeg, as if the build were at fault), or a comparison that is always false
|
|
444
|
+
and so skipped the check it guarded. add_common() registers this for every `type=float`."""
|
|
445
|
+
import argparse
|
|
446
|
+
import math
|
|
447
|
+
value = float(text)
|
|
448
|
+
if not math.isfinite(value):
|
|
449
|
+
raise argparse.ArgumentTypeError(f"{text!r} is not a finite number")
|
|
450
|
+
return value
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
SHARED = ("--dry-run", "--json", "--json-brief", "--progress", "--fast", "--timeout", "--overwrite", "--plan", "--output") # on every tool
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _teach(ap: "argparse.ArgumentParser", message: str = "") -> str:
|
|
457
|
+
"""For each --flag on the command line this tool lacks: a near option, else the options whose help uses the word, and the tools
|
|
458
|
+
that take it. When one answer is left for every mistake, the corrected command line follows as `try:`, for a caller that copies."""
|
|
459
|
+
import difflib
|
|
460
|
+
import shlex
|
|
461
|
+
acts = {o: a for o, a in ap._option_string_actions.items() if o.startswith("--")}
|
|
462
|
+
here, tips, fix = os.path.dirname(os.path.abspath(sys.argv[0])), "", {}
|
|
463
|
+
for flag in dict.fromkeys(a.split("=")[0] for a in sys.argv[1:] if re.match(r"--[a-z]", a)):
|
|
464
|
+
if not any(o.startswith(flag) for o in acts):
|
|
465
|
+
word = flag[2:] if len(flag) > 5 and flag != "--from" else "\0" # --to, --at and --from are in every help text
|
|
466
|
+
# options that share a word with the flag (--pad-color and --fill-color), else a near spelling
|
|
467
|
+
near = [o for o in acts if set(flag[2:].split("-")) - {"to", "at", "in", "no", "min", "max", "from"} & set(o[2:].split("-"))][:5] or difflib.get_close_matches(flag, acts, 2, 0.85)
|
|
468
|
+
said = [o for o, a in acts.items() if re.search(rf"\b{re.escape(word)}".replace("\\-", "[- ]"), a.help or "", re.I) and o not in near and o not in SHARED][:2]
|
|
469
|
+
tools = sorted(n for n in os.listdir(here) if n[0] != "_" and n.endswith(".py") and f'"{flag}"' in open(os.path.join(here, n), encoding="utf-8").read())
|
|
470
|
+
tips += (f"\n{flag} is not an option of this tool" + (f"; did you mean {' or '.join(near)}?" if near else "") + (f"; {' and '.join(said)} mention '{word}'" if said else "")
|
|
471
|
+
+ (f" ({', '.join(tools)} take {flag})" if tools else ""))
|
|
472
|
+
fix[flag] = (near + said)[0] if len(near + said) == 1 else None
|
|
473
|
+
# a choice with one near neighbour or a common other word for it, and a number written with its unit (-30dB, 0.8s, 1080px)
|
|
474
|
+
wrong = re.search(r"invalid choice: '([^']+)' \(choose from (.*)\)", message)
|
|
475
|
+
if wrong:
|
|
476
|
+
fix[wrong[1]] = (difflib.get_close_matches(_OTHER_WORDS.get(wrong[1].lower(), wrong[1]), [c.strip(" '") for c in wrong[2].split(",")], 1, 0.6) or [None])[0]
|
|
477
|
+
words: List[str] = []
|
|
478
|
+
for a in ([] if None in fix.values() else sys.argv[1:]):
|
|
479
|
+
name, eq, rest = a.partition("=")
|
|
480
|
+
b = fix[name] + eq + rest if name in fix else re.sub(r"^(-?\d+(?:\.\d+)?)(dB|s|px|ms|%)$", r"\1", a, flags=re.I)
|
|
481
|
+
fix[""] = fix.get("") or b != a
|
|
482
|
+
# argparse reads `--threshold -30dB` as two options; joined with = the value stays the option's
|
|
483
|
+
if words and re.match(r"--[a-z][^=]*$", words[-1]) and re.match(r"-\d", b):
|
|
484
|
+
words[-1] += "=" + b
|
|
485
|
+
else:
|
|
486
|
+
words.append(b)
|
|
487
|
+
if fix.get(""):
|
|
488
|
+
# a POSIX shell's single quotes mean nothing to cmd.exe, and a Windows path needs no quoting there
|
|
489
|
+
tips += "\ntry: " + (subprocess.list2cmdline if os.name == "nt" else shlex.join)(["python3", sys.argv[0]] + words)
|
|
490
|
+
return tips
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
_OTHER_WORDS = {"strong": "high", "heavy": "high", "max": "high", "weak": "low", "light": "low", "mild": "low", "mid": "medium", "normal": "medium", "moderate": "medium"}
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def add_common(ap: "argparse.ArgumentParser", codec: bool = True) -> None:
|
|
497
|
+
"""Add the flags every script shares. `codec=False` is for a tool that re-encodes but whose
|
|
498
|
+
preset decides the encoder (export.py): it must not advertise --codec/--quality in its schema."""
|
|
499
|
+
# one place for every tool: argparse looks a `type=` up in this registry at parse time, so the
|
|
500
|
+
# flags a tool added before this call are covered as well
|
|
501
|
+
ap.register("type", float, finite_float)
|
|
502
|
+
usage_error = ap.error
|
|
503
|
+
|
|
504
|
+
def error(message: str) -> None:
|
|
505
|
+
# a --json caller gets a failure document for this refusal, as for every other bad value a
|
|
506
|
+
# tool checks itself (export.py --max-mb nan answered with one before this was shared);
|
|
507
|
+
# anything else argparse rejects stays its usage error
|
|
508
|
+
if "is not a finite number" in message and {"--json", "--json-brief"} & set(sys.argv[1:]):
|
|
509
|
+
STATE.json = True
|
|
510
|
+
die(message.replace("argument ", "", 1))
|
|
511
|
+
usage_error(message + _teach(ap, message))
|
|
512
|
+
|
|
513
|
+
ap.error = error # type: ignore[method-assign]
|
|
514
|
+
STATE.parser = ap
|
|
515
|
+
g = ap.add_argument_group("agent options")
|
|
516
|
+
g.add_argument("--dry-run", action="store_true", help="print the ffmpeg commands that would run, run nothing")
|
|
517
|
+
g.add_argument("--json", action="store_true", help="print a JSON result (output, probe, commands) on stdout instead of the path")
|
|
518
|
+
g.add_argument("--json-brief", action="store_true",
|
|
519
|
+
help="like --json but trimmed: status, output, dry_run, verified, a compact summary of the output probe, this tool's own keys, and the command count instead of the command lines (failures print the full failure document, unchanged)")
|
|
520
|
+
g.add_argument("--progress", action="store_true", help="show percent / ETA on stderr while ffmpeg encodes")
|
|
521
|
+
g.add_argument("--fast", action="store_true", help="preview quality: x264 preset veryfast (overrides --preset) for quick iterations")
|
|
522
|
+
if "--timeout" not in ap._option_string_actions: # verify.py defines its own per-step --timeout; apply_common reads either
|
|
523
|
+
g.add_argument("--timeout", type=float, default=None, metavar="SECONDS",
|
|
524
|
+
help=f"kill an ffmpeg run past this many seconds, kind=timeout (default {DEFAULT_TIMEOUT:.0f}; 0 = no limit)")
|
|
525
|
+
g.add_argument("--overwrite", action="store_true",
|
|
526
|
+
help="allow replacing an existing output (refused without it)")
|
|
527
|
+
g.add_argument("--plan", metavar="FILE",
|
|
528
|
+
help="write the dry run as a plan (inputs fingerprinted, commands, expected output, verify steps) that render.py FILE executes later; implies --dry-run")
|
|
529
|
+
if codec and "crf" in ap._defaults:
|
|
530
|
+
# A tool that re-encodes declares its CRF default with set_defaults(crf=N) before calling
|
|
531
|
+
# this; --codec/--quality are its only encoder flags, resolved in video_args(). --crf was
|
|
532
|
+
# the 1.x spelling of --quality (an alias from 1.8, deprecated in 1.10, removed in 2.0).
|
|
533
|
+
g.add_argument("--codec", choices=CODECS, default=None,
|
|
534
|
+
help="video encoder for the re-encode: h264 (x264, the default for SDR), hevc (x265, the default for HDR), av1 (SVT-AV1 or libaom), prores (422 HQ, needs a .mov/.mkv output); HDR sources keep their colour on hevc/av1/prores")
|
|
535
|
+
g.add_argument("--quality", type=int, default=ap._defaults["crf"], metavar="N",
|
|
536
|
+
help="encoder quality on the CRF scale (default %(default)s; lower = better; 18 visually lossless for x264/x265, up to 63 for av1); ignored by prores")
|
|
537
|
+
if (codec and "crf" in ap._defaults) or not codec:
|
|
538
|
+
_add_hw_flags(g, "encode on the GPU with Apple VideoToolbox (h264/hevc/prores; Apple Silicon only): several times faster, "
|
|
539
|
+
"larger files at the same quality; falls back to the CPU encoder, reported, where it cannot apply"
|
|
540
|
+
+ ("" if codec else ". The only way to put a delivery preset on the GPU: $FFMPEG_SKILL_HW does not apply here"),
|
|
541
|
+
"encode on the CPU (x264/x265/SVT-AV1/prores_ks) even when $FFMPEG_SKILL_HW=1")
|
|
542
|
+
ap.set_defaults(_hw_env=bool(codec))
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _add_hw_flags(g: Any, hw_help: str, no_hw_help: str) -> None:
|
|
546
|
+
"""--hw and --no-hw, each its own boolean (dests `hw` and `no_hw`). They are not one dest
|
|
547
|
+
with store_true/store_false: the contract's input_schema keeps one property per dest and the
|
|
548
|
+
MCP transport turns `true` into the flag, so a shared dest published --no-hw under the name
|
|
549
|
+
`hw` and an MCP `hw: true` ran on the CPU. hw_flag() reads the pair back as True/False/None."""
|
|
550
|
+
hw = g.add_mutually_exclusive_group()
|
|
551
|
+
hw.add_argument("--hw", action="store_true", help=hw_help)
|
|
552
|
+
hw.add_argument("--no-hw", action="store_true", help=no_hw_help)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def hw_flag(args: "argparse.Namespace") -> Optional[bool]:
|
|
556
|
+
"""--hw -> True, --no-hw -> False, neither (or a tool without the flags) -> None."""
|
|
557
|
+
if getattr(args, "hw", False):
|
|
558
|
+
return True
|
|
559
|
+
if getattr(args, "no_hw", False):
|
|
560
|
+
return False
|
|
561
|
+
return None
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def apply_common(args: "argparse.Namespace") -> None:
|
|
565
|
+
# argparse takes a shortened option name: `freeze.py --time 3` ran as --timeout 3 and said nothing.
|
|
566
|
+
# A tool's own options keep that (callers use it); the options every tool shares are spelled in full.
|
|
567
|
+
acts = getattr(getattr(STATE, "parser", None), "_option_string_actions", {})
|
|
568
|
+
for flag in [a.split("=")[0] for a in sys.argv[1:] if acts and re.match(r"--[a-z]", a) and a.split("=")[0] not in acts]:
|
|
569
|
+
hit = [o for o in SHARED if o.startswith(flag)]
|
|
570
|
+
if hit:
|
|
571
|
+
STATE.parser.error(f"{flag} is not an option of this tool, and {hit[0]}, the shared option it is the start of, is spelled in full")
|
|
572
|
+
STATE.plan = getattr(args, "plan", None) or None
|
|
573
|
+
STATE.dry_run = bool(getattr(args, "dry_run", False)) or bool(STATE.plan)
|
|
574
|
+
if STATE.plan:
|
|
575
|
+
# tools that print their document instead of calling emit() (probe, and the analysis
|
|
576
|
+
# tools without --json) still get their plan written, at exit, unless die() ran (review 6)
|
|
577
|
+
import atexit
|
|
578
|
+
atexit.register(_plan_at_exit)
|
|
579
|
+
STATE.json_brief = bool(getattr(args, "json_brief", False))
|
|
580
|
+
# --json-brief is a shorter --json, not a second output mode: it implies it, so a caller that
|
|
581
|
+
# passes only --json-brief still gets a JSON document (and --json --json-brief is the brief one).
|
|
582
|
+
STATE.json = bool(getattr(args, "json", False)) or STATE.json_brief
|
|
583
|
+
if hasattr(args, "json"):
|
|
584
|
+
# and a tool that branches on args.json reads the same mode: through 3.8.13, probe --field,
|
|
585
|
+
# check, cropdetect, silence --list, report and verify printed text (or a bare document,
|
|
586
|
+
# or a document and then a path) under --json-brief alone (review of #521)
|
|
587
|
+
args.json = STATE.json
|
|
588
|
+
STATE.progress = bool(getattr(args, "progress", False) or os.environ.get(MCP_PROGRESS_ENV) == "1")
|
|
589
|
+
STATE.fast = bool(getattr(args, "fast", False))
|
|
590
|
+
STATE.overwrite = bool(getattr(args, "overwrite", False))
|
|
591
|
+
if STATE.plan and os.environ.get("FFMPEG_SKILL_READ_ONLY", "") not in ("", "0"):
|
|
592
|
+
# mcp/server.py runs the tools it annotates readOnlyHint (probe, check, cropdetect) with
|
|
593
|
+
# this set: a plan is the one file they could write, so it is refused here, after argparse,
|
|
594
|
+
# whatever spelling of --plan a raw argv used. Refused before the exit hook can write it.
|
|
595
|
+
plan_path, STATE.plan = STATE.plan, None
|
|
596
|
+
refuse("input", "read_only_plan_refused",
|
|
597
|
+
f"--plan {plan_path!r}: this tool runs read-only here (FFMPEG_SKILL_READ_ONLY) and writes no file; "
|
|
598
|
+
"run it from the command line to write a plan", plan=plan_path)
|
|
599
|
+
if STATE.plan:
|
|
600
|
+
# the plan is a file this run writes itself: the side-file guards apply (#408), so it
|
|
601
|
+
# never replaces an input, the output or an existing file without --overwrite
|
|
602
|
+
named = [getattr(args, k, None) for k in ("input", "inputs", "reference", "compare")]
|
|
603
|
+
inputs = [p for v in named for p in (v if isinstance(v, (list, tuple)) else [v]) if isinstance(p, str)]
|
|
604
|
+
out = getattr(args, "output", None)
|
|
605
|
+
guard_sidecar(STATE.plan, *inputs, siblings=(out,) if isinstance(out, str) else ())
|
|
606
|
+
if getattr(args, "timeout", None) is not None:
|
|
607
|
+
# a negative --timeout used to be read as 0 without a word, which removed every limit the
|
|
608
|
+
# caller thought it had tightened, and one past MAX_TIMEOUT was an OverflowError traceback
|
|
609
|
+
# after ffmpeg had started (the MCP call reported a failure while the tool wrote its output)
|
|
610
|
+
if not 0 <= float(args.timeout) <= MAX_TIMEOUT:
|
|
611
|
+
die(f"--timeout must be 0 (no limit) or a number of seconds up to {MAX_TIMEOUT:.0f}, got {float(args.timeout):g}",
|
|
612
|
+
hint="--timeout 0 runs without a time limit")
|
|
613
|
+
STATE.timeout = float(args.timeout)
|
|
614
|
+
else:
|
|
615
|
+
env_limit, env_problem = _read_env_timeout()
|
|
616
|
+
if env_problem:
|
|
617
|
+
warn(env_problem, "timeout_env_invalid", value=os.environ.get("FFMPEG_SKILL_TIMEOUT"), timeout=env_limit)
|
|
618
|
+
# one step for every number a tool takes (#645): the range its help states as a..b is the range it
|
|
619
|
+
# takes, a negative needs a help that names one, and nothing but a sample count is past a million
|
|
620
|
+
for a in getattr(getattr(STATE, "parser", None), "_actions", ()):
|
|
621
|
+
v, text = getattr(args, a.dest, None), a.help or ""
|
|
622
|
+
span = re.search(r"(-?\d+(?:\.\d+)?)\.\.(-?\d+(?:\.\d+)?)", text)
|
|
623
|
+
if a.type in (int, float) and isinstance(v, (int, float)) and v != a.default and a.dest not in ("timeout", "length_samples") and (
|
|
624
|
+
not float(span[1]) <= v <= float(span[2]) if span else abs(v) > 1e6 or (v < 0 and not re.search(r"-\d|dB|degree|stops", text))):
|
|
625
|
+
die(f"{next((o for o in a.option_strings if o in [x.split('=')[0] for x in sys.argv[1:]]), a.option_strings[0])} {v:g} is outside what this option takes" + (f", {span[0]}" if span else ""), hint=text.replace("%%", "%") or None)
|
|
626
|
+
if STATE.fast and getattr(args, "preset", None) in X264_PRESETS:
|
|
627
|
+
args.preset = "veryfast"
|
|
628
|
+
STATE.codec = getattr(args, "codec", None) or None
|
|
629
|
+
STATE.hw_notes, STATE.hw_swaps, STATE.hw_fallback, STATE.hw_env_ignored, STATE.hw_stages, STATE.hw_auto = [], [], False, False, [], []
|
|
630
|
+
flag = hw_flag(args)
|
|
631
|
+
if flag is not None:
|
|
632
|
+
STATE.hw, STATE.hw_source = bool(flag), "flag"
|
|
633
|
+
if getattr(args, "_hw_orchestrator", False):
|
|
634
|
+
# render.py / batch.py --hw|--no-hw: every stage they run inherits it as an explicit
|
|
635
|
+
# choice -- export.py's delivery presets included, which $FFMPEG_SKILL_HW never reaches
|
|
636
|
+
os.environ[HW_ENV] = "1" if flag else "0"
|
|
637
|
+
os.environ[HW_FORCED_ENV] = "1"
|
|
638
|
+
elif hasattr(args, "hw") and os.environ.get(HW_FORCED_ENV) == "1":
|
|
639
|
+
STATE.hw, STATE.hw_source = env_hw(), "flag"
|
|
640
|
+
elif hasattr(args, "hw") and getattr(args, "_hw_env", False) and env_hw():
|
|
641
|
+
STATE.hw, STATE.hw_source = True, "env"
|
|
642
|
+
else:
|
|
643
|
+
STATE.hw, STATE.hw_source = False, None
|
|
644
|
+
# export.py (a delivery preset decides the encoder): the machine default is not applied,
|
|
645
|
+
# and the result says so rather than leaving a caller to wonder why the GPU was not used
|
|
646
|
+
STATE.hw_env_ignored = (hasattr(args, "hw") and env_hw() and not getattr(args, "_hw_env", False)
|
|
647
|
+
and not getattr(args, "_hw_orchestrator", False))
|
|
648
|
+
quality = getattr(args, "quality", None)
|
|
649
|
+
if quality is not None:
|
|
650
|
+
top = 63 if STATE.codec == "av1" else 51
|
|
651
|
+
if not 0 <= int(quality) <= top:
|
|
652
|
+
die(f"--quality must be between 0 and {top} for {STATE.codec or 'h264'} (CRF scale; 18 is visually lossless), got {quality}")
|
|
653
|
+
args.crf = int(quality) # every tool reads args.crf; --quality is the codec-neutral spelling of it
|
|
654
|
+
if STATE.codec == "prores" and hasattr(args, "output"):
|
|
655
|
+
out = getattr(args, "output", None)
|
|
656
|
+
if not out:
|
|
657
|
+
# every tool defaults its output to the source's extension (or .mp4): ProRes in an .mp4
|
|
658
|
+
# fails inside ffmpeg with "codec not currently supported in container" (review 7)
|
|
659
|
+
die("--codec prores needs an explicit -o NAME.mov (or .mkv): the default output name keeps the source's container, which cannot hold ProRes",
|
|
660
|
+
hint="give -o NAME.mov")
|
|
661
|
+
if os.path.splitext(str(out))[1].lower() not in (".mov", ".mkv"):
|
|
662
|
+
die(f"--codec prores needs a .mov (or .mkv) output; {os.path.basename(str(out))} cannot hold ProRes",
|
|
663
|
+
hint="give -o NAME.mov")
|
|
664
|
+
crf = getattr(args, "crf", None) # export.py's own --crf (its preset chooses the encoder)
|
|
665
|
+
top = 63 if STATE.codec == "av1" else 51
|
|
666
|
+
if crf is not None and not 0 <= int(crf) <= top:
|
|
667
|
+
die(f"--crf must be between 0 and {top} ({'SVT-AV1' if STATE.codec == 'av1' else 'x264/x265'} scale; 18 is visually lossless), got {crf}")
|
|
668
|
+
install_signal_handlers()
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
# The child processes this tool is waiting on right now (an ffmpeg, or a sibling script under
|
|
672
|
+
# run_tool), with the command whose partial output would need removing. A signal handler
|
|
673
|
+
# reads it; the runners keep it current. Before 1.4.9 a SIGTERM to the tool (a cancelled MCP
|
|
674
|
+
# call, a supervisor's stop, a closed terminal) killed only the Python parent: ffmpeg carried on
|
|
675
|
+
# as an orphan, finished a file nobody verified, and the caller got no JSON at all; SIGINT was a
|
|
676
|
+
# KeyboardInterrupt traceback with the partial left on disk.
|
|
677
|
+
_CHILDREN: List[Tuple[subprocess.Popen, Sequence[str]]] = []
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
_SIGNALS_INSTALLED = False
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def stop_children() -> None:
|
|
684
|
+
"""Stop every child this tool is waiting on and remove each one's partial output: what the
|
|
685
|
+
signal handler does before it exits, for a tool that reports more than "interrupted" after a
|
|
686
|
+
signal (batch.py's partial table)."""
|
|
687
|
+
for proc, cmd in list(_CHILDREN):
|
|
688
|
+
if not cmd:
|
|
689
|
+
# a sibling script (run_tool(), verify.py's steps): its own handler stops its ffmpeg
|
|
690
|
+
# and removes its partial output, given STOP_GRACE; on Windows its whole tree is killed
|
|
691
|
+
_stop_child(proc, communicate=False)
|
|
692
|
+
continue
|
|
693
|
+
try:
|
|
694
|
+
proc.terminate() # ffmpeg exits promptly on SIGTERM
|
|
695
|
+
try:
|
|
696
|
+
proc.wait(timeout=5)
|
|
697
|
+
except subprocess.TimeoutExpired:
|
|
698
|
+
proc.kill()
|
|
699
|
+
proc.wait()
|
|
700
|
+
except OSError:
|
|
701
|
+
pass
|
|
702
|
+
if cmd:
|
|
703
|
+
_cleanup_partial_output(cmd)
|
|
704
|
+
_CHILDREN.clear()
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def mark_delivered(path: str, side: bool = False) -> None:
|
|
708
|
+
"""Record that this run has written its deliverable and still has a step to run on it (export's
|
|
709
|
+
--normalize, render's chapters and check stages): a timeout or an interrupt from then on says the
|
|
710
|
+
file is there and kept, instead of "nothing was written" (#415)."""
|
|
711
|
+
if path and path not in STATE.delivered:
|
|
712
|
+
STATE.delivered.append(path)
|
|
713
|
+
if path and side:
|
|
714
|
+
STATE.side_deliveries.add(path) # `side`: a file beside the output (an SRT), kept but not the output (#510 review)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def child_exit_code(doc: Any, returncode: Optional[int]) -> int:
|
|
718
|
+
"""The exit code a tool passes on from a child tool that failed: the code its document states,
|
|
719
|
+
else its process's own, else 1. A child killed by a signal has a negative returncode (-9), which
|
|
720
|
+
as an exit code wraps (247); it is passed on as the shell reports it, 128 + the signal (137)."""
|
|
721
|
+
code = (doc.get("exit_code") if isinstance(doc, dict) else None) or returncode or 1
|
|
722
|
+
try:
|
|
723
|
+
code = int(code)
|
|
724
|
+
except (TypeError, ValueError):
|
|
725
|
+
return 1
|
|
726
|
+
return 128 - code if code < 0 else code
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def watch_destination(path: Optional[str]) -> None:
|
|
730
|
+
"""Record what is at `path` before a child tool writes it (render.py's export stage writes the
|
|
731
|
+
delivery itself): if this run is stopped while the child runs, kept_deliverables() compares
|
|
732
|
+
the file then with this record. A file the child changed is this run's and is reported kept;
|
|
733
|
+
one it did not change (the caller's own, restored by the child's cleanup, or never touched)
|
|
734
|
+
is not claimed (#510)."""
|
|
735
|
+
if path and not STATE.dry_run:
|
|
736
|
+
STATE.watched[path] = owned_identity(path)
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def unwatch_destination(path: Optional[str]) -> None:
|
|
740
|
+
STATE.watched.pop(path or "", None)
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def kept_deliverables() -> List[str]:
|
|
744
|
+
"""The deliverables mark_delivered() named that are on disk, and any watched destination that
|
|
745
|
+
is on disk and is not the file that was there when its child started (size, mtime, inode)."""
|
|
746
|
+
kept = [p for p in STATE.delivered if os.path.isfile(p)]
|
|
747
|
+
for path, before in STATE.watched.items():
|
|
748
|
+
now = owned_identity(path)
|
|
749
|
+
if now is not None and now != before and path not in kept:
|
|
750
|
+
kept.append(path)
|
|
751
|
+
return kept
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _in_temp_dir(path: str) -> bool:
|
|
755
|
+
real = os.path.realpath(path)
|
|
756
|
+
return any(real.startswith(os.path.realpath(d) + os.sep) for d in STATE.temp_dirs)
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def written_on_disk() -> List[str]:
|
|
760
|
+
"""Files this process wrote itself (run()'s outputs, STATE.written) that are still on disk, the
|
|
761
|
+
deliverables mark_delivered() named excepted. A stopped command's partial output is removed
|
|
762
|
+
before a stop is reported, so it is not among them."""
|
|
763
|
+
delivered = {os.path.realpath(p) for p in STATE.delivered}
|
|
764
|
+
# a file in a directory removed at exit (render's work directory) is not on disk after the stop
|
|
765
|
+
return sorted(p for p in STATE.written if p not in delivered and os.path.isfile(p) and not _in_temp_dir(p))
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def kept_clause() -> str:
|
|
769
|
+
"""How a stopped run's message ends: "nothing was written" only when no file this run wrote is
|
|
770
|
+
on disk (A182: every tool but export and render said it after writing its output), else which
|
|
771
|
+
deliverable it had already written and keeps (not the finished result: the step that was
|
|
772
|
+
stopped did not run on it), or which files it had written before the stop."""
|
|
773
|
+
kept = kept_deliverables()
|
|
774
|
+
if not kept:
|
|
775
|
+
written = written_on_disk()
|
|
776
|
+
if not written:
|
|
777
|
+
return "nothing was written"
|
|
778
|
+
return (f"{', '.join(written)} had already been written by this run before the stop and "
|
|
779
|
+
f"{'is' if len(written) == 1 else 'are'} still on disk")
|
|
780
|
+
return (f"{', '.join(kept)} had already been written by this run and {'is' if len(kept) == 1 else 'are'} kept, "
|
|
781
|
+
"without the step that was stopped (pass --overwrite to make it again)")
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def kept_output() -> Optional[str]:
|
|
785
|
+
"""The kept file that is this run's output: the last kept one that is not a side delivery (the
|
|
786
|
+
video, not the <output>.srt delivered after it), else the last kept one."""
|
|
787
|
+
kept = kept_deliverables()
|
|
788
|
+
main = [p for p in kept if p not in STATE.side_deliveries]
|
|
789
|
+
return (main or kept or [None])[-1]
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def _kept_fields() -> Dict[str, Any]:
|
|
793
|
+
out = kept_output()
|
|
794
|
+
return {"output": out} if out else {}
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
_STOPPING = {"signal": None}
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def _on_signal(signum: int, frame: Any) -> None:
|
|
801
|
+
import signal as _signal
|
|
802
|
+
if _STOPPING["signal"] is not None:
|
|
803
|
+
# a second signal while the first one's stop runs: a Ctrl-C reaches every process of the
|
|
804
|
+
# group, and the parent then sends its SIGTERM too. Raising again here exited from the
|
|
805
|
+
# middle of the cleanup the first one started (an output lock's __exit__), and left the
|
|
806
|
+
# lock and its takeover file beside the output (#510). The parent's SIGKILL after
|
|
807
|
+
# STOP_GRACE still ends a cleanup that hangs.
|
|
808
|
+
return
|
|
809
|
+
_STOPPING["signal"] = signum
|
|
810
|
+
name = {getattr(_signal, "SIGINT", None): "SIGINT", getattr(_signal, "SIGTERM", None): "SIGTERM"}.get(signum, str(signum))
|
|
811
|
+
stop_children()
|
|
812
|
+
die(f"interrupted by {name}: the running command was stopped and its partial output removed; {kept_clause()}",
|
|
813
|
+
code=128 + signum, kind="interrupted", **_kept_fields())
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def install_signal_handlers() -> None:
|
|
817
|
+
"""SIGINT/SIGTERM stop the child, remove its partial output and exit with a failure document
|
|
818
|
+
(kind: interrupted, exit 130/143). Main thread only; on Windows SIGTERM is never delivered,
|
|
819
|
+
SIGINT (Ctrl-C) is."""
|
|
820
|
+
global _SIGNALS_INSTALLED
|
|
821
|
+
if _SIGNALS_INSTALLED:
|
|
822
|
+
return
|
|
823
|
+
import signal as _signal
|
|
824
|
+
import threading
|
|
825
|
+
if threading.current_thread() is not threading.main_thread():
|
|
826
|
+
return
|
|
827
|
+
for sig in (getattr(_signal, "SIGINT", None), getattr(_signal, "SIGTERM", None)):
|
|
828
|
+
if sig is None:
|
|
829
|
+
continue
|
|
830
|
+
try:
|
|
831
|
+
_signal.signal(sig, _on_signal)
|
|
832
|
+
except (ValueError, OSError):
|
|
833
|
+
pass
|
|
834
|
+
_SIGNALS_INSTALLED = True
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _watch(proc: subprocess.Popen, cmd: Sequence[str]) -> None:
|
|
838
|
+
_CHILDREN.append((proc, cmd))
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def _unwatch(proc: subprocess.Popen) -> None:
|
|
842
|
+
_CHILDREN[:] = [(p, c) for p, c in _CHILDREN if p is not proc]
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _cmdline(cmd: Sequence[str]) -> str:
|
|
846
|
+
return " ".join(shell_quote(c) for c in cmd)
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def _is_ffmpeg(cmd: Sequence[str]) -> bool:
|
|
850
|
+
return os.path.basename(cmd[0]).startswith("ffmpeg")
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _cleanup_partial_output(cmd: Sequence[str]) -> None:
|
|
854
|
+
"""A failed ffmpeg command can still have opened its output container (muxer header
|
|
855
|
+
written) before erroring out mid-stream -- unlike a failure that happens before ffmpeg ever
|
|
856
|
+
touches the output path (a bad filter argument, a missing input), which never creates the
|
|
857
|
+
file at all. Both are reported the same way (status: failed), but only the first case used
|
|
858
|
+
to leave a stray, usually-0-byte file behind: verify_output()'s cleanup only runs on the
|
|
859
|
+
success path, so a failed run() call never routed through it. Remove whatever ffmpeg managed
|
|
860
|
+
to write so a caller scanning the output directory after a failure never mistakes a partial
|
|
861
|
+
artifact for a real (if unverified) one."""
|
|
862
|
+
# run() also executes ffprobe, whose last argument is an INPUT. Never
|
|
863
|
+
# interpret a read-only tool's failure as permission to remove that file.
|
|
864
|
+
if not _is_ffmpeg(cmd):
|
|
865
|
+
return
|
|
866
|
+
output = cmd[-1]
|
|
867
|
+
if output in ("-", "pipe:0", "pipe:1") or output.startswith("pipe:") or output.startswith("-"):
|
|
868
|
+
return
|
|
869
|
+
try:
|
|
870
|
+
if not os.path.exists(output):
|
|
871
|
+
return
|
|
872
|
+
# A file that was already there before this command ran is someone's deliverable, not
|
|
873
|
+
# our partial. If ffmpeg died before opening it (bad filter argument, unreadable input:
|
|
874
|
+
# the common case) it is byte-for-byte what it was, so leave it alone. Only when ffmpeg
|
|
875
|
+
# did open and truncate it (size or mtime changed) is what remains a partial of ours,
|
|
876
|
+
# and the original is already gone either way; then removing it is still right.
|
|
877
|
+
before = STATE.preexisting.get(os.path.realpath(output))
|
|
878
|
+
if before is not None:
|
|
879
|
+
st = os.stat(output)
|
|
880
|
+
if (st.st_size, st.st_mtime_ns) == before:
|
|
881
|
+
return
|
|
882
|
+
os.remove(output)
|
|
883
|
+
except OSError:
|
|
884
|
+
pass
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
# ffmpeg's own words for the failures a caller can act on. Each pattern gives `error.reason` and a
|
|
888
|
+
# hint; the kind stays "ffmpeg" and the exit code 1 (docs/design-decisions.md), so a caller that
|
|
889
|
+
# keyed on those sees no change. Matched against the stderr tail, the first hit wins.
|
|
890
|
+
INCOMPLETE_INPUT = re.compile(r"File ended prematurely(?: at pos\.[^\r\n]*)?|(?:stream \d+, offset|root atom offset) 0x[0-9a-fA-F]+: partial file")
|
|
891
|
+
FFMPEG_FAILURE_CLASSES = (
|
|
892
|
+
(re.compile(r"No space left on device"), "disk_full",
|
|
893
|
+
"the disk the output is written to is full: free space there (or write elsewhere with -o) and run again"),
|
|
894
|
+
(re.compile(r"Unknown encoder '([^']+)'|Encoder '?([\w-]+)'? not found|Requested encoder '?([\w-]+)'? not found"),
|
|
895
|
+
"encoder_missing", "this ffmpeg build has no {0} encoder: `python3 scripts/_contract.py doctor` lists what it has and how to get a fuller build"),
|
|
896
|
+
(re.compile(r"No such filter: '([^']+)'|Filter '?([\w-]+)'? not found"),
|
|
897
|
+
"filter_missing", "this ffmpeg build has no {0} filter: `python3 scripts/_contract.py doctor` lists what it has and how to get a fuller build"),
|
|
898
|
+
(re.compile(r"moov atom not found|" + INCOMPLETE_INPUT.pattern), "input_incomplete",
|
|
899
|
+
"the input is incomplete: copy it again from its source; if the recording itself was cut off but has its index, `export --preset copy --repair` writes the part that is there so it can be edited; a missing index cannot be rebuilt"),
|
|
900
|
+
(re.compile(r"Invalid data found when processing input"), "input_unreadable",
|
|
901
|
+
"ffmpeg cannot read the input as media: check that it plays and finished copying; `check.py --content` names damaged spans in a file that does"),
|
|
902
|
+
)
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def classify_ffmpeg_failure(stderr: str) -> "Optional[Tuple[str, str, Dict[str, str]]]":
|
|
906
|
+
"""(reason, hint, details) for an ffmpeg stderr that names an actionable cause, else None."""
|
|
907
|
+
for pattern, reason, hint in FFMPEG_FAILURE_CLASSES:
|
|
908
|
+
m = pattern.search(stderr or "")
|
|
909
|
+
if m:
|
|
910
|
+
name = next((g for g in m.groups() if g), "")
|
|
911
|
+
return reason, hint.format(name or "that"), {"name": name} if name else {}
|
|
912
|
+
return None
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
def _fail(cmd: Sequence[str], returncode: int, stderr: str, ctx: "Optional[Context]" = None, retried: bool = False, diagnostic: Optional[str] = None) -> None:
|
|
916
|
+
# Partial-output cleanup already ran in the caller (_execute) for
|
|
917
|
+
# every failed ffmpeg invocation, not just this check=True path -- see _cleanup_partial_output.
|
|
918
|
+
# The process exit code is always 1 for an ffmpeg failure: ffmpeg's own code (1, 69, 218, 234,
|
|
919
|
+
# a negative signal number...) varies by build and by the failing stage, and 124/127/130/143
|
|
920
|
+
# are reserved for timeout, missing tool and interrupts. The raw code is kept in the JSON
|
|
921
|
+
# document as `ffmpeg_returncode` for a caller that wants it. docs/design-decisions.md.
|
|
922
|
+
#
|
|
923
|
+
# `cmd` is the command that ran last: after run()'s GPU->CPU retry (`retried`), the CPU one.
|
|
924
|
+
# Under --hw / $FFMPEG_SKILL_HW the message names its video encoder and the document carries
|
|
925
|
+
# `encoder` and `hw`, because two encoders may have run and a caller must know whose stderr
|
|
926
|
+
# this is.
|
|
927
|
+
ctx = ctx or STATE
|
|
928
|
+
tail = "\n".join(stderr.strip().splitlines()[-15:])
|
|
929
|
+
what, extra = str(cmd[0]), {}
|
|
930
|
+
enc = video_encoder_of(cmd) if ctx.hw or ctx.hw_auto else None
|
|
931
|
+
if enc:
|
|
932
|
+
on_gpu = enc.endswith("_videotoolbox")
|
|
933
|
+
why = videotoolbox_failure(stderr) if on_gpu else None
|
|
934
|
+
if not on_gpu and retried:
|
|
935
|
+
what += f" (video encoder {enc}, the CPU retry after VideoToolbox refused the job)"
|
|
936
|
+
elif on_gpu and why is None:
|
|
937
|
+
what += f" (video encoder {enc}; not retried on the CPU: ffmpeg reported no VideoToolbox error)"
|
|
938
|
+
else:
|
|
939
|
+
what += f" (video encoder {enc})"
|
|
940
|
+
report = hw_report(ctx, enc)
|
|
941
|
+
if on_gpu:
|
|
942
|
+
report["notes"].append(
|
|
943
|
+
"the VideoToolbox encode failed and was not retried on the CPU: " +
|
|
944
|
+
("ffmpeg reported no encoder-open or compression-session error, so the cause is not the GPU (see the message)"
|
|
945
|
+
if why is None else f"VideoToolbox refused it ({why}) and no CPU encoder line was recorded to retry with"))
|
|
946
|
+
extra = {"encoder": enc, "hw": report}
|
|
947
|
+
for path in (p for arg in (*shape_of(cmd).inputs, str(cmd[-1])) for p in (arg, os.path.basename(arg)) if diagnostic is None and p not in ("", "-") and classify_ffmpeg_failure(p)):
|
|
948
|
+
stderr = re.sub(r"(?m)(^|(?:file|input|output|for|to) ['\"]?)" + re.escape(path) + r"(?=['\"]|:|\.(?:\s|$))", r"\1<path>", stderr)
|
|
949
|
+
cls = classify_ffmpeg_failure(stderr if diagnostic is None else diagnostic)
|
|
950
|
+
if cls:
|
|
951
|
+
extra["hint"] = cls[1]
|
|
952
|
+
die(f"command {'reported an error despite exit 0' if returncode == 0 else f'failed ({returncode})'}: {what}\n{tail}", code=1, kind="ffmpeg", ctx=ctx, ffmpeg_returncode=returncode,
|
|
953
|
+
error_extra={"reason": cls[0], "details": cls[2]} if cls else None, **extra)
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def video_encoder_of(cmd: Sequence[str]) -> Optional[str]:
|
|
957
|
+
"""The video encoder an ffmpeg argv names last (-c:v / -vcodec / -codec:v), or None."""
|
|
958
|
+
enc = None
|
|
959
|
+
for i, a in enumerate(cmd[:-1]):
|
|
960
|
+
if a in ("-c:v", "-vcodec", "-codec:v"):
|
|
961
|
+
enc = str(cmd[i + 1])
|
|
962
|
+
return enc
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
# A protocol prefix (`tcp:`, `http://`, `file:`, `concat:`, ...): ffmpeg opens such a value as a URL,
|
|
966
|
+
# while every guard here reads it as a path. Two or more letters, so a Windows
|
|
967
|
+
# drive letter (`C:\x.mp4`) is a path; `pipe:` is the skill's own stdout/stdin and stays allowed.
|
|
968
|
+
_URL_SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]+:")
|
|
969
|
+
# Off Windows there are no drive letters, and ffmpeg reads a one-letter `x:y.mp4` as protocol `x`
|
|
970
|
+
# too (#408: it then failed as "Protocol not found", with no hint that ./x:y.mp4 works)
|
|
971
|
+
_URL_SCHEME_POSIX = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
def _is_subfile_url(value: str) -> bool:
|
|
975
|
+
"""ffmpeg's url_find_protocol() also opens `subfile,<options>:<url>` through the subfile
|
|
976
|
+
protocol: the scheme stops at the comma, so the regexes above never see it."""
|
|
977
|
+
return value.startswith("subfile,") and ":" in value[len("subfile,"):]
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def looks_like_url(value: str) -> bool:
|
|
981
|
+
"""True for a value ffmpeg would open through a protocol rather than as a local file."""
|
|
982
|
+
if _is_subfile_url(value):
|
|
983
|
+
return True
|
|
984
|
+
scheme = _URL_SCHEME if os.name == "nt" else _URL_SCHEME_POSIX
|
|
985
|
+
return bool(scheme.match(value)) and not value.startswith("pipe:")
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def url_scheme(value: str) -> str:
|
|
989
|
+
"""The protocol name ffmpeg would open `value` through (for a looks_like_url() value)."""
|
|
990
|
+
return "subfile" if _is_subfile_url(value) else value.split(":", 1)[0].lower()
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
_PLAYLIST_SUFFIXES = (".m3u8", ".m3u", ".ffconcat", ".mpd")
|
|
994
|
+
_PLAYLIST_MAGIC = (b"#EXTM3U", b"ffconcat")
|
|
995
|
+
# ffmpeg probes a text format over the whole probe buffer (up to -probesize, 5,000,000 bytes), not
|
|
996
|
+
# over a fixed prefix, and reads that buffer as a C string, so the scan below stops at the first
|
|
997
|
+
# NUL byte: a real media file has one within its first few bytes, a manifest has none.
|
|
998
|
+
_MANIFEST_SCAN_LIMIT = 5_000_000
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def _manifest_kind(path: str) -> Optional[str]:
|
|
1002
|
+
""""DASH" or "IMF" when ffmpeg's own probe would read `path` as that manifest, whatever its
|
|
1003
|
+
name: dash_probe() looks for `<MPD` and `dash:profile` or `3GPP:PSS:profile:DASH1`
|
|
1004
|
+
(case-insensitively), imf_probe() for
|
|
1005
|
+
`<CompositionPlaylist` and `ContentTitle>`. Either one names other files, local or remote, that
|
|
1006
|
+
ffmpeg then opens (a DASH BaseURL is followed over HTTP even under -protocol_whitelist file)."""
|
|
1007
|
+
buf = bytearray()
|
|
1008
|
+
try:
|
|
1009
|
+
with open(path, "rb") as fh:
|
|
1010
|
+
while len(buf) < _MANIFEST_SCAN_LIMIT:
|
|
1011
|
+
chunk = fh.read(65536)
|
|
1012
|
+
if not chunk:
|
|
1013
|
+
break
|
|
1014
|
+
nul = chunk.find(b"\0")
|
|
1015
|
+
if nul >= 0:
|
|
1016
|
+
buf += chunk[:nul]
|
|
1017
|
+
break
|
|
1018
|
+
buf += chunk
|
|
1019
|
+
except OSError:
|
|
1020
|
+
return None
|
|
1021
|
+
text = bytes(buf[:_MANIFEST_SCAN_LIMIT])
|
|
1022
|
+
low = text.lower()
|
|
1023
|
+
if b"<mpd" in low and (b"dash:profile" in low or b"3gpp:pss:profile:dash1" in low):
|
|
1024
|
+
return "DASH"
|
|
1025
|
+
if b"<CompositionPlaylist" in text and b"ContentTitle>" in text:
|
|
1026
|
+
return "IMF"
|
|
1027
|
+
return None
|
|
1028
|
+
|
|
1029
|
+
|
|
1030
|
+
def _refuse_playlist(value: str) -> None:
|
|
1031
|
+
"""Refuse an input that ffmpeg would read as a playlist (HLS .m3u8, a DASH .mpd, an IMF
|
|
1032
|
+
composition playlist, an ffconcat list) rather than as media. A playlist names other files by
|
|
1033
|
+
path or URL, so a media file handed to the skill could pull in any file the user can read, or
|
|
1034
|
+
make ffmpeg fetch a URL. HLS and ffconcat are told by name or by their first bytes; DASH and IMF
|
|
1035
|
+
by name or by the content ffmpeg's own probe looks for, anywhere before the first NUL byte. The
|
|
1036
|
+
skill's own concat lists pass `-f concat` and are not checked here."""
|
|
1037
|
+
if os.path.exists(value) and not os.path.isfile(value) and not os.path.isdir(value):
|
|
1038
|
+
# a FIFO or a device: ffmpeg would block on it or read whatever it streams
|
|
1039
|
+
refuse("input", "media_path_not_a_file",
|
|
1040
|
+
f"{value!r} is not a regular file (a pipe or a device); this skill takes media files only", path=value)
|
|
1041
|
+
head = b""
|
|
1042
|
+
try:
|
|
1043
|
+
if os.path.isfile(value):
|
|
1044
|
+
with open(value, "rb") as fh:
|
|
1045
|
+
head = fh.read(16).lstrip(b"\xef\xbb\xbf \t\r\n")
|
|
1046
|
+
except OSError:
|
|
1047
|
+
pass
|
|
1048
|
+
kind = None
|
|
1049
|
+
if value.lower().endswith(_PLAYLIST_SUFFIXES) or head.startswith(_PLAYLIST_MAGIC):
|
|
1050
|
+
kind = "HLS, DASH or ffconcat"
|
|
1051
|
+
elif os.path.isfile(value):
|
|
1052
|
+
kind = _manifest_kind(value)
|
|
1053
|
+
if kind:
|
|
1054
|
+
refuse("input", "media_path_is_playlist",
|
|
1055
|
+
f"{value!r} is a playlist ({kind}), which ffmpeg would follow to the files or URLs it names; "
|
|
1056
|
+
"this skill takes media files only. Pass the media file itself", path=value)
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
def _refuse_url_media(cmd: Sequence[str]) -> None:
|
|
1060
|
+
"""Refuse an ffmpeg/ffprobe command that names a URL as an input or as its output, before it
|
|
1061
|
+
runs or is recorded. This skill reads and writes local files only, and the path guards below
|
|
1062
|
+
(output-is-input, existing output, output directory) only mean something for a local path. A
|
|
1063
|
+
`-f lavfi` input is a filtergraph, not a location, and is left alone; a local name that
|
|
1064
|
+
contains a colon still works written as `./name`."""
|
|
1065
|
+
cmd = [str(a) for a in cmd] # in-process callers pass Path objects
|
|
1066
|
+
base = os.path.basename(cmd[0])
|
|
1067
|
+
if not (base.startswith("ffmpeg") or base.startswith("ffprobe")):
|
|
1068
|
+
return
|
|
1069
|
+
fmt = None
|
|
1070
|
+
values = []
|
|
1071
|
+
for i, a in enumerate(cmd[1:-1], start=1):
|
|
1072
|
+
if a == "-f":
|
|
1073
|
+
fmt = cmd[i + 1]
|
|
1074
|
+
elif a == "-i":
|
|
1075
|
+
if fmt != "lavfi":
|
|
1076
|
+
values.append(cmd[i + 1])
|
|
1077
|
+
if fmt is None:
|
|
1078
|
+
_refuse_playlist(cmd[i + 1])
|
|
1079
|
+
fmt = None
|
|
1080
|
+
last = cmd[-1]
|
|
1081
|
+
if not last.startswith("-"):
|
|
1082
|
+
values.append(last)
|
|
1083
|
+
if base.startswith("ffprobe"): # ffprobe's input is its last argument
|
|
1084
|
+
_refuse_playlist(last)
|
|
1085
|
+
elif base.startswith("ffprobe") and last != "-" and os.path.lexists(last):
|
|
1086
|
+
# a file named like an option is still ffprobe's input: guard_input_names() writes it
|
|
1087
|
+
# `./name`, so it is checked as a playlist like any other (review of #636)
|
|
1088
|
+
_refuse_playlist(last)
|
|
1089
|
+
for value in values:
|
|
1090
|
+
if looks_like_url(value):
|
|
1091
|
+
refuse("input", "media_path_is_url",
|
|
1092
|
+
f"{value!r} would be opened by ffmpeg as a URL ({url_scheme(value)}:), not as a local file; "
|
|
1093
|
+
"this skill reads and writes local files only. Pass a plain path (a local name containing "
|
|
1094
|
+
"a colon works as ./name)", path=value, scheme=url_scheme(value))
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def _check_no_overwrite_input(cmd: Sequence[str]) -> None:
|
|
1098
|
+
"""Refuse an ffmpeg command whose output path resolves to the same file as one of its
|
|
1099
|
+
inputs. ffmpeg's own "Output same as Input" guard only catches byte-identical path
|
|
1100
|
+
strings; a relative/absolute pair, a leading "./", a redundant ".." segment, or a symlink
|
|
1101
|
+
all resolve to the same file but pass that check, so "-o ./same.mp4" on an input opened as
|
|
1102
|
+
"same.mp4" would otherwise silently let ffmpeg's -y clobber the source mid-encode. Every
|
|
1103
|
+
write-side script routes through this one run() choke point rather than each computing its
|
|
1104
|
+
own output path defensively, so the guard lives here once instead of at 25+ call sites."""
|
|
1105
|
+
output = cmd[-1]
|
|
1106
|
+
if output in ("-", "pipe:0", "pipe:1") or output.startswith("pipe:") or output.startswith("-"):
|
|
1107
|
+
return
|
|
1108
|
+
try:
|
|
1109
|
+
out_real = os.path.realpath(output)
|
|
1110
|
+
except OSError:
|
|
1111
|
+
return
|
|
1112
|
+
for inp in shape_of(cmd).inputs:
|
|
1113
|
+
if same_file(inp, output):
|
|
1114
|
+
_refuse_output_is_input(output, inp, out_real, "would overwrite it while ffmpeg is still reading it")
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
def same_file(a: str, b: str) -> bool:
|
|
1118
|
+
"""Whether two paths name one file: the same resolved path, or, when both exist, the same
|
|
1119
|
+
file by identity (os.path.samefile: device and inode). The second catches what the strings
|
|
1120
|
+
do not (A5, #465): a hard link, and on a case-insensitive volume (macOS's and Windows'
|
|
1121
|
+
defaults) `Clip.mp4` for `clip.mp4`, which --overwrite then replaced. False when either path
|
|
1122
|
+
cannot be resolved."""
|
|
1123
|
+
try:
|
|
1124
|
+
if os.path.realpath(a) == os.path.realpath(b):
|
|
1125
|
+
return True
|
|
1126
|
+
return os.path.exists(a) and os.path.exists(b) and os.path.samefile(a, b)
|
|
1127
|
+
except (OSError, ValueError):
|
|
1128
|
+
return False
|
|
1129
|
+
|
|
1130
|
+
|
|
1131
|
+
def _refuse_output_is_input(output: str, inp: str, real: str, why: str) -> None:
|
|
1132
|
+
"""The one refusal both output-is-input guards end in: structured, and in the audit log when
|
|
1133
|
+
one is configured (render.py --audit-log)."""
|
|
1134
|
+
details = {"output": output, "input": inp, "resolved": real}
|
|
1135
|
+
audit("output_is_input_refused", details)
|
|
1136
|
+
refuse("input", "output_is_input",
|
|
1137
|
+
f"refusing to run: output {output!r} is the same file as input {inp!r} ({why}) -- choose a different --output/-o path",
|
|
1138
|
+
**details)
|
|
1139
|
+
|
|
1140
|
+
|
|
1141
|
+
def refuse_output_is_input(output: str, *inputs: str, why: str = "the result would replace the source") -> None:
|
|
1142
|
+
"""Tool-level twin of the run() guard, for tools whose final ffmpeg command does not name
|
|
1143
|
+
the user's input at all. `cut.py --segments` cuts each part into a temp dir and then concats
|
|
1144
|
+
a list file: the last command's only `-i` is that list, so `-o` equal to the input sailed
|
|
1145
|
+
through _check_no_overwrite_input() and replaced the source with the join (fourth audit,
|
|
1146
|
+
P0). Call it once the output path is known, before any part of the input is consumed."""
|
|
1147
|
+
try:
|
|
1148
|
+
out_real = os.path.realpath(output)
|
|
1149
|
+
except OSError:
|
|
1150
|
+
return
|
|
1151
|
+
for inp in inputs:
|
|
1152
|
+
# a hard link is another name for the same file: compare the files, not just the names
|
|
1153
|
+
if same_file(inp, output):
|
|
1154
|
+
_refuse_output_is_input(output, inp, out_real, why)
|
|
1155
|
+
|
|
1156
|
+
|
|
1157
|
+
def _check_output_path(cmd: Sequence[str]) -> None:
|
|
1158
|
+
"""An output whose directory does not exist, or that names a directory, is a caller mistake:
|
|
1159
|
+
say so as `kind: input` before ffmpeg runs, instead of the muxer's "No such file or directory"
|
|
1160
|
+
as `kind: ffmpeg` (which reads as an encoder failure) or an `OUTPUT_INVALID` after the fact."""
|
|
1161
|
+
output = cmd[-1]
|
|
1162
|
+
if output == "-" or output.startswith("pipe:"):
|
|
1163
|
+
return
|
|
1164
|
+
if output.startswith("-"):
|
|
1165
|
+
# ffmpeg would read it as an option (-report writes a log file, -y overwrites)
|
|
1166
|
+
refuse("input", "output_looks_like_option",
|
|
1167
|
+
f"output {output!r} starts with '-', which ffmpeg would read as an option; pass ./{output} for a file of that name",
|
|
1168
|
+
output=output)
|
|
1169
|
+
if looks_like_url(output):
|
|
1170
|
+
refuse("input", "media_path_is_url",
|
|
1171
|
+
f"output {output!r} would be opened by ffmpeg as a URL, not as a local file; pass a plain path "
|
|
1172
|
+
"(a local name containing a colon works as ./name)", path=output, scheme=output.split(":", 1)[0].lower())
|
|
1173
|
+
if re.search(r"\.(m3u8?|mpd)$|%0?\d*d[^/\\]*\.(png|jpe?g|bmp|tiff?|webp|dpx|exr|tga|p[pg]m|jp2)$", output, re.I) and "-update" not in cmd:
|
|
1174
|
+
# a playlist or a numbered pattern makes ffmpeg write files it names itself (out0.ts,
|
|
1175
|
+
# frame001.png): no guard here has seen them, and -y replaced the ones that existed (#562)
|
|
1176
|
+
refuse("input", "output_extension_unsupported",
|
|
1177
|
+
f"output {output!r} would make ffmpeg write files it names itself (segments, numbered frames), over any that exist; this skill writes one file per -o",
|
|
1178
|
+
output=output)
|
|
1179
|
+
if os.path.isdir(output):
|
|
1180
|
+
refuse("input", "output_is_directory",
|
|
1181
|
+
f"output {output!r} is a directory; pass a file path (e.g. {os.path.join(output, 'result.mp4')!r})", output=output)
|
|
1182
|
+
parent = os.path.dirname(os.path.abspath(output))
|
|
1183
|
+
if not os.path.isdir(parent):
|
|
1184
|
+
refuse("input", "output_dir_missing",
|
|
1185
|
+
f"output directory {parent!r} does not exist; create it first (this tool never creates directories)",
|
|
1186
|
+
output=output, directory=parent)
|
|
1187
|
+
if not os.access(parent, os.W_OK):
|
|
1188
|
+
refuse("input", "output_dir_not_writable", f"output directory {parent!r} is not writable", output=output, directory=parent)
|
|
1189
|
+
|
|
1190
|
+
|
|
1191
|
+
class Shape(NamedTuple):
|
|
1192
|
+
# What an ffmpeg command line reads and writes, found once: the checks below each used to
|
|
1193
|
+
# search the argument list for `-i` and take the last argument as the output themselves.
|
|
1194
|
+
inputs: Tuple[str, ...] # every `-i` value, in order
|
|
1195
|
+
output: str # the last argument
|
|
1196
|
+
output_opts: Tuple[str, ...] # what follows the last input's path, before the output
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
def shape_of(cmd: Sequence[str]) -> Shape:
|
|
1200
|
+
last_input = max((i for i, tok in enumerate(cmd[:-1]) if tok == "-i"), default=-1)
|
|
1201
|
+
return Shape(tuple(str(cmd[i + 1]) for i, tok in enumerate(cmd[:-1]) if tok == "-i"),
|
|
1202
|
+
str(cmd[-1]) if cmd else "", tuple(str(a) for a in cmd[last_input + 2:-1]))
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
def _check_output_extension(cmd: Sequence[str]) -> None:
|
|
1206
|
+
"""An ffmpeg output with no file extension and no `-f` after its last input leaves the muxer
|
|
1207
|
+
nothing to choose a container by: refused as `kind: input` before anything runs, dry runs
|
|
1208
|
+
included. Through 3.8.8 every tool that writes media handed it on and failed as `kind: ffmpeg`
|
|
1209
|
+
("Unable to choose an output format", audit A159's sweep). Only the ffmpeg commands run()
|
|
1210
|
+
executes are checked: a sidecar (a report, an SRT) is a plain file and needs no extension,
|
|
1211
|
+
and look.py takes an -o without an image extension as a stem (docs/design-decisions.md)."""
|
|
1212
|
+
output = cmd[-1]
|
|
1213
|
+
if output == "-" or output.startswith("pipe:"):
|
|
1214
|
+
return
|
|
1215
|
+
forced = "-f" in shape_of(cmd).output_opts
|
|
1216
|
+
if len(os.path.splitext(output)[1]) > 1:
|
|
1217
|
+
refuse_unwritten_output(output, cmd)
|
|
1218
|
+
if not forced:
|
|
1219
|
+
_refuse_unknown_extension(output)
|
|
1220
|
+
return
|
|
1221
|
+
if forced:
|
|
1222
|
+
return
|
|
1223
|
+
refuse("input", "output_extension_missing",
|
|
1224
|
+
f"output {output!r} has no file extension, so ffmpeg cannot tell which container to write; "
|
|
1225
|
+
f"name it with one (for example {output + '.mp4'!r})", output=output)
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
# Extensions every FFmpeg build this skill supports maps to a muxer: an output named with one is
|
|
1229
|
+
# handed on without asking the build (no process). `.mka` is here because the Matroska audio muxer
|
|
1230
|
+
# shares its name with the Matroska one, so `ffmpeg -h muxer=matroska` never lists it.
|
|
1231
|
+
_COMMON_OUTPUT_EXT = frozenset({
|
|
1232
|
+
".mp4", ".mov", ".mkv", ".mka", ".webm", ".m4v", ".m4a", ".avi", ".ts", ".mts", ".m2ts", ".mxf", ".3gp", ".wmv",
|
|
1233
|
+
".wma", ".gif", ".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff", ".wav", ".flac", ".mp3", ".aac", ".ogg",
|
|
1234
|
+
".opus", ".aif", ".aiff", ".caf", ".srt", ".ass", ".vtt", ".nut", ".mpg", ".mpeg", ".flv", ".y4m"})
|
|
1235
|
+
_MUXER_EXT: "List[Optional[frozenset]]" = [] # this build's answer, read once per process
|
|
1236
|
+
|
|
1237
|
+
|
|
1238
|
+
def _muxer_extensions() -> "Optional[frozenset]":
|
|
1239
|
+
"""Every file extension this ffmpeg build maps to a muxer (lower case, with the dot), or None
|
|
1240
|
+
when the build could not be asked: the names from `ffmpeg -muxers`, and each one's "Common
|
|
1241
|
+
extensions:" line from `ffmpeg -h muxer=NAME`. That is a short process per muxer (about 190
|
|
1242
|
+
on 6.1.1, 1 to 2 s together), so it is asked only for an extension _COMMON_OUTPUT_EXT does not
|
|
1243
|
+
hold, and once. One muxer that cannot be read makes the whole answer None, never a shorter list."""
|
|
1244
|
+
if _MUXER_EXT:
|
|
1245
|
+
return _MUXER_EXT[0]
|
|
1246
|
+
found: Optional[frozenset] = None
|
|
1247
|
+
try:
|
|
1248
|
+
exe = found_exe("ffmpeg")
|
|
1249
|
+
kw: Dict[str, Any] = dict(stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, text=True,
|
|
1250
|
+
encoding="utf-8", errors="replace", timeout=_probe_limit())
|
|
1251
|
+
listing = subprocess.run([exe, "-hide_banner", "-muxers"], **kw)
|
|
1252
|
+
names = re.findall(r"^\s*D?E[d ]?\s+(\S+)", listing.stdout.split("--", 1)[-1], re.M) if listing.returncode == 0 else []
|
|
1253
|
+
|
|
1254
|
+
def extensions(name: str) -> List[str]:
|
|
1255
|
+
shown = subprocess.run([exe, "-hide_banner", "-h", f"muxer={name.split(',')[0]}"], **kw)
|
|
1256
|
+
if shown.returncode != 0 or "Muxer " not in shown.stdout:
|
|
1257
|
+
raise OSError(f"muxer {name} could not be read")
|
|
1258
|
+
return [e.strip().lower() for line in re.findall(r"^\s*Common extensions:\s*(.+?)\.?\s*$", shown.stdout, re.M)
|
|
1259
|
+
for e in line.split(",") if e.strip()]
|
|
1260
|
+
|
|
1261
|
+
if names:
|
|
1262
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
1263
|
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
1264
|
+
exts = {"." + e for group in pool.map(extensions, names) for e in group}
|
|
1265
|
+
found = frozenset(exts) or None
|
|
1266
|
+
except (OSError, ValueError, subprocess.TimeoutExpired, SystemExit):
|
|
1267
|
+
found = None
|
|
1268
|
+
_MUXER_EXT.append(found)
|
|
1269
|
+
return found
|
|
1270
|
+
|
|
1271
|
+
|
|
1272
|
+
def _refuse_unknown_extension(output: str) -> None:
|
|
1273
|
+
"""An output whose extension this ffmpeg build maps to no muxer is refused as `kind: input`
|
|
1274
|
+
before ffmpeg runs, dry runs included (#558): `-o weird.xyz` failed inside ffmpeg as `kind:
|
|
1275
|
+
ffmpeg` ("Unable to choose an output format") after a dry run that completed. FFmpeg chooses
|
|
1276
|
+
the muxer by the extension alone, without case, so the build's own list decides
|
|
1277
|
+
(_muxer_extensions()); when the build cannot be asked the command runs as before."""
|
|
1278
|
+
ext = os.path.splitext(output)[1].lower()
|
|
1279
|
+
if ext in _COMMON_OUTPUT_EXT:
|
|
1280
|
+
return
|
|
1281
|
+
known = _muxer_extensions()
|
|
1282
|
+
if known is None or ext in known:
|
|
1283
|
+
return
|
|
1284
|
+
from _common.decision import AUDIO_CODECS # decision imports this module
|
|
1285
|
+
refuse("input", "output_extension_unknown",
|
|
1286
|
+
f"output {output!r}: this ffmpeg build has no muxer for the extension {ext}, so it cannot tell "
|
|
1287
|
+
"which container to write",
|
|
1288
|
+
hint="name -o with an extension the tool writes: .mp4, .mov or .mkv for video; for a tool that writes "
|
|
1289
|
+
f"sound, {', '.join(AUDIO_CODECS)}; for one that writes a picture, .png or .jpg",
|
|
1290
|
+
output=output, extension=ext)
|
|
1291
|
+
|
|
1292
|
+
|
|
1293
|
+
# The WMA codecs ffprobe names (FFmpeg's decoders): a stream of one of them copied into `.wma` is
|
|
1294
|
+
# the WMA it was, which the ASF muxer holds; wmav1 and wmav2 were written so on 6.1.1 (#517)
|
|
1295
|
+
WMA_CODECS = frozenset({"wmav1", "wmav2", "wmapro", "wmalossless", "wmavoice"})
|
|
1296
|
+
|
|
1297
|
+
|
|
1298
|
+
def _copies_wma_only(cmd: Sequence[str]) -> bool:
|
|
1299
|
+
"""True when `cmd` encodes nothing and every input holds WMA sound and no picture (or the
|
|
1300
|
+
picture is dropped with -vn): a stream copy of a WMA source, which `.wma` holds as it was."""
|
|
1301
|
+
if any(tok in ("-filter_complex", "-lavfi", "-filter_complex_script", "-af", "-filter:a", "-vf", "-filter:v")
|
|
1302
|
+
for tok in cmd):
|
|
1303
|
+
return False
|
|
1304
|
+
codecs = [cmd[i + 1] for i, tok in enumerate(cmd[:-2]) if _CODEC_OPTION_RE.match(tok)
|
|
1305
|
+
and (_CODEC_OPTION_RE.match(tok).group(1) or _CODEC_OPTION_RE.match(tok).group(2)) in (None, "a")]
|
|
1306
|
+
if not codecs or any(c != "copy" for c in codecs):
|
|
1307
|
+
return False
|
|
1308
|
+
no_video = "-vn" in cmd
|
|
1309
|
+
paths: List[str] = []
|
|
1310
|
+
parts: List[str] = []
|
|
1311
|
+
for i, tok in enumerate(cmd[:-1]):
|
|
1312
|
+
if tok != "-i":
|
|
1313
|
+
continue
|
|
1314
|
+
if "concat" in [cmd[j + 1] for j in range(max(0, i - 6), i) if cmd[j] == "-f"]:
|
|
1315
|
+
# a copy join of parts (cut.py --segments): the parts the list names are the inputs
|
|
1316
|
+
try:
|
|
1317
|
+
with open(cmd[i + 1], encoding="utf-8") as fh:
|
|
1318
|
+
listed = [ln.strip()[5:].strip() for ln in fh if ln.strip().startswith("file ")]
|
|
1319
|
+
except OSError:
|
|
1320
|
+
return False
|
|
1321
|
+
names = [p[1:-1].replace("'\\''", "'") if p.startswith("'") and p.endswith("'") else p for p in listed]
|
|
1322
|
+
parts += [os.path.join(os.path.dirname(cmd[i + 1]), p) for p in names] # a relative name is the list's
|
|
1323
|
+
else:
|
|
1324
|
+
paths.append(cmd[i + 1])
|
|
1325
|
+
if not paths and not parts:
|
|
1326
|
+
return False
|
|
1327
|
+
for path in paths + parts:
|
|
1328
|
+
if not os.path.isfile(path):
|
|
1329
|
+
# a dry run has not written the parts it joins; each was a .wma copy its own command let
|
|
1330
|
+
# through, so the join of them is one too
|
|
1331
|
+
if STATE.dry_run and path in parts and os.path.splitext(path)[1].lower() == os.path.splitext(cmd[-1])[1].lower():
|
|
1332
|
+
continue
|
|
1333
|
+
return False
|
|
1334
|
+
probe_cmd = [shutil.which("ffprobe") or "ffprobe", "-v", "error", "-show_entries",
|
|
1335
|
+
"stream=codec_type,codec_name:stream_disposition=attached_pic", "-of", "json", file_arg(path)]
|
|
1336
|
+
try:
|
|
1337
|
+
proc = subprocess.run(probe_cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
1338
|
+
timeout=_probe_limit())
|
|
1339
|
+
streams = json.loads(proc.stdout or "{}").get("streams") or []
|
|
1340
|
+
except (subprocess.TimeoutExpired, OSError, ValueError):
|
|
1341
|
+
return False
|
|
1342
|
+
audio = [st.get("codec_name") for st in streams if st.get("codec_type") == "audio"]
|
|
1343
|
+
video = [st for st in streams if st.get("codec_type") == "video"]
|
|
1344
|
+
if not audio or any(c not in WMA_CODECS for c in audio) or (video and not no_video):
|
|
1345
|
+
return False
|
|
1346
|
+
return True
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
def refuse_unwritten_output(output: str, cmd: Optional[Sequence[str]] = None) -> None:
|
|
1350
|
+
"""An output named with an audio extension this skill reads but does not write
|
|
1351
|
+
(decision.UNWRITTEN_AUDIO_EXT: .wma) is refused as `kind: input`, before ffmpeg runs, dry runs
|
|
1352
|
+
included (#517): there is no WMA encoder line, and FFmpeg's ASF muxer took the H.264 and AAC
|
|
1353
|
+
the tools encode and the run completed, verified, with a file no player takes for WMA. The one
|
|
1354
|
+
command let through is a stream copy of WMA sound (`cmd` given, `_copies_wma_only()`): that
|
|
1355
|
+
was WMA before and is kept. Called for every ffmpeg command run() checks, and with no `cmd`
|
|
1356
|
+
(an encode) by a tool that knows it encodes, before its measuring pass or its own extension
|
|
1357
|
+
rule (join.py, render.py, loudness.py, silence.py)."""
|
|
1358
|
+
from _common.decision import AUDIO_CODECS, UNWRITTEN_AUDIO_EXT # decision imports this module
|
|
1359
|
+
ext = os.path.splitext(output)[1].lower()
|
|
1360
|
+
if ext not in UNWRITTEN_AUDIO_EXT or (cmd is not None and _copies_wma_only(cmd)):
|
|
1361
|
+
return
|
|
1362
|
+
written = list(AUDIO_CODECS)
|
|
1363
|
+
refuse("input", "output_extension_unsupported",
|
|
1364
|
+
f"output {output!r}: this skill writes no {ext} file except a stream copy of WMA sound, and this "
|
|
1365
|
+
f"run would encode into it",
|
|
1366
|
+
hint=f"name -o with an extension it writes: {', '.join(written)} for sound, or a video container",
|
|
1367
|
+
output=output, extension=ext, written=written)
|
|
1368
|
+
|
|
1369
|
+
|
|
1370
|
+
# What the WebM muxer takes (6.1: "Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and
|
|
1371
|
+
# WebVTT subtitles are supported for WebM"), by the encoder a command names (#488).
|
|
1372
|
+
_WEBM_VIDEO_ENCODER_RE = re.compile(r"^(?:libvpx(?:-vp9)?|vp8|vp9|libaom-av1|libsvtav1|librav1e|av1|vp8_\w+|vp9_\w+|av1_\w+)$")
|
|
1373
|
+
_WEBM_AUDIO_ENCODER_RE = re.compile(r"^(?:libopus|opus|libvorbis|vorbis)$")
|
|
1374
|
+
_CODEC_OPTION_RE = re.compile(r"^-(?:c|codec)(?::([va])(?::\d+)?)?$|^-(v|a)codec$")
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
def _an_input_has(cmd: Sequence[str], kind: str) -> bool:
|
|
1378
|
+
"""False only when every input of `cmd` is a file that was read and holds no `kind` ("v"/"a"/"s")
|
|
1379
|
+
stream, and no filter graph could make one. An encoder option for a stream the output will
|
|
1380
|
+
not have selects nothing (FFmpeg applies -c:a after stream selection), so it is not a reason
|
|
1381
|
+
to refuse: cut.py names -c:a aac for a silent source too. Anything not known counts as present."""
|
|
1382
|
+
if any(tok in ("-filter_complex", "-lavfi", "-filter_complex_script") for tok in cmd):
|
|
1383
|
+
return True
|
|
1384
|
+
paths = shape_of(cmd).inputs
|
|
1385
|
+
if not paths:
|
|
1386
|
+
return True
|
|
1387
|
+
for i, tok in enumerate(cmd[:-1]):
|
|
1388
|
+
if tok == "-f" and cmd[i + 1] in ("lavfi", "concat"):
|
|
1389
|
+
return True
|
|
1390
|
+
for path in paths:
|
|
1391
|
+
if not os.path.isfile(path):
|
|
1392
|
+
return True
|
|
1393
|
+
probe_cmd = [shutil.which("ffprobe") or "ffprobe", "-v", "error", "-select_streams", kind,
|
|
1394
|
+
"-show_entries", "stream=index", "-of", "csv=p=0", *input_format_args(path), file_arg(path)]
|
|
1395
|
+
limit = _probe_limit() # PROBE_TIMEOUT, or --timeout when that is lower; never unlimited (--timeout 0)
|
|
1396
|
+
try:
|
|
1397
|
+
proc = subprocess.run(probe_cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=limit)
|
|
1398
|
+
except subprocess.TimeoutExpired:
|
|
1399
|
+
# a stalled read is reported as what it is, not turned into "the stream is there"
|
|
1400
|
+
die(f"ffprobe did not finish reading {path} within {limit:g} s and was killed; nothing was written",
|
|
1401
|
+
code=124, kind="timeout", output=cmd[-1])
|
|
1402
|
+
except OSError:
|
|
1403
|
+
return True
|
|
1404
|
+
if proc.returncode != 0 or proc.stdout.strip():
|
|
1405
|
+
return True
|
|
1406
|
+
return False
|
|
1407
|
+
|
|
1408
|
+
|
|
1409
|
+
def _check_container_codecs(cmd: Sequence[str]) -> None:
|
|
1410
|
+
"""A `.webm` output whose command encodes a picture or a sound WebM cannot hold (the tools'
|
|
1411
|
+
H.264/HEVC and AAC lines) is refused before anything runs, dry runs included: the muxer
|
|
1412
|
+
refused it only after the encode had started, as `kind: ffmpeg` with "Nothing was written
|
|
1413
|
+
into output file", and a dry run said completed (#488). A stream copy is left to the muxer:
|
|
1414
|
+
what it copies is not named in the command."""
|
|
1415
|
+
output = cmd[-1]
|
|
1416
|
+
if os.path.splitext(output)[1].lower() != ".webm":
|
|
1417
|
+
return
|
|
1418
|
+
refused: List[Any] = []
|
|
1419
|
+
for i, tok in enumerate(cmd[:-2]):
|
|
1420
|
+
m = _CODEC_OPTION_RE.match(tok)
|
|
1421
|
+
if not m:
|
|
1422
|
+
continue
|
|
1423
|
+
stream, value = m.group(1) or m.group(2), cmd[i + 1]
|
|
1424
|
+
if value == "copy" or stream is None:
|
|
1425
|
+
continue
|
|
1426
|
+
allowed = _WEBM_VIDEO_ENCODER_RE if stream == "v" else _WEBM_AUDIO_ENCODER_RE
|
|
1427
|
+
if not allowed.match(value):
|
|
1428
|
+
refused.append((stream, value))
|
|
1429
|
+
# only for a stream the output will have: asked last, and only when something would be refused
|
|
1430
|
+
refused = [value for stream, value in dict.fromkeys(refused) if _an_input_has(cmd, stream)]
|
|
1431
|
+
if refused:
|
|
1432
|
+
refuse("input", "output_container_codecs",
|
|
1433
|
+
f"output {output!r} is WebM, which holds only VP8/VP9/AV1 video and Opus/Vorbis sound; this tool "
|
|
1434
|
+
f"encodes {' and '.join(refused)} for it",
|
|
1435
|
+
hint="name a .mp4, .mov or .mkv output (Matroska holds what WebM refuses); "
|
|
1436
|
+
"a transparent VP9 WebM is --keep-alpha --alpha-codec vp9 or export.py --preset vp9-alpha",
|
|
1437
|
+
output=output, container="webm", encoders=refused)
|
|
1438
|
+
|
|
1439
|
+
|
|
1440
|
+
def _check_picture_into_audio_extension(cmd: Sequence[str]) -> None:
|
|
1441
|
+
"""An output named with an audio-only extension (probe.AUDIO_MEDIA_EXT) whose command encodes
|
|
1442
|
+
a picture is refused before anything runs, dry runs included (#539): the tools that always
|
|
1443
|
+
write a picture took `-o x.m4a` and completed, verified, with H.264 in a file named for sound,
|
|
1444
|
+
and failed in the muxer for `-o x.wav` (`kind: ffmpeg`, "WAVE files have exactly one stream")
|
|
1445
|
+
after a dry run that said completed. waveform.py has refused it by its own rule since #516.
|
|
1446
|
+
Judged from the command, as the WebM rule above is: a video encoder named for the output
|
|
1447
|
+
(`-c:v` other than copy), no `-vn`, and an input that can give a picture. A stream copy is not
|
|
1448
|
+
judged (a cover picture copied beside its sound stays), nor is a command that names no
|
|
1449
|
+
video encoder (a sound extraction)."""
|
|
1450
|
+
from _common.probe import AUDIO_MEDIA_EXT # probe imports this module
|
|
1451
|
+
output = cmd[-1]
|
|
1452
|
+
ext = os.path.splitext(output)[1].lower()
|
|
1453
|
+
if ext not in AUDIO_MEDIA_EXT:
|
|
1454
|
+
return
|
|
1455
|
+
if "-vn" in shape_of(cmd).output_opts:
|
|
1456
|
+
return
|
|
1457
|
+
encoders = []
|
|
1458
|
+
for i, tok in enumerate(cmd[:-2]):
|
|
1459
|
+
m = _CODEC_OPTION_RE.match(tok)
|
|
1460
|
+
if m and (m.group(1) or m.group(2)) == "v" and cmd[i + 1] != "copy":
|
|
1461
|
+
encoders.append(cmd[i + 1])
|
|
1462
|
+
if not encoders or not _an_input_has(cmd, "v"):
|
|
1463
|
+
return
|
|
1464
|
+
refuse("input", "output_extension_audio_only",
|
|
1465
|
+
f"output {output!r}: {ext} holds sound only, and this run writes a picture ({encoders[0]})",
|
|
1466
|
+
hint="name a video file (.mp4, .mov, .mkv); for the sound alone, cut.py or audio.py with an audio "
|
|
1467
|
+
"extension extracts it",
|
|
1468
|
+
output=output, extension=ext, encoders=list(dict.fromkeys(encoders)))
|
|
1469
|
+
|
|
1470
|
+
|
|
1471
|
+
# the options whose value is a filter graph this module can read the filter names out of
|
|
1472
|
+
_GRAPH_OPTIONS = frozenset({"-vf", "-af", "-filter:v", "-filter:a", "-filter_complex", "-lavfi"})
|
|
1473
|
+
_ENCODER_OPTION_RE = re.compile(r"^-(?:c|codec):([vas])(?::\d+)?$|^-([vas])codec$")
|
|
1474
|
+
# the output option that drops every stream of a kind: an encoder named for that kind selects nothing
|
|
1475
|
+
_NO_STREAM_OPTION = {"v": "-vn", "a": "-an", "s": "-sn"}
|
|
1476
|
+
# one row of `ffmpeg -encoders` / `ffmpeg -filters` (the filter row by its io-spec token, so the
|
|
1477
|
+
# flag-column width of FFmpeg 6/7 and 8+ does not matter): ffmpeg_encoders(), ffmpeg_filters()
|
|
1478
|
+
_ENCODER_ROW = r"^\s*[VAS][.\w]{5}\s+(\S+)"
|
|
1479
|
+
_FILTER_ROW = r"^\s*(?:[A-Z.|]{1,6}\s+)?([A-Za-z0-9_]+)\s+\S*->\S*"
|
|
1480
|
+
# quiet reads of a list the tool itself never asked for: {"-encoders": names, "-filters": names}
|
|
1481
|
+
_PREFLIGHT_LISTS: Dict[str, set] = {}
|
|
1482
|
+
|
|
1483
|
+
|
|
1484
|
+
def graph_filter_names(graph: str) -> List[str]:
|
|
1485
|
+
"""The filter names of one filter graph string, in order, without duplicates. A `,` or `;`
|
|
1486
|
+
separates filters only outside '...' quotes and when no backslash escapes it; `[labels]` before
|
|
1487
|
+
a filter and its `=options` / `@instance` are dropped. A graph-level `sws_flags=` is not a
|
|
1488
|
+
filter and is left out, as is anything that is not a plain identifier."""
|
|
1489
|
+
parts: List[str] = []
|
|
1490
|
+
cur: List[str] = []
|
|
1491
|
+
quoted = False
|
|
1492
|
+
i = 0
|
|
1493
|
+
while i < len(graph):
|
|
1494
|
+
ch = graph[i]
|
|
1495
|
+
if ch == "\\" and i + 1 < len(graph):
|
|
1496
|
+
cur.append(graph[i:i + 2])
|
|
1497
|
+
i += 2
|
|
1498
|
+
continue
|
|
1499
|
+
if ch == "'":
|
|
1500
|
+
quoted = not quoted
|
|
1501
|
+
elif ch in ",;" and not quoted:
|
|
1502
|
+
parts.append("".join(cur))
|
|
1503
|
+
cur = []
|
|
1504
|
+
i += 1
|
|
1505
|
+
continue
|
|
1506
|
+
cur.append(ch)
|
|
1507
|
+
i += 1
|
|
1508
|
+
parts.append("".join(cur))
|
|
1509
|
+
names: List[str] = []
|
|
1510
|
+
for part in parts:
|
|
1511
|
+
part = part.strip()
|
|
1512
|
+
while part.startswith("["):
|
|
1513
|
+
end = part.find("]")
|
|
1514
|
+
if end < 0:
|
|
1515
|
+
break
|
|
1516
|
+
part = part[end + 1:].lstrip()
|
|
1517
|
+
m = re.match(r"[A-Za-z0-9_]+", part)
|
|
1518
|
+
if not m or m.end() < len(part) and part[m.end()] not in "=@[ \t":
|
|
1519
|
+
continue
|
|
1520
|
+
if m.group(0) != "sws_flags" and m.group(0) not in names:
|
|
1521
|
+
names.append(m.group(0))
|
|
1522
|
+
return names
|
|
1523
|
+
|
|
1524
|
+
|
|
1525
|
+
def _build_list(flag: str) -> set:
|
|
1526
|
+
"""This build's encoder or filter names for the check below: the list a tool already read, else
|
|
1527
|
+
one quiet read. A list that cannot be read is empty here and refuses nothing; the
|
|
1528
|
+
`ffmpeg_list_unreadable` warning stays with the tools that decide something on the list."""
|
|
1529
|
+
cached = _ENCODERS if flag == "-encoders" else _FILTERS
|
|
1530
|
+
if cached is not None:
|
|
1531
|
+
return cached
|
|
1532
|
+
if flag not in _PREFLIGHT_LISTS:
|
|
1533
|
+
_PREFLIGHT_LISTS[flag] = _read_ff_list(flag, _ENCODER_ROW if flag == "-encoders" else _FILTER_ROW, quiet=True)
|
|
1534
|
+
return _PREFLIGHT_LISTS[flag]
|
|
1535
|
+
|
|
1536
|
+
|
|
1537
|
+
def _check_build_components(cmd: Sequence[str]) -> None:
|
|
1538
|
+
"""An encoder or a filter the command names and this ffmpeg build does not have is refused
|
|
1539
|
+
before anything runs, dry runs included, with the kind, reason and hint the run got from
|
|
1540
|
+
ffmpeg's "Unknown encoder" / "No such filter" (#402): the dry run said completed, and a real
|
|
1541
|
+
run found out after its earlier commands had run. Read from the command as built, so every tool
|
|
1542
|
+
and every route to an encoder (an HDR source kept as HEVC, --codec, a preset) is covered.
|
|
1543
|
+
Only output options are read (a -c:v before an -i picks a decoder), and an encoder only for a
|
|
1544
|
+
stream kind the output keeps: not one -an/-vn/-sn drops or no input file carries. A VideoToolbox encoder is
|
|
1545
|
+
left to --hw's own checks and its CPU retry, a -filter_complex_script and a lavfi input are not
|
|
1546
|
+
parsed, and a list that could not be read refuses nothing."""
|
|
1547
|
+
last_input = max((i for i, tok in enumerate(cmd[:-1]) if tok == "-i"), default=-1)
|
|
1548
|
+
encoders: List[str] = []
|
|
1549
|
+
streams: Dict[str, set] = {} # encoder -> the stream kinds ("v", "a", "s") it is named for
|
|
1550
|
+
filters: List[str] = []
|
|
1551
|
+
output_opts = set(shape_of(cmd).output_opts)
|
|
1552
|
+
for i in range(1, len(cmd) - 1):
|
|
1553
|
+
tok, value = str(cmd[i]), str(cmd[i + 1])
|
|
1554
|
+
m = _ENCODER_OPTION_RE.match(tok)
|
|
1555
|
+
if tok in _GRAPH_OPTIONS:
|
|
1556
|
+
filters += [n for n in graph_filter_names(value) if n not in filters]
|
|
1557
|
+
elif i > last_input and m and value != "copy" and not value.endswith("_videotoolbox"):
|
|
1558
|
+
if value not in encoders:
|
|
1559
|
+
encoders.append(value)
|
|
1560
|
+
streams.setdefault(value, set()).add(m.group(1) or m.group(2))
|
|
1561
|
+
|
|
1562
|
+
def selected(name: str) -> bool:
|
|
1563
|
+
# ffmpeg picks an encoder per output stream, after stream selection: one named for a kind
|
|
1564
|
+
# the output drops (-an/-vn/-sn) or that no input carries (cut.py names -c:a aac for a
|
|
1565
|
+
# silent source too) is never opened. What the command cannot tell (a -filter_complex graph, a
|
|
1566
|
+
# lavfi or unreadable input) counts as selected; explicit -map lists are not read.
|
|
1567
|
+
return any(_NO_STREAM_OPTION[k] not in output_opts and _an_input_has(cmd, k) for k in streams.get(name, ()))
|
|
1568
|
+
|
|
1569
|
+
for flag, wanted, what, reason in (("-encoders", encoders, "encoder", "encoder_missing"),
|
|
1570
|
+
("-filters", filters, "filter", "filter_missing")):
|
|
1571
|
+
have = _build_list(flag) if wanted else set()
|
|
1572
|
+
missing = [n for n in wanted if n not in have] if have else []
|
|
1573
|
+
if what == "encoder":
|
|
1574
|
+
missing = [n for n in missing if selected(n)] # asked last: only an encoder that would be refused is probed for
|
|
1575
|
+
if missing:
|
|
1576
|
+
name = missing[0]
|
|
1577
|
+
hint = filter_missing_hint(name) if what == "filter" else filter_missing_hint(name).replace(
|
|
1578
|
+
f"no {name} filter", f"no {name} encoder", 1)
|
|
1579
|
+
die(f"this ffmpeg build has no {name} {what}, which the command this run builds needs"
|
|
1580
|
+
+ (f" (also missing: {', '.join(missing[1:])})" if missing[1:] else ""),
|
|
1581
|
+
code=1, kind="ffmpeg", hint=hint,
|
|
1582
|
+
error_extra={"reason": reason, "details": {"name": name}})
|
|
1583
|
+
|
|
1584
|
+
|
|
1585
|
+
EVEN_SCALE = "scale=trunc(iw/2)*2:trunc(ih/2)*2"
|
|
1586
|
+
|
|
1587
|
+
|
|
1588
|
+
def _pid_dead(pid: int) -> bool:
|
|
1589
|
+
"""True only when the process is known not to have exited. POSIX: signal 0. Windows:
|
|
1590
|
+
OpenProcess fails with ERROR_INVALID_PARAMETER (87) for a pid that is not in use; a process
|
|
1591
|
+
that has exited still opens while any handle to it is open (its parent's Popen keeps one), so
|
|
1592
|
+
its exit code is read too, and one other than STILL_ACTIVE (259) is dead (review of #530: the
|
|
1593
|
+
Windows CI judged a finished child alive and refused its stale lock as held). Any other
|
|
1594
|
+
outcome (access denied, an unreadable code) means it is live. Unknown is treated as live."""
|
|
1595
|
+
if os.name != "nt":
|
|
1596
|
+
try:
|
|
1597
|
+
os.kill(pid, 0)
|
|
1598
|
+
except ProcessLookupError:
|
|
1599
|
+
return True
|
|
1600
|
+
except OSError:
|
|
1601
|
+
pass
|
|
1602
|
+
return False
|
|
1603
|
+
try:
|
|
1604
|
+
import ctypes
|
|
1605
|
+
k32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
1606
|
+
handle = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
|
1607
|
+
if handle:
|
|
1608
|
+
try:
|
|
1609
|
+
code = ctypes.c_ulong(0)
|
|
1610
|
+
if k32.GetExitCodeProcess(handle, ctypes.byref(code)):
|
|
1611
|
+
return code.value != 259 # STILL_ACTIVE
|
|
1612
|
+
return False
|
|
1613
|
+
finally:
|
|
1614
|
+
k32.CloseHandle(handle)
|
|
1615
|
+
return k32.GetLastError() == 87
|
|
1616
|
+
except Exception:
|
|
1617
|
+
return False
|
|
1618
|
+
|
|
1619
|
+
|
|
1620
|
+
LOCK_HOUR = 3600.0
|
|
1621
|
+
LOCK_UNLIMITED = 10 * 365 * 86400.0 # --timeout 0: the deadline is pushed past any run (and kept short of 2038)
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
SECTION_WAIT = 2.0 # seconds a run waits for another's takeover section before it is refused
|
|
1625
|
+
|
|
1626
|
+
|
|
1627
|
+
class _SectionUnavailable(OSError):
|
|
1628
|
+
"""This filesystem (or platform) gives no OS file lock to the takeover section."""
|
|
1629
|
+
|
|
1630
|
+
|
|
1631
|
+
def _os_lock(fd: int) -> bool:
|
|
1632
|
+
"""Lock `fd` exclusively through the OS without waiting: True when locked, False when another
|
|
1633
|
+
open file holds it. The kernel releases it when the file is closed or its process ends, killed
|
|
1634
|
+
or not. _SectionUnavailable when the filesystem or platform has no such lock."""
|
|
1635
|
+
if os.name == "nt":
|
|
1636
|
+
import errno
|
|
1637
|
+
import msvcrt
|
|
1638
|
+
try:
|
|
1639
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
1640
|
+
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) # one byte; a lock past the end of a file is allowed
|
|
1641
|
+
return True
|
|
1642
|
+
except OSError as exc:
|
|
1643
|
+
if exc.errno in (errno.EACCES, getattr(errno, "EDEADLOCK", errno.EDEADLK), errno.EDEADLK):
|
|
1644
|
+
return False
|
|
1645
|
+
raise _SectionUnavailable(str(exc)) from exc
|
|
1646
|
+
try:
|
|
1647
|
+
import fcntl
|
|
1648
|
+
except ImportError as exc:
|
|
1649
|
+
raise _SectionUnavailable(f"no fcntl here: {exc}") from exc
|
|
1650
|
+
try:
|
|
1651
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
1652
|
+
return True
|
|
1653
|
+
except BlockingIOError:
|
|
1654
|
+
return False
|
|
1655
|
+
except OSError as exc:
|
|
1656
|
+
raise _SectionUnavailable(str(exc)) from exc
|
|
1657
|
+
|
|
1658
|
+
|
|
1659
|
+
class _TakeoverSection:
|
|
1660
|
+
"""The section in which a stale output lock is judged, removed and replaced, and in which a
|
|
1661
|
+
holder removes its own lock: `<lock>.takeover`, held through an OS file lock (flock on POSIX,
|
|
1662
|
+
msvcrt.locking on Windows), never through the file's existence or age. The kernel releases it
|
|
1663
|
+
when the run closes it or ends, killed included, so nothing in it expires while its holder
|
|
1664
|
+
lives -- a paused holder still holds it -- and nothing is left for anyone to recover (review of
|
|
1665
|
+
#530: every timed or claimed scheme before this had a window where a paused run lost it).
|
|
1666
|
+
|
|
1667
|
+
The file itself means nothing: its name is removed when the section is left, so no file stays
|
|
1668
|
+
beside the output. On POSIX the name is removed while the lock is still held, and a run that
|
|
1669
|
+
opened the old file before that finds, once it has the lock, that the name is now another file
|
|
1670
|
+
or none, and starts again (the usual lock-file race). On Windows a file another handle has open
|
|
1671
|
+
cannot be removed: the holder closes it first and a failed removal is left alone; the file then
|
|
1672
|
+
serves the next run as it is."""
|
|
1673
|
+
|
|
1674
|
+
def __init__(self, lock_path: str) -> None:
|
|
1675
|
+
self.path = lock_path + ".takeover"
|
|
1676
|
+
self.fd: Optional[int] = None
|
|
1677
|
+
|
|
1678
|
+
def acquire(self, wait: float = SECTION_WAIT) -> Optional[str]:
|
|
1679
|
+
"""None when held; "busy" when another run held it all through `wait` seconds;
|
|
1680
|
+
_SectionUnavailable when the OS lock cannot be had here at all."""
|
|
1681
|
+
import time
|
|
1682
|
+
deadline = time.monotonic() + max(0.0, wait)
|
|
1683
|
+
while True:
|
|
1684
|
+
fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o644)
|
|
1685
|
+
try:
|
|
1686
|
+
got = _os_lock(fd)
|
|
1687
|
+
except BaseException:
|
|
1688
|
+
os.close(fd)
|
|
1689
|
+
raise
|
|
1690
|
+
if got:
|
|
1691
|
+
if os.name == "nt" or self._names(fd):
|
|
1692
|
+
self.fd = fd
|
|
1693
|
+
return None
|
|
1694
|
+
os.close(fd) # locked a file whose name was removed meanwhile: start again
|
|
1695
|
+
continue
|
|
1696
|
+
os.close(fd)
|
|
1697
|
+
if time.monotonic() >= deadline:
|
|
1698
|
+
return "busy"
|
|
1699
|
+
time.sleep(0.05)
|
|
1700
|
+
|
|
1701
|
+
def _names(self, fd: int) -> bool:
|
|
1702
|
+
try:
|
|
1703
|
+
mine, there = os.fstat(fd), os.stat(self.path)
|
|
1704
|
+
except FileNotFoundError:
|
|
1705
|
+
return False
|
|
1706
|
+
return (mine.st_dev, mine.st_ino) == (there.st_dev, there.st_ino)
|
|
1707
|
+
|
|
1708
|
+
def release(self) -> None:
|
|
1709
|
+
fd, self.fd = self.fd, None
|
|
1710
|
+
if fd is None:
|
|
1711
|
+
return
|
|
1712
|
+
if os.name != "nt":
|
|
1713
|
+
try:
|
|
1714
|
+
os.remove(self.path) # still locked: whoever opened this file re-checks its name
|
|
1715
|
+
except OSError:
|
|
1716
|
+
pass
|
|
1717
|
+
os.close(fd) # closing releases the lock
|
|
1718
|
+
return
|
|
1719
|
+
try:
|
|
1720
|
+
import msvcrt
|
|
1721
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
1722
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
|
|
1723
|
+
except OSError:
|
|
1724
|
+
pass
|
|
1725
|
+
os.close(fd)
|
|
1726
|
+
try:
|
|
1727
|
+
os.remove(self.path) # fails while another run has it open: it is left to that run
|
|
1728
|
+
except OSError:
|
|
1729
|
+
pass
|
|
1730
|
+
|
|
1731
|
+
|
|
1732
|
+
class _OutputLock:
|
|
1733
|
+
"""Two runs writing the same output at once used to both report `completed` while one of
|
|
1734
|
+
them described the other's file (sweep F1). A lock file next to the output, created with
|
|
1735
|
+
O_EXCL and holding the writer's pid, makes the second run refuse (`kind: input`,
|
|
1736
|
+
`reason: output_locked`, the holder in `details`).
|
|
1737
|
+
|
|
1738
|
+
Stale locks: a lock whose pid is dead is taken over. A lock whose pid is alive is taken over
|
|
1739
|
+
only once its holder's own time limit has passed: the writer sets the lock's mtime to that
|
|
1740
|
+
deadline minus an hour, so "older than an hour" -- the rule every version since 1.x applies,
|
|
1741
|
+
which this keeps compatible in both directions -- means "past the deadline". The deadline is
|
|
1742
|
+
child_limit() from now (4x --timeout + 60 s, the ceiling on everything one run() does under
|
|
1743
|
+
the lock); with --timeout 0 there is none and a live holder is never taken over. Through 2.10
|
|
1744
|
+
the hour ran from the lock's creation, so a legitimate run longer than an hour lost its lock
|
|
1745
|
+
to a second writer. A takeover is recorded (`diagnostics.fallbacks`, stderr, and the audit
|
|
1746
|
+
log); so is running without a lock where none can be created (`diagnostics.warnings`)."""
|
|
1747
|
+
def __init__(self, output: str, on_locked: "Optional[Callable[[str, str, Dict[str, Any]], None]]" = None) -> None:
|
|
1748
|
+
# on_locked(message, hint, details): a caller that must not exit (batch.py's item worker)
|
|
1749
|
+
# raises its own error for a held lock instead of the refusal below
|
|
1750
|
+
self.path: Optional[str] = None
|
|
1751
|
+
self.fd: Optional[int] = None
|
|
1752
|
+
self.output = output
|
|
1753
|
+
self.on_locked = on_locked
|
|
1754
|
+
if output == "-" or output.startswith("pipe:") or output.startswith("-"):
|
|
1755
|
+
return
|
|
1756
|
+
d, base = os.path.split(os.path.abspath(output))
|
|
1757
|
+
self.path = os.path.join(d, f".{base}.ffskill-lock")
|
|
1758
|
+
|
|
1759
|
+
def __enter__(self) -> "_OutputLock":
|
|
1760
|
+
if not self.path:
|
|
1761
|
+
return self
|
|
1762
|
+
try:
|
|
1763
|
+
self.fd = self._create()
|
|
1764
|
+
return self
|
|
1765
|
+
except FileExistsError:
|
|
1766
|
+
pass
|
|
1767
|
+
except OSError as exc:
|
|
1768
|
+
return self._unlocked(exc)
|
|
1769
|
+
holder = self._holder()
|
|
1770
|
+
if holder["stale"]:
|
|
1771
|
+
holder = self._take_over(holder)
|
|
1772
|
+
if holder.get("unlocked"):
|
|
1773
|
+
return self
|
|
1774
|
+
if self.fd is not None:
|
|
1775
|
+
self._record_takeover(holder)
|
|
1776
|
+
return self
|
|
1777
|
+
name = os.path.basename(self.path)[1:-len(".ffskill-lock")]
|
|
1778
|
+
if holder.get("why") == "takeover_unavailable":
|
|
1779
|
+
msg = (f"the lock on {name!r} ({self.path}) is stale ({holder.get('stale_why')}), but it cannot be taken over "
|
|
1780
|
+
f"safely here: this filesystem gives no OS file lock ({holder.get('takeover_error')})")
|
|
1781
|
+
hint = f"if no other run is writing {name!r}, delete {self.path} and run again"
|
|
1782
|
+
else:
|
|
1783
|
+
msg = (f"another run is writing {name!r} right now (lock {self.path}"
|
|
1784
|
+
+ (f", pid {holder['pid']}" if holder.get("pid") else "") + "); wait for it or choose a different --output/-o path")
|
|
1785
|
+
hint = ("wait for that run, or choose another -o path; if pid "
|
|
1786
|
+
f"{holder.get('pid')} is not an ffmpeg-skill run, delete {self.path}")
|
|
1787
|
+
details = dict(lock=self.path, output=os.path.abspath(self.output), **{k: v for k, v in holder.items() if k != "stale"})
|
|
1788
|
+
if self.on_locked:
|
|
1789
|
+
self.on_locked(msg, hint, details)
|
|
1790
|
+
refuse("input", "output_locked", msg, hint=hint, **details)
|
|
1791
|
+
return self
|
|
1792
|
+
|
|
1793
|
+
def _unlocked(self, exc: OSError) -> "_OutputLock":
|
|
1794
|
+
# an unlockable location (a read-only directory surfaces elsewhere): the run goes
|
|
1795
|
+
# on without a lock, and says so -- two runs could now both write this output
|
|
1796
|
+
details = {"lock": self.path, "output": os.path.abspath(self.output), "error": str(exc)}
|
|
1797
|
+
warn(f"could not create the output lock {self.path} ({exc}); running without one, so a second run "
|
|
1798
|
+
"writing the same output at the same time would not be refused", "output_unlocked", **details)
|
|
1799
|
+
audit("output_unlocked", details, default_path=self._audit_default())
|
|
1800
|
+
return self
|
|
1801
|
+
|
|
1802
|
+
def _take_over(self, judged: Dict[str, Any]) -> Dict[str, Any]:
|
|
1803
|
+
"""Take a lock judged stale over inside the takeover section (A186, #465; review of #530):
|
|
1804
|
+
judge it again there, remove it only if it is still stale, and create this run's own lock
|
|
1805
|
+
before leaving, so no other run can judge, remove or create between those steps. Sets
|
|
1806
|
+
self.fd and returns the holder as judged last when this run now holds the lock; otherwise
|
|
1807
|
+
returns why not (held, `takeover_in_progress`, `takeover_unavailable`, `takeover_error`).
|
|
1808
|
+
Returns {"unlocked": True} when the lock cannot be created at all (the run goes on
|
|
1809
|
+
without one, as __enter__ says)."""
|
|
1810
|
+
section = _TakeoverSection(self.path)
|
|
1811
|
+
try:
|
|
1812
|
+
busy = section.acquire()
|
|
1813
|
+
except OSError as exc:
|
|
1814
|
+
# no OS lock on this filesystem: nothing safe to fall back on, so the stale lock is
|
|
1815
|
+
# left for a person to remove (the refusal says so)
|
|
1816
|
+
return dict(judged, stale=False, why="takeover_unavailable", stale_why=judged.get("why"),
|
|
1817
|
+
takeover_error=str(exc))
|
|
1818
|
+
if busy:
|
|
1819
|
+
return dict(judged, stale=False, why="takeover_in_progress")
|
|
1820
|
+
try:
|
|
1821
|
+
now = judged
|
|
1822
|
+
if os.path.lexists(self.path):
|
|
1823
|
+
now = self._holder()
|
|
1824
|
+
if not now["stale"]:
|
|
1825
|
+
return now # taken over, or written again, since our look
|
|
1826
|
+
try:
|
|
1827
|
+
os.remove(self.path)
|
|
1828
|
+
except FileNotFoundError:
|
|
1829
|
+
pass
|
|
1830
|
+
except OSError as exc:
|
|
1831
|
+
# Windows will not delete a file another process holds open, and a live
|
|
1832
|
+
# holder keeps its lock open until it finishes: the takeover fails and
|
|
1833
|
+
# the run is refused, with the reason, instead of passing silently
|
|
1834
|
+
return dict(now, stale=False, takeover_error=str(exc))
|
|
1835
|
+
try:
|
|
1836
|
+
self.fd = self._create()
|
|
1837
|
+
except FileExistsError:
|
|
1838
|
+
return self._holder() # a run that found no lock created one: it holds it
|
|
1839
|
+
except OSError as exc:
|
|
1840
|
+
self._unlocked(exc)
|
|
1841
|
+
return {"unlocked": True}
|
|
1842
|
+
return now
|
|
1843
|
+
finally:
|
|
1844
|
+
section.release()
|
|
1845
|
+
|
|
1846
|
+
def _audit_default(self) -> Optional[str]:
|
|
1847
|
+
if not self.path:
|
|
1848
|
+
return None
|
|
1849
|
+
d, base = os.path.split(os.path.abspath(self.output))
|
|
1850
|
+
return os.path.join(d, f".{base}.ffskill-audit.jsonl")
|
|
1851
|
+
|
|
1852
|
+
def _create(self) -> int:
|
|
1853
|
+
"""Create the lock, already holding this run's pid and dated with its deadline, and
|
|
1854
|
+
return an open descriptor on it; FileExistsError when another run's lock is there.
|
|
1855
|
+
|
|
1856
|
+
The pid and the date are written to a file of this run's own first, which is then
|
|
1857
|
+
hard-linked to the lock's name: the link is atomic and fails when the name exists, as
|
|
1858
|
+
O_EXCL does, so no other run ever reads this lock empty (an empty lock reads as
|
|
1859
|
+
`unreadable`, which is stale, and was open to a takeover between the create and the
|
|
1860
|
+
write) or undated. Where a hard link cannot be made (a FAT volume, some network shares)
|
|
1861
|
+
the lock is created with O_EXCL and written at once, as before."""
|
|
1862
|
+
import uuid
|
|
1863
|
+
tmp = f"{self.path}.{os.getpid()}-{uuid.uuid4().hex[:12]}.new"
|
|
1864
|
+
try:
|
|
1865
|
+
fd = os.open(tmp, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
|
|
1866
|
+
except OSError:
|
|
1867
|
+
return self._create_in_place()
|
|
1868
|
+
try:
|
|
1869
|
+
try:
|
|
1870
|
+
os.write(fd, str(os.getpid()).encode())
|
|
1871
|
+
finally:
|
|
1872
|
+
os.close(fd) # closed before the link: Windows links and removes only a closed file
|
|
1873
|
+
self._set_deadline(tmp)
|
|
1874
|
+
try:
|
|
1875
|
+
os.link(tmp, self.path)
|
|
1876
|
+
except FileExistsError:
|
|
1877
|
+
raise
|
|
1878
|
+
except (OSError, NotImplementedError, AttributeError):
|
|
1879
|
+
return self._create_in_place()
|
|
1880
|
+
return os.open(self.path, os.O_WRONLY)
|
|
1881
|
+
finally:
|
|
1882
|
+
try:
|
|
1883
|
+
os.remove(tmp)
|
|
1884
|
+
except OSError:
|
|
1885
|
+
pass
|
|
1886
|
+
|
|
1887
|
+
def _create_in_place(self) -> int:
|
|
1888
|
+
fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
|
|
1889
|
+
os.write(fd, str(os.getpid()).encode())
|
|
1890
|
+
self._set_deadline(self.path)
|
|
1891
|
+
return fd
|
|
1892
|
+
|
|
1893
|
+
def _set_deadline(self, path: Optional[str] = None) -> None:
|
|
1894
|
+
import time
|
|
1895
|
+
path = path or self.path
|
|
1896
|
+
limit = child_limit()
|
|
1897
|
+
deadline = time.time() + (limit if limit else LOCK_UNLIMITED)
|
|
1898
|
+
try:
|
|
1899
|
+
os.utime(path, (deadline - LOCK_HOUR, deadline - LOCK_HOUR))
|
|
1900
|
+
except (OSError, OverflowError, ValueError) as exc:
|
|
1901
|
+
warn(f"could not date the output lock {self.path} ({exc}); another run may take it over an hour from now",
|
|
1902
|
+
"lock_deadline_unset", lock=self.path, error=str(exc))
|
|
1903
|
+
|
|
1904
|
+
def _holder(self) -> Dict[str, Any]:
|
|
1905
|
+
"""Who holds the lock and whether it is stale: {pid, pid_alive, deadline (UTC, the
|
|
1906
|
+
mtime plus an hour), why: pid_dead | past_deadline | unreadable | held, stale}.
|
|
1907
|
+
_take_over() adds why `takeover_in_progress` (another run is in the takeover section) and
|
|
1908
|
+
`takeover_unavailable` (no OS file lock here)."""
|
|
1909
|
+
import datetime
|
|
1910
|
+
import time
|
|
1911
|
+
out: Dict[str, Any] = {"pid": None, "pid_alive": None, "deadline": None, "why": "unreadable", "stale": True}
|
|
1912
|
+
try:
|
|
1913
|
+
with open(self.path, encoding="utf-8", errors="replace") as f:
|
|
1914
|
+
text = f.read().strip()
|
|
1915
|
+
deadline = os.path.getmtime(self.path) + LOCK_HOUR
|
|
1916
|
+
pid = int(text or "0")
|
|
1917
|
+
except (OSError, ValueError):
|
|
1918
|
+
return out
|
|
1919
|
+
out["deadline"] = datetime.datetime.fromtimestamp(deadline, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
1920
|
+
out["pid"] = pid if pid > 0 else None
|
|
1921
|
+
if pid > 0 and _pid_dead(pid):
|
|
1922
|
+
out.update(pid_alive=False, why="pid_dead")
|
|
1923
|
+
return out
|
|
1924
|
+
out["pid_alive"] = pid > 0 or None
|
|
1925
|
+
if time.time() > deadline:
|
|
1926
|
+
out["why"] = "past_deadline"
|
|
1927
|
+
return out
|
|
1928
|
+
out.update(why="held", stale=False)
|
|
1929
|
+
return out
|
|
1930
|
+
|
|
1931
|
+
def _record_takeover(self, holder: Dict[str, Any]) -> None:
|
|
1932
|
+
details = {"lock": self.path, "output": os.path.abspath(self.output),
|
|
1933
|
+
**{k: v for k, v in holder.items() if k != "stale"}}
|
|
1934
|
+
why = {"pid_dead": f"its pid {holder.get('pid')} no longer runs",
|
|
1935
|
+
"past_deadline": f"its holder (pid {holder.get('pid')}, still running) is past its own time limit",
|
|
1936
|
+
}.get(holder.get("why") or "", "it could not be read")
|
|
1937
|
+
details["audit_log"] = audit("lock_takeover", details, default_path=self._audit_default())
|
|
1938
|
+
record_fallback(f"took over the stale output lock {self.path}: {why}", "stale_lock_taken_over", **details)
|
|
1939
|
+
|
|
1940
|
+
def __exit__(self, *exc: Any) -> None:
|
|
1941
|
+
"""Remove this run's own lock, inside the takeover section: a holder past its deadline
|
|
1942
|
+
whose lock another run is taking over, or has taken over, never removes that run's lock
|
|
1943
|
+
by its name. On POSIX the lock at the name is removed only when it is still this run's
|
|
1944
|
+
file; on Windows no other run can remove a lock this run has open, so the name is still
|
|
1945
|
+
ours. When the section is busy (a takeover of this lock is under way) the lock is left to
|
|
1946
|
+
that run; when there is no OS lock here, the same file check alone decides."""
|
|
1947
|
+
fd, self.fd = self.fd, None
|
|
1948
|
+
if fd is None or not self.path:
|
|
1949
|
+
if fd is not None:
|
|
1950
|
+
os.close(fd)
|
|
1951
|
+
return
|
|
1952
|
+
section = _TakeoverSection(self.path)
|
|
1953
|
+
try:
|
|
1954
|
+
busy = section.acquire()
|
|
1955
|
+
except OSError:
|
|
1956
|
+
busy = None # no OS lock: the file check below alone
|
|
1957
|
+
try:
|
|
1958
|
+
if busy == "busy":
|
|
1959
|
+
return
|
|
1960
|
+
if os.name == "nt":
|
|
1961
|
+
os.close(fd)
|
|
1962
|
+
fd = None
|
|
1963
|
+
try:
|
|
1964
|
+
os.remove(self.path)
|
|
1965
|
+
except OSError:
|
|
1966
|
+
pass
|
|
1967
|
+
return
|
|
1968
|
+
try:
|
|
1969
|
+
mine, there = os.fstat(fd), os.stat(self.path)
|
|
1970
|
+
if (mine.st_dev, mine.st_ino) == (there.st_dev, there.st_ino):
|
|
1971
|
+
os.remove(self.path)
|
|
1972
|
+
except OSError:
|
|
1973
|
+
pass
|
|
1974
|
+
finally:
|
|
1975
|
+
if fd is not None:
|
|
1976
|
+
try:
|
|
1977
|
+
os.close(fd)
|
|
1978
|
+
except OSError:
|
|
1979
|
+
pass
|
|
1980
|
+
section.release()
|
|
1981
|
+
|
|
1982
|
+
|
|
1983
|
+
def _odd_dimension_retry(cmd: List[str], stderr: str) -> Optional[List[str]]:
|
|
1984
|
+
"""An odd-sized source (641x359 screen captures, some 4:4:4 masters) fails every yuv420p
|
|
1985
|
+
encode with "width/height not divisible by 2" (sweep F8, 15 tools). Return the same command
|
|
1986
|
+
with an even-dimension scale appended to its -vf chain (or a new -vf when the command had
|
|
1987
|
+
none); None when the failure is something else or the graph is a -filter_complex the
|
|
1988
|
+
caller has to fix itself.
|
|
1989
|
+
|
|
1990
|
+
Appended, not prepended: what the encoder refuses is the frame the chain hands it, and a
|
|
1991
|
+
chain can make an even frame odd again (squaring non-square pixels to 636x1401, a conversion
|
|
1992
|
+
that restores the source's own size). Through 3.2.3 the scale went first, so caption.py on an
|
|
1993
|
+
odd-sized clip retried and failed the same way (#438)."""
|
|
1994
|
+
if "not divisible by 2" not in stderr or EVEN_SCALE in cmd or any(EVEN_SCALE in a for a in cmd):
|
|
1995
|
+
return None
|
|
1996
|
+
if "-filter_complex" in cmd:
|
|
1997
|
+
return None
|
|
1998
|
+
new = list(cmd)
|
|
1999
|
+
if "-vf" in new:
|
|
2000
|
+
i = new.index("-vf") + 1
|
|
2001
|
+
new[i] = new[i] + "," + EVEN_SCALE
|
|
2002
|
+
return new
|
|
2003
|
+
if "-c:v" in new and new[new.index("-c:v") + 1] == "copy":
|
|
2004
|
+
return None
|
|
2005
|
+
return new[:-1] + ["-vf", EVEN_SCALE, new[-1]]
|
|
2006
|
+
|
|
2007
|
+
|
|
2008
|
+
def _check_existing_output(cmd: Sequence[str]) -> None:
|
|
2009
|
+
"""An output path that already exists is someone's file: a previous result, a source the
|
|
2010
|
+
agent mis-named, a deliverable from another run. ffmpeg's -y (which every command carries so
|
|
2011
|
+
a run never blocks on a y/N prompt) would replace it without a word. Since 2.0 it is refused
|
|
2012
|
+
(kind: input, before anything runs, dry runs included) unless --overwrite gives explicit
|
|
2013
|
+
consent; 1.x only warned, and FFMPEG_SKILL_NO_OVERWRITE=1 was the opt-in to this. Paths this
|
|
2014
|
+
process wrote itself (a two-pass tool, a copy-then-re-encode fallback) are never in question."""
|
|
2015
|
+
output = cmd[-1]
|
|
2016
|
+
if output in ("-",) or output.startswith("pipe:") or output.startswith("-"):
|
|
2017
|
+
return
|
|
2018
|
+
refuse_existing_outputs([output])
|
|
2019
|
+
|
|
2020
|
+
|
|
2021
|
+
def guard_sidecar(path: str, *inputs: str, siblings: Sequence[str] = ()) -> None:
|
|
2022
|
+
"""The output guards for a file a tool writes itself rather than through ffmpeg (an EDL, a
|
|
2023
|
+
chapter list, a project file): not a URL or an option-shaped name, its directory exists and is
|
|
2024
|
+
writable, not one of the run's inputs, not another file the same run writes (`siblings`), and
|
|
2025
|
+
not an existing file unless --overwrite. Called before the first file is written, so a dry run
|
|
2026
|
+
predicts the same refusal."""
|
|
2027
|
+
if not path:
|
|
2028
|
+
return
|
|
2029
|
+
for other in siblings:
|
|
2030
|
+
if other and same_file(other, path):
|
|
2031
|
+
refuse("input", "output_path_taken",
|
|
2032
|
+
f"{path!r} is also another file this run writes ({other!r}); give each its own path",
|
|
2033
|
+
output=path, other=other)
|
|
2034
|
+
_check_output_path([path])
|
|
2035
|
+
refuse_output_is_input(path, *[p for p in inputs if p])
|
|
2036
|
+
refuse_existing_outputs([path])
|
|
2037
|
+
|
|
2038
|
+
|
|
2039
|
+
def refuse_existing_outputs(paths: Sequence[str]) -> None:
|
|
2040
|
+
"""_check_existing_output() for every file a run will write, named together, before the
|
|
2041
|
+
first of them is written. A tool whose outputs are not all ffmpeg's last argument (caption.py's
|
|
2042
|
+
.srt/.ass sidecars) calls this up front so a hand-edited sidecar is refused like the video
|
|
2043
|
+
is, and a dry run predicts the same refusal."""
|
|
2044
|
+
existing: List[str] = []
|
|
2045
|
+
facts: List[Dict[str, Any]] = []
|
|
2046
|
+
for output in paths:
|
|
2047
|
+
if not output:
|
|
2048
|
+
continue
|
|
2049
|
+
try:
|
|
2050
|
+
exists = os.path.isfile(output)
|
|
2051
|
+
real = os.path.realpath(output)
|
|
2052
|
+
except OSError:
|
|
2053
|
+
continue
|
|
2054
|
+
# what the decision below is about: compared again where the file is replaced
|
|
2055
|
+
# (refuse_changed_output), so one put there during the run is not replaced unasked
|
|
2056
|
+
_record_checked(output, _checked_state(output) if exists else None)
|
|
2057
|
+
if not exists or real in STATE.written:
|
|
2058
|
+
continue
|
|
2059
|
+
size = mtime_ns = None
|
|
2060
|
+
try:
|
|
2061
|
+
st = os.stat(output)
|
|
2062
|
+
STATE.preexisting[real] = (st.st_size, st.st_mtime_ns)
|
|
2063
|
+
size, mtime_ns = st.st_size, st.st_mtime_ns
|
|
2064
|
+
except OSError:
|
|
2065
|
+
pass
|
|
2066
|
+
if output not in existing:
|
|
2067
|
+
existing.append(output)
|
|
2068
|
+
facts.append({"path": output, "resolved": real, "size": size, "mtime_ns": mtime_ns})
|
|
2069
|
+
# a file batch.py delivered on an earlier --watch pass, still exactly as it left it, is that
|
|
2070
|
+
# run's own: replaced without --overwrite, per path (anything else existing is still refused)
|
|
2071
|
+
if existing and not STATE.overwrite:
|
|
2072
|
+
keep = [i for i, p in enumerate(existing) if not owned_replaceable(p)]
|
|
2073
|
+
existing, facts = [existing[i] for i in keep], [facts[i] for i in keep]
|
|
2074
|
+
if not existing or STATE.overwrite:
|
|
2075
|
+
report_owned_targets(paths)
|
|
2076
|
+
return
|
|
2077
|
+
hint = "pass --overwrite, or choose another -o path"
|
|
2078
|
+
if len(existing) == 1:
|
|
2079
|
+
refuse("input", "output_exists",
|
|
2080
|
+
f"refusing to overwrite existing output {existing[0]!r}: pass --overwrite to replace it, or choose another -o path",
|
|
2081
|
+
hint=hint, outputs=facts)
|
|
2082
|
+
refuse("input", "output_exists", "refusing to overwrite existing outputs " + ", ".join(repr(p) for p in existing)
|
|
2083
|
+
+ ": pass --overwrite to replace them, or choose another -o path", hint=hint, outputs=facts)
|
|
2084
|
+
|
|
2085
|
+
|
|
2086
|
+
def _remember_output(cmd: Sequence[str]) -> None:
|
|
2087
|
+
output = cmd[-1]
|
|
2088
|
+
if output == "-" or output.startswith("pipe:") or output.startswith("-"):
|
|
2089
|
+
return
|
|
2090
|
+
_remember_identity(output)
|
|
2091
|
+
report_committed(output)
|
|
2092
|
+
|
|
2093
|
+
|
|
2094
|
+
def _checked_key(path: str) -> str:
|
|
2095
|
+
"""The place a check is about: `path`'s directory resolved, its last component as named, so a
|
|
2096
|
+
symlink created at an absent target since the check is still that target (#480 review)."""
|
|
2097
|
+
full = os.path.abspath(path)
|
|
2098
|
+
return os.path.join(os.path.realpath(os.path.dirname(full)), os.path.basename(full))
|
|
2099
|
+
|
|
2100
|
+
|
|
2101
|
+
def _parent(path: str) -> str:
|
|
2102
|
+
return os.path.realpath(os.path.dirname(os.path.abspath(path)))
|
|
2103
|
+
|
|
2104
|
+
|
|
2105
|
+
def _checked_state(path: str) -> "Optional[Tuple[Optional[Dict[str, int]], bool]]":
|
|
2106
|
+
"""What is at `path` now: (owned_identity, is a symlink), or None when nothing is there."""
|
|
2107
|
+
if not os.path.lexists(path):
|
|
2108
|
+
return None
|
|
2109
|
+
return (owned_identity(path), os.path.islink(path))
|
|
2110
|
+
|
|
2111
|
+
|
|
2112
|
+
def _record_checked(path: str, state: Any) -> None:
|
|
2113
|
+
"""Record what a check (or this run's own write) found at `path`, with the directory the path
|
|
2114
|
+
resolved to then, under the resolved place and under the path as named: a directory symlink
|
|
2115
|
+
switched since is then found by the name and refused, not looked up as a place never checked."""
|
|
2116
|
+
entry = (_parent(path), state)
|
|
2117
|
+
key = _checked_key(path)
|
|
2118
|
+
STATE.checked[key] = entry
|
|
2119
|
+
STATE.checked[os.path.abspath(path)] = entry
|
|
2120
|
+
# the same file reached by another spelling of its path (a write through the resolved name
|
|
2121
|
+
# after a check through a link) is the same record: a later replace through either matches
|
|
2122
|
+
# -- only a record made in the same directory: one whose link has been switched since keeps
|
|
2123
|
+
# what it saw, so the replace through it is still refused
|
|
2124
|
+
for named in [k for k in STATE.checked if k != key]:
|
|
2125
|
+
try:
|
|
2126
|
+
if _checked_key(named) == key and STATE.checked[named][0] == entry[0]:
|
|
2127
|
+
STATE.checked[named] = entry
|
|
2128
|
+
except OSError:
|
|
2129
|
+
pass
|
|
2130
|
+
|
|
2131
|
+
|
|
2132
|
+
def _remember_identity(path: str) -> None:
|
|
2133
|
+
"""Count `path` as this run's own and record the identity this run left it with, which a
|
|
2134
|
+
later replace of it compares (refuse_changed_output)."""
|
|
2135
|
+
try:
|
|
2136
|
+
real = os.path.realpath(path)
|
|
2137
|
+
STATE.written.add(real)
|
|
2138
|
+
except OSError:
|
|
2139
|
+
return
|
|
2140
|
+
_record_checked(path, _checked_state(path))
|
|
2141
|
+
|
|
2142
|
+
|
|
2143
|
+
def refuse_changed_output(path: str, cleanup: "Optional[Callable[[], None]]" = None) -> None:
|
|
2144
|
+
"""Refuse to replace `path` when it is no longer the file its output check decided about.
|
|
2145
|
+
|
|
2146
|
+
refuse_existing_outputs() decides before the encode whether an existing target may be
|
|
2147
|
+
replaced (--overwrite, this run's own file, batch.py's own delivery) and records the
|
|
2148
|
+
target's identity (owned_identity(), None when absent); _remember_identity() records it again
|
|
2149
|
+
when this run writes it. Called under the output's lock just before the replace: a file
|
|
2150
|
+
another process put there meanwhile -- a different file at an existing target, or one at a
|
|
2151
|
+
target that was absent -- is refused (`kind: input`, `reason: output_exists`) and `cleanup`
|
|
2152
|
+
removes the new output's temp, unless --overwrite gave consent to replace whatever is at the
|
|
2153
|
+
path (as batch.py's deliver() does). A path with no recorded check is left alone."""
|
|
2154
|
+
if STATE.overwrite or not path or path == "-" or path.startswith("pipe:") or path.startswith("-"):
|
|
2155
|
+
return
|
|
2156
|
+
try:
|
|
2157
|
+
key, named, real = _checked_key(path), os.path.abspath(path), os.path.realpath(path)
|
|
2158
|
+
# the name first: a resolved place another path also reached says nothing about this one
|
|
2159
|
+
recorded = STATE.checked.get(named) or STATE.checked.get(key)
|
|
2160
|
+
if recorded is None:
|
|
2161
|
+
return
|
|
2162
|
+
(parent_then, expected), parent_now, now = recorded, _parent(path), _checked_state(path)
|
|
2163
|
+
except OSError:
|
|
2164
|
+
return
|
|
2165
|
+
if now == expected and parent_now == parent_then:
|
|
2166
|
+
return
|
|
2167
|
+
if cleanup:
|
|
2168
|
+
cleanup()
|
|
2169
|
+
if parent_now != parent_then:
|
|
2170
|
+
why = (f"is now in another directory ({parent_now!r}, checked in {parent_then!r}): a directory "
|
|
2171
|
+
"link on its path was changed during the run")
|
|
2172
|
+
elif expected is None:
|
|
2173
|
+
why = "did not exist when the run checked it and another process created it during the run"
|
|
2174
|
+
elif now is None:
|
|
2175
|
+
why = "was removed or replaced by something that is not a regular file during the run"
|
|
2176
|
+
else:
|
|
2177
|
+
why = "changed during the run (another process wrote or replaced it after the output check)"
|
|
2178
|
+
refuse("input", "output_exists",
|
|
2179
|
+
f"refusing to replace {path!r}: it {why}; the new output was not put there. Pass --overwrite to "
|
|
2180
|
+
"replace it anyway, or choose another -o path",
|
|
2181
|
+
hint="pass --overwrite, or choose another -o path",
|
|
2182
|
+
outputs=[{"path": path, "resolved": real, "changed_during_run": True,
|
|
2183
|
+
"expected": expected, "found": now}])
|
|
2184
|
+
|
|
2185
|
+
|
|
2186
|
+
def _remove_quietly(path: Optional[str]) -> None:
|
|
2187
|
+
if path:
|
|
2188
|
+
try:
|
|
2189
|
+
os.remove(path)
|
|
2190
|
+
except OSError:
|
|
2191
|
+
pass
|
|
2192
|
+
|
|
2193
|
+
|
|
2194
|
+
def replace_checked(tmp: str, final: str) -> None:
|
|
2195
|
+
"""os.replace(tmp, final) for a file a tool writes itself (a time map, a normalised export):
|
|
2196
|
+
under `final`'s output lock, after refuse_changed_output(), which removes `tmp` when it
|
|
2197
|
+
refuses."""
|
|
2198
|
+
replace_checked_together([(tmp, final)])
|
|
2199
|
+
|
|
2200
|
+
|
|
2201
|
+
def replace_checked_together(pairs: "Sequence[Tuple[str, str]]") -> None:
|
|
2202
|
+
"""Replace each (tmp, final) only once every final has passed refuse_changed_output(), all
|
|
2203
|
+
under their output locks: files that belong together (a fill and its key). A file already at a
|
|
2204
|
+
final is moved aside first and put back if a later replace fails, so a failed pair leaves
|
|
2205
|
+
what was there. Every tmp is removed on a refusal, a refused lock or a failed replace (#480
|
|
2206
|
+
review)."""
|
|
2207
|
+
def cleanup() -> None:
|
|
2208
|
+
for tmp, _final in pairs:
|
|
2209
|
+
_remove_quietly(tmp)
|
|
2210
|
+
aside: List[Tuple[str, Optional[str]]] = [] # (final, where its earlier file went, or None)
|
|
2211
|
+
try:
|
|
2212
|
+
with contextlib.ExitStack() as stack:
|
|
2213
|
+
for final in sorted({final for _tmp, final in pairs}):
|
|
2214
|
+
stack.enter_context(_OutputLock(final))
|
|
2215
|
+
for _tmp, final in pairs:
|
|
2216
|
+
refuse_changed_output(final, cleanup)
|
|
2217
|
+
try:
|
|
2218
|
+
for tmp, final in pairs:
|
|
2219
|
+
kept = None
|
|
2220
|
+
if len(pairs) > 1 and os.path.lexists(final):
|
|
2221
|
+
d, base = os.path.split(final)
|
|
2222
|
+
stem, ext = os.path.splitext(base)
|
|
2223
|
+
kept = reserve_sibling(d, stem, ext, "keep")
|
|
2224
|
+
os.replace(final, kept)
|
|
2225
|
+
try:
|
|
2226
|
+
os.replace(tmp, final)
|
|
2227
|
+
except BaseException:
|
|
2228
|
+
if kept:
|
|
2229
|
+
os.replace(kept, final)
|
|
2230
|
+
raise
|
|
2231
|
+
aside.append((final, kept)) # replaced: undone below if a later one fails
|
|
2232
|
+
except BaseException:
|
|
2233
|
+
for final, kept in reversed(aside):
|
|
2234
|
+
if kept:
|
|
2235
|
+
try:
|
|
2236
|
+
os.replace(kept, final)
|
|
2237
|
+
except OSError:
|
|
2238
|
+
pass
|
|
2239
|
+
elif os.path.exists(final):
|
|
2240
|
+
_remove_quietly(final)
|
|
2241
|
+
raise
|
|
2242
|
+
for _final, kept in aside:
|
|
2243
|
+
_remove_quietly(kept)
|
|
2244
|
+
except BaseException:
|
|
2245
|
+
cleanup()
|
|
2246
|
+
raise
|
|
2247
|
+
|
|
2248
|
+
|
|
2249
|
+
# set only by batch.py for the steps it runs: the path of a JSON file {"replaceable": {real path:
|
|
2250
|
+
# owned_identity()}, "report": directory}. "replaceable" is every file that batch process
|
|
2251
|
+
# delivered (a --watch loop's earlier passes) as it left it; a step replaces one of those without
|
|
2252
|
+
# --overwrite while it is still that file, and nothing else. Each process that passes the output
|
|
2253
|
+
# check writes <report>/<pid>.json: {"targets": the paths it was allowed to write, "committed":
|
|
2254
|
+
# {real path: owned_identity()} taken when each of them was written (report_committed), so batch
|
|
2255
|
+
# learns the side files (an .srt beside the video) it delivered as they were when written, not as
|
|
2256
|
+
# they are when the item ends -- an edit made while a later step ran is not adopted.
|
|
2257
|
+
OWNED_ENV = "_FFMPEG_SKILL_OWNED"
|
|
2258
|
+
_OWNED_CACHE: Dict[str, Dict[str, Any]] = {}
|
|
2259
|
+
_OWNED_TARGETS: Dict[str, List[str]] = {}
|
|
2260
|
+
_OWNED_COMMITTED: Dict[str, Dict[str, Dict[str, int]]] = {}
|
|
2261
|
+
|
|
2262
|
+
|
|
2263
|
+
def owned_identity(path: str) -> "Optional[Dict[str, int]]":
|
|
2264
|
+
"""{size, mtime_ns, ino, dev} of a regular file: what tells the file batch.py delivered from
|
|
2265
|
+
one put at the same path since (a replacement with the same size and mtime is a new inode).
|
|
2266
|
+
None when the path is not a regular file."""
|
|
2267
|
+
try:
|
|
2268
|
+
st = os.stat(path)
|
|
2269
|
+
except OSError:
|
|
2270
|
+
return None
|
|
2271
|
+
if not os.path.isfile(path):
|
|
2272
|
+
return None
|
|
2273
|
+
return {"size": st.st_size, "mtime_ns": st.st_mtime_ns, "ino": st.st_ino, "dev": st.st_dev}
|
|
2274
|
+
|
|
2275
|
+
|
|
2276
|
+
def _owned_config(config: Optional[str] = None) -> Dict[str, Any]:
|
|
2277
|
+
config = config if config is not None else os.environ.get(OWNED_ENV, "")
|
|
2278
|
+
if not config:
|
|
2279
|
+
return {}
|
|
2280
|
+
if config not in _OWNED_CACHE:
|
|
2281
|
+
try:
|
|
2282
|
+
with open(config, encoding="utf-8") as fh:
|
|
2283
|
+
doc = json.load(fh)
|
|
2284
|
+
except (OSError, ValueError):
|
|
2285
|
+
doc = {}
|
|
2286
|
+
_OWNED_CACHE[config] = doc if isinstance(doc, dict) else {}
|
|
2287
|
+
return _OWNED_CACHE[config]
|
|
2288
|
+
|
|
2289
|
+
|
|
2290
|
+
def owned_replaceable(path: str, config: Optional[str] = None) -> bool:
|
|
2291
|
+
"""Whether `path` is a file the batch.py process running this step delivered, still with the
|
|
2292
|
+
identity it had then (checked now, at the output check, not when the step was planned)."""
|
|
2293
|
+
replaceable = _owned_config(config).get("replaceable")
|
|
2294
|
+
if not isinstance(replaceable, dict):
|
|
2295
|
+
return False
|
|
2296
|
+
try:
|
|
2297
|
+
real = os.path.realpath(path)
|
|
2298
|
+
except OSError:
|
|
2299
|
+
return False
|
|
2300
|
+
expected = replaceable.get(real)
|
|
2301
|
+
return isinstance(expected, dict) and owned_identity(real) == expected
|
|
2302
|
+
|
|
2303
|
+
|
|
2304
|
+
def report_owned_targets(paths: Sequence[Optional[str]], config: Optional[str] = None) -> None:
|
|
2305
|
+
"""Under batch.py: record paths this process passed the output check for, in the report
|
|
2306
|
+
directory its config names. Nothing outside batch.py; a report that cannot be written only
|
|
2307
|
+
means the next pass refuses that file as someone else's."""
|
|
2308
|
+
config = config if config is not None else os.environ.get(OWNED_ENV, "")
|
|
2309
|
+
report = _owned_config(config).get("report")
|
|
2310
|
+
if not isinstance(report, str) or not report:
|
|
2311
|
+
return
|
|
2312
|
+
targets = _OWNED_TARGETS.setdefault(config, [])
|
|
2313
|
+
for p in paths:
|
|
2314
|
+
if p:
|
|
2315
|
+
try:
|
|
2316
|
+
real = os.path.realpath(p)
|
|
2317
|
+
except OSError:
|
|
2318
|
+
continue
|
|
2319
|
+
if real not in targets:
|
|
2320
|
+
targets.append(real)
|
|
2321
|
+
_write_owned_report(config, report)
|
|
2322
|
+
|
|
2323
|
+
|
|
2324
|
+
def _write_owned_report(config: str, report: str) -> None:
|
|
2325
|
+
doc = {"targets": _OWNED_TARGETS.get(config, []), "committed": _OWNED_COMMITTED.get(config, {})}
|
|
2326
|
+
try:
|
|
2327
|
+
with open(os.path.join(report, f"{os.getpid()}.json"), "w", encoding="utf-8") as fh:
|
|
2328
|
+
json.dump(doc, fh)
|
|
2329
|
+
except OSError:
|
|
2330
|
+
pass
|
|
2331
|
+
|
|
2332
|
+
|
|
2333
|
+
def report_committed(path: Optional[str], config: Optional[str] = None) -> None:
|
|
2334
|
+
"""Under batch.py: record the identity `path` has right now, just after this process wrote it,
|
|
2335
|
+
if it passed this process's output check. What batch later lets a step replace is that file
|
|
2336
|
+
as it was written; one edited afterwards no longer matches and is refused."""
|
|
2337
|
+
config = config if config is not None else os.environ.get(OWNED_ENV, "")
|
|
2338
|
+
report = _owned_config(config).get("report")
|
|
2339
|
+
if not path or not isinstance(report, str) or not report:
|
|
2340
|
+
return
|
|
2341
|
+
try:
|
|
2342
|
+
real = os.path.realpath(path)
|
|
2343
|
+
except OSError:
|
|
2344
|
+
return
|
|
2345
|
+
if real not in _OWNED_TARGETS.get(config, []):
|
|
2346
|
+
return
|
|
2347
|
+
ident = owned_identity(real)
|
|
2348
|
+
if ident:
|
|
2349
|
+
_OWNED_COMMITTED.setdefault(config, {})[real] = ident
|
|
2350
|
+
_write_owned_report(config, report)
|
|
2351
|
+
|
|
2352
|
+
|
|
2353
|
+
def remember_written(*paths: Optional[str]) -> None:
|
|
2354
|
+
"""Count files a child tool of this run wrote (render.py's stages, batch.py's steps) as this
|
|
2355
|
+
run's own, as run() counts its ffmpeg outputs: a later stage that replaces one is not refused
|
|
2356
|
+
as replacing someone else's file (#415)."""
|
|
2357
|
+
for path in paths:
|
|
2358
|
+
if path and os.path.isfile(path):
|
|
2359
|
+
_remember_identity(path)
|
|
2360
|
+
report_committed(path)
|
|
2361
|
+
|
|
2362
|
+
|
|
2363
|
+
def _timed_out(cmd: Sequence[str], seconds: float) -> "None":
|
|
2364
|
+
_cleanup_partial_output(cmd)
|
|
2365
|
+
if _is_ffmpeg(cmd) or seconds < PROBE_TIMEOUT:
|
|
2366
|
+
advice = "Raise --timeout (or FFMPEG_SKILL_TIMEOUT) if the job is genuinely that long, or check the input for a stall"
|
|
2367
|
+
else:
|
|
2368
|
+
# a probe's own ceiling, which a higher --timeout does not raise: a read this long is a stall (#415)
|
|
2369
|
+
advice = (f"A probe is limited to {PROBE_TIMEOUT:g} s whatever --timeout says, so this is a stall, not a long "
|
|
2370
|
+
"job: check that the input is readable (a network share, a file still being written)")
|
|
2371
|
+
die(f"{os.path.basename(cmd[0])} exceeded the {seconds:g} s time limit and was killed; {kept_clause()}. {advice}",
|
|
2372
|
+
code=124, kind="timeout", **_kept_fields())
|
|
2373
|
+
|
|
2374
|
+
|
|
2375
|
+
def _stage_existing_output(cmd: Sequence[str]) -> Tuple[List[str], Optional[str], Optional[str]]:
|
|
2376
|
+
"""When the output path already holds someone's file, run ffmpeg against a hidden sibling
|
|
2377
|
+
temp path and move it over the original only on success.
|
|
2378
|
+
|
|
2379
|
+
ffmpeg's -y truncates the output the moment it opens it, and *when* it opens it depends on
|
|
2380
|
+
the version: 6.1+ initialises the filter graph first (a bad LUT fails before the file is
|
|
2381
|
+
touched), 5.x opens the output during option parsing, before any filter runs, so the same
|
|
2382
|
+
bad LUT leaves a 0-byte file where the deliverable was. No amount of post-failure cleanup
|
|
2383
|
+
can undo that; the only way to keep an existing file safe across a failed run is for ffmpeg
|
|
2384
|
+
never to write to it. Same directory, same extension (the muxer is chosen by it), hidden
|
|
2385
|
+
name, so nothing else changes for the encoder. Returns (command to execute, final path,
|
|
2386
|
+
temp path); (cmd, None, None) when no staging is needed."""
|
|
2387
|
+
output = cmd[-1]
|
|
2388
|
+
if output == "-" or output.startswith("pipe:") or output.startswith("-"):
|
|
2389
|
+
return list(cmd), None, None
|
|
2390
|
+
try:
|
|
2391
|
+
if not os.path.isfile(output) or os.path.realpath(output) in STATE.written:
|
|
2392
|
+
return list(cmd), None, None
|
|
2393
|
+
except OSError:
|
|
2394
|
+
return list(cmd), None, None
|
|
2395
|
+
d, base = os.path.split(output)
|
|
2396
|
+
stem, ext = os.path.splitext(base)
|
|
2397
|
+
tmp = reserve_sibling(d, stem, ext)
|
|
2398
|
+
return list(cmd[:-1]) + [tmp], output, tmp
|
|
2399
|
+
|
|
2400
|
+
|
|
2401
|
+
def _reserve(d: str, stem: str, ext: str, tag: str) -> "Tuple[str, Optional[int]]":
|
|
2402
|
+
"""(path, open descriptor) of a hidden sibling created exclusively; (path, None) when the
|
|
2403
|
+
directory refuses the create (the write that follows then fails there)."""
|
|
2404
|
+
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
|
|
2405
|
+
n = 1
|
|
2406
|
+
while True:
|
|
2407
|
+
path = os.path.join(d, f".{stem}.ffskill-" + (f"{tag}-" if tag else "") + f"{os.getpid()}"
|
|
2408
|
+
+ (f"-{n}" if n > 1 else "") + ext)
|
|
2409
|
+
try:
|
|
2410
|
+
return path, os.open(path, flags, 0o666)
|
|
2411
|
+
except FileExistsError:
|
|
2412
|
+
n += 1
|
|
2413
|
+
except OSError:
|
|
2414
|
+
return path, None
|
|
2415
|
+
|
|
2416
|
+
|
|
2417
|
+
def reserve_sibling(d: str, stem: str, ext: str, tag: str = "") -> str:
|
|
2418
|
+
"""Create the hidden sibling `.<stem>.ffskill-<pid><ext>` (or `...-<pid>-<n><ext>` when that
|
|
2419
|
+
name is taken) exclusively, and return its path, for ffmpeg to write with -y. O_EXCL never
|
|
2420
|
+
opens an existing entry, a symlink included, so a name planted in the output directory
|
|
2421
|
+
beforehand is never written through. What it cannot stop is someone who may delete files in
|
|
2422
|
+
that directory replacing this one between the create and ffmpeg's open: not possible in a
|
|
2423
|
+
sticky shared directory (/tmp), nor in one only the caller can write. A copy this process makes
|
|
2424
|
+
itself goes through copy_to_sibling(), which writes the descriptor it created."""
|
|
2425
|
+
path, fd = _reserve(d, stem, ext, tag)
|
|
2426
|
+
if fd is None:
|
|
2427
|
+
# fail closed: a name that was not created exclusively is never handed to ffmpeg
|
|
2428
|
+
refuse("input", "output_dir_not_writable", f"cannot create a temporary file in {d or '.'!r}",
|
|
2429
|
+
output=os.path.join(d, stem + ext), directory=d or ".")
|
|
2430
|
+
os.close(fd)
|
|
2431
|
+
return path
|
|
2432
|
+
|
|
2433
|
+
|
|
2434
|
+
def copy_to_sibling(src: str, dst: str) -> str:
|
|
2435
|
+
"""Copy `src` into a hidden sibling of `dst` created exclusively, through the descriptor that
|
|
2436
|
+
created it (never by reopening the name), and return the sibling's path for os.replace()."""
|
|
2437
|
+
import shutil
|
|
2438
|
+
d, base = os.path.split(dst)
|
|
2439
|
+
stem, ext = os.path.splitext(base)
|
|
2440
|
+
path, fd = _reserve(d, stem, ext, "")
|
|
2441
|
+
if fd is None:
|
|
2442
|
+
raise OSError(f"cannot create a temporary file beside {dst}")
|
|
2443
|
+
try:
|
|
2444
|
+
fout = os.fdopen(fd, "wb")
|
|
2445
|
+
except BaseException:
|
|
2446
|
+
os.close(fd)
|
|
2447
|
+
try:
|
|
2448
|
+
os.remove(path)
|
|
2449
|
+
except OSError:
|
|
2450
|
+
pass
|
|
2451
|
+
raise
|
|
2452
|
+
try:
|
|
2453
|
+
with fout, open(src, "rb") as fin:
|
|
2454
|
+
shutil.copyfileobj(fin, fout, 1 << 20)
|
|
2455
|
+
except BaseException:
|
|
2456
|
+
try:
|
|
2457
|
+
os.remove(path)
|
|
2458
|
+
except OSError:
|
|
2459
|
+
pass
|
|
2460
|
+
raise
|
|
2461
|
+
return path
|
|
2462
|
+
|
|
2463
|
+
|
|
2464
|
+
HW_ENV = "FFMPEG_SKILL_HW"
|
|
2465
|
+
# set only by render.py/batch.py --hw/--no-hw for the stages they run: "the outer command chose
|
|
2466
|
+
# explicitly", so a child resolves $FFMPEG_SKILL_HW as a flag (export.py included), not a default
|
|
2467
|
+
HW_FORCED_ENV = "_FFMPEG_SKILL_HW_EXPLICIT"
|
|
2468
|
+
|
|
2469
|
+
|
|
2470
|
+
def add_hw_orchestrator_args(ap: "argparse.ArgumentParser") -> None:
|
|
2471
|
+
"""--hw / --no-hw on a tool that runs other tools (render.py, batch.py) and encodes nothing itself."""
|
|
2472
|
+
_add_hw_flags(ap, "run every stage's encode on Apple VideoToolbox, the final delivery export included (Apple Silicon; "
|
|
2473
|
+
"falls back to the CPU, reported, where it cannot apply). Without it, $FFMPEG_SKILL_HW=1 still "
|
|
2474
|
+
"puts the intermediate stages on the GPU and leaves the delivery export on the CPU",
|
|
2475
|
+
"every stage on the CPU encoders, whatever $FFMPEG_SKILL_HW says")
|
|
2476
|
+
ap.set_defaults(_hw_orchestrator=True)
|
|
2477
|
+
|
|
2478
|
+
|
|
2479
|
+
def env_hw() -> bool:
|
|
2480
|
+
"""$FFMPEG_SKILL_HW asks for VideoToolbox by default (1/true/yes/on); anything else is off."""
|
|
2481
|
+
return os.environ.get(HW_ENV, "").strip().lower() in ("1", "true", "yes", "on")
|
|
2482
|
+
|
|
2483
|
+
|
|
2484
|
+
def hw_platform_reason() -> Optional[str]:
|
|
2485
|
+
"""None when this machine can take a VideoToolbox constant-quality encode, else why not.
|
|
2486
|
+
`-q:v` on VideoToolbox is Apple-Silicon-only in FFmpeg: an Intel Mac lists the encoders but
|
|
2487
|
+
rejects the quality setting, so the machine check is macOS AND Apple Silicon hardware."""
|
|
2488
|
+
if platform.system() != "Darwin":
|
|
2489
|
+
return "VideoToolbox is macOS-only"
|
|
2490
|
+
if not apple_silicon():
|
|
2491
|
+
return "VideoToolbox constant-quality encoding needs Apple Silicon"
|
|
2492
|
+
return None
|
|
2493
|
+
|
|
2494
|
+
|
|
2495
|
+
_APPLE_SILICON: Optional[bool] = None
|
|
2496
|
+
|
|
2497
|
+
|
|
2498
|
+
def apple_silicon() -> bool:
|
|
2499
|
+
"""Whether this Mac's hardware is Apple Silicon -- not this interpreter's architecture: an
|
|
2500
|
+
x86_64 Python under Rosetta reports platform.machine() "x86_64" on an M-series Mac, where
|
|
2501
|
+
`sysctl -n hw.optional.arm64` still reads 1 (an Intel Mac has no such key). What decides -q:v
|
|
2502
|
+
is the ffmpeg binary's own build; an x86_64 ffmpeg there refuses it, and run() re-encodes that
|
|
2503
|
+
job on the CPU with ffmpeg's line in the note. Read once."""
|
|
2504
|
+
global _APPLE_SILICON
|
|
2505
|
+
if _APPLE_SILICON is None:
|
|
2506
|
+
_APPLE_SILICON = platform.machine() == "arm64"
|
|
2507
|
+
if not _APPLE_SILICON and platform.system() == "Darwin":
|
|
2508
|
+
try:
|
|
2509
|
+
out = subprocess.run([safe_which("sysctl") or "/usr/sbin/sysctl", "-n", "hw.optional.arm64"],
|
|
2510
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8",
|
|
2511
|
+
errors="replace", timeout=10).stdout
|
|
2512
|
+
_APPLE_SILICON = out.strip() == "1"
|
|
2513
|
+
except (OSError, subprocess.SubprocessError):
|
|
2514
|
+
_APPLE_SILICON = False
|
|
2515
|
+
return _APPLE_SILICON
|
|
2516
|
+
|
|
2517
|
+
|
|
2518
|
+
# What FFmpeg prints when a VideoToolbox encoder cannot take a job, read from the sources of 5.1,
|
|
2519
|
+
# 6.0, 6.1, 7.0, 7.1, 8.0 and master (fftools/ffmpeg*.c, libavcodec/videotoolboxenc.c):
|
|
2520
|
+
# - the CLI's encoder-open failure, "Error while opening encoder", on every version. From 6.0 the
|
|
2521
|
+
# line carries the output stream's log context, which names the encoder ("[vost#0:0/
|
|
2522
|
+
# h264_videotoolbox @ 0x...]", from 8.0 followed by "[enc:h264_videotoolbox @ 0x...]"). 5.1
|
|
2523
|
+
# prints "Error initializing output stream 0:0 -- Error while opening encoder for output stream
|
|
2524
|
+
# #0:0 ...", which names no encoder, so there it counts only beside an error line the
|
|
2525
|
+
# VideoToolbox encoder logged in its own context;
|
|
2526
|
+
# - the encoder's own session failures, logged in its codec context ("[h264_videotoolbox @
|
|
2527
|
+
# 0x...]"): "cannot create compression session", "cannot prepare encoder", "cannot encode
|
|
2528
|
+
# frame", "Error encoding frame". Each of them fails the encode. Matched without case and
|
|
2529
|
+
# without the "Error: " prefix, which master drops ("Cannot create compression session").
|
|
2530
|
+
# Deliberately not counted, so the job is not run twice and the GPU is not blamed:
|
|
2531
|
+
# - "Could not open encoder before EOF" (7.0+). It names the encoder, but it follows a filter
|
|
2532
|
+
# graph that failed before the first frame -- a missing font, a bad filter argument -- so the
|
|
2533
|
+
# encoder never got as far as opening;
|
|
2534
|
+
# - the encoder's ERROR-level lines that do not fail the encode ("Error setting profile/level
|
|
2535
|
+
# property ... Output will be encoded using a supported profile/level combination", the
|
|
2536
|
+
# frames_before/frames_after/entropy/realtime/pixel-aspect properties), which a job that fails
|
|
2537
|
+
# for another reason (a full disk: "Error submitting a packet to the muxer") can still carry.
|
|
2538
|
+
_VT_ENCODER_RE = re.compile(r"(?:h264|hevc|prores)_videotoolbox")
|
|
2539
|
+
_VT_OWN_CONTEXT_RE = re.compile(r"\[(?:h264|hevc|prores)_videotoolbox @ [^\]]*\]")
|
|
2540
|
+
_VT_SESSION_RE = re.compile(r"create compression session|prepare encoder|encode frame|encoding frame", re.I)
|
|
2541
|
+
# the encoder's own ERROR-level lines that do not fail the encode (listed above)
|
|
2542
|
+
_VT_NONFATAL_RE = re.compile(r"profile/level|entropy|frames_before|frames_after|realtime|pixel aspect|aspect ratio", re.I)
|
|
2543
|
+
_STREAM_CONTEXT_RE = re.compile(r"\[[a-z]ost#\d+:\d+")
|
|
2544
|
+
_ENCODER_OPEN_FAILED = "Error while opening encoder"
|
|
2545
|
+
|
|
2546
|
+
|
|
2547
|
+
def videotoolbox_failure(stderr: str) -> Optional[str]:
|
|
2548
|
+
"""The stderr line that shows a VideoToolbox encoder refused the job (could not open, or its
|
|
2549
|
+
compression session failed), with the log contexts' pointers dropped; None when the failure
|
|
2550
|
+
is something else. Only such a failure is retried on the CPU (see the notes above)."""
|
|
2551
|
+
lines = [ln.strip() for ln in (stderr or "").splitlines() if ln.strip()]
|
|
2552
|
+
own = [ln for ln in lines if _VT_OWN_CONTEXT_RE.search(ln)]
|
|
2553
|
+
# the lines that can explain a refusal: not the non-fatal property errors, which a job that
|
|
2554
|
+
# failed elsewhere (5.1: an audio encoder that could not open) still carries
|
|
2555
|
+
fatal = [ln for ln in own if not _VT_NONFATAL_RE.search(ln)]
|
|
2556
|
+
found = next((ln for ln in own if _VT_SESSION_RE.search(ln)), None)
|
|
2557
|
+
if found is None:
|
|
2558
|
+
for ln in lines:
|
|
2559
|
+
if _ENCODER_OPEN_FAILED not in ln:
|
|
2560
|
+
continue
|
|
2561
|
+
if _VT_ENCODER_RE.search(ln): # 6.0+: the line names the encoder that failed to open
|
|
2562
|
+
found = fatal[-1] if fatal else ln
|
|
2563
|
+
break
|
|
2564
|
+
if fatal and not _STREAM_CONTEXT_RE.search(ln): # 5.1: no encoder named; the encoder's own error line is
|
|
2565
|
+
found = fatal[-1]
|
|
2566
|
+
break
|
|
2567
|
+
return re.sub(r" @ 0x[0-9a-fA-F]+", "", found)[:200] if found else None
|
|
2568
|
+
|
|
2569
|
+
|
|
2570
|
+
def _hw_fallback(cmd: List[str], ctx: "Context") -> Optional[List[str]]:
|
|
2571
|
+
"""`cmd` with every VideoToolbox encoder line this process built swapped back to the CPU line
|
|
2572
|
+
it replaced, or None when it has none -- for run() when the GPU refused an encode."""
|
|
2573
|
+
out, changed = list(cmd), False
|
|
2574
|
+
for vt, cpu in ctx.hw_swaps:
|
|
2575
|
+
n = len(vt)
|
|
2576
|
+
for i in range(len(out) - n + 1):
|
|
2577
|
+
if out[i:i + n] == vt:
|
|
2578
|
+
out[i:i + n] = cpu
|
|
2579
|
+
changed = True
|
|
2580
|
+
break
|
|
2581
|
+
return out if changed else None
|
|
2582
|
+
|
|
2583
|
+
|
|
2584
|
+
def _record_media_write(ctx: Context, cmd: Sequence[str], output: str) -> None:
|
|
2585
|
+
"""Record evidence from a successful FFmpeg write, separately from the printable plan."""
|
|
2586
|
+
if output == "-" or output.startswith("pipe:"):
|
|
2587
|
+
return
|
|
2588
|
+
identity = owned_identity(output)
|
|
2589
|
+
if not identity:
|
|
2590
|
+
return
|
|
2591
|
+
options = shape_of(cmd).output_opts
|
|
2592
|
+
codecs = [(arg, value) for arg, value in zip(options, options[1:])
|
|
2593
|
+
if re.fullmatch(r"-(?:(?:c|codec)(?::\S+)?|[vasdt]codec)", arg)]
|
|
2594
|
+
if any(arg in ("-c", "-codec") for arg, _ in codecs) and all(value == "copy" for _, value in codecs):
|
|
2595
|
+
ctx._stream_copy_outputs[_checked_key(output)] = identity
|
|
2596
|
+
else:
|
|
2597
|
+
# A later concat/remux may copy an intermediate that this run encoded.
|
|
2598
|
+
ctx._encoded_media = True
|
|
2599
|
+
|
|
2600
|
+
|
|
2601
|
+
def stream_copy_output(ctx: Context, output: str) -> bool:
|
|
2602
|
+
"""Conservatively prove stream copy for the current file using this runner's write records."""
|
|
2603
|
+
identity = ctx._stream_copy_outputs.get(_checked_key(output))
|
|
2604
|
+
return bool(identity and not ctx._encoded_media and not ctx.stage_verification
|
|
2605
|
+
and owned_identity(output) == identity)
|
|
2606
|
+
|
|
2607
|
+
|
|
2608
|
+
# FFmpeg 9.1 made a new coder (`nmr`) the AAC encoder's default, and it never returns on some
|
|
2609
|
+
# sound: mono at 192k behind 0.1 s or 2.5 s of silence ran until the time limit, a file of 48
|
|
2610
|
+
# bytes (#659; 64k to 160k, 256k, stereo and no silence all ended). From 9.1 on, every AAC track is
|
|
2611
|
+
# written with the coder that was the default until then, as on every older build; a command that
|
|
2612
|
+
# names a coder keeps it. `version` is for the test: the build on PATH otherwise.
|
|
2613
|
+
def pin_aac_coder(cmd: Sequence[str], version: "Optional[Tuple[int, int]]" = None) -> List[str]:
|
|
2614
|
+
return [x for i, a in enumerate(cmd) for x in ([a, "-aac_coder", "twoloop"] if a == "aac" and i and "-aac_coder" not in cmd and (version or ffmpeg_version()) >= (9, 1) and re.fullmatch(r"-(c|codec):a(:\d+)?|-acodec", cmd[i - 1]) else [a])]
|
|
2615
|
+
|
|
2616
|
+
|
|
2617
|
+
def run(cmd: Sequence[str], *, quiet: bool = False, check: bool = True, ctx: "Optional[Context]" = None) -> subprocess.CompletedProcess:
|
|
2618
|
+
"""Run a command, echoing it to stderr unless quiet. Exits on failure when check=True.
|
|
2619
|
+
|
|
2620
|
+
ffmpeg invocations are recorded in STATE.commands (for --json), skipped under --dry-run
|
|
2621
|
+
(a fake successful CompletedProcess is returned so scripts can keep planning), and run
|
|
2622
|
+
with a progress readout under --progress. ffprobe and other tools always run. An output
|
|
2623
|
+
path that already exists is written through a temp file and replaced only on success
|
|
2624
|
+
(see _stage_existing_output), so a failed run never costs the caller the file that was there.
|
|
2625
|
+
|
|
2626
|
+
`ctx` is the optional per-request Context added in 1.10 (2.0 makes it required, issue #189 B);
|
|
2627
|
+
omitted, the commands and flags are read from the process-global STATE as before.
|
|
2628
|
+
"""
|
|
2629
|
+
ctx = ctx or STATE
|
|
2630
|
+
is_ffmpeg = _is_ffmpeg(cmd)
|
|
2631
|
+
_refuse_url_media(cmd) # check the caller's formats before the runner adds input options
|
|
2632
|
+
cmd = guard_input_names(cmd) # before it is checked, recorded or run
|
|
2633
|
+
if is_ffmpeg:
|
|
2634
|
+
# an encoder line that converts a BT.601 source to the BT.709 it is tagged with carries
|
|
2635
|
+
# that conversion as a -vf; it joins the tool's own graph here, before anything records
|
|
2636
|
+
# or runs the command (color.py imports this module, hence the late import)
|
|
2637
|
+
from _common.color import fold_bt709_matrix
|
|
2638
|
+
cmd = pin_aac_coder(fold_bt709_matrix(cmd))
|
|
2639
|
+
_check_no_overwrite_input(cmd)
|
|
2640
|
+
_check_output_path(cmd)
|
|
2641
|
+
_check_output_extension(cmd)
|
|
2642
|
+
_check_container_codecs(cmd)
|
|
2643
|
+
_check_picture_into_audio_extension(cmd)
|
|
2644
|
+
_check_build_components(cmd)
|
|
2645
|
+
_check_existing_output(cmd)
|
|
2646
|
+
ctx.commands.append(_cmdline(cmd))
|
|
2647
|
+
if not quiet:
|
|
2648
|
+
info(("[dry-run] $ " if ctx.dry_run and is_ffmpeg else "$ ") + _cmdline(cmd), ctx=ctx)
|
|
2649
|
+
if ctx.dry_run and is_ffmpeg:
|
|
2650
|
+
return subprocess.CompletedProcess(list(cmd), 0, "", "")
|
|
2651
|
+
if is_ffmpeg:
|
|
2652
|
+
flush_drawtext_textfiles(cmd)
|
|
2653
|
+
with _OutputLock(cmd[-1] if is_ffmpeg else "-"):
|
|
2654
|
+
if is_ffmpeg:
|
|
2655
|
+
# a file put at the output since the check above is not ours to stage over
|
|
2656
|
+
refuse_changed_output(cmd[-1])
|
|
2657
|
+
exec_cmd, final, tmp = _stage_existing_output(cmd) if is_ffmpeg else (list(cmd), None, None)
|
|
2658
|
+
def even_retry(proc: subprocess.CompletedProcess, ran: List[str]) -> "Tuple[subprocess.CompletedProcess, List[str]]":
|
|
2659
|
+
"""An attempt that failed on odd dimensions, run again with an even scale: after the
|
|
2660
|
+
first attempt, and after a GPU->CPU retry (VideoToolbox may refuse an odd-sized job
|
|
2661
|
+
for another reason before x264 ever reports the size)."""
|
|
2662
|
+
if proc.returncode == 0 or not is_ffmpeg:
|
|
2663
|
+
return proc, ran
|
|
2664
|
+
retry = _odd_dimension_retry(ran, proc.stderr or "")
|
|
2665
|
+
if retry is not None:
|
|
2666
|
+
# recorded, not only said: the output's frame is a pixel narrower or shorter than
|
|
2667
|
+
# the source's, which a caller comparing sizes has to be able to read
|
|
2668
|
+
record_fallback("source has odd dimensions; scaling to even before encoding (yuv420p needs it)",
|
|
2669
|
+
"odd_dimensions_scaled_even", ctx=ctx, output=cmd[-1], scale=EVEN_SCALE)
|
|
2670
|
+
ctx.commands[-1] = _cmdline(retry[:-1] + [cmd[-1]])
|
|
2671
|
+
return _execute(retry, ctx), retry
|
|
2672
|
+
if "not divisible by 2" in (proc.stderr or ""):
|
|
2673
|
+
die("the source has odd dimensions (width or height not divisible by 2) and this tool's filter graph "
|
|
2674
|
+
"cannot pad them itself; make them even first, e.g. fit.py --width/--height, then retry",
|
|
2675
|
+
kind="input")
|
|
2676
|
+
return proc, ran
|
|
2677
|
+
|
|
2678
|
+
# `tried` is the last command run: the CPU fallback swaps its encoder line in
|
|
2679
|
+
proc, tried = even_retry(_execute(exec_cmd, ctx), exec_cmd)
|
|
2680
|
+
retried = False
|
|
2681
|
+
if proc.returncode != 0 and is_ffmpeg and ctx.hw_swaps:
|
|
2682
|
+
cpu_cmd = _hw_fallback(tried, ctx)
|
|
2683
|
+
if cpu_cmd is not None:
|
|
2684
|
+
# Only a failure VideoToolbox itself reported is retried on the CPU: a bad filter
|
|
2685
|
+
# graph, a missing font or a full disk would fail the same way twice and be
|
|
2686
|
+
# reported as the GPU's fault (videotoolbox_failure() has the strings and why).
|
|
2687
|
+
# A failure that is not one stays a failure of this command: with check=True,
|
|
2688
|
+
# _fail() names it; with check=False the caller's own retry decides (a success
|
|
2689
|
+
# after that must not carry a note about it).
|
|
2690
|
+
why = videotoolbox_failure(proc.stderr or "")
|
|
2691
|
+
if why is not None:
|
|
2692
|
+
reason = f"VideoToolbox refused the encode: {why}"
|
|
2693
|
+
# said before the retry, without a claim about its outcome: a retry that never
|
|
2694
|
+
# returns (a timeout exits from inside _execute) leaves this line, which is true
|
|
2695
|
+
_set_refusal_note(ctx, reason, "; retrying on the CPU encoder")
|
|
2696
|
+
info(reason + "; retrying on the CPU encoder")
|
|
2697
|
+
ctx.commands[-1] = _cmdline(cpu_cmd[:-1] + [cmd[-1]])
|
|
2698
|
+
if not quiet:
|
|
2699
|
+
# echoed like the first attempt, so a caller that reads the "$ " lines
|
|
2700
|
+
# (render.py's stages) records the command that really ran
|
|
2701
|
+
info("$ " + ctx.commands[-1], ctx=ctx)
|
|
2702
|
+
proc, tried = even_retry(_execute(cpu_cmd, ctx), cpu_cmd)
|
|
2703
|
+
retried = True
|
|
2704
|
+
# the outcome replaces the line above: a failure document must not claim a
|
|
2705
|
+
# re-encode that did not happen, and hw.fallback is the same claim as a flag
|
|
2706
|
+
ok = proc.returncode == 0
|
|
2707
|
+
_set_refusal_note(ctx, reason, "; re-encoded on the CPU" if ok else "; the CPU retry failed too")
|
|
2708
|
+
ctx.hw_fallback = ctx.hw_fallback or ok
|
|
2709
|
+
if proc.returncode != 0 and check:
|
|
2710
|
+
_fail(tried, proc.returncode, proc.stderr or "", ctx=ctx, retried=retried)
|
|
2711
|
+
if final and tmp:
|
|
2712
|
+
if proc.returncode == 0:
|
|
2713
|
+
# still under the lock: the target the check let this run replace, not a file
|
|
2714
|
+
# another process put there during the encode
|
|
2715
|
+
refuse_changed_output(final, lambda: _cleanup_partial_output(exec_cmd))
|
|
2716
|
+
try:
|
|
2717
|
+
os.replace(tmp, final)
|
|
2718
|
+
except OSError as e:
|
|
2719
|
+
_cleanup_partial_output(exec_cmd)
|
|
2720
|
+
die(f"could not replace {final} with the new output: {e}", kind="output")
|
|
2721
|
+
_remember_output(cmd)
|
|
2722
|
+
else:
|
|
2723
|
+
_cleanup_partial_output(exec_cmd)
|
|
2724
|
+
if is_ffmpeg and proc.returncode == 0:
|
|
2725
|
+
_record_media_write(ctx, tried, cmd[-1])
|
|
2726
|
+
return proc
|
|
2727
|
+
|
|
2728
|
+
|
|
2729
|
+
def _set_refusal_note(ctx: "Context", reason: str, outcome: str) -> None:
|
|
2730
|
+
"""One note per refusal: the latest outcome for `reason` replaces any earlier line for it, so a
|
|
2731
|
+
job of many encodes names it once, and a process that ran an earlier job with the same refusal
|
|
2732
|
+
does not keep that job's outcome beside this one."""
|
|
2733
|
+
ctx.hw_notes[:] = [n for n in ctx.hw_notes if not n.startswith(reason)]
|
|
2734
|
+
ctx.hw_notes.append(reason + outcome)
|
|
2735
|
+
|
|
2736
|
+
|
|
2737
|
+
# A filter graph longer than this is handed to ffmpeg in a file (A138). Linux refuses any single
|
|
2738
|
+
# argument over 128 KiB (MAX_ARG_STRLEN) and Windows a whole command line over 32767 characters, and
|
|
2739
|
+
# a graph grows with the items it is built from: scenes.py --sheet's select expression is ~56
|
|
2740
|
+
# characters a scene, so ~2,340 scenes raised OSError E2BIG before ffmpeg ran, with a traceback and
|
|
2741
|
+
# no JSON. A graph under the limit is passed as it always was.
|
|
2742
|
+
LONG_FILTER_CHARS = 8000 if os.name == "nt" else 100_000
|
|
2743
|
+
_FILTER_OPTION_RE = re.compile(r"^-(?:filter_complex|lavfi|vf|af|filter(?::[^\s]+)?)$")
|
|
2744
|
+
|
|
2745
|
+
|
|
2746
|
+
def _filter_file_option(option: str) -> str:
|
|
2747
|
+
"""The option that reads `option`'s value from a file: `-/OPTION` from FFmpeg 7.0, which
|
|
2748
|
+
deprecated the `_script` spellings, and `-filter_complex_script` / `-filter_script[:spec]`
|
|
2749
|
+
before it (6.x, the oldest CI runs)."""
|
|
2750
|
+
complex_graph = option in ("-filter_complex", "-lavfi")
|
|
2751
|
+
spec = {"-vf": ":v", "-af": ":a"}.get(option, option[len("-filter"):] if option.startswith("-filter:") else "")
|
|
2752
|
+
if ffmpeg_version() >= (7, 0):
|
|
2753
|
+
return "-/filter_complex" if complex_graph else "-/filter" + spec
|
|
2754
|
+
return "-filter_complex_script" if complex_graph else "-filter_script" + spec
|
|
2755
|
+
|
|
2756
|
+
|
|
2757
|
+
@contextlib.contextmanager
|
|
2758
|
+
def long_filters_in_files(cmd: Sequence[str]) -> "Any":
|
|
2759
|
+
"""`cmd` with every filter graph longer than LONG_FILTER_CHARS moved into a temp file read by
|
|
2760
|
+
ffmpeg's file form of the same option; the files are removed when the block ends. The command a
|
|
2761
|
+
run records and prints is the caller's own, with the graph inline."""
|
|
2762
|
+
import tempfile
|
|
2763
|
+
out = list(cmd)
|
|
2764
|
+
made: List[str] = []
|
|
2765
|
+
try:
|
|
2766
|
+
if _is_ffmpeg(out):
|
|
2767
|
+
for i in range(1, len(out) - 1):
|
|
2768
|
+
if _FILTER_OPTION_RE.match(out[i]) and len(out[i + 1]) > LONG_FILTER_CHARS:
|
|
2769
|
+
fd, path = tempfile.mkstemp(prefix="ffmpeg-skill-graph-", suffix=".txt")
|
|
2770
|
+
made.append(path)
|
|
2771
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
2772
|
+
fh.write(out[i + 1])
|
|
2773
|
+
out[i], out[i + 1] = _filter_file_option(out[i]), path
|
|
2774
|
+
yield out
|
|
2775
|
+
finally:
|
|
2776
|
+
for path in made:
|
|
2777
|
+
with contextlib.suppress(OSError):
|
|
2778
|
+
os.remove(path)
|
|
2779
|
+
|
|
2780
|
+
|
|
2781
|
+
def _execute(exec_cmd: List[str], ctx: "Optional[Context]" = None) -> subprocess.CompletedProcess:
|
|
2782
|
+
"""One attempt; incomplete input stops before retries or output promotion."""
|
|
2783
|
+
with long_filters_in_files(exec_cmd) as cmd:
|
|
2784
|
+
if STATE.progress and _is_ffmpeg(cmd) and cmd[-1] != "-":
|
|
2785
|
+
proc = _run_with_progress(cmd)
|
|
2786
|
+
else:
|
|
2787
|
+
proc = _run_captured(cmd)
|
|
2788
|
+
if _is_ffmpeg(cmd):
|
|
2789
|
+
marker = next((line for line in (proc.stderr or "").splitlines() if INCOMPLETE_INPUT.search(line)), None)
|
|
2790
|
+
if marker and not any(a == "-err_detect" and b == "ignore_err" for a, b in zip(cmd, cmd[1:])):
|
|
2791
|
+
_cleanup_partial_output(cmd)
|
|
2792
|
+
_fail(cmd, proc.returncode, f"inputs: {', '.join(shape_of(cmd).inputs)}\n{marker[:500]}", ctx=ctx, diagnostic=INCOMPLETE_INPUT.search(marker).group(0))
|
|
2793
|
+
if proc.returncode:
|
|
2794
|
+
_cleanup_partial_output(cmd)
|
|
2795
|
+
else:
|
|
2796
|
+
_remember_output(cmd)
|
|
2797
|
+
return proc
|
|
2798
|
+
|
|
2799
|
+
|
|
2800
|
+
def run_analysis(cmd: Sequence[str], *, check: bool = True, text: bool = True, record: bool = False,
|
|
2801
|
+
timeout_is_fatal: bool = True) -> subprocess.CompletedProcess:
|
|
2802
|
+
"""Run an ffmpeg *measurement* (scene scores, crop rectangles, decoded PCM, signal stats,
|
|
2803
|
+
silence detection, loudness, stabilisation pass 1): output to `-f null`, a pipe or a temp
|
|
2804
|
+
file, no deliverable written. These are not run() calls -- they run under --dry-run too,
|
|
2805
|
+
since a plan built on a fake measurement is not a plan (silence.py used to report "0
|
|
2806
|
+
silences" and loudness.py a made-up -20 LUFS under --dry-run) -- but they get the same
|
|
2807
|
+
wall-clock limit as any other ffmpeg invocation and, with check=True, the same `kind: ffmpeg`
|
|
2808
|
+
failure instead of an exit-0 "0 scenes found" over a file ffmpeg could not read. record=True
|
|
2809
|
+
lists the command in the --json `commands` like run() does. With
|
|
2810
|
+
timeout_is_fatal=False, raise TimeoutExpired so advisory callers can report a missing measurement."""
|
|
2811
|
+
_refuse_url_media(cmd)
|
|
2812
|
+
cmd = guard_input_names(cmd)
|
|
2813
|
+
if record:
|
|
2814
|
+
STATE.commands.append(_cmdline(cmd))
|
|
2815
|
+
limit = _limit_for(cmd)
|
|
2816
|
+
try:
|
|
2817
|
+
# #234: decode as UTF-8, never as the machine's locale code page -- ffmpeg echoes the
|
|
2818
|
+
# input filename on stderr, and loudness/check parse the loudnorm JSON out of it. The
|
|
2819
|
+
# encoding kwargs are rejected with text=False, so they are only passed for text mode.
|
|
2820
|
+
text_kw = {"encoding": "utf-8", "errors": "replace"} if text else {}
|
|
2821
|
+
with long_filters_in_files(cmd) as exec_cmd:
|
|
2822
|
+
proc = subprocess.run(exec_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, **text_kw, timeout=limit)
|
|
2823
|
+
except subprocess.TimeoutExpired:
|
|
2824
|
+
if not timeout_is_fatal:
|
|
2825
|
+
raise
|
|
2826
|
+
_timed_out(cmd, limit or 0)
|
|
2827
|
+
if check and proc.returncode != 0:
|
|
2828
|
+
err = proc.stderr if text else proc.stderr.decode(errors="replace")
|
|
2829
|
+
_fail(cmd, proc.returncode, err)
|
|
2830
|
+
return proc
|
|
2831
|
+
|
|
2832
|
+
|
|
2833
|
+
def path_denied(path: Any) -> bool:
|
|
2834
|
+
"""True when `path` cannot be looked at or read for lack of permission: a directory on the
|
|
2835
|
+
way to it that the user may not search (os.stat fails with EACCES, which os.path.exists()
|
|
2836
|
+
reports as "not there"), or a file that is there and may not be read. False for a path that
|
|
2837
|
+
is simply absent (#558: both were reported as "not found")."""
|
|
2838
|
+
try:
|
|
2839
|
+
os.stat(path)
|
|
2840
|
+
except PermissionError:
|
|
2841
|
+
return True
|
|
2842
|
+
except (OSError, ValueError):
|
|
2843
|
+
return False
|
|
2844
|
+
return not os.path.isdir(path) and not os.access(path, os.R_OK)
|
|
2845
|
+
|
|
2846
|
+
|
|
2847
|
+
def absent_word(path: Any) -> str:
|
|
2848
|
+
""""permission denied" or "not found", for the message about a file that could not be opened."""
|
|
2849
|
+
return "permission denied" if path_denied(path) else "not found"
|
|
2850
|
+
|
|
2851
|
+
|
|
2852
|
+
def refuse_denied_input(path: Any, what: str = "input") -> None:
|
|
2853
|
+
"""Refuse a file the user may not reach or read as what it is (`input_permission_denied`),
|
|
2854
|
+
for a real run and a dry run alike. Nothing for any other path, an absent one included."""
|
|
2855
|
+
if path_denied(path):
|
|
2856
|
+
refuse("input", "input_permission_denied", f"{what} cannot be read: permission denied: {path}",
|
|
2857
|
+
hint="the file, or a directory on the way to it, is not readable by the user this runs as: "
|
|
2858
|
+
"change its permissions or copy it somewhere readable",
|
|
2859
|
+
path=str(path))
|
|
2860
|
+
|
|
2861
|
+
|
|
2862
|
+
def dry_run_input_pending(path: str) -> bool:
|
|
2863
|
+
"""True when a measurement cannot run because its input does not exist yet under --dry-run:
|
|
2864
|
+
in a render.py/batch.py plan each stage's input is the previous stage's output, which a dry
|
|
2865
|
+
run never wrote. The measurement is then skipped rather than failing the plan, and the skip is
|
|
2866
|
+
recorded (`diagnostics.skipped`, `measurement_input_pending`, once per path) beside its stderr
|
|
2867
|
+
line; on a real file the measurement runs even under --dry-run."""
|
|
2868
|
+
if STATE.dry_run and not os.path.exists(path):
|
|
2869
|
+
record_skip(f"[dry-run] {path} does not exist yet (an earlier dry-run stage would write it); measurement skipped",
|
|
2870
|
+
"measurement_input_pending", path=path)
|
|
2871
|
+
return True
|
|
2872
|
+
return False
|
|
2873
|
+
|
|
2874
|
+
|
|
2875
|
+
def child_limit(per_call: Optional[float] = None) -> Optional[float]:
|
|
2876
|
+
"""Wall-clock ceiling for running one sibling script as a subprocess (render/batch/report
|
|
2877
|
+
stages, the MCP server's dispatch). A tool runs a handful of ffmpeg/ffprobe calls, each
|
|
2878
|
+
under its own --timeout, so the outer ceiling is a multiple of that plus a margin: it never
|
|
2879
|
+
fires first on a healthy run, and it is the only thing that ends a child hung for a reason
|
|
2880
|
+
that is not ffmpeg (a stuck import, a wedged pipe). None when the per-call limit is 0."""
|
|
2881
|
+
limit = STATE.timeout if per_call is None else per_call
|
|
2882
|
+
if not limit or limit != limit or limit > MAX_TIMEOUT:
|
|
2883
|
+
# 0 is "no limit". A per-call value no run can wait for (nan, inf, 1e300 from an MCP
|
|
2884
|
+
# `timeout`) has no ceiling either: the child refuses that --timeout itself, at once, and
|
|
2885
|
+
# communicate(timeout=4e300) would raise OverflowError with the child already running
|
|
2886
|
+
return None
|
|
2887
|
+
return limit * 4 + 60
|
|
2888
|
+
|
|
2889
|
+
|
|
2890
|
+
# How long a sibling script past its outer ceiling gets to stop on SIGTERM before it is killed:
|
|
2891
|
+
# its handler waits up to 5 s for each ffmpeg it runs (stop_children()), then removes the partial
|
|
2892
|
+
# output and exits with its failure document.
|
|
2893
|
+
STOP_GRACE = 15.0
|
|
2894
|
+
|
|
2895
|
+
|
|
2896
|
+
def _taskkill() -> Optional[str]:
|
|
2897
|
+
"""Windows' own taskkill.exe, by its full path under %SystemRoot% (never a `taskkill` found on
|
|
2898
|
+
PATH), or None when it is not there."""
|
|
2899
|
+
root = os.environ.get("SystemRoot") or os.environ.get("windir") or r"C:\Windows"
|
|
2900
|
+
path = os.path.join(root, "System32", "taskkill.exe")
|
|
2901
|
+
return path if os.path.isfile(path) else None
|
|
2902
|
+
|
|
2903
|
+
|
|
2904
|
+
TREE_KILL_TIMEOUT = 30.0
|
|
2905
|
+
|
|
2906
|
+
|
|
2907
|
+
def terminate_tree(child: subprocess.Popen, windows: Optional[bool] = None) -> bool:
|
|
2908
|
+
"""Ask a sibling script to stop, so that its ffmpeg stops too (review of #530).
|
|
2909
|
+
|
|
2910
|
+
POSIX: SIGTERM to the script; its handler stops its ffmpeg (up to 5 s each), removes the
|
|
2911
|
+
partial output and releases the output lock, then exits. Returns True.
|
|
2912
|
+
|
|
2913
|
+
Windows: terminate() is TerminateProcess on the script alone, no handler runs, and its ffmpeg
|
|
2914
|
+
would keep encoding with the lock and the partial output in place. The whole tree is killed
|
|
2915
|
+
with taskkill /T /F and this returns once taskkill has (True when it says it did). Without
|
|
2916
|
+
taskkill, or when it fails or does not finish in TREE_KILL_TIMEOUT, the script alone is
|
|
2917
|
+
killed and this returns False: its ffmpeg may outlive it."""
|
|
2918
|
+
if windows is None:
|
|
2919
|
+
windows = os.name == "nt"
|
|
2920
|
+
if child.poll() is not None:
|
|
2921
|
+
return True
|
|
2922
|
+
if not windows:
|
|
2923
|
+
try:
|
|
2924
|
+
child.terminate()
|
|
2925
|
+
except OSError:
|
|
2926
|
+
pass
|
|
2927
|
+
return True
|
|
2928
|
+
exe = _taskkill()
|
|
2929
|
+
if exe:
|
|
2930
|
+
try:
|
|
2931
|
+
done = subprocess.run([exe, "/T", "/F", "/PID", str(child.pid)], stdout=subprocess.DEVNULL,
|
|
2932
|
+
stderr=subprocess.DEVNULL, timeout=TREE_KILL_TIMEOUT)
|
|
2933
|
+
if done.returncode == 0:
|
|
2934
|
+
return True
|
|
2935
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
2936
|
+
pass
|
|
2937
|
+
if child.poll() is not None:
|
|
2938
|
+
return True # taskkill failed because the tree was already gone
|
|
2939
|
+
try:
|
|
2940
|
+
child.kill()
|
|
2941
|
+
except OSError:
|
|
2942
|
+
pass
|
|
2943
|
+
return False
|
|
2944
|
+
|
|
2945
|
+
|
|
2946
|
+
def _stop_child(child: subprocess.Popen, communicate: bool = True) -> "Tuple[bool, str]":
|
|
2947
|
+
"""Stop a sibling script with terminate_tree(): on POSIX SIGTERM, then SIGKILL if it has not
|
|
2948
|
+
exited within STOP_GRACE; on Windows its whole tree at once (taskkill /T /F). Returns
|
|
2949
|
+
(stopped, stderr): stopped is True when it exited on the SIGTERM, which a sibling script
|
|
2950
|
+
handles by removing its partial output and its output lock, and False when it had to be
|
|
2951
|
+
killed (always on Windows, where no handler runs). communicate=False waits without reading the
|
|
2952
|
+
pipes (stop_children(), whose caller is already reading them or exiting)."""
|
|
2953
|
+
def wait(timeout: Optional[float] = None) -> str:
|
|
2954
|
+
if communicate:
|
|
2955
|
+
return child.communicate(timeout=timeout)[1] or ""
|
|
2956
|
+
child.wait(timeout=timeout)
|
|
2957
|
+
return ""
|
|
2958
|
+
if os.name != "nt":
|
|
2959
|
+
try:
|
|
2960
|
+
terminate_tree(child, windows=False)
|
|
2961
|
+
return True, wait(STOP_GRACE)
|
|
2962
|
+
except subprocess.TimeoutExpired:
|
|
2963
|
+
pass
|
|
2964
|
+
except OSError:
|
|
2965
|
+
return False, wait()
|
|
2966
|
+
try:
|
|
2967
|
+
child.kill()
|
|
2968
|
+
except OSError:
|
|
2969
|
+
pass
|
|
2970
|
+
return False, wait()
|
|
2971
|
+
terminate_tree(child, windows=True)
|
|
2972
|
+
return False, wait()
|
|
2973
|
+
|
|
2974
|
+
|
|
2975
|
+
def _capture_tool_progress(child: subprocess.Popen, limit: Optional[float],
|
|
2976
|
+
report: Callable[[str], None]) -> Tuple[str, str, Optional[bool]]:
|
|
2977
|
+
"""Drain both pipes while the tool runs. Only tagged progress is sent to the caller."""
|
|
2978
|
+
import threading
|
|
2979
|
+
|
|
2980
|
+
out, err = [], []
|
|
2981
|
+
assert child.stdout is not None and child.stderr is not None
|
|
2982
|
+
|
|
2983
|
+
def stdout_reader() -> None:
|
|
2984
|
+
out.append(child.stdout.read())
|
|
2985
|
+
|
|
2986
|
+
def stderr_reader() -> None:
|
|
2987
|
+
for line in child.stderr:
|
|
2988
|
+
if line.startswith(_PROGRESS_PREFIX):
|
|
2989
|
+
try:
|
|
2990
|
+
report(line[len(_PROGRESS_PREFIX):].strip())
|
|
2991
|
+
except OSError:
|
|
2992
|
+
# A closed transport must not leave the child's stderr pipe undrained.
|
|
2993
|
+
pass
|
|
2994
|
+
else:
|
|
2995
|
+
err.append(line)
|
|
2996
|
+
|
|
2997
|
+
readers = [threading.Thread(target=reader, daemon=True) for reader in (stdout_reader, stderr_reader)]
|
|
2998
|
+
for reader in readers:
|
|
2999
|
+
reader.start()
|
|
3000
|
+
stopped = None
|
|
3001
|
+
try:
|
|
3002
|
+
child.wait(timeout=limit)
|
|
3003
|
+
except subprocess.TimeoutExpired:
|
|
3004
|
+
stopped, _ = _stop_child(child, communicate=False)
|
|
3005
|
+
for reader in readers:
|
|
3006
|
+
reader.join()
|
|
3007
|
+
child.stdout.close()
|
|
3008
|
+
child.stderr.close()
|
|
3009
|
+
return "".join(out), "".join(err), stopped
|
|
3010
|
+
|
|
3011
|
+
|
|
3012
|
+
def _relay_progress(message: str) -> None:
|
|
3013
|
+
sys.stderr.write(_PROGRESS_PREFIX + message + "\n")
|
|
3014
|
+
sys.stderr.flush()
|
|
3015
|
+
|
|
3016
|
+
|
|
3017
|
+
def run_tool(argv: Sequence[str], *, per_call: Optional[float] = None,
|
|
3018
|
+
env: Optional[Dict[str, str]] = None,
|
|
3019
|
+
on_start: "Optional[Callable[[subprocess.Popen], None]]" = None,
|
|
3020
|
+
on_progress: "Optional[Callable[[str], None]]" = None) -> subprocess.CompletedProcess:
|
|
3021
|
+
"""Run a sibling script (`argv[0]` is the script path) under child_limit(). On overrun the
|
|
3022
|
+
child is stopped (_stop_child()) and a CompletedProcess is returned whose stdout is this skill's own failure
|
|
3023
|
+
document (kind timeout, exit 124), so callers that parse the child's --json see a timeout
|
|
3024
|
+
exactly as they would from the child itself. `env` replaces the inherited environment.
|
|
3025
|
+
`on_start(child)` is called once the child is running (the MCP server keeps it to stop a call
|
|
3026
|
+
the client cancels). Tagged progress is streamed to `on_progress` or relayed to the MCP
|
|
3027
|
+
process through a parent tool such as render.py."""
|
|
3028
|
+
limit = child_limit(per_call)
|
|
3029
|
+
# its own stdin, never ours: under the MCP server ours is the client's JSON-RPC pipe, and on
|
|
3030
|
+
# Windows a Python child that inherited it did not finish exiting while the client held it open,
|
|
3031
|
+
# so the answer to tools/call was written only when the client hung up (#664)
|
|
3032
|
+
child = subprocess.Popen([sys.executable] + list(argv), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", env=env)
|
|
3033
|
+
_watch(child, []) # a sibling script removes its own partial output; there is none of ours to clean
|
|
3034
|
+
if on_start is not None:
|
|
3035
|
+
on_start(child)
|
|
3036
|
+
report = on_progress
|
|
3037
|
+
if report is None and (os.environ if env is None else env).get(MCP_PROGRESS_ENV) == "1":
|
|
3038
|
+
report = _relay_progress
|
|
3039
|
+
try:
|
|
3040
|
+
if report is None:
|
|
3041
|
+
out, err = child.communicate(timeout=limit)
|
|
3042
|
+
stopped_cleanly = None
|
|
3043
|
+
else:
|
|
3044
|
+
out, err, stopped_cleanly = _capture_tool_progress(child, limit, report)
|
|
3045
|
+
except subprocess.TimeoutExpired:
|
|
3046
|
+
stopped_cleanly, err = _stop_child(child)
|
|
3047
|
+
finally:
|
|
3048
|
+
_unwatch(child)
|
|
3049
|
+
if stopped_cleanly is None:
|
|
3050
|
+
return subprocess.CompletedProcess(child.args, child.returncode, out, err)
|
|
3051
|
+
# Keep the same failure document and SIGTERM cleanup as the non-streaming path (A183).
|
|
3052
|
+
name = os.path.basename(str(argv[0]))
|
|
3053
|
+
msg = (f"{name} did not finish within {limit:g} s (4x the per-ffmpeg --timeout plus 60 s) and was "
|
|
3054
|
+
+ ("stopped" if stopped_cleanly else "killed"))
|
|
3055
|
+
doc = {"status": "failed", "exit_code": 124,
|
|
3056
|
+
"error": {"kind": "timeout", "message": msg, "code": ERROR_CODE["timeout"], "retryable": ERROR_RETRYABLE},
|
|
3057
|
+
"commands": []}
|
|
3058
|
+
return subprocess.CompletedProcess(list(argv), 124, json.dumps(doc), err + f"\nerror: {msg}\n")
|
|
3059
|
+
|
|
3060
|
+
|
|
3061
|
+
def option_args(flag: str, value: Any) -> List[str]:
|
|
3062
|
+
"""One option and its value for a sibling tool's argparse, as [flag, value] -- or as the single
|
|
3063
|
+
token `flag=value` when the value starts with '-'. argparse reads a separate token that starts
|
|
3064
|
+
with '-' (and is not a negative number) as the next option, so overlay text "-50%" was refused
|
|
3065
|
+
as "expected one argument" and a value like "--plan=x" became an option of its own. The joined
|
|
3066
|
+
form is read as the value whatever it holds. `flag` must be a long option: `-o=x` is not."""
|
|
3067
|
+
text = str(value)
|
|
3068
|
+
if text.startswith("-"):
|
|
3069
|
+
if not flag.startswith("--"):
|
|
3070
|
+
raise ValueError(f"option_args: {flag!r} is not a long option")
|
|
3071
|
+
return [f"{flag}={text}"]
|
|
3072
|
+
return [flag, text]
|
|
3073
|
+
|
|
3074
|
+
|
|
3075
|
+
def child_args() -> List[str]:
|
|
3076
|
+
"""The shared flags a tool that runs sibling scripts (render.py, batch.py) forwards to them,
|
|
3077
|
+
so one `--timeout`/`--overwrite`/`--fast`/`--dry-run` on the outer command governs every
|
|
3078
|
+
stage. Before 1.4.3 only --fast and --dry-run were forwarded; a --timeout given to render.py
|
|
3079
|
+
stopped at render.py."""
|
|
3080
|
+
args: List[str] = []
|
|
3081
|
+
if STATE.fast:
|
|
3082
|
+
args.append("--fast")
|
|
3083
|
+
if STATE.dry_run:
|
|
3084
|
+
args.append("--dry-run")
|
|
3085
|
+
if STATE.overwrite:
|
|
3086
|
+
args.append("--overwrite")
|
|
3087
|
+
args += ["--timeout", f"{STATE.timeout:g}"]
|
|
3088
|
+
return args
|
|
3089
|
+
|
|
3090
|
+
|
|
3091
|
+
def _has_non_av_streams(cmd: Sequence[str]) -> bool:
|
|
3092
|
+
"""Whether the command's first input has a subtitle or data stream (True when it cannot be
|
|
3093
|
+
told: the retry then runs as before)."""
|
|
3094
|
+
src = next(iter(shape_of(cmd).inputs), None)
|
|
3095
|
+
if not src or not os.path.isfile(src):
|
|
3096
|
+
return True
|
|
3097
|
+
try:
|
|
3098
|
+
out = _ffprobe("-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", *input_format_args(src), file_arg(src)).stdout
|
|
3099
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
3100
|
+
return True
|
|
3101
|
+
kinds = {ln.strip() for ln in out.splitlines() if ln.strip()}
|
|
3102
|
+
return not kinds or bool(kinds & {"subtitle", "data", "attachment"})
|
|
3103
|
+
|
|
3104
|
+
|
|
3105
|
+
def ffmpeg_failure_extra(stderr: str) -> Dict[str, Any]:
|
|
3106
|
+
"""The die() keywords that carry the cause ffmpeg named in `stderr` -- a missing encoder or
|
|
3107
|
+
filter, a full disk, an unreadable input -- as `hint` and the error's `reason`/`details`, or {}
|
|
3108
|
+
when it named none (#402): a tool that composes its own failure message (cut.py's re-encode, a
|
|
3109
|
+
measurement pass) reports the cause as run()'s own failures do. Used as
|
|
3110
|
+
`die(msg, kind="ffmpeg", **ffmpeg_failure_extra(proc.stderr))`, through the caller's own die."""
|
|
3111
|
+
cls = classify_ffmpeg_failure(stderr or "")
|
|
3112
|
+
return {"hint": cls[1], "error_extra": {"reason": cls[0], "details": cls[2]}} if cls else {}
|
|
3113
|
+
|
|
3114
|
+
|
|
3115
|
+
|
|
3116
|
+
|
|
3117
|
+
MATROSKA_EXT = frozenset({".mkv", ".mka", ".mks"})
|
|
3118
|
+
|
|
3119
|
+
|
|
3120
|
+
def carried_stream_maps(src: Optional[str], output: str, *, chapters: bool = True, attachments: bool = True) -> List[str]:
|
|
3121
|
+
"""What a command that keeps a source's subtitle/data streams (`-map 0:s? -map 0:d?`, or
|
|
3122
|
+
`-map 0`) adds so the written file carries what the source does, and nothing it does not:
|
|
3123
|
+
|
|
3124
|
+
- `-map -0:N` for an MP4/MOV chapter track. FFmpeg reads the QuickTime chapter text track as a
|
|
3125
|
+
data stream (codec tag `text`) and its muxer writes a new one from the chapters it is given;
|
|
3126
|
+
the copied one was written as a `gpmd` data track holding the old titles, so
|
|
3127
|
+
`metadata.py --clear-chapters` left them behind and every pass added a track (A173).
|
|
3128
|
+
- `-map 0:t? -c:t copy` into Matroska: a subtitle track's fonts are attachments, which no
|
|
3129
|
+
`-map 0:s?`/`0:d?` selects, so every tool that kept the subtitles dropped the fonts they are
|
|
3130
|
+
drawn with (A256). Other containers hold no attachments; source_carry reports them dropped.
|
|
3131
|
+
|
|
3132
|
+
Nothing when the source cannot be read here (the command then runs as before)."""
|
|
3133
|
+
if not src or not os.path.isfile(src):
|
|
3134
|
+
return []
|
|
3135
|
+
try:
|
|
3136
|
+
out = _ffprobe("-v", "error", "-show_entries", "stream=index,codec_type,codec_tag_string:chapter=id", "-of", "json", *input_format_args(src), file_arg(src)).stdout
|
|
3137
|
+
doc = json.loads(out or "{}")
|
|
3138
|
+
except (OSError, subprocess.TimeoutExpired, ValueError):
|
|
3139
|
+
return []
|
|
3140
|
+
streams = doc.get("streams") or []
|
|
3141
|
+
maps: List[str] = []
|
|
3142
|
+
if chapters and doc.get("chapters"):
|
|
3143
|
+
for s in streams:
|
|
3144
|
+
if s.get("codec_type") == "data" and str(s.get("codec_tag_string") or "").lower() == "text":
|
|
3145
|
+
maps += ["-map", f"-0:{s.get('index')}"]
|
|
3146
|
+
if attachments and os.path.splitext(output)[1].lower() in MATROSKA_EXT and any(s.get("codec_type") == "attachment" for s in streams):
|
|
3147
|
+
maps += ["-map", "0:t?", "-c:t", "copy"]
|
|
3148
|
+
return maps
|
|
3149
|
+
|
|
3150
|
+
|
|
3151
|
+
def fail_if_classified(proc: subprocess.CompletedProcess) -> None:
|
|
3152
|
+
"""Stop with a failed attempt's own error when ffmpeg named a cause a second encode would hit
|
|
3153
|
+
the same way (a full disk, a missing encoder or filter, an unreadable input): the rule
|
|
3154
|
+
run_keeping_subtitles() follows since #389, for every copy-then-re-encode or keep-then-drop
|
|
3155
|
+
fallback (#415). Returns when the failure is unclassified, so the caller's retry runs."""
|
|
3156
|
+
if proc.returncode != 0 and classify_ffmpeg_failure(proc.stderr or ""):
|
|
3157
|
+
_fail(proc.args, proc.returncode, proc.stderr or "")
|
|
3158
|
+
|
|
3159
|
+
|
|
3160
|
+
# eia_608 (a QuickTime c608 caption track) decodes to text, so it converts like one (ffmpeg 6.1)
|
|
3161
|
+
TEXT_SUBTITLES = frozenset({"mov_text", "subrip", "srt", "ass", "ssa", "webvtt", "text", "eia_608"})
|
|
3162
|
+
MP4_FAMILY = frozenset({"mp4", "m4v", "mov"})
|
|
3163
|
+
|
|
3164
|
+
|
|
3165
|
+
def subtitle_codec_for(codec: str, out_ext: str) -> str:
|
|
3166
|
+
"""The -c:s for one source subtitle stream going into a container with extension `out_ext`
|
|
3167
|
+
(no dot): copy when the container holds it as it is, else the container's own text format --
|
|
3168
|
+
mov_text in MPEG-4, srt in Matroska for a mov_text track, webvtt in WebM. A bitmap track is
|
|
3169
|
+
returned as copy; subtitle_container_holds() says whether that copy can work."""
|
|
3170
|
+
out_ext = out_ext.lstrip(".").lower()
|
|
3171
|
+
if out_ext == "mov" and codec == "eia_608":
|
|
3172
|
+
return "copy" # QuickTime holds a c608 track as it is; .mp4 has no tag for it
|
|
3173
|
+
if out_ext in MP4_FAMILY and codec in TEXT_SUBTITLES and codec != "mov_text":
|
|
3174
|
+
return "mov_text"
|
|
3175
|
+
if out_ext == "mkv" and codec == "mov_text":
|
|
3176
|
+
return "srt"
|
|
3177
|
+
if out_ext == "webm" and codec in TEXT_SUBTITLES and codec != "webvtt":
|
|
3178
|
+
return "webvtt"
|
|
3179
|
+
return "copy"
|
|
3180
|
+
|
|
3181
|
+
|
|
3182
|
+
def subtitle_container_holds(codec: str, out_ext: str) -> bool:
|
|
3183
|
+
"""Whether a subtitle stream of `codec` can be written to an `out_ext` container at all,
|
|
3184
|
+
converted by subtitle_codec_for() where it must be: Matroska takes any, MPEG-4 a text track or
|
|
3185
|
+
DVD bitmaps, WebM only text (as WebVTT)."""
|
|
3186
|
+
out_ext = out_ext.lstrip(".").lower()
|
|
3187
|
+
if out_ext in MP4_FAMILY:
|
|
3188
|
+
return codec in TEXT_SUBTITLES or codec == "dvd_subtitle"
|
|
3189
|
+
if out_ext == "webm":
|
|
3190
|
+
return codec in TEXT_SUBTITLES
|
|
3191
|
+
return True
|
|
3192
|
+
|
|
3193
|
+
|
|
3194
|
+
def default_selection_maps(meta: Optional[Dict[str, Any]], dst: str) -> List[str]:
|
|
3195
|
+
"""The -map arguments for a re-encode that would otherwise rely on ffmpeg's default stream
|
|
3196
|
+
selection: none for a file with one picture and one sound (the default picks those, and a
|
|
3197
|
+
subtitle stream the container can hold, as it always did), and with several, the picture
|
|
3198
|
+
and sound probe() describes plus the first subtitle stream when `dst`'s container can hold it
|
|
3199
|
+
-- what the default would have carried, without its largest-picture / most-channels choice
|
|
3200
|
+
(A258, #484 review)."""
|
|
3201
|
+
from _common.probe import probed_maps, several_av_streams # probe imports this module
|
|
3202
|
+
if not several_av_streams(meta):
|
|
3203
|
+
return []
|
|
3204
|
+
maps = probed_maps(meta)
|
|
3205
|
+
subs = (meta or {}).get("subtitle_stream_details") or []
|
|
3206
|
+
codec, ext = (subs[0].get("codec") or "") if subs else "", os.path.splitext(dst)[1]
|
|
3207
|
+
if subs and subtitle_container_holds(codec, ext):
|
|
3208
|
+
# with its own -c:s: the default subtitle encoder does not exist for every container
|
|
3209
|
+
# (none for MP4 in FFmpeg 6.1) and is a text encoder that cannot take a bitmap track
|
|
3210
|
+
maps += ["-map", "0:s:0", "-c:s", subtitle_codec_for(codec, ext)]
|
|
3211
|
+
return maps
|
|
3212
|
+
|
|
3213
|
+
|
|
3214
|
+
def subtitle_codec_args(src: Optional[str], output: str) -> List[str]:
|
|
3215
|
+
"""`-c:s` for a command that maps every subtitle stream of `src` (`-map 0:s?`) into `output`:
|
|
3216
|
+
copy, and for each text track in a format the container does not take as it is the container's
|
|
3217
|
+
own (subtitle_codec_for: mov_text in MP4/MOV, SubRip in Matroska for mov_text, WebVTT in WebM),
|
|
3218
|
+
as export.py and a crop of several tracks convert it. A plain copy of SubRip into MP4 failed,
|
|
3219
|
+
and the retry dropped the track (#520). Copy alone when the source cannot be read here."""
|
|
3220
|
+
args = ["-c:s", "copy"]
|
|
3221
|
+
if not src or not os.path.isfile(src):
|
|
3222
|
+
return args
|
|
3223
|
+
try:
|
|
3224
|
+
out = _ffprobe("-v", "error", "-select_streams", "s", "-show_entries", "stream=codec_name", "-of", "csv=p=0", *input_format_args(src), file_arg(src)).stdout
|
|
3225
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
3226
|
+
return args
|
|
3227
|
+
ext = os.path.splitext(output)[1]
|
|
3228
|
+
for n, codec in enumerate(ln.strip() for ln in (out or "").splitlines() if ln.strip()):
|
|
3229
|
+
conv = subtitle_codec_for(codec, ext)
|
|
3230
|
+
if conv != "copy":
|
|
3231
|
+
args += [f"-c:s:{n}", conv]
|
|
3232
|
+
return args
|
|
3233
|
+
|
|
3234
|
+
|
|
3235
|
+
def _non_av_kinds(src: Optional[str]) -> Optional[Dict[str, int]]:
|
|
3236
|
+
"""How many subtitle and data streams `src` holds ({"subtitle": n, "data": n}); None when it
|
|
3237
|
+
cannot be told (not a file here, or ffprobe failed), so the caller runs as for a source that
|
|
3238
|
+
has both."""
|
|
3239
|
+
if not src or not os.path.isfile(src):
|
|
3240
|
+
return None
|
|
3241
|
+
try:
|
|
3242
|
+
proc = _ffprobe("-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", *input_format_args(src), file_arg(src))
|
|
3243
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
3244
|
+
return None
|
|
3245
|
+
kinds = [ln.strip().strip(",") for ln in (proc.stdout or "").splitlines() if ln.strip()]
|
|
3246
|
+
if proc.returncode != 0 or not kinds:
|
|
3247
|
+
return None
|
|
3248
|
+
return {"subtitle": kinds.count("subtitle"), "data": kinds.count("data")}
|
|
3249
|
+
|
|
3250
|
+
|
|
3251
|
+
def run_keeping_subtitles(cmd: List[str], output: str, relabel_timecode: bool = False) -> bool:
|
|
3252
|
+
"""Run an ffmpeg command that already maps its video/audio, trying first to also keep the
|
|
3253
|
+
subtitle and data streams the source has (`-map 0:s?`/`0:d?` are no-ops when there are
|
|
3254
|
+
none): a text track converted to the container's own format where it needs it
|
|
3255
|
+
(subtitle_codec_args), everything else stream-copied. `cmd` is the full argv *without* the
|
|
3256
|
+
output path.
|
|
3257
|
+
|
|
3258
|
+
A stream the container refuses fails that attempt, and the tool never touched it, so the
|
|
3259
|
+
command is run again without it rather than failed. The rungs are export.py's
|
|
3260
|
+
(_run_keeping_non_av): subtitles and data, then the subtitles alone, then neither. A refused
|
|
3261
|
+
data stream (a timecode track into Matroska, and on FFmpeg 6.1.1 a copied tmcd track into
|
|
3262
|
+
MP4) so no longer costs the subtitles beside it (#539); the last rung is left for a track no
|
|
3263
|
+
conversion fits (a bitmap track in MPEG-4). A rung is tried only when the source has what it
|
|
3264
|
+
drops, so a source with one kind of stream is encoded twice at most, as before.
|
|
3265
|
+
|
|
3266
|
+
Returns True when a subtitle or data stream of the source is not in the output: always after
|
|
3267
|
+
the last rung, and after the data-only rung unless the written file holds as many data
|
|
3268
|
+
streams as the source (the MOV/MP4 muxer writes a timecode track of its own from the picture's
|
|
3269
|
+
timecode tag, so the track that could not be copied is there all the same; read back, as
|
|
3270
|
+
export.py does).
|
|
3271
|
+
|
|
3272
|
+
Each retry is recorded with the failed attempt's error (`diagnostics.fallbacks`,
|
|
3273
|
+
`non_av_streams_dropped`, `dropped`: the stream types that retry leaves out): the caller's
|
|
3274
|
+
`dropped_non_av_streams` says that streams went, the record says which and why, which is the
|
|
3275
|
+
only way to tell a container that cannot hold them from an attempt that failed for another
|
|
3276
|
+
reason and happened to succeed the next time.
|
|
3277
|
+
|
|
3278
|
+
`relabel_timecode`: the command writes its own start timecode (timeline.output_timecode_args),
|
|
3279
|
+
so a source's tmcd data track is not copied -- its label, at the source's rate, would win over
|
|
3280
|
+
the new one; the MOV/MP4 muxer builds the track again from the label."""
|
|
3281
|
+
# a command that writes its own label (a -metadata:s:v:0 timecode=...) relabels whoever built it
|
|
3282
|
+
relabel_timecode = relabel_timecode or any(a.startswith("timecode=") for a in cmd)
|
|
3283
|
+
skip_tmcd = ["-map", "-0:d:m:timecode"] if relabel_timecode else []
|
|
3284
|
+
src = next(iter(shape_of(cmd).inputs), None)
|
|
3285
|
+
sub_args = ["-map", "0:s?"] + carried_stream_maps(src, output, chapters=False) + subtitle_codec_args(src, output)
|
|
3286
|
+
data_args = ["-map", "0:d?"] + skip_tmcd + carried_stream_maps(src, output, attachments=False) + ["-c:d", "copy"]
|
|
3287
|
+
first = run(cmd + sub_args + data_args + [output], check=False)
|
|
3288
|
+
if first.returncode == 0:
|
|
3289
|
+
return False
|
|
3290
|
+
if classify_ffmpeg_failure(first.stderr or "") or not _has_non_av_streams(cmd):
|
|
3291
|
+
# a full disk, a missing encoder or an unreadable input fails the second encode the same
|
|
3292
|
+
# way: report the first failure rather than run the whole encode again and blame streams
|
|
3293
|
+
# the source may not even have
|
|
3294
|
+
_fail(first.args, first.returncode, first.stderr or "")
|
|
3295
|
+
kinds = _non_av_kinds(src)
|
|
3296
|
+
both = kinds is None or (kinds["subtitle"] > 0 and kinds["data"] > 0)
|
|
3297
|
+
attempt = first
|
|
3298
|
+
if both:
|
|
3299
|
+
_record_non_av_retry(attempt, output, ["data"])
|
|
3300
|
+
attempt = run(cmd + sub_args + [output], check=False)
|
|
3301
|
+
if attempt.returncode == 0:
|
|
3302
|
+
if STATE.dry_run or kinds is None:
|
|
3303
|
+
return True
|
|
3304
|
+
written = _non_av_kinds(output)
|
|
3305
|
+
return written is None or written["data"] < kinds["data"]
|
|
3306
|
+
fail_if_classified(attempt)
|
|
3307
|
+
_record_non_av_retry(attempt, output, [k for k in ("subtitle", "data") if kinds is None or kinds[k]] or ["subtitle", "data"])
|
|
3308
|
+
run(cmd + [output])
|
|
3309
|
+
return True
|
|
3310
|
+
|
|
3311
|
+
|
|
3312
|
+
def _record_non_av_retry(attempt: subprocess.CompletedProcess, output: str, going: List[str]) -> None:
|
|
3313
|
+
"""The `non_av_streams_dropped` fallback of one failed rung of run_keeping_subtitles():
|
|
3314
|
+
`going` is what the next attempt leaves out."""
|
|
3315
|
+
error = " | ".join([ln.strip() for ln in (attempt.stderr or "").splitlines() if ln.strip()][-3:])[-500:]
|
|
3316
|
+
record_fallback(f"the {' and '.join(going)} stream(s) could not be written into {os.path.basename(output)} "
|
|
3317
|
+
f"({error or 'ffmpeg exit ' + str(attempt.returncode)}); encoding again without them",
|
|
3318
|
+
"non_av_streams_dropped", output=output, returncode=attempt.returncode, error=error, dropped=list(going))
|
|
3319
|
+
|
|
3320
|
+
|
|
3321
|
+
def _limit_for(cmd: Sequence[str]) -> Optional[float]:
|
|
3322
|
+
"""The wall-clock ceiling for this command: ffprobe (and other read-only probes) get a short
|
|
3323
|
+
one, PROBE_TIMEOUT or --timeout when that is lower (as _read_ff_list() does: a caller's
|
|
3324
|
+
--timeout 2 bounds every child, #415), ffmpeg the configured one; None means unlimited."""
|
|
3325
|
+
if not _is_ffmpeg(cmd):
|
|
3326
|
+
return min(PROBE_TIMEOUT, STATE.timeout) if STATE.timeout else None
|
|
3327
|
+
return STATE.timeout or None
|
|
3328
|
+
|
|
3329
|
+
|
|
3330
|
+
def _die_with_parent() -> None:
|
|
3331
|
+
"""Linux: have the kernel SIGKILL this child when the tool that started it dies, even by
|
|
3332
|
+
SIGKILL (which no handler can catch). Without it a tool killed by an agent's time limit left
|
|
3333
|
+
ffmpeg running orphaned, writing the output under its final name after the caller had been
|
|
3334
|
+
told the run failed. macOS and Windows have no equivalent; SIGTERM/SIGINT are handled there
|
|
3335
|
+
as everywhere (`kind: interrupted`, the child stopped)."""
|
|
3336
|
+
try:
|
|
3337
|
+
import ctypes
|
|
3338
|
+
ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, 9) # PR_SET_PDEATHSIG, SIGKILL
|
|
3339
|
+
except Exception: # noqa: BLE001 - best effort; a child without it is what every other OS gets
|
|
3340
|
+
pass
|
|
3341
|
+
|
|
3342
|
+
|
|
3343
|
+
def child_kwargs() -> Dict[str, Any]:
|
|
3344
|
+
"""Extra Popen arguments for an ffmpeg/ffprobe child (see _die_with_parent)."""
|
|
3345
|
+
# no child reads this process's stdin: under the MCP server that is the client's JSON-RPC pipe (#664)
|
|
3346
|
+
return dict({"preexec_fn": _die_with_parent} if sys.platform.startswith("linux") else {}, stdin=subprocess.DEVNULL)
|
|
3347
|
+
|
|
3348
|
+
|
|
3349
|
+
def _run_captured(cmd: List[str]) -> subprocess.CompletedProcess:
|
|
3350
|
+
"""Plain run with stdout/stderr captured."""
|
|
3351
|
+
limit = _limit_for(cmd)
|
|
3352
|
+
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace",
|
|
3353
|
+
**child_kwargs())
|
|
3354
|
+
_watch(child, cmd)
|
|
3355
|
+
try:
|
|
3356
|
+
out, err = child.communicate(timeout=limit)
|
|
3357
|
+
except subprocess.TimeoutExpired:
|
|
3358
|
+
child.kill()
|
|
3359
|
+
child.communicate()
|
|
3360
|
+
_unwatch(child)
|
|
3361
|
+
_timed_out(cmd, limit or 0)
|
|
3362
|
+
finally:
|
|
3363
|
+
_unwatch(child)
|
|
3364
|
+
return subprocess.CompletedProcess(list(cmd), child.returncode, out, err)
|
|
3365
|
+
|
|
3366
|
+
|
|
3367
|
+
def _progress_line(done: float, total: float, elapsed: float) -> str:
|
|
3368
|
+
if total > 0:
|
|
3369
|
+
pct = min(99.9, done / total * 100)
|
|
3370
|
+
eta = (elapsed / pct * (100 - pct)) if pct > 0.5 else 0
|
|
3371
|
+
return f"\r {pct:5.1f}% {done:7.1f}s / {total:.1f}s ETA {eta:4.0f}s"
|
|
3372
|
+
return f"\r {done:7.1f}s encoded"
|
|
3373
|
+
|
|
3374
|
+
|
|
3375
|
+
def _run_with_progress(cmd: List[str]) -> subprocess.CompletedProcess:
|
|
3376
|
+
"""Run ffmpeg with -progress on a pipe and print percent/ETA to stderr.
|
|
3377
|
+
|
|
3378
|
+
The time limit is checked on a clock, not per progress line: a deadlocked ffmpeg (the very
|
|
3379
|
+
case --timeout exists for) prints nothing, so a loop that only looked at the deadline when a
|
|
3380
|
+
line arrived waited on it forever. Reader threads drain both pipes; the main loop wakes at
|
|
3381
|
+
least twice a second to compare the clock against the limit."""
|
|
3382
|
+
import queue
|
|
3383
|
+
import threading
|
|
3384
|
+
import time
|
|
3385
|
+
total = STATE.duration_hint or 0.0
|
|
3386
|
+
full = cmd[:1] + ["-progress", "pipe:1", "-nostats"] + cmd[1:]
|
|
3387
|
+
t0 = time.time()
|
|
3388
|
+
limit = _limit_for(cmd)
|
|
3389
|
+
proc = subprocess.Popen(full, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace",
|
|
3390
|
+
**child_kwargs())
|
|
3391
|
+
_watch(proc, cmd)
|
|
3392
|
+
assert proc.stdout is not None and proc.stderr is not None
|
|
3393
|
+
lines: "queue.Queue[Optional[str]]" = queue.Queue()
|
|
3394
|
+
err_chunks: List[str] = []
|
|
3395
|
+
|
|
3396
|
+
def pump_out() -> None:
|
|
3397
|
+
for line in proc.stdout: # type: ignore[union-attr]
|
|
3398
|
+
lines.put(line)
|
|
3399
|
+
lines.put(None)
|
|
3400
|
+
|
|
3401
|
+
def pump_err() -> None:
|
|
3402
|
+
err_chunks.append(proc.stderr.read()) # type: ignore[union-attr]
|
|
3403
|
+
|
|
3404
|
+
threading.Thread(target=pump_out, daemon=True).start()
|
|
3405
|
+
err_thread = threading.Thread(target=pump_err, daemon=True)
|
|
3406
|
+
err_thread.start()
|
|
3407
|
+
last = ""
|
|
3408
|
+
mcp_progress = os.environ.get(MCP_PROGRESS_ENV) == "1"
|
|
3409
|
+
|
|
3410
|
+
def clear_line() -> None:
|
|
3411
|
+
if last and not mcp_progress:
|
|
3412
|
+
sys.stderr.write("\r" + " " * len(last) + "\r")
|
|
3413
|
+
|
|
3414
|
+
def timed_out() -> None:
|
|
3415
|
+
proc.kill()
|
|
3416
|
+
proc.wait()
|
|
3417
|
+
clear_line()
|
|
3418
|
+
_timed_out(cmd, limit or 0)
|
|
3419
|
+
|
|
3420
|
+
while True:
|
|
3421
|
+
remaining = (limit - (time.time() - t0)) if limit else None
|
|
3422
|
+
if remaining is not None and remaining <= 0:
|
|
3423
|
+
timed_out()
|
|
3424
|
+
try:
|
|
3425
|
+
line = lines.get(timeout=min(0.5, remaining) if remaining is not None else 0.5)
|
|
3426
|
+
except queue.Empty:
|
|
3427
|
+
continue
|
|
3428
|
+
if line is None:
|
|
3429
|
+
break
|
|
3430
|
+
if line.startswith("out_time_us=") or line.startswith("out_time_ms="):
|
|
3431
|
+
try:
|
|
3432
|
+
done = int(line.split("=")[1]) / 1_000_000
|
|
3433
|
+
except ValueError:
|
|
3434
|
+
continue
|
|
3435
|
+
msg = _progress_line(done, total, time.time() - t0)
|
|
3436
|
+
if msg != last:
|
|
3437
|
+
if mcp_progress:
|
|
3438
|
+
message = msg.strip() if total > 0 else f"{max(0.0, done):.1f}s processed"
|
|
3439
|
+
_relay_progress(message)
|
|
3440
|
+
else:
|
|
3441
|
+
sys.stderr.write(msg)
|
|
3442
|
+
sys.stderr.flush()
|
|
3443
|
+
last = msg
|
|
3444
|
+
try:
|
|
3445
|
+
proc.wait(timeout=(max(5.0, limit - (time.time() - t0)) if limit else None))
|
|
3446
|
+
except subprocess.TimeoutExpired:
|
|
3447
|
+
timed_out()
|
|
3448
|
+
_unwatch(proc)
|
|
3449
|
+
err_thread.join()
|
|
3450
|
+
err = "".join(err_chunks)
|
|
3451
|
+
clear_line()
|
|
3452
|
+
return subprocess.CompletedProcess(full, proc.returncode, "", err)
|
|
3453
|
+
|
|
3454
|
+
|
|
3455
|
+
def shell_quote(s: str) -> str:
|
|
3456
|
+
"""One argument as a POSIX shell word, so a printed command can be pasted and run again.
|
|
3457
|
+
Anything outside a known-safe set is single-quoted: the old deny-list left a backtick, `!`, a
|
|
3458
|
+
leading `#` or `~` and non-ASCII bare, and a shell ran `x`id`.mp4`'s backtick as a command
|
|
3459
|
+
and dropped `#tag.mp4` (and everything after it) as a comment."""
|
|
3460
|
+
if s and _SHELL_SAFE.fullmatch(s):
|
|
3461
|
+
return s
|
|
3462
|
+
return "'" + s.replace("'", "'\\''") + "'"
|
|
3463
|
+
|
|
3464
|
+
|
|
3465
|
+
_SHELL_SAFE = re.compile(r"[A-Za-z0-9_@%+=:,./-]+")
|
|
3466
|
+
|
|
3467
|
+
|
|
3468
|
+
def ffmpeg_base(overwrite: bool = True) -> List[str]:
|
|
3469
|
+
cmd = [require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin"]
|
|
3470
|
+
cmd.append("-y" if overwrite else "-n")
|
|
3471
|
+
return cmd
|
|
3472
|
+
|
|
3473
|
+
|
|
3474
|
+
def place_output(src: str, dst: str, move: bool = False) -> None:
|
|
3475
|
+
"""Deliver an already-rendered file to `dst` under the same rules as an ffmpeg output:
|
|
3476
|
+
the path is checked, the output's lock is held (as run() holds it for an ffmpeg write), an
|
|
3477
|
+
existing file is only replaced through a sibling temp so a failed copy never costs the
|
|
3478
|
+
caller what was there, and the result is remembered as ours. render.py's final
|
|
3479
|
+
`copyfile()` used to bypass all of them.
|
|
3480
|
+
|
|
3481
|
+
`move`: `src` is a temp file the caller wrote next to `dst` (sibling_temp), renamed into place
|
|
3482
|
+
with os.replace() under the lock instead of copied -- a checked `cut.py --segments` join was
|
|
3483
|
+
copied whole, about 2 s for 240 MB. A rename that fails (another filesystem) falls back to
|
|
3484
|
+
the copy."""
|
|
3485
|
+
cmd = ["ffmpeg", dst]
|
|
3486
|
+
_check_output_path(cmd)
|
|
3487
|
+
_check_existing_output(cmd)
|
|
3488
|
+
d, base = os.path.split(dst)
|
|
3489
|
+
stem, ext = os.path.splitext(base)
|
|
3490
|
+
with _OutputLock(dst):
|
|
3491
|
+
copied = stream_copy_output(STATE, src)
|
|
3492
|
+
# under the lock: the target the check above decided about, not one put there since
|
|
3493
|
+
# (`src` is the caller's to remove, as on every other refusal)
|
|
3494
|
+
refuse_changed_output(dst)
|
|
3495
|
+
if move:
|
|
3496
|
+
try:
|
|
3497
|
+
os.replace(src, dst)
|
|
3498
|
+
_remember_output(cmd)
|
|
3499
|
+
if copied and (identity := owned_identity(dst)):
|
|
3500
|
+
STATE._stream_copy_outputs[_checked_key(dst)] = identity
|
|
3501
|
+
return
|
|
3502
|
+
except OSError:
|
|
3503
|
+
pass
|
|
3504
|
+
tmp = None
|
|
3505
|
+
try:
|
|
3506
|
+
tmp = copy_to_sibling(src, dst)
|
|
3507
|
+
refuse_changed_output(dst, lambda: _remove_quietly(tmp))
|
|
3508
|
+
os.replace(tmp, dst)
|
|
3509
|
+
except OSError as e:
|
|
3510
|
+
if tmp:
|
|
3511
|
+
try:
|
|
3512
|
+
os.remove(tmp)
|
|
3513
|
+
except OSError:
|
|
3514
|
+
pass
|
|
3515
|
+
die(f"could not place {dst}: {e}", kind="output")
|
|
3516
|
+
_remember_output(cmd)
|
|
3517
|
+
if copied and (identity := owned_identity(dst)):
|
|
3518
|
+
STATE._stream_copy_outputs[_checked_key(dst)] = identity
|
|
3519
|
+
|
|
3520
|
+
|
|
3521
|
+
# extensions ffmpeg can open through the image2 demuxer, the only one that expands `%d` in a name
|
|
3522
|
+
# and the only one that has a `pattern_type` option (gif, avif, mp4... reject it: "Option
|
|
3523
|
+
# pattern_type not found")
|
|
3524
|
+
_IMAGE2_EXT = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff", ".dpx", ".exr", ".tga",
|
|
3525
|
+
".ppm", ".pgm", ".pbm", ".pam", ".sgi", ".jp2", ".j2k", ".xbm", ".xpm", ".pcx", ".qoi")
|
|
3526
|
+
|
|
3527
|
+
|
|
3528
|
+
def still_input_args(path: str) -> List[str]:
|
|
3529
|
+
"""`-f image2 -pattern_type none` for a still with an image extension whose path has a `%` in
|
|
3530
|
+
it (#408): image2 otherwise reads `logo%d.png` as a numbered sequence and opens `logo1.png`, a
|
|
3531
|
+
file the run's guards and fingerprints never looked at. The demuxer is named because FFmpeg
|
|
3532
|
+
chooses image2 by itself only for a name it reads as a pattern: `a%20b.png` and `50%.png` are
|
|
3533
|
+
opened by png_pipe (jpeg_pipe, ...), which has no `pattern_type` and failed with "Option
|
|
3534
|
+
pattern_type not found" (#558; measured on 6.1.1 for every extension above that it writes).
|
|
3535
|
+
Forced, image2 takes the codec from the extension and reads the one file of that name. Empty
|
|
3536
|
+
for every other path, a video or a GIF with a `%` in its name included: their demuxers never
|
|
3537
|
+
expand it and reject the option."""
|
|
3538
|
+
p = str(path)
|
|
3539
|
+
if "%" in p and os.path.splitext(p)[1].lower() in _IMAGE2_EXT:
|
|
3540
|
+
return ["-f", "image2", "-pattern_type", "none"]
|
|
3541
|
+
return []
|
|
3542
|
+
|
|
3543
|
+
|
|
3544
|
+
def file_arg(path: Any) -> str:
|
|
3545
|
+
"""`path` as an argument a command line reads as a file: a relative name starting with a
|
|
3546
|
+
dash is written `./name` (#558). ffprobe, whose input is a bare argument, read `-report` and
|
|
3547
|
+
`-dash.mp4` as options ("You have to specify one input file", and a log file written beside
|
|
3548
|
+
the caller). The name itself is unchanged everywhere else (documents, messages, guards)."""
|
|
3549
|
+
p = str(path)
|
|
3550
|
+
return "./" + p if p.startswith("-") and p != "-" else p
|
|
3551
|
+
|
|
3552
|
+
|
|
3553
|
+
def guard_input_names(cmd: Sequence[str]) -> List[str]:
|
|
3554
|
+
"""`cmd` with every input named so that ffmpeg and ffprobe read it as that one file: an input
|
|
3555
|
+
whose name starts with a dash is written `./name` (file_arg(): each `-i` value of an ffmpeg
|
|
3556
|
+
command, and the last argument of an ffprobe one when a file of that name exists, which tells
|
|
3557
|
+
it from an option), then guard_input_formats(). run() and run_analysis() apply it to every
|
|
3558
|
+
command, and so do the frame readers and stream checks that start their own process."""
|
|
3559
|
+
cmd = [str(a) for a in cmd]
|
|
3560
|
+
base = os.path.basename(cmd[0]) if cmd else ""
|
|
3561
|
+
if base.startswith("ffprobe"):
|
|
3562
|
+
if len(cmd) > 1 and cmd[-1].startswith("-") and cmd[-1] != "-" and os.path.lexists(cmd[-1]):
|
|
3563
|
+
cmd[-1] = file_arg(cmd[-1])
|
|
3564
|
+
elif base.startswith("ffmpeg"):
|
|
3565
|
+
for i in range(1, len(cmd) - 1):
|
|
3566
|
+
if cmd[i] == "-i":
|
|
3567
|
+
cmd[i + 1] = file_arg(cmd[i + 1])
|
|
3568
|
+
return guard_input_formats(cmd)
|
|
3569
|
+
|
|
3570
|
+
|
|
3571
|
+
def riff_wave_args(path: str) -> List[str]:
|
|
3572
|
+
"""Select WAV from its RIFF/WAVE header (#518). FFmpeg 9.0.2 can otherwise
|
|
3573
|
+
mistake ordinary PCM for MPEG-TS."""
|
|
3574
|
+
if looks_like_url(path) or not os.path.isfile(path):
|
|
3575
|
+
return []
|
|
3576
|
+
try:
|
|
3577
|
+
with open(path, "rb") as fh:
|
|
3578
|
+
head = fh.read(12)
|
|
3579
|
+
except OSError:
|
|
3580
|
+
return []
|
|
3581
|
+
return ["-f", "wav"] if head[:4] == b"RIFF" and head[8:12] == b"WAVE" else []
|
|
3582
|
+
|
|
3583
|
+
|
|
3584
|
+
def input_format_args(path: str) -> List[str]:
|
|
3585
|
+
return riff_wave_args(path) or still_input_args(path)
|
|
3586
|
+
|
|
3587
|
+
|
|
3588
|
+
def guard_input_formats(cmd: Sequence[str]) -> List[str]:
|
|
3589
|
+
"""Use literal still paths and RIFF/WAVE headers for implicit inputs.
|
|
3590
|
+
|
|
3591
|
+
FFmpeg input options belong to each `-i`. The ffprobe calls without `-i`
|
|
3592
|
+
put the input path last. Keep any explicitly selected input format.
|
|
3593
|
+
"""
|
|
3594
|
+
cmd = [str(a) for a in cmd]
|
|
3595
|
+
base = os.path.basename(cmd[0]) if cmd else ""
|
|
3596
|
+
if base.startswith("ffprobe") and "-i" not in cmd[1:-1]:
|
|
3597
|
+
if "-pattern_type" not in cmd[:-1] and "-f" not in cmd[:-1]:
|
|
3598
|
+
return cmd[:-1] + input_format_args(cmd[-1]) + cmd[-1:]
|
|
3599
|
+
return cmd
|
|
3600
|
+
if not base.startswith(("ffmpeg", "ffprobe")):
|
|
3601
|
+
return cmd
|
|
3602
|
+
out: List[str] = []
|
|
3603
|
+
since = 0 # where the current input's options start in `out`
|
|
3604
|
+
i = 0
|
|
3605
|
+
while i < len(cmd):
|
|
3606
|
+
a = cmd[i]
|
|
3607
|
+
if a == "-i" and i + 1 < len(cmd):
|
|
3608
|
+
opts = out[since:]
|
|
3609
|
+
if "-pattern_type" not in opts and "-f" not in opts:
|
|
3610
|
+
out += input_format_args(cmd[i + 1])
|
|
3611
|
+
out += [a, cmd[i + 1]]
|
|
3612
|
+
since = len(out)
|
|
3613
|
+
i += 2
|
|
3614
|
+
continue
|
|
3615
|
+
out.append(a)
|
|
3616
|
+
i += 1
|
|
3617
|
+
return out
|
|
3618
|
+
|
|
3619
|
+
|
|
3620
|
+
def sibling_temp(dst: str, tag: str) -> str:
|
|
3621
|
+
"""A hidden path next to `dst`, with its extension (the muxer is chosen by it), for a file
|
|
3622
|
+
place_output(..., move=True) renames into place: same directory, so the rename never
|
|
3623
|
+
crosses a filesystem."""
|
|
3624
|
+
d, base = os.path.split(dst)
|
|
3625
|
+
stem, ext = os.path.splitext(base)
|
|
3626
|
+
path = os.path.join(d, f".{stem}.ffskill-{tag}-{os.getpid()}{ext}")
|
|
3627
|
+
n = 1
|
|
3628
|
+
while os.path.lexists(path): # a leftover of an earlier run with this pid: not ours to replace
|
|
3629
|
+
n += 1
|
|
3630
|
+
path = os.path.join(d, f".{stem}.ffskill-{tag}-{os.getpid()}-{n}{ext}")
|
|
3631
|
+
return path
|
|
3632
|
+
|
|
3633
|
+
|
|
3634
|
+
_DRAWTEXT_TMPDIR: "Optional[str]" = None
|
|
3635
|
+
|
|
3636
|
+
|
|
3637
|
+
_DRAWTEXT_PENDING: "Dict[str, str]" = {}
|
|
3638
|
+
|
|
3639
|
+
|
|
3640
|
+
def _drawtext_tmpdir(create: bool = True) -> str:
|
|
3641
|
+
"""The private, per-run directory drawn-text files live in.
|
|
3642
|
+
|
|
3643
|
+
tempfile.mkdtemp() creates it 0700 under a name nobody can guess, which is the whole point:
|
|
3644
|
+
the 1.15.0 shape (a fixed, world-writable `/tmp/ffmpeg-skill-text` entered with
|
|
3645
|
+
makedirs(exist_ok=True) and content-addressed filenames) let any other user on the machine
|
|
3646
|
+
pre-create the directory or plant a symlink at a predictable name, and handed the second
|
|
3647
|
+
user of a shared box a PermissionError out of filter construction instead of a `kind: input`
|
|
3648
|
+
refusal. The directory is removed when the process ends, whether it succeeded or failed.
|
|
3649
|
+
"""
|
|
3650
|
+
global _DRAWTEXT_TMPDIR
|
|
3651
|
+
import tempfile
|
|
3652
|
+
if _DRAWTEXT_TMPDIR and os.path.isdir(_DRAWTEXT_TMPDIR):
|
|
3653
|
+
return _DRAWTEXT_TMPDIR
|
|
3654
|
+
if not create:
|
|
3655
|
+
# --dry-run names the path it WOULD use and creates nothing (a dry run writes nothing).
|
|
3656
|
+
return os.path.join(tempfile.gettempdir(), "ffmpeg-skill-text-%d" % os.getpid())
|
|
3657
|
+
import atexit
|
|
3658
|
+
_DRAWTEXT_TMPDIR = tempfile.mkdtemp(prefix="ffmpeg-skill-text-")
|
|
3659
|
+
atexit.register(shutil.rmtree, _DRAWTEXT_TMPDIR, True)
|
|
3660
|
+
return _DRAWTEXT_TMPDIR
|
|
3661
|
+
|
|
3662
|
+
|
|
3663
|
+
def declare_time_map(how: str) -> None:
|
|
3664
|
+
"""A tool that changes the output's length says how its time-bearing items follow: "mapped"
|
|
3665
|
+
(with_mapped_chapters did it) or why FFmpeg's own handling is right ("input seek": FFmpeg
|
|
3666
|
+
moves chapters with an input -ss; "clipped": the output keeps the source's clock and only ends
|
|
3667
|
+
earlier or later). Without it, emit's source_carry says chapters_not_retimed whenever the
|
|
3668
|
+
length changed (the guard for the time class, docs/defect-guards.json)."""
|
|
3669
|
+
STATE.time_mapped = how
|
|
3670
|
+
|
|
3671
|
+
|
|
3672
|
+
def segments_map(segments: "Sequence[Tuple[float, float]]") -> "Callable[[float], float]":
|
|
3673
|
+
"""The time map of a join of `segments` of one source (cut --segments/--remove, silence): a
|
|
3674
|
+
source time inside a kept range lands at that range's place in the output; a removed time
|
|
3675
|
+
collapses onto the join, so a chapter wholly inside a removed range is left with no length."""
|
|
3676
|
+
return lambda t: sum(min(max(t - s, 0.0), e - s) for s, e in segments)
|
|
3677
|
+
|
|
3678
|
+
|
|
3679
|
+
def with_mapped_chapters(cmd: "List[str]", meta: "Optional[Dict[str, Any]]", to_output: "Callable[[float], float]",
|
|
3680
|
+
length: "Optional[float]") -> "List[str]":
|
|
3681
|
+
"""`cmd` (without its output path) with the source's chapters moved onto the output's clock:
|
|
3682
|
+
FFmpeg copies them as they were, so pad --start, a speed change, a reverse, a hold or a speed
|
|
3683
|
+
ramp left them where the source had them (#470). `to_output` maps a source time to the
|
|
3684
|
+
output's; each chapter is clipped to [0, length] and one left with no length is dropped. The
|
|
3685
|
+
chapters go in as an ffmetadata input of their own, written into the run's private temp
|
|
3686
|
+
directory when the command runs (flush_drawtext_textfiles), so a dry run writes nothing."""
|
|
3687
|
+
chapters = (meta or {}).get("chapters") or []
|
|
3688
|
+
declare_time_map("mapped")
|
|
3689
|
+
if not chapters or "-map_chapters" in cmd:
|
|
3690
|
+
return cmd
|
|
3691
|
+
mapped = []
|
|
3692
|
+
for c in chapters:
|
|
3693
|
+
a, b = sorted((to_output(float(c["start"] or 0.0)), to_output(float(c["end"] or 0.0))))
|
|
3694
|
+
a, b = max(a, 0.0), min(b, length) if length else b
|
|
3695
|
+
if b - a >= 0.0005:
|
|
3696
|
+
mapped.append((a, b, c.get("title") or ""))
|
|
3697
|
+
esc = lambda v: "".join("\\" + ch if ch in "=;#\\\n" else ch for ch in v)
|
|
3698
|
+
body = ";FFMETADATA1\n" + "".join(f"[CHAPTER]\nTIMEBASE=1/1000\nSTART={round(a * 1000)}\nEND={round(b * 1000)}\ntitle={esc(t)}\n"
|
|
3699
|
+
for a, b, t in sorted(mapped))
|
|
3700
|
+
path = os.path.join(_drawtext_tmpdir(create=not STATE.dry_run), f"chapters-{os.getpid()}-{len(_DRAWTEXT_PENDING)}.ffmeta")
|
|
3701
|
+
_DRAWTEXT_PENDING[path] = body
|
|
3702
|
+
last = max(i for i, a in enumerate(cmd) if a == "-i")
|
|
3703
|
+
n = sum(1 for a in cmd if a == "-i")
|
|
3704
|
+
return cmd[:last + 2] + ["-f", "ffmetadata", "-i", path] + cmd[last + 2:] + ["-map_chapters", str(n)]
|
|
3705
|
+
|
|
3706
|
+
|
|
3707
|
+
def flush_drawtext_textfiles(cmd: "Sequence[str]") -> "List[str]":
|
|
3708
|
+
"""Write the drawn-text files this command actually names, and return their paths.
|
|
3709
|
+
|
|
3710
|
+
The text is registered when the filter STRING is built, but a filter string is not a run:
|
|
3711
|
+
graphics.py builds the drawtext graph even on a job that is finally rendered through libass,
|
|
3712
|
+
and every tool builds one under --dry-run. Writing here -- from run(), past the dry-run
|
|
3713
|
+
return, against the command that is about to be executed -- is what keeps both of those from
|
|
3714
|
+
leaving a file behind.
|
|
3715
|
+
"""
|
|
3716
|
+
if not _DRAWTEXT_PENDING:
|
|
3717
|
+
return []
|
|
3718
|
+
joined = " ".join(str(a) for a in cmd)
|
|
3719
|
+
written = []
|
|
3720
|
+
for path, body in list(_DRAWTEXT_PENDING.items()):
|
|
3721
|
+
# match on the unique file name, not the full path: inside a filter string the path is
|
|
3722
|
+
# escaped (a Windows drive colon becomes `C\\:`, and the separators are forward slashes),
|
|
3723
|
+
# so the registered spelling never appears verbatim in the command
|
|
3724
|
+
if os.path.basename(path) not in joined or os.path.exists(path):
|
|
3725
|
+
continue
|
|
3726
|
+
# O_NOFOLLOW exists on POSIX only; the directory is private (mkdtemp, 0700) so the
|
|
3727
|
+
# symlink guard is belt and braces there and unavailable on Windows
|
|
3728
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
|
|
3729
|
+
fd = os.open(path, flags, 0o600)
|
|
3730
|
+
# newline="\n": text mode would write each kept line break as CRLF on Windows, and
|
|
3731
|
+
# drawtext from FFmpeg 6.1 draws that as a blank line plus a line break
|
|
3732
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
|
|
3733
|
+
fh.write(body)
|
|
3734
|
+
written.append(path)
|
|
3735
|
+
return written
|
|
3736
|
+
|
|
3737
|
+
|
|
3738
|
+
def ffmpeg_encoders() -> set:
|
|
3739
|
+
"""Names from `ffmpeg -encoders` -- the build that will run the encode -- read once; empty when
|
|
3740
|
+
it cannot be read. Used to pick an AV1 encoder, to refuse --codec av1 / prores before ffmpeg
|
|
3741
|
+
would, and to see whether --hw's VideoToolbox encoders are built in.
|
|
3742
|
+
|
|
3743
|
+
Under --dry-run only, the list comes from `ffprobe -encoders` instead: a dry run promises
|
|
3744
|
+
never to run ffmpeg (docs/contract.md: ffmpeg_execution "none") while ffprobe always may, as in
|
|
3745
|
+
ffmpeg_version(). That is the one case for ffprobe. On a mixed install (a Homebrew ffprobe next
|
|
3746
|
+
to a static ffmpeg) its list is another build's, so a real run never uses it: the AV1/ProRes
|
|
3747
|
+
refusals and the VideoToolbox check must describe the binary that encodes, and a plan that
|
|
3748
|
+
read ffprobe's list is re-decided against ffmpeg's when it runs.
|
|
3749
|
+
|
|
3750
|
+
An empty list is not "this build has none": when the list could not be read (the binary did
|
|
3751
|
+
not run, timed out, exited non-zero, or printed nothing a list is made of), the reason is kept
|
|
3752
|
+
(ffmpeg_list_error("encoders")) and recorded once as a `ffmpeg_list_unreadable` warning, so a
|
|
3753
|
+
refusal or a CPU note built on the empty set names the read failure, not a missing encoder."""
|
|
3754
|
+
global _ENCODERS
|
|
3755
|
+
if _ENCODERS is None:
|
|
3756
|
+
_ENCODERS = _read_ff_list("-encoders", _ENCODER_ROW)
|
|
3757
|
+
return _ENCODERS
|
|
3758
|
+
|
|
3759
|
+
|
|
3760
|
+
def ffmpeg_bsfs() -> set:
|
|
3761
|
+
"""Names from `ffmpeg -bsfs`, read once, empty when it cannot be read (the reason is kept and
|
|
3762
|
+
recorded as ffmpeg_encoders() keeps it); from ffprobe under --dry-run, for the reason
|
|
3763
|
+
ffmpeg_encoders() gives. color.py --retag rewrites an H.264/HEVC stream's colour description
|
|
3764
|
+
with h264_metadata/hevc_metadata only when the build has it."""
|
|
3765
|
+
global _BSFS
|
|
3766
|
+
if _BSFS is None:
|
|
3767
|
+
_BSFS = _read_ff_list("-bsfs", r"^\s*([a-z0-9_]+)\s*$")
|
|
3768
|
+
return _BSFS
|
|
3769
|
+
|
|
3770
|
+
|
|
3771
|
+
def ffmpeg_filters() -> set:
|
|
3772
|
+
"""Names from `ffmpeg -filters`, read once, empty when it cannot be read (the reason is kept and
|
|
3773
|
+
recorded as ffmpeg_encoders() keeps it); from ffprobe under --dry-run, for the reason
|
|
3774
|
+
ffmpeg_encoders() gives. The row is recognised by its io-spec token (`V->V`, `|->V`), so the
|
|
3775
|
+
flag-column width of FFmpeg 6/7 (three) and 8+ (two) does not matter."""
|
|
3776
|
+
global _FILTERS
|
|
3777
|
+
if _FILTERS is None:
|
|
3778
|
+
_FILTERS = _read_ff_list("-filters", _FILTER_ROW)
|
|
3779
|
+
return _FILTERS
|
|
3780
|
+
|
|
3781
|
+
|
|
3782
|
+
def require_filter(name: str, why: str) -> None:
|
|
3783
|
+
"""Refuse before ffmpeg runs (under --dry-run too) when this build has no `name` filter, with
|
|
3784
|
+
the same kind/reason/hint a run that hit "No such filter" gets (#393). A list that could not be
|
|
3785
|
+
read refuses nothing: an unreadable list is not a missing filter (ffmpeg_list_error)."""
|
|
3786
|
+
names = ffmpeg_filters()
|
|
3787
|
+
if not names or name in names:
|
|
3788
|
+
return
|
|
3789
|
+
die(f"this ffmpeg build has no {name} filter, which {why} needs", code=1, kind="ffmpeg",
|
|
3790
|
+
error_extra={"reason": "filter_missing", "details": {"name": name}},
|
|
3791
|
+
hint=filter_missing_hint(name))
|
|
3792
|
+
|
|
3793
|
+
|
|
3794
|
+
def with_flags(argv: Sequence[str], flags: Sequence[str]) -> List[str]:
|
|
3795
|
+
"""`argv` with `flags` added where argparse still reads them as options: before a bare `--`
|
|
3796
|
+
when there is one (everything after it is positional, so `--dry-run --json` appended after
|
|
3797
|
+
`render.py -- project.json` was refused as unrecognised arguments, #510 review), else at the end."""
|
|
3798
|
+
argv = [str(a) for a in argv]
|
|
3799
|
+
if "--" in argv:
|
|
3800
|
+
i = argv.index("--")
|
|
3801
|
+
return argv[:i] + list(flags) + argv[i:]
|
|
3802
|
+
return argv + list(flags)
|
|
3803
|
+
|
|
3804
|
+
|
|
3805
|
+
BUILD_COMPONENT_REASONS = ("filter_missing", "encoder_missing")
|
|
3806
|
+
|
|
3807
|
+
|
|
3808
|
+
def refuse_missing_components_first(script: str, why: str) -> None:
|
|
3809
|
+
"""A tool that runs its work as several stages (render.py, waveform.py with a title or
|
|
3810
|
+
captions) finds a filter or an encoder the build lacks at the stage that needs it, after the
|
|
3811
|
+
stages before it have encoded (#510). Its --dry-run runs every stage's own dry run, which
|
|
3812
|
+
refuses such a stage before anything is written, so a real run runs that dry run first (this
|
|
3813
|
+
same command line with --dry-run) and, when it is refused for a component this build lacks,
|
|
3814
|
+
is refused with the same document: kind, message, reason, details, hint and stage. Any other
|
|
3815
|
+
outcome of the dry run, a refusal for another reason or a timeout included, is left to the
|
|
3816
|
+
real run, which decides on the files as they then are. Nothing to do under --dry-run itself."""
|
|
3817
|
+
if STATE.dry_run:
|
|
3818
|
+
return
|
|
3819
|
+
info(f"checking every {why} against this ffmpeg build first (a dry run of this command)")
|
|
3820
|
+
proc = run_tool([script] + with_flags(sys.argv[1:], ["--dry-run", "--json"]))
|
|
3821
|
+
try:
|
|
3822
|
+
doc = json.loads(proc.stdout.strip() or "{}")
|
|
3823
|
+
except ValueError:
|
|
3824
|
+
doc = None
|
|
3825
|
+
err = doc.get("error") if isinstance(doc, dict) else None
|
|
3826
|
+
if proc.returncode == 0:
|
|
3827
|
+
return
|
|
3828
|
+
if not isinstance(err, dict) or err.get("reason") not in BUILD_COMPONENT_REASONS:
|
|
3829
|
+
# not a component this build lacks: the real run meets the same thing, or not, itself
|
|
3830
|
+
info("the dry run did not complete (" + (str(err.get("message"))[:200] if isinstance(err, dict) else
|
|
3831
|
+
f"exit {proc.returncode}, no document")
|
|
3832
|
+
+ "); its stages are checked as they run")
|
|
3833
|
+
return
|
|
3834
|
+
extra: Dict[str, Any] = {"hint": err["hint"]} if err.get("hint") else {}
|
|
3835
|
+
for key in ("stage", "encoder"):
|
|
3836
|
+
if doc.get(key):
|
|
3837
|
+
extra[key] = doc[key]
|
|
3838
|
+
die(str(err.get("message") or err["reason"]), code=int(doc.get("exit_code") or 1), kind=str(err.get("kind") or "ffmpeg"),
|
|
3839
|
+
error_extra={k: err[k] for k in ("reason", "details") if err.get(k) is not None}, **extra)
|
|
3840
|
+
|
|
3841
|
+
|
|
3842
|
+
def filter_missing_hint(name: str) -> str:
|
|
3843
|
+
"""The filter_missing hint, with the platform's fuller-build line doctor prints for it."""
|
|
3844
|
+
base = f"this ffmpeg build has no {name} filter: `python3 scripts/_contract.py doctor` lists what it has and how to get a fuller build"
|
|
3845
|
+
system = platform.system()
|
|
3846
|
+
if system == "Darwin":
|
|
3847
|
+
return base + "; on macOS: brew install ffmpeg-full, then put $(brew --prefix ffmpeg-full)/bin first on PATH"
|
|
3848
|
+
if system == "Windows":
|
|
3849
|
+
return base + "; on Windows: winget install Gyan.FFmpeg (the full build)"
|
|
3850
|
+
return base
|
|
3851
|
+
|
|
3852
|
+
|
|
3853
|
+
# why the last read of a capability list came back empty: "-encoders"/"-bsfs" -> reason
|
|
3854
|
+
_LIST_ERRORS: Dict[str, str] = {}
|
|
3855
|
+
|
|
3856
|
+
|
|
3857
|
+
def ffmpeg_list_error(flag: str) -> Optional[str]:
|
|
3858
|
+
"""Why `ffmpeg -encoders` / `-bsfs` (flag "encoders" or "bsfs") could not be read, or None when
|
|
3859
|
+
it was read (or not yet asked for). Only while the cached list is empty: a list a test or a
|
|
3860
|
+
later read filled in has nothing to explain."""
|
|
3861
|
+
flag = "-" + flag.lstrip("-")
|
|
3862
|
+
cache = {"-encoders": _ENCODERS, "-bsfs": _BSFS, "-filters": _FILTERS}.get(flag)
|
|
3863
|
+
return None if cache else _LIST_ERRORS.get(flag)
|
|
3864
|
+
|
|
3865
|
+
|
|
3866
|
+
def _read_ff_list(flag: str, pattern: str, quiet: bool = False) -> set:
|
|
3867
|
+
tool = "ffprobe" if STATE.dry_run else "ffmpeg"
|
|
3868
|
+
# --timeout bounds this read too: on Apple Silicon every CPU re-encode asks for the list
|
|
3869
|
+
# (#314), so a deadlocked ffmpeg must not outlive the limit the caller set before the encode
|
|
3870
|
+
limit = _probe_limit()
|
|
3871
|
+
if not quiet:
|
|
3872
|
+
_LIST_ERRORS.pop(flag, None)
|
|
3873
|
+
names: set = set()
|
|
3874
|
+
why = None
|
|
3875
|
+
try:
|
|
3876
|
+
proc = subprocess.run([found_exe(tool), "-hide_banner", flag], stdout=subprocess.PIPE,
|
|
3877
|
+
stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=limit)
|
|
3878
|
+
names = set(re.findall(pattern, proc.stdout or "", re.M))
|
|
3879
|
+
if not names:
|
|
3880
|
+
tail = [ln.strip() for ln in (proc.stderr or "").splitlines() if ln.strip()][-1:]
|
|
3881
|
+
why = (f"{tool} {flag} exited {proc.returncode}" if proc.returncode else f"{tool} {flag} listed nothing") + \
|
|
3882
|
+
(f": {tail[0][:200]}" if tail else "")
|
|
3883
|
+
except subprocess.TimeoutExpired:
|
|
3884
|
+
why = f"{tool} {flag} did not answer within {limit:g} s"
|
|
3885
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
3886
|
+
why = f"{tool} {flag} could not run: {exc}"
|
|
3887
|
+
if why and quiet:
|
|
3888
|
+
return set()
|
|
3889
|
+
if why:
|
|
3890
|
+
_LIST_ERRORS[flag] = why
|
|
3891
|
+
what = {"-encoders": "encoder", "-decoders": "decoder", "-bsfs": "bitstream filter"}.get(flag, "filter")
|
|
3892
|
+
warn(f"could not read this ffmpeg build's {what} list ({why}); nothing that needs it can be confirmed, which is not the same as the build lacking it",
|
|
3893
|
+
"ffmpeg_list_unreadable", list=flag.lstrip("-"), tool=tool, error=why)
|
|
3894
|
+
return names
|
|
3895
|
+
|
|
3896
|
+
|
|
3897
|
+
_LINE_END = re.compile(r"\r*\n|\r")
|
|
3898
|
+
|
|
3899
|
+
|
|
3900
|
+
def normalize_text(text: str) -> str:
|
|
3901
|
+
"""A caller's text as every reader here takes it: a leading UTF-8 BOM dropped, and every line
|
|
3902
|
+
ending `\\n`. `\\r\\r\\n` is one line end, as ffmpeg's text demuxers read it (a CRLF file passed
|
|
3903
|
+
through a second CRLF conversion); a lone `\\r` (classic Mac) is one too. Only these: a line is
|
|
3904
|
+
never split at U+2028, U+0085, \\v or \\f, which str.splitlines() also splits at."""
|
|
3905
|
+
return _LINE_END.sub("\n", text.lstrip("\ufeff"))
|
|
3906
|
+
|
|
3907
|
+
|
|
3908
|
+
def register_plan_input(path: "os.PathLike[str] | str") -> None:
|
|
3909
|
+
"""Bind a file the tool read through a parsed argument, regardless of its argv spelling."""
|
|
3910
|
+
if STATE.plan:
|
|
3911
|
+
STATE.plan_inputs.append(os.fspath(path))
|
|
3912
|
+
|
|
3913
|
+
|
|
3914
|
+
def read_text_or_die(path: str, flag: str) -> str:
|
|
3915
|
+
"""Read a caller-supplied UTF-8 text file (a cue list, chapters, notes) or fail as kind input
|
|
3916
|
+
with the flag named, instead of a FileNotFoundError / UnicodeDecodeError traceback. The text
|
|
3917
|
+
comes back through normalize_text(): no BOM, `\\n` line ends."""
|
|
3918
|
+
if os.path.isdir(path):
|
|
3919
|
+
# checked first: Windows raises PermissionError, not IsADirectoryError, for a directory
|
|
3920
|
+
die(f"{flag}: {path} is a directory, not a text file")
|
|
3921
|
+
try:
|
|
3922
|
+
with open(path, "r", encoding="utf-8", newline="") as fh:
|
|
3923
|
+
text = normalize_text(fh.read())
|
|
3924
|
+
register_plan_input(path)
|
|
3925
|
+
return text
|
|
3926
|
+
except FileNotFoundError:
|
|
3927
|
+
die(f"{flag}: {path} does not exist")
|
|
3928
|
+
except IsADirectoryError:
|
|
3929
|
+
die(f"{flag}: {path} is a directory, not a text file")
|
|
3930
|
+
except UnicodeDecodeError as e:
|
|
3931
|
+
die(f"{flag}: {path} is not UTF-8 text ({e.reason} at byte {e.start}); save it as UTF-8")
|
|
3932
|
+
except OSError as e:
|
|
3933
|
+
die(f"{flag}: cannot read {path}: {e.strerror}")
|
|
3934
|
+
return "" # unreachable
|
|
3935
|
+
|
|
3936
|
+
|
|
3937
|
+
# Deeper than any project, recipe, brand, plan or transcript this skill reads (those are four or
|
|
3938
|
+
# five levels); a file nested past it is refused before code that walks it recursively
|
|
3939
|
+
# (copy.deepcopy, json.dumps) can raise RecursionError.
|
|
3940
|
+
JSON_MAX_DEPTH = 64
|
|
3941
|
+
|
|
3942
|
+
|
|
3943
|
+
class JsonTooDeep(ValueError):
|
|
3944
|
+
"""parse_json()'s refusal of a document nested past JSON_MAX_DEPTH: a ValueError, so callers
|
|
3945
|
+
that catch ValueError refuse it as malformed JSON; one that falls back on a non-JSON file (a
|
|
3946
|
+
media file) can tell this apart, since the file was JSON."""
|
|
3947
|
+
|
|
3948
|
+
|
|
3949
|
+
def parse_json(text: str) -> Any:
|
|
3950
|
+
"""json.loads for a caller's file: a BOM is dropped, and every way the text can fail to be a
|
|
3951
|
+
document this skill can walk raises ValueError -- malformed JSON (json's own ValueError),
|
|
3952
|
+
nesting too deep for the parser (RecursionError) or deeper than JSON_MAX_DEPTH. Callers that
|
|
3953
|
+
already catch ValueError therefore refuse all three as they refuse malformed JSON."""
|
|
3954
|
+
try:
|
|
3955
|
+
data = json.loads(text.lstrip("\ufeff"))
|
|
3956
|
+
except RecursionError:
|
|
3957
|
+
raise JsonTooDeep(f"nested more than {JSON_MAX_DEPTH} levels deep") from None
|
|
3958
|
+
stack = [(data, 1)]
|
|
3959
|
+
while stack:
|
|
3960
|
+
value, depth = stack.pop()
|
|
3961
|
+
if isinstance(value, (dict, list)):
|
|
3962
|
+
if depth > JSON_MAX_DEPTH:
|
|
3963
|
+
raise JsonTooDeep(f"nested more than {JSON_MAX_DEPTH} levels deep")
|
|
3964
|
+
if isinstance(value, dict):
|
|
3965
|
+
stack.extend((k, depth) for k in value)
|
|
3966
|
+
stack.extend((v, depth + 1) for v in (value.values() if isinstance(value, dict) else value))
|
|
3967
|
+
elif isinstance(value, str) and _SURROGATE.search(value):
|
|
3968
|
+
# A264: "\ud83d" alone is valid JSON and no text: json reads it as a lone surrogate,
|
|
3969
|
+
# which no UTF-8 file, argument or stdout can encode -- the run died on the first write
|
|
3970
|
+
# with a UnicodeEncodeError traceback and nothing on stdout
|
|
3971
|
+
bad = _SURROGATE.search(value).group(0)
|
|
3972
|
+
raise ValueError(f"the string \"{value[:60].encode('ascii', 'backslashreplace').decode()}\" holds \\u{ord(bad):04x}, "
|
|
3973
|
+
"half of a UTF-16 surrogate pair with no other half: it is no character, so no file can "
|
|
3974
|
+
"hold it -- write the character itself, or both halves of its \\u escape")
|
|
3975
|
+
return data
|
|
3976
|
+
|
|
3977
|
+
|
|
3978
|
+
_SURROGATE = re.compile("[\ud800-\udfff]")
|
|
3979
|
+
|
|
3980
|
+
|
|
3981
|
+
def read_json(path: "os.PathLike[str] | str") -> Any:
|
|
3982
|
+
"""parse_json() of a UTF-8 file. Raises OSError for a file that cannot be read and ValueError
|
|
3983
|
+
(UnicodeDecodeError is one) for anything else, so `except (OSError, ValueError)` covers it."""
|
|
3984
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
3985
|
+
doc = parse_json(fh.read())
|
|
3986
|
+
register_plan_input(path)
|
|
3987
|
+
return doc
|
|
3988
|
+
|
|
3989
|
+
|
|
3990
|
+
# Deferred to the foot of the module on purpose. runner is the first module the package loads and
|
|
3991
|
+
# emit needs runner's Context/STATE/ERROR_CODE, so the two form a cycle that has to be cut
|
|
3992
|
+
# somewhere: by the time this line runs every name emit reads from runner above is defined, and
|
|
3993
|
+
# every name runner reads from emit is only ever read inside a function body, never at import.
|
|
3994
|
+
from _common.emit import _plan_at_exit, audit, die, hw_report, info, record_fallback, record_skip, refuse, warn # noqa: E402
|