How to fit word to width with ffmpeg drawtext filter? A script takes a single word 3 to 11 characters long, draws it with a custom font and overlays on top of a video. The word should fit a certain width.

The animation involves pan and zoom that the word follows. Maybe this compositing job suits smth like After Effects, but the task is ffmpeg implementation. I made it work with the shortest 3-character long sample word and the longest 11-character one.

drawtext filter generates a transparent png with big margins around the text. zoompan filter does the zooming afterwards.

I determined the font size for 3- and 11-char sample words and tried linear interpolation to get font size, depending on the word length. This approach fails with some words, as the font has variable width letters, and "MMM" vs. "III" differs n times in width.

Is there a way in ffmpeg to fit a variable-width text to fixed dimensions?

Maybe some filter to detect a least-sized rectangle with non-transparent pixels? 

Plan-B works fine: bash function that calculates word length depending on each letter width in the particular font. Had to measure each letter width in Photoshop in pixels at 100pt font size.

Still wondering if there is a way ffmpeg could scale font size text to fit some fixed width.
There's no way to force the drawtext filter to fit the text in a certain width.

What you can do, is get the rendered text dimensions in a first pass and then run drawtext accordingly in 2nd pass, or crop and scale the output using the values from first pass.

For first pass,

ffmpeg -i video -vf drawtext=fontfile=path/to/font:fontsize=FinalSize:text='Lorem Ipsor' \
                   :x=0+0*print(tw):y=0+0*print(th) -vframes 1 -f null -


This will print the text at the top-left. The print statements will output

84.000000
14.000000


The first value is tw - the width, and the 2nd th - the height, in pixels.