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

Tags: , , , ,



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 specialcool 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

Answer

Alright…after banging my head against a wall for getting the right escape patterns to satisfy both java and ffmpeg I came up with this:


MyDrawTextString.replaceAll("\\", "\\\\\\\\").replaceAll("'", "'\\\\\\''").replaceAll("%", "\\\\\\%").replaceAll(":", "\\\\\\:");

Looks insane, but it works! Note: I had to double my backslashes in my answer here to get this to display correctly too 😛 Dang those backslashes.

The key is ffmpeg drawtext needs 3 backslashes to escape (‘,%,:) and single quotes need to also be wrapped in a second pair of single quotes. Java String needs 2 backslashes to make one and java replaceAll regex needs to have 2 backslashes to make a single one in a string. Therefore you need (2+2)*3 backslashes to escape things in drawtext filter string!



Source: stackoverflow