@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,500 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Detect the time offset between two recordings by audio cross-correlation
|
|
3
|
+
and (optionally) write a synced output, with optional clock-drift correction.
|
|
4
|
+
|
|
5
|
+
Pure standard library: both tracks are decoded by ffmpeg to mono 8 kHz PCM,
|
|
6
|
+
reduced to a loudness envelope, cross-correlated with an FFT implemented in
|
|
7
|
+
Python (coarse, 20 ms), then refined by direct correlation at 1 ms.
|
|
8
|
+
|
|
9
|
+
Offset semantics: a positive offset means the SECOND input starts LATER
|
|
10
|
+
than the reference (it began recording after it), so its sound is delayed by
|
|
11
|
+
that amount (its head padded) to line up; a negative offset means it started
|
|
12
|
+
earlier, and its first -offset seconds are dropped.
|
|
13
|
+
|
|
14
|
+
This aligns two AUDIO tracks to each other; it does not check or guarantee
|
|
15
|
+
lip sync (mouth movement matching the audio). It assumes each recording's
|
|
16
|
+
own audio is already correctly timed against its own picture, which holds
|
|
17
|
+
for ordinary cameras and phones (same device, same clock) but not for a
|
|
18
|
+
capture device with its own internal audio/video offset. There is no
|
|
19
|
+
face or mouth detection anywhere in this codebase to verify that; the only
|
|
20
|
+
way to confirm the final result actually looks in sync is to watch it.
|
|
21
|
+
|
|
22
|
+
Examples:
|
|
23
|
+
python3 sync.py camera.mp4 lavmic.wav # print offset only
|
|
24
|
+
python3 sync.py camera.mp4 lavmic.wav --replace-audio -o synced.mp4
|
|
25
|
+
python3 sync.py camA.mp4 camB.mp4 --trim-second -o camB_synced.mp4
|
|
26
|
+
python3 sync.py cam.mp4 mic.wav --max-offset 60 --json
|
|
27
|
+
python3 sync.py cam.mp4 recorder.wav --fix-drift --replace-audio # long takes: fix clock drift too
|
|
28
|
+
"""
|
|
29
|
+
import argparse
|
|
30
|
+
import math
|
|
31
|
+
import os
|
|
32
|
+
import sys
|
|
33
|
+
from typing import Dict, List
|
|
34
|
+
|
|
35
|
+
from _common.runner import fail_if_classified, refuse_output_is_input
|
|
36
|
+
from _common import STATE, video_args, add_common, apply_common, emit, aac_args, audio_codec_for, default_output, die, ffmpeg_base, info, probe, run, decode_pcm_mono, rms_envelope
|
|
37
|
+
from _common.emit import record_skip, warn
|
|
38
|
+
from _common.decision import SEEK_MARGIN, frame_rate, grid_at_or_after, length_output_t, silence_filter, stream_starts
|
|
39
|
+
from _common.timeline import output_timecode_args
|
|
40
|
+
from _common.runner import default_selection_maps
|
|
41
|
+
from _common.emit import input_length
|
|
42
|
+
|
|
43
|
+
SR = 8000 # decode sample rate
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def sync_meaning(offset: float) -> str:
|
|
47
|
+
"""The sentence a caller reads next to offset_seconds.
|
|
48
|
+
|
|
49
|
+
A zero offset used to take the else branch of `later if offset > 0` and say the second
|
|
50
|
+
file starts earlier. Values that print as 0.000 s (under half a millisecond) say the two
|
|
51
|
+
recordings start together; anything larger keeps later/earlier."""
|
|
52
|
+
if abs(offset) < 5e-4:
|
|
53
|
+
return "second starts together with the reference"
|
|
54
|
+
return "second starts %.3fs %s than reference" % (abs(offset), "later" if offset > 0 else "earlier")
|
|
55
|
+
|
|
56
|
+
# Scoring constants for coarse alignment. Both come from tests/bench_sync.py on real dialogue and
|
|
57
|
+
# music with +/-30 s offsets, gain, noise and EQ (see evals/results and CHANGELOG 0.8.0):
|
|
58
|
+
#
|
|
59
|
+
# MIN_OVERLAP_FRACTION: lags whose overlap with the other track is shorter than this share of the
|
|
60
|
+
# shorter track are never candidates. With the documented rule "analysis window >= 4x the largest
|
|
61
|
+
# expected offset" a true offset keeps >= 75 % overlap, so 0.35 costs nothing there, while the
|
|
62
|
+
# coincidental peaks on quasi-periodic material (music, tone beds) live below it. Raising it to
|
|
63
|
+
# 0.5 started rejecting true 28 s offsets in 60 s windows; lowering it to 0.2 let the partial
|
|
64
|
+
# matches back in (86 % -> 95 % of 60 s stress cases fixed by this alone).
|
|
65
|
+
# OVERLAP_WEIGHT_EXP: normalised similarity is multiplied by (overlap fraction) ** exponent so a
|
|
66
|
+
# perfect match over 55 % of the window cannot tie a perfect match over 100 %. 0.5 keeps a true
|
|
67
|
+
# 75 % overlap at x0.87 and a 53 % one (28 s in 60 s) at x0.73 while a coincidental 40 % match
|
|
68
|
+
# drops to x0.63; exponent 1.0 over-penalised large true offsets, 0.25 left exact ties.
|
|
69
|
+
MIN_OVERLAP_FRACTION = 0.35
|
|
70
|
+
OVERLAP_WEIGHT_EXP = 0.5
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def decode_mono(path: str, seconds: float, start: float = 0.0) -> List[float]:
|
|
74
|
+
return decode_pcm_mono(path, SR, seconds, start)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def envelope(samples: List[float], step: int) -> List[float]:
|
|
78
|
+
"""RMS energy per full block, mean-removed so silence does not correlate."""
|
|
79
|
+
return rms_envelope(samples, step, full_blocks_only=True, remove_mean=True)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def fft(a: List[complex]) -> List[complex]:
|
|
83
|
+
"""Iterative radix-2 Cooley-Tukey FFT. len(a) must be a power of two."""
|
|
84
|
+
n = len(a)
|
|
85
|
+
a = list(a)
|
|
86
|
+
j = 0
|
|
87
|
+
for i in range(1, n):
|
|
88
|
+
bit = n >> 1
|
|
89
|
+
while j & bit:
|
|
90
|
+
j ^= bit
|
|
91
|
+
bit >>= 1
|
|
92
|
+
j ^= bit
|
|
93
|
+
if i < j:
|
|
94
|
+
a[i], a[j] = a[j], a[i]
|
|
95
|
+
length = 2
|
|
96
|
+
while length <= n:
|
|
97
|
+
ang = -2 * math.pi / length
|
|
98
|
+
wlen = complex(math.cos(ang), math.sin(ang))
|
|
99
|
+
half = length // 2
|
|
100
|
+
for i in range(0, n, length):
|
|
101
|
+
w = 1 + 0j
|
|
102
|
+
for k in range(half):
|
|
103
|
+
u = a[i + k]
|
|
104
|
+
v = a[i + k + half] * w
|
|
105
|
+
a[i + k] = u + v
|
|
106
|
+
a[i + k + half] = u - v
|
|
107
|
+
w *= wlen
|
|
108
|
+
length <<= 1
|
|
109
|
+
return a
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def ifft(a: List[complex]) -> List[complex]:
|
|
113
|
+
n = len(a)
|
|
114
|
+
conj = [x.conjugate() for x in a]
|
|
115
|
+
out = fft(conj)
|
|
116
|
+
return [x.conjugate() / n for x in out]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def cross_correlate(ref: List[float], other: List[float], max_lag: int):
|
|
120
|
+
"""Normalised cross-correlation over the overlapping region only.
|
|
121
|
+
|
|
122
|
+
The raw FFT correlation sum grows with the overlap length, so with a 60 s window a
|
|
123
|
+
correct 28 s offset (32 s overlap) loses to a wrong 2 s offset (58 s overlap) on
|
|
124
|
+
music-like material. Dividing each lag by the energy of the overlapping parts
|
|
125
|
+
(prefix sums, O(1) per lag) makes lags comparable and turns the peak value into a
|
|
126
|
+
real similarity score in 0..1 that doubles as the confidence.
|
|
127
|
+
"""
|
|
128
|
+
n = 1
|
|
129
|
+
while n < len(ref) + len(other):
|
|
130
|
+
n <<= 1
|
|
131
|
+
fa = fft([complex(x) for x in ref] + [0j] * (n - len(ref)))
|
|
132
|
+
fb = fft([complex(x) for x in other] + [0j] * (n - len(other)))
|
|
133
|
+
prod = [x * y.conjugate() for x, y in zip(fa, fb)]
|
|
134
|
+
corr = ifft(prod)
|
|
135
|
+
# prefix sums of squares for overlap energy
|
|
136
|
+
def prefix(v: List[float]) -> List[float]:
|
|
137
|
+
out = [0.0]
|
|
138
|
+
acc = 0.0
|
|
139
|
+
for x in v:
|
|
140
|
+
acc += x * x
|
|
141
|
+
out.append(acc)
|
|
142
|
+
return out
|
|
143
|
+
pr, po = prefix(ref), prefix(other)
|
|
144
|
+
lr, lo = len(ref), len(other)
|
|
145
|
+
max_lag = min(max_lag, n // 2 - 1)
|
|
146
|
+
best_lag, best_val, second = 0, -float("inf"), -float("inf")
|
|
147
|
+
min_overlap = max(10, int(MIN_OVERLAP_FRACTION * min(lr, lo))) # see constants above
|
|
148
|
+
scores = []
|
|
149
|
+
for lag in range(-max_lag, max_lag + 1):
|
|
150
|
+
# corr[lag] = sum_i ref[i] * other[i - lag] -> ref index range and other index range overlap:
|
|
151
|
+
r0, r1 = max(0, lag), min(lr, lo + lag)
|
|
152
|
+
if r1 - r0 < min_overlap:
|
|
153
|
+
continue
|
|
154
|
+
e_ref = pr[r1] - pr[r0]
|
|
155
|
+
e_oth = po[r1 - lag] - po[r0 - lag]
|
|
156
|
+
denom = math.sqrt(e_ref * e_oth)
|
|
157
|
+
if denom <= 0:
|
|
158
|
+
continue
|
|
159
|
+
val = corr[lag % n].real / denom
|
|
160
|
+
val *= ((r1 - r0) / min(lr, lo)) ** OVERLAP_WEIGHT_EXP # longer overlap wins ties
|
|
161
|
+
|
|
162
|
+
scores.append((val, lag))
|
|
163
|
+
if val > best_val:
|
|
164
|
+
best_val, best_lag = val, lag
|
|
165
|
+
# The runner-up is the best other PEAK more than 5 lags from the winner (A126). The running
|
|
166
|
+
# "previous best" this used to take was usually the winner's own neighbour, one lag away and
|
|
167
|
+
# on the same slope, so an exact match read 0.59 and could not be told from a tie (0.50).
|
|
168
|
+
by_lag = dict((lag, val) for val, lag in scores)
|
|
169
|
+
for val, lag in scores:
|
|
170
|
+
if abs(lag - best_lag) > 5 and val > second and \
|
|
171
|
+
val >= by_lag.get(lag - 1, -float("inf")) and val >= by_lag.get(lag + 1, -float("inf")):
|
|
172
|
+
second = val
|
|
173
|
+
# confidence: peak similarity, penalised when a distant runner-up is nearly as good
|
|
174
|
+
conf = max(0.0, min(1.0, best_val))
|
|
175
|
+
if second > -float("inf") and best_val > 0:
|
|
176
|
+
margin = (best_val - second) / best_val
|
|
177
|
+
conf *= min(1.0, 0.5 + margin)
|
|
178
|
+
return best_lag, conf
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def refine(ref_s: List[float], oth_s: List[float], coarse_offset: float, fine_step: int, window_s: float) -> float:
|
|
182
|
+
"""Direct correlation at fine resolution around a coarse estimate (+/- window_s)."""
|
|
183
|
+
ref_e = envelope(ref_s, fine_step)
|
|
184
|
+
oth_e = envelope(oth_s, fine_step)
|
|
185
|
+
centre = int(round(coarse_offset * SR / fine_step))
|
|
186
|
+
span = int(window_s * SR / fine_step)
|
|
187
|
+
best_lag, best_val = centre, -float("inf")
|
|
188
|
+
n = min(len(ref_e), len(oth_e))
|
|
189
|
+
for lag in range(centre - span, centre + span + 1):
|
|
190
|
+
# ref[i] ~ oth[i - lag]
|
|
191
|
+
lo, hi = max(0, lag), min(n, n + lag)
|
|
192
|
+
if hi - lo < 10:
|
|
193
|
+
continue
|
|
194
|
+
val = 0.0
|
|
195
|
+
for i in range(lo, hi):
|
|
196
|
+
val += ref_e[i] * oth_e[i - lag]
|
|
197
|
+
val /= (hi - lo)
|
|
198
|
+
if val > best_val:
|
|
199
|
+
best_val, best_lag = val, lag
|
|
200
|
+
return best_lag * fine_step / SR
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def measure_offset(ref_path: str, oth_path: str, start: float, seconds: float, step_ms: float, max_offset: float, fine_ms: float):
|
|
204
|
+
"""Return (offset_seconds, confidence) for a window starting at `start` in both files."""
|
|
205
|
+
ref_s = decode_mono(ref_path, seconds, start)
|
|
206
|
+
oth_s = decode_mono(oth_path, seconds, start)
|
|
207
|
+
step = max(1, int(SR * step_ms / 1000))
|
|
208
|
+
ref = envelope(ref_s, step)
|
|
209
|
+
oth = envelope(oth_s, step)
|
|
210
|
+
if len(ref) < 10 or len(oth) < 10:
|
|
211
|
+
# name the file (or both): sync.py and multicam.py measure several sources, and a bare
|
|
212
|
+
# "not enough audio" left the caller to guess which one was too short
|
|
213
|
+
short = [p for p, env in ((ref_path, ref), (oth_path, oth)) if len(env) < 10]
|
|
214
|
+
die(f"not enough audio to analyse in {' and '.join(short)} "
|
|
215
|
+
f"(needs at least {10 * step_ms / 1000:g} s of audio from {start:g} s)", kind="input")
|
|
216
|
+
max_lag = int(max_offset * SR / step)
|
|
217
|
+
lag, score = cross_correlate(ref, oth, max_lag)
|
|
218
|
+
offset = lag * step / SR
|
|
219
|
+
if fine_ms and fine_ms < step_ms:
|
|
220
|
+
offset = refine(ref_s, oth_s, offset, max(1, int(SR * fine_ms / 1000)), step_ms / 1000 * 2)
|
|
221
|
+
return offset, max(0.0, min(1.0, score))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def measure_one(reference: str, path: str, args) -> Dict:
|
|
225
|
+
"""Everything sync.py measures for ONE other source against the reference: offset,
|
|
226
|
+
confidence and (with --fix-drift) the same end-of-file drift measurement main() has always
|
|
227
|
+
made for a single pair. Used for every source when N>1, and for the historical single-pair
|
|
228
|
+
CLI shape when N==1 -- one measurement, so the two shapes cannot disagree."""
|
|
229
|
+
offset, score = measure_offset(reference, path, 0.0, args.analyze_seconds, args.step_ms, args.max_offset, args.fine_ms)
|
|
230
|
+
drift_ratio = 1.0
|
|
231
|
+
drift_info = None
|
|
232
|
+
# why a requested --fix-drift was not applied: too_short (no tail window far enough from
|
|
233
|
+
# the head to measure over) or low_confidence (the tail did not correlate); None when applied
|
|
234
|
+
skipped_reason = None
|
|
235
|
+
if args.fix_drift:
|
|
236
|
+
ref_dur = input_length(probe(reference))
|
|
237
|
+
sec_dur = input_length(probe(path))
|
|
238
|
+
overlap_end = min(ref_dur, sec_dur + offset)
|
|
239
|
+
head_len = min(args.analyze_seconds, overlap_end)
|
|
240
|
+
tail_start = overlap_end - args.drift_window
|
|
241
|
+
if tail_start <= head_len / 2 + 5:
|
|
242
|
+
skipped_reason = "too_short"
|
|
243
|
+
record_skip(f"{path} too short to measure drift reliably; skipping drift correction", "drift_correction_skipped",
|
|
244
|
+
path=path, reason=skipped_reason, overlap_seconds=round(overlap_end, 3),
|
|
245
|
+
drift_window=args.drift_window)
|
|
246
|
+
else:
|
|
247
|
+
ref_start = tail_start
|
|
248
|
+
sec_start = tail_start - offset
|
|
249
|
+
if sec_start < 0:
|
|
250
|
+
ref_start -= sec_start
|
|
251
|
+
sec_start = 0.0
|
|
252
|
+
ref_s = decode_mono(reference, args.drift_window, ref_start)
|
|
253
|
+
oth_s = decode_mono(path, args.drift_window, sec_start)
|
|
254
|
+
step = max(1, int(SR * args.step_ms / 1000))
|
|
255
|
+
lag, end_score = cross_correlate(envelope(ref_s, step), envelope(oth_s, step), int(2.0 * SR / step))
|
|
256
|
+
residual = lag * step / SR
|
|
257
|
+
if args.fine_ms:
|
|
258
|
+
residual = refine(ref_s, oth_s, residual, max(1, int(SR * args.fine_ms / 1000)), args.step_ms / 1000 * 2)
|
|
259
|
+
head_mid = head_len / 2
|
|
260
|
+
tail_mid = ref_start + args.drift_window / 2
|
|
261
|
+
elapsed = tail_mid - head_mid
|
|
262
|
+
if elapsed > 0 and end_score > 0.1:
|
|
263
|
+
drift_ratio = 1.0 - residual / elapsed
|
|
264
|
+
offset = offset + (drift_ratio - 1.0) * head_mid
|
|
265
|
+
drift_info = {"residual_at_end_seconds": round(residual, 4), "measured_over_seconds": round(elapsed, 2),
|
|
266
|
+
"drift_ppm": round((drift_ratio - 1) * 1e6, 1),
|
|
267
|
+
# a measure-only run writes nothing (#403: it said "will be resampled")
|
|
268
|
+
"meaning": "second file runs %.1f ppm %s (%.3fs over %.0fs); %s" % (
|
|
269
|
+
abs(drift_ratio - 1) * 1e6, "long/slow" if drift_ratio > 1 else "short/fast", abs(residual), elapsed,
|
|
270
|
+
("it would be resampled to match in the file this run plans (--dry-run writes nothing)" if STATE.dry_run
|
|
271
|
+
else "it is resampled to match in the file this run writes")
|
|
272
|
+
if args.replace_audio or args.trim_second else
|
|
273
|
+
"nothing is resampled in this measure-only run (--replace-audio or --trim-second writes the corrected file)"),
|
|
274
|
+
"confidence": round(end_score, 3)}
|
|
275
|
+
else:
|
|
276
|
+
skipped_reason = "low_confidence"
|
|
277
|
+
record_skip(f"could not measure drift with confidence for {path}; skipping drift correction",
|
|
278
|
+
"drift_correction_skipped", path=path, reason=skipped_reason,
|
|
279
|
+
confidence=round(max(0.0, end_score), 3), measured_over_seconds=round(elapsed, 2))
|
|
280
|
+
return {"path": path, "offset_seconds": round(offset, 4), "offset_s": round(offset, 4),
|
|
281
|
+
"confidence": round(max(0.0, min(1.0, score)), 3), "drift_ratio": drift_ratio, "drift": drift_info,
|
|
282
|
+
"drift_ppm": (drift_info["drift_ppm"] if drift_info else None), "drift_skipped_reason": skipped_reason}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def main() -> int:
|
|
286
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
287
|
+
ap.add_argument("reference", help="reference recording (usually the camera video)")
|
|
288
|
+
ap.add_argument("second", help="recording to align (external audio or second camera)")
|
|
289
|
+
ap.add_argument("more_sources", nargs="*", metavar="SOURCE3...", default=[],
|
|
290
|
+
help="(1.18) additional recordings beyond `second` to align to the same "
|
|
291
|
+
"reference -- a third camera, a second external recorder. With none of "
|
|
292
|
+
"these, sync.py keeps its original 2-source shape (offset_seconds/"
|
|
293
|
+
"confidence/drift at the top level, --replace-audio/--trim-second "
|
|
294
|
+
"available). With 1+, all sources (second plus these) are measured and "
|
|
295
|
+
"reported as one offsets JSON {reference, sources: [{path, offset_s, "
|
|
296
|
+
"confidence, drift_ppm}]}, and --replace-audio/--trim-second refuse: "
|
|
297
|
+
"each writes ONE synced output and there is more than one source")
|
|
298
|
+
ap.add_argument("-o", "--output", help="output file when writing a synced result (one-source runs only)")
|
|
299
|
+
ap.add_argument("--max-offset", type=float, default=30.0, help="largest offset to search in seconds (default 30)")
|
|
300
|
+
ap.add_argument("--analyze-seconds", type=float, default=120.0, help="how much audio to analyse from each file (default 120)")
|
|
301
|
+
ap.add_argument("--step-ms", type=float, default=20.0, help="coarse envelope resolution in ms for the FFT search (default 20)")
|
|
302
|
+
ap.add_argument("--fine-ms", type=float, default=1.0, help="fine resolution in ms for the refinement pass, 0 to skip (default 1)")
|
|
303
|
+
ap.add_argument("--fix-drift", action="store_true", help="also measure the offset near the END and correct clock drift by resampling the second file")
|
|
304
|
+
ap.add_argument("--drift-window", type=float, default=60.0, help="seconds of audio analysed at each end for drift (default 60)")
|
|
305
|
+
mode = ap.add_mutually_exclusive_group()
|
|
306
|
+
mode.add_argument("--replace-audio", action="store_true", help="write reference video with the second file's audio, aligned")
|
|
307
|
+
mode.add_argument("--trim-second", action="store_true", help="write the second file shifted so it lines up with the reference")
|
|
308
|
+
ap.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
|
|
309
|
+
add_common(ap)
|
|
310
|
+
args = ap.parse_args()
|
|
311
|
+
apply_common(args)
|
|
312
|
+
# A190: with a search range of 0 or below no lag is tried, and the run reported an offset
|
|
313
|
+
# (0.012 s at confidence 0) for a correlation it never made
|
|
314
|
+
if args.max_offset <= 0:
|
|
315
|
+
die(f"--max-offset must be more than 0 seconds (the largest offset searched), got {args.max_offset:g}")
|
|
316
|
+
if args.analyze_seconds <= 0:
|
|
317
|
+
die(f"--analyze-seconds must be more than 0 seconds, got {args.analyze_seconds:g}")
|
|
318
|
+
if args.analyze_seconds > 900:
|
|
319
|
+
die(f"--analyze-seconds {args.analyze_seconds:g}: the window is decoded into memory; 900 s is the ceiling")
|
|
320
|
+
args.sources = [args.second] + list(args.more_sources)
|
|
321
|
+
|
|
322
|
+
for p in (args.reference,) + tuple(args.sources):
|
|
323
|
+
if not probe(p).get("audio"):
|
|
324
|
+
die(f"{p} has no audio stream to correlate")
|
|
325
|
+
|
|
326
|
+
n_sources = len(args.sources)
|
|
327
|
+
if (args.replace_audio or args.trim_second) and n_sources > 1:
|
|
328
|
+
die("--replace-audio/--trim-second write ONE synced output and need exactly one SOURCE; "
|
|
329
|
+
f"{n_sources} were given. Run sync.py once per source, or drop the flag and read the "
|
|
330
|
+
"offsets JSON.", kind="input")
|
|
331
|
+
|
|
332
|
+
measured = [measure_one(args.reference, p, args) for p in args.sources]
|
|
333
|
+
for p, m in zip(args.sources, measured):
|
|
334
|
+
if m["confidence"] < 0.1:
|
|
335
|
+
warn(f"{p}: low correlation confidence; check that it shares an audio event with the reference",
|
|
336
|
+
"sync_low_confidence", path=p, confidence=m["confidence"])
|
|
337
|
+
|
|
338
|
+
sources_block = [{"path": p, "offset_s": m["offset_s"], "confidence": m["confidence"],
|
|
339
|
+
**({"drift_ppm": m["drift_ppm"], "drift_skipped_reason": m["drift_skipped_reason"]} if args.fix_drift else {})}
|
|
340
|
+
for p, m in zip(args.sources, measured)]
|
|
341
|
+
|
|
342
|
+
if n_sources == 1:
|
|
343
|
+
# The original 2-source shape, unchanged, plus (additively) the same measurement under
|
|
344
|
+
# `sources` so a caller reading the new key gets the same numbers for a single source.
|
|
345
|
+
args.second = args.sources[0]
|
|
346
|
+
m = measured[0]
|
|
347
|
+
offset, score, drift_ratio, drift_info = m["offset_seconds"], m["confidence"], m["drift_ratio"], m["drift"]
|
|
348
|
+
result = {
|
|
349
|
+
"reference": args.reference,
|
|
350
|
+
"second": args.second,
|
|
351
|
+
"offset_seconds": offset,
|
|
352
|
+
"confidence": score,
|
|
353
|
+
"meaning": sync_meaning(offset),
|
|
354
|
+
"sources": sources_block,
|
|
355
|
+
}
|
|
356
|
+
if drift_info:
|
|
357
|
+
result["drift"] = drift_info
|
|
358
|
+
if args.fix_drift:
|
|
359
|
+
result["drift_skipped_reason"] = m["drift_skipped_reason"]
|
|
360
|
+
else:
|
|
361
|
+
offset = drift_ratio = drift_info = None # not used below; output writing is 1-source only
|
|
362
|
+
result = {"reference": args.reference, "sources": sources_block}
|
|
363
|
+
info(f"measured {n_sources} sources against {args.reference}: " +
|
|
364
|
+
", ".join(f"{s['path']}: {s['offset_s']:+.3f}s (confidence {s['confidence']:.2f})" for s in sources_block))
|
|
365
|
+
|
|
366
|
+
if args.replace_audio or args.trim_second:
|
|
367
|
+
output = args.output or default_output(args.reference if args.replace_audio else args.second, "synced", "mp4")
|
|
368
|
+
# --trim-second's command takes only SECOND as -i, so run()'s guard never saw the reference:
|
|
369
|
+
# REF named SECOND_synced.mp4 (the default name) or `-o REF` was replaced (#522)
|
|
370
|
+
refuse_output_is_input(output, args.reference, args.second)
|
|
371
|
+
# second started later (offset > 0) -> delay it by `offset` (pad the head)
|
|
372
|
+
# second started earlier (offset < 0) -> drop its first `-offset` seconds
|
|
373
|
+
delay_ms = int(round(offset * 1000))
|
|
374
|
+
head_trim = -offset if offset < 0 else 0.0
|
|
375
|
+
second_meta = probe(args.second)
|
|
376
|
+
has_video = bool(second_meta.get("video"))
|
|
377
|
+
sec_sr = (second_meta.get("audio") or {}).get("sample_rate") or 48000
|
|
378
|
+
drift_af: List[str] = []
|
|
379
|
+
if abs(drift_ratio - 1.0) > 1e-7:
|
|
380
|
+
# the second file runs long by drift_ratio -> play it faster by that ratio (pitch shift is ~ppm, inaudible)
|
|
381
|
+
drift_af = [f"asetrate={sec_sr * drift_ratio:.6f}", f"aresample={sec_sr}"]
|
|
382
|
+
# the offset is measured between the files' clocks (decode_pcm_mono pads a late sound), so
|
|
383
|
+
# the second's sound is placed on its own clock first: one that starts 0.3 s after its
|
|
384
|
+
# file's start keeps that 0.3 s instead of being delayed from its first sample (#409).
|
|
385
|
+
# Only then, so the command for an ordinary file is the one it always was.
|
|
386
|
+
on_clock = ["aresample=async=1:first_pts=0"] if stream_starts(second_meta)[1] > 0.0005 else []
|
|
387
|
+
|
|
388
|
+
if args.replace_audio:
|
|
389
|
+
cmd = ffmpeg_base() + ["-i", args.reference]
|
|
390
|
+
if head_trim > 0:
|
|
391
|
+
cmd += ["-ss", f"{head_trim:.4f}"]
|
|
392
|
+
cmd += ["-i", args.second, "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy"]
|
|
393
|
+
if os.path.splitext(output)[1].lower() in (".mp4", ".mov", ".m4v"):
|
|
394
|
+
cmd += ["-movflags", "+faststart"]
|
|
395
|
+
# the reference picture is the deliverable: pad the (possibly trimmed) second audio to
|
|
396
|
+
# its length instead of -shortest, which cut the reference's tail whenever the second
|
|
397
|
+
# file started earlier (head_trim > 0) or was simply shorter
|
|
398
|
+
ref_dur = probe(args.reference).get("duration")
|
|
399
|
+
# the delay is the measured offset to the sample of the second's rate: at the default
|
|
400
|
+
# --fine-ms 1 without --fix-drift the offset is a whole millisecond and the text is the
|
|
401
|
+
# one it was; a finer step (0.25 ms: 0.23425 s) or a drift-adjusted offset (kept to
|
|
402
|
+
# 0.1 ms) was rounded to `adelay=234` (silence_filter)
|
|
403
|
+
lead = [silence_filter(sec_sr, lead=offset)] if offset > 0 and round(offset * sec_sr) else []
|
|
404
|
+
af_parts = on_clock + drift_af + lead + ["apad"]
|
|
405
|
+
cmd += ["-af", ",".join(af_parts)]
|
|
406
|
+
# to the sample of the rate the second's sound is written at, not to the millisecond:
|
|
407
|
+
# the endless apad is ended by this -t alone (length_output_t)
|
|
408
|
+
ref_t = length_output_t(ref_dur, (second_meta.get("audio") or {}).get("sample_rate"), runs_on=True) if ref_dur else None
|
|
409
|
+
cmd += aac_args() + (["-t", ref_t] if ref_dur else ["-shortest"]) + [output]
|
|
410
|
+
proc = run(cmd, check=False)
|
|
411
|
+
fail_if_classified(proc) # a cause the re-encode would hit too is reported, not retried (#415)
|
|
412
|
+
if proc.returncode != 0:
|
|
413
|
+
cmd = [c for c in cmd if c != "copy"]
|
|
414
|
+
idx = cmd.index("-c:v"); del cmd[idx]
|
|
415
|
+
cmd = cmd[:-1] + video_args(probe(args.reference) if args.replace_audio else probe(args.second), args.crf) + [output]
|
|
416
|
+
run(cmd)
|
|
417
|
+
else:
|
|
418
|
+
# A picture is never stream-copied here: a copy starts at the keyframe at or before -ss
|
|
419
|
+
# and -avoid_negative_ts make_zero shows the frames from it, so the output started
|
|
420
|
+
# early by up to a GOP (a 5 s GOP: nothing trimmed at all) and was reported as synced.
|
|
421
|
+
# Even a keyframe on the trim point moved the picture by its B-frame delay (+69 ms).
|
|
422
|
+
# The re-encode below starts on the frame itself; a sound-only file is still copied.
|
|
423
|
+
if head_trim > 0 and not drift_af and not has_video:
|
|
424
|
+
# the second file's first audio track: the one decode_pcm_mono() measured
|
|
425
|
+
cmd = ffmpeg_base() + ["-ss", f"{head_trim:.4f}", "-i", args.second] + default_selection_maps(second_meta, output) + ["-c", "copy"]
|
|
426
|
+
if os.path.splitext(output)[1].lower() in (".mp4", ".mov", ".m4v"):
|
|
427
|
+
cmd += ["-movflags", "+faststart"]
|
|
428
|
+
cmd += ["-avoid_negative_ts", "make_zero", output]
|
|
429
|
+
proc = run(cmd, check=False)
|
|
430
|
+
fail_if_classified(proc)
|
|
431
|
+
if proc.returncode != 0:
|
|
432
|
+
cmd = ffmpeg_base() + ["-ss", f"{head_trim:.4f}", "-i", args.second] + default_selection_maps(second_meta, output) + (video_args(probe(args.reference) if args.replace_audio else probe(args.second), args.crf) if has_video else []) + audio_codec_for(output) + [output]
|
|
433
|
+
run(cmd)
|
|
434
|
+
else:
|
|
435
|
+
# Seek SEEK_MARGIN early and drop the margin on the output side, as cut.py's
|
|
436
|
+
# re-encode does: an input seek straight to head_trim can land (the MP4 demuxer
|
|
437
|
+
# seeks over raw decode times) on a keyframe whose picture comes after it, and a
|
|
438
|
+
# B-frame HEVC file lost the frames before it. The output-side -ss decodes and
|
|
439
|
+
# drops the margin from both streams alike; it counts on the output's clock, which
|
|
440
|
+
# a drift fix runs faster by drift_ratio (setpts and asetrate alike).
|
|
441
|
+
cmd = ffmpeg_base()
|
|
442
|
+
out_seek: List[str] = []
|
|
443
|
+
if head_trim > 0:
|
|
444
|
+
m = min(SEEK_MARGIN, head_trim)
|
|
445
|
+
cmd += ["-ss", f"{head_trim - m:.6f}"]
|
|
446
|
+
if m > 0:
|
|
447
|
+
out_seek = ["-ss", f"{m / (drift_ratio if drift_af else 1.0):.6f}"]
|
|
448
|
+
# -map after the output-side -ss: both are output options, so the order is the
|
|
449
|
+
# same command, and the seek stays next to the -i it drops the margin from
|
|
450
|
+
cmd += ["-i", args.second] + out_seek + default_selection_maps(second_meta, output)
|
|
451
|
+
af_parts = on_clock + drift_af
|
|
452
|
+
# one sound is written here (the default selection, or the probed track of a file
|
|
453
|
+
# with several: default_selection_maps), the one sec_sr is the rate of, so the delay
|
|
454
|
+
# is counted in its samples as --replace-audio's is. A whole millisecond (the
|
|
455
|
+
# default --fine-ms 1 without --fix-drift) keeps `adelay=<ms>:all=1`
|
|
456
|
+
if offset > 0 and round(offset * sec_sr):
|
|
457
|
+
af_parts.append(silence_filter(sec_sr, lead=offset))
|
|
458
|
+
if has_video:
|
|
459
|
+
vf = []
|
|
460
|
+
if delay_ms > 0:
|
|
461
|
+
vf.append(f"tpad=start_duration={offset:.4f}")
|
|
462
|
+
if drift_af:
|
|
463
|
+
vf.append(f"setpts=PTS/{drift_ratio:.9f}")
|
|
464
|
+
if vf:
|
|
465
|
+
cmd += ["-vf", ",".join(vf)]
|
|
466
|
+
cmd += video_args(probe(args.reference) if args.replace_audio else probe(args.second), args.crf)
|
|
467
|
+
# the output's first frame is the second file's frame at head_trim, or (padded)
|
|
468
|
+
# one `offset` before its first: its start timecode moves with it
|
|
469
|
+
v0, rate = stream_starts(second_meta)[0], frame_rate(second_meta)
|
|
470
|
+
# (a trim before a picture that starts after the file's origin starts on its
|
|
471
|
+
# first frame; only the padded head counts back before it)
|
|
472
|
+
first = (grid_at_or_after(max(round(head_trim, 4), v0), v0, rate) - v0 if head_trim > 0
|
|
473
|
+
else -offset if delay_ms > 0 else 0.0)
|
|
474
|
+
cmd += output_timecode_args(second_meta, first)
|
|
475
|
+
if af_parts:
|
|
476
|
+
cmd += ["-af", ",".join(af_parts)]
|
|
477
|
+
cmd += audio_codec_for(output) + [output]
|
|
478
|
+
run(cmd)
|
|
479
|
+
result["output"] = output
|
|
480
|
+
info(f"wrote {output}")
|
|
481
|
+
|
|
482
|
+
if args.json:
|
|
483
|
+
emit(result.get("output"), **{k: v for k, v in result.items() if k != "output"})
|
|
484
|
+
elif n_sources == 1:
|
|
485
|
+
print(f"offset: {result['offset_seconds']:+.3f}s ({result['meaning']}), confidence {result['confidence']:.2f}")
|
|
486
|
+
if drift_info:
|
|
487
|
+
print(f"drift: {drift_info['drift_ppm']:+.1f} ppm ({drift_info['residual_at_end_seconds']:+.3f}s over {drift_info['measured_over_seconds']:.0f}s), confidence {drift_info['confidence']:.2f}")
|
|
488
|
+
if "output" in result:
|
|
489
|
+
print(result["output"])
|
|
490
|
+
else:
|
|
491
|
+
for s in sources_block:
|
|
492
|
+
line = f"{s['path']}: {s['offset_s']:+.3f}s, confidence {s['confidence']:.2f}"
|
|
493
|
+
if args.fix_drift:
|
|
494
|
+
line += f", drift {s['drift_ppm']:+.1f} ppm" if s["drift_ppm"] is not None else ""
|
|
495
|
+
print(line)
|
|
496
|
+
return 0
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
if __name__ == "__main__":
|
|
500
|
+
sys.exit(main())
|