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.

846 lines
32KB

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