Home > OS >  How to escape single quotes in Shell FFmpeg?
How to escape single quotes in Shell FFmpeg?

Time:03-04

My environment

  • zsh
  • Apple clang version 13.0.0

Summary of my problem

I want to draw some text on a video using FFmpeg.

My command line is sent by a C program with the system() function.

When there is a single quote in my string, the text does not display, which makes sense.

What I've tried

  • Leaving it as it is → no text is drawn
  • Escaping it normally with \' → no text is drawn
  • Double escaping it with \\' → no text is drawn
  • Triple escaping it, etc...
  • Using the \0027 and \xE2\x80\x99 notations → text is drawn as "0027" or "xE2x80x99"

My code

The generateVideo() function

void generateVideo(char sourceVideoPath[], char text[], int destinationFileName) {
    char line[1000];
    sprintf(line, "ffmpeg -i %s -vf \"drawtext=fontfile=/path/to/font/:text='%s':fontcolor=white:fontsize=28:borderw=2.8:x=(w-text_w)/2:y=(h-text_h)/2\" -codec:a copy ../%d.mp4", sourceVideoPath, text, destinationFileName);
    system(line);
}

I don't know if the problem comes from FFmpeg or Shell, but it is a pain that I can't draw texts with quotes for the moment.

Thank you guys in advance!

CodePudding user response:

It's a little hard to tell from your question what the problem is, but I believe a fix like encoding \ before the quotes in the text should fix it. It might be easier to help if you started from a command line that works from the shell and then tried to issue that command with 'system' from your C code. Here is a main.c that demonstrates what I think ought to work:

#import <stdio.h>
#import <stdlib.h>

int main(int argc, char **argv) {
    char *sourceVideoPath = "video";
    char *text = "text \\'quoted\\' text";
    int destinationFileName = 10;
    char line[1000];
    sprintf(line, "echo ffmpeg -i %s -vf \"drawtext=fontfile=/path/to/font/:text='%s':fontcolor=white:fontsize=28:borderw=2.8:x=(w-text_w)/2:y=(h-text_h)/2\" -codec:a copy ../%d.mp4", sourceVideoPath, text, destinationFileName);
    system(line);
}

CodePudding user response:

Would you please try the following:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *sourceVideoPath = "video.mp4";
    char *text = "'text '\\\\\\\\\\\''quoted'\\\\\\\\\\\'' text'";
    char *destinationFileName = "with_text.mp4";
    char line[1000];
    sprintf(line, "ffmpeg -i \"%s\" -vf \"drawtext=fontfile=/path/to/fonts/font.ttf:text=%s:fontcolor=white:fontsize=28:borderw=2.8:x=(w-text_w)/2:y=(h-text_h)/2\" -codec:a copy \"%s\"", sourceVideoPath, text, destinationFileName);
    system(line);
}

I'm not joking :). Tested with an actual video file.

  • Related