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.

1190 lines
40KB

  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 "config.h"
  28. #if HAVE_SYS_TIME_H
  29. #include <sys/time.h>
  30. #endif
  31. #include <sys/types.h>
  32. #include <sys/stat.h>
  33. #include <time.h>
  34. #include <unistd.h>
  35. #if CONFIG_LIBFONTCONFIG
  36. #include <fontconfig/fontconfig.h>
  37. #endif
  38. #include "libavutil/avstring.h"
  39. #include "libavutil/bprint.h"
  40. #include "libavutil/common.h"
  41. #include "libavutil/file.h"
  42. #include "libavutil/eval.h"
  43. #include "libavutil/opt.h"
  44. #include "libavutil/random_seed.h"
  45. #include "libavutil/parseutils.h"
  46. #include "libavutil/timecode.h"
  47. #include "libavutil/tree.h"
  48. #include "libavutil/lfg.h"
  49. #include "avfilter.h"
  50. #include "drawutils.h"
  51. #include "formats.h"
  52. #include "internal.h"
  53. #include "video.h"
  54. #include <ft2build.h>
  55. #include FT_FREETYPE_H
  56. #include FT_GLYPH_H
  57. #include FT_STROKER_H
  58. static const char *const var_names[] = {
  59. "dar",
  60. "hsub", "vsub",
  61. "line_h", "lh", ///< line height, same as max_glyph_h
  62. "main_h", "h", "H", ///< height of the input video
  63. "main_w", "w", "W", ///< width of the input video
  64. "max_glyph_a", "ascent", ///< max glyph ascent
  65. "max_glyph_d", "descent", ///< min glyph descent
  66. "max_glyph_h", ///< max glyph height
  67. "max_glyph_w", ///< max glyph width
  68. "n", ///< number of frame
  69. "sar",
  70. "t", ///< timestamp expressed in seconds
  71. "text_h", "th", ///< height of the rendered text
  72. "text_w", "tw", ///< width of the rendered text
  73. "x",
  74. "y",
  75. "pict_type",
  76. NULL
  77. };
  78. static const char *const fun2_names[] = {
  79. "rand"
  80. };
  81. static double drand(void *opaque, double min, double max)
  82. {
  83. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  84. }
  85. typedef double (*eval_func2)(void *, double a, double b);
  86. static const eval_func2 fun2[] = {
  87. drand,
  88. NULL
  89. };
  90. enum var_name {
  91. VAR_DAR,
  92. VAR_HSUB, VAR_VSUB,
  93. VAR_LINE_H, VAR_LH,
  94. VAR_MAIN_H, VAR_h, VAR_H,
  95. VAR_MAIN_W, VAR_w, VAR_W,
  96. VAR_MAX_GLYPH_A, VAR_ASCENT,
  97. VAR_MAX_GLYPH_D, VAR_DESCENT,
  98. VAR_MAX_GLYPH_H,
  99. VAR_MAX_GLYPH_W,
  100. VAR_N,
  101. VAR_SAR,
  102. VAR_T,
  103. VAR_TEXT_H, VAR_TH,
  104. VAR_TEXT_W, VAR_TW,
  105. VAR_X,
  106. VAR_Y,
  107. VAR_PICT_TYPE,
  108. VAR_VARS_NB
  109. };
  110. enum expansion_mode {
  111. EXP_NONE,
  112. EXP_NORMAL,
  113. EXP_STRFTIME,
  114. };
  115. typedef struct DrawTextContext {
  116. const AVClass *class;
  117. enum expansion_mode exp_mode; ///< expansion mode to use for the text
  118. int reinit; ///< tells if the filter is being reinited
  119. #if CONFIG_LIBFONTCONFIG
  120. uint8_t *font; ///< font to be used
  121. #endif
  122. uint8_t *fontfile; ///< font to be used
  123. uint8_t *text; ///< text to be drawn
  124. AVBPrint expanded_text; ///< used to contain the expanded text
  125. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  126. FT_Vector *positions; ///< positions for each element in the text
  127. size_t nb_positions; ///< number of elements of positions array
  128. char *textfile; ///< file with text to be drawn
  129. int x; ///< x position to start drawing text
  130. int y; ///< y position to start drawing text
  131. int max_glyph_w; ///< max glyph width
  132. int max_glyph_h; ///< max glyph height
  133. int shadowx, shadowy;
  134. int borderw; ///< border width
  135. unsigned int fontsize; ///< font size to use
  136. short int draw_box; ///< draw box around text - true or false
  137. int use_kerning; ///< font kerning is used - true/false
  138. int tabsize; ///< tab size
  139. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  140. FFDrawContext dc;
  141. FFDrawColor fontcolor; ///< foreground color
  142. FFDrawColor shadowcolor; ///< shadow color
  143. FFDrawColor bordercolor; ///< border color
  144. FFDrawColor boxcolor; ///< background color
  145. FT_Library library; ///< freetype font library handle
  146. FT_Face face; ///< freetype font face handle
  147. FT_Stroker stroker; ///< freetype stroker handle
  148. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  149. char *x_expr; ///< expression for x position
  150. char *y_expr; ///< expression for y position
  151. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  152. int64_t basetime; ///< base pts time in the real world for display
  153. double var_values[VAR_VARS_NB];
  154. #if FF_API_DRAWTEXT_OLD_TIMELINE
  155. char *draw_expr; ///< expression for draw
  156. AVExpr *draw_pexpr; ///< parsed expression for draw
  157. int draw; ///< set to zero to prevent drawing
  158. #endif
  159. AVLFG prng; ///< random
  160. char *tc_opt_string; ///< specified timecode option string
  161. AVRational tc_rate; ///< frame rate for timecode
  162. AVTimecode tc; ///< timecode context
  163. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  164. int reload; ///< reload text file for each frame
  165. int start_number; ///< starting frame number for n/frame_num var
  166. AVDictionary *metadata;
  167. } DrawTextContext;
  168. #define OFFSET(x) offsetof(DrawTextContext, x)
  169. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  170. static const AVOption drawtext_options[]= {
  171. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  172. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  173. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  174. {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  175. {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  176. {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  177. {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  178. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  179. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  180. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  181. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  182. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  183. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  184. {"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  185. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  186. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  187. #if FF_API_DRAWTEXT_OLD_TIMELINE
  188. {"draw", "if false do not draw (deprecated)", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  189. #endif
  190. #if CONFIG_LIBFONTCONFIG
  191. { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
  192. #endif
  193. {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
  194. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  195. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  196. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  197. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  198. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  199. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  200. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  201. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  202. {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  203. {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
  204. {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
  205. /* FT_LOAD_* flags */
  206. { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT }, 0, INT_MAX, FLAGS, "ft_load_flags" },
  207. { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  208. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  209. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  210. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  211. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  212. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  213. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  214. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  215. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  216. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  217. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  218. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  219. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  220. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  221. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  222. { NULL }
  223. };
  224. AVFILTER_DEFINE_CLASS(drawtext);
  225. #undef __FTERRORS_H__
  226. #define FT_ERROR_START_LIST {
  227. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  228. #define FT_ERROR_END_LIST { 0, NULL } };
  229. struct ft_error
  230. {
  231. int err;
  232. const char *err_msg;
  233. } static ft_errors[] =
  234. #include FT_ERRORS_H
  235. #define FT_ERRMSG(e) ft_errors[e].err_msg
  236. typedef struct Glyph {
  237. FT_Glyph glyph;
  238. FT_Glyph border_glyph;
  239. uint32_t code;
  240. FT_Bitmap bitmap; ///< array holding bitmaps of font
  241. FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
  242. FT_BBox bbox;
  243. int advance;
  244. int bitmap_left;
  245. int bitmap_top;
  246. } Glyph;
  247. static int glyph_cmp(void *key, const void *b)
  248. {
  249. const Glyph *a = key, *bb = b;
  250. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  251. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  252. }
  253. /**
  254. * Load glyphs corresponding to the UTF-32 codepoint code.
  255. */
  256. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  257. {
  258. DrawTextContext *s = ctx->priv;
  259. FT_BitmapGlyph bitmapglyph;
  260. Glyph *glyph;
  261. struct AVTreeNode *node = NULL;
  262. int ret;
  263. /* load glyph into s->face->glyph */
  264. if (FT_Load_Char(s->face, code, s->ft_load_flags))
  265. return AVERROR(EINVAL);
  266. glyph = av_mallocz(sizeof(*glyph));
  267. if (!glyph) {
  268. ret = AVERROR(ENOMEM);
  269. goto error;
  270. }
  271. glyph->code = code;
  272. if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
  273. ret = AVERROR(EINVAL);
  274. goto error;
  275. }
  276. if (s->borderw) {
  277. glyph->border_glyph = glyph->glyph;
  278. if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
  279. FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
  280. ret = AVERROR_EXTERNAL;
  281. goto error;
  282. }
  283. bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
  284. glyph->border_bitmap = bitmapglyph->bitmap;
  285. }
  286. if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
  287. ret = AVERROR_EXTERNAL;
  288. goto error;
  289. }
  290. bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
  291. glyph->bitmap = bitmapglyph->bitmap;
  292. glyph->bitmap_left = bitmapglyph->left;
  293. glyph->bitmap_top = bitmapglyph->top;
  294. glyph->advance = s->face->glyph->advance.x >> 6;
  295. /* measure text height to calculate text_height (or the maximum text height) */
  296. FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  297. /* cache the newly created glyph */
  298. if (!(node = av_tree_node_alloc())) {
  299. ret = AVERROR(ENOMEM);
  300. goto error;
  301. }
  302. av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
  303. if (glyph_ptr)
  304. *glyph_ptr = glyph;
  305. return 0;
  306. error:
  307. if (glyph)
  308. av_freep(&glyph->glyph);
  309. av_freep(&glyph);
  310. av_freep(&node);
  311. return ret;
  312. }
  313. static int load_font_file(AVFilterContext *ctx, const char *path, int index)
  314. {
  315. DrawTextContext *s = ctx->priv;
  316. int err;
  317. err = FT_New_Face(s->library, path, index, &s->face);
  318. if (err) {
  319. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  320. s->fontfile, FT_ERRMSG(err));
  321. return AVERROR(EINVAL);
  322. }
  323. return 0;
  324. }
  325. #if CONFIG_LIBFONTCONFIG
  326. static int load_font_fontconfig(AVFilterContext *ctx)
  327. {
  328. DrawTextContext *s = ctx->priv;
  329. FcConfig *fontconfig;
  330. FcPattern *pat, *best;
  331. FcResult result = FcResultMatch;
  332. FcChar8 *filename;
  333. int index;
  334. double size;
  335. int err = AVERROR(ENOENT);
  336. fontconfig = FcInitLoadConfigAndFonts();
  337. if (!fontconfig) {
  338. av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
  339. return AVERROR_UNKNOWN;
  340. }
  341. pat = FcNameParse(s->fontfile ? s->fontfile :
  342. (uint8_t *)(intptr_t)"default");
  343. if (!pat) {
  344. av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
  345. return AVERROR(EINVAL);
  346. }
  347. FcPatternAddString(pat, FC_FAMILY, s->font);
  348. if (s->fontsize)
  349. FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
  350. FcDefaultSubstitute(pat);
  351. if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
  352. av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
  353. FcPatternDestroy(pat);
  354. return AVERROR(ENOMEM);
  355. }
  356. best = FcFontMatch(fontconfig, pat, &result);
  357. FcPatternDestroy(pat);
  358. if (!best || result != FcResultMatch) {
  359. av_log(ctx, AV_LOG_ERROR,
  360. "Cannot find a valid font for the family %s\n",
  361. s->font);
  362. goto fail;
  363. }
  364. if (
  365. FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
  366. FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
  367. av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
  368. return AVERROR(EINVAL);
  369. }
  370. if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
  371. av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
  372. s->font);
  373. goto fail;
  374. }
  375. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  376. if (!s->fontsize)
  377. s->fontsize = size + 0.5;
  378. err = load_font_file(ctx, filename, index);
  379. if (err)
  380. return err;
  381. FcConfigDestroy(fontconfig);
  382. fail:
  383. FcPatternDestroy(best);
  384. return err;
  385. }
  386. #endif
  387. static int load_font(AVFilterContext *ctx)
  388. {
  389. DrawTextContext *s = ctx->priv;
  390. int err;
  391. /* load the face, and set up the encoding, which is by default UTF-8 */
  392. err = load_font_file(ctx, s->fontfile, 0);
  393. if (!err)
  394. return 0;
  395. #if CONFIG_LIBFONTCONFIG
  396. err = load_font_fontconfig(ctx);
  397. if (!err)
  398. return 0;
  399. #endif
  400. return err;
  401. }
  402. static int load_textfile(AVFilterContext *ctx)
  403. {
  404. DrawTextContext *s = ctx->priv;
  405. int err;
  406. uint8_t *textbuf;
  407. uint8_t *tmp;
  408. size_t textbuf_size;
  409. if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  410. av_log(ctx, AV_LOG_ERROR,
  411. "The text file '%s' could not be read or is empty\n",
  412. s->textfile);
  413. return err;
  414. }
  415. if (!(tmp = av_realloc(s->text, textbuf_size + 1))) {
  416. av_file_unmap(textbuf, textbuf_size);
  417. return AVERROR(ENOMEM);
  418. }
  419. s->text = tmp;
  420. memcpy(s->text, textbuf, textbuf_size);
  421. s->text[textbuf_size] = 0;
  422. av_file_unmap(textbuf, textbuf_size);
  423. return 0;
  424. }
  425. static av_cold int init(AVFilterContext *ctx)
  426. {
  427. int err;
  428. DrawTextContext *s = ctx->priv;
  429. Glyph *glyph;
  430. #if FF_API_DRAWTEXT_OLD_TIMELINE
  431. if (s->draw_expr)
  432. av_log(ctx, AV_LOG_WARNING, "'draw' option is deprecated and will be removed soon, "
  433. "you are encouraged to use the generic timeline support through the 'enable' option\n");
  434. #endif
  435. if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
  436. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  437. return AVERROR(EINVAL);
  438. }
  439. if (s->textfile) {
  440. if (s->text) {
  441. av_log(ctx, AV_LOG_ERROR,
  442. "Both text and text file provided. Please provide only one\n");
  443. return AVERROR(EINVAL);
  444. }
  445. if ((err = load_textfile(ctx)) < 0)
  446. return err;
  447. }
  448. if (s->reload && !s->textfile)
  449. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  450. if (s->tc_opt_string) {
  451. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  452. s->tc_opt_string, ctx);
  453. if (ret < 0)
  454. return ret;
  455. if (s->tc24hmax)
  456. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  457. if (!s->text)
  458. s->text = av_strdup("");
  459. }
  460. if (!s->text) {
  461. av_log(ctx, AV_LOG_ERROR,
  462. "Either text, a valid file or a timecode must be provided\n");
  463. return AVERROR(EINVAL);
  464. }
  465. if ((err = FT_Init_FreeType(&(s->library)))) {
  466. av_log(ctx, AV_LOG_ERROR,
  467. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  468. return AVERROR(EINVAL);
  469. }
  470. err = load_font(ctx);
  471. if (err)
  472. return err;
  473. if (!s->fontsize)
  474. s->fontsize = 16;
  475. if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
  476. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  477. s->fontsize, FT_ERRMSG(err));
  478. return AVERROR(EINVAL);
  479. }
  480. if (s->borderw) {
  481. if (FT_Stroker_New(s->library, &s->stroker)) {
  482. av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
  483. return AVERROR_EXTERNAL;
  484. }
  485. FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
  486. FT_STROKER_LINEJOIN_ROUND, 0);
  487. }
  488. s->use_kerning = FT_HAS_KERNING(s->face);
  489. /* load the fallback glyph with code 0 */
  490. load_glyph(ctx, NULL, 0);
  491. /* set the tabsize in pixels */
  492. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  493. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  494. return err;
  495. }
  496. s->tabsize *= glyph->advance;
  497. if (s->exp_mode == EXP_STRFTIME &&
  498. (strchr(s->text, '%') || strchr(s->text, '\\')))
  499. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  500. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  501. return 0;
  502. }
  503. static int query_formats(AVFilterContext *ctx)
  504. {
  505. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  506. return 0;
  507. }
  508. static int glyph_enu_free(void *opaque, void *elem)
  509. {
  510. Glyph *glyph = elem;
  511. FT_Done_Glyph(glyph->glyph);
  512. FT_Done_Glyph(glyph->border_glyph);
  513. av_free(elem);
  514. return 0;
  515. }
  516. static av_cold void uninit(AVFilterContext *ctx)
  517. {
  518. DrawTextContext *s = ctx->priv;
  519. av_expr_free(s->x_pexpr);
  520. av_expr_free(s->y_pexpr);
  521. #if FF_API_DRAWTEXT_OLD_TIMELINE
  522. av_expr_free(s->draw_pexpr);
  523. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  524. #endif
  525. av_freep(&s->positions);
  526. s->nb_positions = 0;
  527. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  528. av_tree_destroy(s->glyphs);
  529. s->glyphs = NULL;
  530. FT_Done_Face(s->face);
  531. FT_Stroker_Done(s->stroker);
  532. FT_Done_FreeType(s->library);
  533. av_bprint_finalize(&s->expanded_text, NULL);
  534. }
  535. static inline int is_newline(uint32_t c)
  536. {
  537. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  538. }
  539. static int config_input(AVFilterLink *inlink)
  540. {
  541. AVFilterContext *ctx = inlink->dst;
  542. DrawTextContext *s = ctx->priv;
  543. int ret;
  544. ff_draw_init(&s->dc, inlink->format, 0);
  545. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  546. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  547. ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
  548. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  549. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  550. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  551. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  552. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  553. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  554. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  555. s->var_values[VAR_X] = NAN;
  556. s->var_values[VAR_Y] = NAN;
  557. s->var_values[VAR_T] = NAN;
  558. av_lfg_init(&s->prng, av_get_random_seed());
  559. av_expr_free(s->x_pexpr);
  560. av_expr_free(s->y_pexpr);
  561. #if FF_API_DRAWTEXT_OLD_TIMELINE
  562. av_expr_free(s->draw_pexpr);
  563. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  564. #else
  565. s->x_pexpr = s->y_pexpr = NULL;
  566. #endif
  567. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  568. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  569. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  570. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  571. return AVERROR(EINVAL);
  572. #if FF_API_DRAWTEXT_OLD_TIMELINE
  573. if (s->draw_expr &&
  574. (ret = av_expr_parse(&s->draw_pexpr, s->draw_expr, var_names,
  575. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  576. return ret;
  577. #endif
  578. return 0;
  579. }
  580. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  581. {
  582. DrawTextContext *s = ctx->priv;
  583. if (!strcmp(cmd, "reinit")) {
  584. int ret;
  585. uninit(ctx);
  586. s->reinit = 1;
  587. if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
  588. return ret;
  589. if ((ret = init(ctx)) < 0)
  590. return ret;
  591. return config_input(ctx->inputs[0]);
  592. }
  593. return AVERROR(ENOSYS);
  594. }
  595. static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
  596. char *fct, unsigned argc, char **argv, int tag)
  597. {
  598. DrawTextContext *s = ctx->priv;
  599. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  600. return 0;
  601. }
  602. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  603. char *fct, unsigned argc, char **argv, int tag)
  604. {
  605. DrawTextContext *s = ctx->priv;
  606. const char *fmt;
  607. double pts = s->var_values[VAR_T];
  608. int ret;
  609. fmt = argc >= 1 ? argv[0] : "flt";
  610. if (argc >= 2) {
  611. int64_t delta;
  612. if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
  613. av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
  614. return ret;
  615. }
  616. pts += (double)delta / AV_TIME_BASE;
  617. }
  618. if (!strcmp(fmt, "flt")) {
  619. av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
  620. } else if (!strcmp(fmt, "hms")) {
  621. if (isnan(pts)) {
  622. av_bprintf(bp, " ??:??:??.???");
  623. } else {
  624. int64_t ms = round(pts * 1000);
  625. char sign = ' ';
  626. if (ms < 0) {
  627. sign = '-';
  628. ms = -ms;
  629. }
  630. av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
  631. (int)(ms / (60 * 60 * 1000)),
  632. (int)(ms / (60 * 1000)) % 60,
  633. (int)(ms / 1000) % 60,
  634. (int)ms % 1000);
  635. }
  636. } else {
  637. av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
  638. return AVERROR(EINVAL);
  639. }
  640. return 0;
  641. }
  642. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  643. char *fct, unsigned argc, char **argv, int tag)
  644. {
  645. DrawTextContext *s = ctx->priv;
  646. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  647. return 0;
  648. }
  649. static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
  650. char *fct, unsigned argc, char **argv, int tag)
  651. {
  652. DrawTextContext *s = ctx->priv;
  653. AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
  654. if (e && e->value)
  655. av_bprintf(bp, "%s", e->value);
  656. return 0;
  657. }
  658. #if !HAVE_LOCALTIME_R
  659. static void localtime_r(const time_t *t, struct tm *tm)
  660. {
  661. *tm = *localtime(t);
  662. }
  663. #endif
  664. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  665. char *fct, unsigned argc, char **argv, int tag)
  666. {
  667. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  668. time_t now;
  669. struct tm tm;
  670. time(&now);
  671. if (tag == 'L')
  672. localtime_r(&now, &tm);
  673. else
  674. tm = *gmtime(&now);
  675. av_bprint_strftime(bp, fmt, &tm);
  676. return 0;
  677. }
  678. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  679. char *fct, unsigned argc, char **argv, int tag)
  680. {
  681. DrawTextContext *s = ctx->priv;
  682. double res;
  683. int ret;
  684. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  685. NULL, NULL, fun2_names, fun2,
  686. &s->prng, 0, ctx);
  687. if (ret < 0)
  688. av_log(ctx, AV_LOG_ERROR,
  689. "Expression '%s' for the expr text expansion function is not valid\n",
  690. argv[0]);
  691. else
  692. av_bprintf(bp, "%f", res);
  693. return ret;
  694. }
  695. static const struct drawtext_function {
  696. const char *name;
  697. unsigned argc_min, argc_max;
  698. int tag; /**< opaque argument to func */
  699. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  700. } functions[] = {
  701. { "expr", 1, 1, 0, func_eval_expr },
  702. { "e", 1, 1, 0, func_eval_expr },
  703. { "pict_type", 0, 0, 0, func_pict_type },
  704. { "pts", 0, 2, 0, func_pts },
  705. { "gmtime", 0, 1, 'G', func_strftime },
  706. { "localtime", 0, 1, 'L', func_strftime },
  707. { "frame_num", 0, 0, 0, func_frame_num },
  708. { "n", 0, 0, 0, func_frame_num },
  709. { "metadata", 1, 1, 0, func_metadata },
  710. };
  711. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  712. unsigned argc, char **argv)
  713. {
  714. unsigned i;
  715. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  716. if (strcmp(fct, functions[i].name))
  717. continue;
  718. if (argc < functions[i].argc_min) {
  719. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  720. fct, functions[i].argc_min);
  721. return AVERROR(EINVAL);
  722. }
  723. if (argc > functions[i].argc_max) {
  724. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  725. fct, functions[i].argc_max);
  726. return AVERROR(EINVAL);
  727. }
  728. break;
  729. }
  730. if (i >= FF_ARRAY_ELEMS(functions)) {
  731. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  732. return AVERROR(EINVAL);
  733. }
  734. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  735. }
  736. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  737. {
  738. const char *text = *rtext;
  739. char *argv[16] = { NULL };
  740. unsigned argc = 0, i;
  741. int ret;
  742. if (*text != '{') {
  743. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  744. return AVERROR(EINVAL);
  745. }
  746. text++;
  747. while (1) {
  748. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  749. ret = AVERROR(ENOMEM);
  750. goto end;
  751. }
  752. if (!*text) {
  753. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  754. ret = AVERROR(EINVAL);
  755. goto end;
  756. }
  757. if (argc == FF_ARRAY_ELEMS(argv))
  758. av_freep(&argv[--argc]); /* error will be caught later */
  759. if (*text == '}')
  760. break;
  761. text++;
  762. }
  763. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  764. goto end;
  765. ret = 0;
  766. *rtext = (char *)text + 1;
  767. end:
  768. for (i = 0; i < argc; i++)
  769. av_freep(&argv[i]);
  770. return ret;
  771. }
  772. static int expand_text(AVFilterContext *ctx)
  773. {
  774. DrawTextContext *s = ctx->priv;
  775. char *text = s->text;
  776. AVBPrint *bp = &s->expanded_text;
  777. int ret;
  778. av_bprint_clear(bp);
  779. while (*text) {
  780. if (*text == '\\' && text[1]) {
  781. av_bprint_chars(bp, text[1], 1);
  782. text += 2;
  783. } else if (*text == '%') {
  784. text++;
  785. if ((ret = expand_function(ctx, bp, &text)) < 0)
  786. return ret;
  787. } else {
  788. av_bprint_chars(bp, *text, 1);
  789. text++;
  790. }
  791. }
  792. if (!av_bprint_is_complete(bp))
  793. return AVERROR(ENOMEM);
  794. return 0;
  795. }
  796. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  797. int width, int height,
  798. FFDrawColor *color, int x, int y, int borderw)
  799. {
  800. char *text = s->expanded_text.str;
  801. uint32_t code = 0;
  802. int i, x1, y1;
  803. uint8_t *p;
  804. Glyph *glyph = NULL;
  805. for (i = 0, p = text; *p; i++) {
  806. FT_Bitmap bitmap;
  807. Glyph dummy = { 0 };
  808. GET_UTF8(code, *p++, continue;);
  809. /* skip new line chars, just go to new line */
  810. if (code == '\n' || code == '\r' || code == '\t')
  811. continue;
  812. dummy.code = code;
  813. glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
  814. bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
  815. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  816. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  817. return AVERROR(EINVAL);
  818. x1 = s->positions[i].x+s->x+x - borderw;
  819. y1 = s->positions[i].y+s->y+y - borderw;
  820. ff_blend_mask(&s->dc, color,
  821. frame->data, frame->linesize, width, height,
  822. bitmap.buffer, bitmap.pitch,
  823. bitmap.width, bitmap.rows,
  824. bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  825. 0, x1, y1);
  826. }
  827. return 0;
  828. }
  829. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  830. int width, int height)
  831. {
  832. DrawTextContext *s = ctx->priv;
  833. AVFilterLink *inlink = ctx->inputs[0];
  834. uint32_t code = 0, prev_code = 0;
  835. int x = 0, y = 0, i = 0, ret;
  836. int max_text_line_w = 0, len;
  837. int box_w, box_h;
  838. char *text;
  839. uint8_t *p;
  840. int y_min = 32000, y_max = -32000;
  841. int x_min = 32000, x_max = -32000;
  842. FT_Vector delta;
  843. Glyph *glyph = NULL, *prev_glyph = NULL;
  844. Glyph dummy = { 0 };
  845. time_t now = time(0);
  846. struct tm ltime;
  847. AVBPrint *bp = &s->expanded_text;
  848. av_bprint_clear(bp);
  849. if(s->basetime != AV_NOPTS_VALUE)
  850. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  851. switch (s->exp_mode) {
  852. case EXP_NONE:
  853. av_bprintf(bp, "%s", s->text);
  854. break;
  855. case EXP_NORMAL:
  856. if ((ret = expand_text(ctx)) < 0)
  857. return ret;
  858. break;
  859. case EXP_STRFTIME:
  860. localtime_r(&now, &ltime);
  861. av_bprint_strftime(bp, s->text, &ltime);
  862. break;
  863. }
  864. if (s->tc_opt_string) {
  865. char tcbuf[AV_TIMECODE_STR_SIZE];
  866. av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
  867. av_bprint_clear(bp);
  868. av_bprintf(bp, "%s%s", s->text, tcbuf);
  869. }
  870. if (!av_bprint_is_complete(bp))
  871. return AVERROR(ENOMEM);
  872. text = s->expanded_text.str;
  873. if ((len = s->expanded_text.len) > s->nb_positions) {
  874. if (!(s->positions =
  875. av_realloc(s->positions, len*sizeof(*s->positions))))
  876. return AVERROR(ENOMEM);
  877. s->nb_positions = len;
  878. }
  879. x = 0;
  880. y = 0;
  881. /* load and cache glyphs */
  882. for (i = 0, p = text; *p; i++) {
  883. GET_UTF8(code, *p++, continue;);
  884. /* get glyph */
  885. dummy.code = code;
  886. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  887. if (!glyph) {
  888. load_glyph(ctx, &glyph, code);
  889. }
  890. y_min = FFMIN(glyph->bbox.yMin, y_min);
  891. y_max = FFMAX(glyph->bbox.yMax, y_max);
  892. x_min = FFMIN(glyph->bbox.xMin, x_min);
  893. x_max = FFMAX(glyph->bbox.xMax, x_max);
  894. }
  895. s->max_glyph_h = y_max - y_min;
  896. s->max_glyph_w = x_max - x_min;
  897. /* compute and save position for each glyph */
  898. glyph = NULL;
  899. for (i = 0, p = text; *p; i++) {
  900. GET_UTF8(code, *p++, continue;);
  901. /* skip the \n in the sequence \r\n */
  902. if (prev_code == '\r' && code == '\n')
  903. continue;
  904. prev_code = code;
  905. if (is_newline(code)) {
  906. max_text_line_w = FFMAX(max_text_line_w, x);
  907. y += s->max_glyph_h;
  908. x = 0;
  909. continue;
  910. }
  911. /* get glyph */
  912. prev_glyph = glyph;
  913. dummy.code = code;
  914. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  915. /* kerning */
  916. if (s->use_kerning && prev_glyph && glyph->code) {
  917. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  918. ft_kerning_default, &delta);
  919. x += delta.x >> 6;
  920. }
  921. /* save position */
  922. s->positions[i].x = x + glyph->bitmap_left;
  923. s->positions[i].y = y - glyph->bitmap_top + y_max;
  924. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  925. else x += glyph->advance;
  926. }
  927. max_text_line_w = FFMAX(x, max_text_line_w);
  928. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
  929. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
  930. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  931. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  932. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
  933. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
  934. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
  935. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  936. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  937. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  938. #if FF_API_DRAWTEXT_OLD_TIMELINE
  939. if (s->draw_pexpr){
  940. s->draw = av_expr_eval(s->draw_pexpr, s->var_values, &s->prng);
  941. if(!s->draw)
  942. return 0;
  943. }
  944. if (ctx->is_disabled)
  945. return 0;
  946. #endif
  947. box_w = FFMIN(width - 1 , max_text_line_w);
  948. box_h = FFMIN(height - 1, y + s->max_glyph_h);
  949. /* draw box */
  950. if (s->draw_box)
  951. ff_blend_rectangle(&s->dc, &s->boxcolor,
  952. frame->data, frame->linesize, width, height,
  953. s->x, s->y, box_w, box_h);
  954. if (s->shadowx || s->shadowy) {
  955. if ((ret = draw_glyphs(s, frame, width, height,
  956. &s->shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
  957. return ret;
  958. }
  959. if (s->borderw) {
  960. if ((ret = draw_glyphs(s, frame, width, height,
  961. &s->bordercolor, 0, 0, s->borderw)) < 0)
  962. return ret;
  963. }
  964. if ((ret = draw_glyphs(s, frame, width, height,
  965. &s->fontcolor, 0, 0, 0)) < 0)
  966. return ret;
  967. return 0;
  968. }
  969. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  970. {
  971. AVFilterContext *ctx = inlink->dst;
  972. AVFilterLink *outlink = ctx->outputs[0];
  973. DrawTextContext *s = ctx->priv;
  974. int ret;
  975. if (s->reload)
  976. if ((ret = load_textfile(ctx)) < 0)
  977. return ret;
  978. s->var_values[VAR_N] = inlink->frame_count+s->start_number;
  979. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  980. NAN : frame->pts * av_q2d(inlink->time_base);
  981. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  982. s->metadata = av_frame_get_metadata(frame);
  983. draw_text(ctx, frame, frame->width, frame->height);
  984. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  985. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  986. (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
  987. s->x, s->y);
  988. return ff_filter_frame(outlink, frame);
  989. }
  990. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  991. {
  992. .name = "default",
  993. .type = AVMEDIA_TYPE_VIDEO,
  994. .filter_frame = filter_frame,
  995. .config_props = config_input,
  996. .needs_writable = 1,
  997. },
  998. { NULL }
  999. };
  1000. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  1001. {
  1002. .name = "default",
  1003. .type = AVMEDIA_TYPE_VIDEO,
  1004. },
  1005. { NULL }
  1006. };
  1007. AVFilter ff_vf_drawtext = {
  1008. .name = "drawtext",
  1009. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  1010. .priv_size = sizeof(DrawTextContext),
  1011. .priv_class = &drawtext_class,
  1012. .init = init,
  1013. .uninit = uninit,
  1014. .query_formats = query_formats,
  1015. .inputs = avfilter_vf_drawtext_inputs,
  1016. .outputs = avfilter_vf_drawtext_outputs,
  1017. .process_command = command,
  1018. #if FF_API_DRAWTEXT_OLD_TIMELINE
  1019. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL,
  1020. #else
  1021. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
  1022. #endif
  1023. };