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.

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