vf_drawtext.c 34 KB

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