vf_drawtext.c 33 KB

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