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.

902 lines
34KB

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