How to escape all special characters for ffmpeg drawtext filter in java

Viewed 4799

Does anyone have a good recipe for escaping all of the special characters (',%,\,:,{,}) from a String in java, that will be used in an ffmpeg drawtext filter chain? Trying to use replaceAll with different combinations of escaping has been an exercise in frustration!

String myTextString = "Bob's special\cool mix:stuff @ 40% off"; Runtime.getRuntime().exec(new String[] { "ffmpeg",...., "filter_complex", "drawtext=enable='between(t,0,10)':x=10:y=10:fontfile=Roboto-Black.ttf:text='" + myTextString + "':fontcolor=#a43ddb:fontsize=14", ... });

ffmpeg drawtext filter: https://ffmpeg.org/ffmpeg-filters.html#drawtext-1

3 Answers

Just put your text into a text file (e.g. myText.txt) and use the textfile option:

-> myText.txt:

This is my text with special characters: ,(,),'

Then instead of using:

ffmpeg -i test.mpg -vf drawtext="This is my text with special characters :,(,),'"

Use the following command:

ffmpeg -i test.mpg -vf drawtext=textfile=textFile.txt

for Python (in Colab)

Hi, I ran into the same issue using Google Colab and Python. For those looking for a solution, this might help.

I execute the ffmpeg commandline as follows:

!ffmpeg ... -filter_complex "$texts" ...

... where texts refers to a string variable containing the mentioned filteres with drawtext option.

For me worked:

texts = ... # init

def normalize_text(t):
  return t\
  .replace("\\", "\\\\")\
  .replace('"', '""')\
  .replace("'", "''")\
  .replace("%", "\\%")\
  .replace(":", "\\:")

texts = normalize_text(texts) #normalize
!ffmpeg ... #execute

As you can see, escaping it once has worked for me. Note: this function might be extended to include certain other characters which will result in an error message being displayed upon execution, something along the lines of "filter could not be parsed" or "no option XXX" and more.

Thanks guys

Related