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.

843 lines
31KB

  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/file.h"
  32. #include "libavutil/eval.h"
  33. #include "libavutil/opt.h"
  34. #include "libavutil/random_seed.h"
  35. #include "libavutil/parseutils.h"
  36. #include "libavutil/timecode.h"
  37. #include "libavutil/tree.h"
  38. #include "libavutil/lfg.h"
  39. #include "avfilter.h"
  40. #include "drawutils.h"
  41. #include "video.h"
  42. #undef time
  43. #include <ft2build.h>
  44. #include <freetype/config/ftheader.h>
  45. #include FT_FREETYPE_H
  46. #include FT_GLYPH_H
  47. #if CONFIG_FONTCONFIG
  48. #include <fontconfig/fontconfig.h>
  49. #endif
  50. static const char *const var_names[] = {
  51. "dar",
  52. "hsub", "vsub",
  53. "line_h", "lh", ///< line height, same as max_glyph_h
  54. "main_h", "h", "H", ///< height of the input video
  55. "main_w", "w", "W", ///< width of the input video
  56. "max_glyph_a", "ascent", ///< max glyph ascent
  57. "max_glyph_d", "descent", ///< min glyph descent
  58. "max_glyph_h", ///< max glyph height
  59. "max_glyph_w", ///< max glyph width
  60. "n", ///< number of frame
  61. "sar",
  62. "t", ///< timestamp expressed in seconds
  63. "text_h", "th", ///< height of the rendered text
  64. "text_w", "tw", ///< width of the rendered text
  65. "x",
  66. "y",
  67. NULL
  68. };
  69. static const char *const fun2_names[] = {
  70. "rand"
  71. };
  72. static double drand(void *opaque, double min, double max)
  73. {
  74. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  75. }
  76. typedef double (*eval_func2)(void *, double a, double b);
  77. static const eval_func2 fun2[] = {
  78. drand,
  79. NULL
  80. };
  81. enum var_name {
  82. VAR_DAR,
  83. VAR_HSUB, VAR_VSUB,
  84. VAR_LINE_H, VAR_LH,
  85. VAR_MAIN_H, VAR_h, VAR_H,
  86. VAR_MAIN_W, VAR_w, VAR_W,
  87. VAR_MAX_GLYPH_A, VAR_ASCENT,
  88. VAR_MAX_GLYPH_D, VAR_DESCENT,
  89. VAR_MAX_GLYPH_H,
  90. VAR_MAX_GLYPH_W,
  91. VAR_N,
  92. VAR_SAR,
  93. VAR_T,
  94. VAR_TEXT_H, VAR_TH,
  95. VAR_TEXT_W, VAR_TW,
  96. VAR_X,
  97. VAR_Y,
  98. VAR_VARS_NB
  99. };
  100. typedef struct {
  101. const AVClass *class;
  102. int reinit; ///< tells if the filter is being reinited
  103. uint8_t *fontfile; ///< font to be used
  104. uint8_t *text; ///< text to be drawn
  105. uint8_t *expanded_text; ///< used to contain the strftime()-expanded text
  106. size_t expanded_text_size; ///< size in bytes of the expanded_text buffer
  107. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  108. FT_Vector *positions; ///< positions for each element in the text
  109. size_t nb_positions; ///< number of elements of positions array
  110. char *textfile; ///< file with text to be drawn
  111. int x; ///< x position to start drawing text
  112. int y; ///< y position to start drawing text
  113. int max_glyph_w; ///< max glyph width
  114. int max_glyph_h; ///< max glyph height
  115. int shadowx, shadowy;
  116. unsigned int fontsize; ///< font size to use
  117. char *fontcolor_string; ///< font color as string
  118. char *boxcolor_string; ///< box color as string
  119. char *shadowcolor_string; ///< shadow color as string
  120. short int draw_box; ///< draw box around text - true or false
  121. int use_kerning; ///< font kerning is used - true/false
  122. int tabsize; ///< tab size
  123. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  124. FFDrawContext dc;
  125. FFDrawColor fontcolor; ///< foreground color
  126. FFDrawColor shadowcolor; ///< shadow color
  127. FFDrawColor boxcolor; ///< background color
  128. FT_Library library; ///< freetype font library handle
  129. FT_Face face; ///< freetype font face handle
  130. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  131. char *x_expr; ///< expression for x position
  132. char *y_expr; ///< expression for y position
  133. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  134. int64_t basetime; ///< base pts time in the real world for display
  135. double var_values[VAR_VARS_NB];
  136. char *draw_expr; ///< expression for draw
  137. AVExpr *draw_pexpr; ///< parsed expression for draw
  138. int draw; ///< set to zero to prevent drawing
  139. AVLFG prng; ///< random
  140. char *tc_opt_string; ///< specified timecode option string
  141. AVRational tc_rate; ///< frame rate for timecode
  142. AVTimecode tc; ///< timecode context
  143. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  144. int frame_id;
  145. } DrawTextContext;
  146. #define OFFSET(x) offsetof(DrawTextContext, x)
  147. static const AVOption drawtext_options[]= {
  148. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  149. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  150. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  151. {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
  152. {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX },
  153. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
  154. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  155. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.dbl=0}, 0, INT_MAX },
  156. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
  157. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
  158. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  159. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  160. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.dbl=4}, 0, INT_MAX },
  161. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.dbl=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX },
  162. {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX },
  163. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  164. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  165. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX },
  166. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX },
  167. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX },
  168. {"fix_bounds", "if true, check and fix text coords to avoid clipping",
  169. OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
  170. /* FT_LOAD_* flags */
  171. {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.dbl=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, 0, "ft_load_flags" },
  172. {"default", "set default", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  173. {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  174. {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  175. {"render", "set render", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_RENDER}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  176. {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  177. {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  178. {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  179. {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  180. {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  181. {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  182. {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  183. {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  184. {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  185. {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  186. {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  187. {NULL},
  188. };
  189. static const AVClass drawtext_class = {
  190. "DrawTextContext",
  191. av_default_item_name,
  192. drawtext_options
  193. };
  194. #undef __FTERRORS_H__
  195. #define FT_ERROR_START_LIST {
  196. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  197. #define FT_ERROR_END_LIST { 0, NULL } };
  198. struct ft_error
  199. {
  200. int err;
  201. const char *err_msg;
  202. } static ft_errors[] =
  203. #include FT_ERRORS_H
  204. #define FT_ERRMSG(e) ft_errors[e].err_msg
  205. typedef struct {
  206. FT_Glyph *glyph;
  207. uint32_t code;
  208. FT_Bitmap bitmap; ///< array holding bitmaps of font
  209. FT_BBox bbox;
  210. int advance;
  211. int bitmap_left;
  212. int bitmap_top;
  213. } Glyph;
  214. static int glyph_cmp(void *key, const void *b)
  215. {
  216. const Glyph *a = key, *bb = b;
  217. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  218. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  219. }
  220. /**
  221. * Load glyphs corresponding to the UTF-32 codepoint code.
  222. */
  223. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  224. {
  225. DrawTextContext *dtext = ctx->priv;
  226. Glyph *glyph;
  227. struct AVTreeNode *node = NULL;
  228. int ret;
  229. /* load glyph into dtext->face->glyph */
  230. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  231. return AVERROR(EINVAL);
  232. /* save glyph */
  233. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  234. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  235. ret = AVERROR(ENOMEM);
  236. goto error;
  237. }
  238. glyph->code = code;
  239. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  240. ret = AVERROR(EINVAL);
  241. goto error;
  242. }
  243. glyph->bitmap = dtext->face->glyph->bitmap;
  244. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  245. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  246. glyph->advance = dtext->face->glyph->advance.x >> 6;
  247. /* measure text height to calculate text_height (or the maximum text height) */
  248. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  249. /* cache the newly created glyph */
  250. if (!(node = av_mallocz(av_tree_node_size))) {
  251. ret = AVERROR(ENOMEM);
  252. goto error;
  253. }
  254. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  255. if (glyph_ptr)
  256. *glyph_ptr = glyph;
  257. return 0;
  258. error:
  259. if (glyph)
  260. av_freep(&glyph->glyph);
  261. av_freep(&glyph);
  262. av_freep(&node);
  263. return ret;
  264. }
  265. static int load_font_file(AVFilterContext *ctx, const char *path, int index,
  266. const char **error)
  267. {
  268. DrawTextContext *dtext = ctx->priv;
  269. int err;
  270. err = FT_New_Face(dtext->library, path, index, &dtext->face);
  271. if (err) {
  272. *error = FT_ERRMSG(err);
  273. return AVERROR(EINVAL);
  274. }
  275. return 0;
  276. }
  277. #if CONFIG_FONTCONFIG
  278. static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
  279. {
  280. DrawTextContext *dtext = ctx->priv;
  281. FcConfig *fontconfig;
  282. FcPattern *pattern, *fpat;
  283. FcResult result = FcResultMatch;
  284. FcChar8 *filename;
  285. int err, index;
  286. double size;
  287. fontconfig = FcInitLoadConfigAndFonts();
  288. if (!fontconfig) {
  289. *error = "impossible to init fontconfig\n";
  290. return AVERROR(EINVAL);
  291. }
  292. pattern = FcNameParse(dtext->fontfile ? dtext->fontfile :
  293. (uint8_t *)(intptr_t)"default");
  294. if (!pattern) {
  295. *error = "could not parse fontconfig pattern";
  296. return AVERROR(EINVAL);
  297. }
  298. if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
  299. *error = "could not substitue fontconfig options"; /* very unlikely */
  300. return AVERROR(EINVAL);
  301. }
  302. FcDefaultSubstitute(pattern);
  303. fpat = FcFontMatch(fontconfig, pattern, &result);
  304. if (!fpat || result != FcResultMatch) {
  305. *error = "impossible to find a matching font";
  306. return AVERROR(EINVAL);
  307. }
  308. if (FcPatternGetString (fpat, FC_FILE, 0, &filename) != FcResultMatch ||
  309. FcPatternGetInteger(fpat, FC_INDEX, 0, &index ) != FcResultMatch ||
  310. FcPatternGetDouble (fpat, FC_SIZE, 0, &size ) != FcResultMatch) {
  311. *error = "impossible to find font information";
  312. return AVERROR(EINVAL);
  313. }
  314. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  315. if (!dtext->fontsize)
  316. dtext->fontsize = size + 0.5;
  317. err = load_font_file(ctx, filename, index, error);
  318. if (err)
  319. return err;
  320. FcPatternDestroy(fpat);
  321. FcPatternDestroy(pattern);
  322. FcConfigDestroy(fontconfig);
  323. return 0;
  324. }
  325. #endif
  326. static int load_font(AVFilterContext *ctx)
  327. {
  328. DrawTextContext *dtext = ctx->priv;
  329. int err;
  330. const char *error = "unknown error\n";
  331. /* load the face, and set up the encoding, which is by default UTF-8 */
  332. err = load_font_file(ctx, dtext->fontfile, 0, &error);
  333. if (!err)
  334. return 0;
  335. #if CONFIG_FONTCONFIG
  336. err = load_font_fontconfig(ctx, &error);
  337. if (!err)
  338. return 0;
  339. #endif
  340. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  341. dtext->fontfile, error);
  342. return err;
  343. }
  344. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  345. {
  346. int err;
  347. DrawTextContext *dtext = ctx->priv;
  348. Glyph *glyph;
  349. dtext->class = &drawtext_class;
  350. av_opt_set_defaults(dtext);
  351. if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
  352. av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  353. return err;
  354. }
  355. if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
  356. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  357. return AVERROR(EINVAL);
  358. }
  359. if (dtext->textfile) {
  360. uint8_t *textbuf;
  361. size_t textbuf_size;
  362. if (dtext->text) {
  363. av_log(ctx, AV_LOG_ERROR,
  364. "Both text and text file provided. Please provide only one\n");
  365. return AVERROR(EINVAL);
  366. }
  367. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  368. av_log(ctx, AV_LOG_ERROR,
  369. "The text file '%s' could not be read or is empty\n",
  370. dtext->textfile);
  371. return err;
  372. }
  373. if (!(dtext->text = av_malloc(textbuf_size+1)))
  374. return AVERROR(ENOMEM);
  375. memcpy(dtext->text, textbuf, textbuf_size);
  376. dtext->text[textbuf_size] = 0;
  377. av_file_unmap(textbuf, textbuf_size);
  378. }
  379. if (dtext->tc_opt_string) {
  380. int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
  381. dtext->tc_opt_string, ctx);
  382. if (ret < 0)
  383. return ret;
  384. if (dtext->tc24hmax)
  385. dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  386. if (!dtext->text)
  387. dtext->text = av_strdup("");
  388. }
  389. if (!dtext->text) {
  390. av_log(ctx, AV_LOG_ERROR,
  391. "Either text, a valid file or a timecode must be provided\n");
  392. return AVERROR(EINVAL);
  393. }
  394. if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
  395. av_log(ctx, AV_LOG_ERROR,
  396. "Invalid font color '%s'\n", dtext->fontcolor_string);
  397. return err;
  398. }
  399. if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
  400. av_log(ctx, AV_LOG_ERROR,
  401. "Invalid box color '%s'\n", dtext->boxcolor_string);
  402. return err;
  403. }
  404. if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
  405. av_log(ctx, AV_LOG_ERROR,
  406. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  407. return err;
  408. }
  409. if ((err = FT_Init_FreeType(&(dtext->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 (!dtext->fontsize)
  418. dtext->fontsize = 16;
  419. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  420. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  421. dtext->fontsize, FT_ERRMSG(err));
  422. return AVERROR(EINVAL);
  423. }
  424. dtext->use_kerning = FT_HAS_KERNING(dtext->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. dtext->tabsize *= glyph->advance;
  433. return 0;
  434. }
  435. static int query_formats(AVFilterContext *ctx)
  436. {
  437. avfilter_set_common_pixel_formats(ctx, ff_draw_supported_pixel_formats(0));
  438. return 0;
  439. }
  440. static int glyph_enu_free(void *opaque, void *elem)
  441. {
  442. Glyph *glyph = elem;
  443. FT_Done_Glyph(*glyph->glyph);
  444. av_freep(&glyph->glyph);
  445. av_free(elem);
  446. return 0;
  447. }
  448. static av_cold void uninit(AVFilterContext *ctx)
  449. {
  450. DrawTextContext *dtext = ctx->priv;
  451. av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
  452. av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
  453. av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
  454. av_freep(&dtext->boxcolor_string);
  455. av_freep(&dtext->expanded_text);
  456. av_freep(&dtext->fontcolor_string);
  457. av_freep(&dtext->fontfile);
  458. av_freep(&dtext->shadowcolor_string);
  459. av_freep(&dtext->text);
  460. av_freep(&dtext->x_expr);
  461. av_freep(&dtext->y_expr);
  462. av_freep(&dtext->draw_expr);
  463. av_freep(&dtext->positions);
  464. dtext->nb_positions = 0;
  465. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  466. av_tree_destroy(dtext->glyphs);
  467. dtext->glyphs = NULL;
  468. FT_Done_Face(dtext->face);
  469. FT_Done_FreeType(dtext->library);
  470. }
  471. static inline int is_newline(uint32_t c)
  472. {
  473. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  474. }
  475. static int config_input(AVFilterLink *inlink)
  476. {
  477. AVFilterContext *ctx = inlink->dst;
  478. DrawTextContext *dtext = ctx->priv;
  479. int ret;
  480. ff_draw_init(&dtext->dc, inlink->format, 0);
  481. ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
  482. ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
  483. ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
  484. dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
  485. dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
  486. dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  487. dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
  488. dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
  489. dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
  490. dtext->var_values[VAR_X] = NAN;
  491. dtext->var_values[VAR_Y] = NAN;
  492. if (!dtext->reinit)
  493. dtext->var_values[VAR_N] = 0;
  494. dtext->var_values[VAR_T] = NAN;
  495. av_lfg_init(&dtext->prng, av_get_random_seed());
  496. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  497. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  498. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  499. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  500. (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
  501. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  502. return AVERROR(EINVAL);
  503. return 0;
  504. }
  505. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  506. {
  507. DrawTextContext *dtext = ctx->priv;
  508. if (!strcmp(cmd, "reinit")) {
  509. int ret;
  510. uninit(ctx);
  511. dtext->reinit = 1;
  512. if ((ret = init(ctx, arg, NULL)) < 0)
  513. return ret;
  514. return config_input(ctx->inputs[0]);
  515. }
  516. return AVERROR(ENOSYS);
  517. }
  518. static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
  519. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  520. {
  521. char *text = dtext->expanded_text;
  522. uint32_t code = 0;
  523. int i, x1, y1;
  524. uint8_t *p;
  525. Glyph *glyph = NULL;
  526. for (i = 0, p = text; *p; i++) {
  527. Glyph dummy = { 0 };
  528. GET_UTF8(code, *p++, continue;);
  529. /* skip new line chars, just go to new line */
  530. if (code == '\n' || code == '\r' || code == '\t')
  531. continue;
  532. dummy.code = code;
  533. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  534. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  535. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  536. return AVERROR(EINVAL);
  537. x1 = dtext->positions[i].x+dtext->x+x;
  538. y1 = dtext->positions[i].y+dtext->y+y;
  539. ff_blend_mask(&dtext->dc, color,
  540. picref->data, picref->linesize, width, height,
  541. glyph->bitmap.buffer, glyph->bitmap.pitch,
  542. glyph->bitmap.width, glyph->bitmap.rows,
  543. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  544. 0, x1, y1);
  545. }
  546. return 0;
  547. }
  548. static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
  549. int width, int height)
  550. {
  551. DrawTextContext *dtext = ctx->priv;
  552. uint32_t code = 0, prev_code = 0;
  553. int x = 0, y = 0, i = 0, ret;
  554. int max_text_line_w = 0, len;
  555. int box_w, box_h;
  556. char *text = dtext->text;
  557. uint8_t *p;
  558. int y_min = 32000, y_max = -32000;
  559. int x_min = 32000, x_max = -32000;
  560. FT_Vector delta;
  561. Glyph *glyph = NULL, *prev_glyph = NULL;
  562. Glyph dummy = { 0 };
  563. time_t now = time(0);
  564. struct tm ltime;
  565. uint8_t *buf = dtext->expanded_text;
  566. int buf_size = dtext->expanded_text_size;
  567. if(dtext->basetime != AV_NOPTS_VALUE)
  568. now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  569. if (!buf) {
  570. buf_size = 2*strlen(dtext->text)+1;
  571. buf = av_malloc(buf_size);
  572. }
  573. #if HAVE_LOCALTIME_R
  574. localtime_r(&now, &ltime);
  575. #else
  576. if(strchr(dtext->text, '%'))
  577. ltime= *localtime(&now);
  578. #endif
  579. do {
  580. *buf = 1;
  581. if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
  582. break;
  583. buf_size *= 2;
  584. } while ((buf = av_realloc(buf, buf_size)));
  585. if (dtext->tc_opt_string) {
  586. char tcbuf[AV_TIMECODE_STR_SIZE];
  587. av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
  588. buf = av_asprintf("%s%s", dtext->text, tcbuf);
  589. }
  590. if (!buf)
  591. return AVERROR(ENOMEM);
  592. text = dtext->expanded_text = buf;
  593. dtext->expanded_text_size = buf_size;
  594. if ((len = strlen(text)) > dtext->nb_positions) {
  595. if (!(dtext->positions =
  596. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  597. return AVERROR(ENOMEM);
  598. dtext->nb_positions = len;
  599. }
  600. x = 0;
  601. y = 0;
  602. /* load and cache glyphs */
  603. for (i = 0, p = text; *p; i++) {
  604. GET_UTF8(code, *p++, continue;);
  605. /* get glyph */
  606. dummy.code = code;
  607. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  608. if (!glyph) {
  609. load_glyph(ctx, &glyph, code);
  610. }
  611. y_min = FFMIN(glyph->bbox.yMin, y_min);
  612. y_max = FFMAX(glyph->bbox.yMax, y_max);
  613. x_min = FFMIN(glyph->bbox.xMin, x_min);
  614. x_max = FFMAX(glyph->bbox.xMax, x_max);
  615. }
  616. dtext->max_glyph_h = y_max - y_min;
  617. dtext->max_glyph_w = x_max - x_min;
  618. /* compute and save position for each glyph */
  619. glyph = NULL;
  620. for (i = 0, p = text; *p; i++) {
  621. GET_UTF8(code, *p++, continue;);
  622. /* skip the \n in the sequence \r\n */
  623. if (prev_code == '\r' && code == '\n')
  624. continue;
  625. prev_code = code;
  626. if (is_newline(code)) {
  627. max_text_line_w = FFMAX(max_text_line_w, x);
  628. y += dtext->max_glyph_h;
  629. x = 0;
  630. continue;
  631. }
  632. /* get glyph */
  633. prev_glyph = glyph;
  634. dummy.code = code;
  635. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  636. /* kerning */
  637. if (dtext->use_kerning && prev_glyph && glyph->code) {
  638. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  639. ft_kerning_default, &delta);
  640. x += delta.x >> 6;
  641. }
  642. /* save position */
  643. dtext->positions[i].x = x + glyph->bitmap_left;
  644. dtext->positions[i].y = y - glyph->bitmap_top + y_max;
  645. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  646. else x += glyph->advance;
  647. }
  648. max_text_line_w = FFMAX(x, max_text_line_w);
  649. dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
  650. dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
  651. dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
  652. dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
  653. dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
  654. dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
  655. dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
  656. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  657. dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  658. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  659. dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
  660. if(!dtext->draw)
  661. return 0;
  662. box_w = FFMIN(width - 1 , max_text_line_w);
  663. box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
  664. /* draw box */
  665. if (dtext->draw_box)
  666. ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
  667. picref->data, picref->linesize, width, height,
  668. dtext->x, dtext->y, box_w, box_h);
  669. if (dtext->shadowx || dtext->shadowy) {
  670. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor.rgba,
  671. &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  672. return ret;
  673. }
  674. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor.rgba,
  675. &dtext->fontcolor, 0, 0)) < 0)
  676. return ret;
  677. return 0;
  678. }
  679. static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
  680. static void end_frame(AVFilterLink *inlink)
  681. {
  682. AVFilterContext *ctx = inlink->dst;
  683. AVFilterLink *outlink = ctx->outputs[0];
  684. DrawTextContext *dtext = ctx->priv;
  685. AVFilterBufferRef *picref = inlink->cur_buf;
  686. dtext->var_values[VAR_T] = picref->pts == AV_NOPTS_VALUE ?
  687. NAN : picref->pts * av_q2d(inlink->time_base);
  688. draw_text(ctx, picref, picref->video->w, picref->video->h);
  689. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  690. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  691. (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
  692. dtext->x, dtext->y);
  693. dtext->var_values[VAR_N] += 1.0;
  694. avfilter_draw_slice(outlink, 0, picref->video->h, 1);
  695. avfilter_end_frame(outlink);
  696. }
  697. AVFilter avfilter_vf_drawtext = {
  698. .name = "drawtext",
  699. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  700. .priv_size = sizeof(DrawTextContext),
  701. .init = init,
  702. .uninit = uninit,
  703. .query_formats = query_formats,
  704. .inputs = (const AVFilterPad[]) {{ .name = "default",
  705. .type = AVMEDIA_TYPE_VIDEO,
  706. .get_video_buffer = ff_null_get_video_buffer,
  707. .start_frame = ff_null_start_frame,
  708. .draw_slice = null_draw_slice,
  709. .end_frame = end_frame,
  710. .config_props = config_input,
  711. .min_perms = AV_PERM_WRITE |
  712. AV_PERM_READ,
  713. .rej_perms = AV_PERM_PRESERVE },
  714. { .name = NULL}},
  715. .outputs = (const AVFilterPad[]) {{ .name = "default",
  716. .type = AVMEDIA_TYPE_VIDEO, },
  717. { .name = NULL}},
  718. .process_command = command,
  719. };