You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1013 lines
36KB

  1. /*
  2. * Copyright (c) 2011 Stefano Sabatini
  3. * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
  4. * Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri@yahoo.com.br>
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * drawtext filter, based on the original vhook/drawtext.c
  25. * filter by Gustavo Sverzut Barbieri
  26. */
  27. #include <sys/time.h>
  28. #include <time.h>
  29. #include "config.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/bprint.h"
  32. #include "libavutil/common.h"
  33. #include "libavutil/file.h"
  34. #include "libavutil/eval.h"
  35. #include "libavutil/opt.h"
  36. #include "libavutil/random_seed.h"
  37. #include "libavutil/parseutils.h"
  38. #include "libavutil/timecode.h"
  39. #include "libavutil/tree.h"
  40. #include "libavutil/lfg.h"
  41. #include "avfilter.h"
  42. #include "drawutils.h"
  43. #include "formats.h"
  44. #include "internal.h"
  45. #include "video.h"
  46. #undef time
  47. #include <ft2build.h>
  48. #include <freetype/config/ftheader.h>
  49. #include FT_FREETYPE_H
  50. #include FT_GLYPH_H
  51. #if CONFIG_FONTCONFIG
  52. #include <fontconfig/fontconfig.h>
  53. #endif
  54. static const char *const var_names[] = {
  55. "dar",
  56. "hsub", "vsub",
  57. "line_h", "lh", ///< line height, same as max_glyph_h
  58. "main_h", "h", "H", ///< height of the input video
  59. "main_w", "w", "W", ///< width of the input video
  60. "max_glyph_a", "ascent", ///< max glyph ascent
  61. "max_glyph_d", "descent", ///< min glyph descent
  62. "max_glyph_h", ///< max glyph height
  63. "max_glyph_w", ///< max glyph width
  64. "n", ///< number of frame
  65. "sar",
  66. "t", ///< timestamp expressed in seconds
  67. "text_h", "th", ///< height of the rendered text
  68. "text_w", "tw", ///< width of the rendered text
  69. "x",
  70. "y",
  71. NULL
  72. };
  73. static const char *const fun2_names[] = {
  74. "rand"
  75. };
  76. static double drand(void *opaque, double min, double max)
  77. {
  78. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  79. }
  80. typedef double (*eval_func2)(void *, double a, double b);
  81. static const eval_func2 fun2[] = {
  82. drand,
  83. NULL
  84. };
  85. enum var_name {
  86. VAR_DAR,
  87. VAR_HSUB, VAR_VSUB,
  88. VAR_LINE_H, VAR_LH,
  89. VAR_MAIN_H, VAR_h, VAR_H,
  90. VAR_MAIN_W, VAR_w, VAR_W,
  91. VAR_MAX_GLYPH_A, VAR_ASCENT,
  92. VAR_MAX_GLYPH_D, VAR_DESCENT,
  93. VAR_MAX_GLYPH_H,
  94. VAR_MAX_GLYPH_W,
  95. VAR_N,
  96. VAR_SAR,
  97. VAR_T,
  98. VAR_TEXT_H, VAR_TH,
  99. VAR_TEXT_W, VAR_TW,
  100. VAR_X,
  101. VAR_Y,
  102. VAR_VARS_NB
  103. };
  104. enum expansion_mode {
  105. EXP_NONE,
  106. EXP_NORMAL,
  107. EXP_STRFTIME,
  108. };
  109. typedef struct {
  110. const AVClass *class;
  111. enum expansion_mode exp_mode; ///< expansion mode to use for the text
  112. int reinit; ///< tells if the filter is being reinited
  113. uint8_t *fontfile; ///< font to be used
  114. uint8_t *text; ///< text to be drawn
  115. AVBPrint expanded_text; ///< used to contain the expanded text
  116. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  117. FT_Vector *positions; ///< positions for each element in the text
  118. size_t nb_positions; ///< number of elements of positions array
  119. char *textfile; ///< file with text to be drawn
  120. int x; ///< x position to start drawing text
  121. int y; ///< y position to start drawing text
  122. int max_glyph_w; ///< max glyph width
  123. int max_glyph_h; ///< max glyph height
  124. int shadowx, shadowy;
  125. unsigned int fontsize; ///< font size to use
  126. char *fontcolor_string; ///< font color as string
  127. char *boxcolor_string; ///< box color as string
  128. char *shadowcolor_string; ///< shadow color as string
  129. short int draw_box; ///< draw box around text - true or false
  130. int use_kerning; ///< font kerning is used - true/false
  131. int tabsize; ///< tab size
  132. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  133. FFDrawContext dc;
  134. FFDrawColor fontcolor; ///< foreground color
  135. FFDrawColor shadowcolor; ///< shadow color
  136. FFDrawColor boxcolor; ///< background color
  137. FT_Library library; ///< freetype font library handle
  138. FT_Face face; ///< freetype font face handle
  139. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  140. char *x_expr; ///< expression for x position
  141. char *y_expr; ///< expression for y position
  142. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  143. int64_t basetime; ///< base pts time in the real world for display
  144. double var_values[VAR_VARS_NB];
  145. char *draw_expr; ///< expression for draw
  146. AVExpr *draw_pexpr; ///< parsed expression for draw
  147. int draw; ///< set to zero to prevent drawing
  148. AVLFG prng; ///< random
  149. char *tc_opt_string; ///< specified timecode option string
  150. AVRational tc_rate; ///< frame rate for timecode
  151. AVTimecode tc; ///< timecode context
  152. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  153. int frame_id;
  154. } DrawTextContext;
  155. #define OFFSET(x) offsetof(DrawTextContext, x)
  156. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  157. static const AVOption drawtext_options[]= {
  158. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  159. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  160. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  161. {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  162. {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  163. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  164. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  165. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  166. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  167. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  168. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  169. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  170. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  171. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  172. {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
  173. {"expansion","set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_STRFTIME}, 0, 2, FLAGS, "expansion"},
  174. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  175. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  176. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  177. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  178. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  179. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  180. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  181. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  182. {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
  183. /* FT_LOAD_* flags */
  184. {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.i64=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, FLAGS, "ft_load_flags"},
  185. {"default", "set default", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  186. {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  187. {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  188. {"render", "set render", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_RENDER}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  189. {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  190. {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  191. {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  192. {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  193. {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  194. {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  195. {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  196. {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  197. {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  198. {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  199. {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  200. {NULL},
  201. };
  202. AVFILTER_DEFINE_CLASS(drawtext);
  203. #undef __FTERRORS_H__
  204. #define FT_ERROR_START_LIST {
  205. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  206. #define FT_ERROR_END_LIST { 0, NULL } };
  207. struct ft_error
  208. {
  209. int err;
  210. const char *err_msg;
  211. } static ft_errors[] =
  212. #include FT_ERRORS_H
  213. #define FT_ERRMSG(e) ft_errors[e].err_msg
  214. typedef struct {
  215. FT_Glyph *glyph;
  216. uint32_t code;
  217. FT_Bitmap bitmap; ///< array holding bitmaps of font
  218. FT_BBox bbox;
  219. int advance;
  220. int bitmap_left;
  221. int bitmap_top;
  222. } Glyph;
  223. static int glyph_cmp(void *key, const void *b)
  224. {
  225. const Glyph *a = key, *bb = b;
  226. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  227. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  228. }
  229. /**
  230. * Load glyphs corresponding to the UTF-32 codepoint code.
  231. */
  232. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  233. {
  234. DrawTextContext *dtext = ctx->priv;
  235. Glyph *glyph;
  236. struct AVTreeNode *node = NULL;
  237. int ret;
  238. /* load glyph into dtext->face->glyph */
  239. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  240. return AVERROR(EINVAL);
  241. /* save glyph */
  242. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  243. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  244. ret = AVERROR(ENOMEM);
  245. goto error;
  246. }
  247. glyph->code = code;
  248. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  249. ret = AVERROR(EINVAL);
  250. goto error;
  251. }
  252. glyph->bitmap = dtext->face->glyph->bitmap;
  253. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  254. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  255. glyph->advance = dtext->face->glyph->advance.x >> 6;
  256. /* measure text height to calculate text_height (or the maximum text height) */
  257. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  258. /* cache the newly created glyph */
  259. if (!(node = av_tree_node_alloc())) {
  260. ret = AVERROR(ENOMEM);
  261. goto error;
  262. }
  263. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  264. if (glyph_ptr)
  265. *glyph_ptr = glyph;
  266. return 0;
  267. error:
  268. if (glyph)
  269. av_freep(&glyph->glyph);
  270. av_freep(&glyph);
  271. av_freep(&node);
  272. return ret;
  273. }
  274. static int load_font_file(AVFilterContext *ctx, const char *path, int index,
  275. const char **error)
  276. {
  277. DrawTextContext *dtext = ctx->priv;
  278. int err;
  279. err = FT_New_Face(dtext->library, path, index, &dtext->face);
  280. if (err) {
  281. *error = FT_ERRMSG(err);
  282. return AVERROR(EINVAL);
  283. }
  284. return 0;
  285. }
  286. #if CONFIG_FONTCONFIG
  287. static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
  288. {
  289. DrawTextContext *dtext = ctx->priv;
  290. FcConfig *fontconfig;
  291. FcPattern *pattern, *fpat;
  292. FcResult result = FcResultMatch;
  293. FcChar8 *filename;
  294. int err, index;
  295. double size;
  296. fontconfig = FcInitLoadConfigAndFonts();
  297. if (!fontconfig) {
  298. *error = "impossible to init fontconfig\n";
  299. return AVERROR(EINVAL);
  300. }
  301. pattern = FcNameParse(dtext->fontfile ? dtext->fontfile :
  302. (uint8_t *)(intptr_t)"default");
  303. if (!pattern) {
  304. *error = "could not parse fontconfig pattern";
  305. return AVERROR(EINVAL);
  306. }
  307. if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
  308. *error = "could not substitue fontconfig options"; /* very unlikely */
  309. return AVERROR(EINVAL);
  310. }
  311. FcDefaultSubstitute(pattern);
  312. fpat = FcFontMatch(fontconfig, pattern, &result);
  313. if (!fpat || result != FcResultMatch) {
  314. *error = "impossible to find a matching font";
  315. return AVERROR(EINVAL);
  316. }
  317. if (FcPatternGetString (fpat, FC_FILE, 0, &filename) != FcResultMatch ||
  318. FcPatternGetInteger(fpat, FC_INDEX, 0, &index ) != FcResultMatch ||
  319. FcPatternGetDouble (fpat, FC_SIZE, 0, &size ) != FcResultMatch) {
  320. *error = "impossible to find font information";
  321. return AVERROR(EINVAL);
  322. }
  323. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  324. if (!dtext->fontsize)
  325. dtext->fontsize = size + 0.5;
  326. err = load_font_file(ctx, filename, index, error);
  327. if (err)
  328. return err;
  329. FcPatternDestroy(fpat);
  330. FcPatternDestroy(pattern);
  331. FcConfigDestroy(fontconfig);
  332. return 0;
  333. }
  334. #endif
  335. static int load_font(AVFilterContext *ctx)
  336. {
  337. DrawTextContext *dtext = ctx->priv;
  338. int err;
  339. const char *error = "unknown error\n";
  340. /* load the face, and set up the encoding, which is by default UTF-8 */
  341. err = load_font_file(ctx, dtext->fontfile, 0, &error);
  342. if (!err)
  343. return 0;
  344. #if CONFIG_FONTCONFIG
  345. err = load_font_fontconfig(ctx, &error);
  346. if (!err)
  347. return 0;
  348. #endif
  349. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  350. dtext->fontfile, error);
  351. return err;
  352. }
  353. static av_cold int init(AVFilterContext *ctx, const char *args)
  354. {
  355. int err;
  356. DrawTextContext *dtext = ctx->priv;
  357. Glyph *glyph;
  358. dtext->class = &drawtext_class;
  359. av_opt_set_defaults(dtext);
  360. if ((err = av_set_options_string(dtext, args, "=", ":")) < 0)
  361. return err;
  362. if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
  363. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  364. return AVERROR(EINVAL);
  365. }
  366. if (dtext->textfile) {
  367. uint8_t *textbuf;
  368. size_t textbuf_size;
  369. if (dtext->text) {
  370. av_log(ctx, AV_LOG_ERROR,
  371. "Both text and text file provided. Please provide only one\n");
  372. return AVERROR(EINVAL);
  373. }
  374. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  375. av_log(ctx, AV_LOG_ERROR,
  376. "The text file '%s' could not be read or is empty\n",
  377. dtext->textfile);
  378. return err;
  379. }
  380. if (!(dtext->text = av_malloc(textbuf_size+1)))
  381. return AVERROR(ENOMEM);
  382. memcpy(dtext->text, textbuf, textbuf_size);
  383. dtext->text[textbuf_size] = 0;
  384. av_file_unmap(textbuf, textbuf_size);
  385. }
  386. if (dtext->tc_opt_string) {
  387. int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
  388. dtext->tc_opt_string, ctx);
  389. if (ret < 0)
  390. return ret;
  391. if (dtext->tc24hmax)
  392. dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  393. if (!dtext->text)
  394. dtext->text = av_strdup("");
  395. }
  396. if (!dtext->text) {
  397. av_log(ctx, AV_LOG_ERROR,
  398. "Either text, a valid file or a timecode must be provided\n");
  399. return AVERROR(EINVAL);
  400. }
  401. if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
  402. av_log(ctx, AV_LOG_ERROR,
  403. "Invalid font color '%s'\n", dtext->fontcolor_string);
  404. return err;
  405. }
  406. if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
  407. av_log(ctx, AV_LOG_ERROR,
  408. "Invalid box color '%s'\n", dtext->boxcolor_string);
  409. return err;
  410. }
  411. if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
  412. av_log(ctx, AV_LOG_ERROR,
  413. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  414. return err;
  415. }
  416. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  417. av_log(ctx, AV_LOG_ERROR,
  418. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  419. return AVERROR(EINVAL);
  420. }
  421. err = load_font(ctx);
  422. if (err)
  423. return err;
  424. if (!dtext->fontsize)
  425. dtext->fontsize = 16;
  426. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  427. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  428. dtext->fontsize, FT_ERRMSG(err));
  429. return AVERROR(EINVAL);
  430. }
  431. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  432. /* load the fallback glyph with code 0 */
  433. load_glyph(ctx, NULL, 0);
  434. /* set the tabsize in pixels */
  435. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  436. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  437. return err;
  438. }
  439. dtext->tabsize *= glyph->advance;
  440. if (dtext->exp_mode == EXP_STRFTIME &&
  441. (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
  442. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  443. av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  444. return 0;
  445. }
  446. static int query_formats(AVFilterContext *ctx)
  447. {
  448. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  449. return 0;
  450. }
  451. static int glyph_enu_free(void *opaque, void *elem)
  452. {
  453. Glyph *glyph = elem;
  454. FT_Done_Glyph(*glyph->glyph);
  455. av_freep(&glyph->glyph);
  456. av_free(elem);
  457. return 0;
  458. }
  459. static av_cold void uninit(AVFilterContext *ctx)
  460. {
  461. DrawTextContext *dtext = ctx->priv;
  462. av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
  463. av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
  464. av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
  465. av_opt_free(dtext);
  466. av_freep(&dtext->positions);
  467. dtext->nb_positions = 0;
  468. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  469. av_tree_destroy(dtext->glyphs);
  470. dtext->glyphs = NULL;
  471. FT_Done_Face(dtext->face);
  472. FT_Done_FreeType(dtext->library);
  473. av_bprint_finalize(&dtext->expanded_text, NULL);
  474. }
  475. static inline int is_newline(uint32_t c)
  476. {
  477. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  478. }
  479. static int config_input(AVFilterLink *inlink)
  480. {
  481. AVFilterContext *ctx = inlink->dst;
  482. DrawTextContext *dtext = ctx->priv;
  483. int ret;
  484. ff_draw_init(&dtext->dc, inlink->format, 0);
  485. ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
  486. ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
  487. ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
  488. dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
  489. dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
  490. dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  491. dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
  492. dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
  493. dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
  494. dtext->var_values[VAR_X] = NAN;
  495. dtext->var_values[VAR_Y] = NAN;
  496. if (!dtext->reinit)
  497. dtext->var_values[VAR_N] = 0;
  498. dtext->var_values[VAR_T] = NAN;
  499. av_lfg_init(&dtext->prng, av_get_random_seed());
  500. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  501. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  502. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  503. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  504. (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
  505. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  506. return AVERROR(EINVAL);
  507. return 0;
  508. }
  509. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  510. {
  511. DrawTextContext *dtext = ctx->priv;
  512. if (!strcmp(cmd, "reinit")) {
  513. int ret;
  514. uninit(ctx);
  515. dtext->reinit = 1;
  516. if ((ret = init(ctx, arg)) < 0)
  517. return ret;
  518. return config_input(ctx->inputs[0]);
  519. }
  520. return AVERROR(ENOSYS);
  521. }
  522. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  523. char *fct, unsigned argc, char **argv, int tag)
  524. {
  525. DrawTextContext *dtext = ctx->priv;
  526. av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
  527. return 0;
  528. }
  529. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  530. char *fct, unsigned argc, char **argv, int tag)
  531. {
  532. DrawTextContext *dtext = ctx->priv;
  533. av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
  534. return 0;
  535. }
  536. #if !HAVE_LOCALTIME_R
  537. static void localtime_r(const time_t *t, struct tm *tm)
  538. {
  539. *tm = *localtime(t);
  540. }
  541. #endif
  542. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  543. char *fct, unsigned argc, char **argv, int tag)
  544. {
  545. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  546. time_t now;
  547. struct tm tm;
  548. time(&now);
  549. if (tag == 'L')
  550. localtime_r(&now, &tm);
  551. else
  552. tm = *gmtime(&now);
  553. av_bprint_strftime(bp, fmt, &tm);
  554. return 0;
  555. }
  556. static const struct drawtext_function {
  557. const char *name;
  558. unsigned argc_min, argc_max;
  559. int tag; /** opaque argument to func */
  560. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  561. } functions[] = {
  562. { "pts", 0, 0, 0, func_pts },
  563. { "gmtime", 0, 1, 'G', func_strftime },
  564. { "localtime", 0, 1, 'L', func_strftime },
  565. { "frame_num", 0, 0, 0, func_frame_num },
  566. { "n", 0, 0, 0, func_frame_num },
  567. };
  568. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  569. unsigned argc, char **argv)
  570. {
  571. unsigned i;
  572. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  573. if (strcmp(fct, functions[i].name))
  574. continue;
  575. if (argc < functions[i].argc_min) {
  576. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  577. fct, functions[i].argc_min);
  578. return AVERROR(EINVAL);
  579. }
  580. if (argc > functions[i].argc_max) {
  581. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  582. fct, functions[i].argc_max);
  583. return AVERROR(EINVAL);
  584. }
  585. break;
  586. }
  587. if (i >= FF_ARRAY_ELEMS(functions)) {
  588. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  589. return AVERROR(EINVAL);
  590. }
  591. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  592. }
  593. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  594. {
  595. const char *text = *rtext;
  596. char *argv[16] = { NULL };
  597. unsigned argc = 0, i;
  598. int ret;
  599. if (*text != '{') {
  600. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  601. return AVERROR(EINVAL);
  602. }
  603. text++;
  604. while (1) {
  605. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  606. ret = AVERROR(ENOMEM);
  607. goto end;
  608. }
  609. if (!*text) {
  610. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  611. ret = AVERROR(EINVAL);
  612. goto end;
  613. }
  614. if (argc == FF_ARRAY_ELEMS(argv))
  615. av_freep(&argv[--argc]); /* error will be caught later */
  616. if (*text == '}')
  617. break;
  618. text++;
  619. }
  620. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  621. goto end;
  622. ret = 0;
  623. *rtext = (char *)text + 1;
  624. end:
  625. for (i = 0; i < argc; i++)
  626. av_freep(&argv[i]);
  627. return ret;
  628. }
  629. static int expand_text(AVFilterContext *ctx)
  630. {
  631. DrawTextContext *dtext = ctx->priv;
  632. char *text = dtext->text;
  633. AVBPrint *bp = &dtext->expanded_text;
  634. int ret;
  635. av_bprint_clear(bp);
  636. while (*text) {
  637. if (*text == '\\' && text[1]) {
  638. av_bprint_chars(bp, text[1], 1);
  639. text += 2;
  640. } else if (*text == '%') {
  641. text++;
  642. if ((ret = expand_function(ctx, bp, &text)) < 0)
  643. return ret;
  644. } else {
  645. av_bprint_chars(bp, *text, 1);
  646. text++;
  647. }
  648. }
  649. if (!av_bprint_is_complete(bp))
  650. return AVERROR(ENOMEM);
  651. return 0;
  652. }
  653. static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
  654. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  655. {
  656. char *text = dtext->expanded_text.str;
  657. uint32_t code = 0;
  658. int i, x1, y1;
  659. uint8_t *p;
  660. Glyph *glyph = NULL;
  661. for (i = 0, p = text; *p; i++) {
  662. Glyph dummy = { 0 };
  663. GET_UTF8(code, *p++, continue;);
  664. /* skip new line chars, just go to new line */
  665. if (code == '\n' || code == '\r' || code == '\t')
  666. continue;
  667. dummy.code = code;
  668. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  669. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  670. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  671. return AVERROR(EINVAL);
  672. x1 = dtext->positions[i].x+dtext->x+x;
  673. y1 = dtext->positions[i].y+dtext->y+y;
  674. ff_blend_mask(&dtext->dc, color,
  675. picref->data, picref->linesize, width, height,
  676. glyph->bitmap.buffer, glyph->bitmap.pitch,
  677. glyph->bitmap.width, glyph->bitmap.rows,
  678. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  679. 0, x1, y1);
  680. }
  681. return 0;
  682. }
  683. static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
  684. int width, int height)
  685. {
  686. DrawTextContext *dtext = ctx->priv;
  687. uint32_t code = 0, prev_code = 0;
  688. int x = 0, y = 0, i = 0, ret;
  689. int max_text_line_w = 0, len;
  690. int box_w, box_h;
  691. char *text = dtext->text;
  692. uint8_t *p;
  693. int y_min = 32000, y_max = -32000;
  694. int x_min = 32000, x_max = -32000;
  695. FT_Vector delta;
  696. Glyph *glyph = NULL, *prev_glyph = NULL;
  697. Glyph dummy = { 0 };
  698. time_t now = time(0);
  699. struct tm ltime;
  700. AVBPrint *bp = &dtext->expanded_text;
  701. av_bprint_clear(bp);
  702. if(dtext->basetime != AV_NOPTS_VALUE)
  703. now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  704. switch (dtext->exp_mode) {
  705. case EXP_NONE:
  706. av_bprintf(bp, "%s", dtext->text);
  707. break;
  708. case EXP_NORMAL:
  709. if ((ret = expand_text(ctx)) < 0)
  710. return ret;
  711. break;
  712. case EXP_STRFTIME:
  713. localtime_r(&now, &ltime);
  714. av_bprint_strftime(bp, dtext->text, &ltime);
  715. break;
  716. }
  717. if (dtext->tc_opt_string) {
  718. char tcbuf[AV_TIMECODE_STR_SIZE];
  719. av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
  720. av_bprint_clear(bp);
  721. av_bprintf(bp, "%s%s", dtext->text, tcbuf);
  722. }
  723. if (!av_bprint_is_complete(bp))
  724. return AVERROR(ENOMEM);
  725. text = dtext->expanded_text.str;
  726. if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
  727. if (!(dtext->positions =
  728. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  729. return AVERROR(ENOMEM);
  730. dtext->nb_positions = len;
  731. }
  732. x = 0;
  733. y = 0;
  734. /* load and cache glyphs */
  735. for (i = 0, p = text; *p; i++) {
  736. GET_UTF8(code, *p++, continue;);
  737. /* get glyph */
  738. dummy.code = code;
  739. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  740. if (!glyph) {
  741. load_glyph(ctx, &glyph, code);
  742. }
  743. y_min = FFMIN(glyph->bbox.yMin, y_min);
  744. y_max = FFMAX(glyph->bbox.yMax, y_max);
  745. x_min = FFMIN(glyph->bbox.xMin, x_min);
  746. x_max = FFMAX(glyph->bbox.xMax, x_max);
  747. }
  748. dtext->max_glyph_h = y_max - y_min;
  749. dtext->max_glyph_w = x_max - x_min;
  750. /* compute and save position for each glyph */
  751. glyph = NULL;
  752. for (i = 0, p = text; *p; i++) {
  753. GET_UTF8(code, *p++, continue;);
  754. /* skip the \n in the sequence \r\n */
  755. if (prev_code == '\r' && code == '\n')
  756. continue;
  757. prev_code = code;
  758. if (is_newline(code)) {
  759. max_text_line_w = FFMAX(max_text_line_w, x);
  760. y += dtext->max_glyph_h;
  761. x = 0;
  762. continue;
  763. }
  764. /* get glyph */
  765. prev_glyph = glyph;
  766. dummy.code = code;
  767. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  768. /* kerning */
  769. if (dtext->use_kerning && prev_glyph && glyph->code) {
  770. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  771. ft_kerning_default, &delta);
  772. x += delta.x >> 6;
  773. }
  774. /* save position */
  775. dtext->positions[i].x = x + glyph->bitmap_left;
  776. dtext->positions[i].y = y - glyph->bitmap_top + y_max;
  777. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  778. else x += glyph->advance;
  779. }
  780. max_text_line_w = FFMAX(x, max_text_line_w);
  781. dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
  782. dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
  783. dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
  784. dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
  785. dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
  786. dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
  787. dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
  788. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  789. dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  790. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  791. dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
  792. if(!dtext->draw)
  793. return 0;
  794. box_w = FFMIN(width - 1 , max_text_line_w);
  795. box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
  796. /* draw box */
  797. if (dtext->draw_box)
  798. ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
  799. picref->data, picref->linesize, width, height,
  800. dtext->x, dtext->y, box_w, box_h);
  801. if (dtext->shadowx || dtext->shadowy) {
  802. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor.rgba,
  803. &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  804. return ret;
  805. }
  806. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor.rgba,
  807. &dtext->fontcolor, 0, 0)) < 0)
  808. return ret;
  809. return 0;
  810. }
  811. static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
  812. {
  813. return 0;
  814. }
  815. static int end_frame(AVFilterLink *inlink)
  816. {
  817. AVFilterContext *ctx = inlink->dst;
  818. AVFilterLink *outlink = ctx->outputs[0];
  819. DrawTextContext *dtext = ctx->priv;
  820. AVFilterBufferRef *picref = inlink->cur_buf;
  821. int ret;
  822. dtext->var_values[VAR_T] = picref->pts == AV_NOPTS_VALUE ?
  823. NAN : picref->pts * av_q2d(inlink->time_base);
  824. draw_text(ctx, picref, picref->video->w, picref->video->h);
  825. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  826. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  827. (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
  828. dtext->x, dtext->y);
  829. dtext->var_values[VAR_N] += 1.0;
  830. if ((ret = ff_draw_slice(outlink, 0, picref->video->h, 1)) < 0 ||
  831. (ret = ff_end_frame(outlink)) < 0)
  832. return ret;
  833. return 0;
  834. }
  835. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  836. {
  837. .name = "default",
  838. .type = AVMEDIA_TYPE_VIDEO,
  839. .get_video_buffer = ff_null_get_video_buffer,
  840. .start_frame = ff_null_start_frame,
  841. .draw_slice = null_draw_slice,
  842. .end_frame = end_frame,
  843. .config_props = config_input,
  844. .min_perms = AV_PERM_WRITE |
  845. AV_PERM_READ,
  846. },
  847. { NULL }
  848. };
  849. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  850. {
  851. .name = "default",
  852. .type = AVMEDIA_TYPE_VIDEO,
  853. },
  854. { NULL }
  855. };
  856. AVFilter avfilter_vf_drawtext = {
  857. .name = "drawtext",
  858. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  859. .priv_size = sizeof(DrawTextContext),
  860. .init = init,
  861. .uninit = uninit,
  862. .query_formats = query_formats,
  863. .inputs = avfilter_vf_drawtext_inputs,
  864. .outputs = avfilter_vf_drawtext_outputs,
  865. .process_command = command,
  866. .priv_class = &drawtext_class,
  867. };