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.

893 lines
33KB

  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 Libav.
  7. *
  8. * Libav 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. * Libav 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 Libav; 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 "libavutil/colorspace.h"
  30. #include "libavutil/file.h"
  31. #include "libavutil/eval.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/random_seed.h"
  35. #include "libavutil/parseutils.h"
  36. #include "libavutil/pixdesc.h"
  37. #include "libavutil/tree.h"
  38. #include "libavutil/lfg.h"
  39. #include "avfilter.h"
  40. #include "drawutils.h"
  41. #include "formats.h"
  42. #include "video.h"
  43. #undef time
  44. #include <ft2build.h>
  45. #include <freetype/config/ftheader.h>
  46. #include FT_FREETYPE_H
  47. #include FT_GLYPH_H
  48. static const char *const var_names[] = {
  49. "E",
  50. "PHI",
  51. "PI",
  52. "main_w", "W", ///< width of the main video
  53. "main_h", "H", ///< height of the main video
  54. "text_w", "w", ///< width of the overlay text
  55. "text_h", "h", ///< height of the overlay text
  56. "x",
  57. "y",
  58. "n", ///< number of processed frames
  59. "t", ///< timestamp expressed in seconds
  60. NULL
  61. };
  62. static const char *const fun2_names[] = {
  63. "rand"
  64. };
  65. static double drand(void *opaque, double min, double max)
  66. {
  67. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  68. }
  69. typedef double (*eval_func2)(void *, double a, double b);
  70. static const eval_func2 fun2[] = {
  71. drand,
  72. NULL
  73. };
  74. enum var_name {
  75. VAR_E,
  76. VAR_PHI,
  77. VAR_PI,
  78. VAR_MAIN_W, VAR_MW,
  79. VAR_MAIN_H, VAR_MH,
  80. VAR_TEXT_W, VAR_TW,
  81. VAR_TEXT_H, VAR_TH,
  82. VAR_X,
  83. VAR_Y,
  84. VAR_N,
  85. VAR_T,
  86. VAR_VARS_NB
  87. };
  88. typedef struct {
  89. const AVClass *class;
  90. uint8_t *fontfile; ///< font to be used
  91. uint8_t *text; ///< text to be drawn
  92. uint8_t *expanded_text; ///< used to contain the strftime()-expanded text
  93. size_t expanded_text_size; ///< size in bytes of the expanded_text buffer
  94. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  95. FT_Vector *positions; ///< positions for each element in the text
  96. size_t nb_positions; ///< number of elements of positions array
  97. char *textfile; ///< file with text to be drawn
  98. int x, y; ///< position to start drawing text
  99. int w, h; ///< dimension of the text block
  100. int shadowx, shadowy;
  101. unsigned int fontsize; ///< font size to use
  102. char *fontcolor_string; ///< font color as string
  103. char *boxcolor_string; ///< box color as string
  104. char *shadowcolor_string; ///< shadow color as string
  105. uint8_t fontcolor[4]; ///< foreground color
  106. uint8_t boxcolor[4]; ///< background color
  107. uint8_t shadowcolor[4]; ///< shadow color
  108. uint8_t fontcolor_rgba[4]; ///< foreground color in RGBA
  109. uint8_t boxcolor_rgba[4]; ///< background color in RGBA
  110. uint8_t shadowcolor_rgba[4]; ///< shadow color in RGBA
  111. short int draw_box; ///< draw box around text - true or false
  112. int use_kerning; ///< font kerning is used - true/false
  113. int tabsize; ///< tab size
  114. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  115. FT_Library library; ///< freetype font library handle
  116. FT_Face face; ///< freetype font face handle
  117. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  118. int hsub, vsub; ///< chroma subsampling values
  119. int is_packed_rgb;
  120. int pixel_step[4]; ///< distance in bytes between the component of each pixel
  121. uint8_t rgba_map[4]; ///< map RGBA offsets to the positions in the packed RGBA format
  122. uint8_t *box_line[4]; ///< line used for filling the box background
  123. char *x_expr, *y_expr;
  124. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  125. double var_values[VAR_VARS_NB];
  126. char *d_expr;
  127. AVExpr *d_pexpr;
  128. int draw; ///< set to zero to prevent drawing
  129. AVLFG prng; ///< random
  130. } DrawTextContext;
  131. #define OFFSET(x) offsetof(DrawTextContext, x)
  132. static const AVOption drawtext_options[]= {
  133. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  134. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  135. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  136. {"fontcolor","set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  137. {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  138. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  139. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  140. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.dbl=16}, 1, 72 },
  141. {"x", "set x", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
  142. {"y", "set y", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
  143. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  144. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  145. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.dbl=4}, 0, INT_MAX },
  146. {"draw", "if false do not draw", OFFSET(d_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX },
  147. {"fix_bounds", "if true, check and fix text coords to avoid clipping",
  148. OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
  149. /* FT_LOAD_* flags */
  150. {"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" },
  151. {"default", "set default", 0, AV_OPT_TYPE_CONST, {FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  152. {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  153. {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  154. {"render", "set render", 0, AV_OPT_TYPE_CONST, {FT_LOAD_RENDER}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  155. {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  156. {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  157. {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  158. {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  159. {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  160. {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  161. {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  162. {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  163. {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  164. {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  165. {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  166. {NULL},
  167. };
  168. static const char *drawtext_get_name(void *ctx)
  169. {
  170. return "drawtext";
  171. }
  172. static const AVClass drawtext_class = {
  173. "DrawTextContext",
  174. drawtext_get_name,
  175. drawtext_options
  176. };
  177. #undef __FTERRORS_H__
  178. #define FT_ERROR_START_LIST {
  179. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  180. #define FT_ERROR_END_LIST { 0, NULL } };
  181. struct ft_error
  182. {
  183. int err;
  184. const char *err_msg;
  185. } static ft_errors[] =
  186. #include FT_ERRORS_H
  187. #define FT_ERRMSG(e) ft_errors[e].err_msg
  188. typedef struct {
  189. FT_Glyph *glyph;
  190. uint32_t code;
  191. FT_Bitmap bitmap; ///< array holding bitmaps of font
  192. FT_BBox bbox;
  193. int advance;
  194. int bitmap_left;
  195. int bitmap_top;
  196. } Glyph;
  197. static int glyph_cmp(void *key, const void *b)
  198. {
  199. const Glyph *a = key, *bb = b;
  200. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  201. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  202. }
  203. /**
  204. * Load glyphs corresponding to the UTF-32 codepoint code.
  205. */
  206. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  207. {
  208. DrawTextContext *dtext = ctx->priv;
  209. Glyph *glyph;
  210. struct AVTreeNode *node = NULL;
  211. int ret;
  212. /* load glyph into dtext->face->glyph */
  213. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  214. return AVERROR(EINVAL);
  215. /* save glyph */
  216. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  217. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  218. ret = AVERROR(ENOMEM);
  219. goto error;
  220. }
  221. glyph->code = code;
  222. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  223. ret = AVERROR(EINVAL);
  224. goto error;
  225. }
  226. glyph->bitmap = dtext->face->glyph->bitmap;
  227. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  228. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  229. glyph->advance = dtext->face->glyph->advance.x >> 6;
  230. /* measure text height to calculate text_height (or the maximum text height) */
  231. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  232. /* cache the newly created glyph */
  233. if (!(node = av_mallocz(av_tree_node_size))) {
  234. ret = AVERROR(ENOMEM);
  235. goto error;
  236. }
  237. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  238. if (glyph_ptr)
  239. *glyph_ptr = glyph;
  240. return 0;
  241. error:
  242. if (glyph)
  243. av_freep(&glyph->glyph);
  244. av_freep(&glyph);
  245. av_freep(&node);
  246. return ret;
  247. }
  248. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  249. {
  250. int err;
  251. DrawTextContext *dtext = ctx->priv;
  252. Glyph *glyph;
  253. dtext->class = &drawtext_class;
  254. av_opt_set_defaults(dtext);
  255. dtext->fontcolor_string = av_strdup("black");
  256. dtext->boxcolor_string = av_strdup("white");
  257. dtext->shadowcolor_string = av_strdup("black");
  258. if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
  259. av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  260. return err;
  261. }
  262. if (!dtext->fontfile) {
  263. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  264. return AVERROR(EINVAL);
  265. }
  266. if (dtext->textfile) {
  267. uint8_t *textbuf;
  268. size_t textbuf_size;
  269. if (dtext->text) {
  270. av_log(ctx, AV_LOG_ERROR,
  271. "Both text and text file provided. Please provide only one\n");
  272. return AVERROR(EINVAL);
  273. }
  274. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  275. av_log(ctx, AV_LOG_ERROR,
  276. "The text file '%s' could not be read or is empty\n",
  277. dtext->textfile);
  278. return err;
  279. }
  280. if (!(dtext->text = av_malloc(textbuf_size+1)))
  281. return AVERROR(ENOMEM);
  282. memcpy(dtext->text, textbuf, textbuf_size);
  283. dtext->text[textbuf_size] = 0;
  284. av_file_unmap(textbuf, textbuf_size);
  285. }
  286. if (!dtext->text) {
  287. av_log(ctx, AV_LOG_ERROR,
  288. "Either text or a valid file must be provided\n");
  289. return AVERROR(EINVAL);
  290. }
  291. if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
  292. av_log(ctx, AV_LOG_ERROR,
  293. "Invalid font color '%s'\n", dtext->fontcolor_string);
  294. return err;
  295. }
  296. if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
  297. av_log(ctx, AV_LOG_ERROR,
  298. "Invalid box color '%s'\n", dtext->boxcolor_string);
  299. return err;
  300. }
  301. if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
  302. av_log(ctx, AV_LOG_ERROR,
  303. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  304. return err;
  305. }
  306. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  307. av_log(ctx, AV_LOG_ERROR,
  308. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  309. return AVERROR(EINVAL);
  310. }
  311. /* load the face, and set up the encoding, which is by default UTF-8 */
  312. if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
  313. av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
  314. dtext->fontfile, FT_ERRMSG(err));
  315. return AVERROR(EINVAL);
  316. }
  317. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  318. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  319. dtext->fontsize, FT_ERRMSG(err));
  320. return AVERROR(EINVAL);
  321. }
  322. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  323. /* load the fallback glyph with code 0 */
  324. load_glyph(ctx, NULL, 0);
  325. /* set the tabsize in pixels */
  326. if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
  327. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  328. return err;
  329. }
  330. dtext->tabsize *= glyph->advance;
  331. #if !HAVE_LOCALTIME_R
  332. av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
  333. #endif
  334. return 0;
  335. }
  336. static int query_formats(AVFilterContext *ctx)
  337. {
  338. static const enum PixelFormat pix_fmts[] = {
  339. PIX_FMT_ARGB, PIX_FMT_RGBA,
  340. PIX_FMT_ABGR, PIX_FMT_BGRA,
  341. PIX_FMT_RGB24, PIX_FMT_BGR24,
  342. PIX_FMT_YUV420P, PIX_FMT_YUV444P,
  343. PIX_FMT_YUV422P, PIX_FMT_YUV411P,
  344. PIX_FMT_YUV410P, PIX_FMT_YUV440P,
  345. PIX_FMT_NONE
  346. };
  347. ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
  348. return 0;
  349. }
  350. static int glyph_enu_free(void *opaque, void *elem)
  351. {
  352. av_free(elem);
  353. return 0;
  354. }
  355. static av_cold void uninit(AVFilterContext *ctx)
  356. {
  357. DrawTextContext *dtext = ctx->priv;
  358. int i;
  359. av_freep(&dtext->fontfile);
  360. av_freep(&dtext->text);
  361. av_freep(&dtext->expanded_text);
  362. av_freep(&dtext->fontcolor_string);
  363. av_freep(&dtext->boxcolor_string);
  364. av_freep(&dtext->positions);
  365. av_freep(&dtext->shadowcolor_string);
  366. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  367. av_tree_destroy(dtext->glyphs);
  368. dtext->glyphs = 0;
  369. FT_Done_Face(dtext->face);
  370. FT_Done_FreeType(dtext->library);
  371. for (i = 0; i < 4; i++) {
  372. av_freep(&dtext->box_line[i]);
  373. dtext->pixel_step[i] = 0;
  374. }
  375. }
  376. static inline int is_newline(uint32_t c)
  377. {
  378. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  379. }
  380. static int dtext_prepare_text(AVFilterContext *ctx)
  381. {
  382. DrawTextContext *dtext = ctx->priv;
  383. uint32_t code = 0, prev_code = 0;
  384. int x = 0, y = 0, i = 0, ret;
  385. int text_height, baseline;
  386. char *text = dtext->text;
  387. uint8_t *p;
  388. int str_w = 0, len;
  389. int y_min = 32000, y_max = -32000;
  390. FT_Vector delta;
  391. Glyph *glyph = NULL, *prev_glyph = NULL;
  392. Glyph dummy = { 0 };
  393. int width = ctx->inputs[0]->w;
  394. int height = ctx->inputs[0]->h;
  395. #if HAVE_LOCALTIME_R
  396. time_t now = time(0);
  397. struct tm ltime;
  398. uint8_t *buf = dtext->expanded_text;
  399. int buf_size = dtext->expanded_text_size;
  400. if (!buf)
  401. buf_size = 2*strlen(dtext->text)+1;
  402. localtime_r(&now, &ltime);
  403. while ((buf = av_realloc(buf, buf_size))) {
  404. *buf = 1;
  405. if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
  406. break;
  407. buf_size *= 2;
  408. }
  409. if (!buf)
  410. return AVERROR(ENOMEM);
  411. text = dtext->expanded_text = buf;
  412. dtext->expanded_text_size = buf_size;
  413. #endif
  414. if ((len = strlen(text)) > dtext->nb_positions) {
  415. FT_Vector *p = av_realloc(dtext->positions,
  416. len * sizeof(*dtext->positions));
  417. if (!p) {
  418. av_freep(dtext->positions);
  419. dtext->nb_positions = 0;
  420. return AVERROR(ENOMEM);
  421. } else {
  422. dtext->positions = p;
  423. dtext->nb_positions = len;
  424. }
  425. }
  426. /* load and cache glyphs */
  427. for (i = 0, p = text; *p; i++) {
  428. GET_UTF8(code, *p++, continue;);
  429. /* get glyph */
  430. dummy.code = code;
  431. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  432. if (!glyph) {
  433. ret = load_glyph(ctx, &glyph, code);
  434. if (ret)
  435. return ret;
  436. }
  437. y_min = FFMIN(glyph->bbox.yMin, y_min);
  438. y_max = FFMAX(glyph->bbox.yMax, y_max);
  439. }
  440. text_height = y_max - y_min;
  441. baseline = y_max;
  442. /* compute and save position for each glyph */
  443. glyph = NULL;
  444. for (i = 0, p = text; *p; i++) {
  445. GET_UTF8(code, *p++, continue;);
  446. /* skip the \n in the sequence \r\n */
  447. if (prev_code == '\r' && code == '\n')
  448. continue;
  449. prev_code = code;
  450. if (is_newline(code)) {
  451. str_w = FFMAX(str_w, x - dtext->x);
  452. y += text_height;
  453. x = 0;
  454. continue;
  455. }
  456. /* get glyph */
  457. prev_glyph = glyph;
  458. dummy.code = code;
  459. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  460. /* kerning */
  461. if (dtext->use_kerning && prev_glyph && glyph->code) {
  462. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  463. ft_kerning_default, &delta);
  464. x += delta.x >> 6;
  465. }
  466. if (x + glyph->bbox.xMax >= width) {
  467. str_w = FFMAX(str_w, x);
  468. y += text_height;
  469. x = 0;
  470. }
  471. /* save position */
  472. dtext->positions[i].x = x + glyph->bitmap_left;
  473. dtext->positions[i].y = y - glyph->bitmap_top + baseline;
  474. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  475. else x += glyph->advance;
  476. }
  477. str_w = FFMIN(width - 1, FFMAX(str_w, x));
  478. y = FFMIN(y + text_height, height - 1);
  479. dtext->w = str_w;
  480. dtext->var_values[VAR_TEXT_W] = dtext->var_values[VAR_TW] = dtext->w;
  481. dtext->h = y;
  482. dtext->var_values[VAR_TEXT_H] = dtext->var_values[VAR_TH] = dtext->h;
  483. return 0;
  484. }
  485. static int config_input(AVFilterLink *inlink)
  486. {
  487. AVFilterContext *ctx = inlink->dst;
  488. DrawTextContext *dtext = ctx->priv;
  489. const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
  490. int ret;
  491. dtext->hsub = pix_desc->log2_chroma_w;
  492. dtext->vsub = pix_desc->log2_chroma_h;
  493. dtext->var_values[VAR_E ] = M_E;
  494. dtext->var_values[VAR_PHI] = M_PHI;
  495. dtext->var_values[VAR_PI ] = M_PI;
  496. dtext->var_values[VAR_MAIN_W] =
  497. dtext->var_values[VAR_MW] = ctx->inputs[0]->w;
  498. dtext->var_values[VAR_MAIN_H] =
  499. dtext->var_values[VAR_MH] = ctx->inputs[0]->h;
  500. dtext->var_values[VAR_X] = 0;
  501. dtext->var_values[VAR_Y] = 0;
  502. dtext->var_values[VAR_N] = 0;
  503. dtext->var_values[VAR_T] = NAN;
  504. av_lfg_init(&dtext->prng, av_get_random_seed());
  505. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  506. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  507. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  508. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  509. (ret = av_expr_parse(&dtext->d_pexpr, dtext->d_expr, var_names,
  510. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  511. return AVERROR(EINVAL);
  512. if ((ret =
  513. ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
  514. inlink->w, dtext->boxcolor,
  515. inlink->format, dtext->boxcolor_rgba,
  516. &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
  517. return ret;
  518. if (!dtext->is_packed_rgb) {
  519. uint8_t *rgba = dtext->fontcolor_rgba;
  520. dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  521. dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  522. dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  523. dtext->fontcolor[3] = rgba[3];
  524. rgba = dtext->shadowcolor_rgba;
  525. dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  526. dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  527. dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  528. dtext->shadowcolor[3] = rgba[3];
  529. }
  530. dtext->draw = 1;
  531. return dtext_prepare_text(ctx);
  532. }
  533. #define GET_BITMAP_VAL(r, c) \
  534. bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
  535. (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
  536. bitmap->buffer[(r) * bitmap->pitch + (c)]
  537. #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) { \
  538. luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
  539. alpha = yuva_color[3] * (val) * 129; \
  540. picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos] ) >> 23; \
  541. if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
  542. chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
  543. chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
  544. picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
  545. picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
  546. }\
  547. }
  548. static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
  549. unsigned int y, unsigned int width, unsigned int height,
  550. const uint8_t yuva_color[4], int hsub, int vsub)
  551. {
  552. int r, c, alpha;
  553. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  554. uint8_t src_val;
  555. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  556. for (c = 0; c < bitmap->width && c+x < width; c++) {
  557. /* get intensity value in the glyph bitmap (source) */
  558. src_val = GET_BITMAP_VAL(r, c);
  559. if (!src_val)
  560. continue;
  561. SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
  562. }
  563. }
  564. return 0;
  565. }
  566. #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
  567. p = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
  568. alpha = rgba_color[3] * (val) * 129; \
  569. *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
  570. *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
  571. *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
  572. }
  573. static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
  574. unsigned int x, unsigned int y,
  575. unsigned int width, unsigned int height, int pixel_step,
  576. const uint8_t rgba_color[4], const uint8_t rgba_map[4])
  577. {
  578. int r, c, alpha;
  579. uint8_t *p;
  580. uint8_t src_val;
  581. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  582. for (c = 0; c < bitmap->width && c+x < width; c++) {
  583. /* get intensity value in the glyph bitmap (source) */
  584. src_val = GET_BITMAP_VAL(r, c);
  585. if (!src_val)
  586. continue;
  587. SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
  588. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  589. }
  590. }
  591. return 0;
  592. }
  593. static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
  594. unsigned int width, unsigned int height,
  595. uint8_t *line[4], int pixel_step[4], uint8_t color[4],
  596. int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
  597. {
  598. int i, j, alpha;
  599. if (color[3] != 0xFF) {
  600. if (is_rgba_packed) {
  601. uint8_t *p;
  602. for (j = 0; j < height; j++)
  603. for (i = 0; i < width; i++)
  604. SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
  605. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  606. } else {
  607. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  608. for (j = 0; j < height; j++)
  609. for (i = 0; i < width; i++)
  610. SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
  611. }
  612. } else {
  613. ff_draw_rectangle(picref->data, picref->linesize,
  614. line, pixel_step, hsub, vsub,
  615. x, y, width, height);
  616. }
  617. }
  618. static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
  619. int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
  620. {
  621. char *text = HAVE_LOCALTIME_R ? dtext->expanded_text : dtext->text;
  622. uint32_t code = 0;
  623. int i;
  624. uint8_t *p;
  625. Glyph *glyph = NULL;
  626. for (i = 0, p = text; *p; i++) {
  627. Glyph dummy = { 0 };
  628. GET_UTF8(code, *p++, continue;);
  629. /* skip new line chars, just go to new line */
  630. if (code == '\n' || code == '\r' || code == '\t')
  631. continue;
  632. dummy.code = code;
  633. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  634. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  635. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  636. return AVERROR(EINVAL);
  637. if (dtext->is_packed_rgb) {
  638. draw_glyph_rgb(picref, &glyph->bitmap,
  639. dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
  640. dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
  641. } else {
  642. draw_glyph_yuv(picref, &glyph->bitmap,
  643. dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
  644. yuvcolor, dtext->hsub, dtext->vsub);
  645. }
  646. }
  647. return 0;
  648. }
  649. static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
  650. int width, int height)
  651. {
  652. DrawTextContext *dtext = ctx->priv;
  653. int ret;
  654. /* draw box */
  655. if (dtext->draw_box)
  656. drawbox(picref, dtext->x, dtext->y, dtext->w, dtext->h,
  657. dtext->box_line, dtext->pixel_step, dtext->boxcolor,
  658. dtext->hsub, dtext->vsub, dtext->is_packed_rgb,
  659. dtext->rgba_map);
  660. if (dtext->shadowx || dtext->shadowy) {
  661. if ((ret = draw_glyphs(dtext, picref, width, height,
  662. dtext->shadowcolor_rgba,
  663. dtext->shadowcolor,
  664. dtext->x + dtext->shadowx,
  665. dtext->y + dtext->shadowy)) < 0)
  666. return ret;
  667. }
  668. if ((ret = draw_glyphs(dtext, picref, width, height,
  669. dtext->fontcolor_rgba,
  670. dtext->fontcolor,
  671. dtext->x,
  672. dtext->y)) < 0)
  673. return ret;
  674. return 0;
  675. }
  676. static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
  677. static inline int normalize_double(int *n, double d)
  678. {
  679. int ret = 0;
  680. if (isnan(d)) {
  681. ret = AVERROR(EINVAL);
  682. } else if (d > INT_MAX || d < INT_MIN) {
  683. *n = d > INT_MAX ? INT_MAX : INT_MIN;
  684. ret = AVERROR(EINVAL);
  685. } else
  686. *n = round(d);
  687. return ret;
  688. }
  689. static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
  690. {
  691. AVFilterContext *ctx = inlink->dst;
  692. DrawTextContext *dtext = ctx->priv;
  693. int fail = 0;
  694. if (dtext_prepare_text(ctx) < 0) {
  695. av_log(ctx, AV_LOG_ERROR, "Can't draw text\n");
  696. fail = 1;
  697. }
  698. dtext->var_values[VAR_T] = inpicref->pts == AV_NOPTS_VALUE ?
  699. NAN : inpicref->pts * av_q2d(inlink->time_base);
  700. dtext->var_values[VAR_X] =
  701. av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  702. dtext->var_values[VAR_Y] =
  703. av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  704. dtext->var_values[VAR_X] =
  705. av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  706. dtext->draw = fail ? 0 :
  707. av_expr_eval(dtext->d_pexpr, dtext->var_values, &dtext->prng);
  708. normalize_double(&dtext->x, dtext->var_values[VAR_X]);
  709. normalize_double(&dtext->y, dtext->var_values[VAR_Y]);
  710. if (dtext->fix_bounds) {
  711. if (dtext->x < 0) dtext->x = 0;
  712. if (dtext->y < 0) dtext->y = 0;
  713. if ((unsigned)dtext->x + (unsigned)dtext->w > inlink->w)
  714. dtext->x = inlink->w - dtext->w;
  715. if ((unsigned)dtext->y + (unsigned)dtext->h > inlink->h)
  716. dtext->y = inlink->h - dtext->h;
  717. }
  718. dtext->x &= ~((1 << dtext->hsub) - 1);
  719. dtext->y &= ~((1 << dtext->vsub) - 1);
  720. av_dlog(ctx, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
  721. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  722. dtext->x, dtext->y, dtext->x+dtext->w, dtext->y+dtext->h);
  723. ff_start_frame(inlink->dst->outputs[0], inpicref);
  724. }
  725. static void end_frame(AVFilterLink *inlink)
  726. {
  727. AVFilterLink *outlink = inlink->dst->outputs[0];
  728. AVFilterBufferRef *picref = inlink->cur_buf;
  729. DrawTextContext *dtext = inlink->dst->priv;
  730. if (dtext->draw)
  731. draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
  732. dtext->var_values[VAR_N] += 1.0;
  733. ff_draw_slice(outlink, 0, picref->video->h, 1);
  734. ff_end_frame(outlink);
  735. }
  736. AVFilter avfilter_vf_drawtext = {
  737. .name = "drawtext",
  738. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  739. .priv_size = sizeof(DrawTextContext),
  740. .init = init,
  741. .uninit = uninit,
  742. .query_formats = query_formats,
  743. .inputs = (AVFilterPad[]) {{ .name = "default",
  744. .type = AVMEDIA_TYPE_VIDEO,
  745. .get_video_buffer = ff_null_get_video_buffer,
  746. .start_frame = start_frame,
  747. .draw_slice = null_draw_slice,
  748. .end_frame = end_frame,
  749. .config_props = config_input,
  750. .min_perms = AV_PERM_WRITE |
  751. AV_PERM_READ,
  752. .rej_perms = AV_PERM_PRESERVE },
  753. { .name = NULL}},
  754. .outputs = (AVFilterPad[]) {{ .name = "default",
  755. .type = AVMEDIA_TYPE_VIDEO, },
  756. { .name = NULL}},
  757. };