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.

882 lines
32KB

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