"""Fit a video to a target duration and/or aspect ratio.
Duration: --duration N with --method speed (retime video+audio, pitch-preserving
via atempo chaining) or --method trim (keep the first N seconds, or a centred
window with --from-center). Speed is the default method, but a retime beyond
1.15x in either direction is never silent: the result's diagnostics carry a
large_speed_change warning with the factor, because retiming the whole clip is
easy to ask for by accident when what was wanted was a cut.
Aspect: --aspect 16:9|9:16|1:1|4:5|W:H with
--fit pad (letterbox/pillarbox with --pad-color, default black, or --pad-fill blur\nfor a blurred copy of the frame behind the picture), --fit crop, or --fit blur\n(the whole picture centred on a blurred, darkened copy of itself -- nothing\ncropped, no black bars).
--width and/or --height set the output size: give one and the other follows
the aspect (source aspect if --aspect is not also given); give both for an
exact frame. --rotate 90|180|270 (clockwise) and --flip h|v apply a new
rotation/mirror to the picture -- distinct from the rotation metadata a
source already carries (read automatically to compute the displayed size,
never altered by these flags unless asked). Both can be combined; rotate is
applied before flip.
Crop keeps the centre of the frame by default, which is a guess: going from
16:9 to 9:16 throws away most of the width, and whatever isn't in the middle
third (a person at the edge, a product held to one side) is cut off. Say what
to keep with --crop-x / --crop-y (0=left/top, 0.5=centre, 1=right/bottom, or
a decimal in between) rather than accepting the default silently when the
subject isn't centred; --fit pad never loses anything if you don't know yet.
After a real --fit crop that cuts something away, the result's crop_check
measures where the source's luma motion (in a still shot, its edge detail)
sits against the kept window: a proxy sampled at 9 points, not subject
detection. A crop_content_off_centre warning names --crop-x/--crop-y with a
suggested value, or --fit pad / --fit blur, when most of it is cut away.
Advisory only: the output and the exit status are unchanged.
Examples:
python3 fit.py input.mp4 --duration 60 --method trim # keep the first 60s
python3 fit.py input.mp4 --duration 30 --method speed # retime the whole clip to exactly 30s
python3 fit.py input.mp4 --aspect 9:16 --fit pad --width 1080
python3 fit.py input.mp4 --aspect 9:16 --fit pad --pad-fill blur # the phone-editor look: blurred frame behind the bars
python3 fit.py input.mp4 --aspect 9:16 --fit blur # same look in one word (blurred + darkened fill)
python3 fit.py input.mp4 --aspect 1:1 --fit crop --duration 15
python3 fit.py input.mp4 --aspect 9:16 --fit crop --crop-x 1 # keep the right edge (e.g. product held stage-right)
python3 fit.py input.mp4 --height 1080 # width follows the source aspect
python3 fit.py input.mp4 --width 1920 --height 1080 # exact frame, no aspect needed
python3 fit.py input.mp4 --rotate 90 # rotate 90 degrees clockwise
python3 fit.py input.mp4 --flip h # mirror horizontally
"""
import argparse
import os
import sys
from fractions import Fraction
from typing import Any, List, Optional
from _common.runner import require_tool, run_analysis
from _common.decision import SEEK_MARGIN, atempo_chain_with_lead, line_matrix_filter, delivered_rate, frame_durations, frame_rate, grid_at_or_after, length_output_t, stream_starts
from _common.timeline import exact_rate, output_timecode_args
from _common import video_args, STATE, add_common, apply_common, emit, aac_args, aspect_ratio, cfr_args, cfr_filter, default_output, die, ffmpeg_base, info, probe, run, run_keeping_subtitles, validate_color, pad_filters, add_pad_fill_args, X264_PRESETS, time_arg, fmt_secs, frame_size, display_size, square_pixels, square_pixels_note, note
from _common.emit import input_length, refuse_still, warn
from _common.probe import fingerprint
BLUR_DARKEN = 0.15
SPEED_WARN_FACTOR = 1.15
CROP_SAMPLES = 9
CROP_SAMPLE_GAP = 0.2
CROP_SAMPLE_LONG = 160
CROP_DETAIL_MIN = 16
CROP_MOTION_MIN = 8
CROP_MOTION_FLOOR = 0.05
CROP_DETAIL_FLOOR = 0.05
CROP_MOTION_OUTSIDE_WARN = 0.5
CROP_DETAIL_EXCESS_WARN = 0.15
def parse_aspect(value: str) -> Fraction:
ratio = aspect_ratio(value)
if ratio is None:
die(f"bad aspect '{value}', use W:H like 16:9")
return ratio
def atempo_chain(factor: float, sample_rate: Any = 0) -> str:
"""atempo accepts 0.5..100 per instance; chain for extreme factors. The chain is led by the
samples atempo leaves out (atempo_chain_with_lead, at the track's `sample_rate`), so the
retimed sound keeps its timing against the retimed picture (#523: about 21 ms early in input
time without them)."""
parts: List[str] = []
remaining = factor
while remaining < 0.5:
parts.append("0.5")
remaining /= 0.5
while remaining > 100.0:
parts.append("100.0")
remaining /= 100.0
parts.append(f"{remaining:.6f}")
return atempo_chain_with_lead(parts, sample_rate)
def picture_output_t(target: float, meta: dict) -> str:
"""The output `-t` of a trim from the start that has no sound to end: `{target:.3f}` as it
always was, unless that text keeps another number of frames than `target` does. The frames
kept are those that start before `target`. 37 frames of a 30000/1001 picture are 1.2345667 s:
`-t 1.235` is past the 38th frame's start and wrote it, and `-t 1.001` for 1.0014 s stopped
before the 31st. The limit is then written half a frame before the first frame left out.
Without a frame grid (no rate: a dry run's pending input; a variable rate, which the output's
-r regrids) the millisecond text stays."""
text = f"{target:.3f}"
rate = frame_rate(meta)
if not rate or (meta.get("video") or {}).get("variable_frame_rate_suspected"):
return text
out = grid_at_or_after(target, stream_starts(meta)[0], rate)
if out - 1 / rate + 1e-6 < float(text) <= out + 1e-9:
return text
return f"{out - 0.5 / rate:.6f}"
def _picture_rows(path_meta: dict, chain: str, colour: str, sw: int, sh: int, size: int,
out_pix: "Optional[str]") -> "Optional[bytes]":
"""One frame of `colour` at the source's displayed size and pixel format through `chain`, as
8-bit grey bytes, or None when ffmpeg did not give exactly one frame of `size` bytes. The chain
ends in the written file's pixel format, as the encoder line makes it end: pad rounds its
offset and the picture's size to that format's chroma grid (a 203-row picture is padded as 202
rows of a 4:2:0 frame), and a chain ending in grey would pad in grey."""
pix = (path_meta.get("video") or {}).get("pix_fmt")
src = f"color=c={colour}:s={sw}x{sh}:r=1:d=1" + (f",format={pix}" if pix else "")
cmd = [require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin", "-filter_threads", "1",
"-f", "lavfi", "-i", src,
"-vf", chain + (f",format={out_pix}" if out_pix else "") + ",format=gray", "-frames:v", "1", "-f", "rawvideo", "-"]
proc = run_analysis(cmd, check=False, text=False)
return proc.stdout if proc.returncode == 0 and len(proc.stdout or b"") == size else None
def measure_picture(geometry, meta: dict, sw: int, sh: int, out_video: dict, sized: bool) -> dict:
"""Where the picture sits in the written frame (#519): measured, not judged. ffmpeg runs the
frame's own filters (the scale and pad, the blur graph with its background drawn black, or the
scale and crop) on one white and one black frame of the source's displayed size and pixel
format, after the colour conversion the encoder line adds; the picture is where the two
differ, and the frame is the written file's. No frame of the source is decoded. Whether the
subject is inside that rectangle is still a look (subject_framing stays unverified)."""
filters, crop_scale, cropped = geometry
W, H = int(out_video.get("width") or 0), int(out_video.get("height") or 0)
why = None
if not (sw and sh and W and H):
why = "the source or the written frame has no size"
else:
conv = line_matrix_filter(meta)
chain = ",".join(([conv] if conv else []) + list(filters))
out_pix = out_video.get("pix_fmt")
white = _picture_rows(meta, chain, "white", sw, sh, W * H, out_pix)
black = _picture_rows(meta, chain, "black", sw, sh, W * H, out_pix) if white is not None else None
if white is None or black is None:
why = f"ffmpeg did not give one {W}x{H} frame of the frame's filters (the written frame's size)"
if why:
note(f"picture: not measured: {why}")
return {"measured": False, "reason": why}
rows = [r for r in range(H) if white[r * W:(r + 1) * W] != black[r * W:(r + 1) * W]]
if not rows:
note("picture: not measured: no pixel of the frame changed with the picture")
return {"measured": False, "reason": "no pixel of the frame changed with the picture"}
left, right = W, -1
for r in rows:
d = int.from_bytes(white[r * W:(r + 1) * W], "big") ^ int.from_bytes(black[r * W:(r + 1) * W], "big")
x0 = W - (d.bit_length() + 7) // 8
x1 = W - 1 - ((d & -d).bit_length() - 1) // 8
left, right = min(left, x0), max(right, x1)
x, y, w, h = left, rows[0], right - left + 1, rows[-1] - rows[0] + 1
scale = crop_scale if crop_scale is not None else w / sw
pic = {"measured": True, "x": x, "y": y, "width": w, "height": h, "frame_width": W, "frame_height": H,
"frame_share": round(w * h / (W * H), 4), "scale": round(scale, 4),
"cropped": cropped or {"left": 0, "right": 0, "top": 0, "bottom": 0}}
if scale < 1 and not sized:
note(f"picture: scaled to {scale:.1%} of the source's width ({w}x{h} in a {W}x{H} frame): with no --width or "
"--height the frame keeps the source's height or width (give --width/--height for a larger frame)")
return pic
def sample_crop_frames(path: str, orient: List[str], sw: int, sh: int, start: float,
length: float) -> "Optional[tuple]":
"""The crop check's decode step: CROP_SAMPLES points evenly over the kept source range
[start, start + length] at (i + 0.5) / CROP_SAMPLES, two 8-bit grey frames CROP_SAMPLE_GAP s
apart at each, in the displayed frame the crop is cut from (autorotated, then the run's own
--rotate/--flip filters `orient`) scaled to CROP_SAMPLE_LONG px on the long axis. Returns
([(first, second), ...], width, height), or None when no point gave two whole frames. A
point that fails (past the end, a decode error) is left out; the others still count."""
if not (sw and sh) or length <= CROP_SAMPLE_GAP:
return None
if sw >= sh:
w, h = CROP_SAMPLE_LONG, max(2, round(CROP_SAMPLE_LONG * sh / sw / 2) * 2)
else:
w, h = max(2, round(CROP_SAMPLE_LONG * sw / sh / 2) * 2), CROP_SAMPLE_LONG
size = w * h
filters = [f"fps={1 / CROP_SAMPLE_GAP:g}"] + list(orient) + [f"scale={w}:{h}:flags=area", "format=gray"]
last = start + max(0.0, length - CROP_SAMPLE_GAP - 0.1)
frames = []
for i in range(CROP_SAMPLES):
t = min(start + length * (i + 0.5) / CROP_SAMPLES, last)
seek = f"{t:.6f}"
remaining = start + length - float(seek)
chain = ",".join([f"trim=end={remaining:.6f}"] + filters)
cmd = [require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin",
"-ss", seek, "-i", path, "-map", "0:V:0", "-an", "-sn", "-dn",
"-vf", chain, "-frames:v", "2", "-f", "rawvideo", "-"]
proc = run_analysis(cmd, check=False, text=False, timeout_is_fatal=False)
out = proc.stdout or b""
if proc.returncode == 0 and len(out) == 2 * size:
frames.append((out[:size], out[size:]))
return (frames, w, h) if frames else None
def crop_loss(frames, width: int, height: int, window, axis: str) -> dict:
"""Where the luma motion and detail sit against a crop's kept window: a measurement, not a
judgement, and a proxy, not subject detection. Pure: `frames` is [(first, second), ...] of
`width` x `height` 8-bit grey bytes; `window` is (start, end) of the kept part as fractions
0..1 of the frame along `axis` ("x": columns, "y": rows).
Per column (per row for y): detail D = sum of |luma gradient| (right and down neighbours) of
the first frame, counting only gradients >= CROP_DETAIL_MIN; motion M = sum of |first -
second|, counting only differences >= CROP_MOTION_MIN. motion_outside / detail_outside: the
energy share in the discarded part (a column the window edge cuts counts pro rata).
centroid: of M when its mean is at or above CROP_MOTION_FLOOR, else of D. suggested_anchor:
the --crop-x/--crop-y value (0..1) that centres the kept window on the centroid, clamped.
verdict: review when motion is present and motion_outside >= CROP_MOTION_OUTSIDE_WARN, or
with no motion when detail_outside - discarded_fraction >= CROP_DETAIL_EXCESS_WARN; ok
otherwise; unmeasured when no whole pair was given or the frames are flat (no division by
zero, centroid and suggested_anchor null)."""
n = max(1, width if axis == "x" else height)
size = width * height
detail = [0] * n
motion = [0] * n
used = 0
for pair in frames or []:
a = pair[0] if len(pair) > 0 else b""
b = pair[1] if len(pair) > 1 else b""
if size <= 0 or len(a) != size or len(b) != size:
continue
used += 1
for r in range(height):
o = r * width
row, other = a[o:o + width], b[o:o + width]
below = a[o + width:o + 2 * width] if r + 1 < height else None
for c in range(width):
v = row[c]
k = c if axis == "x" else r
s = 0
if c + 1 < width:
g = abs(row[c + 1] - v)
if g >= CROP_DETAIL_MIN:
s += g
if below is not None:
g = abs(below[c] - v)
if g >= CROP_DETAIL_MIN:
s += g
if s:
detail[k] += s
m = abs(other[c] - v)
if m >= CROP_MOTION_MIN:
motion[k] += m
w0 = min(max(float(min(window)), 0.0), 1.0)
w1 = min(max(float(max(window)), 0.0), 1.0)
keep = w1 - w0
discarded = 1.0 - keep
def outside(profile):
total = sum(profile)
if total <= 0:
return None
lost = 0.0
for k, e in enumerate(profile):
if e:
inside = max(0.0, min((k + 1) / n, w1) - max(k / n, w0)) * n
lost += e * (1.0 - inside)
return lost / total
pixels = used * size
has_motion = bool(pixels) and sum(motion) / pixels >= CROP_MOTION_FLOOR
has_detail = bool(pixels) and sum(detail) / pixels >= CROP_DETAIL_FLOOR
m_out, d_out = outside(motion), outside(detail)
check = {"axis": axis, "discarded_fraction": round(discarded, 4),
"motion_outside": None if m_out is None else round(m_out, 4),
"detail_outside": None if d_out is None else round(d_out, 4),
"centroid": None, "suggested_anchor": None, "samples": used,
"basis": "luma_motion_proxy", "verdict": "unmeasured"}
if not (has_motion or has_detail):
return check
profile = motion if has_motion else detail
centroid = sum((k + 0.5) / n * e for k, e in enumerate(profile)) / sum(profile)
check["centroid"] = round(centroid, 4)
if discarded > 1e-9:
check["suggested_anchor"] = round(min(1.0, max(0.0, (centroid - keep / 2) / discarded)), 2)
if has_motion:
review = (m_out or 0.0) >= CROP_MOTION_OUTSIDE_WARN
else:
review = (d_out or 0.0) - discarded >= CROP_DETAIL_EXCESS_WARN
check["verdict"] = "review" if review else "ok"
return check
def check_crop(path: str, orient: List[str], sw: int, sh: int, window, start: float, length: float) -> dict:
"""crop_check for a --fit crop that cut something away: samples the kept source range,
measures it with crop_loss and records crop_content_off_centre when the verdict is review.
Advisory: nothing here changes the output or the exit status. A measurement that fails is
verdict unmeasured with a note, never another diagnostic code."""
axis, w0, w1 = window
try:
got = sample_crop_frames(path, orient, sw, sh, start, length)
frames, fw, fh = got if got else ([], 1, 1)
check = crop_loss(frames, fw, fh, (w0, w1), axis)
except Exception as exc:
note(f"crop check: not measured: {exc}")
return crop_loss([], 1, 1, (w0, w1), axis)
if check["verdict"] == "unmeasured":
note("crop check: not measured: " + ("no sample gave two frames" if not check["samples"]
else "the sampled frames have no luma motion or detail"))
return check
if check["verdict"] == "review":
moving = check["motion_outside"] is not None and check["motion_outside"] >= CROP_MOTION_OUTSIDE_WARN
share = check["motion_outside"] if moving else check["detail_outside"]
flag = f"--crop-{axis}"
anchor = check["suggested_anchor"]
remedy = (f"{flag} {anchor:g} centres the kept window on it" if anchor is not None else f"{flag} moves the kept window")
warn(f"--fit crop: {share:.0%} of the sampled luma {'motion' if moving else 'detail'} lies in the "
f"{check['discarded_fraction']:.0%} of the frame ({axis} axis) the crop cuts away. This is a "
f"luma motion/detail proxy, not subject detection. {remedy}; --fit pad or --fit blur crop nothing",
"crop_content_off_centre",
**{k: check[k] for k in ("axis", "discarded_fraction", "motion_outside", "detail_outside",
"centroid", "suggested_anchor", "samples", "basis")})
return check
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input")
ap.add_argument("-o", "--output", help="output file (default: <name>_fit.<ext>)")
ap.add_argument("--audio-stream", type=int, default=0,
help="which audio stream of the input to keep, 0-based in file order (probe.py lists them under "
"audio_streams) -- matters on a multi-track input (dubbed languages, M&E stems); default 0, "
"the first track, same as leaving it unset always did")
d = ap.add_argument_group("duration")
d.add_argument("--duration", help="target duration (seconds or mm:ss)")
d.add_argument("--method", choices=["speed", "trim"], default="speed", help="how to reach the duration (default speed; a retime beyond 1.15x in either direction is reported as a large_speed_change warning in the result)")
d.add_argument("--from-center", action="store_true", help="with --method trim, keep the middle instead of the start")
d.add_argument("--max-speed", type=float, default=4.0, help="refuse speed factors above this (default 4x)")
d.add_argument("--smooth", choices=["none", "blend", "interpolate"], default="none",
help="slow-motion quality: blend (frame blending) or interpolate (motion-compensated, slow but fluid). default none = duplicate frames")
a = ap.add_argument_group("aspect")
a.add_argument("--aspect", help="target aspect ratio, e.g. 16:9, 9:16, 1:1, 4:5")
a.add_argument("--fit", choices=["pad", "crop", "blur"], default="pad",
help="how to reach the aspect: pad (letterbox), crop, or blur -- the whole picture centred on a "
"blurred, darkened copy of itself filling the rest (the phone-editor vertical, 1.14). "
"The darkening is applied to SDR sources only: on an HDR source the background is blurred "
"but left at its own levels, since an eq on PQ/HLG code values is not a -15%% perceptual dim")
a.add_argument("--width", type=int, help="output width in px (default: keep source width or the width implied by the aspect); with --height also given, both are used directly")
a.add_argument("--height", type=int, help="output height in px (default: keep source height or the height implied by the aspect); with --width also given, both are used directly")
a.add_argument("--pad-color", default="black", help="pad colour, e.g. black, white, 0x101010 (default black)")
add_pad_fill_args(a)
a.add_argument("--crop-x", type=float, default=0.5, help="with --fit crop, horizontal anchor 0=left, 0.5=centre (default), 1=right")
a.add_argument("--crop-y", type=float, default=0.5, help="with --fit crop, vertical anchor 0=top, 0.5=centre (default), 1=bottom")
r = ap.add_argument_group("rotate / flip")
r.add_argument("--rotate", type=int, choices=[90, 180, 270], help="rotate the picture clockwise by this many degrees")
r.add_argument("--flip", choices=["h", "v"], help="mirror the picture horizontally (h) or vertically (v)")
e = ap.add_argument_group("encoding")
e.set_defaults(crf=18)
e.add_argument("--preset", default="medium", choices=X264_PRESETS)
e.add_argument("--fps", type=float, help="force a constant output frame rate (recommended for VFR sources)")
add_common(ap)
args = ap.parse_args()
apply_common(args)
if args.fps is not None and args.fps <= 0:
die(f"--fps must be positive, got {args.fps:g}")
for flag, value in (("--width", args.width), ("--height", args.height)):
if value is not None and value < 1:
die(f"{flag} must be a positive number of pixels, got {value}")
if not args.duration and not args.aspect and not args.width and not args.height and not args.fps and not args.rotate and not args.flip:
die("nothing to do: give --duration, --aspect, --width/--height, --rotate/--flip and/or --fps")
if not 0.0 <= args.crop_x <= 1.0:
die(f"--crop-x must be 0..1, got {args.crop_x}")
if not 0.0 <= args.crop_y <= 1.0:
die(f"--crop-y must be 0..1, got {args.crop_y}")
validate_color(args.pad_color, "--pad-color")
if args.pad_blur <= 0:
die(f"--pad-blur must be > 0, got {args.pad_blur}")
if STATE.plan and args.duration and os.path.isfile(args.input):
try:
source = fingerprint(args.input)
except OSError as exc:
die(f"cannot fingerprint the source for the duration plan: {exc}", kind="input")
STATE.measured_plan_inputs[source["path"]] = source
meta = probe(args.input)
if not meta.get("video"):
die("input has no video stream")
audio_streams = meta.get("audio_streams") or []
if audio_streams and not (0 <= args.audio_stream < len(audio_streams)):
die(f"--audio-stream {args.audio_stream}: input has {len(audio_streams)} audio stream(s), 0..{len(audio_streams) - 1}")
if args.audio_stream and not audio_streams:
die("--audio-stream needs an input with audio streams")
src_dur = meta["duration"] or 0.0
sw, sh = display_size(meta["video"])
if args.rotate in (90, 270):
sw, sh = sh, sw
has_audio = bool(meta.get("audio"))
vf: List[str] = []
af: List[str] = []
pre_input: List[str] = []
post: List[str] = []
factor = 1.0
retimed = False
extra = {}
tc_first = None
regridded = False
out_seek = 0.0
kept = None
if args.rotate == 90:
vf.append("transpose=1")
elif args.rotate == 270:
vf.append("transpose=2")
elif args.rotate == 180:
vf.append("transpose=2,transpose=2")
if args.flip == "h":
vf.append("hflip")
elif args.flip == "v":
vf.append("vflip")
orient = list(vf)
if args.duration:
target = time_arg(args.duration, "--duration", meta["video"].get("fps") if meta.get("video") else None)
if target <= 0:
die("target duration must be > 0")
refuse_still(meta, args.input, "--duration retimes or trims the input's length, and a still has none")
src_dur = (meta.get("duration") or 0.0) if STATE.dry_run else input_length(meta)
length_unknown = STATE.dry_run and src_dur <= 0
rate = (audio_streams[args.audio_stream].get("sample_rate") if has_audio and audio_streams else None)
if args.method == "speed":
factor = 1.0 if length_unknown else src_dur / target
if factor > args.max_speed or factor < 1 / args.max_speed:
die(f"required speed factor {factor:.2f}x exceeds --max-speed {args.max_speed}x; use --method trim or raise the limit")
if factor > SPEED_WARN_FACTOR or factor < 1 / SPEED_WARN_FACTOR:
warn(f"speed {factor:.2f}x: the whole picture and sound are retimed to reach "
f"{target:.2f}s and nothing is cut; a retime beyond {SPEED_WARN_FACTOR:g}x "
"is reported because it is easy to ask for by accident (speed is the "
"default --method) when a cut was wanted -- if it was, use --method trim "
"or cut first (silence.py removes dead air)",
"large_speed_change", factor=round(factor, 3), threshold=SPEED_WARN_FACTOR,
source_duration=round(src_dur, 3), target_duration=round(target, 3))
retimed = abs(factor - 1.0) > 1e-4
if retimed:
vf.append(f"setpts={1/factor:.8f}*PTS")
src_fps = meta["video"].get("fps") or 30.0
if factor < 1.0 and args.smooth == "interpolate":
vf.append(f"minterpolate=fps={args.fps or src_fps:g}:mi_mode=mci:mc_mode=aobmc:me_mode=bidir:vsbmc=1")
elif factor < 1.0 and args.smooth == "blend":
vf.append(f"fps={src_fps:g}")
vf.append("tblend=all_mode=average")
elif not args.fps:
vf.append(frame_durations(meta, delivered_rate(meta) or frame_rate(meta) or src_fps))
regridded = True
if has_audio:
af.append(atempo_chain(factor, rate))
post += ["-t", f"{target:.3f}" if af else length_output_t(target, rate, runs_on=True) if rate
else f"{target:.3f}" if retimed or args.fps or has_audio else picture_output_t(target, meta)]
STATE.duration_hint = target
else:
if target < src_dur:
start = (src_dur - target) / 2 if args.from_center else 0.0
kept = (start, target)
m = min(SEEK_MARGIN, round(start, 3))
pre_input += ["-ss", f"{start - m:.3f}"] if round(start, 3) > 0 else []
keep = (picture_output_t(target, meta) if not rate and not args.fps and not args.from_center
else length_output_t(target, rate, runs_on=True))
post += (["-ss", f"{m:.3f}"] if m > 0 else []) + ["-t", keep]
out_seek = round(m, 3) if m > 0 else 0.0
v0, rate = stream_starts(meta)[0], frame_rate(meta)
tc_first = grid_at_or_after(max(round(start, 3), v0), v0, rate) - v0
elif not length_unknown:
info(f"source ({src_dur:.2f}s) is already shorter than {target:.2f}s; trim does nothing")
speed_unknown = length_unknown and args.method == "speed"
extra["timing"] = {
"method": args.method,
"source_duration": None if length_unknown else src_dur,
"target_duration": target,
"speed_factor": None if speed_unknown else factor,
"retimed": None if speed_unknown else retimed,
}
if args.fps:
vf.append(f"fps={args.fps:g}")
elif meta["video"].get("variable_frame_rate_suspected"):
info("source looks variable-frame-rate; conforming to constant fps automatically")
if not regridded:
vf.append(cfr_filter(meta, seek=out_seek))
geometry = None
crop_window = None
if args.aspect or args.width or args.height:
out_w, out_h = frame_size(parse_aspect(args.aspect) if args.aspect else None, args.width, args.height, sw, sh)
if args.fit == "crop" and sw and sh:
sc_w = max(out_w, (2 * out_h * sw + sh) // (2 * sh))
sc_h = max(out_h, (2 * out_w * sh + sw) // (2 * sw))
mx, my = (-(-(sc - o) // 4) * 4 for sc, o in ((sc_w, out_w), (sc_h, out_h)))
ox, oy = (int(m * f / 2 + 0.5) * 2 for m, f in ((mx, args.crop_x), (my, args.crop_y)))
for axis, m, f, got in (("x", mx, args.crop_x, ox), ("y", my, args.crop_y, oy)):
if abs(m * f - got) > 1e-9:
note(f"--crop-{axis} {f:g}: crop offset {got}px, not {m * f:g}px: the offset is kept even "
f"(4:2:0 chroma), on a {m}px margin")
vf.append(f"scale={out_w + mx}:{out_h + my}")
vf.append(f"crop={out_w}:{out_h}:{ox}:{oy}")
kx, ky = sw / (out_w + mx), sh / (out_h + my)
geometry = (vf[-2:], (out_w + mx) / sw, {"left": round(ox * kx), "right": round((mx - ox) * kx),
"top": round(oy * ky), "bottom": round((my - oy) * ky)})
rel_x, rel_y = mx / (out_w + mx), my / (out_h + my)
if rel_x > 0 or rel_y > 0:
crop_window = (("x", ox / (out_w + mx), (ox + out_w) / (out_w + mx)) if rel_x >= rel_y
else ("y", oy / (out_h + my), (oy + out_h) / (out_h + my)))
elif args.fit == "crop":
vf.append(f"scale={out_w}:{out_h}:force_original_aspect_ratio=increase")
vf.append(f"crop={out_w}:{out_h}:(in_w-out_w)*{args.crop_x:g}:(in_h-out_h)*{args.crop_y:g}")
elif args.fit == "blur":
darken = 0.0 if meta["video"].get("bt2020_or_hdr") else BLUR_DARKEN
if not darken:
info("--fit blur: HDR source, so the blurred background is not dimmed "
"(an eq on PQ/HLG code values is not the -15% dim it is on SDR); "
"run color.py --to-sdr first for the SDR look")
vf.append(pad_filters(out_w, out_h, "blur", args.pad_color, args.pad_blur, darken))
geometry = ([pad_filters(out_w, out_h, "blur", args.pad_color, args.pad_blur, darken, blank=True)], None, None)
else:
vf.append(pad_filters(out_w, out_h, args.pad_fill, args.pad_color, args.pad_blur, meta=meta))
geometry = ([pad_filters(out_w, out_h, args.pad_fill, args.pad_color, args.pad_blur, meta=meta, blank=True)], None, None)
vf.append("setsar=1")
if square_pixels(meta["video"]):
vf.insert(0, square_pixels(meta["video"]))
note(square_pixels_note(meta["video"]))
out_rate = args.fps or delivered_rate(meta)
src_fps = meta["video"].get("fps")
rate_changed = bool(out_rate and src_fps and exact_rate(float(out_rate)) != exact_rate(float(src_fps)))
relabel = tc_first is not None or rate_changed
if relabel:
post += output_timecode_args(meta, tc_first or 0.0, out_rate)
output = args.output or default_output(args.input, "fit")
cmd = ffmpeg_base() + pre_input + ["-i", args.input]
if vf:
cmd += ["-vf", ",".join(vf)]
if af:
cmd += ["-af", ",".join(af)]
cmd += ["-map", "0:v:0"]
if has_audio:
cmd += ["-map", f"0:a:{args.audio_stream}"]
cmd += video_args(meta, args.crf, args.preset)
cmd += cfr_args(meta, args.fps) if not args.fps else []
if has_audio:
cmd += aac_args()
else:
cmd += ["-an"]
cmd += post
if retimed or "-ss" in pre_input:
run(cmd + [output])
dropped_streams = bool(meta.get("subtitle_streams") or meta.get("data_streams"))
else:
dropped_streams = run_keeping_subtitles(cmd, output, relabel_timecode=relabel)
result = probe(output, role="output")
msg = f"wrote {output} ({fmt_secs(result['duration'])}, {result['video']['width']}x{result['video']['height']})"
if retimed:
msg += f", speed {factor:.3f}x"
info(msg)
if geometry and not STATE.dry_run:
extra["picture"] = measure_picture(geometry, meta, sw, sh, result["video"], sized=bool(args.width or args.height))
if crop_window and not STATE.dry_run:
k0, klen = kept if kept else (0.0, src_dur or (meta.get("duration") or 0.0))
extra["crop_check"] = check_crop(args.input, orient, sw, sh, crop_window, k0, klen)
emit(output, dropped_non_av_streams=dropped_streams, **extra)
return 0
if __name__ == "__main__":
sys.exit(main())