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.

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