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.

755 lines
29KB

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