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.

1152 lines
39KB

  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. uint32_t code;
  239. FT_Bitmap bitmap; ///< array holding bitmaps of font
  240. FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
  241. FT_BBox bbox;
  242. int advance;
  243. int bitmap_left;
  244. int bitmap_top;
  245. } Glyph;
  246. static int glyph_cmp(void *key, const void *b)
  247. {
  248. const Glyph *a = key, *bb = b;
  249. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  250. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  251. }
  252. /**
  253. * Load glyphs corresponding to the UTF-32 codepoint code.
  254. */
  255. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  256. {
  257. DrawTextContext *s = ctx->priv;
  258. FT_BitmapGlyph bitmapglyph;
  259. Glyph *glyph;
  260. struct AVTreeNode *node = NULL;
  261. int ret;
  262. /* load glyph into s->face->glyph */
  263. if (FT_Load_Char(s->face, code, s->ft_load_flags))
  264. return AVERROR(EINVAL);
  265. /* save glyph */
  266. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  267. !(glyph->glyph = av_mallocz(sizeof(*glyph->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. FT_Glyph border_glyph = *glyph->glyph;
  278. if (FT_Glyph_StrokeBorder(&border_glyph, s->stroker, 0, 0) ||
  279. FT_Glyph_To_Bitmap(&border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
  280. ret = AVERROR_EXTERNAL;
  281. goto error;
  282. }
  283. bitmapglyph = (FT_BitmapGlyph) 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. size_t textbuf_size;
  408. if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  409. av_log(ctx, AV_LOG_ERROR,
  410. "The text file '%s' could not be read or is empty\n",
  411. s->textfile);
  412. return err;
  413. }
  414. if (!(s->text = av_realloc(s->text, textbuf_size + 1)))
  415. return AVERROR(ENOMEM);
  416. memcpy(s->text, textbuf, textbuf_size);
  417. s->text[textbuf_size] = 0;
  418. av_file_unmap(textbuf, textbuf_size);
  419. return 0;
  420. }
  421. static av_cold int init(AVFilterContext *ctx)
  422. {
  423. int err;
  424. DrawTextContext *s = ctx->priv;
  425. Glyph *glyph;
  426. #if FF_API_DRAWTEXT_OLD_TIMELINE
  427. if (s->draw_expr)
  428. av_log(ctx, AV_LOG_WARNING, "'draw' option is deprecated and will be removed soon, "
  429. "you are encouraged to use the generic timeline support through the 'enable' option\n");
  430. #endif
  431. if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
  432. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  433. return AVERROR(EINVAL);
  434. }
  435. if (s->textfile) {
  436. if (s->text) {
  437. av_log(ctx, AV_LOG_ERROR,
  438. "Both text and text file provided. Please provide only one\n");
  439. return AVERROR(EINVAL);
  440. }
  441. if ((err = load_textfile(ctx)) < 0)
  442. return err;
  443. }
  444. if (s->reload && !s->textfile)
  445. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  446. if (s->tc_opt_string) {
  447. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  448. s->tc_opt_string, ctx);
  449. if (ret < 0)
  450. return ret;
  451. if (s->tc24hmax)
  452. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  453. if (!s->text)
  454. s->text = av_strdup("");
  455. }
  456. if (!s->text) {
  457. av_log(ctx, AV_LOG_ERROR,
  458. "Either text, a valid file or a timecode must be provided\n");
  459. return AVERROR(EINVAL);
  460. }
  461. if ((err = FT_Init_FreeType(&(s->library)))) {
  462. av_log(ctx, AV_LOG_ERROR,
  463. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  464. return AVERROR(EINVAL);
  465. }
  466. err = load_font(ctx);
  467. if (err)
  468. return err;
  469. if (!s->fontsize)
  470. s->fontsize = 16;
  471. if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
  472. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  473. s->fontsize, FT_ERRMSG(err));
  474. return AVERROR(EINVAL);
  475. }
  476. if (s->borderw) {
  477. if (FT_Stroker_New(s->library, &s->stroker)) {
  478. av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
  479. return AVERROR_EXTERNAL;
  480. }
  481. FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
  482. FT_STROKER_LINEJOIN_ROUND, 0);
  483. }
  484. s->use_kerning = FT_HAS_KERNING(s->face);
  485. /* load the fallback glyph with code 0 */
  486. load_glyph(ctx, NULL, 0);
  487. /* set the tabsize in pixels */
  488. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  489. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  490. return err;
  491. }
  492. s->tabsize *= glyph->advance;
  493. if (s->exp_mode == EXP_STRFTIME &&
  494. (strchr(s->text, '%') || strchr(s->text, '\\')))
  495. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  496. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  497. return 0;
  498. }
  499. static int query_formats(AVFilterContext *ctx)
  500. {
  501. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  502. return 0;
  503. }
  504. static int glyph_enu_free(void *opaque, void *elem)
  505. {
  506. Glyph *glyph = elem;
  507. FT_Done_Glyph(*glyph->glyph);
  508. av_freep(&glyph->glyph);
  509. av_free(elem);
  510. return 0;
  511. }
  512. static av_cold void uninit(AVFilterContext *ctx)
  513. {
  514. DrawTextContext *s = ctx->priv;
  515. av_expr_free(s->x_pexpr);
  516. av_expr_free(s->y_pexpr);
  517. #if FF_API_DRAWTEXT_OLD_TIMELINE
  518. av_expr_free(s->draw_pexpr);
  519. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  520. #endif
  521. av_freep(&s->positions);
  522. s->nb_positions = 0;
  523. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  524. av_tree_destroy(s->glyphs);
  525. s->glyphs = NULL;
  526. FT_Done_Face(s->face);
  527. FT_Stroker_Done(s->stroker);
  528. FT_Done_FreeType(s->library);
  529. av_bprint_finalize(&s->expanded_text, NULL);
  530. }
  531. static inline int is_newline(uint32_t c)
  532. {
  533. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  534. }
  535. static int config_input(AVFilterLink *inlink)
  536. {
  537. AVFilterContext *ctx = inlink->dst;
  538. DrawTextContext *s = ctx->priv;
  539. int ret;
  540. ff_draw_init(&s->dc, inlink->format, 0);
  541. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  542. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  543. ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
  544. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  545. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  546. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  547. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  548. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  549. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  550. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  551. s->var_values[VAR_X] = NAN;
  552. s->var_values[VAR_Y] = NAN;
  553. s->var_values[VAR_T] = NAN;
  554. av_lfg_init(&s->prng, av_get_random_seed());
  555. av_expr_free(s->x_pexpr);
  556. av_expr_free(s->y_pexpr);
  557. #if FF_API_DRAWTEXT_OLD_TIMELINE
  558. av_expr_free(s->draw_pexpr);
  559. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  560. #else
  561. s->x_pexpr = s->y_pexpr = NULL;
  562. #endif
  563. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  564. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  565. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  566. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  567. return AVERROR(EINVAL);
  568. #if FF_API_DRAWTEXT_OLD_TIMELINE
  569. if (s->draw_expr &&
  570. (ret = av_expr_parse(&s->draw_pexpr, s->draw_expr, var_names,
  571. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  572. return ret;
  573. #endif
  574. return 0;
  575. }
  576. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  577. {
  578. DrawTextContext *s = ctx->priv;
  579. if (!strcmp(cmd, "reinit")) {
  580. int ret;
  581. uninit(ctx);
  582. s->reinit = 1;
  583. if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
  584. return ret;
  585. if ((ret = init(ctx)) < 0)
  586. return ret;
  587. return config_input(ctx->inputs[0]);
  588. }
  589. return AVERROR(ENOSYS);
  590. }
  591. static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
  592. char *fct, unsigned argc, char **argv, int tag)
  593. {
  594. DrawTextContext *s = ctx->priv;
  595. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  596. return 0;
  597. }
  598. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  599. char *fct, unsigned argc, char **argv, int tag)
  600. {
  601. DrawTextContext *s = ctx->priv;
  602. av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
  603. return 0;
  604. }
  605. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  606. char *fct, unsigned argc, char **argv, int tag)
  607. {
  608. DrawTextContext *s = ctx->priv;
  609. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  610. return 0;
  611. }
  612. static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
  613. char *fct, unsigned argc, char **argv, int tag)
  614. {
  615. DrawTextContext *s = ctx->priv;
  616. AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
  617. if (e && e->value)
  618. av_bprintf(bp, "%s", e->value);
  619. return 0;
  620. }
  621. #if !HAVE_LOCALTIME_R
  622. static void localtime_r(const time_t *t, struct tm *tm)
  623. {
  624. *tm = *localtime(t);
  625. }
  626. #endif
  627. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  628. char *fct, unsigned argc, char **argv, int tag)
  629. {
  630. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  631. time_t now;
  632. struct tm tm;
  633. time(&now);
  634. if (tag == 'L')
  635. localtime_r(&now, &tm);
  636. else
  637. tm = *gmtime(&now);
  638. av_bprint_strftime(bp, fmt, &tm);
  639. return 0;
  640. }
  641. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  642. char *fct, unsigned argc, char **argv, int tag)
  643. {
  644. DrawTextContext *s = ctx->priv;
  645. double res;
  646. int ret;
  647. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  648. NULL, NULL, fun2_names, fun2,
  649. &s->prng, 0, ctx);
  650. if (ret < 0)
  651. av_log(ctx, AV_LOG_ERROR,
  652. "Expression '%s' for the expr text expansion function is not valid\n",
  653. argv[0]);
  654. else
  655. av_bprintf(bp, "%f", res);
  656. return ret;
  657. }
  658. static const struct drawtext_function {
  659. const char *name;
  660. unsigned argc_min, argc_max;
  661. int tag; /**< opaque argument to func */
  662. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  663. } functions[] = {
  664. { "expr", 1, 1, 0, func_eval_expr },
  665. { "e", 1, 1, 0, func_eval_expr },
  666. { "pict_type", 0, 0, 0, func_pict_type },
  667. { "pts", 0, 0, 0, func_pts },
  668. { "gmtime", 0, 1, 'G', func_strftime },
  669. { "localtime", 0, 1, 'L', func_strftime },
  670. { "frame_num", 0, 0, 0, func_frame_num },
  671. { "n", 0, 0, 0, func_frame_num },
  672. { "metadata", 1, 1, 0, func_metadata },
  673. };
  674. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  675. unsigned argc, char **argv)
  676. {
  677. unsigned i;
  678. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  679. if (strcmp(fct, functions[i].name))
  680. continue;
  681. if (argc < functions[i].argc_min) {
  682. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  683. fct, functions[i].argc_min);
  684. return AVERROR(EINVAL);
  685. }
  686. if (argc > functions[i].argc_max) {
  687. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  688. fct, functions[i].argc_max);
  689. return AVERROR(EINVAL);
  690. }
  691. break;
  692. }
  693. if (i >= FF_ARRAY_ELEMS(functions)) {
  694. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  695. return AVERROR(EINVAL);
  696. }
  697. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  698. }
  699. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  700. {
  701. const char *text = *rtext;
  702. char *argv[16] = { NULL };
  703. unsigned argc = 0, i;
  704. int ret;
  705. if (*text != '{') {
  706. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  707. return AVERROR(EINVAL);
  708. }
  709. text++;
  710. while (1) {
  711. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  712. ret = AVERROR(ENOMEM);
  713. goto end;
  714. }
  715. if (!*text) {
  716. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  717. ret = AVERROR(EINVAL);
  718. goto end;
  719. }
  720. if (argc == FF_ARRAY_ELEMS(argv))
  721. av_freep(&argv[--argc]); /* error will be caught later */
  722. if (*text == '}')
  723. break;
  724. text++;
  725. }
  726. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  727. goto end;
  728. ret = 0;
  729. *rtext = (char *)text + 1;
  730. end:
  731. for (i = 0; i < argc; i++)
  732. av_freep(&argv[i]);
  733. return ret;
  734. }
  735. static int expand_text(AVFilterContext *ctx)
  736. {
  737. DrawTextContext *s = ctx->priv;
  738. char *text = s->text;
  739. AVBPrint *bp = &s->expanded_text;
  740. int ret;
  741. av_bprint_clear(bp);
  742. while (*text) {
  743. if (*text == '\\' && text[1]) {
  744. av_bprint_chars(bp, text[1], 1);
  745. text += 2;
  746. } else if (*text == '%') {
  747. text++;
  748. if ((ret = expand_function(ctx, bp, &text)) < 0)
  749. return ret;
  750. } else {
  751. av_bprint_chars(bp, *text, 1);
  752. text++;
  753. }
  754. }
  755. if (!av_bprint_is_complete(bp))
  756. return AVERROR(ENOMEM);
  757. return 0;
  758. }
  759. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  760. int width, int height, const uint8_t rgbcolor[4],
  761. FFDrawColor *color, int x, int y, int borderw)
  762. {
  763. char *text = s->expanded_text.str;
  764. uint32_t code = 0;
  765. int i, x1, y1;
  766. uint8_t *p;
  767. Glyph *glyph = NULL;
  768. for (i = 0, p = text; *p; i++) {
  769. FT_Bitmap bitmap;
  770. Glyph dummy = { 0 };
  771. GET_UTF8(code, *p++, continue;);
  772. /* skip new line chars, just go to new line */
  773. if (code == '\n' || code == '\r' || code == '\t')
  774. continue;
  775. dummy.code = code;
  776. glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
  777. bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
  778. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  779. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  780. return AVERROR(EINVAL);
  781. x1 = s->positions[i].x+s->x+x - borderw;
  782. y1 = s->positions[i].y+s->y+y - borderw;
  783. ff_blend_mask(&s->dc, color,
  784. frame->data, frame->linesize, width, height,
  785. bitmap.buffer, bitmap.pitch,
  786. bitmap.width, bitmap.rows,
  787. bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  788. 0, x1, y1);
  789. }
  790. return 0;
  791. }
  792. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  793. int width, int height)
  794. {
  795. DrawTextContext *s = ctx->priv;
  796. AVFilterLink *inlink = ctx->inputs[0];
  797. uint32_t code = 0, prev_code = 0;
  798. int x = 0, y = 0, i = 0, ret;
  799. int max_text_line_w = 0, len;
  800. int box_w, box_h;
  801. char *text;
  802. uint8_t *p;
  803. int y_min = 32000, y_max = -32000;
  804. int x_min = 32000, x_max = -32000;
  805. FT_Vector delta;
  806. Glyph *glyph = NULL, *prev_glyph = NULL;
  807. Glyph dummy = { 0 };
  808. time_t now = time(0);
  809. struct tm ltime;
  810. AVBPrint *bp = &s->expanded_text;
  811. av_bprint_clear(bp);
  812. if(s->basetime != AV_NOPTS_VALUE)
  813. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  814. switch (s->exp_mode) {
  815. case EXP_NONE:
  816. av_bprintf(bp, "%s", s->text);
  817. break;
  818. case EXP_NORMAL:
  819. if ((ret = expand_text(ctx)) < 0)
  820. return ret;
  821. break;
  822. case EXP_STRFTIME:
  823. localtime_r(&now, &ltime);
  824. av_bprint_strftime(bp, s->text, &ltime);
  825. break;
  826. }
  827. if (s->tc_opt_string) {
  828. char tcbuf[AV_TIMECODE_STR_SIZE];
  829. av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
  830. av_bprint_clear(bp);
  831. av_bprintf(bp, "%s%s", s->text, tcbuf);
  832. }
  833. if (!av_bprint_is_complete(bp))
  834. return AVERROR(ENOMEM);
  835. text = s->expanded_text.str;
  836. if ((len = s->expanded_text.len) > s->nb_positions) {
  837. if (!(s->positions =
  838. av_realloc(s->positions, len*sizeof(*s->positions))))
  839. return AVERROR(ENOMEM);
  840. s->nb_positions = len;
  841. }
  842. x = 0;
  843. y = 0;
  844. /* load and cache glyphs */
  845. for (i = 0, p = text; *p; i++) {
  846. GET_UTF8(code, *p++, continue;);
  847. /* get glyph */
  848. dummy.code = code;
  849. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  850. if (!glyph) {
  851. load_glyph(ctx, &glyph, code);
  852. }
  853. y_min = FFMIN(glyph->bbox.yMin, y_min);
  854. y_max = FFMAX(glyph->bbox.yMax, y_max);
  855. x_min = FFMIN(glyph->bbox.xMin, x_min);
  856. x_max = FFMAX(glyph->bbox.xMax, x_max);
  857. }
  858. s->max_glyph_h = y_max - y_min;
  859. s->max_glyph_w = x_max - x_min;
  860. /* compute and save position for each glyph */
  861. glyph = NULL;
  862. for (i = 0, p = text; *p; i++) {
  863. GET_UTF8(code, *p++, continue;);
  864. /* skip the \n in the sequence \r\n */
  865. if (prev_code == '\r' && code == '\n')
  866. continue;
  867. prev_code = code;
  868. if (is_newline(code)) {
  869. max_text_line_w = FFMAX(max_text_line_w, x);
  870. y += s->max_glyph_h;
  871. x = 0;
  872. continue;
  873. }
  874. /* get glyph */
  875. prev_glyph = glyph;
  876. dummy.code = code;
  877. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  878. /* kerning */
  879. if (s->use_kerning && prev_glyph && glyph->code) {
  880. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  881. ft_kerning_default, &delta);
  882. x += delta.x >> 6;
  883. }
  884. /* save position */
  885. s->positions[i].x = x + glyph->bitmap_left;
  886. s->positions[i].y = y - glyph->bitmap_top + y_max;
  887. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  888. else x += glyph->advance;
  889. }
  890. max_text_line_w = FFMAX(x, max_text_line_w);
  891. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
  892. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
  893. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  894. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  895. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
  896. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
  897. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
  898. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  899. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  900. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  901. #if FF_API_DRAWTEXT_OLD_TIMELINE
  902. if (s->draw_pexpr){
  903. s->draw = av_expr_eval(s->draw_pexpr, s->var_values, &s->prng);
  904. if(!s->draw)
  905. return 0;
  906. }
  907. if (ctx->is_disabled)
  908. return 0;
  909. #endif
  910. box_w = FFMIN(width - 1 , max_text_line_w);
  911. box_h = FFMIN(height - 1, y + s->max_glyph_h);
  912. /* draw box */
  913. if (s->draw_box)
  914. ff_blend_rectangle(&s->dc, &s->boxcolor,
  915. frame->data, frame->linesize, width, height,
  916. s->x, s->y, box_w, box_h);
  917. if (s->shadowx || s->shadowy) {
  918. if ((ret = draw_glyphs(s, frame, width, height, s->shadowcolor.rgba,
  919. &s->shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
  920. return ret;
  921. }
  922. if (s->borderw) {
  923. if ((ret = draw_glyphs(s, frame, width, height, s->bordercolor.rgba,
  924. &s->bordercolor, 0, 0, s->borderw)) < 0)
  925. return ret;
  926. }
  927. if ((ret = draw_glyphs(s, frame, width, height, s->fontcolor.rgba,
  928. &s->fontcolor, 0, 0, 0)) < 0)
  929. return ret;
  930. return 0;
  931. }
  932. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  933. {
  934. AVFilterContext *ctx = inlink->dst;
  935. AVFilterLink *outlink = ctx->outputs[0];
  936. DrawTextContext *s = ctx->priv;
  937. int ret;
  938. if (s->reload)
  939. if ((ret = load_textfile(ctx)) < 0)
  940. return ret;
  941. s->var_values[VAR_N] = inlink->frame_count+s->start_number;
  942. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  943. NAN : frame->pts * av_q2d(inlink->time_base);
  944. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  945. s->metadata = av_frame_get_metadata(frame);
  946. draw_text(ctx, frame, frame->width, frame->height);
  947. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  948. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  949. (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
  950. s->x, s->y);
  951. return ff_filter_frame(outlink, frame);
  952. }
  953. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  954. {
  955. .name = "default",
  956. .type = AVMEDIA_TYPE_VIDEO,
  957. .filter_frame = filter_frame,
  958. .config_props = config_input,
  959. .needs_writable = 1,
  960. },
  961. { NULL }
  962. };
  963. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  964. {
  965. .name = "default",
  966. .type = AVMEDIA_TYPE_VIDEO,
  967. },
  968. { NULL }
  969. };
  970. AVFilter ff_vf_drawtext = {
  971. .name = "drawtext",
  972. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  973. .priv_size = sizeof(DrawTextContext),
  974. .priv_class = &drawtext_class,
  975. .init = init,
  976. .uninit = uninit,
  977. .query_formats = query_formats,
  978. .inputs = avfilter_vf_drawtext_inputs,
  979. .outputs = avfilter_vf_drawtext_outputs,
  980. .process_command = command,
  981. #if FF_API_DRAWTEXT_OLD_TIMELINE
  982. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL,
  983. #else
  984. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
  985. #endif
  986. };