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.

853 lines
31KB

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