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.

1030 lines
35KB

  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. } DrawTextContext;
  153. #define OFFSET(x) offsetof(DrawTextContext, x)
  154. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  155. static const AVOption drawtext_options[]= {
  156. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  157. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  158. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  159. {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  160. {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  161. {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  162. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  163. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  164. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  165. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  166. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  167. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  168. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  169. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  170. {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
  171. {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
  172. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  173. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  174. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  175. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  176. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  177. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  178. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  179. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  180. {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  181. {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
  182. /* FT_LOAD_* flags */
  183. { "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" },
  184. { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  185. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  186. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  187. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  188. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  189. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  190. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  191. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  192. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  193. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  194. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  195. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  196. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  197. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  198. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  199. { NULL},
  200. };
  201. AVFILTER_DEFINE_CLASS(drawtext);
  202. #undef __FTERRORS_H__
  203. #define FT_ERROR_START_LIST {
  204. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  205. #define FT_ERROR_END_LIST { 0, NULL } };
  206. struct ft_error
  207. {
  208. int err;
  209. const char *err_msg;
  210. } static ft_errors[] =
  211. #include FT_ERRORS_H
  212. #define FT_ERRMSG(e) ft_errors[e].err_msg
  213. typedef struct {
  214. FT_Glyph *glyph;
  215. uint32_t code;
  216. FT_Bitmap bitmap; ///< array holding bitmaps of font
  217. FT_BBox bbox;
  218. int advance;
  219. int bitmap_left;
  220. int bitmap_top;
  221. } Glyph;
  222. static int glyph_cmp(void *key, const void *b)
  223. {
  224. const Glyph *a = key, *bb = b;
  225. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  226. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  227. }
  228. /**
  229. * Load glyphs corresponding to the UTF-32 codepoint code.
  230. */
  231. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  232. {
  233. DrawTextContext *s = ctx->priv;
  234. Glyph *glyph;
  235. struct AVTreeNode *node = NULL;
  236. int ret;
  237. /* load glyph into s->face->glyph */
  238. if (FT_Load_Char(s->face, code, s->ft_load_flags))
  239. return AVERROR(EINVAL);
  240. /* save glyph */
  241. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  242. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  243. ret = AVERROR(ENOMEM);
  244. goto error;
  245. }
  246. glyph->code = code;
  247. if (FT_Get_Glyph(s->face->glyph, glyph->glyph)) {
  248. ret = AVERROR(EINVAL);
  249. goto error;
  250. }
  251. glyph->bitmap = s->face->glyph->bitmap;
  252. glyph->bitmap_left = s->face->glyph->bitmap_left;
  253. glyph->bitmap_top = s->face->glyph->bitmap_top;
  254. glyph->advance = s->face->glyph->advance.x >> 6;
  255. /* measure text height to calculate text_height (or the maximum text height) */
  256. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  257. /* cache the newly created glyph */
  258. if (!(node = av_tree_node_alloc())) {
  259. ret = AVERROR(ENOMEM);
  260. goto error;
  261. }
  262. av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
  263. if (glyph_ptr)
  264. *glyph_ptr = glyph;
  265. return 0;
  266. error:
  267. if (glyph)
  268. av_freep(&glyph->glyph);
  269. av_freep(&glyph);
  270. av_freep(&node);
  271. return ret;
  272. }
  273. static int load_font_file(AVFilterContext *ctx, const char *path, int index,
  274. const char **error)
  275. {
  276. DrawTextContext *s = ctx->priv;
  277. int err;
  278. err = FT_New_Face(s->library, path, index, &s->face);
  279. if (err) {
  280. *error = FT_ERRMSG(err);
  281. return AVERROR(EINVAL);
  282. }
  283. return 0;
  284. }
  285. #if CONFIG_FONTCONFIG
  286. static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
  287. {
  288. DrawTextContext *s = ctx->priv;
  289. FcConfig *fontconfig;
  290. FcPattern *pattern, *fpat;
  291. FcResult result = FcResultMatch;
  292. FcChar8 *filename;
  293. int err, index;
  294. double size;
  295. fontconfig = FcInitLoadConfigAndFonts();
  296. if (!fontconfig) {
  297. *error = "impossible to init fontconfig\n";
  298. return AVERROR(EINVAL);
  299. }
  300. pattern = FcNameParse(s->fontfile ? s->fontfile :
  301. (uint8_t *)(intptr_t)"default");
  302. if (!pattern) {
  303. *error = "could not parse fontconfig pattern";
  304. return AVERROR(EINVAL);
  305. }
  306. if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
  307. *error = "could not substitue fontconfig options"; /* very unlikely */
  308. return AVERROR(EINVAL);
  309. }
  310. FcDefaultSubstitute(pattern);
  311. fpat = FcFontMatch(fontconfig, pattern, &result);
  312. if (!fpat || result != FcResultMatch) {
  313. *error = "impossible to find a matching font";
  314. return AVERROR(EINVAL);
  315. }
  316. if (FcPatternGetString (fpat, FC_FILE, 0, &filename) != FcResultMatch ||
  317. FcPatternGetInteger(fpat, FC_INDEX, 0, &index ) != FcResultMatch ||
  318. FcPatternGetDouble (fpat, FC_SIZE, 0, &size ) != FcResultMatch) {
  319. *error = "impossible to find font information";
  320. return AVERROR(EINVAL);
  321. }
  322. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  323. if (!s->fontsize)
  324. s->fontsize = size + 0.5;
  325. err = load_font_file(ctx, filename, index, error);
  326. if (err)
  327. return err;
  328. FcPatternDestroy(fpat);
  329. FcPatternDestroy(pattern);
  330. FcConfigDestroy(fontconfig);
  331. return 0;
  332. }
  333. #endif
  334. static int load_font(AVFilterContext *ctx)
  335. {
  336. DrawTextContext *s = ctx->priv;
  337. int err;
  338. const char *error = "unknown error\n";
  339. /* load the face, and set up the encoding, which is by default UTF-8 */
  340. err = load_font_file(ctx, s->fontfile, 0, &error);
  341. if (!err)
  342. return 0;
  343. #if CONFIG_FONTCONFIG
  344. err = load_font_fontconfig(ctx, &error);
  345. if (!err)
  346. return 0;
  347. #endif
  348. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  349. s->fontfile, error);
  350. return err;
  351. }
  352. static int load_textfile(AVFilterContext *ctx)
  353. {
  354. DrawTextContext *s = ctx->priv;
  355. int err;
  356. uint8_t *textbuf;
  357. size_t textbuf_size;
  358. if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  359. av_log(ctx, AV_LOG_ERROR,
  360. "The text file '%s' could not be read or is empty\n",
  361. s->textfile);
  362. return err;
  363. }
  364. if (!(s->text = av_realloc(s->text, textbuf_size + 1)))
  365. return AVERROR(ENOMEM);
  366. memcpy(s->text, textbuf, textbuf_size);
  367. s->text[textbuf_size] = 0;
  368. av_file_unmap(textbuf, textbuf_size);
  369. return 0;
  370. }
  371. static av_cold int init(AVFilterContext *ctx)
  372. {
  373. int err;
  374. DrawTextContext *s = ctx->priv;
  375. Glyph *glyph;
  376. if (!s->fontfile && !CONFIG_FONTCONFIG) {
  377. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  378. return AVERROR(EINVAL);
  379. }
  380. if (s->textfile) {
  381. if (s->text) {
  382. av_log(ctx, AV_LOG_ERROR,
  383. "Both text and text file provided. Please provide only one\n");
  384. return AVERROR(EINVAL);
  385. }
  386. if ((err = load_textfile(ctx)) < 0)
  387. return err;
  388. }
  389. if (s->reload && !s->textfile)
  390. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  391. if (s->tc_opt_string) {
  392. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  393. s->tc_opt_string, ctx);
  394. if (ret < 0)
  395. return ret;
  396. if (s->tc24hmax)
  397. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  398. if (!s->text)
  399. s->text = av_strdup("");
  400. }
  401. if (!s->text) {
  402. av_log(ctx, AV_LOG_ERROR,
  403. "Either text, a valid file or a timecode must be provided\n");
  404. return AVERROR(EINVAL);
  405. }
  406. if ((err = FT_Init_FreeType(&(s->library)))) {
  407. av_log(ctx, AV_LOG_ERROR,
  408. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  409. return AVERROR(EINVAL);
  410. }
  411. err = load_font(ctx);
  412. if (err)
  413. return err;
  414. if (!s->fontsize)
  415. s->fontsize = 16;
  416. if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
  417. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  418. s->fontsize, FT_ERRMSG(err));
  419. return AVERROR(EINVAL);
  420. }
  421. s->use_kerning = FT_HAS_KERNING(s->face);
  422. /* load the fallback glyph with code 0 */
  423. load_glyph(ctx, NULL, 0);
  424. /* set the tabsize in pixels */
  425. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  426. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  427. return err;
  428. }
  429. s->tabsize *= glyph->advance;
  430. if (s->exp_mode == EXP_STRFTIME &&
  431. (strchr(s->text, '%') || strchr(s->text, '\\')))
  432. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  433. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  434. return 0;
  435. }
  436. static int query_formats(AVFilterContext *ctx)
  437. {
  438. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  439. return 0;
  440. }
  441. static int glyph_enu_free(void *opaque, void *elem)
  442. {
  443. Glyph *glyph = elem;
  444. FT_Done_Glyph(*glyph->glyph);
  445. av_freep(&glyph->glyph);
  446. av_free(elem);
  447. return 0;
  448. }
  449. static av_cold void uninit(AVFilterContext *ctx)
  450. {
  451. DrawTextContext *s = ctx->priv;
  452. av_expr_free(s->x_pexpr);
  453. av_expr_free(s->y_pexpr);
  454. av_expr_free(s->draw_pexpr);
  455. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  456. av_freep(&s->positions);
  457. s->nb_positions = 0;
  458. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  459. av_tree_destroy(s->glyphs);
  460. s->glyphs = NULL;
  461. FT_Done_Face(s->face);
  462. FT_Done_FreeType(s->library);
  463. av_bprint_finalize(&s->expanded_text, NULL);
  464. }
  465. static inline int is_newline(uint32_t c)
  466. {
  467. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  468. }
  469. static int config_input(AVFilterLink *inlink)
  470. {
  471. AVFilterContext *ctx = inlink->dst;
  472. DrawTextContext *s = ctx->priv;
  473. int ret;
  474. ff_draw_init(&s->dc, inlink->format, 0);
  475. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  476. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  477. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  478. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  479. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  480. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  481. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  482. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  483. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  484. s->var_values[VAR_X] = NAN;
  485. s->var_values[VAR_Y] = NAN;
  486. s->var_values[VAR_T] = NAN;
  487. av_lfg_init(&s->prng, av_get_random_seed());
  488. av_expr_free(s->x_pexpr);
  489. av_expr_free(s->y_pexpr);
  490. av_expr_free(s->draw_pexpr);
  491. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  492. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  493. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  494. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  495. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  496. (ret = av_expr_parse(&s->draw_pexpr, s->draw_expr, var_names,
  497. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  498. return AVERROR(EINVAL);
  499. return 0;
  500. }
  501. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  502. {
  503. DrawTextContext *s = ctx->priv;
  504. if (!strcmp(cmd, "reinit")) {
  505. int ret;
  506. uninit(ctx);
  507. s->reinit = 1;
  508. if ((ret = init(ctx)) < 0)
  509. return ret;
  510. return config_input(ctx->inputs[0]);
  511. }
  512. return AVERROR(ENOSYS);
  513. }
  514. static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
  515. char *fct, unsigned argc, char **argv, int tag)
  516. {
  517. DrawTextContext *s = ctx->priv;
  518. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  519. return 0;
  520. }
  521. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  522. char *fct, unsigned argc, char **argv, int tag)
  523. {
  524. DrawTextContext *s = ctx->priv;
  525. av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
  526. return 0;
  527. }
  528. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  529. char *fct, unsigned argc, char **argv, int tag)
  530. {
  531. DrawTextContext *s = ctx->priv;
  532. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  533. return 0;
  534. }
  535. #if !HAVE_LOCALTIME_R
  536. static void localtime_r(const time_t *t, struct tm *tm)
  537. {
  538. *tm = *localtime(t);
  539. }
  540. #endif
  541. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  542. char *fct, unsigned argc, char **argv, int tag)
  543. {
  544. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  545. time_t now;
  546. struct tm tm;
  547. time(&now);
  548. if (tag == 'L')
  549. localtime_r(&now, &tm);
  550. else
  551. tm = *gmtime(&now);
  552. av_bprint_strftime(bp, fmt, &tm);
  553. return 0;
  554. }
  555. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  556. char *fct, unsigned argc, char **argv, int tag)
  557. {
  558. DrawTextContext *s = ctx->priv;
  559. double res;
  560. int ret;
  561. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  562. NULL, NULL, fun2_names, fun2,
  563. &s->prng, 0, ctx);
  564. if (ret < 0)
  565. av_log(ctx, AV_LOG_ERROR,
  566. "Expression '%s' for the expr text expansion function is not valid\n",
  567. argv[0]);
  568. else
  569. av_bprintf(bp, "%f", res);
  570. return ret;
  571. }
  572. static const struct drawtext_function {
  573. const char *name;
  574. unsigned argc_min, argc_max;
  575. int tag; /**< opaque argument to func */
  576. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  577. } functions[] = {
  578. { "expr", 1, 1, 0, func_eval_expr },
  579. { "e", 1, 1, 0, func_eval_expr },
  580. { "pict_type", 0, 0, 0, func_pict_type },
  581. { "pts", 0, 0, 0, func_pts },
  582. { "gmtime", 0, 1, 'G', func_strftime },
  583. { "localtime", 0, 1, 'L', func_strftime },
  584. { "frame_num", 0, 0, 0, func_frame_num },
  585. { "n", 0, 0, 0, func_frame_num },
  586. };
  587. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  588. unsigned argc, char **argv)
  589. {
  590. unsigned i;
  591. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  592. if (strcmp(fct, functions[i].name))
  593. continue;
  594. if (argc < functions[i].argc_min) {
  595. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  596. fct, functions[i].argc_min);
  597. return AVERROR(EINVAL);
  598. }
  599. if (argc > functions[i].argc_max) {
  600. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  601. fct, functions[i].argc_max);
  602. return AVERROR(EINVAL);
  603. }
  604. break;
  605. }
  606. if (i >= FF_ARRAY_ELEMS(functions)) {
  607. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  608. return AVERROR(EINVAL);
  609. }
  610. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  611. }
  612. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  613. {
  614. const char *text = *rtext;
  615. char *argv[16] = { NULL };
  616. unsigned argc = 0, i;
  617. int ret;
  618. if (*text != '{') {
  619. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  620. return AVERROR(EINVAL);
  621. }
  622. text++;
  623. while (1) {
  624. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  625. ret = AVERROR(ENOMEM);
  626. goto end;
  627. }
  628. if (!*text) {
  629. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  630. ret = AVERROR(EINVAL);
  631. goto end;
  632. }
  633. if (argc == FF_ARRAY_ELEMS(argv))
  634. av_freep(&argv[--argc]); /* error will be caught later */
  635. if (*text == '}')
  636. break;
  637. text++;
  638. }
  639. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  640. goto end;
  641. ret = 0;
  642. *rtext = (char *)text + 1;
  643. end:
  644. for (i = 0; i < argc; i++)
  645. av_freep(&argv[i]);
  646. return ret;
  647. }
  648. static int expand_text(AVFilterContext *ctx)
  649. {
  650. DrawTextContext *s = ctx->priv;
  651. char *text = s->text;
  652. AVBPrint *bp = &s->expanded_text;
  653. int ret;
  654. av_bprint_clear(bp);
  655. while (*text) {
  656. if (*text == '\\' && text[1]) {
  657. av_bprint_chars(bp, text[1], 1);
  658. text += 2;
  659. } else if (*text == '%') {
  660. text++;
  661. if ((ret = expand_function(ctx, bp, &text)) < 0)
  662. return ret;
  663. } else {
  664. av_bprint_chars(bp, *text, 1);
  665. text++;
  666. }
  667. }
  668. if (!av_bprint_is_complete(bp))
  669. return AVERROR(ENOMEM);
  670. return 0;
  671. }
  672. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  673. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  674. {
  675. char *text = s->expanded_text.str;
  676. uint32_t code = 0;
  677. int i, x1, y1;
  678. uint8_t *p;
  679. Glyph *glyph = NULL;
  680. for (i = 0, p = text; *p; i++) {
  681. Glyph dummy = { 0 };
  682. GET_UTF8(code, *p++, continue;);
  683. /* skip new line chars, just go to new line */
  684. if (code == '\n' || code == '\r' || code == '\t')
  685. continue;
  686. dummy.code = code;
  687. glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
  688. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  689. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  690. return AVERROR(EINVAL);
  691. x1 = s->positions[i].x+s->x+x;
  692. y1 = s->positions[i].y+s->y+y;
  693. ff_blend_mask(&s->dc, color,
  694. frame->data, frame->linesize, width, height,
  695. glyph->bitmap.buffer, glyph->bitmap.pitch,
  696. glyph->bitmap.width, glyph->bitmap.rows,
  697. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  698. 0, x1, y1);
  699. }
  700. return 0;
  701. }
  702. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  703. int width, int height)
  704. {
  705. DrawTextContext *s = ctx->priv;
  706. AVFilterLink *inlink = ctx->inputs[0];
  707. uint32_t code = 0, prev_code = 0;
  708. int x = 0, y = 0, i = 0, ret;
  709. int max_text_line_w = 0, len;
  710. int box_w, box_h;
  711. char *text = s->text;
  712. uint8_t *p;
  713. int y_min = 32000, y_max = -32000;
  714. int x_min = 32000, x_max = -32000;
  715. FT_Vector delta;
  716. Glyph *glyph = NULL, *prev_glyph = NULL;
  717. Glyph dummy = { 0 };
  718. time_t now = time(0);
  719. struct tm ltime;
  720. AVBPrint *bp = &s->expanded_text;
  721. av_bprint_clear(bp);
  722. if(s->basetime != AV_NOPTS_VALUE)
  723. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  724. switch (s->exp_mode) {
  725. case EXP_NONE:
  726. av_bprintf(bp, "%s", s->text);
  727. break;
  728. case EXP_NORMAL:
  729. if ((ret = expand_text(ctx)) < 0)
  730. return ret;
  731. break;
  732. case EXP_STRFTIME:
  733. localtime_r(&now, &ltime);
  734. av_bprint_strftime(bp, s->text, &ltime);
  735. break;
  736. }
  737. if (s->tc_opt_string) {
  738. char tcbuf[AV_TIMECODE_STR_SIZE];
  739. av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
  740. av_bprint_clear(bp);
  741. av_bprintf(bp, "%s%s", s->text, tcbuf);
  742. }
  743. if (!av_bprint_is_complete(bp))
  744. return AVERROR(ENOMEM);
  745. text = s->expanded_text.str;
  746. if ((len = s->expanded_text.len) > s->nb_positions) {
  747. if (!(s->positions =
  748. av_realloc(s->positions, len*sizeof(*s->positions))))
  749. return AVERROR(ENOMEM);
  750. s->nb_positions = len;
  751. }
  752. x = 0;
  753. y = 0;
  754. /* load and cache glyphs */
  755. for (i = 0, p = text; *p; i++) {
  756. GET_UTF8(code, *p++, continue;);
  757. /* get glyph */
  758. dummy.code = code;
  759. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  760. if (!glyph) {
  761. load_glyph(ctx, &glyph, code);
  762. }
  763. y_min = FFMIN(glyph->bbox.yMin, y_min);
  764. y_max = FFMAX(glyph->bbox.yMax, y_max);
  765. x_min = FFMIN(glyph->bbox.xMin, x_min);
  766. x_max = FFMAX(glyph->bbox.xMax, x_max);
  767. }
  768. s->max_glyph_h = y_max - y_min;
  769. s->max_glyph_w = x_max - x_min;
  770. /* compute and save position for each glyph */
  771. glyph = NULL;
  772. for (i = 0, p = text; *p; i++) {
  773. GET_UTF8(code, *p++, continue;);
  774. /* skip the \n in the sequence \r\n */
  775. if (prev_code == '\r' && code == '\n')
  776. continue;
  777. prev_code = code;
  778. if (is_newline(code)) {
  779. max_text_line_w = FFMAX(max_text_line_w, x);
  780. y += s->max_glyph_h;
  781. x = 0;
  782. continue;
  783. }
  784. /* get glyph */
  785. prev_glyph = glyph;
  786. dummy.code = code;
  787. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  788. /* kerning */
  789. if (s->use_kerning && prev_glyph && glyph->code) {
  790. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  791. ft_kerning_default, &delta);
  792. x += delta.x >> 6;
  793. }
  794. /* save position */
  795. s->positions[i].x = x + glyph->bitmap_left;
  796. s->positions[i].y = y - glyph->bitmap_top + y_max;
  797. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  798. else x += glyph->advance;
  799. }
  800. max_text_line_w = FFMAX(x, max_text_line_w);
  801. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
  802. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
  803. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  804. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  805. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
  806. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
  807. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
  808. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  809. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  810. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  811. s->draw = av_expr_eval(s->draw_pexpr, s->var_values, &s->prng);
  812. if(!s->draw)
  813. return 0;
  814. box_w = FFMIN(width - 1 , max_text_line_w);
  815. box_h = FFMIN(height - 1, y + s->max_glyph_h);
  816. /* draw box */
  817. if (s->draw_box)
  818. ff_blend_rectangle(&s->dc, &s->boxcolor,
  819. frame->data, frame->linesize, width, height,
  820. s->x, s->y, box_w, box_h);
  821. if (s->shadowx || s->shadowy) {
  822. if ((ret = draw_glyphs(s, frame, width, height, s->shadowcolor.rgba,
  823. &s->shadowcolor, s->shadowx, s->shadowy)) < 0)
  824. return ret;
  825. }
  826. if ((ret = draw_glyphs(s, frame, width, height, s->fontcolor.rgba,
  827. &s->fontcolor, 0, 0)) < 0)
  828. return ret;
  829. return 0;
  830. }
  831. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  832. {
  833. AVFilterContext *ctx = inlink->dst;
  834. AVFilterLink *outlink = ctx->outputs[0];
  835. DrawTextContext *s = ctx->priv;
  836. int ret;
  837. if (s->reload)
  838. if ((ret = load_textfile(ctx)) < 0)
  839. return ret;
  840. s->var_values[VAR_N] = inlink->frame_count;
  841. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  842. NAN : frame->pts * av_q2d(inlink->time_base);
  843. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  844. draw_text(ctx, frame, frame->width, frame->height);
  845. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  846. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  847. (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
  848. s->x, s->y);
  849. return ff_filter_frame(outlink, frame);
  850. }
  851. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  852. {
  853. .name = "default",
  854. .type = AVMEDIA_TYPE_VIDEO,
  855. .get_video_buffer = ff_null_get_video_buffer,
  856. .filter_frame = filter_frame,
  857. .config_props = config_input,
  858. .needs_writable = 1,
  859. },
  860. { NULL }
  861. };
  862. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  863. {
  864. .name = "default",
  865. .type = AVMEDIA_TYPE_VIDEO,
  866. },
  867. { NULL }
  868. };
  869. AVFilter avfilter_vf_drawtext = {
  870. .name = "drawtext",
  871. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  872. .priv_size = sizeof(DrawTextContext),
  873. .priv_class = &drawtext_class,
  874. .init = init,
  875. .uninit = uninit,
  876. .query_formats = query_formats,
  877. .inputs = avfilter_vf_drawtext_inputs,
  878. .outputs = avfilter_vf_drawtext_outputs,
  879. .process_command = command,
  880. };