FFMPEG - Width/ Height Not Divisible by 2 (Scaling to Generate MBR Output) - ffmpeg

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)'"

Related

Tile a set of images and pan/scroll across them using ffmpeg

I have a set of very large images that I would like to tile horizontally and pan across using ffmpeg.
The images are relatively large and can be created using magick using:
magick convert -compress lzw -size 90000x800 xc:"rgb(160,160,255)" test001.tif
... and so on
The command I've gotten closest with is the following:
ffmpeg -loop 1 -i test%03d.tif -vf "tile=4x1,scroll=horizontal=0.05,crop=800:600:0:0,format=yuv420p" -t 10 output.mp4
The issues with the above command:
it is very very slow (0.3 frames/sec)
the animation loops because i picked an arbitrary 10 sec duration (not sure how to get it to stop at end of image)
high memory usage, i'm not sure if ffmpeg is creating the tiled image first, and then going to process the video, or if there's a way to only access the areas of the tiffs that are needed for each frame
Any pointers for how scroll/pan across multiple input images would be greatly appreciated!
Start with 90000x800 images (hundreds of them), use input framerate of 1 fps (for the ease of presentation), let M = 90000
step 1: tile=2x1:overlap=1 appends the next image to the previous: [Img1|Img2],[Img2|Img3], [Img3|Img4]...
step 2: fps=N increases the frame rate to N fps by repeating each tiled frame N times
step 3: crop=w=1280:h=800:x=mod(n,N)*M/N:y=0 positions the current video frame on the image then crops out the rest. On frame n=N, the next pair of images will be set so it resets the frame position to 0.
ffmpeg -r 1 -i test%03d.tif \
-vf 'tile=2x1:overlap=1, \
fps=N, \
crop=w=1280:h=800:x=mod(n,N)*M/N:y=0' \
-pix_fmt yuv420p output.mp4
Pick your number for N and substitute the symbols with actual numbers, and you should be ready to roll (I hope...)
But now, how do you pick N? It'll depends on your input frame rate (which is preliminary set to 1), your desired output frame rate, and the image transition time...
Say you want each image to stay on screen for 2 seconds and the output frame rate to be 30 fps, then each image should appear on 2*30=60 frames. So, set N = 60 and the input frame rate 30/60 = 0.5.
I have not tested the command, so give it a try and I'd be happy to troubleshoot if not working. Also, I'm curious if it's reasonably fast.
===============================
Update: requested to change input to 800x800 images instead of 90000x800.
Change tile and crop as follows:
ffmpeg -r 1 -i test%03d.tif \
-vf 'tile=3x1:overlap=2, \
fps=N, \
crop=w=1280:h=800:x=mod(n,N)*800/N:y=0' \
-pix_fmt yuv420p output.mp4
Also N needs to be readjusted by Nnew = 800/90000 * N or thereabouts.

Trying to convert multiple images into a video [duplicate]

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.

Transcode any video to mp4 with max. 800 width or max. 800 height + watermark

I need a ffmpeg command that works with every video (with audio) format / type to encode it to h264 mp4. The output may have a maximum width of 800px and a maximum height of 800px. It would also be necesary to add a watermark in to bottom right corner... Is there a way to get all those things done with a single command line? Even if it's WMV, MOV, 3gp and whatever filetype is beeing used?
Use
ffmpeg -i video -i watermark
-filter_complex "[0]scale=min(800,iw):min(800,ih):force_original_aspect_ratio=decrease,
scale=2*trunc(iw/2):2*trunc(ih/2)[v];
[v][1]overlay=x=W-w-10:y=H-h-10" output.mp4
The first scale filter fits the video to within a 800x800 canvas but proportionally. The 2nd scale filter makes sure that the video has even dimensions - required for standard H264 playback compatibility.
The image overlay is overlaid at bottom-right corner, offset by 10 pixels from both edges.

How to have ffmpeg calculate the width after modifying by set height ratio?

After finding the resolution was the source of all my webm to MP4 codec conversion errors on my Android. I came across another problem. To break down my question:
What all MP4 resolutions are supported on most devices? I know they go by p from certain height value for them to work. 720p /?X720 for example.
Is there an easier way to calculate the width based from the height change while keeping the ratio?
ffmpeg -i old.webm -t 00:00:03 -s 320x240 new.mp4
I currently use the -s setting perimeter from my testing example.
The standard ratio for widescreens is 16:9 and the typical list of resolutions used is
256x144, 426x240, 640x360, 854x480, 960x540, 1024x576, 1280x720, 1920x1080, 2560x1440, 3840x2160
If you directly use the scale filter, you can tell ffmpeg to maintain the aspect ratio:
ffmpeg -i old.webm -t 00:00:03 -vf scale=-2:240 new.mp4
In the command above, scale=-2:240 tells ffmpeg to scale to height 240, select a width so that aspect ratio is maintained, and then adjust that value so that the width and height is a multiple of 2 (required for H.264/MP4). If you did not care whether the value was even, you could just use -1.

Maintaining aspect ratio with FFmpeg

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'

Resources