vf_drawtext.c 33 KB

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