vf_drawtext.c 32 KB

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