How to get width of the video and scale another video to that width using ffmpeg?

I'm using ffmpeg to stack two videos vertically. They might be different size so I need to scale them to same size. I have found following commands.

First one works for different sizes (but won't scale to proper size):

ffmpeg -i input1 -i input2 -filter_complex '[0:v]pad=iw:ih*2[int];[int][1:v]overlay=0:H/2[vid]' -map [vid] -c:v libx264 -crf 23 -preset veryfast output

Second one works if videos have same width and same pixel format:

ffmpeg -i input1 -i input2 -filter_complex vstack output

How to get width of first input inside complex filter argument so second input could be scaled to same width? What would be the command to do so? I would prefer vstack filter since it should be faster than combination of pad and overlay.


You need to use the scale2ref filter.

ffmpeg -i input1 -i input2
 -filter_complex '[1][0]scale2ref[2nd][ref];[ref][2nd]vstack'
 -map [vid] -c:v libx264 -crf 23 -preset veryfast output

Note that this only works well if the aspect ratios of both the videos are the same. If not, and you know the aspect ratio of the 2nd video, use [1][0]scale2ref=iw:iw*(H/W)[2nd][ref] where (H/W) should be replaced with the ratio of the height to width of the 2nd video.


With a build of a recent git version of ffmpeg, a simplified version is possible,

ffmpeg -i input1 -i input2
 -filter_complex '[1][0]scale2ref=oh*mdar:ih[2nd][ref];[ref][2nd]vstack'
 -map [vid] -c:v libx264 -crf 23 -preset veryfast output

This will automatically preserve the 2nd input's aspect ratio.