Tell me more ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I need to fit videos to 640x360 (the maximum my phone's player can handle), while also preserving aspect ratio, but I also want the video to be unchanged if it is smaller than 640x360 (no point in up-scaling it after all).

Is there a way to get this behavior using ffmpeg's command line?

share|improve this question
I don't think this can be done solely in ffmpeg, but if you're willing to script it, it can definitely be done. – evilsoup Mar 16 at 17:15
I've already scripted it, but I wanted to clean up my code in case it' s not needed. – satuon Mar 16 at 17:16
It's probably possible with a scale filter that uses functions such as min(…) but most definitely easier with a simple script that parses the dimensions. See my command here for an example of what can be done: superuser.com/questions/547296/… – slhck Mar 16 at 18:47

1 Answer

up vote 1 down vote accepted

First, define the width, height and aspect ratio of your output. This will save us some typing.

width=640; height=360
aspect=$( bc <<< "scale=3; $width / $height") # <= floating point division

Now, let's apply the super complex filter command that Jim Worrall wrote:

ffmpeg -i input.mp4 -vf "scale = min(1\,gt(iw\,$width)+gt(ih\,$height)) * (gte(a\,$aspect)*$width + \
lt(a\,$aspect)*(($height*iw)/ih)) + not(min(1\,gt(iw\,$width)+gt(ih\,$height)))*iw : \
min(1\,gt(iw\,$width)+gt(ih\,$height)) * (lte(a\,$aspect)*$height + \
gt(a\,$aspect)*(($width*ih)/iw)) + not(min(1\,gt(iw\,$width)+gt(ih\,$height)))*ih" \
output.mp4

I won't really go into explaining what this all does, but basically you can feed it any video, and it will only downscale, not upscale. If you're up for it you can dissect the filter into its individual expressions. It might be possible to shorten this, but it works like that as well.

share|improve this answer
+1 but that is a truly horrific command :P – evilsoup Mar 19 at 21:33
I know right? I spent ten minutes trying to break it into logical parts and then inserting some values but I gave up. It's a little old and maybe it'd be possible to write it much more concisely than this though. – slhck Mar 19 at 21:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.