@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,1083 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Join clips with transitions, normalising resolution, frame rate and audio
|
|
3
|
+
layout so mismatched sources (phone + camera + screen recording) cut together.
|
|
4
|
+
|
|
5
|
+
Transitions (xfade): fade, dissolve, wipeleft, wiperight, wipeup, wipedown,
|
|
6
|
+
slideleft, slideright, circleopen, fadeblack, fadewhite, smoothleft, none.
|
|
7
|
+
|
|
8
|
+
Audio-only inputs (WAV, FLAC, MP3, M4A, ...) are joined as audio: every clip is
|
|
9
|
+
resampled to one rate and channel layout (the first clip's rate, the widest
|
|
10
|
+
layout; --sample-rate / --channels override), crossfaded with acrossfade or
|
|
11
|
+
butted with concat, and written in the codec the output extension names. The
|
|
12
|
+
output of an audio join must be an audio extension; mixing audio and video
|
|
13
|
+
inputs is refused.
|
|
14
|
+
|
|
15
|
+
Examples:
|
|
16
|
+
python3 join.py a.mp4 b.mp4 c.mp4 -o final.mp4 # 0.5 s crossfade, size/fps from the first clip
|
|
17
|
+
python3 join.py *.mp4 --transition fadeblack --duration 1 -o reel.mp4
|
|
18
|
+
python3 join.py a.mov b.mp4 --transition none --width 1920 --height 1080 --fps 30
|
|
19
|
+
python3 join.py intro.wav talk.m4a outro.wav -o episode.flac # audio join, 0.5 s crossfade
|
|
20
|
+
python3 join.py part1.wav part2.wav --transition none -o full.wav # butt join, sample rate of part1
|
|
21
|
+
python3 join.py --list parts.txt --transition none -o voice.wav # the segments a TTS step wrote, in order
|
|
22
|
+
python3 join.py --list parts.txt --on-missing skip -o voice.wav # join what is there, report the rest
|
|
23
|
+
|
|
24
|
+
Every input is checked before anything is joined: a missing, empty or unreadable segment is
|
|
25
|
+
refused with every problem named at once (kind input), never discovered one run at a time.
|
|
26
|
+
--on-missing skip joins the usable segments instead and lists the others under `skipped`.
|
|
27
|
+
Under --dry-run a segment that does not exist yet is an earlier step's output: it is planned
|
|
28
|
+
on and named under `pending` (never `skipped`), whichever --on-missing was given, and its
|
|
29
|
+
extension stands in for what it will hold (an audio extension: no picture).
|
|
30
|
+
|
|
31
|
+
Every input with an audio stream is also measured (one volumedetect pass): a segment whose peak
|
|
32
|
+
is at or below --silence-threshold (default -50 dBFS) is silent -- the trace of a TTS call that
|
|
33
|
+
wrote a valid but empty wav. --on-silent warn (default) joins it and names it under `silent`;
|
|
34
|
+
fail refuses it with the other input problems; skip drops it into `skipped`. A clip with no
|
|
35
|
+
audio stream is never silent.
|
|
36
|
+
"""
|
|
37
|
+
import argparse
|
|
38
|
+
import json
|
|
39
|
+
import math
|
|
40
|
+
import os
|
|
41
|
+
import tempfile
|
|
42
|
+
import sys
|
|
43
|
+
from fractions import Fraction
|
|
44
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
45
|
+
|
|
46
|
+
from _common.probe import SILENT_PEAK_DBFS, signatures_match, stream_signature
|
|
47
|
+
from _common.runner import path_denied, read_text_or_die, run_analysis
|
|
48
|
+
from _common import STATE, AUDIO_CODECS, AUDIO_MEDIA_EXT, concat_list_line, refuse_unwritten_output, guard_sidecar, refuse_output_is_input, place_output, refuse, sibling_temp, as_limited, draws_chroma, drawn_chain, mix_color_chains, video_args, aac_args, add_common, apply_common, audio_codec_for, default_output, die, dry_run_input_pending, emit, ffmpeg_base, info, measured_level_dbfs, is_audio_output, probe, require_tool, run, validate_color, X264_PRESETS, fmt_secs
|
|
49
|
+
from _common.emit import note, warn
|
|
50
|
+
from _common.decision import av_clip_length, av_trim, stream_starts, warn_mostly_cropped
|
|
51
|
+
from _common.probe import display_size, square_pixels, square_pixels_note
|
|
52
|
+
from _common.timeline import exact_rate
|
|
53
|
+
from _common.emit import input_length, refuse_still
|
|
54
|
+
|
|
55
|
+
TRANSITIONS = ["fade", "dissolve", "wipeleft", "wiperight", "wipeup", "wipedown", "slideleft", "slideright",
|
|
56
|
+
"circleopen", "circleclose", "fadeblack", "fadewhite", "smoothleft", "smoothright", "radial", "none"]
|
|
57
|
+
LAYOUTS = {1: "mono", 2: "stereo", 6: "5.1", 8: "7.1"}
|
|
58
|
+
# inputs --on-missing skip dropped, reported in the success document (empty when nothing was)
|
|
59
|
+
STATE_SKIPPED: List[Dict[str, Any]] = []
|
|
60
|
+
# --dry-run: inputs that do not exist yet, planned on as an earlier step's output
|
|
61
|
+
STATE_PENDING: List[Dict[str, Any]] = []
|
|
62
|
+
STATE_NOTES: List[str] = []
|
|
63
|
+
# the joined picture's length against the clips' sum less the transitions: 1.5 frames, at least 0.05 s
|
|
64
|
+
DURATION_TOLERANCE_FRAMES = 1.5
|
|
65
|
+
DURATION_TOLERANCE_MIN = 0.05
|
|
66
|
+
# --on-silent warn: inputs whose audio peak is at or below --silence-threshold, joined anyway
|
|
67
|
+
STATE_SILENT: List[Dict[str, Any]] = []
|
|
68
|
+
# warnings, never refusals: a clip shorter than MIN_SEGMENT_FRAMES frames (audio-only: shorter than
|
|
69
|
+
# MIN_AUDIO_SEGMENT seconds) and a path listed more than once (repeating a clip can be intentional)
|
|
70
|
+
STATE_SHORT: List[Dict[str, Any]] = []
|
|
71
|
+
STATE_DUPES: List[Dict[str, Any]] = []
|
|
72
|
+
# original 0-based list position of each input still in args.inputs (after any skip)
|
|
73
|
+
STATE_KEPT: List[int] = []
|
|
74
|
+
MIN_SEGMENT_FRAMES = 2
|
|
75
|
+
MIN_AUDIO_SEGMENT = 0.05
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def reported() -> Dict[str, Any]:
|
|
79
|
+
"""The input bookkeeping both success documents carry: `skipped` is what the join left out,
|
|
80
|
+
`pending` what a dry run planned on without it existing; `notes` says the same in words."""
|
|
81
|
+
extra: Dict[str, Any] = {"skipped": list(STATE_SKIPPED), "pending": list(STATE_PENDING), "silent": list(STATE_SILENT),
|
|
82
|
+
"short_segments": list(STATE_SHORT), "duplicates": list(STATE_DUPES)}
|
|
83
|
+
if STATE_NOTES:
|
|
84
|
+
extra["notes"] = list(STATE_NOTES)
|
|
85
|
+
return extra
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def unpending_length(durs: List[float], d: float) -> Optional[float]:
|
|
89
|
+
"""The joined length the clip durations add up to, or None while an input is pending: its
|
|
90
|
+
dry-run stub says 0 s, which would count the clip as nothing and still subtract a transition
|
|
91
|
+
for it (a negative length when nothing exists yet)."""
|
|
92
|
+
if STATE_PENDING:
|
|
93
|
+
return None
|
|
94
|
+
return round(sum(durs) - d * (len(durs) - 1), 3)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def overlap_report(durs: List[float], expected: Optional[float]) -> Dict[str, Any]:
|
|
98
|
+
"""The clips' own total next to the joined length (2.20). The joined length is derived from
|
|
99
|
+
the transition the join itself applied, so a check against it alone cannot show that a fade
|
|
100
|
+
took time out of the material; the sum of the inputs is the yardstick the user holds."""
|
|
101
|
+
if expected is None or STATE_PENDING:
|
|
102
|
+
return {}
|
|
103
|
+
total = round(sum(durs), 3)
|
|
104
|
+
out: Dict[str, Any] = {"inputs_duration": total, "transition_shortening": round(total - expected, 3)}
|
|
105
|
+
if out["transition_shortening"] > 0.0005:
|
|
106
|
+
STATE_NOTES.append(f"the transitions overlap the clips: {fmt_secs(total)} of clips play as {fmt_secs(expected)} "
|
|
107
|
+
f"({out['transition_shortening']:.3f} s shorter)")
|
|
108
|
+
return out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def clip_length(meta: Dict[str, Any], fps: float) -> float:
|
|
112
|
+
"""The one length a clip holds in a join, for its picture and its sound alike: the
|
|
113
|
+
video stream's, or up to where the sound ends when it runs more than a frame past the picture
|
|
114
|
+
(narration is never cut; an AAC tail adds no frame), counted from the first frame. The container
|
|
115
|
+
duration (audio priming, a longer track) is only the fallback when a stream length is unknown
|
|
116
|
+
(a pending input). Shared with reverse.py as av_clip_length."""
|
|
117
|
+
return av_clip_length(meta, fps)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# the video join's sound rate (every clip is resampled to it before the trims)
|
|
121
|
+
JOIN_AUDIO_RATE = 48000
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def output_rate(fps: float, first: Dict[str, Any], asked: bool) -> Fraction:
|
|
125
|
+
"""The join's frame rate as an exact fraction: the first clip's own r_frame_rate/avg_frame_rate
|
|
126
|
+
when `fps` is that clip's (30000/1001, not 29.97), else the NTSC fraction or the plain one
|
|
127
|
+
`fps` names (timeline.exact_rate). Every clip length, offset and sound length is counted in
|
|
128
|
+
frames of this rate, so the graph's fps filter runs at the same fraction."""
|
|
129
|
+
if not asked:
|
|
130
|
+
for key in ("r_frame_rate", "avg_frame_rate"):
|
|
131
|
+
try:
|
|
132
|
+
q = Fraction(str(first.get(key) or ""))
|
|
133
|
+
except (ValueError, ZeroDivisionError):
|
|
134
|
+
continue
|
|
135
|
+
# the declared rate also wins when the average was taken over a length that leaves out
|
|
136
|
+
# the last frame's duration (#475: 5 frames in 0.1333 s read 37.5 fps, and the whole
|
|
137
|
+
# join ran at 75/2)
|
|
138
|
+
if 0 < q <= 240 and (abs(float(q) - fps) < 1e-3 or short_last_frame(first, q)):
|
|
139
|
+
return q
|
|
140
|
+
return exact_rate(fps)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def short_last_frame(video: Optional[Dict[str, Any]], q: Fraction) -> bool:
|
|
144
|
+
"""Whether a picture's duration is its frame count less one frame at rate `q`: a container
|
|
145
|
+
that stores no duration for the last frame (MOV written with -fps_mode passthrough, seen on
|
|
146
|
+
FFmpeg 7.1) reads 5 frames as 0.1333 s at 30 fps (#475)."""
|
|
147
|
+
v = video or {}
|
|
148
|
+
nb, dur = v.get("nb_frames"), v.get("duration")
|
|
149
|
+
if not nb or nb < 2 or not dur or q <= 0:
|
|
150
|
+
return False
|
|
151
|
+
step = float(1 / q)
|
|
152
|
+
return abs(dur - (nb - 1) * step) < 0.25 * step and abs(dur - nb * step) > 0.25 * step
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def with_whole_picture(meta: Dict[str, Any], q: Fraction) -> Dict[str, Any]:
|
|
156
|
+
"""`meta` with its picture counted as every frame it holds when its duration leaves out the
|
|
157
|
+
last one (short_last_frame), so the clip-length rule does not read the sound as running a
|
|
158
|
+
frame past the picture and hold the clip longer (#475). Other clips are returned as they are."""
|
|
159
|
+
v = meta.get("video") or {}
|
|
160
|
+
# each clip at its OWN declared rate: at the join's rate a complete 30 fps clip of 5 frames
|
|
161
|
+
# (5/30 s) also equals 4 frames at --fps 24 and would be stretched to 5/24 s
|
|
162
|
+
try:
|
|
163
|
+
own = Fraction(str(v.get("r_frame_rate") or ""))
|
|
164
|
+
except (ValueError, ZeroDivisionError):
|
|
165
|
+
own = q
|
|
166
|
+
if not 0 < own <= 240:
|
|
167
|
+
own = q
|
|
168
|
+
if not short_last_frame(v, own):
|
|
169
|
+
return meta
|
|
170
|
+
return dict(meta, video=dict(v, duration=float(v["nb_frames"] / own)))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def clip_frames(meta: Dict[str, Any], length: float, q: Fraction) -> int:
|
|
174
|
+
"""How many frames of rate `q` a clip of `length` seconds (clip_length) holds in the join: its
|
|
175
|
+
picture's frames, or, when the clip lasts as long as its sound, enough frames to cover that
|
|
176
|
+
sound (narration is never cut; a hundredth of a frame is rounding, not sound). A pending
|
|
177
|
+
dry-run stub's 0 s stays 0; a measured clip holds at least one frame (#455: a length in
|
|
178
|
+
milliseconds rounded up started every next clip late, and the errors added up)."""
|
|
179
|
+
exact = length * q.numerator / q.denominator
|
|
180
|
+
vlen = (meta.get("video") or {}).get("duration") or 0.0
|
|
181
|
+
frames = math.ceil(exact - 0.01) if vlen and length > vlen else round(exact)
|
|
182
|
+
return frames if meta.get("dry_run") else max(1, frames)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def frame_time(frames: int, q: Fraction) -> str:
|
|
186
|
+
"""The time of frame `frames` at rate `q` in seconds, rounded down to the microsecond: never
|
|
187
|
+
after that frame's own timestamp, so a filter that starts on the first frame at or after it
|
|
188
|
+
(xfade's offset) starts on that frame and not the next (#468: 2.566667 written 2.567 started
|
|
189
|
+
the transition a frame late). Trailing zeros are dropped (0.5, not 0.500000)."""
|
|
190
|
+
us = (frames * q.denominator * 1_000_000) // q.numerator
|
|
191
|
+
text = f"{us // 1_000_000}.{us % 1_000_000:06d}".rstrip("0").rstrip(".")
|
|
192
|
+
return text or "0"
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def find_duplicates(paths: List[str]) -> List[Dict[str, Any]]:
|
|
196
|
+
"""Every path (compared by its resolved absolute form) listed more than once, with the 0-based
|
|
197
|
+
list positions it appears at. A warning, not a refusal: repeating a clip can be intentional."""
|
|
198
|
+
seen: Dict[str, List[int]] = {}
|
|
199
|
+
for i, p in enumerate(paths):
|
|
200
|
+
seen.setdefault(os.path.realpath(p), []).append(i)
|
|
201
|
+
return [{"path": paths[ix[0]], "indices": ix} for ix in seen.values() if len(ix) > 1]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def note_short_segments(paths: List[str], metas: List[dict], minimum: float, unit: str) -> None:
|
|
205
|
+
"""Record every measured input shorter than `minimum` seconds (a pending dry-run stub is not
|
|
206
|
+
measured): such a clip joins as a flash nobody sees -- usually a failed earlier step."""
|
|
207
|
+
for p, m, k in zip(paths, metas, STATE_KEPT or range(len(paths))):
|
|
208
|
+
dur = m.get("duration") or 0.0
|
|
209
|
+
if m.get("dry_run") or dur >= minimum:
|
|
210
|
+
continue
|
|
211
|
+
STATE_SHORT.append({"index": k, "path": p, "duration": round(dur, 4)})
|
|
212
|
+
if STATE_SHORT:
|
|
213
|
+
listing = ", ".join(f"#{s['index'] + 1} {s['path']} ({s['duration']:g}s)" for s in STATE_SHORT)
|
|
214
|
+
warn(f"{len(STATE_SHORT)} input(s) shorter than {unit}: {listing}", "short_inputs", count=len(STATE_SHORT))
|
|
215
|
+
STATE_NOTES.append(f"{len(STATE_SHORT)} input(s) are shorter than {unit} and were joined anyway: {listing}")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def expected_text(expected: Optional[float]) -> str:
|
|
219
|
+
"""unpending_length() as the stderr summary line puts it."""
|
|
220
|
+
return f"expected ~{expected:.3f}s" if expected is not None else "expected length unknown until the pending inputs exist"
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def join_audio(args: argparse.Namespace, metas: List[dict]) -> int:
|
|
224
|
+
"""Concatenate audio-only inputs: one sample rate, one channel layout, acrossfade or concat."""
|
|
225
|
+
n = len(args.inputs)
|
|
226
|
+
durs = [m.get("duration") or 0.0 for m in metas]
|
|
227
|
+
d = args.duration if args.transition != "none" else 0.0
|
|
228
|
+
place_silent(durs, d)
|
|
229
|
+
note_short_segments(args.inputs, metas, MIN_AUDIO_SEGMENT, f"{MIN_AUDIO_SEGMENT:g}s")
|
|
230
|
+
for p, dur in zip(args.inputs, durs):
|
|
231
|
+
if d and dur <= d * 2 and not STATE.dry_run:
|
|
232
|
+
die(f"{p} is only {dur:.2f}s, too short for a {d:.2f}s crossfade; shorten --duration")
|
|
233
|
+
# a pending input's probe is the dry-run stub (rate and layout unmeasured): plan from the
|
|
234
|
+
# clips that exist, and fall back to 48 kHz stereo only when none does
|
|
235
|
+
known = [m for m in metas if not m.get("dry_run")] or metas
|
|
236
|
+
rates = [m["audio"].get("sample_rate") or 48000 for m in known]
|
|
237
|
+
chans = [m["audio"].get("channels") or 2 for m in known]
|
|
238
|
+
rate = args.sample_rate or rates[0]
|
|
239
|
+
channels = args.channels or max(chans)
|
|
240
|
+
layout = LAYOUTS.get(channels)
|
|
241
|
+
if layout is None:
|
|
242
|
+
die(f"{channels}-channel output has no standard layout here (1, 2, 6 or 8); pass --channels")
|
|
243
|
+
if len(set(rates)) > 1:
|
|
244
|
+
info(f"sample rates differ ({', '.join(str(r) for r in rates)} Hz); resampling every clip to {rate} Hz")
|
|
245
|
+
if len(set(chans)) > 1:
|
|
246
|
+
info(f"channel counts differ ({', '.join(str(c) for c in chans)}); every clip becomes {layout}")
|
|
247
|
+
output = args.output or default_output(args.inputs[0], "joined")
|
|
248
|
+
refuse_list_as_output(args, output)
|
|
249
|
+
if not is_audio_output(output):
|
|
250
|
+
refuse_unwritten_output(output) # .wma is not a video container either (#517)
|
|
251
|
+
die(f"audio-only inputs cannot fill a video container: give -o an audio extension ({', '.join(AUDIO_CODECS)}), not {output}")
|
|
252
|
+
|
|
253
|
+
cmd = ffmpeg_base()
|
|
254
|
+
for p in args.inputs:
|
|
255
|
+
cmd += ["-i", p]
|
|
256
|
+
parts = [f"[{i}:a:0]aformat=sample_rates={rate}:channel_layouts={layout},asetpts=PTS-STARTPTS[a{i}]" for i in range(n)]
|
|
257
|
+
if args.transition == "none":
|
|
258
|
+
parts.append("".join(f"[a{i}]" for i in range(n)) + f"concat=n={n}:v=0:a=1[aout]")
|
|
259
|
+
else:
|
|
260
|
+
prev = "a0"
|
|
261
|
+
for i in range(1, n):
|
|
262
|
+
out = f"ax{i}" if i < n - 1 else "aout"
|
|
263
|
+
parts.append(f"[{prev}][a{i}]acrossfade=d={d:g}:c1=tri:c2=tri[{out}]")
|
|
264
|
+
prev = out
|
|
265
|
+
cmd += ["-filter_complex", ";".join(parts), "-map", "[aout]", "-vn"] + audio_codec_for(output) + [output]
|
|
266
|
+
run(cmd)
|
|
267
|
+
expected = unpending_length(durs, d)
|
|
268
|
+
r = probe(output, role="output")
|
|
269
|
+
a = r.get("audio") or {}
|
|
270
|
+
if not STATE.dry_run:
|
|
271
|
+
if r.get("video"):
|
|
272
|
+
die(f"{output} unexpectedly contains a video stream")
|
|
273
|
+
if a.get("sample_rate") != rate or a.get("channels") != channels:
|
|
274
|
+
die(f"{output} is {a.get('sample_rate')} Hz {a.get('channels')} ch, expected {rate} Hz {channels} ch")
|
|
275
|
+
info(f"wrote {output} ({fmt_secs(r['duration'])}, {expected_text(expected)}, audio {a.get('codec')} {channels}ch {rate}Hz, {n} clips, "
|
|
276
|
+
+ ("crossfade" if d else "butt join") + ")")
|
|
277
|
+
overlap = overlap_report(durs, expected)
|
|
278
|
+
emit(output, mode="audio", **overlap, **reported(), clips=n, transition=args.transition if d else "none", expected_duration=expected,
|
|
279
|
+
sample_rate=rate, channels=channels, video=False, expect_streams={"audio": 1})
|
|
280
|
+
return 0
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
# ffmpeg concat-demuxer directives other than `file`: they change what a `file` line plays
|
|
284
|
+
CONCAT_DIRECTIVES = frozenset({"inpoint", "outpoint", "duration", "stream", "exact_stream_id", "file_packet_metadata",
|
|
285
|
+
"file_packet_meta", "option", "stream_meta", "stream_codec", "stream_extradata", "chapter"})
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def refuse_list_as_output(args: argparse.Namespace, output: str) -> None:
|
|
289
|
+
"""The --list file is read here and is never an -i of the join, so run()'s guard did not see
|
|
290
|
+
an output named like it (#522's sweep): refused once the output is known, before any write."""
|
|
291
|
+
if args.list:
|
|
292
|
+
refuse_output_is_input(output, args.list, why="the clip list would be replaced by the join")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def read_list(path: str) -> List[str]:
|
|
296
|
+
"""--list FILE: one segment per line, in order, relative to the list file's own folder.
|
|
297
|
+
Blank lines and # comments are ignored, and ffmpeg's concat-demuxer spelling
|
|
298
|
+
(`file 'part 01.wav'`, the `ffconcat version` header) is accepted, so a list written for
|
|
299
|
+
`ffmpeg -f concat` works as is unless it trims: `inpoint`, `outpoint`, `duration` and the other
|
|
300
|
+
directives are refused by name, since nothing here applies them."""
|
|
301
|
+
# the shared reader: a BOM, CRLF and a file that is not UTF-8 are read or refused as every
|
|
302
|
+
# other text input is, and a line ends at "\n" only
|
|
303
|
+
text = read_text_or_die(path, "--list")
|
|
304
|
+
base = os.path.dirname(os.path.abspath(path))
|
|
305
|
+
entries: List[str] = []
|
|
306
|
+
ffconcat = False
|
|
307
|
+
for line in text.split("\n"):
|
|
308
|
+
line = line.strip()
|
|
309
|
+
if not line or line.startswith("#"):
|
|
310
|
+
continue
|
|
311
|
+
# In a plain list an existing POSIX filename can contain a literal tab.
|
|
312
|
+
tab_directive = line.startswith("file\t") and (ffconcat or not os.path.isfile(os.path.join(base, line)))
|
|
313
|
+
if line.startswith("file ") or tab_directive:
|
|
314
|
+
line = line[5:].strip()
|
|
315
|
+
if len(line) >= 2 and line[0] == line[-1] and line[0] in "'\"":
|
|
316
|
+
line = line[1:-1].replace("'\\''", "'")
|
|
317
|
+
elif line.split()[0] == "ffconcat" and line.split()[1:2] == ["version"]:
|
|
318
|
+
ffconcat = True
|
|
319
|
+
continue # the concat demuxer's header line names no file
|
|
320
|
+
elif line.split()[0] in CONCAT_DIRECTIVES and not os.path.exists(os.path.join(base, line)):
|
|
321
|
+
# only `file` lines are read: a directive was taken for a path, reported as a missing
|
|
322
|
+
# (or, under --dry-run, pending) input, and with --on-missing skip its trim was lost.
|
|
323
|
+
# `stream` takes no argument (FFmpeg 6.1's concat demuxer); a line naming a file that is
|
|
324
|
+
# there is a path, whatever its first word
|
|
325
|
+
die(f"--list {path}: `{line}` is an ffmpeg concat directive, which join.py does not apply: the list is "
|
|
326
|
+
"read for its `file` lines only", kind="input",
|
|
327
|
+
hint="trim a clip with cut.py first and list the cut file (inpoint/outpoint/duration), "
|
|
328
|
+
"or remove the line")
|
|
329
|
+
entries.append(line if os.path.isabs(line) else os.path.join(base, line))
|
|
330
|
+
if not entries:
|
|
331
|
+
# the failure this exists for: an upstream step produced nothing, and the join must
|
|
332
|
+
# say so plainly rather than hand ffmpeg an empty concat and die somewhere later
|
|
333
|
+
die(f"--list {path} names no segments (empty, or only blank lines and comments)",
|
|
334
|
+
hint="check the step that writes the list: it produced no files")
|
|
335
|
+
return entries
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def preflight(paths: List[str], audible: Optional[List[int]] = None) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
|
339
|
+
"""Every problem with every input, found before anything runs: missing, empty (0 bytes,
|
|
340
|
+
the usual trace of a TTS or download step that failed after creating its file), or not
|
|
341
|
+
readable as media. One ffprobe per file; nothing is decoded. Under --dry-run a file that
|
|
342
|
+
does not exist yet is not a problem but pending (the second list, with a note): in a
|
|
343
|
+
planned pipeline it is an earlier step's output, and the plan keeps it. The index of every
|
|
344
|
+
readable input with an audio stream is appended to `audible` (for find_silent())."""
|
|
345
|
+
ffprobe = require_tool("ffprobe")
|
|
346
|
+
problems: List[Dict[str, Any]] = []
|
|
347
|
+
pending: List[Dict[str, Any]] = []
|
|
348
|
+
for i, p in enumerate(paths):
|
|
349
|
+
if dry_run_input_pending(p):
|
|
350
|
+
pending.append({"index": i, "path": p})
|
|
351
|
+
continue
|
|
352
|
+
# a file that is there but unreadable is "permission denied" too, not ffprobe's line (#558)
|
|
353
|
+
if path_denied(p) or not os.path.exists(p):
|
|
354
|
+
problems.append({"index": i, "path": p, "reason": "permission denied" if path_denied(p) else "missing"})
|
|
355
|
+
continue
|
|
356
|
+
if os.path.isdir(p):
|
|
357
|
+
problems.append({"index": i, "path": p, "reason": "a directory, not a file"})
|
|
358
|
+
continue
|
|
359
|
+
if os.path.getsize(p) == 0:
|
|
360
|
+
problems.append({"index": i, "path": p, "reason": "empty (0 bytes)"})
|
|
361
|
+
continue
|
|
362
|
+
proc = run([ffprobe, "-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", p],
|
|
363
|
+
quiet=True, check=False)
|
|
364
|
+
kinds = {line.strip() for line in (proc.stdout or "").splitlines() if line.strip()}
|
|
365
|
+
if proc.returncode != 0 or not kinds & {"audio", "video"}:
|
|
366
|
+
first = ((proc.stderr or "").strip().splitlines() or ["no audio or video stream"])[-1]
|
|
367
|
+
problems.append({"index": i, "path": p, "reason": f"unreadable: {first}"})
|
|
368
|
+
elif "audio" in kinds and audible is not None:
|
|
369
|
+
audible.append(i)
|
|
370
|
+
return problems, pending
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def find_silent(paths: List[str], audible: List[int], threshold: float) -> List[Dict[str, Any]]:
|
|
374
|
+
"""The audible inputs whose whole-file peak (volumedetect max_volume) is at or below
|
|
375
|
+
`threshold` dBFS: one decode of the audio per input. Not under --dry-run: join is a writing
|
|
376
|
+
tool, and a dry run of it (or of render.py, which joins through it) runs no ffmpeg -- the plan
|
|
377
|
+
notes that silence is measured on the real run. An input whose level cannot be measured is
|
|
378
|
+
left to the join itself."""
|
|
379
|
+
silent: List[Dict[str, Any]] = []
|
|
380
|
+
if STATE.dry_run:
|
|
381
|
+
if audible:
|
|
382
|
+
STATE_NOTES.append("silence is not measured under --dry-run; a real run measures every input with audio "
|
|
383
|
+
"for --on-silent")
|
|
384
|
+
return silent
|
|
385
|
+
for i in audible:
|
|
386
|
+
lv = measured_level_dbfs(paths[i], seconds=86400)
|
|
387
|
+
if lv is not None and lv["peak_dbfs"] <= threshold:
|
|
388
|
+
silent.append({"index": i, "path": paths[i], "peak_db": lv["peak_dbfs"]})
|
|
389
|
+
return silent
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def place_silent(lens: List[float], d: float) -> None:
|
|
393
|
+
"""Where each joined silent input sits in the output: `at`/`end` in output seconds. Input k
|
|
394
|
+
(in kept order) starts after the kept inputs before it, each overlapped by the transition d."""
|
|
395
|
+
for sil in STATE_SILENT:
|
|
396
|
+
if sil["index"] not in STATE_KEPT:
|
|
397
|
+
continue
|
|
398
|
+
k = STATE_KEPT.index(sil["index"])
|
|
399
|
+
if k >= len(lens):
|
|
400
|
+
continue
|
|
401
|
+
at = sum(lens[:k]) - k * d
|
|
402
|
+
sil["at"], sil["end"] = round(at, 3), round(at + lens[k], 3)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def parse_allow_silent(value: Optional[str], n: int) -> List[int]:
|
|
406
|
+
"""--allow-silent 3,7 -> 0-based indices; each must name an input (1..n)."""
|
|
407
|
+
if not value:
|
|
408
|
+
return []
|
|
409
|
+
out = []
|
|
410
|
+
for tok in value.split(","):
|
|
411
|
+
tok = tok.strip()
|
|
412
|
+
if not tok.isdigit() or not 1 <= int(tok) <= n:
|
|
413
|
+
die(f"--allow-silent takes input numbers 1..{n} separated by commas, got {tok!r}")
|
|
414
|
+
out.append(int(tok) - 1)
|
|
415
|
+
return out
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
# join.py --copy (2.24). The concat demuxer starts each clip where the previous one's container
|
|
419
|
+
# ends, so a stream that ends early leaves a gap at the join: a held frame for the picture, a hole
|
|
420
|
+
# for the sound. A clip whose picture and sound end further apart than this is refused.
|
|
421
|
+
COPY_AV_GAP = 0.05
|
|
422
|
+
COPY_PREROLL_PACKETS = 300 # packets read per clip to find an edit list's hidden pre-roll
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _copy_doc(path: str) -> "Optional[Dict[str, Any]]":
|
|
426
|
+
"""ffprobe's first video and first audio stream of `path`, with extradata hashes, as the doc
|
|
427
|
+
stream_signature() reads; None when it cannot be read."""
|
|
428
|
+
proc = run([require_tool("ffprobe"), "-v", "error", "-show_data_hash", "sha256", "-show_streams", "-show_format",
|
|
429
|
+
"-of", "json", path], quiet=True, check=False)
|
|
430
|
+
try:
|
|
431
|
+
doc = json.loads(proc.stdout or "") if proc.returncode == 0 else None
|
|
432
|
+
except ValueError:
|
|
433
|
+
return None
|
|
434
|
+
if not isinstance(doc, dict):
|
|
435
|
+
return None
|
|
436
|
+
# attached pictures (cover art) are not the picture being joined, as V:0 skips them
|
|
437
|
+
every = doc.get("streams") or []
|
|
438
|
+
streams = [st for st in every if not (st.get("disposition") or {}).get("attached_pic")]
|
|
439
|
+
keep = [next((st for st in streams if st.get("codec_type") == kind), None) for kind in ("video", "audio")]
|
|
440
|
+
doc["streams"] = [st for st in keep if st]
|
|
441
|
+
# the concat demuxer maps every clip's packets by stream index, laid out as the first clip's
|
|
442
|
+
doc["layout"] = {"streams": len(every), "indices": [st.get("index") for st in doc["streams"]]}
|
|
443
|
+
return doc
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _video_packets(path: str, limit: "Optional[int]" = None) -> "List[str]":
|
|
447
|
+
"""The flags of the first video stream's packets (all of them, or the first `limit`); cover art
|
|
448
|
+
is not that stream."""
|
|
449
|
+
cmd = [require_tool("ffprobe"), "-v", "error", "-select_streams", "V:0", "-show_entries", "packet=flags", "-of", "csv=p=0"]
|
|
450
|
+
if limit:
|
|
451
|
+
cmd += ["-read_intervals", f"%+#{limit}"]
|
|
452
|
+
proc = run(cmd + [path], quiet=True, check=False)
|
|
453
|
+
return (proc.stdout or "").split() if proc.returncode == 0 else []
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _aac_priming_seconds(path: str, sample_rate: int) -> Optional[float]:
|
|
457
|
+
"""Measure the samples to skip when decoding the input's first AAC packet."""
|
|
458
|
+
cmd = [require_tool("ffprobe"), "-v", "error", "-select_streams", "a:0",
|
|
459
|
+
"-read_intervals", "%+#1", "-show_entries", "packet=pts:packet_side_data=skip_samples",
|
|
460
|
+
"-of", "json", path]
|
|
461
|
+
proc = run(cmd, quiet=True, check=False)
|
|
462
|
+
if proc.returncode != 0 or not sample_rate:
|
|
463
|
+
return None
|
|
464
|
+
try:
|
|
465
|
+
packet = json.loads(proc.stdout or "{}")["packets"][0]
|
|
466
|
+
return sum(int(side.get("skip_samples", 0)) for side in packet.get("side_data_list", [])) / sample_rate
|
|
467
|
+
except (ValueError, KeyError, IndexError, TypeError):
|
|
468
|
+
return None
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _decoded_audio_seconds(path: str) -> Optional[float]:
|
|
472
|
+
"""The length of the first sound stream as a decoder delivers it (priming already dropped),
|
|
473
|
+
by decoding it: packet spans miss the overhang a stream-copy join carries into the next clip.
|
|
474
|
+
One byte per 1/8000 s (8-bit mono at 8 kHz): only the length is wanted, so an hour of sound
|
|
475
|
+
is 29 MB in memory rather than 345 MB at 48 kHz 16-bit, and 0.125 ms is well under COPY_AV_GAP."""
|
|
476
|
+
cmd = ffmpeg_base() + ["-v", "error", "-i", path, "-map", "0:a:0", "-ac", "1", "-ar", "8000",
|
|
477
|
+
"-f", "u8", "-"]
|
|
478
|
+
proc = run_analysis(cmd, check=False, text=False)
|
|
479
|
+
return len(proc.stdout or b"") / 8000 if proc.returncode == 0 else None
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
SPAN_HEAD_PACKETS = 64 # enough to see the earliest presentation time past B-frame reordering
|
|
483
|
+
SPAN_TAIL_SECONDS = 10.0 # read from this far before the end, so a seek that lands early still reaches it
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _stream_span(path: str, kind: str, duration: float = 0.0, start: float = 0.0) -> "Optional[Tuple[float, float]]":
|
|
487
|
+
"""First packet's time and last packet's time plus its duration for the first `kind` stream
|
|
488
|
+
(V or a): measured, because Matroska/WebM state no stream length and MPEG-TS only an estimate.
|
|
489
|
+
None when the packets cannot be read or one has no time: a partial span would invent a gap."""
|
|
490
|
+
# JSON, not csv: older ffprobe builds (5.1) print side-data rows between the packet rows in csv.
|
|
491
|
+
# A long clip is read at its head and its tail only: every packet of a two-hour file is
|
|
492
|
+
# hundreds of thousands of entries for two numbers
|
|
493
|
+
cmd = [require_tool("ffprobe"), "-v", "error", "-select_streams", f"{kind}:0", "-show_entries",
|
|
494
|
+
"packet=pts_time,dts_time,duration_time", "-of", "json"]
|
|
495
|
+
if duration > 3 * SPAN_TAIL_SECONDS:
|
|
496
|
+
# read_intervals takes timestamps, so the tail starts from the file's own start time
|
|
497
|
+
# (an MPEG-TS clock can start hours in; an edit list can start it below zero)
|
|
498
|
+
cmd += ["-read_intervals", f"%+#{SPAN_HEAD_PACKETS},{start + duration - SPAN_TAIL_SECONDS:.3f}%"]
|
|
499
|
+
proc = run(cmd + [path], quiet=True, check=False)
|
|
500
|
+
try:
|
|
501
|
+
packets = json.loads(proc.stdout or "{}").get("packets") or [] if proc.returncode == 0 else []
|
|
502
|
+
except ValueError:
|
|
503
|
+
return None
|
|
504
|
+
times = []
|
|
505
|
+
for pkt in packets:
|
|
506
|
+
try:
|
|
507
|
+
# a packet ffprobe gives no pts (some muxers leave it on B-frames) still has its dts
|
|
508
|
+
t = float(pkt.get("pts_time", pkt.get("dts_time")))
|
|
509
|
+
except (TypeError, ValueError):
|
|
510
|
+
return None
|
|
511
|
+
try:
|
|
512
|
+
d = float(pkt.get("duration_time") or 0.0)
|
|
513
|
+
except (TypeError, ValueError):
|
|
514
|
+
d = 0.0
|
|
515
|
+
times.append((t, t + d))
|
|
516
|
+
if not times:
|
|
517
|
+
return None
|
|
518
|
+
first, last = min(t for t, _ in times), max(e for _, e in times)
|
|
519
|
+
if duration > 3 * SPAN_TAIL_SECONDS and (
|
|
520
|
+
len(packets) <= SPAN_HEAD_PACKETS or last < start + duration - SPAN_TAIL_SECONDS
|
|
521
|
+
):
|
|
522
|
+
# Some ffprobe builds exit 0 after the head read. A sparse head can reach the tail
|
|
523
|
+
# window on its own, so require more packets than the head interval can return.
|
|
524
|
+
return _stream_span(path, kind, 0.0, start)
|
|
525
|
+
return first, last
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def join_copy(args, metas: List[Dict[str, Any]]) -> int:
|
|
529
|
+
"""--copy: the concat demuxer with -c copy, after checking that the clips can be joined that
|
|
530
|
+
way, and measured afterwards (video packet count and length against the clips')."""
|
|
531
|
+
if args.transition != "none":
|
|
532
|
+
die("--copy joins without a transition: pass --transition none (a transition re-encodes the frames it blends)")
|
|
533
|
+
if args.width or args.height or args.fps:
|
|
534
|
+
die("--copy keeps every clip's own frame and rate: --width, --height and --fps need a re-encode, so drop --copy")
|
|
535
|
+
if args.sample_rate or args.channels:
|
|
536
|
+
die("--copy keeps every clip's own sound: --sample-rate and --channels need a re-encode, so drop --copy")
|
|
537
|
+
encoder = [f for f, on in (("--codec", STATE.codec), ("--hw", STATE.hw and STATE.hw_source == "flag"),
|
|
538
|
+
("--quality", getattr(args, "quality_given", False)))
|
|
539
|
+
if on]
|
|
540
|
+
if encoder:
|
|
541
|
+
die(f"--copy keeps every clip's own encoding: {', '.join(encoder)} choose(s) an encode, so drop --copy")
|
|
542
|
+
output = args.output or default_output(args.inputs[0], "joined", os.path.splitext(args.inputs[0])[1].lstrip(".") or "mp4")
|
|
543
|
+
guard_sidecar(output, *args.inputs)
|
|
544
|
+
refuse_list_as_output(args, output)
|
|
545
|
+
ext = os.path.splitext(output)[1].lower()
|
|
546
|
+
mov_output = ext in (".mp4", ".mov", ".m4v")
|
|
547
|
+
n = len(args.inputs)
|
|
548
|
+
pending = any(m.get("dry_run") for m in metas)
|
|
549
|
+
if pending:
|
|
550
|
+
STATE_NOTES.append("--copy: an input does not exist yet, so whether the clips match is checked when a real run has them")
|
|
551
|
+
else:
|
|
552
|
+
docs = [_copy_doc(p) for p in args.inputs]
|
|
553
|
+
unreadable = [p for p, d in zip(args.inputs, docs) if d is None]
|
|
554
|
+
if unreadable:
|
|
555
|
+
die(f"--copy: could not read the streams of {', '.join(unreadable)}")
|
|
556
|
+
moved = [{"index": i, "path": p, "differs": {"stream_layout": [docs[0]["layout"], d["layout"]]}}
|
|
557
|
+
for i, (p, d) in enumerate(zip(args.inputs, docs)) if i and d["layout"] != docs[0]["layout"]]
|
|
558
|
+
if moved:
|
|
559
|
+
refuse("input", "join_copy_mismatch",
|
|
560
|
+
f"--copy: {', '.join(m['path'] for m in moved)} lay(s) out their streams differently from "
|
|
561
|
+
f"{args.inputs[0]} (count or order, cover art included); the concat demuxer maps streams by position",
|
|
562
|
+
hint="drop --copy to re-encode them to one layout", clips=moved)
|
|
563
|
+
sigs = [stream_signature(d) for d in docs]
|
|
564
|
+
mismatched = [{"index": i, "path": p, "differs": {k: [a.get(k), b.get(k)] for a, b in zip(sigs[0], sig)
|
|
565
|
+
for k in a if k != "extradata_hash" and a.get(k) != b.get(k)}
|
|
566
|
+
if len(sig) == len(sigs[0]) else {"streams": [len(sigs[0]), len(sig)]}}
|
|
567
|
+
for i, (p, sig) in enumerate(zip(args.inputs, sigs)) if i and not signatures_match([sigs[0], sig], ext)]
|
|
568
|
+
if mismatched:
|
|
569
|
+
listing = "; ".join(f"#{m['index'] + 1} {m['path']}: " + (", ".join(f"{k} {v[1]} (not {v[0]})" for k, v in m["differs"].items())
|
|
570
|
+
or "codec configuration (extradata) differs")
|
|
571
|
+
for m in mismatched)
|
|
572
|
+
refuse("input", "join_copy_mismatch", f"--copy: {len(mismatched)} clip(s) do not match the first one: {listing}",
|
|
573
|
+
hint="drop --copy to re-encode them to one format", clips=mismatched)
|
|
574
|
+
hidden = [p for p in args.inputs if "D" in "".join(_video_packets(p, COPY_PREROLL_PACKETS))]
|
|
575
|
+
if hidden:
|
|
576
|
+
refuse("input", "join_copy_mismatch",
|
|
577
|
+
f"--copy: {', '.join(hidden)} hide(s) frames before their start (an edit list), which a copy join would show",
|
|
578
|
+
hint="drop --copy, or re-cut those clips with cut.py --accurate", clips=[{"path": p, "differs": {"edit_list": True}} for p in hidden])
|
|
579
|
+
gaps = []
|
|
580
|
+
for p, m in zip(args.inputs, metas):
|
|
581
|
+
# each stream's span from its packets: Matroska/WebM state no stream length and an
|
|
582
|
+
# MPEG-TS stream length is an estimate, so a stated duration missed or invented gaps
|
|
583
|
+
if not (m.get("video") and m.get("audio")):
|
|
584
|
+
continue
|
|
585
|
+
length, origin = float(m.get("duration") or 0.0), float(m.get("start_time") or 0.0)
|
|
586
|
+
v_span, a_span = _stream_span(p, "V", length, origin), _stream_span(p, "a", length, origin)
|
|
587
|
+
if v_span is None or a_span is None:
|
|
588
|
+
refuse("input", "join_copy_mismatch",
|
|
589
|
+
f"--copy: could not measure where picture and sound start and end in {p} (a packet without a "
|
|
590
|
+
"time), so a gap at the join could not be ruled out", hint="drop --copy to re-encode the join",
|
|
591
|
+
clips=[{"path": p, "differs": {"av_span": "unmeasured"}}])
|
|
592
|
+
(vb, ve), (ab, ae) = v_span, a_span
|
|
593
|
+
if abs(vb - ab) > COPY_AV_GAP or abs(ve - ae) > COPY_AV_GAP:
|
|
594
|
+
gaps.append({"path": p, "video": [round(vb, 3), None if ve is None else round(ve, 3)],
|
|
595
|
+
"audio": [round(ab, 3), None if ae is None else round(ae, 3)]})
|
|
596
|
+
if gaps:
|
|
597
|
+
def span(x):
|
|
598
|
+
return f"{x[0]:.3f}-" + ("?" if x[1] is None else f"{x[1]:.3f}") + "s"
|
|
599
|
+
listing = "; ".join(f"{g['path']} (video {span(g['video'])}, audio {span(g['audio'])})" for g in gaps)
|
|
600
|
+
refuse("input", "join_copy_mismatch",
|
|
601
|
+
f"--copy: picture and sound start or end more than {COPY_AV_GAP * 1000:.0f} ms apart in {listing}; a copy join "
|
|
602
|
+
"would leave that gap at the next clip", hint="drop --copy, which trims both streams to one length",
|
|
603
|
+
clips=[{"path": g["path"], "differs": {"video_span": g["video"], "audio_span": g["audio"]}} for g in gaps])
|
|
604
|
+
if (metas[0].get("audio") or {}).get("codec") == "aac" and n > 1:
|
|
605
|
+
# A stream-copy join plays each later clip's AAC priming (the samples its first packet
|
|
606
|
+
# says to skip) at its seam, and carries the sound an earlier clip decodes to beyond its
|
|
607
|
+
# picture into the next one, whatever the container. Both streams' spans in the joined
|
|
608
|
+
# file still match, so only this sum shows it: on eight 4 s clips (21.3 ms priming,
|
|
609
|
+
# 10.7 ms overhang each) it predicted 32 ms more delay at every join, and the measured
|
|
610
|
+
# delay of a beep against a flash was 32, 64, ... 224 ms on FFmpeg 6.1 in .mp4, .mov
|
|
611
|
+
# and .mkv alike (#610). Beyond COPY_AV_GAP at any clip, --copy is refused.
|
|
612
|
+
drift, at, rows = 0.0, [], []
|
|
613
|
+
for index, (path, meta) in enumerate(zip(args.inputs, metas)):
|
|
614
|
+
priming = 0.0 if index == 0 else _aac_priming_seconds(path, (meta.get("audio") or {}).get("sample_rate") or 0)
|
|
615
|
+
decoded = _decoded_audio_seconds(path)
|
|
616
|
+
v_span = _stream_span(path, "V", float(meta.get("duration") or 0.0), float(meta.get("start_time") or 0.0))
|
|
617
|
+
if priming is None or decoded is None or v_span is None or v_span[1] is None:
|
|
618
|
+
refuse("input", "join_copy_mismatch", f"--copy: could not measure the AAC priming or sound length of {path}, "
|
|
619
|
+
"so the delay a copy join adds at its seams is unknown", hint="drop --copy to re-encode the join",
|
|
620
|
+
clips=[{"index": index, "path": path, "differs": {"aac_drift_ms": None}}])
|
|
621
|
+
drift += priming
|
|
622
|
+
at.append(drift)
|
|
623
|
+
rows.append({"index": index, "path": path, "differs": {"aac_priming_ms": round(priming * 1000, 3),
|
|
624
|
+
"sound_delay_ms": round(drift * 1000, 3)}})
|
|
625
|
+
drift += decoded - (v_span[1] - v_span[0])
|
|
626
|
+
# either way: a clip whose sound ends before its picture pulls the next clips' sound ahead
|
|
627
|
+
worst = max(at, key=abs)
|
|
628
|
+
if abs(worst) > COPY_AV_GAP:
|
|
629
|
+
side = "behind" if worst > 0 else "ahead of"
|
|
630
|
+
refuse("input", "join_copy_mismatch",
|
|
631
|
+
f"--copy: a copy join would put the sound {abs(worst) * 1000:.0f} ms {side} the picture by clip "
|
|
632
|
+
f"{at.index(worst) + 1} (AAC priming played at each seam, plus the difference between each "
|
|
633
|
+
"clip's sound and its picture)",
|
|
634
|
+
hint="drop --copy, which decodes each clip and trims its sound to its picture",
|
|
635
|
+
aac_drift_ms=round(worst * 1000, 3), tolerance_ms=COPY_AV_GAP * 1000, clips=rows)
|
|
636
|
+
fps = (metas[0].get("video") or {}).get("fps") or 30.0
|
|
637
|
+
note_short_segments(args.inputs, metas, MIN_SEGMENT_FRAMES / fps, f"{MIN_SEGMENT_FRAMES} frames at {fps:g} fps")
|
|
638
|
+
place_silent([m.get("duration") or 0.0 for m in metas], 0.0)
|
|
639
|
+
with tempfile.TemporaryDirectory(prefix="ffskill_join_") as tmp:
|
|
640
|
+
listfile = os.path.join(tmp, "list.txt")
|
|
641
|
+
with open(listfile, "w", encoding="utf-8") as fh:
|
|
642
|
+
for p in args.inputs:
|
|
643
|
+
fh.write(concat_list_line(os.path.abspath(p)) + "\n")
|
|
644
|
+
joined = sibling_temp(output, "join") if not STATE.dry_run else output
|
|
645
|
+
cmd = ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile, "-map", "0:V:0", "-map", "0:a:0?", "-c", "copy"]
|
|
646
|
+
if mov_output:
|
|
647
|
+
cmd += ["-movflags", "+faststart"]
|
|
648
|
+
try:
|
|
649
|
+
run(cmd + [joined])
|
|
650
|
+
verification: List[Dict[str, Any]] = []
|
|
651
|
+
if not STATE.dry_run:
|
|
652
|
+
want = sum(len(_video_packets(p)) for p in args.inputs)
|
|
653
|
+
got = len(_video_packets(joined))
|
|
654
|
+
# nothing counted on either side is a failed read, not a match
|
|
655
|
+
verification.append({"step": "join", "property": "video_packets", "ok": got == want and want > 0,
|
|
656
|
+
"measured": got, "expected": want, "provenance": "input_premeasurement"})
|
|
657
|
+
r = probe(joined, role="output")
|
|
658
|
+
measured = (r.get("video") or {}).get("duration") or r.get("duration")
|
|
659
|
+
expected = round(sum(m.get("duration") or 0.0 for m in metas), 3)
|
|
660
|
+
tol = round(n * COPY_AV_GAP + 1.0 / fps, 3)
|
|
661
|
+
verification.append({"step": "join", "property": "video_duration",
|
|
662
|
+
"ok": measured is not None and abs(measured - expected) <= tol,
|
|
663
|
+
"measured": None if measured is None else round(measured, 3), "expected": expected,
|
|
664
|
+
"tolerance": tol, "provenance": "input_premeasurement"})
|
|
665
|
+
bad = [v for v in verification if not v["ok"]]
|
|
666
|
+
if bad:
|
|
667
|
+
die("--copy: the joined file does not hold the clips it was given: "
|
|
668
|
+
+ "; ".join(f"{v['property']} {v['measured']} (expected {v['expected']})" for v in bad),
|
|
669
|
+
kind="verification", hint="drop --copy to re-encode the join", verification=verification)
|
|
670
|
+
place_output(joined, output, move=True)
|
|
671
|
+
finally:
|
|
672
|
+
if joined != output and os.path.exists(joined):
|
|
673
|
+
os.remove(joined)
|
|
674
|
+
r = probe(output, role="output")
|
|
675
|
+
info(f"wrote {output} ({fmt_secs(r.get('duration'))}, {n} clips, stream copy)")
|
|
676
|
+
emit(output, mode="copy", **reported(), clips=n, transition="none", reencoded=False,
|
|
677
|
+
verification=verification, expect_streams={"video": 1, "audio": 1 if all(m.get("audio") for m in metas) else 0},
|
|
678
|
+
stream_reference=metas,
|
|
679
|
+
dropped_non_av_streams=any(m.get("subtitle_streams") or m.get("data_streams") for m in metas))
|
|
680
|
+
return 0
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def main() -> int:
|
|
684
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
685
|
+
ap.add_argument("inputs", nargs="*", help="two or more clips in order (or --list FILE)")
|
|
686
|
+
ap.add_argument("--list", metavar="FILE", help="read the clips from FILE, one per line in order (paths relative to FILE; "
|
|
687
|
+
"ffmpeg concat lines `file 'x.wav'` also accepted, other concat directives refused); an empty list is refused")
|
|
688
|
+
ap.add_argument("--on-missing", choices=["fail", "skip"], default="fail",
|
|
689
|
+
help="a missing, empty or unreadable input: fail (default; every problem named at once) or skip "
|
|
690
|
+
"(join the rest; each skipped input is reported under `skipped`)")
|
|
691
|
+
ap.add_argument("--on-silent", choices=["warn", "fail", "skip"], default="warn",
|
|
692
|
+
help="an input whose audio peak is at or below --silence-threshold: warn (default; join it, "
|
|
693
|
+
"name it under `silent`), fail (refuse with the other input problems) or skip (leave it out, "
|
|
694
|
+
"under `skipped`); a clip with no audio stream is never silent")
|
|
695
|
+
ap.add_argument("--allow-silent", metavar="N[,N...]",
|
|
696
|
+
help="input numbers (1-based) whose silence is intended, e.g. a planned pause: always joined, "
|
|
697
|
+
"listed under `silent` with intended: true, no warning, whatever --on-silent says")
|
|
698
|
+
ap.add_argument("--silence-threshold", type=float, default=SILENT_PEAK_DBFS, metavar="DB",
|
|
699
|
+
help="peak level in dBFS at or below which an input counts as silent (default -50)")
|
|
700
|
+
ap.add_argument("-o", "--output", help="output file (default: <first>_joined.mp4)")
|
|
701
|
+
ap.add_argument("--transition", choices=TRANSITIONS, default="fade", help="transition between clips (default fade)")
|
|
702
|
+
ap.add_argument("--duration", type=float, default=0.5, help="transition length in seconds (default 0.5)")
|
|
703
|
+
ap.add_argument("--width", type=int, help="output width (default: first clip); a size or resolution WxH is --width W --height H")
|
|
704
|
+
ap.add_argument("--height", type=int, help="output height (default: first clip)")
|
|
705
|
+
ap.add_argument("--fps", type=float, help="output frame rate (default: first clip)")
|
|
706
|
+
ap.add_argument("--fit", choices=["pad", "crop"], default="pad", help="how clips of another aspect reach the frame (default pad)")
|
|
707
|
+
ap.add_argument("--copy", action="store_true",
|
|
708
|
+
help="join by stream copy, no re-encode (needs --transition none): every clip must carry the same "
|
|
709
|
+
"video and audio parameters (codec, size, rate, pixel format, sample rate, channels); a clip "
|
|
710
|
+
"that does not is refused, by name, with what differs")
|
|
711
|
+
ap.add_argument("--audio-lead", type=float, metavar="S",
|
|
712
|
+
help="J-cut: at each boundary the next clip's sound starts S seconds (0.001..600, whole frames) before its picture; "
|
|
713
|
+
"sync is kept, so each boundary costs S seconds (needs --transition none; not with --copy or --audio-lag)")
|
|
714
|
+
ap.add_argument("--audio-lag", type=float, metavar="S",
|
|
715
|
+
help="L-cut: at each boundary the previous clip's sound runs S seconds (0.001..600, whole frames) past the picture "
|
|
716
|
+
"change; sync is kept, so each boundary costs S seconds (needs --transition none; not with --copy or --audio-lead)")
|
|
717
|
+
ap.add_argument("--pad-color", default="black", help="pad colour when a clip's aspect differs, e.g. black, white, 0x101010 (default black)")
|
|
718
|
+
ap.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
|
|
719
|
+
ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")
|
|
720
|
+
aud = ap.add_argument_group("audio-only inputs")
|
|
721
|
+
aud.add_argument("--sample-rate", type=int, help="output sample rate in Hz (default: first clip's)")
|
|
722
|
+
aud.add_argument("--channels", type=int, choices=[1, 2, 6, 8], help="output channel count (default: the widest clip)")
|
|
723
|
+
add_common(ap)
|
|
724
|
+
args = ap.parse_args()
|
|
725
|
+
# given at all, not only different from the default: --quality 18 asks for an encode as much as 23 does
|
|
726
|
+
args.quality_given = any(a == "--quality" or a.startswith("--quality=") for a in sys.argv[1:])
|
|
727
|
+
apply_common(args)
|
|
728
|
+
if args.fps is not None and args.fps <= 0:
|
|
729
|
+
die(f"--fps must be positive, got {args.fps:g}")
|
|
730
|
+
# nan and inf are refused by the parser (finite_float) and a negative length by apply_common: it
|
|
731
|
+
# was taken as the one-frame minimum and the join succeeded with a transition nobody asked for
|
|
732
|
+
|
|
733
|
+
cut_flag = "--audio-lead" if args.audio_lead is not None else "--audio-lag" if args.audio_lag is not None else None
|
|
734
|
+
hint = "a J-cut or an L-cut is a plain cut: --transition none, no --copy, one of the two flags"
|
|
735
|
+
if args.audio_lead is not None and args.audio_lag is not None:
|
|
736
|
+
refuse("input", "audio_cut_both_flags", "--audio-lead and --audio-lag are two different cuts: give one", hint=hint)
|
|
737
|
+
if cut_flag and args.transition != "none":
|
|
738
|
+
refuse("input", "audio_cut_transition", f"{cut_flag} needs --transition none: a transition already overlaps the picture of the two clips", hint=hint)
|
|
739
|
+
if cut_flag and args.copy:
|
|
740
|
+
refuse("input", "audio_cut_copy", f"{cut_flag} cuts picture and sound at different times, which a stream copy cannot do: drop --copy", hint=hint)
|
|
741
|
+
cut_s = args.audio_lead if args.audio_lead is not None else args.audio_lag
|
|
742
|
+
|
|
743
|
+
if args.list:
|
|
744
|
+
if args.inputs:
|
|
745
|
+
die("give the clips either as arguments or with --list, not both")
|
|
746
|
+
args.inputs = read_list(args.list)
|
|
747
|
+
if not args.inputs:
|
|
748
|
+
die("give at least two clips (or --list FILE)")
|
|
749
|
+
if args.silence_threshold >= 0:
|
|
750
|
+
die(f"--silence-threshold is a peak level in dBFS and must be negative, got {args.silence_threshold:g}")
|
|
751
|
+
skipped: List[Dict[str, Any]] = []
|
|
752
|
+
orig_inputs = list(args.inputs)
|
|
753
|
+
audible: List[int] = []
|
|
754
|
+
problems, pending = preflight(args.inputs, audible)
|
|
755
|
+
allowed = parse_allow_silent(args.allow_silent, len(args.inputs))
|
|
756
|
+
found = find_silent(args.inputs, audible, args.silence_threshold)
|
|
757
|
+
intended = [dict(s, intended=True) for s in found if s["index"] in allowed]
|
|
758
|
+
silent = [s for s in found if s["index"] not in allowed]
|
|
759
|
+
silent_problems = [{"index": s["index"], "path": s["path"], "reason": f"silent (peak {s['peak_db']:.1f} dBFS)"}
|
|
760
|
+
for s in silent]
|
|
761
|
+
refused = sorted((problems if args.on_missing == "fail" else [])
|
|
762
|
+
+ (silent_problems if args.on_silent == "fail" else []), key=lambda p: p["index"])
|
|
763
|
+
if refused:
|
|
764
|
+
listing = "; ".join(f"#{p['index'] + 1} {p['path']}: {p['reason']}" for p in refused)
|
|
765
|
+
ways = []
|
|
766
|
+
if args.on_missing == "fail" and problems:
|
|
767
|
+
ways.append("--on-missing skip")
|
|
768
|
+
if args.on_silent == "fail" and silent:
|
|
769
|
+
ways.append("--on-silent skip (or warn)")
|
|
770
|
+
die(f"{len(refused)} of {len(args.inputs)} inputs cannot be joined: {listing}",
|
|
771
|
+
hint="fix or regenerate them, or pass " + " and ".join(ways) + " to join the rest", problems=refused)
|
|
772
|
+
dropped = sorted((problems if args.on_missing == "skip" else [])
|
|
773
|
+
+ (silent_problems if args.on_silent == "skip" else []), key=lambda p: p["index"])
|
|
774
|
+
if dropped:
|
|
775
|
+
bad = {p["index"] for p in dropped}
|
|
776
|
+
skipped = dropped
|
|
777
|
+
args.inputs = [p for i, p in enumerate(args.inputs) if i not in bad]
|
|
778
|
+
for p in dropped:
|
|
779
|
+
info(f"skipping #{p['index'] + 1} {p['path']}: {p['reason']}")
|
|
780
|
+
STATE_SILENT[:] = sorted(intended + (silent if args.on_silent == "warn" else []), key=lambda s: s["index"])
|
|
781
|
+
if silent and args.on_silent == "warn":
|
|
782
|
+
listing = ", ".join(f"#{s['index'] + 1} {s['path']} (peak {s['peak_db']:.1f} dBFS)" for s in silent)
|
|
783
|
+
warn(f"{len(silent)} input(s) silent at or below {args.silence_threshold:g} dBFS, joined anyway: {listing}",
|
|
784
|
+
"silent_inputs", count=len(silent))
|
|
785
|
+
STATE_NOTES.append(f"{len(silent)} input(s) have no audible sound (peak at or below {args.silence_threshold:g} dBFS) "
|
|
786
|
+
f"and were joined anyway: {listing}; pass --on-silent fail or skip to refuse or drop them")
|
|
787
|
+
STATE_SKIPPED[:] = skipped
|
|
788
|
+
STATE_KEPT[:] = [i for i in range(len(args.inputs) + len(skipped)) if i not in {p["index"] for p in skipped}]
|
|
789
|
+
dupes = [dd for dd in find_duplicates(orig_inputs)
|
|
790
|
+
if len([i for i in dd["indices"] if i in STATE_KEPT]) > 1]
|
|
791
|
+
for dd in dupes:
|
|
792
|
+
dd["indices"] = [i for i in dd["indices"] if i in STATE_KEPT]
|
|
793
|
+
STATE_DUPES[:] = dupes
|
|
794
|
+
if dupes:
|
|
795
|
+
listing = "; ".join(f"{dd['path']} at #" + ", #".join(str(i + 1) for i in dd["indices"]) for dd in dupes)
|
|
796
|
+
warn(f"input(s) listed more than once: {listing}", "duplicate_inputs", count=len(dupes))
|
|
797
|
+
STATE_NOTES.append(f"{len(dupes)} input(s) are listed more than once and joined each time: {listing}; "
|
|
798
|
+
"fine if the repeat is intended")
|
|
799
|
+
STATE_PENDING[:] = pending
|
|
800
|
+
if pending:
|
|
801
|
+
# a dry run cannot know whether the file will be there: it plans on it, and says what a
|
|
802
|
+
# real run does if it still is not (the same --on-missing rule as any missing input --
|
|
803
|
+
# including the refusal when skipping would leave fewer than two inputs)
|
|
804
|
+
left = len(args.inputs) - len(pending)
|
|
805
|
+
if args.on_missing == "fail":
|
|
806
|
+
then = "refuses the join if one is still missing"
|
|
807
|
+
elif left >= 2:
|
|
808
|
+
then = "skips one that is still missing"
|
|
809
|
+
else:
|
|
810
|
+
then = (f"skips one that is still missing and refuses the join if that leaves fewer than two inputs "
|
|
811
|
+
f"(only {left} exist{'s' if left == 1 else ''} now)")
|
|
812
|
+
STATE_NOTES.append(f"{len(pending)} of {len(args.inputs) + len(skipped)} inputs do not exist yet and were planned on "
|
|
813
|
+
"as an earlier step's output: " + ", ".join(f"#{p['index'] + 1} {p['path']}" for p in pending)
|
|
814
|
+
+ f"; a real run {then}")
|
|
815
|
+
if len(args.inputs) < 2:
|
|
816
|
+
die("give at least two clips" if not skipped else
|
|
817
|
+
f"only {len(args.inputs)} usable input(s) left after skipping {len(skipped)}; nothing to join",
|
|
818
|
+
skipped=skipped)
|
|
819
|
+
validate_color(args.pad_color, "--pad-color")
|
|
820
|
+
metas = [probe(p) for p in args.inputs]
|
|
821
|
+
for p, m in zip(args.inputs, metas):
|
|
822
|
+
input_length(m, p) # every clip is placed by its length: one that states none is refused, not 0 s (#491)
|
|
823
|
+
# a still joined as one frame (--transition none, verified), was refused as "too short" for
|
|
824
|
+
# a transition, or as a stream mismatch by --copy: it has no length to place (#531)
|
|
825
|
+
refuse_still(m, p, "a join places each clip by its length, and a still has none")
|
|
826
|
+
# A pending input's probe is the dry-run stub, whose (0x0) video stream says nothing about the
|
|
827
|
+
# file an earlier step will write. Its extension stands in: a step names its output for what
|
|
828
|
+
# it holds, so an audio extension (.wav, .m4a, .aiff, ... -- every audio file this skill
|
|
829
|
+
# reads, not only the ones it writes) is taken for a file without a picture and any other for
|
|
830
|
+
# one with a picture. Measured and pending inputs then meet the same rules a real run
|
|
831
|
+
# applies: all without a picture is an audio join, a mix is refused.
|
|
832
|
+
pictured = [(os.path.splitext(p)[1].lower() not in AUDIO_MEDIA_EXT) if m.get("dry_run") else bool(m.get("video"))
|
|
833
|
+
for p, m in zip(args.inputs, metas)]
|
|
834
|
+
if all(m.get("dry_run") for m in metas):
|
|
835
|
+
STATE_NOTES.append(f"no input exists yet: {'a video' if any(pictured) else 'an audio'} join was planned from the file extensions")
|
|
836
|
+
if not any(pictured):
|
|
837
|
+
for p, m in zip(args.inputs, metas):
|
|
838
|
+
if not m.get("audio"):
|
|
839
|
+
die(f"{p} has neither a video nor an audio stream")
|
|
840
|
+
if cut_flag:
|
|
841
|
+
die(f"{cut_flag} moves the sound against a picture, and these clips have none")
|
|
842
|
+
if args.copy:
|
|
843
|
+
die("--copy joins video clips; an audio-only join resamples every clip to one format, which a copy cannot do")
|
|
844
|
+
return join_audio(args, metas)
|
|
845
|
+
for p, m, pic in zip(args.inputs, metas, pictured):
|
|
846
|
+
if not pic:
|
|
847
|
+
# name an input measured to have a picture first; a pending one only as expected to
|
|
848
|
+
measured = [q for q, mm in zip(args.inputs, metas) if mm.get("video") and not mm.get("dry_run")]
|
|
849
|
+
planned = [q for q, mm, pc in zip(args.inputs, metas, pictured) if pc and mm.get("dry_run")]
|
|
850
|
+
other = (f"{measured[0]} has one" if measured else
|
|
851
|
+
f"{planned[0]}, which does not exist yet, is expected to have one (its extension is not an audio one)" if planned else "")
|
|
852
|
+
die((f"{p} does not exist yet, and its audio extension says it will have no video stream" if m.get("dry_run")
|
|
853
|
+
else f"{p} has no video stream")
|
|
854
|
+
+ (f" while {other}; join audio with audio or give every clip a picture" if other else ""))
|
|
855
|
+
if args.copy:
|
|
856
|
+
return join_copy(args, metas)
|
|
857
|
+
first = metas[0]["video"]
|
|
858
|
+
# the first clip's displayed frame: rotation applied, non-square pixels squared (#411)
|
|
859
|
+
fw, fh = display_size(first)
|
|
860
|
+
if args.width and args.height:
|
|
861
|
+
w, h = args.width, args.height
|
|
862
|
+
elif args.width:
|
|
863
|
+
w = args.width
|
|
864
|
+
h = int(round(args.width * fh / fw)) if fw else args.width
|
|
865
|
+
elif args.height:
|
|
866
|
+
h = args.height
|
|
867
|
+
w = int(round(args.height * fw / fh)) if fh else args.height
|
|
868
|
+
else:
|
|
869
|
+
w, h = fw, fh
|
|
870
|
+
fps = args.fps or first.get("fps") or 30.0
|
|
871
|
+
fps = round(fps) if abs(fps - round(fps)) < 0.02 else fps
|
|
872
|
+
# the exact rate every length below is counted in (30000/1001, not 29.97)
|
|
873
|
+
rate_q = output_rate(fps, first, bool(args.fps))
|
|
874
|
+
fps = float(rate_q)
|
|
875
|
+
w, h = w - (w % 2), h - (h % 2)
|
|
876
|
+
note_short_segments(args.inputs, metas, MIN_SEGMENT_FRAMES / fps, f"{MIN_SEGMENT_FRAMES} frames at {fps:g} fps")
|
|
877
|
+
durs = [m.get("duration") or 0.0 for m in metas]
|
|
878
|
+
d = args.duration if args.transition != "none" else 0.0
|
|
879
|
+
# every clip gets one length for both streams, so whatever places the next clip -- xfade's
|
|
880
|
+
# offsets, or the concat filter, which starts it after the LONGER stream of this one -- places
|
|
881
|
+
# its picture and its sound together. The plain cut used to take the raw streams, and a sound
|
|
882
|
+
# past the picture (a music bed padded to the container, even a 20 ms AAC tail) left a hole in
|
|
883
|
+
# the video there.
|
|
884
|
+
# Each length is a whole number of frames of the output rate, and each sound length the
|
|
885
|
+
# samples those frames last (#455): a length in milliseconds rounded 5 frames at 30 fps
|
|
886
|
+
# (0.166667 s) up to 0.167 s, the concat filter started the next clip after it, and 60 such
|
|
887
|
+
# clips left one-frame holes from about 8 s on. Sample counts come from the running frame
|
|
888
|
+
# total, so the sound never drifts from the picture by more than one sample.
|
|
889
|
+
lmetas = [with_whole_picture(m, rate_q) for m in metas]
|
|
890
|
+
frames = [clip_frames(m, clip_length(m, fps), rate_q) for m in lmetas]
|
|
891
|
+
# the transition is a whole number of frames too, so xfade's offsets (and acrossfade's
|
|
892
|
+
# overlap) land on frames of the output rate (#468). A transition is at least one frame:
|
|
893
|
+
# --duration 0 used to build acrossfade=ns=0, which FFmpeg refuses
|
|
894
|
+
tframes = max(1, round(d * fps)) if args.transition != "none" else 0
|
|
895
|
+
d = tframes / fps
|
|
896
|
+
lens = [f / fps for f in frames]
|
|
897
|
+
# the J-cut or L-cut offset: whole frames of the output rate, and a clip it takes from must be longer
|
|
898
|
+
cut_f = round(cut_s * fps) if cut_s else 0
|
|
899
|
+
if cut_s and (cut_f < 1 or any(0 < nf <= cut_f for nf in frames)):
|
|
900
|
+
refuse("input", "audio_cut_too_long", f"{cut_flag} {cut_s:g} is not between one frame ({1 / fps:.3f} s) and the length "
|
|
901
|
+
f"of the shortest clip ({min(frames) / fps:.3f} s): it takes that much of a clip", hint="give a shorter value", frames=frames)
|
|
902
|
+
place_silent(lens, d)
|
|
903
|
+
for p, nf in zip(args.inputs, frames):
|
|
904
|
+
if d and nf <= tframes * 2 and not STATE.dry_run:
|
|
905
|
+
die(f"{p} is only {nf / fps:.2f}s, too short for a {d:.2f}s transition; shorten --duration")
|
|
906
|
+
# every sample boundary is a frame position of the OUTPUT rounded once: clip i spans output
|
|
907
|
+
# frames [start_i, start_i + frames_i) and overlaps the clip before it over [start_i,
|
|
908
|
+
# start_i + tframes), so its samples and each overlap's are differences of rounded
|
|
909
|
+
# cumulative positions and their sum telescopes to the output's own length. Rounding each
|
|
910
|
+
# overlap on its own (14414.4 samples -> 14414 at 30000/1001 and 9 frames) left the sound
|
|
911
|
+
# 0.4 samples longer per transition.
|
|
912
|
+
def at(frame: int) -> int:
|
|
913
|
+
return round(frame * JOIN_AUDIO_RATE / rate_q)
|
|
914
|
+
starts, start = [], 0
|
|
915
|
+
for i, nf in enumerate(frames):
|
|
916
|
+
starts.append(start)
|
|
917
|
+
start += nf - tframes
|
|
918
|
+
samples = [at(s0 + nf) - at(s0) for s0, nf in zip(starts, frames)]
|
|
919
|
+
overlaps = [at(s0 + tframes) - at(s0) for s0 in starts]
|
|
920
|
+
|
|
921
|
+
cmd = ffmpeg_base()
|
|
922
|
+
extra_inputs: List[str] = []
|
|
923
|
+
parts: List[str] = []
|
|
924
|
+
n = len(args.inputs)
|
|
925
|
+
for i, (p, m) in enumerate(zip(args.inputs, metas)):
|
|
926
|
+
cmd += ["-i", p]
|
|
927
|
+
# silent audio for clips without an audio track. `idx` is this ffmpeg input's position, i.e. n +
|
|
928
|
+
# how many synthetic inputs were already added -- not len(extra_inputs), which counts the six
|
|
929
|
+
# argv tokens ("-f", "lavfi", "-t", duration, "-i", "anullsrc=...") each synthetic input adds, not
|
|
930
|
+
# the input itself. With one no-audio clip both counts coincide (n + 0); from the second no-audio
|
|
931
|
+
# clip onward they diverge, and the previous `n + len(extra_inputs)` named a nonexistent, far-out-of-
|
|
932
|
+
# range ffmpeg input index -- found via a real multi-camera join where every clip lacked audio.
|
|
933
|
+
audio_src: List[str] = []
|
|
934
|
+
added = 0
|
|
935
|
+
for i, m in enumerate(metas):
|
|
936
|
+
if m.get("audio"):
|
|
937
|
+
audio_src.append(f"{i}:a:0")
|
|
938
|
+
else:
|
|
939
|
+
idx = n + added
|
|
940
|
+
extra_inputs += ["-f", "lavfi", "-t", f"{durs[i]:.3f}", "-i", "anullsrc=r=48000:cl=stereo"]
|
|
941
|
+
audio_src.append(f"{idx}:a:0")
|
|
942
|
+
added += 1
|
|
943
|
+
cmd += extra_inputs
|
|
944
|
+
|
|
945
|
+
# Any HDR input makes the join HDR (10-bit, HEVC via video_args on that clip's tags): an SDR
|
|
946
|
+
# first clip used to drag an HDR second clip down to 8-bit without a tone map.
|
|
947
|
+
hdr_meta = next((m for m in metas if (m.get("video") or {}).get("bt2020_or_hdr")), None)
|
|
948
|
+
pixfmt = "yuv420p10le" if hdr_meta else "yuv420p"
|
|
949
|
+
line = hdr_meta or metas[0]
|
|
950
|
+
chroma_pad = args.fit != "crop" and draws_chroma([args.pad_color], line)
|
|
951
|
+
convert = mix_color_chains(metas, line, draws_colour=chroma_pad)
|
|
952
|
+
|
|
953
|
+
for p, m in zip(args.inputs, metas):
|
|
954
|
+
if square_pixels(m.get("video")):
|
|
955
|
+
note(square_pixels_note(m["video"], p))
|
|
956
|
+
|
|
957
|
+
def geo(i: int) -> str:
|
|
958
|
+
# every clip is squared at its display aspect before it is fitted (#411)
|
|
959
|
+
sq = (square_pixels(metas[i].get("video")) + ",") if square_pixels(metas[i].get("video")) else ""
|
|
960
|
+
if args.fit == "crop":
|
|
961
|
+
warn_mostly_cropped(metas[i].get("video"), w, h)
|
|
962
|
+
return f"{sq}scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}"
|
|
963
|
+
pad = f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color="
|
|
964
|
+
return (f"{sq}scale={w}:{h}:force_original_aspect_ratio=decrease,"
|
|
965
|
+
+ drawn_chain(pad + args.pad_color, as_limited(metas[i]), [args.pad_color], pad + "black", line_meta=line,
|
|
966
|
+
tag=f"pad{i}", labelled=True))
|
|
967
|
+
# the audio-only join keeps the widest layout; the video join used to force stereo and
|
|
968
|
+
# silently dropped the centre/LFE of 5.1 material. A pending input's stub has no measured
|
|
969
|
+
# layout: plan from the inputs that exist, as join_audio() does.
|
|
970
|
+
chans = [(m.get("audio") or {}).get("channels") or 2 for m in ([m for m in metas if not m.get("dry_run")] or metas)]
|
|
971
|
+
channels = args.channels or max(chans)
|
|
972
|
+
layout = LAYOUTS.get(channels)
|
|
973
|
+
if layout is None:
|
|
974
|
+
die(f"{channels}-channel output has no standard layout here (1, 2, 6 or 8); pass --channels")
|
|
975
|
+
if len(set(chans)) > 1:
|
|
976
|
+
info(f"channel counts differ ({', '.join(str(c) for c in chans)}); every clip becomes {layout}")
|
|
977
|
+
for i in range(n):
|
|
978
|
+
# the fps filter's time base is one frame (1/rate), so every timestamp downstream is a
|
|
979
|
+
# frame number and an offset in seconds is rounded to a whole frame, never a microsecond
|
|
980
|
+
# off it on any FFmpeg (AVTB left xfade to compare microseconds)
|
|
981
|
+
parts.append(f"[{i}:v]{convert[i]}{geo(i)},setsar=1,setpts=PTS-STARTPTS,fps={rate_q.numerator}/{rate_q.denominator},format={pixfmt}[v{i}]")
|
|
982
|
+
# the sound is shifted by the picture's start, not to its own (#409): #338 started each
|
|
983
|
+
# clip's picture at 0, and a per-stream PTS-STARTPTS then moved a sound that starts 0.3 s
|
|
984
|
+
# after its picture 0.3 s early. Sound before the first frame is dropped and a late sound
|
|
985
|
+
# is padded, as cut.py's re-cut does; a generated silent track starts at 0 already.
|
|
986
|
+
shift = (av_trim(stream_starts(metas[i])[0], None)[1] + ",") if metas[i].get("audio") else ""
|
|
987
|
+
parts.append(f"[{audio_src[i]}]{shift}aformat=sample_rates=48000:channel_layouts={layout},asetpts=PTS-STARTPTS[a{i}]")
|
|
988
|
+
|
|
989
|
+
# pad the shorter stream to the clip's length: the audio with silence, the picture by holding
|
|
990
|
+
# its last frame, then cut both there -- each clip boundary is then the same for both chains
|
|
991
|
+
# -- by frame and by sample, never by rounded seconds (#455)
|
|
992
|
+
for i in range(n):
|
|
993
|
+
vlen = (lmetas[i].get("video") or {}).get("duration") or lens[i]
|
|
994
|
+
have = round(vlen * fps)
|
|
995
|
+
# one frame more than the gap is held, and the trim cuts at the clip's last frame
|
|
996
|
+
hold = f"tpad=stop_mode=clone:stop={frames[i] - have + 1}," if frames[i] > have else ""
|
|
997
|
+
# J-cut: picture from frame cut_f of every clip but the first, sound without the last cut_f of
|
|
998
|
+
# every clip but the last; L-cut: the other way round (sync is kept, so both lose the same)
|
|
999
|
+
lead, last = args.audio_lead is not None and cut_f, i < n - 1
|
|
1000
|
+
lag = args.audio_lag is not None and cut_f
|
|
1001
|
+
vs, ve = (cut_f if lead and i else 0), frames[i] - (cut_f if lag and last else 0)
|
|
1002
|
+
a0, a1 = (at(cut_f) if lag and i else 0), samples[i] - (at(cut_f) if lead and last else 0)
|
|
1003
|
+
parts.append(f"[v{i}]{hold}trim={f'start_frame={vs}:' if vs else ''}end_frame={ve}{',setpts=PTS-STARTPTS' if vs else ''}[vp{i}]")
|
|
1004
|
+
parts.append(f"[a{i}]apad=whole_len={samples[i]},atrim={f'start_sample={a0}:' if a0 else ''}end_sample={a1}"
|
|
1005
|
+
f"{',asetpts=PTS-STARTPTS' if a0 else ''}[ap{i}]")
|
|
1006
|
+
if cut_f: # one concat each, as the two streams are cut at different frames
|
|
1007
|
+
parts.append("".join(f"[vp{i}]" for i in range(n)) + f"concat=n={n}:v=1:a=0[vout]")
|
|
1008
|
+
parts.append("".join(f"[ap{i}]" for i in range(n)) + f"concat=n={n}:v=0:a=1[aout]")
|
|
1009
|
+
elif args.transition == "none":
|
|
1010
|
+
chain = "".join(f"[vp{i}][ap{i}]" for i in range(n))
|
|
1011
|
+
parts.append(f"{chain}concat=n={n}:v=1:a=1[vout][aout]")
|
|
1012
|
+
else:
|
|
1013
|
+
vprev, aprev = "vp0", "ap0"
|
|
1014
|
+
start = 0
|
|
1015
|
+
for i in range(1, n):
|
|
1016
|
+
# clip i starts on frame `start` of the output; xfade starts on the first frame at or
|
|
1017
|
+
# after its offset, so the offset is that frame's time rounded down (#468)
|
|
1018
|
+
start += frames[i - 1] - tframes
|
|
1019
|
+
vout = f"vx{i}" if i < n - 1 else "vout"
|
|
1020
|
+
aout = f"ax{i}" if i < n - 1 else "aout"
|
|
1021
|
+
parts.append(f"[{vprev}][vp{i}]xfade=transition={args.transition}:duration={frame_time(tframes, rate_q)}"
|
|
1022
|
+
f":offset={frame_time(start, rate_q)}[{vout}]")
|
|
1023
|
+
parts.append(f"[{aprev}][ap{i}]acrossfade=ns={overlaps[i]}:c1=tri:c2=tri[{aout}]")
|
|
1024
|
+
vprev, aprev = vout, aout
|
|
1025
|
+
|
|
1026
|
+
# A pending input's stub is unmeasured (0x0, 0 fps, 0 s -- #77 keeps it honest rather than
|
|
1027
|
+
# plausible), and the planned command is built on it: say which numbers are placeholders.
|
|
1028
|
+
if metas[0].get("dry_run") and not (args.width and args.height and args.fps):
|
|
1029
|
+
STATE_NOTES.append(f"the first input is pending, so the planned frame and rate ({w}x{h} @ {fps:g}fps) are "
|
|
1030
|
+
"placeholders: a real run takes them from that file")
|
|
1031
|
+
if d and any(m.get("dry_run") for m in metas[:-1]):
|
|
1032
|
+
STATE_NOTES.append("the planned xfade offsets count each pending input as 0 s long: a real run offsets "
|
|
1033
|
+
"by its measured length")
|
|
1034
|
+
elif not d and any(m.get("dry_run") for m in metas):
|
|
1035
|
+
# the plain cut trims/holds every clip to clip_length too (2.4.1), so a pending clip's
|
|
1036
|
+
# planned trim=end_frame=0 is the stub's placeholder, not the cut
|
|
1037
|
+
STATE_NOTES.append("the planned trim lengths count each pending input as 0 s long: a real run trims "
|
|
1038
|
+
"or holds it to its measured length")
|
|
1039
|
+
output = args.output or default_output(args.inputs[0], "joined", "mp4")
|
|
1040
|
+
refuse_list_as_output(args, output)
|
|
1041
|
+
cmd += ["-filter_complex", ";".join(parts), "-map", "[vout]", "-map", "[aout]"]
|
|
1042
|
+
# the fps filter already made the picture constant-rate, and the per-clip trims (then xfade or
|
|
1043
|
+
# concat) place every frame: FFmpeg 5.1's default cfr output mode still duplicated the last one
|
|
1044
|
+
# to meet the AAC tail (a 51-frame dissolve came out 52), which newer builds no longer do -- pass
|
|
1045
|
+
# the frames through as built, for a plain cut as much as for a transition
|
|
1046
|
+
cmd += ["-fps_mode", "passthrough"]
|
|
1047
|
+
cmd += video_args(hdr_meta or metas[0], args.crf, args.preset, convert_matrix=False) + aac_args() + [output]
|
|
1048
|
+
run(cmd)
|
|
1049
|
+
expected = unpending_length(lens, d)
|
|
1050
|
+
if expected is not None and cut_f:
|
|
1051
|
+
expected = round(expected - cut_f * (n - 1) / fps, 3)
|
|
1052
|
+
r = probe(output, role="output")
|
|
1053
|
+
# the picture is what the offsets place: measure the video stream, not the container (whose
|
|
1054
|
+
# length also counts the AAC tail), against the length the clips add up to
|
|
1055
|
+
measured = (r.get("video") or {}).get("duration") or r.get("duration")
|
|
1056
|
+
verification = []
|
|
1057
|
+
if expected is not None and measured is not None and not STATE.dry_run:
|
|
1058
|
+
tol = max(DURATION_TOLERANCE_FRAMES / fps, DURATION_TOLERANCE_MIN)
|
|
1059
|
+
verification.append({"step": "duration", "property": "video_duration", "ok": abs(measured - expected) <= tol,
|
|
1060
|
+
"measured": round(measured, 3), "expected": expected,
|
|
1061
|
+
"delta": round(measured - expected, 3), "tolerance": round(tol, 3),
|
|
1062
|
+
"provenance": "input_premeasurement", "inputs_total": round(sum(lens), 3)})
|
|
1063
|
+
# a clip with no audio stream is joined over generated silence: the join is right to do that, but
|
|
1064
|
+
# the report must say which clips' sound is not theirs (the paper's join finding: absence was
|
|
1065
|
+
# filled and nothing in the result showed it)
|
|
1066
|
+
substituted = [p for p, m in zip(args.inputs, metas) if not m.get("audio")]
|
|
1067
|
+
if substituted:
|
|
1068
|
+
STATE_NOTES.append(f"{len(substituted)} clip(s) had no audio stream; their span of the join is generated "
|
|
1069
|
+
"silence: " + ", ".join(os.path.basename(p) for p in substituted))
|
|
1070
|
+
info(f"wrote {output} ({fmt_secs(measured)}, {expected_text(expected)}, {w}x{h} @ {fps:g}fps, {n} clips, {args.transition})")
|
|
1071
|
+
overlap = {} if cut_f else overlap_report(lens, expected)
|
|
1072
|
+
emit(output, mode="video", **overlap, **reported(), clips=n, transition=args.transition, expected_duration=expected,
|
|
1073
|
+
frame_rate=f"{rate_q.numerator}/{rate_q.denominator}", clip_frames=frames, transition_frames=tframes,
|
|
1074
|
+
**({"audio_lead_seconds": cut_f / fps} if cut_f and args.audio_lead is not None else {}),
|
|
1075
|
+
**({"audio_lag_seconds": cut_f / fps} if cut_f and args.audio_lag is not None else {}),
|
|
1076
|
+
verification=verification, expect_streams={"video": 1, "audio": 1}, stream_reference=metas,
|
|
1077
|
+
audio_substituted=substituted,
|
|
1078
|
+
dropped_non_av_streams=any(m.get("subtitle_streams") or m.get("data_streams") for m in metas))
|
|
1079
|
+
return 0
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
if __name__ == "__main__":
|
|
1083
|
+
sys.exit(main())
|