@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,1309 @@
|
|
|
1
|
+
"""Result documents: die(), info(), emit(), the brief and 2.0 shapes, and the plan file.
|
|
2
|
+
|
|
3
|
+
Every script ends in exactly one of these: emit() on success, die() on failure. Both print a
|
|
4
|
+
single JSON document when --json is on and record the Context the caller passed.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
import shlex
|
|
12
|
+
import stat
|
|
13
|
+
import sys
|
|
14
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
15
|
+
from _common.runner import Context, ERROR_CODE, ERROR_RETRYABLE, STATE, same_file, stream_copy_output
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# Characters that never belong in a message a calling agent reads (#400): C0 controls (a line
|
|
19
|
+
# break is one), DEL and C1, the Unicode line/paragraph separators and the bidi embedding,
|
|
20
|
+
# override and isolate marks. A path or other argument carrying one would otherwise reach
|
|
21
|
+
# error.message / a diagnostic verbatim, where a newline can start what reads as a new line of
|
|
22
|
+
# instructions and a bidi override can reorder what is shown.
|
|
23
|
+
_UNSAFE = frozenset([chr(c) for c in range(0x20) if c not in (0x09, 0x0A)] + [chr(0x7F)]
|
|
24
|
+
+ [chr(c) for c in range(0x80, 0xA0)]
|
|
25
|
+
+ ["\u2028", "\u2029", "\u200e", "\u200f"] + [chr(c) for c in range(0x202A, 0x202F)]
|
|
26
|
+
+ [chr(c) for c in range(0x2066, 0x206A)])
|
|
27
|
+
_LINE_BREAKS = frozenset("\n")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def shown(value: Any) -> str:
|
|
31
|
+
"""`value` as text with every unsafe character (and any line break) written as an escape
|
|
32
|
+
(\\n, \\x1b, \\u202e). A clean value comes back unchanged, so an ordinary path, a Windows one
|
|
33
|
+
with backslashes included, reads exactly as before."""
|
|
34
|
+
text = str(value)
|
|
35
|
+
if not any(ch in _UNSAFE or ch in _LINE_BREAKS for ch in text):
|
|
36
|
+
return text
|
|
37
|
+
return "".join((ch.encode("unicode_escape").decode("ascii") if (ch in _UNSAFE or ch in _LINE_BREAKS) else ch)
|
|
38
|
+
for ch in text)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _argument_forms(arg: str) -> List[str]:
|
|
42
|
+
"""The spellings a message may print an argument in: as given, resolved, and its file name;
|
|
43
|
+
for `--opt=value`, the same for the value, which is what a tool prints back."""
|
|
44
|
+
given = [arg] + ([arg.split("=", 1)[1]] if arg.startswith("-") and "=" in arg else [])
|
|
45
|
+
forms = set(given)
|
|
46
|
+
for a in given:
|
|
47
|
+
try:
|
|
48
|
+
forms.update({os.path.abspath(a), os.path.realpath(a), os.path.basename(a)})
|
|
49
|
+
except (OSError, ValueError):
|
|
50
|
+
pass
|
|
51
|
+
return sorted((f for f in forms if f), key=len, reverse=True)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def neutralize(msg: Any) -> Any:
|
|
55
|
+
"""A message with caller-supplied text made inert (#400): every command-line argument that
|
|
56
|
+
carries a line break or an unsafe character is replaced by its shown() form wherever it
|
|
57
|
+
appears (as given, resolved or as a file name), then any unsafe character left is escaped.
|
|
58
|
+
Line breaks the tool itself wrote (an ffmpeg stderr tail) stay; one inside an argument does not."""
|
|
59
|
+
if not isinstance(msg, str):
|
|
60
|
+
return msg
|
|
61
|
+
for arg in sys.argv[1:]:
|
|
62
|
+
if isinstance(arg, str) and any(ch in _UNSAFE or ch in _LINE_BREAKS for ch in arg):
|
|
63
|
+
for form in _argument_forms(arg):
|
|
64
|
+
if form in msg and (form != os.path.basename(arg) or any(ch in _UNSAFE or ch in _LINE_BREAKS for ch in form)):
|
|
65
|
+
msg = msg.replace(form, shown(form))
|
|
66
|
+
if any(ch in _UNSAFE for ch in msg):
|
|
67
|
+
msg = "".join(ch.encode("unicode_escape").decode("ascii") if ch in _UNSAFE else ch for ch in msg)
|
|
68
|
+
return msg
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def die(msg: str, code: int = 1, kind: str = "input", *, ctx: "Optional[Context]" = None,
|
|
72
|
+
error_extra: "Optional[Dict[str, Any]]" = None, **extra: Any) -> "None":
|
|
73
|
+
"""Exit with a message. Under --json also print a machine-readable failure document
|
|
74
|
+
(status: failed) on stdout so callers get the same shape as a success; exit codes are unchanged.
|
|
75
|
+
|
|
76
|
+
`extra` fields are added to the failure document: a tool whose *result* failed (check.py's
|
|
77
|
+
platform rows, render.py's check stage, batch.py's per-item results, verify.py's steps) keeps
|
|
78
|
+
reporting that detail while the top-level status says failed. Before 1.4.3 those four printed
|
|
79
|
+
`status: "completed"` next to a non-zero exit code, so a caller keying on the status alone
|
|
80
|
+
read a failed delivery as a success.
|
|
81
|
+
|
|
82
|
+
`error_extra` goes inside `error` (refuse() passes `reason` and `details` there); the
|
|
83
|
+
collector's records (warn() and friends) are merged into the document as emit() merges them."""
|
|
84
|
+
if extra.get("hint") is None and kind == "input" and getattr(ctx or STATE, "smpte_hint", None):
|
|
85
|
+
extra["hint"] = (ctx or STATE).smpte_hint # an hh:mm:ss:ff flag read past a timecoded source's end (#411)
|
|
86
|
+
hint = neutralize(extra.pop("hint", None))
|
|
87
|
+
msg = neutralize(msg)
|
|
88
|
+
ctx = ctx or STATE # 1.10: the optional per-request Context (2.0 makes it required); STATE is the default instance
|
|
89
|
+
_set_current_ctx(ctx) # the atexit hook has no argument: it reads the ctx emit()/die() last used
|
|
90
|
+
ctx.plan = None # a failed run plans nothing (the exit hook must not write a plan for it)
|
|
91
|
+
STATE.plan = None # the hook falls back to STATE when nothing passed a ctx; a failed run plans nothing there either
|
|
92
|
+
sys.stderr.write(f"error: {msg}\n" + (f"hint: {hint}\n" if hint else ""))
|
|
93
|
+
if kind == "ffmpeg" and "hw" not in extra and (ctx.hw or ctx.hw_stages or ctx.hw_env_ignored or ctx.hw_auto):
|
|
94
|
+
# a tool's own ffmpeg failure (cut.py runs run(check=False) and dies itself; render.py
|
|
95
|
+
# re-raises a stage's) carries `encoder` and `hw` as run()'s _fail() does: under --hw /
|
|
96
|
+
# $FFMPEG_SKILL_HW two encoders may have run, and a caller must know whose failure it is
|
|
97
|
+
enc = extra.get("encoder") or _video_encoders(ctx.commands)[0]
|
|
98
|
+
if enc and "encoder" not in extra:
|
|
99
|
+
extra["encoder"] = enc
|
|
100
|
+
extra["hw"] = hw_report(ctx, enc)
|
|
101
|
+
if ctx.json:
|
|
102
|
+
doc: Dict[str, Any] = {
|
|
103
|
+
"status": "failed", "exit_code": code,
|
|
104
|
+
"error": {
|
|
105
|
+
"kind": kind, "message": msg,
|
|
106
|
+
"code": ERROR_CODE.get(kind, "INTERNAL_ERROR"),
|
|
107
|
+
"retryable": ERROR_RETRYABLE,
|
|
108
|
+
},
|
|
109
|
+
"commands": list(ctx.commands),
|
|
110
|
+
}
|
|
111
|
+
if hint:
|
|
112
|
+
doc["error"]["hint"] = hint
|
|
113
|
+
for key, value in (error_extra or {}).items():
|
|
114
|
+
if value is not None:
|
|
115
|
+
doc["error"][key] = value
|
|
116
|
+
doc.update(extra)
|
|
117
|
+
for key in ("verified", "lossless"):
|
|
118
|
+
if key in doc:
|
|
119
|
+
doc[key] = False
|
|
120
|
+
_merge_collector(doc, ctx)
|
|
121
|
+
print_json(doc)
|
|
122
|
+
sys.exit(code)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _report_dropped_audio_tracks(meta: Dict[str, Any], ctx: "Context") -> None:
|
|
126
|
+
"""The tools write one audio track: a source with several must say how many did not come
|
|
127
|
+
along (#397, every tool, not only cut.py). Only when the output kept sound at all: a tool told
|
|
128
|
+
to drop it (--no-audio, a picture-only output) left nothing out by surprise."""
|
|
129
|
+
first = getattr(STATE, "first_input", None)
|
|
130
|
+
if not first or first[1] < 2 or not meta:
|
|
131
|
+
return
|
|
132
|
+
if len(getattr(STATE, "audio_inputs", None) or ()) > 1:
|
|
133
|
+
return # several sources with sound: which one's tracks the output carries is the tool's own choice
|
|
134
|
+
kept = len(meta.get("audio_streams") or [])
|
|
135
|
+
if not kept or kept >= first[1]:
|
|
136
|
+
return
|
|
137
|
+
if any(w.get("code") == "audio_tracks_dropped" for w in ctx.warnings):
|
|
138
|
+
return # the tool said it already (cut.py, with its own field)
|
|
139
|
+
warn(f"the source has {first[1]} audio tracks; this output kept {kept} and left {first[1] - kept} out "
|
|
140
|
+
"(the tools write one audio track; --audio-stream N picks which, where a tool takes it)",
|
|
141
|
+
"audio_tracks_dropped", ctx=ctx, source=first[1], kept=kept, dropped=first[1] - kept)
|
|
142
|
+
note_line = ctx.warnings[-1]["message"] if ctx.warnings else None
|
|
143
|
+
if note_line and note_line not in ctx.notes:
|
|
144
|
+
ctx.notes.append(note_line)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _report_dropped_hdr10_metadata(meta: Dict[str, Any], ctx: "Context") -> None:
|
|
148
|
+
"""A PQ source's mastering-display / content-light metadata that a PQ output came out without
|
|
149
|
+
(#401): measured on the written file, so whatever encoder or FFmpeg version dropped it is said.
|
|
150
|
+
An output that is no longer PQ (color.py --to-sdr, an HLG conversion) was converted on purpose."""
|
|
151
|
+
first = getattr(STATE, "first_input", None)
|
|
152
|
+
src = first[2] if first and len(first) > 2 else None
|
|
153
|
+
v = (meta or {}).get("video") or {}
|
|
154
|
+
if not src or v.get("color_transfer") != "smpte2084":
|
|
155
|
+
return
|
|
156
|
+
if len(getattr(STATE, "video_inputs", None) or ()) > 1:
|
|
157
|
+
return # several pictures: the first input's metadata need not be the output's source
|
|
158
|
+
have = v.get("hdr10_static") or {}
|
|
159
|
+
lost = [k for k in ("mastering_display", "content_light") if src.get(k) and not have.get(k)]
|
|
160
|
+
if not lost:
|
|
161
|
+
return
|
|
162
|
+
names = {"mastering_display": "mastering display", "content_light": "content light level"}
|
|
163
|
+
warn("the source's HDR10 " + " and ".join(names[k] for k in lost) + " metadata did not come through to this output "
|
|
164
|
+
"(the encoder or this FFmpeg build did not write it); players may tone-map it differently",
|
|
165
|
+
"hdr10_metadata_dropped", ctx=ctx, dropped=lost, codec=v.get("codec"))
|
|
166
|
+
note_line = ctx.warnings[-1]["message"] if ctx.warnings else None
|
|
167
|
+
if note_line and note_line not in ctx.notes:
|
|
168
|
+
ctx.notes.append(note_line)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _report_reduced_bit_depth(output: str, meta: Dict[str, Any], ctx: "Context") -> None:
|
|
172
|
+
# A 10-bit (or deeper) picture written as 8-bit (#696, from #558): the reduction is decided
|
|
173
|
+
# (docs/design-decisions.md, "After 3.6.0": an SDR H.264 line is 8-bit), saying so was not.
|
|
174
|
+
# Measured on the written file for every tool; not for several pictures or a still.
|
|
175
|
+
from .probe import MEDIA_EXT, _STILL_EXT
|
|
176
|
+
src, out = (list(getattr(STATE, "first_input", None) or ()) + [None] * 4)[3], ((meta or {}).get("video") or {}).get("bit_depth")
|
|
177
|
+
ext = os.path.splitext(output)[1].lower()
|
|
178
|
+
if src and out and out < src and src > 8 and ext in MEDIA_EXT and ext not in _STILL_EXT and len(STATE.video_inputs or ()) <= 1:
|
|
179
|
+
ctx.notes.append(f"the source picture is {src}-bit and this output is {out}-bit: the encoder writes {out} bits "
|
|
180
|
+
f"(a ProRes master, --codec prores where the tool offers it, keeps the depth)")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# source_carry: the items compared, in report order. The first group is content a viewer or
|
|
184
|
+
# listener notices missing and raises the warning; the second is tags, listed but never warned
|
|
185
|
+
# about (every camera file has a creation_time, so a warning for it would fire on every run).
|
|
186
|
+
CARRY_CONTENT = ("subtitles", "chapters", "cover_art", "audio_channels", "attachments", "video_streams")
|
|
187
|
+
CARRY_TAGS = ("creation_time", "audio_language", "timecode")
|
|
188
|
+
_CARRY_NAMES = {"subtitles": "subtitle track", "chapters": "chapters", "cover_art": "cover picture",
|
|
189
|
+
"audio_channels": "audio channels", "attachments": "attached files (a subtitle track's fonts)",
|
|
190
|
+
"video_streams": "video streams"}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def source_carry(output: Optional[str], ctx: "Context", extra: Dict[str, Any]) -> "Optional[Dict[str, List[str]]]":
|
|
194
|
+
"""What the first input carried besides its picture and sound, and whether the written file
|
|
195
|
+
still has it (#401): {"kept": [...], "dropped": [...]}, or None when the source had none of
|
|
196
|
+
it or the two files are not comparable. Measured on the written file, so the tool, encoder or
|
|
197
|
+
FFmpeg version that dropped it does not matter. A report, not a check: `verified` is not
|
|
198
|
+
touched. Not compared: two or more picture or sound sources (which one's items the output
|
|
199
|
+
should carry is the tool's choice), an output that is not a media file, and items bound to a
|
|
200
|
+
stream the output does not have at all (a sound-only extract has no subtitle track or
|
|
201
|
+
timecode to lose; a picture-only output has no audio channels). Audio channels are an item
|
|
202
|
+
only for a surround source (more than two)."""
|
|
203
|
+
from .probe import MEDIA_EXT, _STILL_EXT, carry_inventory
|
|
204
|
+
first = getattr(STATE, "first_input", None)
|
|
205
|
+
if not first or not output:
|
|
206
|
+
return None
|
|
207
|
+
# a tool that reads its own output back (cut.py measures the cut it wrote) probed it as an
|
|
208
|
+
# input too: that is not a second source
|
|
209
|
+
own = os.path.realpath(output)
|
|
210
|
+
if any(len(set(getattr(STATE, name, None) or ()) - {own}) > 1 for name in ("video_inputs", "audio_inputs")):
|
|
211
|
+
return None
|
|
212
|
+
ext = os.path.splitext(output)[1].lower()
|
|
213
|
+
if ext not in MEDIA_EXT or ext in _STILL_EXT:
|
|
214
|
+
return None # a still, a contact sheet or an animated GIF holds none of these
|
|
215
|
+
src, out = carry_inventory(first[0]), carry_inventory(output)
|
|
216
|
+
if not src or not out or os.path.realpath(first[0]) == os.path.realpath(output):
|
|
217
|
+
return None
|
|
218
|
+
kept: List[str] = []
|
|
219
|
+
dropped: List[str] = []
|
|
220
|
+
for item in CARRY_CONTENT + CARRY_TAGS:
|
|
221
|
+
if not src.get(item):
|
|
222
|
+
continue
|
|
223
|
+
if item == "audio_channels" and src[item] <= 2:
|
|
224
|
+
continue # mono and stereo are what every tool writes; only a surround layout can be folded down
|
|
225
|
+
if item == "video_streams" and src[item] <= 1:
|
|
226
|
+
continue # one picture is what every tool writes; only a second one can be left out
|
|
227
|
+
if item in ("subtitles", "timecode", "attachments", "video_streams") and src["has_video"] and not out["has_video"]:
|
|
228
|
+
continue
|
|
229
|
+
if item in ("audio_channels", "audio_language") and not out["has_audio"]:
|
|
230
|
+
continue
|
|
231
|
+
if item == "timecode":
|
|
232
|
+
# the value, not only its presence: a cut from 1 s that wrote the source's 01:00:00:00
|
|
233
|
+
# on frame 30 kept a timecode that lies. A tool that moved the picture's start names
|
|
234
|
+
# the label it wrote (STATE.expected_timecode, "" for none); any other keeps the source's
|
|
235
|
+
want = getattr(STATE, "expected_timecode", None)
|
|
236
|
+
want = src.get("timecode_value") if want is None else want
|
|
237
|
+
(kept if want and out.get("timecode_value") == want else dropped).append(item)
|
|
238
|
+
continue
|
|
239
|
+
(kept if out.get(item, 0) >= src[item] else dropped).append(item)
|
|
240
|
+
if not kept and not dropped:
|
|
241
|
+
return None
|
|
242
|
+
# The class guard for time (docs/defect-guards.json): an output of another length whose
|
|
243
|
+
# chapters were carried by a tool that declared no time map (runner.with_mapped_chapters, or
|
|
244
|
+
# runner.declare_time_map where FFmpeg's own handling is right) kept them at the source's
|
|
245
|
+
# times. Seven ledger entries were one tool each moving time and leaving something behind
|
|
246
|
+
# (#470, #653, #696); this is said for every tool, including one written after this line.
|
|
247
|
+
if ("chapters" in kept and not getattr(STATE, "time_mapped", None)
|
|
248
|
+
and abs((out.get("duration") or 0.0) - (src.get("duration") or 0.0)) > 0.1):
|
|
249
|
+
warn(f"the output is {out.get('duration') or 0:.2f} s against the source's {src.get('duration') or 0:.2f} s, and its chapters "
|
|
250
|
+
f"were carried at the source's times: the tool moved the picture in time without moving them",
|
|
251
|
+
"chapters_not_retimed", source_chapters=src.get("chapter_times"), output_chapters=out.get("chapter_times"))
|
|
252
|
+
said = set()
|
|
253
|
+
if extra.get("dropped_non_av_streams") or any(w.get("code") == "non_av_streams_dropped" for w in ctx.fallbacks):
|
|
254
|
+
said.add("subtitles") # the tool's own field already says the track went
|
|
255
|
+
loud = [i for i in dropped if i in CARRY_CONTENT and i not in said]
|
|
256
|
+
if loud:
|
|
257
|
+
parts = []
|
|
258
|
+
for i in loud:
|
|
259
|
+
if i in ("audio_channels", "video_streams"):
|
|
260
|
+
parts.append(f"{src[i] - out.get(i, 0)} of its {src[i]} {_CARRY_NAMES[i]}")
|
|
261
|
+
else:
|
|
262
|
+
parts.append("its " + _CARRY_NAMES[i])
|
|
263
|
+
warn("the source carried " + ", ".join(parts) + " that this output does not have "
|
|
264
|
+
"(source_carry lists everything kept and dropped)",
|
|
265
|
+
"source_items_dropped", ctx=ctx, dropped=loud)
|
|
266
|
+
note_line = ctx.warnings[-1]["message"] if ctx.warnings else None
|
|
267
|
+
if note_line and note_line not in ctx.notes:
|
|
268
|
+
ctx.notes.append(note_line)
|
|
269
|
+
return {"kept": kept, "dropped": dropped}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def refuse(kind: str, reason: str, msg: str, *, hint: Optional[str] = None, code: int = 1,
|
|
273
|
+
ctx: "Optional[Context]" = None, extra: "Optional[Dict[str, Any]]" = None, **details: Any) -> "None":
|
|
274
|
+
"""die() for a refusal a caller has to act on: `error.reason` is a stable snake_case code for
|
|
275
|
+
*why* (output_exists, output_is_input, output_locked, plan_inputs_changed, ...), and
|
|
276
|
+
`error.details` holds the facts the message is written from (paths, expected and actual
|
|
277
|
+
values), so a caller never parses the prose. `extra` adds top-level keys as die()'s do."""
|
|
278
|
+
die(msg, code=code, kind=kind, ctx=ctx, hint=hint, error_extra={"reason": reason, "details": json_safe(details)}, **(extra or {}))
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _record(bucket: str, msg: str, code: str, ctx: "Optional[Context]", data: Dict[str, Any], prefix: str) -> Dict[str, Any]:
|
|
282
|
+
ctx = ctx or STATE
|
|
283
|
+
msg = neutralize(msg)
|
|
284
|
+
entry: Dict[str, Any] = {"code": code, "message": msg}
|
|
285
|
+
entry.update(data)
|
|
286
|
+
# once per run: a decision taken for every encode of a job (an AV1 encoder fallback, a CRF
|
|
287
|
+
# clamp) is one record, though its stderr line is printed each time it is taken
|
|
288
|
+
if entry not in getattr(ctx, bucket):
|
|
289
|
+
getattr(ctx, bucket).append(entry)
|
|
290
|
+
sys.stderr.write(f"{prefix}{msg}\n")
|
|
291
|
+
return entry
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def warn(msg: str, code: str, *, ctx: "Optional[Context]" = None, **data: Any) -> Dict[str, Any]:
|
|
295
|
+
"""Say something went other than asked, on stderr AND in the document
|
|
296
|
+
(`diagnostics.warnings`: {code, message, ...data}). Use it where a bare info("warning: ...")
|
|
297
|
+
would leave the caller of --json nothing to read (a source test refuses that spelling).
|
|
298
|
+
Every code is listed in the contract (`json_output.diagnostic_codes`)."""
|
|
299
|
+
return _record("warnings", msg, code, ctx, data, "warning: ")
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def record_fallback(msg: str, code: str, *, ctx: "Optional[Context]" = None, **data: Any) -> Dict[str, Any]:
|
|
303
|
+
"""The run took another route than the asked one and went on (`diagnostics.fallbacks`)."""
|
|
304
|
+
return _record("fallbacks", msg, code, ctx, data, "")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def record_skip(msg: str, code: str, *, ctx: "Optional[Context]" = None, **data: Any) -> Dict[str, Any]:
|
|
308
|
+
"""A step that was asked for, or would normally run, did not (`diagnostics.skipped`)."""
|
|
309
|
+
return _record("skipped", msg, code, ctx, data, "")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def note(msg: str, ctx: "Optional[Context]" = None) -> None:
|
|
313
|
+
"""A plain `notes` line that also goes to stderr, made inert as messages are (#400)."""
|
|
314
|
+
ctx = ctx or STATE
|
|
315
|
+
msg = neutralize(msg)
|
|
316
|
+
if msg not in ctx.notes:
|
|
317
|
+
ctx.notes.append(msg)
|
|
318
|
+
sys.stderr.write(f"{msg}\n")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _merge_collector(doc: Dict[str, Any], ctx: "Context") -> None:
|
|
322
|
+
"""The collector into a result or failure document: ctx.notes join `notes` (once each), and
|
|
323
|
+
the three record lists become `diagnostics`, present only when one of them is not empty
|
|
324
|
+
(`warnings` and `skipped` are not top-level keys: check.py's `warnings` is a count and join.py's
|
|
325
|
+
`skipped` its left-out inputs)."""
|
|
326
|
+
extra_notes = [n for n in ctx.notes if n not in (doc.get("notes") or [])]
|
|
327
|
+
if extra_notes:
|
|
328
|
+
doc["notes"] = list(doc.get("notes") or []) + extra_notes
|
|
329
|
+
if doc.get("notes"):
|
|
330
|
+
# a tool's own notes can quote an input path (join.py's duplicates): made inert as messages are (#400)
|
|
331
|
+
doc["notes"] = [neutralize(n) for n in doc["notes"]]
|
|
332
|
+
diag = {k: list(getattr(ctx, k)) for k in ("warnings", "fallbacks", "skipped") if getattr(ctx, k)}
|
|
333
|
+
if diag:
|
|
334
|
+
merged = dict(doc.get("diagnostics") or {})
|
|
335
|
+
for k, v in diag.items():
|
|
336
|
+
merged[k] = list(merged.get(k) or []) + [e for e in v if e not in (merged.get(k) or [])]
|
|
337
|
+
doc["diagnostics"] = merged
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def audit(event: str, details: Dict[str, Any], *, default_path: Optional[str] = None, plan_sha256: Optional[str] = None,
|
|
341
|
+
ctx: "Optional[Context]" = None) -> Dict[str, Any]:
|
|
342
|
+
"""Append one JSON line to the audit log: {ts, tool, event, pid, plan_sha256?, details}.
|
|
343
|
+
The log is render.py's --audit-log FILE when given, else the event's own `default_path` (a
|
|
344
|
+
plan's `<plan>.audit.jsonl`, a lock's hidden sibling); neither = nothing to write. Never under
|
|
345
|
+
--dry-run (a dry run writes nothing). A write that fails is a recorded warning, never a
|
|
346
|
+
failure of the run. Returns what happened, for the caller's `details.audit_log`."""
|
|
347
|
+
import datetime
|
|
348
|
+
ctx = ctx or STATE
|
|
349
|
+
path = ctx.audit_log or default_path
|
|
350
|
+
if not path:
|
|
351
|
+
return {"path": None, "written": False, "reason": "no_audit_log"}
|
|
352
|
+
if ctx.dry_run:
|
|
353
|
+
return {"path": path, "written": False, "reason": "dry_run"}
|
|
354
|
+
rec: Dict[str, Any] = {"ts": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
|
|
355
|
+
"tool": os.path.splitext(os.path.basename(sys.argv[0] or "?"))[0], "event": event, "pid": os.getpid()}
|
|
356
|
+
if plan_sha256:
|
|
357
|
+
rec["plan_sha256"] = plan_sha256
|
|
358
|
+
rec["details"] = details
|
|
359
|
+
try:
|
|
360
|
+
# a default path is a hidden name in someone's output directory: never appended to through a
|
|
361
|
+
# symlink planted there. A log the caller named (--audit-log) is opened as named.
|
|
362
|
+
flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | (0 if ctx.audit_log else getattr(os, "O_NOFOLLOW", 0))
|
|
363
|
+
checked = not ctx.audit_log and not hasattr(os, "O_NOFOLLOW")
|
|
364
|
+
if checked and os.path.islink(path):
|
|
365
|
+
raise OSError(f"{path} is a symbolic link")
|
|
366
|
+
fd = os.open(path, flags, 0o666)
|
|
367
|
+
if checked:
|
|
368
|
+
# no O_NOFOLLOW (Windows): a link that appeared between the look above and the open is
|
|
369
|
+
# caught after it -- the descriptor must be the file now at that name, not a link's
|
|
370
|
+
# target -- and nothing is written through it
|
|
371
|
+
try:
|
|
372
|
+
st, at = os.fstat(fd), os.lstat(path)
|
|
373
|
+
# st_nlink: a link swapped for a hard link to its target before the lstat would
|
|
374
|
+
# otherwise pass the identity check; a log this tool created has one name
|
|
375
|
+
if (stat.S_ISLNK(at.st_mode) or (st.st_dev, st.st_ino) != (at.st_dev, at.st_ino)
|
|
376
|
+
or not stat.S_ISREG(st.st_mode) or st.st_nlink != 1):
|
|
377
|
+
raise OSError(f"{path} was replaced by a link while it was opened")
|
|
378
|
+
except BaseException:
|
|
379
|
+
os.close(fd)
|
|
380
|
+
raise
|
|
381
|
+
with os.fdopen(fd, "a", encoding="utf-8") as f:
|
|
382
|
+
f.write(json.dumps(json_safe(rec), ensure_ascii=False, sort_keys=True) + "\n")
|
|
383
|
+
except OSError as exc:
|
|
384
|
+
warn(f"could not append the {event} record to the audit log {path} ({exc}); the run is unaffected",
|
|
385
|
+
"audit_log_unwritable", ctx=ctx, path=path, event=event, error=str(exc))
|
|
386
|
+
return {"path": path, "written": False, "reason": "unwritable", "error": str(exc)}
|
|
387
|
+
return {"path": path, "written": True}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def info(msg: str, ctx: "Optional[Context]" = None) -> None:
|
|
391
|
+
# under --dry-run nothing is written; do not let scripts claim otherwise
|
|
392
|
+
ctx = ctx or STATE
|
|
393
|
+
if msg.startswith("wrote ") and ctx.dry_run:
|
|
394
|
+
msg = "[dry-run] would write " + msg[len("wrote "):]
|
|
395
|
+
sys.stderr.write(f"{msg}\n")
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
# The atexit plan hook takes no arguments, so emit()/die() record the Context they were given
|
|
399
|
+
# here; nothing passed a ctx = it stays None and the hook falls back to STATE, as before (1.10).
|
|
400
|
+
_CURRENT_CTX: "Optional[Context]" = None
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _set_current_ctx(ctx: "Context") -> None:
|
|
404
|
+
global _CURRENT_CTX
|
|
405
|
+
_CURRENT_CTX = ctx
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
ENV_HW_NOTE = ("VideoToolbox chosen by FFMPEG_SKILL_HW=1 (machine default; ~1.1-3.5x the bytes of x264/x265 "
|
|
409
|
+
"at matched quality); rerun with --no-hw for a final deliverable")
|
|
410
|
+
ENV_NOT_FOR_DELIVERY_BASE = ("FFMPEG_SKILL_HW=1 is not applied to export.py's delivery presets (a delivered file is where "
|
|
411
|
+
"VideoToolbox's larger files cost most)")
|
|
412
|
+
ENV_NOT_FOR_DELIVERY_NOTE = ENV_NOT_FOR_DELIVERY_BASE + "; pass --hw to put this export on the GPU"
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def env_not_for_delivery_note() -> str:
|
|
416
|
+
"""The note for an export the variable left on the CPU: the advice to pass --hw only on a
|
|
417
|
+
machine that can take it (the same advice on a Linux box would send the caller to a flag that
|
|
418
|
+
then reports the CPU encode)."""
|
|
419
|
+
from _common import decision # the same name the --hw decisions (and their tests) stand the platform in on
|
|
420
|
+
return ENV_NOT_FOR_DELIVERY_NOTE if decision.hw_platform_reason() is None else ENV_NOT_FOR_DELIVERY_BASE
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _video_encoders(commands: Sequence[str]) -> "Tuple[Optional[str], Optional[str]]":
|
|
424
|
+
"""(the last video encoder the command lines name, or `copy` for a stream copy; that encoder's
|
|
425
|
+
command line). A later copy (loudness.py after export's encode) keeps the encode before it."""
|
|
426
|
+
import re as _re
|
|
427
|
+
enc, line, copied = None, None, False
|
|
428
|
+
for c in commands:
|
|
429
|
+
for name in _re.findall(r"(?:^|\s)-(?:c:v|vcodec|codec:v)\s+(\S+)", c):
|
|
430
|
+
if name == "copy":
|
|
431
|
+
copied = True
|
|
432
|
+
else:
|
|
433
|
+
enc, line = name, c
|
|
434
|
+
if _re.search(r"(?:^|\s)-(?:c|codec)\s+copy(?:\s|$)", c):
|
|
435
|
+
copied = True
|
|
436
|
+
if enc is None and copied:
|
|
437
|
+
return "copy", None
|
|
438
|
+
return enc, line
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def hw_report(ctx: "Context", enc: Optional[str]) -> Dict[str, Any]:
|
|
442
|
+
"""The `hw` object for a run whose last video encoder was `enc` (None: this process recorded
|
|
443
|
+
no encode -- batch.py, whose stages are child processes). `requested`: VideoToolbox was asked
|
|
444
|
+
for this run's encodes (by --hw, by $FFMPEG_SKILL_HW where it applies, or for a stage);
|
|
445
|
+
`source`: flag|env; `used`: the encoder that ran last is VideoToolbox; `fallback`: a job
|
|
446
|
+
VideoToolbox refused was re-encoded on the CPU, here or in a stage; `notes`: why. Under
|
|
447
|
+
--dry-run `used` is null and `fallback` false: nothing ran."""
|
|
448
|
+
stages = list(ctx.hw_stages)
|
|
449
|
+
requested = bool(ctx.hw) or any(st.get("requested") for st in stages)
|
|
450
|
+
source = ctx.hw_source if ctx.hw else next((st.get("source") for st in stages if st.get("requested")), None)
|
|
451
|
+
if not requested and ctx.hw_env_ignored:
|
|
452
|
+
source = "env"
|
|
453
|
+
if not requested and ctx.hw_auto:
|
|
454
|
+
source = "auto" # nobody asked: this build has no libx264/libx265, so VideoToolbox was the only encoder
|
|
455
|
+
# a stage that reported its source without asking (export.py under the variable: requested
|
|
456
|
+
# false, source env) still names where the request came from
|
|
457
|
+
source = source or next((st.get("source") for st in stages if st.get("source")), None)
|
|
458
|
+
vt = enc is not None and enc.endswith("_videotoolbox")
|
|
459
|
+
# `used` is what ran; a dry run ran nothing (the planned encoder is `encoder`), so null --
|
|
460
|
+
# as waveform.py's `silent` is null when nothing was measured
|
|
461
|
+
used = None if enc is None or ctx.dry_run else vt
|
|
462
|
+
notes = list(ctx.hw_notes)
|
|
463
|
+
if vt and source == "env" and not any(n.endswith(ENV_HW_NOTE) for n in notes):
|
|
464
|
+
# the machine default, not this call, chose the GPU: say what it costs and how to opt out
|
|
465
|
+
# (once: a stage that ran on it already said so)
|
|
466
|
+
notes.append(ENV_HW_NOTE)
|
|
467
|
+
if ctx.hw_env_ignored and enc not in (None, "copy") and not vt:
|
|
468
|
+
notes.append(env_not_for_delivery_note())
|
|
469
|
+
return {"requested": requested, "source": source, "used": used,
|
|
470
|
+
"fallback": bool(ctx.hw_fallback) or any(st.get("fallback") for st in stages), "notes": notes}
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def hw_quality_note(enc: Optional[str], line: Optional[str], no_cpu_encoder: bool = False) -> Optional[str]:
|
|
474
|
+
"""The `notes` line every VideoToolbox encode carries: its quality is not the CRF encode's.
|
|
475
|
+
`no_cpu_encoder`: the build has no libx264/libx265, so `--no-hw` is no remedy and is not offered."""
|
|
476
|
+
import re as _re
|
|
477
|
+
if not enc or not enc.endswith("_videotoolbox"):
|
|
478
|
+
return None
|
|
479
|
+
if enc == "prores_videotoolbox":
|
|
480
|
+
return ("prores_videotoolbox is not prores_ks: the same 422 HQ profile from a different encoder, so size and detail "
|
|
481
|
+
"differ from the CPU encode; `verified` covers the output's measured properties, not parity with the CPU "
|
|
482
|
+
"encode; --no-hw for prores_ks")
|
|
483
|
+
m = _re.search(r"(?:^|\s)-q:v\s+(\d+)", line or "")
|
|
484
|
+
return (f"{enc}{' -q:v ' + m.group(1) if m else ''} is not CRF-equivalent: --quality (or the preset's CRF) is mapped "
|
|
485
|
+
"to -q:v by an approximate SSIM fit (docs/design-decisions.md), so size and detail differ from the x264/x265 "
|
|
486
|
+
"encode (~1.1-3.5x the bytes at matched SSIM); `verified` covers the output's measured properties, not quality "
|
|
487
|
+
"parity with the CPU encode" + ("" if no_cpu_encoder else "; --no-hw for the CRF encode"))
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _encoder_report(ctx: "Context") -> Dict[str, Any]:
|
|
491
|
+
"""`encoder`: the last video encoder this run's ffmpeg commands name (after any GPU->CPU
|
|
492
|
+
fallback, since run() rewrites the recorded command), `copy` for a stream copy; absent when no
|
|
493
|
+
command encoded video. `hw` (hw_report): present whenever VideoToolbox was asked for (--hw or
|
|
494
|
+
$FFMPEG_SKILL_HW, a stage's, or the variable a delivery preset does not take)."""
|
|
495
|
+
enc, _line = _video_encoders(ctx.commands)
|
|
496
|
+
out: Dict[str, Any] = {"encoder": enc} if enc else {}
|
|
497
|
+
if ctx.hw or ctx.hw_stages or ctx.hw_env_ignored or ctx.hw_auto:
|
|
498
|
+
out["hw"] = hw_report(ctx, enc)
|
|
499
|
+
return out
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _hw_notes_for(ctx: "Context") -> List[str]:
|
|
503
|
+
"""Top-level `notes` lines for the GPU encodes this result stands on: this tool's last encode,
|
|
504
|
+
and (render.py) every stage that ran on VideoToolbox."""
|
|
505
|
+
enc, line = _video_encoders(ctx.commands)
|
|
506
|
+
out: List[str] = []
|
|
507
|
+
cpu = {"h264_videotoolbox": "libx264", "hevc_videotoolbox": "libx265"}.get(enc or "")
|
|
508
|
+
for note in [hw_quality_note(enc, line, cpu in ctx.hw_auto)] + [st.get("quality_note") for st in ctx.hw_stages]:
|
|
509
|
+
if note and note not in out:
|
|
510
|
+
out.append(note)
|
|
511
|
+
return out
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def absorb_stage_hw(stage: str, doc: Any, ctx: "Optional[Context]" = None) -> None:
|
|
515
|
+
"""render.py runs each stage as a child process: carry the stage's `hw` facts (fell back, and
|
|
516
|
+
why; ran on VideoToolbox, with its quality note) into this result, which records only the
|
|
517
|
+
command lines."""
|
|
518
|
+
ctx = ctx or STATE
|
|
519
|
+
hw = doc.get("hw") if isinstance(doc, dict) else None
|
|
520
|
+
if not isinstance(hw, dict):
|
|
521
|
+
return
|
|
522
|
+
for n in hw.get("notes") or []:
|
|
523
|
+
# once: this process may have said it already (waveform.py's own encode), or another stage
|
|
524
|
+
if n not in ctx.hw_notes and not any(existing.endswith(": " + n) for existing in ctx.hw_notes):
|
|
525
|
+
ctx.hw_notes.append(f"{stage}: {n}")
|
|
526
|
+
enc, line = _video_encoders([str(c) for c in (doc.get("commands") or [])])
|
|
527
|
+
quality = hw_quality_note(enc, line, hw.get("source") == "auto") if hw.get("used") else None
|
|
528
|
+
ctx.hw_stages.append({"stage": stage, "requested": bool(hw.get("requested")), "source": hw.get("source"),
|
|
529
|
+
"used": hw.get("used"), "fallback": bool(hw.get("fallback")), "quality_note": quality})
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _stage_hw_notes(doc: Dict[str, Any]) -> List[str]:
|
|
533
|
+
"""The notes lines a stage's document carries only because of its GPU encode (its `hw.notes`
|
|
534
|
+
and the VideoToolbox quality line): absorb_stage_hw() already reports those, once."""
|
|
535
|
+
hw = doc.get("hw") if isinstance(doc.get("hw"), dict) else {}
|
|
536
|
+
out = [str(n) for n in hw.get("notes") or []]
|
|
537
|
+
enc, line = _video_encoders([str(c) for c in (doc.get("commands") or [])])
|
|
538
|
+
for no_cpu in (False, True):
|
|
539
|
+
q = hw_quality_note(enc, line, no_cpu)
|
|
540
|
+
if q:
|
|
541
|
+
out.append(q)
|
|
542
|
+
return out
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
# A stage's own artifact checks: a stage that completed passed them (verify_output() fails the
|
|
546
|
+
# stage otherwise), and its artifact is an intermediate, so carrying them would only lengthen the list.
|
|
547
|
+
_STAGE_ARTIFACT_STEPS = ("probe", "exists")
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def absorb_stage(stage: str, doc: Any, ctx: "Optional[Context]" = None) -> Dict[str, Any]:
|
|
551
|
+
"""A child tool's --json document into this result: its `hw` facts (absorb_stage_hw), its
|
|
552
|
+
`diagnostics` records and its `notes` (each tagged with the stage it came from), and -- for a
|
|
553
|
+
stage that completed in a real run -- its verification steps beyond the artifact probe, tagged
|
|
554
|
+
with `stage`, which emit() adds to this result's own: the parent's `verified` is then the
|
|
555
|
+
conjunction of every stage's (a stage that said `verified: false` without a failing step adds
|
|
556
|
+
one `{step: verified, stage, ok: false}`). Returns the fields a re-raise of the stage's failure
|
|
557
|
+
carries in its own `error`: the child's `reason` and `details`."""
|
|
558
|
+
ctx = ctx or STATE
|
|
559
|
+
absorb_stage_hw(stage, doc, ctx)
|
|
560
|
+
if not isinstance(doc, dict):
|
|
561
|
+
return {}
|
|
562
|
+
for bucket in ("warnings", "fallbacks", "skipped"):
|
|
563
|
+
for entry in (doc.get("diagnostics") or {}).get(bucket) or []:
|
|
564
|
+
if isinstance(entry, dict):
|
|
565
|
+
tagged = dict(entry, stage=entry.get("stage") or stage)
|
|
566
|
+
if tagged not in getattr(ctx, bucket):
|
|
567
|
+
getattr(ctx, bucket).append(tagged)
|
|
568
|
+
hw_only = _stage_hw_notes(doc)
|
|
569
|
+
for n in doc.get("notes") or []:
|
|
570
|
+
if not isinstance(n, str) or n in hw_only or n.endswith(ENV_HW_NOTE) or any(n.endswith(": " + h) for h in hw_only):
|
|
571
|
+
continue
|
|
572
|
+
# a nested stage's note (render.py inside a pack) already names its stage
|
|
573
|
+
tagged_note = n if n.startswith(f"{stage}: ") else f"{stage}: {n}"
|
|
574
|
+
if tagged_note not in ctx.notes:
|
|
575
|
+
ctx.notes.append(tagged_note)
|
|
576
|
+
if doc.get("status") == "completed" and not doc.get("dry_run") and not ctx.dry_run:
|
|
577
|
+
carried = [dict(s, stage=s.get("stage") or stage) for s in doc.get("verification") or []
|
|
578
|
+
if isinstance(s, dict) and (s.get("step") not in _STAGE_ARTIFACT_STEPS or not s.get("ok"))]
|
|
579
|
+
if doc.get("verified") is False and all(s.get("ok") for s in carried):
|
|
580
|
+
carried.append({"step": "verified", "stage": stage, "ok": False})
|
|
581
|
+
for s in carried:
|
|
582
|
+
if s not in ctx.stage_verification:
|
|
583
|
+
ctx.stage_verification.append(s)
|
|
584
|
+
err = doc.get("error") if isinstance(doc.get("error"), dict) else {}
|
|
585
|
+
return {k: err[k] for k in ("reason", "details") if err.get(k) is not None}
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def steps_encoder_report(steps: Sequence["Tuple[str, Any]"]) -> Dict[str, Any]:
|
|
589
|
+
"""batch.py's per-item `encoder`, `hw` and `notes`, from the --json documents of the steps
|
|
590
|
+
(child processes) that made the item: the last encoder a step ran (a later stream copy keeps
|
|
591
|
+
the encode before it), and their GPU facts as render.py's result carries its stages'."""
|
|
592
|
+
ctx = Context()
|
|
593
|
+
ctx.dry_run = STATE.dry_run
|
|
594
|
+
enc: Optional[str] = None
|
|
595
|
+
for name, doc in steps:
|
|
596
|
+
step_enc = doc.get("encoder") if isinstance(doc, dict) else None
|
|
597
|
+
if step_enc and (step_enc != "copy" or enc is None):
|
|
598
|
+
enc = step_enc
|
|
599
|
+
absorb_stage_hw(name, doc, ctx)
|
|
600
|
+
out: Dict[str, Any] = {"encoder": enc} if enc else {}
|
|
601
|
+
if ctx.hw_stages:
|
|
602
|
+
out["hw"] = hw_report(ctx, enc)
|
|
603
|
+
quality = [st["quality_note"] for st in ctx.hw_stages if st.get("quality_note")]
|
|
604
|
+
if quality:
|
|
605
|
+
out["notes"] = list(dict.fromkeys(quality))
|
|
606
|
+
return out
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
# The properties each writing tool does NOT measure about its output, by tool name: the unverified
|
|
610
|
+
# range U that every --json result reports (docs/contract.md "unverified"). A property listed here
|
|
611
|
+
# is one a caller might assume was checked; naming it is the difference between "verified" meaning
|
|
612
|
+
# "the listed properties were measured" and "everything is fine". Kept beside emit() so a tool
|
|
613
|
+
# cannot report verified without this list travelling with it.
|
|
614
|
+
UNVERIFIED: Dict[str, List[str]] = {
|
|
615
|
+
"cut": ["picture_content"],
|
|
616
|
+
"join": ["picture_content", "transition_look"],
|
|
617
|
+
"fit": ["subject_framing"],
|
|
618
|
+
"crop": ["subject_framing"],
|
|
619
|
+
"caption": ["rendered_placement", "legibility"],
|
|
620
|
+
"overlay": ["rendered_placement"],
|
|
621
|
+
"graphics": ["rendered_placement"],
|
|
622
|
+
"color": ["grade_look"],
|
|
623
|
+
"export": ["picture_content"],
|
|
624
|
+
"render": ["picture_content", "rendered_placement"],
|
|
625
|
+
"silence": ["removed_span_content"],
|
|
626
|
+
"audio": ["mix_balance"],
|
|
627
|
+
"loudness": ["perceived_loudness"],
|
|
628
|
+
"sync": ["lip_sync"],
|
|
629
|
+
"multicam": ["lip_sync", "shot_choice"],
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
# a picture and its sound may differ in length by this much more than they did in the input
|
|
634
|
+
STREAM_LENGTH_TOLERANCE = 0.25
|
|
635
|
+
# how many seconds at each end of every kept stream the decode check decodes
|
|
636
|
+
DECODE_WINDOW_SECONDS = 1.0
|
|
637
|
+
# how much earlier than its window the tail decode starts reading (a seek past the last keyframe)
|
|
638
|
+
DECODE_SEEK_MARGIN_SECONDS = 10.0
|
|
639
|
+
# how far back the one retry of an empty tail reads (a GOP longer than the margin)
|
|
640
|
+
DECODE_LONG_GOP_SECONDS = 60.0
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _expected_count(want: Any) -> int:
|
|
644
|
+
"""`expect_streams` values: a count, or True/False for "at least one" / "none"."""
|
|
645
|
+
return int(want) if not isinstance(want, bool) else (1 if want else 0)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def stream_inventory_step(meta: Dict[str, Any], expect: Dict[str, Any]) -> Dict[str, Any]:
|
|
649
|
+
"""The output's stream composition checked against what the operation should have produced
|
|
650
|
+
(#367: a cut of an MPEG-TS source lost its whole video stream and still said verified: true,
|
|
651
|
+
because the only properties measured were duration and start skew). `expect` comes from the
|
|
652
|
+
input's own probe and the tool's arguments (provenance "input_premeasurement"): a stream the
|
|
653
|
+
input had and the operation was not told to drop must still be there. A value is a count
|
|
654
|
+
(the cut, join and export writers map one stream of each kind) or a bool for "at least one";
|
|
655
|
+
fewer streams than that is `missing`."""
|
|
656
|
+
counts = meta.get("stream_counts") or {k: int(bool(meta.get(k))) for k in expect}
|
|
657
|
+
want = {k: _expected_count(v) for k, v in expect.items()}
|
|
658
|
+
got = {k: int(counts.get(k) or 0) if meta.get(k) else 0 for k in expect}
|
|
659
|
+
missing = [k for k in expect if got[k] < want[k]]
|
|
660
|
+
step: Dict[str, Any] = {"step": "streams", "property": "stream_inventory",
|
|
661
|
+
"expected": {k: want[k] > 0 for k in expect}, "measured": {k: got[k] > 0 for k in expect},
|
|
662
|
+
"expected_count": want, "measured_count": got,
|
|
663
|
+
"provenance": "input_premeasurement", "ok": not missing}
|
|
664
|
+
if missing:
|
|
665
|
+
step["missing"] = missing
|
|
666
|
+
return step
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _finite(v: Any) -> Optional[float]:
|
|
670
|
+
return float(v) if isinstance(v, (int, float)) and math.isfinite(v) else None
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def own_length(s: Optional[Dict[str, Any]]) -> Optional[float]:
|
|
674
|
+
"""The length of one probed stream (`meta["video"]`, `meta["audio"]`): its duration, else the
|
|
675
|
+
DURATION tag Matroska/WebM keep, which is where the stream ENDS on the file's clock (the
|
|
676
|
+
muxer's last timestamp plus its packet's duration), not how long it lasts: a sound from 1 s
|
|
677
|
+
to 6 s is tagged 6. The tag less the stream's start (from 0 when the start is a priming
|
|
678
|
+
frame before 0). A value that is not a finite number is no length (a NaN compares false and
|
|
679
|
+
would pass every check)."""
|
|
680
|
+
s = s or {}
|
|
681
|
+
duration = _finite(s.get("duration"))
|
|
682
|
+
if duration is not None and duration > 0:
|
|
683
|
+
return duration
|
|
684
|
+
tagged = _finite(s.get("tagged_duration"))
|
|
685
|
+
if tagged is None:
|
|
686
|
+
return None
|
|
687
|
+
length = tagged - max(_finite(s.get("start_time")) or 0.0, 0.0)
|
|
688
|
+
return length if length > 0 else None
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def own_end(s: Optional[Dict[str, Any]]) -> Optional[float]:
|
|
692
|
+
"""Where one probed stream ends on the file's own timestamps: its start plus its duration,
|
|
693
|
+
else the Matroska/WebM DURATION tag, which is already that end."""
|
|
694
|
+
s = s or {}
|
|
695
|
+
duration = _finite(s.get("duration"))
|
|
696
|
+
if duration is not None and duration > 0:
|
|
697
|
+
return (_finite(s.get("start_time")) or 0.0) + duration
|
|
698
|
+
if own_length(s) is None:
|
|
699
|
+
return None
|
|
700
|
+
return _finite(s.get("tagged_duration"))
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def stream_length(meta: Dict[str, Any], kind: str) -> Optional[float]:
|
|
704
|
+
"""One stream's own length (own_length())."""
|
|
705
|
+
return own_length(meta.get(kind))
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
LENGTH_UNREAD_HINT = ("remux the file so its container states a length (export.py INPUT --preset copy -o remuxed.mkv), "
|
|
709
|
+
"then run this on the remux")
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def input_length(meta: Optional[Dict[str, Any]], path: Optional[str] = None) -> float:
|
|
713
|
+
"""An input's length in seconds, for a tool that computes with it (#491). A file that states
|
|
714
|
+
no length (Matroska written to a pipe: ffprobe prints N/A for the container and every stream)
|
|
715
|
+
probes as duration None, and `meta.get("duration") or 0.0` read that as a clip 0 s long: a
|
|
716
|
+
speed factor of 0.00x, "--at 1 is outside the clip (0..0.000)", a reverse of no frames. Unread
|
|
717
|
+
is not zero, so this refuses, as check.py's duration row says "could not measure". A dry run's
|
|
718
|
+
pending input (probe()'s stub, duration 0.0), a stated length of 0 and a still picture (one
|
|
719
|
+
image read by an image demuxer has no length to state) pass through as before."""
|
|
720
|
+
meta = meta or {}
|
|
721
|
+
length = meta.get("duration")
|
|
722
|
+
fmt = meta.get("format") or ""
|
|
723
|
+
still = fmt == "image2" or fmt.endswith("_pipe") # probe._is_still()'s rule, on the probe document
|
|
724
|
+
if length is None and not meta.get("dry_run") and not still:
|
|
725
|
+
die(f"the length of {path or meta.get('file') or 'the input'} could not be read: neither its container nor "
|
|
726
|
+
"its streams state one, and this operation is computed from the input's length",
|
|
727
|
+
kind="input", hint=LENGTH_UNREAD_HINT)
|
|
728
|
+
return float(length or 0.0)
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
STILL_AS_CLIP_HINT = ("make a clip of the still first (insert.py STILL --duration SECONDS), "
|
|
732
|
+
"then run this on that clip")
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def refuse_still(meta: Optional[Dict[str, Any]], path: Optional[str], why: str) -> None:
|
|
736
|
+
"""Refuse a still picture given where a clip with a length is needed (#531), kind input, naming
|
|
737
|
+
the input and insert.py. input_length() lets a still through as 0 s (grid.py and broll.py show
|
|
738
|
+
one for as long as the clip beside it), and a tool that then computed with that 0 refused with
|
|
739
|
+
a length of 0.000 or a speed of 0.00x, or wrote nothing and failed as kind output. `why` says
|
|
740
|
+
what the tool needed the length for. A dry run's pending input is not a still."""
|
|
741
|
+
meta = meta or {}
|
|
742
|
+
fmt = str(meta.get("format") or "")
|
|
743
|
+
if meta.get("dry_run") or not (fmt == "image2" or fmt.endswith("_pipe")): # probe._is_still()'s rule
|
|
744
|
+
return
|
|
745
|
+
die(f"{path or meta.get('file') or 'the input'} is a still picture (one image, no length of its own): {why}",
|
|
746
|
+
kind="input", hint=STILL_AS_CLIP_HINT)
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def stream_end(meta: Dict[str, Any], kind: str) -> Optional[float]:
|
|
750
|
+
"""Where one stream ends on the file's timeline (own_end())."""
|
|
751
|
+
return own_end(meta.get(kind))
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def file_origin(meta: Dict[str, Any]) -> float:
|
|
755
|
+
"""Where the file's timeline starts: the container's start time, else its earliest stream's.
|
|
756
|
+
A -ss, a cut's --start and a window are counted from here, while stream starts and ends are
|
|
757
|
+
on the file's own timestamps."""
|
|
758
|
+
if isinstance(meta.get("start_time"), (int, float)):
|
|
759
|
+
return float(meta["start_time"])
|
|
760
|
+
starts = [(meta.get(k) or {}).get("start_time") for k in ("video", "audio")]
|
|
761
|
+
return min([s for s in starts if isinstance(s, (int, float))] or [0.0])
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
def stream_lengths_step(meta: Dict[str, Any], references: Sequence[Dict[str, Any]],
|
|
765
|
+
tolerance: float = STREAM_LENGTH_TOLERANCE,
|
|
766
|
+
windows: Optional[Sequence[Tuple[float, float]]] = None) -> Dict[str, Any]:
|
|
767
|
+
"""Where the picture and the sound of the output end, against each other, allowing the gap
|
|
768
|
+
the inputs already had. A filename with a space was reported to have lost 40 s of sound with
|
|
769
|
+
no error: the container's length is the longest stream's, so a duration check passes while
|
|
770
|
+
one stream stops early. `short` names a stream that ends more than `tolerance` (plus the
|
|
771
|
+
inputs' own shortfall, summed over the inputs) before the other one. Ends, not lengths: a
|
|
772
|
+
stream that only starts late is the start-skew check's (cut.py reports it in a note). A length
|
|
773
|
+
that cannot be read is not a pass (`not_measured`). `windows` (cut.py's requested ranges, on
|
|
774
|
+
the input's own timeline) count only the gap the input has inside them: a source whose video
|
|
775
|
+
runs 5 s past its sound allows nothing to a cut from its middle."""
|
|
776
|
+
kinds = ("video", "audio")
|
|
777
|
+
lengths = {k: stream_length(meta, k) for k in kinds}
|
|
778
|
+
step: Dict[str, Any] = {"step": "stream_lengths", "property": "stream_end", "measured": lengths,
|
|
779
|
+
"tolerance": tolerance, "provenance": "input_premeasurement"}
|
|
780
|
+
unknown = [k for k in kinds if lengths[k] is None]
|
|
781
|
+
if unknown:
|
|
782
|
+
return dict(step, ok=False, reason="not_measured: no length for the %s stream" % " and ".join(unknown))
|
|
783
|
+
allowed: Dict[str, float] = {k: 0.0 for k in kinds}
|
|
784
|
+
unread_input = False
|
|
785
|
+
for ref in references:
|
|
786
|
+
if not all(ref.get(k) for k in kinds):
|
|
787
|
+
continue # an input with one stream (join's silent clip) brings no gap of its own
|
|
788
|
+
ref_ends = {k: stream_end(ref, k) for k in kinds}
|
|
789
|
+
if None in ref_ends.values():
|
|
790
|
+
unread_input = True # its gap is unknown, not zero
|
|
791
|
+
continue
|
|
792
|
+
rel = {k: ref_ends[k] - file_origin(ref) for k in kinds} # the clock cut's ranges are on
|
|
793
|
+
for s, e in (windows or [(0.0, max(rel.values()))]):
|
|
794
|
+
inside = {k: max(s, min(e, rel[k])) for k in kinds}
|
|
795
|
+
top = max(inside.values())
|
|
796
|
+
for k in kinds:
|
|
797
|
+
allowed[k] += top - inside[k]
|
|
798
|
+
ends = {k: stream_end(meta, k) for k in kinds}
|
|
799
|
+
last = max(ends.values())
|
|
800
|
+
raw = {k: last - ends[k] for k in kinds}
|
|
801
|
+
short = [k for k in kinds if raw[k] > allowed[k] + tolerance]
|
|
802
|
+
step.update(ends={k: round(v, 3) for k, v in ends.items()}, shortfall={k: round(v, 3) for k, v in raw.items()},
|
|
803
|
+
input_shortfall={k: round(v, 3) for k, v in allowed.items()}, ok=not short)
|
|
804
|
+
if short and unread_input:
|
|
805
|
+
# a gap the output has may be one an input already had: neither a pass nor a "short"
|
|
806
|
+
step["input_shortfall"] = None
|
|
807
|
+
step["reason"] = ("not_measured: an input's stream length cannot be read, so whether the %s gap "
|
|
808
|
+
"was already in the input is unknown" % " and ".join(short))
|
|
809
|
+
elif short:
|
|
810
|
+
step["short"] = short
|
|
811
|
+
return step
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def decode_step(path: str, meta: Dict[str, Any], kinds: Sequence[str], window: float = DECODE_WINDOW_SECONDS) -> Dict[str, Any]:
|
|
815
|
+
"""Decode the first `window` seconds of every kept stream and the last `window` before that
|
|
816
|
+
stream's own end, and count the frames. A stream ffprobe lists from the container header can
|
|
817
|
+
still hold nothing a decoder accepts; the inventory and length checks read the header, this
|
|
818
|
+
one reads the payload. The tail read starts DECODE_SEEK_MARGIN_SECONDS earlier, so a seek that
|
|
819
|
+
lands past the last keyframe (MPEG-TS seeks by timestamp, not to a keyframe) still decodes,
|
|
820
|
+
but only frames in the last `window` count, and the read stops a second past the end. A
|
|
821
|
+
stream whose own end cannot be read is not decoded at its end: its tail is `not_measured`,
|
|
822
|
+
not undecodable (the container's end is the longest stream's, not this one's)."""
|
|
823
|
+
from _common.runner import require_tool, run_analysis
|
|
824
|
+
ffmpeg = require_tool("ffmpeg")
|
|
825
|
+
frames: Dict[str, Dict[str, int]] = {}
|
|
826
|
+
unmeasured: List[str] = []
|
|
827
|
+
for kind in kinds:
|
|
828
|
+
# 0:V is the motion picture only: an attached cover picture would be 0:v:0
|
|
829
|
+
sel = ["-map", "0:%s:0" % ("V" if kind == "video" else "a"), "-f", "framecrc", "-"]
|
|
830
|
+
base = [ffmpeg, "-hide_banner", "-nostdin", "-v", "error"]
|
|
831
|
+
origin = file_origin(meta)
|
|
832
|
+
# the head is the stream's own first window: sound that starts 2 s in has none in the file's
|
|
833
|
+
head_from = max(0.0, ((meta.get(kind) or {}).get("start_time") or origin) - origin)
|
|
834
|
+
head = run_analysis(base + ["-ss", "%.3f" % head_from, "-i", path, "-t", "%g" % window] + sel, check=False)
|
|
835
|
+
frames[kind] = {"head": _framecrc_frames(head) if head.returncode == 0 else 0}
|
|
836
|
+
# the stream's own end only: the container's is the longest stream's, and a shorter stream
|
|
837
|
+
# read there would decode nothing and be called undecodable when it is only unmeasured
|
|
838
|
+
end = stream_end(meta, kind)
|
|
839
|
+
if end is None:
|
|
840
|
+
frames[kind]["tail"] = 0
|
|
841
|
+
unmeasured.append(kind)
|
|
842
|
+
continue
|
|
843
|
+
tail_from = max(0.0, end - origin - window - DECODE_SEEK_MARGIN_SECONDS) # -ss counts from the origin
|
|
844
|
+
# -copyts keeps the file's own timestamps, the timeline `end` is measured on
|
|
845
|
+
def tail_frames(start: float) -> int:
|
|
846
|
+
proc = run_analysis(base + ["-copyts", "-ss", "%.3f" % start, "-t", "%g" % (end - origin - start + 1.0), "-i", path]
|
|
847
|
+
+ sel, check=False)
|
|
848
|
+
return _framecrc_frames(proc, since=end - window) if proc.returncode == 0 else 0
|
|
849
|
+
frames[kind]["tail"] = tail_frames(tail_from)
|
|
850
|
+
if not frames[kind]["tail"] and tail_from > 0:
|
|
851
|
+
# a GOP longer than the margin (long-GOP MPEG-TS) has no keyframe after tail_from: read
|
|
852
|
+
# once more from up to DECODE_LONG_GOP_SECONDS earlier before calling it undecodable
|
|
853
|
+
# (bounded, so a failing hour-long stream is not decoded whole)
|
|
854
|
+
frames[kind]["tail"] = tail_frames(max(0.0, end - origin - window - DECODE_LONG_GOP_SECONDS))
|
|
855
|
+
bad = [k for k in kinds if not all(frames[k].values())]
|
|
856
|
+
# no provenance: it says where an expected value came from, and this step has none (#403: it
|
|
857
|
+
# said "measurement", which is not one of the contract's values)
|
|
858
|
+
step: Dict[str, Any] = {"step": "decode", "property": "decodable", "frames": frames, "window": window,
|
|
859
|
+
"ok": not bad}
|
|
860
|
+
if bad:
|
|
861
|
+
step["undecodable"] = [k for k in bad if k not in unmeasured]
|
|
862
|
+
if unmeasured:
|
|
863
|
+
step["reason"] = "not_measured: no end time for the %s stream" % " and ".join(unmeasured)
|
|
864
|
+
return step
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def _framecrc_frames(proc: Any, since: Optional[float] = None) -> int:
|
|
868
|
+
"""Frames in ffmpeg's framecrc output; with `since`, only those still on screen after that time
|
|
869
|
+
(pts plus duration past it: a last frame held for 2 s starts before the window and still
|
|
870
|
+
counts, one that ends exactly at it does not). Rows
|
|
871
|
+
are `stream, dts, pts, duration, size, crc`, timestamps in the `#tb N: num/den` time base."""
|
|
872
|
+
tb: Dict[str, float] = {}
|
|
873
|
+
n = 0
|
|
874
|
+
for line in (proc.stdout or "").splitlines():
|
|
875
|
+
if line.startswith("#tb "):
|
|
876
|
+
idx, frac = line[4:].split(":", 1)
|
|
877
|
+
num, den = frac.strip().split("/")
|
|
878
|
+
tb[idx.strip()] = float(num) / float(den)
|
|
879
|
+
elif line and not line.startswith("#"):
|
|
880
|
+
cols = [c.strip() for c in line.split(",")]
|
|
881
|
+
if since is None:
|
|
882
|
+
n += 1
|
|
883
|
+
elif len(cols) > 3 and cols[0] in tb and (float(cols[2]) + float(cols[3])) * tb[cols[0]] > since + 1e-6:
|
|
884
|
+
n += 1
|
|
885
|
+
return n
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def file_identity(path: str) -> "Optional[Dict[str, int]]":
|
|
889
|
+
"""{size, mtime_ns} of a file this run wrote or measured (2.24): what ties a later check.py
|
|
890
|
+
--expect-identity to this file rather than to whatever sits at the path then. None when the
|
|
891
|
+
path is not a regular file."""
|
|
892
|
+
try:
|
|
893
|
+
st = os.stat(path)
|
|
894
|
+
except OSError:
|
|
895
|
+
return None
|
|
896
|
+
return {"size": st.st_size, "mtime_ns": st.st_mtime_ns} if os.path.isfile(path) else None
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
_RESULT_FIELDS = frozenset({"status", "dry_run", "commands", "probe", "output_identity", "verified", "lossless"})
|
|
900
|
+
_OUTPUT_MEASUREMENTS = frozenset({
|
|
901
|
+
"duration", "width", "height", "resolution", "fps", "size_bytes",
|
|
902
|
+
"output_duration", "output_width", "output_height", "output_resolution", "output_fps", "output_size_bytes",
|
|
903
|
+
})
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def _verified_artifact(path: str) -> bool:
|
|
907
|
+
identity = file_identity(path)
|
|
908
|
+
if not identity or not identity["size"]:
|
|
909
|
+
return False
|
|
910
|
+
if os.path.splitext(path)[1].lower() not in MEDIA_EXT:
|
|
911
|
+
return True
|
|
912
|
+
meta = probe(path, role="output", required=False)
|
|
913
|
+
return bool(meta.get("video") or meta.get("audio"))
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def emit(output: Optional[str], *, ctx: "Optional[Context]" = None,
|
|
917
|
+
verification_paths: Sequence[str] = (), **extra: Any) -> None:
|
|
918
|
+
"""Final stdout line: the output path, or a JSON document with --json.
|
|
919
|
+
|
|
920
|
+
`ctx` is the optional per-request Context added in 1.10 (2.0 makes it required, issue #189 B);
|
|
921
|
+
omitted, every read falls back to the process-global STATE as before. A tool with no
|
|
922
|
+
single output can name the files its verification steps concern in verification_paths."""
|
|
923
|
+
ctx = ctx or STATE
|
|
924
|
+
_set_current_ctx(ctx) # so the atexit hook writes (or skips) this ctx's plan, not STATE's
|
|
925
|
+
meta: Dict[str, Any] = {}
|
|
926
|
+
if output and not ctx.dry_run:
|
|
927
|
+
meta = verify_output(output) # dies (status: failed, kind: output) if the artifact is unusable
|
|
928
|
+
_report_dropped_audio_tracks(meta, ctx)
|
|
929
|
+
_report_dropped_hdr10_metadata(meta, ctx)
|
|
930
|
+
_report_reduced_bit_depth(output, meta, ctx)
|
|
931
|
+
carry = source_carry(output, ctx, extra)
|
|
932
|
+
if carry and "source_carry" not in extra:
|
|
933
|
+
extra["source_carry"] = carry
|
|
934
|
+
if ctx.json:
|
|
935
|
+
for key in _RESULT_FIELDS.intersection(extra):
|
|
936
|
+
del extra[key]
|
|
937
|
+
if output and ctx.dry_run:
|
|
938
|
+
for key in _OUTPUT_MEASUREMENTS.intersection(extra):
|
|
939
|
+
extra[key] = None
|
|
940
|
+
doc: Dict[str, Any] = {"status": "completed", "output": output, "dry_run": ctx.dry_run, "commands": list(ctx.commands)}
|
|
941
|
+
probed = bool(meta and not meta.get("dry_run"))
|
|
942
|
+
if probed and meta.get("duration") is not None:
|
|
943
|
+
# the first thing a caller reads: what the file is, and where its length misses what
|
|
944
|
+
# was asked (a 120 ms miss of a stream copy sat in duration_error_ms under verified: true)
|
|
945
|
+
v, got, want = meta.get("video") or {}, float(meta["duration"]), extra.get("expected_duration")
|
|
946
|
+
miss = f" (ASKED {want:.3f} s: {abs(got - want):.3f} s {'longer' if got > want else 'shorter'})" if isinstance(want, (int, float)) and abs(got - want) > 0.04 else ""
|
|
947
|
+
shape = f", {v.get('width')}x{v.get('height')}, {v.get('fps')} fps" if v else ""
|
|
948
|
+
doc = {"status": "completed", "wrote": f"{got:.3f} s{miss}{shape}, " + ("picture and sound" if v and meta.get("audio") else "picture only" if v else "sound only"), **doc}
|
|
949
|
+
if probed:
|
|
950
|
+
doc["probe"] = meta
|
|
951
|
+
identity = file_identity(output) if output and not ctx.dry_run else None
|
|
952
|
+
if identity:
|
|
953
|
+
doc["output_identity"] = identity
|
|
954
|
+
# What this tool itself verified about its artifact (issue #189 C, "verify as part of the
|
|
955
|
+
# contract"): the probe every writing tool runs, plus the measurements a tool adds
|
|
956
|
+
# (`verification` extra: loudness after the write, a platform check). `verified` is true
|
|
957
|
+
# only when the file was written, probed, and every self-check met its target; a dry run
|
|
958
|
+
# verified nothing. Spec failures the tool cannot fix on its own (export's loudness gap)
|
|
959
|
+
# keep status completed and say verified: false, so a caller keys on one field.
|
|
960
|
+
expect_streams = extra.pop("expect_streams", None)
|
|
961
|
+
stream_reference = extra.pop("stream_reference", None)
|
|
962
|
+
stream_windows = extra.pop("stream_windows", None)
|
|
963
|
+
own_steps = extra.pop("verification", None) or []
|
|
964
|
+
steps: List[Dict[str, Any]] = ([{"step": "probe", "ok": True}] if probed else [])
|
|
965
|
+
steps.extend(s for s in own_steps if s.get("step") != "probe")
|
|
966
|
+
if probed and expect_streams:
|
|
967
|
+
steps.append(stream_inventory_step(meta, expect_streams))
|
|
968
|
+
kept = [k for k in ("video", "audio") if _expected_count(expect_streams.get(k, 0))]
|
|
969
|
+
if stream_reference is not None and len(kept) == 2:
|
|
970
|
+
steps.append(stream_lengths_step(meta, stream_reference, windows=stream_windows))
|
|
971
|
+
present = [k for k in kept if meta.get(k)]
|
|
972
|
+
if present:
|
|
973
|
+
steps.append(decode_step(output, meta, present))
|
|
974
|
+
# a tool that ran others (render.py) verified what its stages verified too (absorb_stage())
|
|
975
|
+
steps += [s for s in ctx.stage_verification if s not in steps]
|
|
976
|
+
non_media = bool(output and not ctx.dry_run and os.path.splitext(output)[1].lower() not in MEDIA_EXT)
|
|
977
|
+
if non_media:
|
|
978
|
+
steps.insert(0, {"step": "exists", "ok": True})
|
|
979
|
+
if ctx.dry_run:
|
|
980
|
+
steps = []
|
|
981
|
+
passed = bool(steps) and all(s.get("ok") is True for s in steps)
|
|
982
|
+
evidence = probed or non_media
|
|
983
|
+
if passed and not evidence and verification_paths:
|
|
984
|
+
evidence = all(_verified_artifact(path) for path in dict.fromkeys(verification_paths))
|
|
985
|
+
doc["verified"] = bool(passed and evidence)
|
|
986
|
+
doc["lossless"] = bool(probed and output and stream_copy_output(ctx, output))
|
|
987
|
+
# a failed check asserts that something in artifact, reference, instrument or the expected
|
|
988
|
+
# value's provenance is wrong; until a tool knows which, it says it does not know
|
|
989
|
+
steps = [dict(s, attribution=s.get("attribution") or "unresolved") if s.get("ok") is False else s for s in steps]
|
|
990
|
+
doc["verification"] = steps
|
|
991
|
+
tool = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
|
|
992
|
+
if output and not ctx.dry_run and tool in UNVERIFIED and "unverified" not in extra:
|
|
993
|
+
doc["unverified"] = list(UNVERIFIED[tool])
|
|
994
|
+
if tool in ("export", "render") and (extra.get("picture") or extra.get("stage_pictures")):
|
|
995
|
+
doc["unverified"].append("subject_framing")
|
|
996
|
+
doc.update(_encoder_report(ctx))
|
|
997
|
+
doc.update(extra)
|
|
998
|
+
hw_notes = [n for n in _hw_notes_for(ctx) if n not in (doc.get("notes") or [])]
|
|
999
|
+
if hw_notes:
|
|
1000
|
+
doc["notes"] = list(doc.get("notes") or []) + hw_notes
|
|
1001
|
+
_merge_collector(doc, ctx)
|
|
1002
|
+
if ctx.plan:
|
|
1003
|
+
doc["plan"] = write_plan(ctx.plan, output, extra, ctx=ctx)
|
|
1004
|
+
print_json(_brief(doc, meta if probed else {}) if ctx.json_brief else doc)
|
|
1005
|
+
elif ctx.plan:
|
|
1006
|
+
print(write_plan(ctx.plan, output, extra, ctx=ctx))
|
|
1007
|
+
elif output:
|
|
1008
|
+
print(output)
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
# Keys the brief document replaces or drops: the full probe (summarised), the command lines
|
|
1012
|
+
# (counted) and the per-step verification list (its verdict stays as `verified`).
|
|
1013
|
+
_BRIEF_DROP = ("probe", "commands", "verification")
|
|
1014
|
+
|
|
1015
|
+
|
|
1016
|
+
def _brief_summary(meta: Dict[str, Any], extra: Dict[str, Any]) -> Dict[str, Any]:
|
|
1017
|
+
"""The handful of output facts a caller reports or branches on, from the probe this tool
|
|
1018
|
+
already ran -- plus the measured loudness when the tool measured one. Keys whose value is
|
|
1019
|
+
unknown are left out rather than emitted as null."""
|
|
1020
|
+
video = (meta or {}).get("video") or {}
|
|
1021
|
+
audio = (meta or {}).get("audio") or {}
|
|
1022
|
+
summary: Dict[str, Any] = {}
|
|
1023
|
+
duration = (meta or {}).get("duration")
|
|
1024
|
+
if duration is not None:
|
|
1025
|
+
summary["duration_s"] = round(float(duration), 3)
|
|
1026
|
+
for key, value in (("width", video.get("width")), ("height", video.get("height")), ("fps", video.get("fps")),
|
|
1027
|
+
("vcodec", video.get("codec")), ("acodec", audio.get("codec")), ("channels", audio.get("channels"))):
|
|
1028
|
+
if value is not None:
|
|
1029
|
+
summary[key] = value
|
|
1030
|
+
lufs = None
|
|
1031
|
+
for source, key in ((extra.get("result"), "input_i"), (extra.get("measured"), "input_i")):
|
|
1032
|
+
if lufs is None and isinstance(source, dict):
|
|
1033
|
+
lufs = _to_float(source.get(key))
|
|
1034
|
+
for step in extra.get("verification") or []:
|
|
1035
|
+
if lufs is None and isinstance(step, dict):
|
|
1036
|
+
lufs = _to_float(step.get("lufs"))
|
|
1037
|
+
# a silent file measures -inf, which json.dumps writes as the non-standard -Infinity: the
|
|
1038
|
+
# brief document stays valid JSON by leaving the key out instead (the full document's own
|
|
1039
|
+
# `measured`/`result` still carries whatever the tool reported).
|
|
1040
|
+
if lufs is not None and math.isfinite(lufs):
|
|
1041
|
+
summary["lufs"] = round(lufs, 2)
|
|
1042
|
+
return summary
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
def _brief(doc: Dict[str, Any], meta: Dict[str, Any]) -> Dict[str, Any]:
|
|
1046
|
+
"""--json-brief: the same success document with the bulky parts replaced by what a caller
|
|
1047
|
+
acts on. Same keys, same meanings -- `commands` becomes the count of the command lines,
|
|
1048
|
+
`probe` becomes `summary` -- plus every tool-specific key the tool itself passed to emit().
|
|
1049
|
+
Failures are untouched: die() prints the full failure document either way."""
|
|
1050
|
+
brief: Dict[str, Any] = {"status": doc["status"], "output": doc["output"], "dry_run": doc["dry_run"],
|
|
1051
|
+
"verified": doc.get("verified", False)}
|
|
1052
|
+
summary = _brief_summary(meta, doc)
|
|
1053
|
+
if summary:
|
|
1054
|
+
brief["summary"] = summary
|
|
1055
|
+
brief["commands"] = len(doc.get("commands") or [])
|
|
1056
|
+
for key, value in doc.items():
|
|
1057
|
+
if key not in brief and key not in _BRIEF_DROP:
|
|
1058
|
+
brief[key] = value
|
|
1059
|
+
# the emoji report is a full inventory in the long document; brief keeps the two fields a
|
|
1060
|
+
# caller branches on (did colour happen, and how many)
|
|
1061
|
+
if isinstance(brief.get("emoji"), dict):
|
|
1062
|
+
brief["emoji"] = {k: v for k, v in brief["emoji"].items() if k in ("mode", "count")}
|
|
1063
|
+
return brief
|
|
1064
|
+
|
|
1065
|
+
|
|
1066
|
+
PLAN_VERSION = 1
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
_PLAN_STRIP = ("--plan", "--dry-run", "--json", "--json-brief")
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def is_output_shape_flag(token: str) -> bool:
|
|
1073
|
+
"""`--json-brief`, or an abbreviation argparse reads as it (`--json-b`): the flag that changes
|
|
1074
|
+
the shape of the document a tool prints. A plan's argv and a plan's execution leave it out
|
|
1075
|
+
(A181): render.py runs the planned tool with --json and reads its full document, whose
|
|
1076
|
+
`commands` the brief form replaces with a count, and executing a plan recorded with it crashed
|
|
1077
|
+
on that count."""
|
|
1078
|
+
return token.startswith("--json-") and "--json-brief".startswith(token)
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
def _command_complete(line: str) -> bool:
|
|
1082
|
+
"""Whether a `$ CMD` / `[dry-run] $ CMD` stderr line holds the whole command: run() prints it
|
|
1083
|
+
shell-quoted, so a quote still open at the end of the line is an argument with a line break in
|
|
1084
|
+
it (a `-metadata title=` with two lines), continued on the next stderr line."""
|
|
1085
|
+
body = line[2:] if line.startswith("$ ") else line[len("[dry-run] $ "):]
|
|
1086
|
+
try:
|
|
1087
|
+
shlex.split(body)
|
|
1088
|
+
except ValueError:
|
|
1089
|
+
return False
|
|
1090
|
+
return True
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
def stderr_records(stderr: str) -> "List[Tuple[bool, str]]":
|
|
1094
|
+
"""A sibling tool's stderr as (is_command, text) records, in order, for a tool that ran it
|
|
1095
|
+
(render.py's stages and plans): `$ CMD` is the command CMD, a `[dry-run]` line is kept whole as
|
|
1096
|
+
a command record (what render.py has always listed for a dry run), anything else is a line to
|
|
1097
|
+
pass on. A command whose quoted argument holds a line break spans several stderr lines; they
|
|
1098
|
+
are one record again, joined with the break they had (A4: one ffmpeg command became two
|
|
1099
|
+
records, the second passed on as prose). A quote that never closes leaves the lines as they
|
|
1100
|
+
were."""
|
|
1101
|
+
lines = stderr.splitlines(keepends=True)
|
|
1102
|
+
out: "List[Tuple[bool, str]]" = []
|
|
1103
|
+
i = 0
|
|
1104
|
+
while i < len(lines):
|
|
1105
|
+
line = lines[i].rstrip("\r\n")
|
|
1106
|
+
i += 1
|
|
1107
|
+
if not (line.startswith("$ ") or line.startswith("[dry-run]")):
|
|
1108
|
+
out.append((False, line))
|
|
1109
|
+
continue
|
|
1110
|
+
if line.startswith("$ ") or line.startswith("[dry-run] $ "):
|
|
1111
|
+
text, j = line, i
|
|
1112
|
+
while not _command_complete(text) and j < len(lines):
|
|
1113
|
+
text = text + lines[j - 1][len(lines[j - 1].rstrip("\r\n")):] + lines[j].rstrip("\r\n")
|
|
1114
|
+
j += 1
|
|
1115
|
+
if _command_complete(text):
|
|
1116
|
+
line, i = text, j
|
|
1117
|
+
out.append((True, line[2:] if line.startswith("$ ") else line))
|
|
1118
|
+
return out
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
def _plan_at_exit() -> None:
|
|
1122
|
+
ctx = _CURRENT_CTX or STATE
|
|
1123
|
+
if ctx.plan and not ctx.plan_written:
|
|
1124
|
+
try:
|
|
1125
|
+
write_plan(ctx.plan, None, {}, ctx=ctx)
|
|
1126
|
+
except SystemExit:
|
|
1127
|
+
pass
|
|
1128
|
+
|
|
1129
|
+
|
|
1130
|
+
def _plan_inputs(commands: Sequence[str], argv: Sequence[str] = (), ctx: "Optional[Context]" = None) -> List[str]:
|
|
1131
|
+
"""Every existing file the plan depends on: the `-i` inputs of the planned commands, any
|
|
1132
|
+
existing file named in argv, and files registered by the input readers or by
|
|
1133
|
+
escape_filter_path(). Registered paths come from parsed inputs and may start with a dash."""
|
|
1134
|
+
import shlex
|
|
1135
|
+
seen: Dict[str, None] = {}
|
|
1136
|
+
candidates = [a for a in argv if a and not a.startswith("-")] + (ctx or STATE).plan_inputs
|
|
1137
|
+
for a in candidates:
|
|
1138
|
+
if a and a not in seen and os.path.isfile(a):
|
|
1139
|
+
seen[a] = None
|
|
1140
|
+
for line in commands:
|
|
1141
|
+
try:
|
|
1142
|
+
toks = shlex.split(line.split("] ", 1)[1] if line.startswith("[dry-run] ") else line)
|
|
1143
|
+
except ValueError:
|
|
1144
|
+
continue
|
|
1145
|
+
for i, tok in enumerate(toks[:-1]):
|
|
1146
|
+
if tok == "-i" and os.path.isfile(toks[i + 1]) and toks[i + 1] not in seen:
|
|
1147
|
+
seen[toks[i + 1]] = None
|
|
1148
|
+
return list(seen)
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
def _planned_outputs(commands: Sequence[str]) -> List[str]:
|
|
1152
|
+
"""The file each planned command writes: its last argument, unless that is stdout, a pipe or
|
|
1153
|
+
an option (a measurement's `-f null -`)."""
|
|
1154
|
+
import shlex
|
|
1155
|
+
out: List[str] = []
|
|
1156
|
+
for line in commands:
|
|
1157
|
+
try:
|
|
1158
|
+
toks = shlex.split(line.split("] ", 1)[1] if line.startswith("[dry-run] ") else line)
|
|
1159
|
+
except ValueError:
|
|
1160
|
+
continue
|
|
1161
|
+
if len(toks) > 1 and toks[-1] != "-" and not toks[-1].startswith(("pipe:", "-")):
|
|
1162
|
+
out.append(toks[-1])
|
|
1163
|
+
return out
|
|
1164
|
+
|
|
1165
|
+
|
|
1166
|
+
def _plan_unbound_inputs(commands: Sequence[str], ctx: "Optional[Context]" = None) -> List[str]:
|
|
1167
|
+
"""The inputs _plan_inputs() could not fingerprint because they did not exist when the plan
|
|
1168
|
+
was made: a planned command's `-i` file (or a side input registered through
|
|
1169
|
+
escape_filter_path) that is not on disk and is not written by an earlier planned command (the
|
|
1170
|
+
tool's own intermediates are bound by the command that makes them). render.py reports them on
|
|
1171
|
+
execution: nothing checks that their content is what the plan was made for."""
|
|
1172
|
+
import shlex
|
|
1173
|
+
ctx = ctx or STATE
|
|
1174
|
+
produced: List[str] = []
|
|
1175
|
+
out: List[str] = []
|
|
1176
|
+
|
|
1177
|
+
def consider(p: str) -> None:
|
|
1178
|
+
if (not p or p == "-" or p.startswith("pipe:") or p in ctx.plan_generated_inputs or os.path.exists(p)
|
|
1179
|
+
or os.path.abspath(p) in produced or os.path.abspath(p) in out):
|
|
1180
|
+
return
|
|
1181
|
+
out.append(os.path.abspath(p))
|
|
1182
|
+
for p in ctx.plan_inputs:
|
|
1183
|
+
consider(p)
|
|
1184
|
+
for line in commands:
|
|
1185
|
+
try:
|
|
1186
|
+
toks = shlex.split(line.split("] ", 1)[1] if line.startswith("[dry-run] ") else line)
|
|
1187
|
+
except ValueError:
|
|
1188
|
+
continue
|
|
1189
|
+
fmt = None # an input's -f (lavfi's "inputs" are filter graphs, not files)
|
|
1190
|
+
for i, tok in enumerate(toks[:-1]):
|
|
1191
|
+
if tok == "-f":
|
|
1192
|
+
fmt = toks[i + 1]
|
|
1193
|
+
elif tok == "-i":
|
|
1194
|
+
if fmt != "lavfi":
|
|
1195
|
+
consider(toks[i + 1])
|
|
1196
|
+
fmt = None
|
|
1197
|
+
if toks:
|
|
1198
|
+
produced.append(os.path.abspath(toks[-1]))
|
|
1199
|
+
return out
|
|
1200
|
+
|
|
1201
|
+
|
|
1202
|
+
def write_plan(path: str, output: Optional[str], extra: Dict[str, Any], ctx: "Optional[Context]" = None) -> str:
|
|
1203
|
+
"""The dry run as an artifact: what will run, on which exact inputs, producing what, checked
|
|
1204
|
+
how. `render.py PLAN` executes it after re-fingerprinting the inputs (issue #189 C).
|
|
1205
|
+
|
|
1206
|
+
`ctx` is the Context whose commands and inputs the plan describes (emit()/die() pass the one
|
|
1207
|
+
they were given); omitted, it is the process-global STATE as before."""
|
|
1208
|
+
import datetime
|
|
1209
|
+
ctx = ctx or STATE
|
|
1210
|
+
argv = [a for a in sys.argv[1:]]
|
|
1211
|
+
cleaned: List[str] = []
|
|
1212
|
+
skip = False
|
|
1213
|
+
for a in argv:
|
|
1214
|
+
if skip:
|
|
1215
|
+
skip = False
|
|
1216
|
+
continue
|
|
1217
|
+
if a in _PLAN_STRIP or is_output_shape_flag(a):
|
|
1218
|
+
skip = a == "--plan"
|
|
1219
|
+
continue
|
|
1220
|
+
if a.startswith("--plan="):
|
|
1221
|
+
continue
|
|
1222
|
+
cleaned.append(a)
|
|
1223
|
+
tool = os.path.splitext(os.path.basename(sys.argv[0]))[0]
|
|
1224
|
+
verify: List[Dict[str, Any]] = [{"tool": "probe"}] if output else []
|
|
1225
|
+
platform = None
|
|
1226
|
+
if "--platform" in cleaned:
|
|
1227
|
+
platform = cleaned[cleaned.index("--platform") + 1]
|
|
1228
|
+
elif tool == "export" and "--preset" in cleaned:
|
|
1229
|
+
platform = {"youtube": "youtube", "youtube4k": "youtube", "reels": "reels", "x": "x"}.get(cleaned[cleaned.index("--preset") + 1])
|
|
1230
|
+
if platform and output and tool != "check":
|
|
1231
|
+
verify.append({"tool": "check", "platform": platform})
|
|
1232
|
+
plan_inputs = _plan_inputs(ctx.commands, cleaned, ctx)
|
|
1233
|
+
# every file the plan names (#413 review): its inputs, side inputs included (an SRT, a still),
|
|
1234
|
+
# and the output it promises, a default name too, which apply_common could not know
|
|
1235
|
+
for named in plan_inputs + ([output] if output else []):
|
|
1236
|
+
if same_file(named, path):
|
|
1237
|
+
refuse("input", "output_is_input" if named != output else "output_path_taken",
|
|
1238
|
+
f"--plan {path!r} is also {'the output' if named == output else 'an input'} of this run "
|
|
1239
|
+
f"({named!r}); give the plan its own path", output=path, other=named)
|
|
1240
|
+
# and every file a planned command writes (its last argument): a tool with several outputs
|
|
1241
|
+
# (loudness.py --versions, whose `output` is null; export.py's key file) names them only there,
|
|
1242
|
+
# and a plan written over one of them is refused as an existing output when it is executed
|
|
1243
|
+
for written in _planned_outputs(ctx.commands):
|
|
1244
|
+
if same_file(written, path):
|
|
1245
|
+
refuse("input", "output_path_taken", f"--plan {path!r} is also a file this run writes ({written!r}); "
|
|
1246
|
+
"give the plan its own path", output=path, other=written)
|
|
1247
|
+
try:
|
|
1248
|
+
fingerprints = [fingerprint(p, complete=True)
|
|
1249
|
+
if "sha256_full" in ctx.measured_plan_inputs.get(os.path.abspath(p), {})
|
|
1250
|
+
else fingerprint(p) for p in plan_inputs]
|
|
1251
|
+
except OSError as exc:
|
|
1252
|
+
die(f"cannot fingerprint a plan input: {exc}", kind="input", ctx=ctx)
|
|
1253
|
+
by_path = {entry["path"]: entry for entry in fingerprints}
|
|
1254
|
+
for source, expected in ctx.measured_plan_inputs.items():
|
|
1255
|
+
if by_path.get(source) != expected:
|
|
1256
|
+
die(f"plan input {source!r} changed since measurement; make a new plan", kind="input", ctx=ctx)
|
|
1257
|
+
doc = {
|
|
1258
|
+
"plan_version": PLAN_VERSION,
|
|
1259
|
+
"created": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
1260
|
+
"tool": tool,
|
|
1261
|
+
"argv": cleaned,
|
|
1262
|
+
"cwd": os.getcwd(),
|
|
1263
|
+
"inputs": fingerprints,
|
|
1264
|
+
# inputs that did not exist yet, so carry no fingerprint (render.py reports them on execution)
|
|
1265
|
+
"unbound_inputs": _plan_unbound_inputs(ctx.commands, ctx),
|
|
1266
|
+
"commands": list(ctx.commands),
|
|
1267
|
+
"output": os.path.abspath(output) if output else None,
|
|
1268
|
+
"verify": verify,
|
|
1269
|
+
"notes": list(extra.get("notes") or []),
|
|
1270
|
+
}
|
|
1271
|
+
if ctx.sequence_frames_sha256 is not None:
|
|
1272
|
+
doc["sequence_frames_sha256"] = ctx.sequence_frames_sha256
|
|
1273
|
+
if tool == "silence" and "cut_plan" in extra:
|
|
1274
|
+
doc["cut_plan"] = extra["cut_plan"]
|
|
1275
|
+
if tool == "fit" and "timing" in extra:
|
|
1276
|
+
doc["timing"] = extra["timing"]
|
|
1277
|
+
try:
|
|
1278
|
+
tmp = f"{path}.tmp{os.getpid()}"
|
|
1279
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
1280
|
+
json.dump(doc, f, indent=2, ensure_ascii=False)
|
|
1281
|
+
f.write("\n")
|
|
1282
|
+
os.replace(tmp, path)
|
|
1283
|
+
except OSError as exc:
|
|
1284
|
+
die(f"cannot write plan {path}: {exc}", kind="output")
|
|
1285
|
+
ctx.plan_written = True
|
|
1286
|
+
info(f"plan written: {path} ({len(doc['commands'])} command(s), {len(doc['inputs'])} input(s)); run it with render.py {path}", ctx)
|
|
1287
|
+
return path
|
|
1288
|
+
|
|
1289
|
+
|
|
1290
|
+
def json_safe(obj: Any) -> Any:
|
|
1291
|
+
"""Replace non-finite floats with the strings loudness.py already reports ("-inf" / "inf")
|
|
1292
|
+
and NaN with null: json.dumps would otherwise write -Infinity / NaN, which no strict JSON
|
|
1293
|
+
parser accepts (a silent file measures -inf LUFS)."""
|
|
1294
|
+
if isinstance(obj, float) and not math.isfinite(obj):
|
|
1295
|
+
return None if obj != obj else ("inf" if obj > 0 else "-inf")
|
|
1296
|
+
if isinstance(obj, dict):
|
|
1297
|
+
return {k: json_safe(v) for k, v in obj.items()}
|
|
1298
|
+
if isinstance(obj, (list, tuple)):
|
|
1299
|
+
return [json_safe(v) for v in obj]
|
|
1300
|
+
return obj
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
def print_json(obj: Any) -> None:
|
|
1304
|
+
sys.stdout.write(json.dumps(json_safe(obj), indent=2, ensure_ascii=False, allow_nan=False) + "\n")
|
|
1305
|
+
|
|
1306
|
+
|
|
1307
|
+
# Deferred for the same reason as runner's import of this module: probe needs die() from here, and
|
|
1308
|
+
# emit() needs verify_output() from there, but only ever at call time.
|
|
1309
|
+
from _common.probe import MEDIA_EXT, _to_float, fingerprint, probe, verify_output # noqa: E402
|