@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,695 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Colour management: convert HDR (HDR10/PQ, HLG, BT.2020) to SDR BT.709 with
|
|
3
|
+
real tone mapping, apply a .cube LUT (Log footage, creative grades), fix wrong
|
|
4
|
+
colour tags without re-encoding, or apply typed primary colour correction
|
|
5
|
+
(exposure, contrast, saturation, gamma, white balance, three-way
|
|
6
|
+
lift/gain, levels, curves).
|
|
7
|
+
|
|
8
|
+
Examples:
|
|
9
|
+
python3 color.py iphone_hdr.mov --to-sdr # PQ/HLG -> BT.709 SDR, hable tonemap
|
|
10
|
+
python3 color.py iphone_hdr.mov --to-sdr --tonemap mobius --peak 1000
|
|
11
|
+
python3 color.py slog3.mp4 --lut SLog3_to_Rec709.cube # apply LUT (any Log -> 709 or a look)
|
|
12
|
+
python3 color.py clip.mp4 --lut look.cube --lut-strength 0.6
|
|
13
|
+
python3 color.py wrongly_tagged.mp4 --retag bt709 # metadata only, stream copy
|
|
14
|
+
python3 color.py iphone_dv.mov --strip-dovi # drop Dolby Vision RPU, keep HLG base layer
|
|
15
|
+
python3 color.py iphone_dv.mov --to-sdr # DV 8.4 = HLG base layer -> tone-mapped SDR
|
|
16
|
+
python3 color.py flat.mp4 --correct --exposure 0.3 --contrast 1.1 --saturation 1.05 --temperature 5600 --tint -0.05
|
|
17
|
+
python3 color.py flat.mp4 --correct --gamma 1.2 --lift 0.04 --gain -0.03 # three-way shadows/gamma/highlights
|
|
18
|
+
python3 color.py flat.mp4 --correct --levels-in-black 16 --levels-in-white 235 --curves medium_contrast
|
|
19
|
+
python3 color.py logo_4444.mov --correct --exposure 0.3 --keep-alpha -o logo_graded.mov # alpha kept, ProRes 4444
|
|
20
|
+
python3 color.py graded.mp4 --correct --legalize ebu-r103 # clamp only: no correction values given
|
|
21
|
+
python3 color.py log.mov --lut to709.cube --legalize bt709 # the LUT, then the clamp, one encode
|
|
22
|
+
|
|
23
|
+
--legalize bt709|ebu-r103 (with --to-sdr, --lut or --correct) clamps every luma and chroma sample into
|
|
24
|
+
the standard's legal range after the picture has become 8-bit 4:2:0, the last filter before the
|
|
25
|
+
encoder, then measures the written file the way check.py --levels does (`legalize` in the JSON): the
|
|
26
|
+
encoder's error around clamped edges can leave a few decoded samples out, and the legal_levels step
|
|
27
|
+
passes with up to 1 % of one frame's luma or chroma samples out of range.
|
|
28
|
+
"""
|
|
29
|
+
import argparse
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import sys
|
|
33
|
+
from typing import List, Optional
|
|
34
|
+
|
|
35
|
+
from _common.runner import absent_word, carried_stream_maps, fail_if_classified
|
|
36
|
+
from _common import STATE, add_common, analyze_levels, LEGAL_RANGE_CHOICES, legal_limits, measure_signal_range, apply_common, emit, aac_args, cfr_args, cfr_at_input, with_cfr, default_output, die, escape_filter_path, ffmpeg_base, ffmpeg_bsfs, info, probe, require_tool, run, run_analysis, run_keeping_subtitles, x264_args, X264_PRESETS, fmt_secs
|
|
37
|
+
from _common.emit import note, refuse, warn
|
|
38
|
+
from _common.color import is_rgb, rgb_to_bt709_filter
|
|
39
|
+
from _common.alpha import (add_alpha_args, audio_line, check_alpha_args, decoder_args_for, default_ext, finish_chain,
|
|
40
|
+
matrix_label, report as alpha_report, rgb_line, rgb_to_bt709_line, source_alpha, tag_args,
|
|
41
|
+
unpremultiply_leg, video_line)
|
|
42
|
+
from _common.decision import keeps_source_tags
|
|
43
|
+
from _common.color import bt2020_sdr_to_bt709_chain, hdr_to_sdr_chain, is_bt2020_sdr # noqa: E402,F401
|
|
44
|
+
|
|
45
|
+
# the curves of FFmpeg's CPU `tonemap` filter (every version from 5.1 to 9). bt2390 was listed
|
|
46
|
+
# until 2.24 but exists only in tonemap_opencl/libplacebo, so choosing it always failed.
|
|
47
|
+
TONEMAPS = ["hable", "mobius", "reinhard", "clip", "linear", "gamma"]
|
|
48
|
+
|
|
49
|
+
# Typed primary correction: each flag is one option of one real, always-available libavfilter filter
|
|
50
|
+
# (never a caller-supplied filter string). Range is this script's own safe subset of what the filter
|
|
51
|
+
# documents (`ffmpeg -h filter=<name>`), not the filter's full technical range. default is each filter's
|
|
52
|
+
# own documented no-op value, so every stage in this dict is always emitted and the chain never depends
|
|
53
|
+
# on which flags were actually given (exposure/temperature/tint/gamma/lift/gain). `colorlevels` and
|
|
54
|
+
# `curves` (see LEVELS and CURVES_PRESETS below) are the exception: they only add a term to the chain
|
|
55
|
+
# when the caller actually asks for them, because "levels 0..255 in, 0..255 out" and "no curve" are
|
|
56
|
+
# already the identity operation without emitting a no-op filter term for it.
|
|
57
|
+
CORRECTION = {
|
|
58
|
+
# flag default lo hi unit
|
|
59
|
+
"exposure": (0.0, -3.0, 3.0, "stops"), # exposure filter's own full range (linear-domain stops)
|
|
60
|
+
"contrast": (1.0, 0.0, 2.0, "x"), # eq filter; 0=flat grey, 1=unchanged, 2=double contrast
|
|
61
|
+
"saturation": (1.0, 0.0, 2.0, "x"), # eq filter; 0=grayscale, 1=unchanged, 2=double saturation
|
|
62
|
+
"temperature": (6500.0, 2000.0, 12000.0, "K"), # colortemperature filter; 6500=unchanged (no term: the filter itself tints at 6500)
|
|
63
|
+
"tint": (0.0, -1.0, 1.0, "x"), # mapped to colorbalance midtones, see correction_chain()
|
|
64
|
+
"gamma": (1.0, 0.1, 10.0, "x"), # eq filter's own gamma option; 1=unchanged (its own default)
|
|
65
|
+
"lift": (0.0, -1.0, 1.0, "x"), # colorbalance shadows (rs=gs=bs); 0=unchanged
|
|
66
|
+
"gain": (0.0, -1.0, 1.0, "x"), # colorbalance highlights (rh=gh=bh); 0=unchanged
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
# colorlevels takes fractional 0.0..1.0 input/output black/white points; this tool exposes the
|
|
70
|
+
# familiar 8-bit 0..255 unit instead and divides by 255.0 when building the filter (same convention
|
|
71
|
+
# as the rest of CORRECTION: a human-friendly CLI unit formatted into the filter's own native unit).
|
|
72
|
+
LEVELS = {
|
|
73
|
+
# flag default lo hi
|
|
74
|
+
"levels_in_black": (0, 0, 255),
|
|
75
|
+
"levels_in_white": (255, 0, 255),
|
|
76
|
+
"levels_out_black": (0, 0, 255),
|
|
77
|
+
"levels_out_white": (255, 0, 255),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
# curves filter's real built-in presets (`ffmpeg -h filter=curves`), excluding its own "none" (0):
|
|
81
|
+
# omitting --curves already gets that identity result without adding a filter term for it.
|
|
82
|
+
CURVES_PRESETS = ["color_negative", "cross_process", "darker", "increase_contrast", "lighter",
|
|
83
|
+
"linear_contrast", "medium_contrast", "negative", "strong_contrast", "vintage"]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _checked(args: argparse.Namespace, flag: str) -> float:
|
|
87
|
+
_, lo, hi, unit = CORRECTION[flag]
|
|
88
|
+
value = getattr(args, flag)
|
|
89
|
+
if not (lo <= value <= hi):
|
|
90
|
+
die(f"--{flag} {value:g} is outside {lo:g}..{hi:g} {unit} (the safe range this tool guarantees)")
|
|
91
|
+
return value
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _checked_levels(args: argparse.Namespace, flag: str) -> int:
|
|
95
|
+
_, lo, hi = LEVELS[flag]
|
|
96
|
+
value = getattr(args, flag)
|
|
97
|
+
if not (lo <= value <= hi):
|
|
98
|
+
die(f"--{flag.replace('_', '-')} {value} is outside {lo}..{hi} (8-bit units, scaled to colorlevels' own 0..1 range)")
|
|
99
|
+
return value
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def correction_chain(args: argparse.Namespace, out_fmt: str = "yuv420p", matrix: str = "bt601",
|
|
103
|
+
rgb_in: bool = False) -> str:
|
|
104
|
+
"""Always-present filter stages, in a fixed order chosen so each stage sees a picture already
|
|
105
|
+
corrected by the previous one: exposure (linear light level) -> white balance (temperature/tint/
|
|
106
|
+
lift/gain, so contrast/saturation act on colour-balanced footage) -> contrast/saturation/gamma
|
|
107
|
+
(the most creative-adjacent stage of the always-on chain). `tint` (-1 green .. +1 magenta) is not
|
|
108
|
+
a single ffmpeg option: it is expressed as colorbalance's three midtone channels (gm=-tint,
|
|
109
|
+
rm=bm=tint/2) so a positive tint shifts midtones toward magenta and a negative one toward green
|
|
110
|
+
without changing overall midtone lightness, the same balanced-axis convention colour tools use
|
|
111
|
+
for a one-dial tint control. `lift` and `gain` extend the same colorbalance call to the shadow
|
|
112
|
+
(rs=gs=bs=lift) and highlight (rh=gh=bh=gain) channels, giving a classic three-way shadows/
|
|
113
|
+
midtones/highlights correction in one filter invocation. `gamma` is folded into the same `eq`
|
|
114
|
+
term contrast/saturation already use, as `eq`'s own `gamma` option. Two further stages are
|
|
115
|
+
appended only when asked for, since their own identity value would otherwise add a no-op filter
|
|
116
|
+
term to the chain: `colorlevels` (--levels-*, 8-bit units scaled to the filter's 0..1 range) and
|
|
117
|
+
`curves` (--curves, one of the filter's own named presets)."""
|
|
118
|
+
exposure = _checked(args, "exposure")
|
|
119
|
+
contrast = _checked(args, "contrast")
|
|
120
|
+
saturation = _checked(args, "saturation")
|
|
121
|
+
temperature = _checked(args, "temperature")
|
|
122
|
+
tint = _checked(args, "tint")
|
|
123
|
+
gamma = _checked(args, "gamma")
|
|
124
|
+
lift = _checked(args, "lift")
|
|
125
|
+
gain = _checked(args, "gain")
|
|
126
|
+
in_black = _checked_levels(args, "levels_in_black")
|
|
127
|
+
in_white = _checked_levels(args, "levels_in_white")
|
|
128
|
+
out_black = _checked_levels(args, "levels_out_black")
|
|
129
|
+
out_white = _checked_levels(args, "levels_out_white")
|
|
130
|
+
if in_black >= in_white:
|
|
131
|
+
die(f"--levels-in-black {in_black} must be less than --levels-in-white {in_white}")
|
|
132
|
+
if out_black >= out_white:
|
|
133
|
+
die(f"--levels-out-black {out_black} must be less than --levels-out-white {out_white}")
|
|
134
|
+
|
|
135
|
+
gm, rm, bm = -tint, tint / 2.0, tint / 2.0
|
|
136
|
+
rgb = [f"exposure=exposure={exposure:g}"]
|
|
137
|
+
if temperature != CORRECTION["temperature"][0]:
|
|
138
|
+
# colortemperature at 6500 K is not the identity it is documented as here: it multiplies by
|
|
139
|
+
# its own approximation of that white point, which tinted grey 808080 to 7E7E7B (#410), so
|
|
140
|
+
# "unchanged" adds no term at all
|
|
141
|
+
rgb.append(f"colortemperature=temperature={temperature:g}")
|
|
142
|
+
rgb.append(f"colorbalance=rs={lift:g}:gs={lift:g}:bs={lift:g}:rm={rm:g}:gm={gm:g}:bm={bm:g}:rh={gain:g}:gh={gain:g}:bh={gain:g}")
|
|
143
|
+
terms = [_rgb_stage(rgb, out_fmt, matrix, rgb_in), f"eq=contrast={contrast:g}:saturation={saturation:g}:gamma={gamma:g}"]
|
|
144
|
+
rgb2 = []
|
|
145
|
+
if (in_black, in_white, out_black, out_white) != (0, 255, 0, 255):
|
|
146
|
+
rimin, rimax = in_black / 255.0, in_white / 255.0
|
|
147
|
+
romin, romax = out_black / 255.0, out_white / 255.0
|
|
148
|
+
rgb2.append(
|
|
149
|
+
f"colorlevels=rimin={rimin:g}:gimin={rimin:g}:bimin={rimin:g}:"
|
|
150
|
+
f"rimax={rimax:g}:gimax={rimax:g}:bimax={rimax:g}:"
|
|
151
|
+
f"romin={romin:g}:gomin={romin:g}:bomin={romin:g}:"
|
|
152
|
+
f"romax={romax:g}:gomax={romax:g}:bomax={romax:g}"
|
|
153
|
+
)
|
|
154
|
+
if args.curves:
|
|
155
|
+
rgb2.append(f"curves=preset={args.curves}")
|
|
156
|
+
if rgb2:
|
|
157
|
+
terms.append(_rgb_stage(rgb2, out_fmt, matrix))
|
|
158
|
+
return ",".join(terms)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _rgb_stage(filters: list, out_fmt: str = "yuv420p", matrix: str = "bt601", rgb_in: bool = False) -> str:
|
|
162
|
+
"""Wrap a run of RGB-only filters in explicit, matching YUV<->RGB conversions.
|
|
163
|
+
|
|
164
|
+
exposure/colortemperature/colorbalance/colorlevels/curves take RGB, so libavfilter inserts a
|
|
165
|
+
swscale conversion on each side. Left to itself, the way in honours the frame's colour tag
|
|
166
|
+
(bt709 on any camera or export.py file) while the way back uses swscale's default matrix
|
|
167
|
+
(bt601): on a bt709-tagged source an all-defaults --correct came out 26 dB PSNR from its
|
|
168
|
+
input and ~8 % less saturated (#159). Untagged sources never showed it because both legs
|
|
169
|
+
then fall back to bt601 and cancel. Pinning both legs to the same matrix restores the
|
|
170
|
+
identity on every source (39 dB, the same as an untagged one always got); bt601 on both
|
|
171
|
+
sides measured better than bt709 on both (34 dB) because swscale's 601 path round-trips
|
|
172
|
+
8-bit 4:2:0 more exactly. The matrix here is only the working space of the conversion pair,
|
|
173
|
+
never a tag: the output carries the encoder's BT.709 tags as before. `out_fmt` is yuv444p for
|
|
174
|
+
an alpha line (--keep-alpha), whose 4:4:4 master would otherwise get 4:2:0 chroma.
|
|
175
|
+
|
|
176
|
+
The pair cancels only when the picture comes in as YUV. An RGB source (qtrle, PNG in .mov)
|
|
177
|
+
meets no matrix on the way in, so the way out is the one real RGB-to-YUV conversion of the
|
|
178
|
+
graph and `matrix` is the matrix of the YUV that leaves it. The H.264 line converts such a
|
|
179
|
+
source to BT.709 YUV first (x264_args(source=...)), so the pair cancels there as well. An
|
|
180
|
+
alpha line converts nothing in front, and with bt601 here its ProRes 4444 or VP9 master of an
|
|
181
|
+
RGB source held BT.601 YUV under no tag, which a player reads as BT.709 at HD (30C050 shown as
|
|
182
|
+
26AB4D, #496): for an RGB source on a YUV alpha line `matrix` is bt709 (working_matrix()),
|
|
183
|
+
and the line is tagged so. A later stage of the same chain takes the same matrix on both legs.
|
|
184
|
+
|
|
185
|
+
`rgb_in`: the picture reaches this stage as RGB (the first stage of an RGB source on an alpha
|
|
186
|
+
line), so the way in names no matrix. It has none to read, and with
|
|
187
|
+
`scale=in_color_matrix=bt709` in front of RGB frames FFmpeg 7.1 wrote BT.601 samples whatever
|
|
188
|
+
the way out asked for (30C050 as 26AB4D again; 6.1 was right either way). Seen in CI, not
|
|
189
|
+
traced inside FFmpeg: --lut-strength 0, whose chain has the way out alone, was right there."""
|
|
190
|
+
way_in = "format=gbrpf32le," if rgb_in else f"scale=in_color_matrix={matrix},format=gbrpf32le,"
|
|
191
|
+
return (way_in + ",".join(filters)
|
|
192
|
+
+ f",scale=out_color_matrix={matrix},format={out_fmt}")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def working_matrix(meta=None) -> "str | None":
|
|
196
|
+
"""The matrix of the YUV an RGB source's grade writes on an alpha line, or None for every other
|
|
197
|
+
case (a YUV source, the H.264 line), whose legs are what they were.
|
|
198
|
+
|
|
199
|
+
bt709 on a line that stores YUV (ProRes 4444, VP9): that YUV is the master, tagged BT.709
|
|
200
|
+
(alpha.rgb_to_bt709_line). bt601 on a line that stores RGB (qtrle, PNG): the YUV is only the
|
|
201
|
+
grade's working format and FFmpeg converts it back for the line with its own default, BT.601
|
|
202
|
+
(unlabelled frames on 6.1, the tag the leg wrote on 7.1+), so the legs use that and the written
|
|
203
|
+
RGB is the graded RGB. --lut's legs said bt709 there and an identity LUT wrote 30C050 as 3CD753."""
|
|
204
|
+
if rgb_to_bt709_line(meta):
|
|
205
|
+
return "bt709"
|
|
206
|
+
if rgb_line() and is_rgb(meta):
|
|
207
|
+
return "bt601"
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# swscale's names for the non-BT.709 matrices a --codec prores re-encode keeps (it does not convert)
|
|
212
|
+
_SWS_MATRIX = {"smpte170m": "bt601", "bt470bg": "bt601", "smpte240m": "smpte240m", "fcc": "fcc"}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def lut_legs(meta=None, out_fmt: str = "yuv420p") -> "tuple":
|
|
216
|
+
"""(to RGB, back to YUV) around --lut's lut3d: explicit BT.709 conversions through float RGB,
|
|
217
|
+
the matrix the picture holds when it reaches them (an untagged or BT.709 source as it is, a
|
|
218
|
+
BT.601 or RGB one after x264_args(source=...)'s conversion), limited range on the way out.
|
|
219
|
+
|
|
220
|
+
lut3d takes RGB, and left to libavfilter the way in honoured the frame's BT.709 tag while the
|
|
221
|
+
way back used swscale's BT.601 default, so even an identity LUT shifted every colour (2FAE4E to
|
|
222
|
+
249A4B, #410); --correct had its legs pinned for the same reason in #159. A LUT maps the RGB the
|
|
223
|
+
picture really shows, so unlike --correct's working-space pair (bt601 both ways, see
|
|
224
|
+
_rgb_stage) these legs use the BT.709 the picture is: an identity LUT then returns every sample
|
|
225
|
+
as --lut-strength 0, which applies none, does (6.1, BT.709/BT.601/untagged, limited and full
|
|
226
|
+
range, 8- and 10-bit). The input range is read from the frames, as every scale here reads it."""
|
|
227
|
+
# --codec prores (and an alpha line, --keep-alpha) keeps a BT.601 (or other non-BT.709)
|
|
228
|
+
# source's matrix and tags instead of converting it (decision.video_args), so the legs use
|
|
229
|
+
# that matrix (#416 review)
|
|
230
|
+
matrix = "bt709"
|
|
231
|
+
if keeps_source_tags():
|
|
232
|
+
matrix = _SWS_MATRIX.get(((meta or {}).get("video") or {}).get("color_space"), "bt709")
|
|
233
|
+
# an RGB source on an alpha line: the matrix of the YUV its line is written from (#496)
|
|
234
|
+
matrix = working_matrix(meta) or matrix
|
|
235
|
+
# an RGB source on an alpha line reaches the way in as RGB: no matrix is named there (see
|
|
236
|
+
# _rgb_stage's rgb_in; with one, FFmpeg 7.1 wrote BT.601 samples)
|
|
237
|
+
way_in = "format=gbrpf32le" if keeps_source_tags() and working_matrix(meta) else f"scale=in_color_matrix={matrix},format=gbrpf32le"
|
|
238
|
+
return (way_in, f"scale=out_color_matrix={matrix}:out_range=tv,format={out_fmt}")
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# --retag targets: ffprobe's names (colorspace, primaries, transfer) and the ITU-T H.273 code points
|
|
242
|
+
# h264_metadata/hevc_metadata write into the VUI (matrix_coefficients, colour_primaries,
|
|
243
|
+
# transfer_characteristics).
|
|
244
|
+
RETAG = {
|
|
245
|
+
"bt709": (("bt709", "bt709", "bt709"), (1, 1, 1)),
|
|
246
|
+
"bt2020-pq": (("bt2020nc", "bt2020", "smpte2084"), (9, 9, 16)),
|
|
247
|
+
"bt2020-hlg": (("bt2020nc", "bt2020", "arib-std-b67"), (9, 9, 18)),
|
|
248
|
+
"bt601": (("smpte170m", "smpte170m", "smpte170m"), (6, 6, 6)),
|
|
249
|
+
}
|
|
250
|
+
# codecs whose colour description lives in the bitstream, and the bitstream filter that rewrites it
|
|
251
|
+
# without touching a coded picture (each in every FFmpeg from 5.0: tests/fixtures/ffmpeg_bsfs_*)
|
|
252
|
+
RETAG_BSF = {"h264": "h264_metadata", "hevc": "hevc_metadata", "mpeg2video": "mpeg2_metadata",
|
|
253
|
+
"av1": "av1_metadata", "vp9": "vp9_metadata"}
|
|
254
|
+
# VP9 has only a colour space (its primaries and transfer are the container's); vp9_metadata's names
|
|
255
|
+
VP9_SPACE = {"bt709": "bt709", "smpte170m": "smpte170", "bt2020nc": "bt2020"}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def retag_bsf(meta: dict, target: str) -> List[str]:
|
|
259
|
+
"""`-bsf:v:0 <codec>_metadata=...` writing `target`'s colour description into the first video
|
|
260
|
+
stream's own headers (H.264/HEVC VUI, MPEG-2 sequence display extension, AV1 sequence header,
|
|
261
|
+
VP9 frame header), or [] when the codec has no such filter (ProRes, DNxHD, MPEG-4 Part 2 ...)
|
|
262
|
+
or this build lacks it.
|
|
263
|
+
|
|
264
|
+
A stream copy with -colorspace/-color_primaries/-color_trc changes only the container's
|
|
265
|
+
description (mp4 `colr`, Matroska Colour); decoders, ffprobe included, read the stream's own
|
|
266
|
+
description first, so a source that already carried tags there kept them while the tool
|
|
267
|
+
reported success. The filter rewrites those headers and nothing else: the copy stays
|
|
268
|
+
lossless. Where the filter has a range field it gets the source's probed range (pc/tv),
|
|
269
|
+
because h264_metadata/hevc_metadata set it to limited when the VUI had no signal type at all;
|
|
270
|
+
an unknown range is left alone."""
|
|
271
|
+
v = meta["video"]
|
|
272
|
+
codec = v.get("codec") or ""
|
|
273
|
+
bsf = RETAG_BSF.get(codec)
|
|
274
|
+
if not bsf or bsf not in ffmpeg_bsfs():
|
|
275
|
+
return []
|
|
276
|
+
names, (matrix, prim, trc) = RETAG[target]
|
|
277
|
+
rng = v.get("color_range") if v.get("color_range") in ("tv", "pc") else None
|
|
278
|
+
if codec == "vp9":
|
|
279
|
+
opts = f"color_space={VP9_SPACE[names[0]]}" + (f":color_range={rng}" if rng else "")
|
|
280
|
+
elif codec == "av1":
|
|
281
|
+
opts = (f"color_primaries={prim}:transfer_characteristics={trc}:matrix_coefficients={matrix}"
|
|
282
|
+
+ (f":color_range={rng}" if rng else ""))
|
|
283
|
+
else:
|
|
284
|
+
opts = f"colour_primaries={prim}:transfer_characteristics={trc}:matrix_coefficients={matrix}"
|
|
285
|
+
if rng and codec != "mpeg2video":
|
|
286
|
+
opts += f":video_full_range_flag={1 if rng == 'pc' else 0}"
|
|
287
|
+
return ["-bsf:v:0", f"{bsf}={opts}"]
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def retag_mismatch(output: str, want: tuple) -> "Optional[str]":
|
|
291
|
+
"""None when the output carries `want` (colorspace, primaries, transfer), else what was read
|
|
292
|
+
-- the check behind every completed --retag.
|
|
293
|
+
|
|
294
|
+
Two readings, because they disagree: ffprobe's stream tags (from 8.1 the container's `colr`
|
|
295
|
+
wins there over an H.264 VUI that still says bt709, while 6.1 and 8.0 show the VUI) and the
|
|
296
|
+
first decoded frame's, which is what a player or filter graph gets. Each stream tag must be
|
|
297
|
+
the requested one; a frame tag must be the requested one or unspecified (8.1's ProRes decoder
|
|
298
|
+
leaves its frames untagged and players read the container's)."""
|
|
299
|
+
got = probe(output, role="output")["video"]
|
|
300
|
+
stream = (got.get("color_space"), got.get("color_primaries"), got.get("color_transfer"))
|
|
301
|
+
keys = ("color_space", "color_primaries", "color_transfer")
|
|
302
|
+
proc = run_analysis([require_tool("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_frames",
|
|
303
|
+
"-read_intervals", "%+#1", "-show_entries", "frame=" + ",".join(keys), "-of", "json", output],
|
|
304
|
+
check=False)
|
|
305
|
+
try:
|
|
306
|
+
frames = json.loads(proc.stdout or "{}").get("frames") or [{}]
|
|
307
|
+
except ValueError:
|
|
308
|
+
frames = [{}]
|
|
309
|
+
frame = tuple(frames[0].get(k) for k in keys)
|
|
310
|
+
if stream == tuple(want) and all(f in (None, "unknown", w) for f, w in zip(frame, want)):
|
|
311
|
+
return None
|
|
312
|
+
shown = "/".join(str(t) for t in stream)
|
|
313
|
+
return shown if frame in ((None,) * 3, stream) else f"{shown} (decoded frames: {'/'.join(str(t) for t in frame)})"
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def retag(args: argparse.Namespace, meta: dict, has_audio: bool, src_alpha=lambda: None) -> int:
|
|
317
|
+
"""--retag: rewrite the colour description, never the pixels.
|
|
318
|
+
|
|
319
|
+
First a stream copy of every stream: the container options plus, where the codec keeps its
|
|
320
|
+
own description, its rewrite (retag_bsf). When the copy fails, or ffprobe still reads other
|
|
321
|
+
tags on its output (a codec with no such filter here), the video is re-encoded with the tags
|
|
322
|
+
put on the frames (`setparams`): from FFmpeg 7.1 the encoder takes them from the frames and the output options feed the
|
|
323
|
+
filter graph's colourspace negotiation, which converted the matrix of a tagged source and left
|
|
324
|
+
its primaries and transfer as they were (measured on 8.0.1 and 8.1.3), while setparams labels
|
|
325
|
+
the frames on 5.x-8.x alike. Every completed run has been checked: ffprobe reads the requested
|
|
326
|
+
tags on the output (`verification`'s `color_tags` step), or the run fails with kind `verification`."""
|
|
327
|
+
names = RETAG[args.retag][0]
|
|
328
|
+
output = args.output or default_output(args.input, "retag")
|
|
329
|
+
ext = os.path.splitext(output)[1].lower()
|
|
330
|
+
tags = ["-colorspace", names[0], "-color_primaries", names[1], "-color_trc", names[2]]
|
|
331
|
+
bsf = retag_bsf(meta, args.retag)
|
|
332
|
+
cmd = (ffmpeg_base() + ["-i", args.input, "-map", "0"] + carried_stream_maps(args.input, output, attachments=False)
|
|
333
|
+
+ ["-c", "copy"] + bsf + tags)
|
|
334
|
+
if ext in (".mp4", ".mov", ".m4v"):
|
|
335
|
+
cmd += ["-movflags", "+faststart"]
|
|
336
|
+
cmd.append(output)
|
|
337
|
+
proc = run(cmd, check=False)
|
|
338
|
+
fail_if_classified(proc) # a full disk fails the re-encode too: its error, not two more encodes (#415)
|
|
339
|
+
notes: List[str] = []
|
|
340
|
+
reencoded = proc.returncode != 0
|
|
341
|
+
if not reencoded and not STATE.dry_run:
|
|
342
|
+
wrong = retag_mismatch(output, names)
|
|
343
|
+
if wrong:
|
|
344
|
+
reencoded = True
|
|
345
|
+
notes.append(f"a stream copy cannot rewrite the colour tags of {meta['video'].get('codec')} here "
|
|
346
|
+
f"(the output still read {wrong}), so the video was re-encoded with the tags on its frames")
|
|
347
|
+
info("note: " + notes[-1])
|
|
348
|
+
elif reencoded:
|
|
349
|
+
notes.append("the stream copy failed, so the video was re-encoded with the tags on its frames")
|
|
350
|
+
dropped_streams = False
|
|
351
|
+
if reencoded:
|
|
352
|
+
# The copy path (-map 0 -c copy) keeps every stream -- extra audio tracks, subtitles,
|
|
353
|
+
# chapters, attached pictures -- byte-for-byte; -c:s/-c:d copy here keeps that same
|
|
354
|
+
# guarantee for subtitle/data streams even though video/audio must be re-encoded. Only if
|
|
355
|
+
# THAT also fails (e.g. a subtitle codec genuinely incompatible with the target container)
|
|
356
|
+
# do we drop to video+selected-audio-only, and even then we say so explicitly rather than
|
|
357
|
+
# silently reporting "completed" with streams missing.
|
|
358
|
+
info("re-encoding video/audio with the new tags (subtitles/data streams kept)")
|
|
359
|
+
label = ["-vf", f"setparams=color_primaries={names[1]}:color_trc={names[2]}:colorspace={names[0]}"]
|
|
360
|
+
enc = x264_args(args.crf, args.preset, keep_bt709=False) + (aac_args() if has_audio else [])
|
|
361
|
+
cmd = (ffmpeg_base() + ["-i", args.input, "-map", "0:v:0", "-map", f"0:a:{args.audio_stream}?",
|
|
362
|
+
"-map", "0:s?", "-map", "0:d?"] + carried_stream_maps(args.input, output) + label + enc
|
|
363
|
+
+ ["-c:s", "copy", "-c:d", "copy", output])
|
|
364
|
+
proc2 = run(cmd, check=False)
|
|
365
|
+
fail_if_classified(proc2)
|
|
366
|
+
if proc2.returncode != 0:
|
|
367
|
+
info("re-encode with subtitles/data streams kept also failed; dropping them")
|
|
368
|
+
dropped_streams = True
|
|
369
|
+
cmd = ffmpeg_base() + ["-i", args.input, "-map", "0:v:0", "-map", f"0:a:{args.audio_stream}?"] + label + enc + [output]
|
|
370
|
+
run(cmd)
|
|
371
|
+
wrong = None if STATE.dry_run else retag_mismatch(output, names)
|
|
372
|
+
if wrong:
|
|
373
|
+
die(f"--retag {args.retag}: the re-encoded output still reads {wrong}, not {'/'.join(names)}",
|
|
374
|
+
kind="verification", hint=f"the output was written to {output} but is not tagged as asked")
|
|
375
|
+
info(f"wrote {output} (tags -> {args.retag})")
|
|
376
|
+
check = [] if STATE.dry_run else [{"step": "color_tags", "ok": True, "color_space": names[0],
|
|
377
|
+
"color_primaries": names[1], "color_transfer": names[2]}]
|
|
378
|
+
extra = {"reencoded": reencoded, "dropped_non_av_streams": dropped_streams, "verification": check}
|
|
379
|
+
if reencoded:
|
|
380
|
+
# the fallback re-encode is H.264, which holds no alpha: on a source whose alpha is used the
|
|
381
|
+
# `alpha` step fails (a stream copy keeps every pixel, alpha included, and needs no step)
|
|
382
|
+
alpha_report(args, None, src_alpha(), output, extra, composite=False)
|
|
383
|
+
emit(output, **extra, **({"notes": notes} if notes else {}))
|
|
384
|
+
return 0
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def correction_is_identity(args: argparse.Namespace) -> bool:
|
|
388
|
+
"""--correct with every value at its no-op default and no --curves: nothing to correct."""
|
|
389
|
+
return (all(getattr(args, k) == CORRECTION[k][0] for k in CORRECTION)
|
|
390
|
+
and all(getattr(args, k) == LEVELS[k][0] for k in LEVELS) and args.curves is None)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def legal_clamp(standard: str) -> str:
|
|
394
|
+
"""lutyuv clamping an 8-bit 4:2:0 picture into `standard`'s legal codes (legal_limits)."""
|
|
395
|
+
lim = legal_limits(standard, 8)
|
|
396
|
+
(ylo, yhi), (clo, chi) = lim["y"], lim["c"]
|
|
397
|
+
return f"lutyuv=y='clip(val\\,{ylo}\\,{yhi})':u='clip(val\\,{clo}\\,{chi})':v='clip(val\\,{clo}\\,{chi})'"
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
# --legalize: the share of one frame's luma (or chroma) samples the encode may leave out of range
|
|
401
|
+
# before the legal_levels step fails -- the same allowance check.py --levels gives by default. The
|
|
402
|
+
# clamp holds every sample the encoder receives; a lossy encoder's error around a clipped edge can
|
|
403
|
+
# still land a few decoded samples a code or two outside, which is what this measures.
|
|
404
|
+
LEGALIZE_TOLERANCE_PCT = 1.0
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def legalize_report(standard: str, output: str) -> "tuple":
|
|
408
|
+
"""Measure the written file against `standard` ({standard, limits, output}, verification list)."""
|
|
409
|
+
doc = measure_signal_range(output, standard, window=0, bit_depth=8)
|
|
410
|
+
if doc is None:
|
|
411
|
+
return ({"standard": standard, "output": None},
|
|
412
|
+
[{"step": "legal_levels", "ok": False, "reason": "the written file did not decode for the measurement"}])
|
|
413
|
+
worst = doc["worst_frame"]
|
|
414
|
+
ok = worst["y_pct"] <= LEGALIZE_TOLERANCE_PCT and worst["chroma_pct"] <= LEGALIZE_TOLERANCE_PCT
|
|
415
|
+
pct = doc["out_of_range_pct"]
|
|
416
|
+
if pct["y"] or pct["chroma"]:
|
|
417
|
+
warn(f"--legalize {standard}: the encoded file still has {pct['y']:.4f}% of luma and {pct['chroma']:.4f}% of chroma "
|
|
418
|
+
f"samples out of range (the encoder's error around clamped areas; worst frame {worst['y_pct']:.4f}% / "
|
|
419
|
+
f"{worst['chroma_pct']:.4f}%)", "legalize_residual")
|
|
420
|
+
return ({"standard": standard, "reference": doc["reference"], "legal": doc["legal"], "output": doc},
|
|
421
|
+
[{"step": "legal_levels", "ok": ok, "standard": standard, "out_of_range_pct": pct,
|
|
422
|
+
"worst_frame": worst, "tolerance_pct": LEGALIZE_TOLERANCE_PCT}])
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def refuse_bad_cube(path: str) -> None:
|
|
426
|
+
"""--lut given a .cube that holds no complete 3D LUT (#404): lut3d failed on it with "Invalid
|
|
427
|
+
data found when processing input", which reads as an unreadable video and got that hint. Only
|
|
428
|
+
.cube is checked (lut3d's other formats are left to it), by what lut3d itself needs: a
|
|
429
|
+
LUT_3D_SIZE line and size^3 rows that start with three numbers."""
|
|
430
|
+
if os.path.splitext(path)[1].lower() != ".cube":
|
|
431
|
+
return
|
|
432
|
+
size = rows = 0
|
|
433
|
+
one_d = False
|
|
434
|
+
try:
|
|
435
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
436
|
+
for line in fh:
|
|
437
|
+
words = line.split()
|
|
438
|
+
if not words or words[0].startswith("#"):
|
|
439
|
+
continue
|
|
440
|
+
if words[0] == "LUT_3D_SIZE" and len(words) > 1 and words[1].isdigit():
|
|
441
|
+
size = int(words[1])
|
|
442
|
+
elif words[0] == "LUT_1D_SIZE":
|
|
443
|
+
one_d = True
|
|
444
|
+
elif len(words) >= 3:
|
|
445
|
+
try:
|
|
446
|
+
[float(w) for w in words[:3]]
|
|
447
|
+
rows += 1
|
|
448
|
+
except ValueError:
|
|
449
|
+
pass
|
|
450
|
+
except OSError as e:
|
|
451
|
+
die(f"--lut: cannot read {path}: {e.strerror}", kind="input")
|
|
452
|
+
if size < 2 or rows < size ** 3:
|
|
453
|
+
what = ("it is a 1D LUT (LUT_1D_SIZE), and --lut applies a 3D one" if one_d and size < 2
|
|
454
|
+
else "it has no LUT_3D_SIZE line" if size < 2
|
|
455
|
+
else f"it has {rows} rows of three numbers, and a LUT_3D_SIZE {size} table has {size ** 3}")
|
|
456
|
+
die(f"--lut {path} is not a complete 3D .cube LUT: {what}", kind="input",
|
|
457
|
+
hint="a .cube file is plain text with a LUT_3D_SIZE line and size^3 rows of three numbers; export it again from the grading tool")
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def main() -> int:
|
|
461
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
462
|
+
ap.add_argument("input")
|
|
463
|
+
ap.add_argument("-o", "--output", help="output file (default: <name>_sdr / _lut / _retag)")
|
|
464
|
+
mode = ap.add_mutually_exclusive_group(required=True)
|
|
465
|
+
mode.add_argument("--to-sdr", action="store_true", help="convert to SDR BT.709: tone-map HDR (PQ/HLG/Dolby Vision); BT.2020 primaries on an SDR transfer get a gamut conversion only, no tone map")
|
|
466
|
+
mode.add_argument("--lut", help=".cube LUT to apply (3D)")
|
|
467
|
+
mode.add_argument("--retag", choices=["bt709", "bt2020-pq", "bt2020-hlg", "bt601"], help="rewrite colour tags only (no re-encode)")
|
|
468
|
+
mode.add_argument("--strip-dovi", action="store_true", help="remove the Dolby Vision RPU (profile 8.4 iPhone clips) so players use the plain HLG/HDR10 base layer; stream copy")
|
|
469
|
+
mode.add_argument("--correct", action="store_true", help="typed primary colour correction: --exposure/--contrast/--saturation/--temperature/--tint/--gamma/--lift/--gain/--levels-*/--curves")
|
|
470
|
+
ap.add_argument("--legalize", choices=LEGAL_RANGE_CHOICES, default=None,
|
|
471
|
+
help="with --to-sdr, --lut or --correct: clamp luma and chroma into the bt709 (16-235 / 16-240) or ebu-r103 "
|
|
472
|
+
"(luma 14-241, chroma 5-251) legal range after the 8-bit 4:2:0 conversion, then measure the written "
|
|
473
|
+
"file's out-of-range share (JSON legalize). --correct with no correction values clamps only")
|
|
474
|
+
ap.add_argument("--tonemap", choices=TONEMAPS, default="hable", help="tone-mapping curve (default hable)")
|
|
475
|
+
ap.add_argument("--peak", type=float, default=1000.0, help="the PQ source's peak brightness in nits, the level the tone map takes to SDR white (default 1000; an HLG source peaks at 1000 by definition, so it does not apply there)")
|
|
476
|
+
ap.add_argument("--desat", type=float, default=0.0, help="tonemap desaturation strength (default 0)")
|
|
477
|
+
ap.add_argument("--lut-strength", type=float, default=1.0, help="blend LUT result with the original, 0..1 (default 1)")
|
|
478
|
+
ap.add_argument("--force", action="store_true", help="run --to-sdr even if the file is tagged neither HDR nor BT.2020 (tone-mapped as PQ; a BT.2020 SDR file never needs it)")
|
|
479
|
+
ap.add_argument("--exposure", type=float, default=CORRECTION["exposure"][0], help="--correct: exposure in stops, -3..3 (default 0)")
|
|
480
|
+
ap.add_argument("--contrast", type=float, default=CORRECTION["contrast"][0], help="--correct: contrast, 0..2, 1=unchanged (default 1)")
|
|
481
|
+
ap.add_argument("--saturation", type=float, default=CORRECTION["saturation"][0], help="--correct: saturation, 0..2, 1=unchanged (default 1)")
|
|
482
|
+
ap.add_argument("--temperature", type=float, default=CORRECTION["temperature"][0], help="--correct: white-balance temperature in Kelvin, 2000..12000, 6500=unchanged (default 6500)")
|
|
483
|
+
ap.add_argument("--tint", type=float, default=CORRECTION["tint"][0], help="--correct: green(-1)/magenta(+1) tint, 0=unchanged (default 0)")
|
|
484
|
+
ap.add_argument("--gamma", type=float, default=CORRECTION["gamma"][0], help="--correct: master gamma (eq filter's own gamma), 0.1..10, 1=unchanged (default 1)")
|
|
485
|
+
ap.add_argument("--lift", type=float, default=CORRECTION["lift"][0], help="--correct: shadows lift (colorbalance rs/gs/bs), -1..1, 0=unchanged (default 0)")
|
|
486
|
+
ap.add_argument("--gain", type=float, default=CORRECTION["gain"][0], help="--correct: highlights gain (colorbalance rh/gh/bh), -1..1, 0=unchanged (default 0)")
|
|
487
|
+
ap.add_argument("--levels-in-black", type=int, default=LEVELS["levels_in_black"][0], help="--correct: colorlevels input black point, 0..255 (default 0, unchanged)")
|
|
488
|
+
ap.add_argument("--levels-in-white", type=int, default=LEVELS["levels_in_white"][0], help="--correct: colorlevels input white point, 0..255 (default 255, unchanged)")
|
|
489
|
+
ap.add_argument("--levels-out-black", type=int, default=LEVELS["levels_out_black"][0], help="--correct: colorlevels output black point, 0..255 (default 0, unchanged)")
|
|
490
|
+
ap.add_argument("--levels-out-white", type=int, default=LEVELS["levels_out_white"][0], help="--correct: colorlevels output white point, 0..255 (default 255, unchanged)")
|
|
491
|
+
ap.add_argument("--curves", choices=CURVES_PRESETS, default=None, help="--correct: curves filter built-in preset (default: none, no curves term added)")
|
|
492
|
+
ap.add_argument("--audio-stream", type=int, default=0,
|
|
493
|
+
help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "
|
|
494
|
+
"audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "
|
|
495
|
+
"the first track, same as leaving it unset always did. Only affects modes that re-encode "
|
|
496
|
+
"audio (--to-sdr, --lut, --correct, and --retag's re-encode fallback) -- --strip-dovi and "
|
|
497
|
+
"a successful --retag stream-copy all streams untouched, so the flag has nothing to select there.")
|
|
498
|
+
ap.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
|
|
499
|
+
ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
|
|
500
|
+
add_alpha_args(ap)
|
|
501
|
+
ap.add_argument("--source-alpha-mode", choices=["straight", "premultiplied"], default=None,
|
|
502
|
+
help="--keep-alpha: premultiplied grades the straight colour (default straight)")
|
|
503
|
+
add_common(ap)
|
|
504
|
+
args = ap.parse_args()
|
|
505
|
+
apply_common(args)
|
|
506
|
+
# A165: a peak of 0 or below and a negative desaturation reached zscale/tonemap, which refused
|
|
507
|
+
# them as an ffmpeg failure (kind ffmpeg, as if the build were at fault)
|
|
508
|
+
if args.peak <= 0:
|
|
509
|
+
die(f"--peak must be more than 0 nits, got {args.peak:g}")
|
|
510
|
+
if args.desat < 0:
|
|
511
|
+
die(f"--desat must be 0 or more, got {args.desat:g}")
|
|
512
|
+
|
|
513
|
+
meta = probe(args.input)
|
|
514
|
+
if not meta.get("video"):
|
|
515
|
+
die("input has no video stream")
|
|
516
|
+
v = meta["video"]
|
|
517
|
+
has_audio = bool(meta.get("audio"))
|
|
518
|
+
audio_streams = meta.get("audio_streams") or []
|
|
519
|
+
if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):
|
|
520
|
+
die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")
|
|
521
|
+
if args.audio_stream and not audio_streams:
|
|
522
|
+
die("--audio-stream needs an input with audio streams")
|
|
523
|
+
if args.legalize and (args.strip_dovi or args.retag):
|
|
524
|
+
die(f"--legalize changes pixels, so it needs a mode that re-encodes (--to-sdr, --lut or --correct); "
|
|
525
|
+
f"{'--strip-dovi' if args.strip_dovi else '--retag'} is a stream copy")
|
|
526
|
+
if args.legalize and STATE.codec not in (None, "h264"):
|
|
527
|
+
die(f"--legalize clamps the 8-bit 4:2:0 picture the H.264 line encodes; --codec {STATE.codec} converts it again "
|
|
528
|
+
f"after the clamp (another depth or chroma format), which can move samples back out of range. Leave --codec "
|
|
529
|
+
f"unset, or run check.py --levels on that encode")
|
|
530
|
+
if args.legalize and args.keep_alpha:
|
|
531
|
+
# the clamp and its measurement are defined on the 8-bit 4:2:0 picture the H.264 line encodes;
|
|
532
|
+
# the alpha line grades at 4:4:4 and every --alpha-codec converts that picture again after the
|
|
533
|
+
# clamp (10-bit ProRes 4444, RGB qtrle/PNG, VP9's yuva420p) -- the same reason --codec is refused
|
|
534
|
+
die("--legalize clamps the 8-bit 4:2:0 picture the H.264 line encodes; --keep-alpha grades at 4:4:4 and its "
|
|
535
|
+
"--alpha-codec converts the picture again after the clamp (10-bit, RGB or yuva420p), which can move samples "
|
|
536
|
+
"back out of range",
|
|
537
|
+
kind="input", hint="legalize the opaque delivery (--drop-alpha, or no alpha flag), or run check.py --levels "
|
|
538
|
+
"on the alpha master")
|
|
539
|
+
if args.keep_alpha and not (args.correct or args.lut):
|
|
540
|
+
# --retag and --strip-dovi are stream copies, which keep an alpha channel as they keep every
|
|
541
|
+
# pixel; --to-sdr's tone map ends in the SDR line's own 4:2:0 (an HDR alpha master is not a case here)
|
|
542
|
+
die("--keep-alpha applies to --correct and --lut (--retag and --strip-dovi copy the stream, alpha included)",
|
|
543
|
+
kind="input")
|
|
544
|
+
if args.drop_alpha and not (args.correct or args.lut or args.to_sdr):
|
|
545
|
+
die("--drop-alpha applies to the re-encodes (--correct, --lut, --to-sdr); --retag and --strip-dovi copy the stream, "
|
|
546
|
+
"alpha included", kind="input")
|
|
547
|
+
alpha_codec = check_alpha_args(args, args.output)
|
|
548
|
+
if args.source_alpha_mode and not alpha_codec:
|
|
549
|
+
refuse("input", "source_alpha_mode_needs_keep_alpha", "--source-alpha-mode applies with --keep-alpha: without it the "
|
|
550
|
+
"alpha is not kept and there is no colour to divide it from", hint="add --keep-alpha")
|
|
551
|
+
if args.source_alpha_mode == "premultiplied" and not args.alpha_mode:
|
|
552
|
+
args.alpha_mode = "premultiplied" # premultiplied in, premultiplied out, unless --alpha-mode straight asks otherwise
|
|
553
|
+
src_alpha = source_alpha(args, meta, args.input) if (args.correct or args.lut or args.to_sdr) else None
|
|
554
|
+
# an alpha line is graded at 4:4:4: its master would otherwise come back with 4:2:0 chroma
|
|
555
|
+
out_fmt = "yuv444p" if alpha_codec else "yuv420p"
|
|
556
|
+
ext = default_ext(alpha_codec) if alpha_codec else None
|
|
557
|
+
|
|
558
|
+
if args.strip_dovi:
|
|
559
|
+
output = args.output or default_output(args.input, "nodv")
|
|
560
|
+
if v.get("codec") != "hevc":
|
|
561
|
+
die("--strip-dovi only applies to HEVC (Dolby Vision) streams")
|
|
562
|
+
if not v.get("dolby_vision"):
|
|
563
|
+
warn("no Dolby Vision metadata detected; removing unregistered SEI anyway", "dovi_not_detected")
|
|
564
|
+
cmd = (ffmpeg_base() + ["-i", args.input, "-map", "0"] + carried_stream_maps(args.input, output, attachments=False)
|
|
565
|
+
+ ["-c", "copy", "-bsf:v", "filter_units=remove_types=62", "-tag:v", "hvc1"])
|
|
566
|
+
if os.path.splitext(output)[1].lower() in (".mp4", ".mov", ".m4v"):
|
|
567
|
+
cmd += ["-movflags", "+faststart"]
|
|
568
|
+
cmd.append(output)
|
|
569
|
+
run(cmd)
|
|
570
|
+
r = probe(output, role="output")
|
|
571
|
+
info(f"wrote {output} (dolby_vision={r['video'].get('dolby_vision')})")
|
|
572
|
+
emit(output)
|
|
573
|
+
return 0
|
|
574
|
+
|
|
575
|
+
if args.retag:
|
|
576
|
+
return retag(args, meta, has_audio, lambda: source_alpha(args, meta, args.input))
|
|
577
|
+
|
|
578
|
+
measurements = None
|
|
579
|
+
sdr_extra: dict = {}
|
|
580
|
+
if args.to_sdr:
|
|
581
|
+
if not v.get("bt2020_or_hdr") and not args.force:
|
|
582
|
+
die(f"{args.input} is not tagged as HDR (transfer={v.get('color_transfer')}, primaries={v.get('color_primaries')}). Use --force to tone-map anyway.")
|
|
583
|
+
if is_bt2020_sdr(v):
|
|
584
|
+
vf = bt2020_sdr_to_bt709_chain(meta)
|
|
585
|
+
sdr_path = "gamut"
|
|
586
|
+
sdr_note = (f"BT.2020 primaries on an SDR transfer ({v.get('color_transfer')}): converted the gamut to BT.709 "
|
|
587
|
+
f"without a tone map (--tonemap/--peak/--desat do not apply)")
|
|
588
|
+
else:
|
|
589
|
+
vf = hdr_to_sdr_chain(meta, args.tonemap, args.peak, args.desat)
|
|
590
|
+
sdr_path = "tonemap"
|
|
591
|
+
# the note names what hdr_to_sdr_chain read the source as: its own tags, PQ / BT.2020
|
|
592
|
+
# only where a tag is missing. Through 3.8.8 any non-HDR file was called "untagged
|
|
593
|
+
# input as PQ", a BT.709-tagged one included, which the chain linearised as BT.709 (A161)
|
|
594
|
+
read_as = v.get("hdr_format") or (
|
|
595
|
+
f"a non-HDR input read as transfer {v.get('color_transfer') or 'smpte2084 (untagged, taken as PQ)'}, "
|
|
596
|
+
f"primaries {v.get('color_primaries') or 'bt2020 (untagged)'} (--force)")
|
|
597
|
+
sdr_note = f"tone-mapped {read_as} to SDR BT.709 with {args.tonemap}"
|
|
598
|
+
info(f"note: {sdr_note}")
|
|
599
|
+
sdr_extra = {"sdr_path": sdr_path, "notes": [sdr_note]}
|
|
600
|
+
output = args.output or default_output(args.input, "sdr")
|
|
601
|
+
tag = "sdr"
|
|
602
|
+
elif args.correct:
|
|
603
|
+
if v.get("bt2020_or_hdr") and not args.force:
|
|
604
|
+
die(f"{args.input} is HDR ({v.get('hdr_format')}); --correct works on SDR pixels and would tag PQ/HLG data as BT.709 "
|
|
605
|
+
f"without a tone map (sweep F10). Run --to-sdr first, or --force to grade the raw values anyway")
|
|
606
|
+
vf = ("" if args.legalize and correction_is_identity(args)
|
|
607
|
+
else correction_chain(args, out_fmt, working_matrix(meta) or "bt601", working_matrix(meta) is not None))
|
|
608
|
+
output = args.output or default_output(args.input, "correct", ext)
|
|
609
|
+
tag = "correct"
|
|
610
|
+
# OBSERVED technical measurements (signalstats: luma / saturation distribution), never a
|
|
611
|
+
# "looks better" judgement -- the same primitive probe.py --analyze uses for Log detection.
|
|
612
|
+
measurements = None if STATE.dry_run else {"input": analyze_levels(args.input)}
|
|
613
|
+
else:
|
|
614
|
+
if v.get("bt2020_or_hdr") and not args.force:
|
|
615
|
+
die(f"{args.input} is HDR ({v.get('hdr_format')}); a LUT made for SDR applied to PQ/HLG pixels gives a wrong picture "
|
|
616
|
+
f"tagged BT.709 (sweep F10). Run --to-sdr first (or chain it), or --force if the LUT expects HDR input")
|
|
617
|
+
if not os.path.exists(args.lut):
|
|
618
|
+
die(f"LUT {absent_word(args.lut)}: {args.lut}")
|
|
619
|
+
refuse_bad_cube(args.lut)
|
|
620
|
+
if not (0.0 <= args.lut_strength <= 1.0):
|
|
621
|
+
die(f"--lut-strength {args.lut_strength:g} is outside 0..1")
|
|
622
|
+
lut = f"lut3d=file={escape_filter_path(args.lut)}:interp=tetrahedral"
|
|
623
|
+
to_rgb, to_yuv = lut_legs(meta, out_fmt)
|
|
624
|
+
if args.lut_strength == 0.0:
|
|
625
|
+
# 0 means "no LUT at all" -- without this branch, 0 (falling outside the open interval
|
|
626
|
+
# below) landed in the same "apply the LUT at full strength" fallback as an out-of-range
|
|
627
|
+
# value did before the guard above existed: the one strength value documented to mean
|
|
628
|
+
# "don't grade it" instead silently graded it at 100%, the opposite of what was asked.
|
|
629
|
+
# (an RGB source on a YUV alpha line is still converted to the BT.709 that line is, #496)
|
|
630
|
+
vf = (("format=rgb24," if v.get("pix_fmt") == "pal8" else "") + rgb_to_bt709_filter(out_fmt)
|
|
631
|
+
if rgb_to_bt709_line(meta) else f"format={out_fmt}")
|
|
632
|
+
elif args.lut_strength < 1.0:
|
|
633
|
+
# blend graded and original
|
|
634
|
+
# blended in RGB, both pictures through the same two legs
|
|
635
|
+
vf = f"{to_rgb},split[o][g];[g]{lut}[g2];[o][g2]blend=all_mode=normal:all_opacity={args.lut_strength:g},{to_yuv}"
|
|
636
|
+
else:
|
|
637
|
+
vf = f"{to_rgb},{lut},{to_yuv}"
|
|
638
|
+
output = args.output or default_output(args.input, "lut", ext)
|
|
639
|
+
tag = "lut"
|
|
640
|
+
|
|
641
|
+
if args.legalize:
|
|
642
|
+
# the last filter before the encoder, on the 4:2:0 picture it encodes: a clamp ahead of the
|
|
643
|
+
# chroma subsampling would let the subsampling filter's overshoot put samples back out
|
|
644
|
+
# a full-range picture (yuvj420p, or tagged pc) is converted to limited range first: its codes
|
|
645
|
+
# span 0-255 by design, and clamping them as they are would crush its blacks and whites into
|
|
646
|
+
# the limits instead of scaling them there. A limited-range source gets the chain it always had.
|
|
647
|
+
full = v.get("color_range") == "pc" or str(v.get("pix_fmt") or "").startswith("yuvj")
|
|
648
|
+
vf = ((vf + "," if vf else "") + ("scale=out_range=tv," if full else "")
|
|
649
|
+
+ "format=yuv420p," + legal_clamp(args.legalize))
|
|
650
|
+
if alpha_codec:
|
|
651
|
+
# --keep-alpha: the grade works on the colour and never touches the alpha, which is split off
|
|
652
|
+
# the source, kept as it is and merged back (alphamerge) in front of the alpha line; the
|
|
653
|
+
# source's colour tags are kept, as --codec prores keeps them (no BT.709 conversion). An
|
|
654
|
+
# RGB source has none: its YUV line is BT.709 and tagged so (working_matrix). An RGB line
|
|
655
|
+
# converts the graded YUV in front of alphamerge, so the matrix is labelled there too
|
|
656
|
+
un = unpremultiply_leg(meta) if args.source_alpha_mode == "premultiplied" else ""
|
|
657
|
+
# alphamerge negotiates an 8-bit mask. Keep the source mask at 16 bits
|
|
658
|
+
# through the RGB multiply on a premultiplied ProRes master.
|
|
659
|
+
merge = "[ka_a]alphaextract[ka_m];[ka_g][ka_m]alphamerge"
|
|
660
|
+
if un and alpha_codec == "prores4444":
|
|
661
|
+
merge = ("[ka_g]format=gbrp16le[ka_rgb];[ka_a]alphaextract,format=gray16le[ka_m];"
|
|
662
|
+
"[ka_rgb][ka_m]mergeplanes=map1p=1:map2p=2:map3s=1:format=gbrap16le")
|
|
663
|
+
fc = (f"[0:v]split[ka_c][ka_a];[ka_c]{un}{vf}{matrix_label(meta)}[ka_g];"
|
|
664
|
+
f"{merge},{finish_chain(alpha_codec, args.alpha_mode, meta, wide=bool(un))}[ka_v]")
|
|
665
|
+
fc = cfr_at_input(fc, meta) # the conform of a VFR source: the fps filter (#512)
|
|
666
|
+
cmd = ffmpeg_base() + decoder_args_for(meta, args.input) + ["-i", args.input, "-filter_complex", fc,
|
|
667
|
+
"-map", "[ka_v]", "-map", f"0:a:{args.audio_stream}?"]
|
|
668
|
+
cmd += video_line(alpha_codec) + tag_args(meta) + cfr_args(meta) + (audio_line(alpha_codec) if has_audio else [])
|
|
669
|
+
if STATE.hw:
|
|
670
|
+
note(f"--hw: --alpha-codec {alpha_codec} stays on the CPU (no VideoToolbox encoder writes it with its alpha)")
|
|
671
|
+
else:
|
|
672
|
+
cmd = ffmpeg_base() + ["-i", args.input, "-vf", with_cfr(vf, meta), "-map", "0:v:0", "-map", f"0:a:{args.audio_stream}?"]
|
|
673
|
+
# --lut/--correct grade the source's own pixels, so a BT.601 source is converted to the BT.709
|
|
674
|
+
# the line is tagged with; --to-sdr's zscale chain already writes BT.709 and converts nothing more
|
|
675
|
+
cmd += x264_args(args.crf, args.preset, source=None if args.to_sdr else meta) + cfr_args(meta) + (aac_args() if has_audio else [])
|
|
676
|
+
dropped_streams = run_keeping_subtitles(cmd, output)
|
|
677
|
+
r = probe(output, role="output")
|
|
678
|
+
info(f"wrote {output} ({fmt_secs(r['duration'])}, {r['video']['width']}x{r['video']['height']}, "
|
|
679
|
+
f"{r['video']['color_transfer']}/{r['video']['color_primaries']}, {tag})")
|
|
680
|
+
extra = {"dropped_non_av_streams": dropped_streams, **sdr_extra}
|
|
681
|
+
if measurements is not None:
|
|
682
|
+
measurements["output"] = analyze_levels(output)
|
|
683
|
+
extra["measurements"] = measurements
|
|
684
|
+
# the source's alpha against the output's: kept (--keep-alpha), or lost and failing the `alpha`
|
|
685
|
+
# step (an opaque line on a source whose alpha is used), or dropped on purpose (--drop-alpha)
|
|
686
|
+
alpha_report(args, alpha_codec, src_alpha, output, extra, composite=False)
|
|
687
|
+
if args.legalize and not STATE.dry_run:
|
|
688
|
+
extra["legalize"], check = legalize_report(args.legalize, output)
|
|
689
|
+
extra["verification"] = extra.get("verification", []) + check
|
|
690
|
+
emit(output, **extra)
|
|
691
|
+
return 0
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
if __name__ == "__main__":
|
|
695
|
+
sys.exit(main())
|