FFmpeg Drawtext Fade In and Out Equation
This article explains how to use mathematical expressions within the
FFmpeg drawtext filter to seamlessly fade text in and out
over a specific timeframe. You will learn the exact equations to control
the alpha (opacity) parameter, enabling professional text
transitions directly from the command line without requiring external
video editing software.
To fade text in and out in FFmpeg, you must dynamically calculate the
alpha parameter of the drawtext filter based
on the current timestamp of the video (t). This is achieved
using nested if conditions that transition the opacity from
0 (invisible) to 1 (fully visible), and back
to 0.
The Fade Equation Template
The standard mathematical formula to fade text in and out requires four time markers (in seconds): * \(T_1\): The time the text starts to fade in. * \(T_2\): The time the text becomes fully visible. * \(T_3\): The time the text starts to fade out. * \(T_4\): The time the text becomes fully invisible.
Using these variables, the generic equation for the
alpha parameter is:
alpha='if(lt(t, T1), 0, if(lt(t, T2), (t-T1)/(T2-T1), if(lt(t, T3), 1, if(lt(t, T4), 1-(t-T3)/(T4-T3), 0))))'
Step-by-Step Example
Suppose you want to overlay text on a video with the following timing: * Start fading in at 2 seconds (\(T_1 = 2\)) * Become fully visible at 3 seconds (\(T_2 = 3\), meaning a 1-second fade-in) * Start fading out at 7 seconds (\(T_3 = 7\)) * Become fully invisible at 8 seconds (\(T_4 = 8\), meaning a 1-second fade-out)
Plugging these numbers into the template gives you this expression:
alpha='if(lt(t,2),0,if(lt(t,3),(t-2)/1,if(lt(t,7),1,if(lt(t,8),1-(t-7)/1,0))))'
Complete FFmpeg Command
Here is how to apply this equation inside a complete FFmpeg command:
ffmpeg -i input.mp4 -vf "drawtext=text='Your Text Here':fontcolor=white:fontsize=48:x=(w-text_w)/2:y=(h-text_h)/2:alpha='if(lt(t,2),0,if(lt(t,3),(t-2)/1,if(lt(t,7),1,if(lt(t,8),1-(t-7)/1,0))))'" -codec:a copy output.mp4How the Logic Works
if(lt(t,2),0, ...): If the current video time (t) is less than 2 seconds, the alpha is0(hidden).if(lt(t,3),(t-2)/1, ...): If the time is between 2 and 3 seconds, it calculates a linear ramp from0to1. For example, at 2.5 seconds, the calculation is(2.5-2)/1 = 0.5opacity.if(lt(t,7),1, ...): If the time is between 3 and 7 seconds, the alpha remains solid at1.if(lt(t,8),1-(t-7)/1,0): If the time is between 7 and 8 seconds, it calculates a linear downward ramp from1to0. Once the time exceeds 8 seconds, the alpha defaults to0.