Use the FFmpeg drawtext filter with the text=%{localtime} expression to overlay a dynamic clock on your video. This method requires no external images or complex scripting, relying instead on built-in time formatting capabilities to render accurate timestamps directly onto the video frames during encoding.
Understanding the Drawtext Filter
The core of this solution lies in thedrawtext video filter. While many users attempt to use static text overlays, a videolog clock must update every second to remain useful for timestamping events. The drawtext filter supports expressions that are evaluated per frame, allowing us to pull the current system time dynamically.
To implement this, you need to understand the basic syntax of the filter within an FFmpeg command line. The general structure involves adding -vf "drawtext=..." to your input and output specifications. The critical component is the text parameter, which accepts format strings similar to those used in C's printf function. By using the special variable %{localtime}, FFmpeg automatically inserts the local date and time into the text string.
This approach is superior to pre-rendering images because it adapts to any duration of video without manual intervention. It also ensures that the time displayed matches the system clock at the moment of processing, which is crucial for logs where precise timing matters. If you have previously struggled with color extraction issues in other FFmpeg tasks, note that drawtext handles its own rendering context, so standard color space conversions do not interfere with the text visibility unless explicitly misconfigured. For more details on handling visual artifacts, see Fixing FFmpeg Color Number Extraction Issue.
Constructing the Command Line
Building the correct command requires careful attention to escaping characters and setting positional parameters. A typical command starts with specifying the input file and the desired output format. You then append the video filter option followed by the drawtext configuration. Here is a robust example command:ffmpeg -i input.mp4 -vf "drawtext=text='%{localtime}':fontcolor=white:fontsize=24:x=w-tw-10:y=h-th-10" output.mp4
Let's break down the key parameters used here:
- text='%{localtime}': This sets the content of the text. The single quotes ensure that the shell does not interpret the curly braces as variables before passing them to FFmpeg.
- fontcolor=white: Defines the color of the text. White is standard for readability against most backgrounds, but you can use hex codes like
fontcolor=0xFFFFFF. - fontsize=24: Sets the size of the font. Adjust this based on your video resolution; larger videos may require bigger fonts to remain legible.
- x=w-tw-10: Positions the text horizontally.
wis the width of the video, andtwis the width of the text. Subtracting the text width from the video width places it at the far right, minus 10 pixels for padding. - y=h-th-10: Positions the text vertically.
his the height of the video, andthis the height of the text. This places the clock in the bottom-right corner.
x=10:y=10. For center alignment, you would use x=(w-tw)/2:y=(h-th)/2. These mathematical expressions are evaluated per frame, ensuring the clock stays centered even if the video dimensions change due to scaling filters applied elsewhere in the chain.
Customizing Time Format
While%{localtime} provides a default human-readable format (usually YYYY-MM-DD HH:MM:SS), you might need a specific layout for your videolog. You can customize this by appending format specifiers after the variable name, separated by a colon.
For example, to display only the time in a 24-hour format, use:
text='%{localtime:%H:%M:%S}'
This will result in output like 14:30:05. If you want the full date and a custom separator, such as 2023-10-27 | 14:30:05, you can mix literal strings with variables:
text='%{localtime:%Y-%m-%d} | %{localtime:%H:%M:%S}'
Note that each instance of %{localtime} evaluates independently. In high-speed scenarios, there is a negligible chance of a one-second discrepancy between the two calls, but for standard videologging, this is imperceptible. Combining them into a single call with format specifiers is generally safer and cleaner.
Handling Font Availability
A common pitfall occurs when FFmpeg cannot find the specified font. By default, FFmpeg uses a built-in fallback font, but it often looks generic or lacks proper glyph support for certain characters. To specify a custom font, add thefontfile parameter to your filter string.
drawtext=text='%{localtime}':fontfile=/path/to/font.ttf:fontsize=24:fontcolor=white
Ensure the path to the .ttf file is absolute or relative to the working directory. On Linux systems, fonts are typically located in /usr/share/fonts. On Windows, they are in C:\Windows\Fonts. If you encounter errors stating that the font could not be loaded, verify the path and ensure the font file is readable by the user running the FFmpeg process.
For troubleshooting other visual encoding issues, such as those related to animated GIFs which share similar rendering constraints, check out Creating Animated GIF Images.
Troubleshooting Common Issues
Even with a correct command, users may face several challenges. Here are the most frequent problems and their solutions. Text Not Appearing Check your coordinate calculations. Ifx or y values place the text outside the video frame boundaries, it will be rendered off-screen. Use x=0:y=0 temporarily to verify if the text appears in the top-left corner. If it does, adjust your padding values.
Black Box Behind Text
Some versions of FFmpeg or specific codecs may render a black background behind the text, obscuring the video underneath. To fix this, ensure you are not accidentally enabling alpha channel blending incorrectly. Usually, simply ensuring the fontcolor is opaque (not transparent) resolves this. If you need transparency, use fontcolor=0x000000AA where AA is the alpha value in hex.
Performance Lag
Rendering text on every frame adds computational overhead. If you are processing 4K video on an older machine, you might notice slower encoding speeds. This is normal. Using hardware acceleration flags (like -hwaccel vaapi) can help mitigate this, though software rendering of drawtext remains CPU-bound.
Incorrect Time Zone
The localtime variable uses the system's local time zone settings. If your server or computer is set to UTC, the clock will show UTC time. To force a specific time zone, you can use the strftime function with environment variables, but this is complex. A simpler workaround is to set the system time zone before running the command or use %{gmtime} if UTC is preferred.
Integrating with Other Filters
You can combinedrawtext with other video filters using commas. For instance, if you want to blur the background slightly to make the white text pop, you can chain filters:
-vf "boxblur=2:4,drawtext=text='%{localtime}':fontcolor=black:fontsize=24:x=w-tw-10:y=h-th-10"
In this example, the boxblur filter is applied first, followed by the text drawing. The order matters: the text is drawn on top of the blurred video. This technique enhances readability significantly, especially for busy video content. However, be aware that chaining multiple heavy filters increases processing time. Always test with a short clip before applying the full pipeline to long recordings.
For audio-related integrations, such as merging audio tracks while preserving these visual edits, refer to Merging Three Audio Files into One: A Tech Support Guide.
Frequently Asked Questions
Can I use drawtext to display a static timestamp instead of a live clock?
Yes, replace%{localtime} with a fixed string enclosed in quotes, such as text='Log Start'. This renders the same text on every frame, which is useful for titles or watermarks that should not change over time.
Why is my clock updating too slowly or appearing frozen?
FFmpeg evaluates expressions per frame. If your video has a low frame rate (e.g., 1 FPS), the clock will only update once per second, which is correct. However, if the text appears to jump or stutter, it may be due to codec keyframe intervals. Ensure you are using a standard frame rate like 30 or 60 FPS for smooth updates.How do I change the font style to bold or italic?
Standard TrueType fonts do not always support bold or italic styles via simple flags in FFmpeg. Instead, install separate font files for bold and italic variants (e.g.,Font-Bold.ttf) and switch the fontfile parameter accordingly, or use a font that includes all styles in a single file with proper metadata.
Does this method work with streaming outputs like RTMP?
Yes, thedrawtext filter works with any output container supported by FFmpeg, including network streams. Simply replace the output file path with your stream URL (e.g., rtmp://server/live/key). The performance impact remains the same, so monitor your CPU usage during live streaming.
Can I animate the clock moving across the screen?
Absolutely. You can use thet variable in the x or y coordinates to create motion. For example, x='if(gt(t,10),100,x)' keeps the x-position constant until 10 seconds have passed, then jumps to 100 pixels. This allows for complex entrance animations synchronized with the video timeline.