I need to convert a bunch of video files using FFmpeg. I run a Bash file that converts all the files nicely, however there is a problem if a file converted is not in 16:9 format.
As I am fixing the size of the screen to -s 720x400, if the aspect ratio of the original is 4:3, FFmpeg creates a 16:9 output file, screwing up the aspect ratio.
Is there a setting that allows setting an aspect ratio as the main parameter, with size being adjusted (for example, by fixing an X or Y dimension only)?
-vf "scale=640:-1"
works great until you will encounter error
[libx264 # 0x2f08120] height not divisible by 2 (640x853)
So most generic approach is use filter expressions:
scale=640:trunc(ow/a/2)*2
It takes output width (ow), divides it by aspect ratio (a), divides by 2, truncates digits after decimal point and multiplies by 2. It guarantees that resulting height is divisible by 2.
Credits to ffmpeg trac
UPDATE
As comments pointed out simpler way would be to use -vf "scale=640:-2".
Credits to #BradWerth for elegant solution
For example:
1920x1080 aspect ratio 16:9 => 640x480 aspect 4:3:
ffmpeg -y -i import.media -aspect 16:9 scale=640x360,pad=640:480:0:60:black output.media
aspect ratio 16:9 , size width 640pixel => height 360pixel:
With final output size 640x480, and pad 60pixel black image (top and bottom):
"-vf scale=640x360,pad=640:480:0:60:black"
I've asked this a long time ago, but I've actually got a solution which was not known to me at the time -- in order to keep the aspect ratio, you should use the video filter scale, which is a very powerful filter.
You can simply use it like this:
-vf "scale=640:-1"
Which will fix the width and supply the height required to keep the aspect ratio. But you can also use many other options and even mathematical functions, check the documentation here - http://ffmpeg.org/ffmpeg.html#scale
Although most of these answers are great, I was looking for a command that could resize to a target dimension (width or height) while maintaining aspect ratio. I was able to accomplish this using ffmpeg's Expression Evaluation.
Here's the relevant video filter, with a target dimension of 512:
-vf "thumbnail,scale='if(gt(iw,ih),512,trunc(oh*a/2)*2)':'if(gt(iw,ih),trunc(ow/a/2)*2,512)'"
For the output width:
'if(gt(iw,ih),512,trunc(oh*a/2)*2)'
If width is greater than height, return the target, otherwise, return the proportional width.
For the output height:
'if(gt(iw,ih),trunc(ow/a/2)*2,512)'
If width is greater than height, return the proportional height, otherwise, return the target.
Use force_original_aspect_ratio, from the ffmpeg trac:
ffmpeg -i input.mp4 -vf scale=720:400:force_original_aspect_ratio=decrease output.mp4
If you are trying to fit a bounding box, then using force_original_aspect_ratio as per xmedeko's answer is a good starting point.
However, this does not work if your input video has a weird size and you are encoding to a format that requires the dimensions to be divisible by 2, resulting in an error.
In this case, you can use expression evaluation in the scale function, like that used in Charlie's answer.
Assuming an output bounding box of 720x400:
-vf "scale='trunc(min(1,min(720/iw,400/ih))*iw/2)*2':'trunc(min(1,min(720/iw,400/ih))*ih/2)*2'"
To break this down:
min(1,min(720/iw,400/ih) finds the scaling factor to fit within the bounding box (from here), constraining it to a maximum of 1 to ensure it only downscales, and
trunc(<scaling factor>*iw/2)*2 and trunc(<scaling factor>*iw/2)*2 ensure that the dimensions are divisible by 2 by dividing by 2, making the result an integer, then multiplying it back by 2.
This eliminates the need for finding the dimensions of the input video prior to encoding.
As ffmpeg requires to have width/height dividable by 2,
and I suppose you want to specify one of the dimensions, this would be the option:
ffmpeg -i input.mp4 -vf scale=1280:-2 output.mp4
you can use ffmpeg -i to get the dimensions of the original file, and use that in your commands for the encode. What platform are you using ffmpeg on?
If '-aspect x:y' is present and output file format is ISO Media File Format (mp4) then ffmpeg adds pasp-atom (PixelAspectRatioBox) into stsd-box in the video track to indicate to players the expected
aspect ratio. Players should scale video frames respectively.
Not needed to scale video before encoding or transcoding to fit it to the aspect ratio, it should be performed by a player.
The above answers are great, but most of them assume specific video dimensions and don't operate on a generic aspect ratio.
You can pad the video to fit any aspect ratio, regardless of specific dimensions, using this:
-vf 'pad=x=(ow-iw)/2:y=(oh-ih)/2:aspect=16/9'
I use the ratio 16/9 in my example. The above is a shortcut for just doing something more manual like this:
pad='max(iw,(16/9)*ih)':'max(ih,iw/(16/9))':(ow-iw)/2:(oh-ih)/2
That might output odd-sized (not even) video dimensions, so you can make sure the output is even like this:
pad='trunc(max(iw,(16/9)*ih)/2)*2':'trunc(max(ih,iw/(16/9))/2)*2':(ow-iw)/2:(oh-ih)/2
But really all you need is pad=x=(ow-iw)/2:y=(oh-ih)/2:aspect=16/9
For all of the above examples you'll get an error if the INPUT video has odd-sized dimensions. Even pad=iw:ih gives error if the input is odd-sized. Normally you wouldn't ever have odd-sized input, but if you do you can fix it by first using this filter: pad='mod(iw,2)+iw':'mod(ih,2)+ih'
Related
I am trying to encode a .mp4 video from a set of frames using FFMPEG using the libx264 codec.
This is the command I am running:
/usr/local/bin/ffmpeg -r 24 -i frame_%05d.jpg -vcodec libx264 -y -an video.mp4
I sometimes get the following error:
[libx264 # 0xa3b85a0] height not divisible by 2 (520x369)
After searching around a bit it seems that the issue has something to do with the scaling algorithm and can be fixed by adding a -vf argument.
However, in my case I don't want to do any scaling. Ideally, I want to keep the dimensions exactly the same as the frames. Any advice? Is there some sort of aspect ratio that h264 enforces?
The answer to the original question should not scale the video but instead fix the height not divisible by 2 error. This can be achieve using this filter:
-vf "pad=ceil(iw/2)*2:ceil(ih/2)*2"
Full command:
ffmpeg -i frame_%05d.jpg -vcodec libx264 \
-vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" -r 24 \
-y -an video.mp4
Basically, .h264 needs even dimensions so this filter will:
Divide the original height and width by 2
Round it up to the nearest pixel
Multiply it by 2 again, thus making it an even number
Add black padding pixels up to this number
You can change the color of the padding by adding filter parameter :color=white. See the documentation of pad.
For width and height
Make width and height divisible by 2 with the crop filter:
ffmpeg -i input.mp4 -vf "crop=trunc(iw/2)*2:trunc(ih/2)*2" output.mp4
If you want to scale instead of crop change crop to scale.
For width or height
Using the scale filter. This will make width 1280. Height will be automatically calculated to preserve the aspect ratio, and the width will be divisible by 2:
ffmpeg -i input.mp4 -vf scale=1280:-2 output.mp4
Similar to above, but make height 720 and automatically calculate width:
ffmpeg -i input.mp4 -vf scale=-2:720 output.mp4
You can't use -2 for both width and height, but if you already specified one dimension then using -2 is a simple solution.
If you want to set some output width and have output with the same ratio as original
scale=720:-1
and not to fall with this problem then you can use
scale="720:trunc(ow/a/2)*2"
(Just for people searching how to do that with scaling)
The problem with the scale solutions here is that they distort the source image/video which is almost never what you want.
Instead, I've found the best solution is to add a 1-pixel pad to the odd dimension. (By default, the pading is black and hard to notice.)
The problem with the other pad solutions is that they do not generalize over arbitrary dimensions because they always pad.
This solution only adds a 1-pixel pad to height and/or width if they are odd:
-vf pad="width=ceil(iw/2)*2:height=ceil(ih/2)*2"
This is ideal because it always does the right thing even when no padding is necessary.
It's likely due to the the fact that H264 video is usually converted from RGB to YUV space as 4:2:0 prior to applying compression (although the format conversion itself is a lossy compression algorithm resulting in 50% space savings).
YUV-420 starts with an RGB (Red Green Blue) picture and converts it into YUV (basically one intensity channel and two "hue" channels). The Hue channels are then subsampled by creating one hue sample for every 2X2 square of that hue.
If you have an odd number of RGB pixels either horizontally or vertically, you will have incomplete data for the last pixel column or row in the subsampled hue space of the YUV frame.
LordNeckbeard has the right answer, very fast
-vf scale=1280:-2
For android, dont forget add
"-preset ultrafast" and|or "-threads n"
You may also use bitand function instead of trunc:
bitand(x, 65534)
will do the same as trunc(x/2)*2 and it is more transparent in my opinion.
(Consider 65534 a magical number here ;) )
My task was to scale automatically a lot of video files to half resolution.
scale=-2,ih/2 lead to slightly blurred images
reason:
input videos had their display aspect ratio (DAR) set
scale scales the real frame dimensions
during preview the new videos' sizes have to be corrected using DAR which in case of quite low-resoution video (360x288, DAR 16:9) may lead to blurring
solution:
-vf "scale='bitand(oh*dar, 65534)':'bitand(ih/2, 65534)', setsar=1"
explanation:
output_height = input_height / 2
output_width = output_height * original_display_aspect_ratio
both output_width and output_height are now rounded to nearest smaller number divisible by 2
setsar=1 means output_dimensions are now final, no aspect ratio correction should be applied
Someone might find this helpful.
I am trying to generate multilple variants of videos in my library (Mp4 formats) and have renditions planned ranging from 1080p to 240p and popular sizes in between. For that I am taking a video with a AxB resolution and then running through a code (on bash) which scales them to desired following sizes -
426x240
640x360
842x480
1280x720
1920x1080, with different bitrates of course, and then saves as Mp4 again.
Now, this works just fine if source video has height and width divisible by 2, but code breaks on the following line for the videos with odd width and height:
-vf scale=w=${width}:h=${height}:force_original_aspect_ratio=decrease"
Where 'width' and 'height' are the desired (and hardcoded) for every iteration: E.g. "426x240", and "640x360"
The Error:
[libx264 # 00000187da2a1580] width not divisible by 2 (639x360)
Error initializing output stream 1:0 -- Error while opening encoder for output stream #1:0 - maybe incorrect parameters such as bit_rate, rate, width or height
Now approaches those are explained in this one doesn't work for me since I am scaling - FFMPEG (libx264) "height not divisible by 2"
And, I tried this one too but it seems all qualities are getting the same size -ffmpeg : width not divisible by 2 (when keep proportions)
This is how I tried to use this one: scale='bitand(oh*dar,65534)':'min(${height},ih)'
Kindly suggest how to solve this, keeping in view that:
1. I have a very large library and I can't do manual change for every video
2. I need to scale the video and keep the aspect ratio
Thanks!
PS: [Edit] One way that I can see is padding all of the odd height/ weight videos using a second script in advance. This however doubles my work time and load. I would prefer to keep it in single script. This is the script I see that I can use for padding:
```ffmpeg -r 24 -i -vcodec libx264 -y -an -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2"`` (from: FFMPEG (libx264) "height not divisible by 2")
You can insert either insert a pad or crop filter after the scale, depending on whether you prefer dimensions to increase or decrease respectively.
e.g. for pad,
scale=w=...,pad='iw+mod(iw\,2)':'ih+mod(ih\,2)'"
e.g. for crop,
scale=w=...,crop='iw-mod(iw\,2)':'ih-mod(ih\,2)'"
I have some videos taken of a display, with the camera not perfectly oriented, so that the result shows a strong trapezoidal effect.
I know that there is a perspective filter in ffmpeg https://ffmpeg.org/ffmpeg-filters.html#perspective, but I'm too dumb to understand how it works from the docs - and I cannot find a single example.
Somebody can show me how it works?
The following example extracts a trapezoidal perspective section from an input Matroska video to an output video.
An estimated coordinate had to be inserted to complete the trapezoidal pattern (out-of-frame coordinate x2=-60,y2=469).
Input video frame was 1280x720. Pixel interpolation was specified linear, however that is the default if not specified at all. Cubic interpolation bloats the output with NO apparent improvement in video quality. Output video frame size will be of the input video's frame size.
Video output was viewable but rough quality due to sampling error.
ffmpeg -hide_banner -i input.mkv -lavfi "perspective=x0=225:y0=0:x1=715:y1=385:x2=-60:y2=469:x3=615:y3=634:interpolation=linear" output.mkv
You can also make use of ffplay (or any player which lets you access ffmpeg filters, like mpv) to preview the effect, or if you want to keystone-correct a display surface.
For example, if you have your TV above your fireplace mantle and you're sitting on the floor looking up at it, this will un-distort the image to a large extent:
ffplay video.mkv -vf 'perspective=W*.1:0:W*.9:0:-W*.1:H:W*1.1:H'
The above expands the top by 20% and compresses the bottom by 20%, cropping the top and infilling the bottom with the edge pixels.
Also handy for playing back video of a building you're standing in front of with the camera pointed up around 30 degrees.
We have some videos that have different scale and aspect ratio and we'd like to convert them to a fix 640x480 size (4/3 ar letterbox padding if necessary).
Two sizes are occurs very often: 853 × 480, 1280 × 720.
I made some research and tries before write this question but didn't get the expected result.
For example:
ffmpeg -i video.mp4 -vf "scale=640:480,pad=640:480:(ow-iw)/2:(oh-ih)/2,setdar=4/3" -c:a copy output.mp4
setdar=4/3 seems to required because if I omitted the result remain the original aspect ratio.
Are there any solution for different size conversion?
The generic filterchain for fitting a video in a WxH canvas is
"scale=iw*sar:ih,scale=640:480:force_original_aspect_ratio=decrease,pad=640:480:-1:-1"
The first scale filter makes sure the video is not kept anamorphic. If you know the video is square-pixels, you can skip it. The 2nd filter fits the video in a canvas of 640x480 using the force_original_aspect_ratio option.
In using the scale filter with ffmpeg, I see many examples similar to this:
ffmpeg -i input.mov -vf scale="'if(gt(a,4/3),320,-2)':'if(gt(a,4/3),-2,240)'" output.mov
What does the variable a signify?
From the ffmpeg scale options docs.
a The same as iw / ih
where
iw Input Width ih Input Height
My guess after reading https://trac.ffmpeg.org/wiki/Scaling%20(resizing)%20with%20ffmpeg is that a is the aspect ratio of the input file.
The example given on the webpage gives you an idea how to use it:
Sometimes there is a need to scale the input image in such way it fits
into a specified rectangle, i.e. if you have a placeholder (empty
rectangle) in which you want to scale any given image. This is a
little bit tricky, since you need to check the original aspect ratio,
in order to decide which component to specify and to set the other
component to -1 (to keep the aspect ratio). For example, if we would
like to scale our input image into a rectangle with dimensions of
320x240, we could use something like this:
ffmpeg -i input.jpg -vf scale="'if(gt(a,4/3),320,-1)':'if(gt(a,4/3),-1,240)'"
output_320x240_boxed.png
In the ffmpeg wiki "Scaling (resizing) with ffmpeg", they use this example:
ffmpeg -i input.jpg -vf scale="'if(gt(a,4/3),320,-1)':'if(gt(a,4/3),-1,240)'" output.png
The purpose of the gt(a,4/3) is, as far as I can tell, to determine the orientation (portrait or landscape) of the video (or image, in this case).
This wouldn't work for some strange aspect ratios (7:6, for an example, where gt(a,4/3) would incorrectly turn false.
It seems to me better to use the height and width of the video, so the above line would instead be:
ffmpeg -i input.jpg -vf scale="'if(gt(iw,ih),320,-1)':'if(gt(iw,ih),-1,240)'" output.png