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.

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