How to Render RTL Text in FFmpeg Drawtext

Rendering right-to-left (RTL) languages like Arabic or Hebrew in FFmpeg using the drawtext filter requires specific configuration, as standard FFmpeg builds often render these scripts left-to-right or with disconnected characters. To display RTL text correctly, FFmpeg must be compiled with external libraries that handle bidirectional text layout and font shaping. This guide walk you through verifying your FFmpeg installation, selecting the correct parameters, and executing the command to display RTL text seamlessly.

Step 1: Verify FFmpeg Library Support

To render RTL languages properly, FFmpeg requires two crucial external libraries: * FriBidi (libfribidi): Handles the bidirectional (BiDi) algorithm, ensuring text flows from right to left while maintaining left-to-right flow for numbers or English words mixed in. * HarfBuzz (libharfbuzz): Handles text shaping, which is essential for Arabic where letter shapes change depending on their position in a word.

Run the following command in your terminal to check if your FFmpeg build includes these libraries:

ffmpeg -version

Look for --enable-libfribidi and --enable-libharfbuzz in the printed configuration block. If these are missing, you must install a build of FFmpeg that includes them, or compile FFmpeg from source with these flags enabled.

Step 2: Choose a Compatible Font

You must use a TrueType (TTF) or OpenType (OTF) font that fully supports the character set of your target language (e.g., Arial, DejaVu Sans, or specialized fonts like Amiri for Arabic or David for Hebrew).

Step 3: Run the FFmpeg Command

When libfribidi is enabled, the drawtext filter automatically applies bidirectional reordering. Here is the basic command structure to burn RTL text into a video:

ffmpeg -i input.mp4 -vf "drawtext=fontfile='/path/to/font.ttf':text='العربية':fontcolor=white:fontsize=48:x=(w-tw)/2:y=(h-th)/2" -codec:a copy output.mp4

Step 4: Best Practices for Complex Text

If you are dealing with long sentences or shell scripting environments, passing RTL characters directly in the command line can cause display encoding issues. To avoid this, write your text to a UTF-8 encoded text file and reference it using the textfile parameter:

  1. Create a file named text.txt containing your RTL text.
  2. Run the following command:
ffmpeg -i input.mp4 -vf "drawtext=fontfile='/path/to/font.ttf':textfile='text.txt':fontcolor=white:fontsize=48:x=(w-tw)/2:y=(h-th)/2" -codec:a copy output.mp4

This method ensures that the terminal shell does not alter the character bytes before they reach the FFmpeg layout engine.