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.

1033 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. #include <ft2build.h>
  47. #include <freetype/config/ftheader.h>
  48. #include FT_FREETYPE_H
  49. #include FT_GLYPH_H
  50. #if CONFIG_FONTCONFIG
  51. #include <fontconfig/fontconfig.h>
  52. #endif
  53. static const char *const var_names[] = {
  54. "dar",
  55. "hsub", "vsub",
  56. "line_h", "lh", ///< line height, same as max_glyph_h
  57. "main_h", "h", "H", ///< height of the input video
  58. "main_w", "w", "W", ///< width of the input video
  59. "max_glyph_a", "ascent", ///< max glyph ascent
  60. "max_glyph_d", "descent", ///< min glyph descent
  61. "max_glyph_h", ///< max glyph height
  62. "max_glyph_w", ///< max glyph width
  63. "n", ///< number of frame
  64. "sar",
  65. "t", ///< timestamp expressed in seconds
  66. "text_h", "th", ///< height of the rendered text
  67. "text_w", "tw", ///< width of the rendered text
  68. "x",
  69. "y",
  70. NULL
  71. };
  72. static const char *const fun2_names[] = {
  73. "rand"
  74. };
  75. static double drand(void *opaque, double min, double max)
  76. {
  77. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  78. }
  79. typedef double (*eval_func2)(void *, double a, double b);
  80. static const eval_func2 fun2[] = {
  81. drand,
  82. NULL
  83. };
  84. enum var_name {
  85. VAR_DAR,
  86. VAR_HSUB, VAR_VSUB,
  87. VAR_LINE_H, VAR_LH,
  88. VAR_MAIN_H, VAR_h, VAR_H,
  89. VAR_MAIN_W, VAR_w, VAR_W,
  90. VAR_MAX_GLYPH_A, VAR_ASCENT,
  91. VAR_MAX_GLYPH_D, VAR_DESCENT,
  92. VAR_MAX_GLYPH_H,
  93. VAR_MAX_GLYPH_W,
  94. VAR_N,
  95. VAR_SAR,
  96. VAR_T,
  97. VAR_TEXT_H, VAR_TH,
  98. VAR_TEXT_W, VAR_TW,
  99. VAR_X,
  100. VAR_Y,
  101. VAR_VARS_NB
  102. };
  103. enum expansion_mode {
  104. EXP_NONE,
  105. EXP_NORMAL,
  106. EXP_STRFTIME,
  107. };
  108. typedef struct {
  109. const AVClass *class;
  110. enum expansion_mode exp_mode; ///< expansion mode to use for the text
  111. int reinit; ///< tells if the filter is being reinited
  112. uint8_t *fontfile; ///< font to be used
  113. uint8_t *text; ///< text to be drawn
  114. AVBPrint expanded_text; ///< used to contain the expanded text
  115. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  116. FT_Vector *positions; ///< positions for each element in the text
  117. size_t nb_positions; ///< number of elements of positions array
  118. char *textfile; ///< file with text to be drawn
  119. int x; ///< x position to start drawing text
  120. int y; ///< y position to start drawing text
  121. int max_glyph_w; ///< max glyph width
  122. int max_glyph_h; ///< max glyph height
  123. int shadowx, shadowy;
  124. unsigned int fontsize; ///< font size to use
  125. char *fontcolor_string; ///< font color as string
  126. char *boxcolor_string; ///< box color as string
  127. char *shadowcolor_string; ///< shadow color as string
  128. short int draw_box; ///< draw box around text - true or false
  129. int use_kerning; ///< font kerning is used - true/false
  130. int tabsize; ///< tab size
  131. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  132. FFDrawContext dc;
  133. FFDrawColor fontcolor; ///< foreground color
  134. FFDrawColor shadowcolor; ///< shadow color
  135. FFDrawColor boxcolor; ///< background color
  136. FT_Library library; ///< freetype font library handle
  137. FT_Face face; ///< freetype font face handle
  138. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  139. char *x_expr; ///< expression for x position
  140. char *y_expr; ///< expression for y position
  141. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  142. int64_t basetime; ///< base pts time in the real world for display
  143. double var_values[VAR_VARS_NB];
  144. char *draw_expr; ///< expression for draw
  145. AVExpr *draw_pexpr; ///< parsed expression for draw
  146. int draw; ///< set to zero to prevent drawing
  147. AVLFG prng; ///< random
  148. char *tc_opt_string; ///< specified timecode option string
  149. AVRational tc_rate; ///< frame rate for timecode
  150. AVTimecode tc; ///< timecode context
  151. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  152. int reload; ///< reload text file for each frame
  153. } DrawTextContext;
  154. #define OFFSET(x) offsetof(DrawTextContext, x)
  155. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  156. static const AVOption drawtext_options[]= {
  157. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  158. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  159. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  160. {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  161. {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  162. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  163. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  164. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  165. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  166. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  167. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  168. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  169. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  170. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  171. {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
  172. {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
  173. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  174. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  175. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  176. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  177. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  178. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  179. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  180. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  181. {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, 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", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  186. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  187. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  188. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  189. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  190. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  191. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  192. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  193. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  194. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  195. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  196. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  197. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  198. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  199. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "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 int load_textfile(AVFilterContext *ctx)
  354. {
  355. DrawTextContext *dtext = ctx->priv;
  356. int err;
  357. uint8_t *textbuf;
  358. size_t textbuf_size;
  359. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  360. av_log(ctx, AV_LOG_ERROR,
  361. "The text file '%s' could not be read or is empty\n",
  362. dtext->textfile);
  363. return err;
  364. }
  365. if (!(dtext->text = av_realloc(dtext->text, textbuf_size + 1)))
  366. return AVERROR(ENOMEM);
  367. memcpy(dtext->text, textbuf, textbuf_size);
  368. dtext->text[textbuf_size] = 0;
  369. av_file_unmap(textbuf, textbuf_size);
  370. return 0;
  371. }
  372. static av_cold int init(AVFilterContext *ctx)
  373. {
  374. int err;
  375. DrawTextContext *dtext = ctx->priv;
  376. Glyph *glyph;
  377. if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
  378. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  379. return AVERROR(EINVAL);
  380. }
  381. if (dtext->textfile) {
  382. if (dtext->text) {
  383. av_log(ctx, AV_LOG_ERROR,
  384. "Both text and text file provided. Please provide only one\n");
  385. return AVERROR(EINVAL);
  386. }
  387. if ((err = load_textfile(ctx)) < 0)
  388. return err;
  389. }
  390. if (dtext->reload && !dtext->textfile)
  391. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  392. if (dtext->tc_opt_string) {
  393. int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
  394. dtext->tc_opt_string, ctx);
  395. if (ret < 0)
  396. return ret;
  397. if (dtext->tc24hmax)
  398. dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  399. if (!dtext->text)
  400. dtext->text = av_strdup("");
  401. }
  402. if (!dtext->text) {
  403. av_log(ctx, AV_LOG_ERROR,
  404. "Either text, a valid file or a timecode must be provided\n");
  405. return AVERROR(EINVAL);
  406. }
  407. if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
  408. av_log(ctx, AV_LOG_ERROR,
  409. "Invalid font color '%s'\n", dtext->fontcolor_string);
  410. return err;
  411. }
  412. if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
  413. av_log(ctx, AV_LOG_ERROR,
  414. "Invalid box color '%s'\n", dtext->boxcolor_string);
  415. return err;
  416. }
  417. if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
  418. av_log(ctx, AV_LOG_ERROR,
  419. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  420. return err;
  421. }
  422. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  423. av_log(ctx, AV_LOG_ERROR,
  424. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  425. return AVERROR(EINVAL);
  426. }
  427. err = load_font(ctx);
  428. if (err)
  429. return err;
  430. if (!dtext->fontsize)
  431. dtext->fontsize = 16;
  432. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  433. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  434. dtext->fontsize, FT_ERRMSG(err));
  435. return AVERROR(EINVAL);
  436. }
  437. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  438. /* load the fallback glyph with code 0 */
  439. load_glyph(ctx, NULL, 0);
  440. /* set the tabsize in pixels */
  441. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  442. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  443. return err;
  444. }
  445. dtext->tabsize *= glyph->advance;
  446. if (dtext->exp_mode == EXP_STRFTIME &&
  447. (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
  448. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  449. av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  450. return 0;
  451. }
  452. static int query_formats(AVFilterContext *ctx)
  453. {
  454. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  455. return 0;
  456. }
  457. static int glyph_enu_free(void *opaque, void *elem)
  458. {
  459. Glyph *glyph = elem;
  460. FT_Done_Glyph(*glyph->glyph);
  461. av_freep(&glyph->glyph);
  462. av_free(elem);
  463. return 0;
  464. }
  465. static av_cold void uninit(AVFilterContext *ctx)
  466. {
  467. DrawTextContext *dtext = ctx->priv;
  468. av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
  469. av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
  470. av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
  471. av_freep(&dtext->positions);
  472. dtext->nb_positions = 0;
  473. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  474. av_tree_destroy(dtext->glyphs);
  475. dtext->glyphs = NULL;
  476. FT_Done_Face(dtext->face);
  477. FT_Done_FreeType(dtext->library);
  478. av_bprint_finalize(&dtext->expanded_text, NULL);
  479. }
  480. static inline int is_newline(uint32_t c)
  481. {
  482. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  483. }
  484. static int config_input(AVFilterLink *inlink)
  485. {
  486. AVFilterContext *ctx = inlink->dst;
  487. DrawTextContext *dtext = ctx->priv;
  488. int ret;
  489. ff_draw_init(&dtext->dc, inlink->format, 0);
  490. ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
  491. ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
  492. ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
  493. dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
  494. dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
  495. dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  496. dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
  497. dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
  498. dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
  499. dtext->var_values[VAR_X] = NAN;
  500. dtext->var_values[VAR_Y] = NAN;
  501. if (!dtext->reinit)
  502. dtext->var_values[VAR_N] = 0;
  503. dtext->var_values[VAR_T] = NAN;
  504. av_lfg_init(&dtext->prng, av_get_random_seed());
  505. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  506. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  507. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  508. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  509. (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
  510. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  511. return AVERROR(EINVAL);
  512. return 0;
  513. }
  514. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  515. {
  516. DrawTextContext *dtext = ctx->priv;
  517. if (!strcmp(cmd, "reinit")) {
  518. int ret;
  519. uninit(ctx);
  520. dtext->reinit = 1;
  521. if ((ret = init(ctx)) < 0)
  522. return ret;
  523. return config_input(ctx->inputs[0]);
  524. }
  525. return AVERROR(ENOSYS);
  526. }
  527. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  528. char *fct, unsigned argc, char **argv, int tag)
  529. {
  530. DrawTextContext *dtext = ctx->priv;
  531. av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
  532. return 0;
  533. }
  534. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  535. char *fct, unsigned argc, char **argv, int tag)
  536. {
  537. DrawTextContext *dtext = ctx->priv;
  538. av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
  539. return 0;
  540. }
  541. #if !HAVE_LOCALTIME_R
  542. static void localtime_r(const time_t *t, struct tm *tm)
  543. {
  544. *tm = *localtime(t);
  545. }
  546. #endif
  547. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  548. char *fct, unsigned argc, char **argv, int tag)
  549. {
  550. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  551. time_t now;
  552. struct tm tm;
  553. time(&now);
  554. if (tag == 'L')
  555. localtime_r(&now, &tm);
  556. else
  557. tm = *gmtime(&now);
  558. av_bprint_strftime(bp, fmt, &tm);
  559. return 0;
  560. }
  561. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  562. char *fct, unsigned argc, char **argv, int tag)
  563. {
  564. DrawTextContext *dtext = ctx->priv;
  565. double res;
  566. int ret;
  567. ret = av_expr_parse_and_eval(&res, argv[0], var_names, dtext->var_values,
  568. NULL, NULL, fun2_names, fun2,
  569. &dtext->prng, 0, ctx);
  570. if (ret < 0)
  571. av_log(ctx, AV_LOG_ERROR,
  572. "Expression '%s' for the expr text expansion function is not valid\n",
  573. argv[0]);
  574. else
  575. av_bprintf(bp, "%f", res);
  576. return ret;
  577. }
  578. static const struct drawtext_function {
  579. const char *name;
  580. unsigned argc_min, argc_max;
  581. int tag; /** opaque argument to func */
  582. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  583. } functions[] = {
  584. { "expr", 1, 1, 0, func_eval_expr },
  585. { "e", 1, 1, 0, func_eval_expr },
  586. { "pts", 0, 0, 0, func_pts },
  587. { "gmtime", 0, 1, 'G', func_strftime },
  588. { "localtime", 0, 1, 'L', func_strftime },
  589. { "frame_num", 0, 0, 0, func_frame_num },
  590. { "n", 0, 0, 0, func_frame_num },
  591. };
  592. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  593. unsigned argc, char **argv)
  594. {
  595. unsigned i;
  596. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  597. if (strcmp(fct, functions[i].name))
  598. continue;
  599. if (argc < functions[i].argc_min) {
  600. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  601. fct, functions[i].argc_min);
  602. return AVERROR(EINVAL);
  603. }
  604. if (argc > functions[i].argc_max) {
  605. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  606. fct, functions[i].argc_max);
  607. return AVERROR(EINVAL);
  608. }
  609. break;
  610. }
  611. if (i >= FF_ARRAY_ELEMS(functions)) {
  612. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  613. return AVERROR(EINVAL);
  614. }
  615. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  616. }
  617. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  618. {
  619. const char *text = *rtext;
  620. char *argv[16] = { NULL };
  621. unsigned argc = 0, i;
  622. int ret;
  623. if (*text != '{') {
  624. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  625. return AVERROR(EINVAL);
  626. }
  627. text++;
  628. while (1) {
  629. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  630. ret = AVERROR(ENOMEM);
  631. goto end;
  632. }
  633. if (!*text) {
  634. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  635. ret = AVERROR(EINVAL);
  636. goto end;
  637. }
  638. if (argc == FF_ARRAY_ELEMS(argv))
  639. av_freep(&argv[--argc]); /* error will be caught later */
  640. if (*text == '}')
  641. break;
  642. text++;
  643. }
  644. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  645. goto end;
  646. ret = 0;
  647. *rtext = (char *)text + 1;
  648. end:
  649. for (i = 0; i < argc; i++)
  650. av_freep(&argv[i]);
  651. return ret;
  652. }
  653. static int expand_text(AVFilterContext *ctx)
  654. {
  655. DrawTextContext *dtext = ctx->priv;
  656. char *text = dtext->text;
  657. AVBPrint *bp = &dtext->expanded_text;
  658. int ret;
  659. av_bprint_clear(bp);
  660. while (*text) {
  661. if (*text == '\\' && text[1]) {
  662. av_bprint_chars(bp, text[1], 1);
  663. text += 2;
  664. } else if (*text == '%') {
  665. text++;
  666. if ((ret = expand_function(ctx, bp, &text)) < 0)
  667. return ret;
  668. } else {
  669. av_bprint_chars(bp, *text, 1);
  670. text++;
  671. }
  672. }
  673. if (!av_bprint_is_complete(bp))
  674. return AVERROR(ENOMEM);
  675. return 0;
  676. }
  677. static int draw_glyphs(DrawTextContext *dtext, AVFrame *frame,
  678. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  679. {
  680. char *text = dtext->expanded_text.str;
  681. uint32_t code = 0;
  682. int i, x1, y1;
  683. uint8_t *p;
  684. Glyph *glyph = NULL;
  685. for (i = 0, p = text; *p; i++) {
  686. Glyph dummy = { 0 };
  687. GET_UTF8(code, *p++, continue;);
  688. /* skip new line chars, just go to new line */
  689. if (code == '\n' || code == '\r' || code == '\t')
  690. continue;
  691. dummy.code = code;
  692. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  693. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  694. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  695. return AVERROR(EINVAL);
  696. x1 = dtext->positions[i].x+dtext->x+x;
  697. y1 = dtext->positions[i].y+dtext->y+y;
  698. ff_blend_mask(&dtext->dc, color,
  699. frame->data, frame->linesize, width, height,
  700. glyph->bitmap.buffer, glyph->bitmap.pitch,
  701. glyph->bitmap.width, glyph->bitmap.rows,
  702. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  703. 0, x1, y1);
  704. }
  705. return 0;
  706. }
  707. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  708. int width, int height)
  709. {
  710. DrawTextContext *dtext = ctx->priv;
  711. AVFilterLink *inlink = ctx->inputs[0];
  712. uint32_t code = 0, prev_code = 0;
  713. int x = 0, y = 0, i = 0, ret;
  714. int max_text_line_w = 0, len;
  715. int box_w, box_h;
  716. char *text = dtext->text;
  717. uint8_t *p;
  718. int y_min = 32000, y_max = -32000;
  719. int x_min = 32000, x_max = -32000;
  720. FT_Vector delta;
  721. Glyph *glyph = NULL, *prev_glyph = NULL;
  722. Glyph dummy = { 0 };
  723. time_t now = time(0);
  724. struct tm ltime;
  725. AVBPrint *bp = &dtext->expanded_text;
  726. av_bprint_clear(bp);
  727. if(dtext->basetime != AV_NOPTS_VALUE)
  728. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  729. switch (dtext->exp_mode) {
  730. case EXP_NONE:
  731. av_bprintf(bp, "%s", dtext->text);
  732. break;
  733. case EXP_NORMAL:
  734. if ((ret = expand_text(ctx)) < 0)
  735. return ret;
  736. break;
  737. case EXP_STRFTIME:
  738. localtime_r(&now, &ltime);
  739. av_bprint_strftime(bp, dtext->text, &ltime);
  740. break;
  741. }
  742. if (dtext->tc_opt_string) {
  743. char tcbuf[AV_TIMECODE_STR_SIZE];
  744. av_timecode_make_string(&dtext->tc, tcbuf, inlink->frame_count);
  745. av_bprint_clear(bp);
  746. av_bprintf(bp, "%s%s", dtext->text, tcbuf);
  747. }
  748. if (!av_bprint_is_complete(bp))
  749. return AVERROR(ENOMEM);
  750. text = dtext->expanded_text.str;
  751. if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
  752. if (!(dtext->positions =
  753. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  754. return AVERROR(ENOMEM);
  755. dtext->nb_positions = len;
  756. }
  757. x = 0;
  758. y = 0;
  759. /* load and cache glyphs */
  760. for (i = 0, p = text; *p; i++) {
  761. GET_UTF8(code, *p++, continue;);
  762. /* get glyph */
  763. dummy.code = code;
  764. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  765. if (!glyph) {
  766. load_glyph(ctx, &glyph, code);
  767. }
  768. y_min = FFMIN(glyph->bbox.yMin, y_min);
  769. y_max = FFMAX(glyph->bbox.yMax, y_max);
  770. x_min = FFMIN(glyph->bbox.xMin, x_min);
  771. x_max = FFMAX(glyph->bbox.xMax, x_max);
  772. }
  773. dtext->max_glyph_h = y_max - y_min;
  774. dtext->max_glyph_w = x_max - x_min;
  775. /* compute and save position for each glyph */
  776. glyph = NULL;
  777. for (i = 0, p = text; *p; i++) {
  778. GET_UTF8(code, *p++, continue;);
  779. /* skip the \n in the sequence \r\n */
  780. if (prev_code == '\r' && code == '\n')
  781. continue;
  782. prev_code = code;
  783. if (is_newline(code)) {
  784. max_text_line_w = FFMAX(max_text_line_w, x);
  785. y += dtext->max_glyph_h;
  786. x = 0;
  787. continue;
  788. }
  789. /* get glyph */
  790. prev_glyph = glyph;
  791. dummy.code = code;
  792. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  793. /* kerning */
  794. if (dtext->use_kerning && prev_glyph && glyph->code) {
  795. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  796. ft_kerning_default, &delta);
  797. x += delta.x >> 6;
  798. }
  799. /* save position */
  800. dtext->positions[i].x = x + glyph->bitmap_left;
  801. dtext->positions[i].y = y - glyph->bitmap_top + y_max;
  802. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  803. else x += glyph->advance;
  804. }
  805. max_text_line_w = FFMAX(x, max_text_line_w);
  806. dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
  807. dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
  808. dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
  809. dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
  810. dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
  811. dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
  812. dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
  813. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  814. dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  815. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  816. dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
  817. if(!dtext->draw)
  818. return 0;
  819. box_w = FFMIN(width - 1 , max_text_line_w);
  820. box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
  821. /* draw box */
  822. if (dtext->draw_box)
  823. ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
  824. frame->data, frame->linesize, width, height,
  825. dtext->x, dtext->y, box_w, box_h);
  826. if (dtext->shadowx || dtext->shadowy) {
  827. if ((ret = draw_glyphs(dtext, frame, width, height, dtext->shadowcolor.rgba,
  828. &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  829. return ret;
  830. }
  831. if ((ret = draw_glyphs(dtext, frame, width, height, dtext->fontcolor.rgba,
  832. &dtext->fontcolor, 0, 0)) < 0)
  833. return ret;
  834. return 0;
  835. }
  836. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  837. {
  838. AVFilterContext *ctx = inlink->dst;
  839. AVFilterLink *outlink = ctx->outputs[0];
  840. DrawTextContext *dtext = ctx->priv;
  841. int ret;
  842. if (dtext->reload)
  843. if ((ret = load_textfile(ctx)) < 0)
  844. return ret;
  845. dtext->var_values[VAR_N] = inlink->frame_count;
  846. dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  847. NAN : frame->pts * av_q2d(inlink->time_base);
  848. draw_text(ctx, frame, frame->width, frame->height);
  849. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  850. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  851. (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
  852. dtext->x, dtext->y);
  853. return ff_filter_frame(outlink, frame);
  854. }
  855. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  856. {
  857. .name = "default",
  858. .type = AVMEDIA_TYPE_VIDEO,
  859. .get_video_buffer = ff_null_get_video_buffer,
  860. .filter_frame = filter_frame,
  861. .config_props = config_input,
  862. .needs_writable = 1,
  863. },
  864. { NULL }
  865. };
  866. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  867. {
  868. .name = "default",
  869. .type = AVMEDIA_TYPE_VIDEO,
  870. },
  871. { NULL }
  872. };
  873. AVFilter avfilter_vf_drawtext = {
  874. .name = "drawtext",
  875. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  876. .priv_size = sizeof(DrawTextContext),
  877. .priv_class = &drawtext_class,
  878. .init = init,
  879. .uninit = uninit,
  880. .query_formats = query_formats,
  881. .inputs = avfilter_vf_drawtext_inputs,
  882. .outputs = avfilter_vf_drawtext_outputs,
  883. .process_command = command,
  884. };