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.

1046 lines
36KB

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