vf_drawtext.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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 "config.h"
  28. #if HAVE_SYS_TIME_H
  29. #include <sys/time.h>
  30. #endif
  31. #include <sys/types.h>
  32. #include <sys/stat.h>
  33. #include <time.h>
  34. #if HAVE_UNISTD_H
  35. #include <unistd.h>
  36. #endif
  37. #include <fenv.h>
  38. #if CONFIG_LIBFONTCONFIG
  39. #include <fontconfig/fontconfig.h>
  40. #endif
  41. #include "libavutil/avstring.h"
  42. #include "libavutil/bprint.h"
  43. #include "libavutil/common.h"
  44. #include "libavutil/file.h"
  45. #include "libavutil/eval.h"
  46. #include "libavutil/opt.h"
  47. #include "libavutil/random_seed.h"
  48. #include "libavutil/parseutils.h"
  49. #include "libavutil/timecode.h"
  50. #include "libavutil/time_internal.h"
  51. #include "libavutil/tree.h"
  52. #include "libavutil/lfg.h"
  53. #include "avfilter.h"
  54. #include "drawutils.h"
  55. #include "formats.h"
  56. #include "internal.h"
  57. #include "video.h"
  58. #if CONFIG_LIBFRIBIDI
  59. #include <fribidi.h>
  60. #endif
  61. #include <ft2build.h>
  62. #include FT_FREETYPE_H
  63. #include FT_GLYPH_H
  64. #include FT_STROKER_H
  65. static const char *const var_names[] = {
  66. "dar",
  67. "hsub", "vsub",
  68. "line_h", "lh", ///< line height, same as max_glyph_h
  69. "main_h", "h", "H", ///< height of the input video
  70. "main_w", "w", "W", ///< width of the input video
  71. "max_glyph_a", "ascent", ///< max glyph ascent
  72. "max_glyph_d", "descent", ///< min glyph descent
  73. "max_glyph_h", ///< max glyph height
  74. "max_glyph_w", ///< max glyph width
  75. "n", ///< number of frame
  76. "sar",
  77. "t", ///< timestamp expressed in seconds
  78. "text_h", "th", ///< height of the rendered text
  79. "text_w", "tw", ///< width of the rendered text
  80. "x",
  81. "y",
  82. "pict_type",
  83. NULL
  84. };
  85. static const char *const fun2_names[] = {
  86. "rand"
  87. };
  88. static double drand(void *opaque, double min, double max)
  89. {
  90. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  91. }
  92. typedef double (*eval_func2)(void *, double a, double b);
  93. static const eval_func2 fun2[] = {
  94. drand,
  95. NULL
  96. };
  97. enum var_name {
  98. VAR_DAR,
  99. VAR_HSUB, VAR_VSUB,
  100. VAR_LINE_H, VAR_LH,
  101. VAR_MAIN_H, VAR_h, VAR_H,
  102. VAR_MAIN_W, VAR_w, VAR_W,
  103. VAR_MAX_GLYPH_A, VAR_ASCENT,
  104. VAR_MAX_GLYPH_D, VAR_DESCENT,
  105. VAR_MAX_GLYPH_H,
  106. VAR_MAX_GLYPH_W,
  107. VAR_N,
  108. VAR_SAR,
  109. VAR_T,
  110. VAR_TEXT_H, VAR_TH,
  111. VAR_TEXT_W, VAR_TW,
  112. VAR_X,
  113. VAR_Y,
  114. VAR_PICT_TYPE,
  115. VAR_VARS_NB
  116. };
  117. enum expansion_mode {
  118. EXP_NONE,
  119. EXP_NORMAL,
  120. EXP_STRFTIME,
  121. };
  122. typedef struct DrawTextContext {
  123. const AVClass *class;
  124. enum expansion_mode exp_mode; ///< expansion mode to use for the text
  125. int reinit; ///< tells if the filter is being reinited
  126. #if CONFIG_LIBFONTCONFIG
  127. uint8_t *font; ///< font to be used
  128. #endif
  129. uint8_t *fontfile; ///< font to be used
  130. uint8_t *text; ///< text to be drawn
  131. AVBPrint expanded_text; ///< used to contain the expanded text
  132. uint8_t *fontcolor_expr; ///< fontcolor expression to evaluate
  133. AVBPrint expanded_fontcolor; ///< used to contain the expanded fontcolor spec
  134. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  135. FT_Vector *positions; ///< positions for each element in the text
  136. size_t nb_positions; ///< number of elements of positions array
  137. char *textfile; ///< file with text to be drawn
  138. int x; ///< x position to start drawing text
  139. int y; ///< y position to start drawing text
  140. int max_glyph_w; ///< max glyph width
  141. int max_glyph_h; ///< max glyph height
  142. int shadowx, shadowy;
  143. int borderw; ///< border width
  144. unsigned int fontsize; ///< font size to use
  145. short int draw_box; ///< draw box around text - true or false
  146. int use_kerning; ///< font kerning is used - true/false
  147. int tabsize; ///< tab size
  148. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  149. FFDrawContext dc;
  150. FFDrawColor fontcolor; ///< foreground color
  151. FFDrawColor shadowcolor; ///< shadow color
  152. FFDrawColor bordercolor; ///< border color
  153. FFDrawColor boxcolor; ///< background color
  154. FT_Library library; ///< freetype font library handle
  155. FT_Face face; ///< freetype font face handle
  156. FT_Stroker stroker; ///< freetype stroker handle
  157. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  158. char *x_expr; ///< expression for x position
  159. char *y_expr; ///< expression for y position
  160. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  161. int64_t basetime; ///< base pts time in the real world for display
  162. double var_values[VAR_VARS_NB];
  163. AVLFG prng; ///< random
  164. char *tc_opt_string; ///< specified timecode option string
  165. AVRational tc_rate; ///< frame rate for timecode
  166. AVTimecode tc; ///< timecode context
  167. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  168. int reload; ///< reload text file for each frame
  169. int start_number; ///< starting frame number for n/frame_num var
  170. #if CONFIG_LIBFRIBIDI
  171. int text_shaping; ///< 1 to shape the text before drawing it
  172. #endif
  173. AVDictionary *metadata;
  174. } DrawTextContext;
  175. #define OFFSET(x) offsetof(DrawTextContext, x)
  176. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  177. static const AVOption drawtext_options[]= {
  178. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  179. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  180. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  181. {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  182. {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, CHAR_MIN, CHAR_MAX, FLAGS},
  183. {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  184. {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  185. {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  186. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  187. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  188. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  189. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  190. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  191. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  192. {"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  193. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  194. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  195. #if CONFIG_LIBFONTCONFIG
  196. { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
  197. #endif
  198. {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
  199. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  200. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  201. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  202. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  203. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  204. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  205. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  206. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  207. {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  208. {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
  209. {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
  210. #if CONFIG_LIBFRIBIDI
  211. {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
  212. #endif
  213. /* FT_LOAD_* flags */
  214. { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT }, 0, INT_MAX, FLAGS, "ft_load_flags" },
  215. { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  216. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  217. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  218. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  219. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  220. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  221. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  222. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  223. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  224. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  225. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  226. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  227. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  228. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  229. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  230. { NULL }
  231. };
  232. AVFILTER_DEFINE_CLASS(drawtext);
  233. #undef __FTERRORS_H__
  234. #define FT_ERROR_START_LIST {
  235. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  236. #define FT_ERROR_END_LIST { 0, NULL } };
  237. static const struct ft_error
  238. {
  239. int err;
  240. const char *err_msg;
  241. } ft_errors[] =
  242. #include FT_ERRORS_H
  243. #define FT_ERRMSG(e) ft_errors[e].err_msg
  244. typedef struct Glyph {
  245. FT_Glyph glyph;
  246. FT_Glyph border_glyph;
  247. uint32_t code;
  248. FT_Bitmap bitmap; ///< array holding bitmaps of font
  249. FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
  250. FT_BBox bbox;
  251. int advance;
  252. int bitmap_left;
  253. int bitmap_top;
  254. } Glyph;
  255. static int glyph_cmp(void *key, const void *b)
  256. {
  257. const Glyph *a = key, *bb = b;
  258. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  259. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  260. }
  261. /**
  262. * Load glyphs corresponding to the UTF-32 codepoint code.
  263. */
  264. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  265. {
  266. DrawTextContext *s = ctx->priv;
  267. FT_BitmapGlyph bitmapglyph;
  268. Glyph *glyph;
  269. struct AVTreeNode *node = NULL;
  270. int ret;
  271. /* load glyph into s->face->glyph */
  272. if (FT_Load_Char(s->face, code, s->ft_load_flags))
  273. return AVERROR(EINVAL);
  274. glyph = av_mallocz(sizeof(*glyph));
  275. if (!glyph) {
  276. ret = AVERROR(ENOMEM);
  277. goto error;
  278. }
  279. glyph->code = code;
  280. if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
  281. ret = AVERROR(EINVAL);
  282. goto error;
  283. }
  284. if (s->borderw) {
  285. glyph->border_glyph = glyph->glyph;
  286. if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
  287. FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
  288. ret = AVERROR_EXTERNAL;
  289. goto error;
  290. }
  291. bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
  292. glyph->border_bitmap = bitmapglyph->bitmap;
  293. }
  294. if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
  295. ret = AVERROR_EXTERNAL;
  296. goto error;
  297. }
  298. bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
  299. glyph->bitmap = bitmapglyph->bitmap;
  300. glyph->bitmap_left = bitmapglyph->left;
  301. glyph->bitmap_top = bitmapglyph->top;
  302. glyph->advance = s->face->glyph->advance.x >> 6;
  303. /* measure text height to calculate text_height (or the maximum text height) */
  304. FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  305. /* cache the newly created glyph */
  306. if (!(node = av_tree_node_alloc())) {
  307. ret = AVERROR(ENOMEM);
  308. goto error;
  309. }
  310. av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
  311. if (glyph_ptr)
  312. *glyph_ptr = glyph;
  313. return 0;
  314. error:
  315. if (glyph)
  316. av_freep(&glyph->glyph);
  317. av_freep(&glyph);
  318. av_freep(&node);
  319. return ret;
  320. }
  321. static int load_font_file(AVFilterContext *ctx, const char *path, int index)
  322. {
  323. DrawTextContext *s = ctx->priv;
  324. int err;
  325. err = FT_New_Face(s->library, path, index, &s->face);
  326. if (err) {
  327. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  328. s->fontfile, FT_ERRMSG(err));
  329. return AVERROR(EINVAL);
  330. }
  331. return 0;
  332. }
  333. #if CONFIG_LIBFONTCONFIG
  334. static int load_font_fontconfig(AVFilterContext *ctx)
  335. {
  336. DrawTextContext *s = ctx->priv;
  337. FcConfig *fontconfig;
  338. FcPattern *pat, *best;
  339. FcResult result = FcResultMatch;
  340. FcChar8 *filename;
  341. int index;
  342. double size;
  343. int err = AVERROR(ENOENT);
  344. fontconfig = FcInitLoadConfigAndFonts();
  345. if (!fontconfig) {
  346. av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
  347. return AVERROR_UNKNOWN;
  348. }
  349. pat = FcNameParse(s->fontfile ? s->fontfile :
  350. (uint8_t *)(intptr_t)"default");
  351. if (!pat) {
  352. av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
  353. return AVERROR(EINVAL);
  354. }
  355. FcPatternAddString(pat, FC_FAMILY, s->font);
  356. if (s->fontsize)
  357. FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
  358. FcDefaultSubstitute(pat);
  359. if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
  360. av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
  361. FcPatternDestroy(pat);
  362. return AVERROR(ENOMEM);
  363. }
  364. best = FcFontMatch(fontconfig, pat, &result);
  365. FcPatternDestroy(pat);
  366. if (!best || result != FcResultMatch) {
  367. av_log(ctx, AV_LOG_ERROR,
  368. "Cannot find a valid font for the family %s\n",
  369. s->font);
  370. goto fail;
  371. }
  372. if (
  373. FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
  374. FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
  375. av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
  376. return AVERROR(EINVAL);
  377. }
  378. if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
  379. av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
  380. s->font);
  381. goto fail;
  382. }
  383. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  384. if (!s->fontsize)
  385. s->fontsize = size + 0.5;
  386. err = load_font_file(ctx, filename, index);
  387. if (err)
  388. return err;
  389. FcConfigDestroy(fontconfig);
  390. fail:
  391. FcPatternDestroy(best);
  392. return err;
  393. }
  394. #endif
  395. static int load_font(AVFilterContext *ctx)
  396. {
  397. DrawTextContext *s = ctx->priv;
  398. int err;
  399. /* load the face, and set up the encoding, which is by default UTF-8 */
  400. err = load_font_file(ctx, s->fontfile, 0);
  401. if (!err)
  402. return 0;
  403. #if CONFIG_LIBFONTCONFIG
  404. err = load_font_fontconfig(ctx);
  405. if (!err)
  406. return 0;
  407. #endif
  408. return err;
  409. }
  410. static int load_textfile(AVFilterContext *ctx)
  411. {
  412. DrawTextContext *s = ctx->priv;
  413. int err;
  414. uint8_t *textbuf;
  415. uint8_t *tmp;
  416. size_t textbuf_size;
  417. if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  418. av_log(ctx, AV_LOG_ERROR,
  419. "The text file '%s' could not be read or is empty\n",
  420. s->textfile);
  421. return err;
  422. }
  423. if (textbuf_size > SIZE_MAX - 1 || !(tmp = av_realloc(s->text, textbuf_size + 1))) {
  424. av_file_unmap(textbuf, textbuf_size);
  425. return AVERROR(ENOMEM);
  426. }
  427. s->text = tmp;
  428. memcpy(s->text, textbuf, textbuf_size);
  429. s->text[textbuf_size] = 0;
  430. av_file_unmap(textbuf, textbuf_size);
  431. return 0;
  432. }
  433. static inline int is_newline(uint32_t c)
  434. {
  435. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  436. }
  437. #if CONFIG_LIBFRIBIDI
  438. static int shape_text(AVFilterContext *ctx)
  439. {
  440. DrawTextContext *s = ctx->priv;
  441. uint8_t *tmp;
  442. int ret = AVERROR(ENOMEM);
  443. static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
  444. FRIBIDI_FLAGS_ARABIC;
  445. FriBidiChar *unicodestr = NULL;
  446. FriBidiStrIndex len;
  447. FriBidiParType direction = FRIBIDI_PAR_LTR;
  448. FriBidiStrIndex line_start = 0;
  449. FriBidiStrIndex line_end = 0;
  450. FriBidiLevel *embedding_levels = NULL;
  451. FriBidiArabicProp *ar_props = NULL;
  452. FriBidiCharType *bidi_types = NULL;
  453. FriBidiStrIndex i,j;
  454. len = strlen(s->text);
  455. if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
  456. goto out;
  457. }
  458. len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
  459. s->text, len, unicodestr);
  460. bidi_types = av_malloc_array(len, sizeof(*bidi_types));
  461. if (!bidi_types) {
  462. goto out;
  463. }
  464. fribidi_get_bidi_types(unicodestr, len, bidi_types);
  465. embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
  466. if (!embedding_levels) {
  467. goto out;
  468. }
  469. if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
  470. embedding_levels)) {
  471. goto out;
  472. }
  473. ar_props = av_malloc_array(len, sizeof(*ar_props));
  474. if (!ar_props) {
  475. goto out;
  476. }
  477. fribidi_get_joining_types(unicodestr, len, ar_props);
  478. fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
  479. fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
  480. for (line_end = 0, line_start = 0; line_end < len; line_end++) {
  481. if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
  482. if (!fribidi_reorder_line(flags, bidi_types,
  483. line_end - line_start + 1, line_start,
  484. direction, embedding_levels, unicodestr,
  485. NULL)) {
  486. goto out;
  487. }
  488. line_start = line_end + 1;
  489. }
  490. }
  491. /* Remove zero-width fill chars put in by libfribidi */
  492. for (i = 0, j = 0; i < len; i++)
  493. if (unicodestr[i] != FRIBIDI_CHAR_FILL)
  494. unicodestr[j++] = unicodestr[i];
  495. len = j;
  496. if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
  497. /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
  498. goto out;
  499. }
  500. s->text = tmp;
  501. len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
  502. unicodestr, len, s->text);
  503. ret = 0;
  504. out:
  505. av_free(unicodestr);
  506. av_free(embedding_levels);
  507. av_free(ar_props);
  508. av_free(bidi_types);
  509. return ret;
  510. }
  511. #endif
  512. static av_cold int init(AVFilterContext *ctx)
  513. {
  514. int err;
  515. DrawTextContext *s = ctx->priv;
  516. Glyph *glyph;
  517. if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
  518. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  519. return AVERROR(EINVAL);
  520. }
  521. if (s->textfile) {
  522. if (s->text) {
  523. av_log(ctx, AV_LOG_ERROR,
  524. "Both text and text file provided. Please provide only one\n");
  525. return AVERROR(EINVAL);
  526. }
  527. if ((err = load_textfile(ctx)) < 0)
  528. return err;
  529. }
  530. #if CONFIG_LIBFRIBIDI
  531. if (s->text_shaping)
  532. if ((err = shape_text(ctx)) < 0)
  533. return err;
  534. #endif
  535. if (s->reload && !s->textfile)
  536. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  537. if (s->tc_opt_string) {
  538. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  539. s->tc_opt_string, ctx);
  540. if (ret < 0)
  541. return ret;
  542. if (s->tc24hmax)
  543. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  544. if (!s->text)
  545. s->text = av_strdup("");
  546. }
  547. if (!s->text) {
  548. av_log(ctx, AV_LOG_ERROR,
  549. "Either text, a valid file or a timecode must be provided\n");
  550. return AVERROR(EINVAL);
  551. }
  552. if ((err = FT_Init_FreeType(&(s->library)))) {
  553. av_log(ctx, AV_LOG_ERROR,
  554. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  555. return AVERROR(EINVAL);
  556. }
  557. err = load_font(ctx);
  558. if (err)
  559. return err;
  560. if (!s->fontsize)
  561. s->fontsize = 16;
  562. if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
  563. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  564. s->fontsize, FT_ERRMSG(err));
  565. return AVERROR(EINVAL);
  566. }
  567. if (s->borderw) {
  568. if (FT_Stroker_New(s->library, &s->stroker)) {
  569. av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
  570. return AVERROR_EXTERNAL;
  571. }
  572. FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
  573. FT_STROKER_LINEJOIN_ROUND, 0);
  574. }
  575. s->use_kerning = FT_HAS_KERNING(s->face);
  576. /* load the fallback glyph with code 0 */
  577. load_glyph(ctx, NULL, 0);
  578. /* set the tabsize in pixels */
  579. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  580. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  581. return err;
  582. }
  583. s->tabsize *= glyph->advance;
  584. if (s->exp_mode == EXP_STRFTIME &&
  585. (strchr(s->text, '%') || strchr(s->text, '\\')))
  586. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  587. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  588. av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
  589. return 0;
  590. }
  591. static int query_formats(AVFilterContext *ctx)
  592. {
  593. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  594. return 0;
  595. }
  596. static int glyph_enu_free(void *opaque, void *elem)
  597. {
  598. Glyph *glyph = elem;
  599. FT_Done_Glyph(glyph->glyph);
  600. FT_Done_Glyph(glyph->border_glyph);
  601. av_free(elem);
  602. return 0;
  603. }
  604. static av_cold void uninit(AVFilterContext *ctx)
  605. {
  606. DrawTextContext *s = ctx->priv;
  607. av_expr_free(s->x_pexpr);
  608. av_expr_free(s->y_pexpr);
  609. s->x_pexpr = s->y_pexpr = NULL;
  610. av_freep(&s->positions);
  611. s->nb_positions = 0;
  612. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  613. av_tree_destroy(s->glyphs);
  614. s->glyphs = NULL;
  615. FT_Done_Face(s->face);
  616. FT_Stroker_Done(s->stroker);
  617. FT_Done_FreeType(s->library);
  618. av_bprint_finalize(&s->expanded_text, NULL);
  619. av_bprint_finalize(&s->expanded_fontcolor, NULL);
  620. }
  621. static int config_input(AVFilterLink *inlink)
  622. {
  623. AVFilterContext *ctx = inlink->dst;
  624. DrawTextContext *s = ctx->priv;
  625. int ret;
  626. ff_draw_init(&s->dc, inlink->format, 0);
  627. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  628. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  629. ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
  630. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  631. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  632. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  633. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  634. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  635. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  636. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  637. s->var_values[VAR_X] = NAN;
  638. s->var_values[VAR_Y] = NAN;
  639. s->var_values[VAR_T] = NAN;
  640. av_lfg_init(&s->prng, av_get_random_seed());
  641. av_expr_free(s->x_pexpr);
  642. av_expr_free(s->y_pexpr);
  643. s->x_pexpr = s->y_pexpr = NULL;
  644. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  645. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  646. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  647. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  648. return AVERROR(EINVAL);
  649. return 0;
  650. }
  651. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  652. {
  653. DrawTextContext *s = ctx->priv;
  654. if (!strcmp(cmd, "reinit")) {
  655. int ret;
  656. uninit(ctx);
  657. s->reinit = 1;
  658. if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
  659. return ret;
  660. if ((ret = init(ctx)) < 0)
  661. return ret;
  662. return config_input(ctx->inputs[0]);
  663. }
  664. return AVERROR(ENOSYS);
  665. }
  666. static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
  667. char *fct, unsigned argc, char **argv, int tag)
  668. {
  669. DrawTextContext *s = ctx->priv;
  670. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  671. return 0;
  672. }
  673. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  674. char *fct, unsigned argc, char **argv, int tag)
  675. {
  676. DrawTextContext *s = ctx->priv;
  677. const char *fmt;
  678. double pts = s->var_values[VAR_T];
  679. int ret;
  680. fmt = argc >= 1 ? argv[0] : "flt";
  681. if (argc >= 2) {
  682. int64_t delta;
  683. if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
  684. av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
  685. return ret;
  686. }
  687. pts += (double)delta / AV_TIME_BASE;
  688. }
  689. if (!strcmp(fmt, "flt")) {
  690. av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
  691. } else if (!strcmp(fmt, "hms")) {
  692. if (isnan(pts)) {
  693. av_bprintf(bp, " ??:??:??.???");
  694. } else {
  695. int64_t ms = round(pts * 1000);
  696. char sign = ' ';
  697. if (ms < 0) {
  698. sign = '-';
  699. ms = -ms;
  700. }
  701. av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
  702. (int)(ms / (60 * 60 * 1000)),
  703. (int)(ms / (60 * 1000)) % 60,
  704. (int)(ms / 1000) % 60,
  705. (int)ms % 1000);
  706. }
  707. } else {
  708. av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
  709. return AVERROR(EINVAL);
  710. }
  711. return 0;
  712. }
  713. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  714. char *fct, unsigned argc, char **argv, int tag)
  715. {
  716. DrawTextContext *s = ctx->priv;
  717. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  718. return 0;
  719. }
  720. static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
  721. char *fct, unsigned argc, char **argv, int tag)
  722. {
  723. DrawTextContext *s = ctx->priv;
  724. AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
  725. if (e && e->value)
  726. av_bprintf(bp, "%s", e->value);
  727. return 0;
  728. }
  729. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  730. char *fct, unsigned argc, char **argv, int tag)
  731. {
  732. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  733. time_t now;
  734. struct tm tm;
  735. time(&now);
  736. if (tag == 'L')
  737. localtime_r(&now, &tm);
  738. else
  739. tm = *gmtime_r(&now, &tm);
  740. av_bprint_strftime(bp, fmt, &tm);
  741. return 0;
  742. }
  743. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  744. char *fct, unsigned argc, char **argv, int tag)
  745. {
  746. DrawTextContext *s = ctx->priv;
  747. double res;
  748. int ret;
  749. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  750. NULL, NULL, fun2_names, fun2,
  751. &s->prng, 0, ctx);
  752. if (ret < 0)
  753. av_log(ctx, AV_LOG_ERROR,
  754. "Expression '%s' for the expr text expansion function is not valid\n",
  755. argv[0]);
  756. else
  757. av_bprintf(bp, "%f", res);
  758. return ret;
  759. }
  760. static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
  761. char *fct, unsigned argc, char **argv, int tag)
  762. {
  763. DrawTextContext *s = ctx->priv;
  764. double res;
  765. int intval;
  766. int ret;
  767. unsigned int positions = 0;
  768. char fmt_str[30] = "%";
  769. /*
  770. * argv[0] expression to be converted to `int`
  771. * argv[1] format: 'x', 'X', 'd' or 'u'
  772. * argv[2] positions printed (optional)
  773. */
  774. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  775. NULL, NULL, fun2_names, fun2,
  776. &s->prng, 0, ctx);
  777. if (ret < 0) {
  778. av_log(ctx, AV_LOG_ERROR,
  779. "Expression '%s' for the expr text expansion function is not valid\n",
  780. argv[0]);
  781. return ret;
  782. }
  783. if (!strchr("xXdu", argv[1][0])) {
  784. av_log(ctx, AV_LOG_ERROR, "Invalid format '%c' specified,"
  785. " allowed values: 'x', 'X', 'd', 'u'\n", argv[1][0]);
  786. return AVERROR(EINVAL);
  787. }
  788. if (argc == 3) {
  789. ret = sscanf(argv[2], "%u", &positions);
  790. if (ret != 1) {
  791. av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
  792. " to print: '%s'\n", argv[2]);
  793. return AVERROR(EINVAL);
  794. }
  795. }
  796. feclearexcept(FE_ALL_EXCEPT);
  797. intval = res;
  798. if ((ret = fetestexcept(FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW))) {
  799. av_log(ctx, AV_LOG_ERROR, "Conversion of floating-point result to int failed. Control register: 0x%08x. Conversion result: %d\n", ret, intval);
  800. return AVERROR(EINVAL);
  801. }
  802. if (argc == 3)
  803. av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
  804. av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
  805. av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
  806. res, argv[0], fmt_str);
  807. av_bprintf(bp, fmt_str, intval);
  808. return 0;
  809. }
  810. static const struct drawtext_function {
  811. const char *name;
  812. unsigned argc_min, argc_max;
  813. int tag; /**< opaque argument to func */
  814. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  815. } functions[] = {
  816. { "expr", 1, 1, 0, func_eval_expr },
  817. { "e", 1, 1, 0, func_eval_expr },
  818. { "expr_int_format", 2, 3, 0, func_eval_expr_int_format },
  819. { "eif", 2, 3, 0, func_eval_expr_int_format },
  820. { "pict_type", 0, 0, 0, func_pict_type },
  821. { "pts", 0, 2, 0, func_pts },
  822. { "gmtime", 0, 1, 'G', func_strftime },
  823. { "localtime", 0, 1, 'L', func_strftime },
  824. { "frame_num", 0, 0, 0, func_frame_num },
  825. { "n", 0, 0, 0, func_frame_num },
  826. { "metadata", 1, 1, 0, func_metadata },
  827. };
  828. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  829. unsigned argc, char **argv)
  830. {
  831. unsigned i;
  832. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  833. if (strcmp(fct, functions[i].name))
  834. continue;
  835. if (argc < functions[i].argc_min) {
  836. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  837. fct, functions[i].argc_min);
  838. return AVERROR(EINVAL);
  839. }
  840. if (argc > functions[i].argc_max) {
  841. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  842. fct, functions[i].argc_max);
  843. return AVERROR(EINVAL);
  844. }
  845. break;
  846. }
  847. if (i >= FF_ARRAY_ELEMS(functions)) {
  848. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  849. return AVERROR(EINVAL);
  850. }
  851. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  852. }
  853. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  854. {
  855. const char *text = *rtext;
  856. char *argv[16] = { NULL };
  857. unsigned argc = 0, i;
  858. int ret;
  859. if (*text != '{') {
  860. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  861. return AVERROR(EINVAL);
  862. }
  863. text++;
  864. while (1) {
  865. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  866. ret = AVERROR(ENOMEM);
  867. goto end;
  868. }
  869. if (!*text) {
  870. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  871. ret = AVERROR(EINVAL);
  872. goto end;
  873. }
  874. if (argc == FF_ARRAY_ELEMS(argv))
  875. av_freep(&argv[--argc]); /* error will be caught later */
  876. if (*text == '}')
  877. break;
  878. text++;
  879. }
  880. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  881. goto end;
  882. ret = 0;
  883. *rtext = (char *)text + 1;
  884. end:
  885. for (i = 0; i < argc; i++)
  886. av_freep(&argv[i]);
  887. return ret;
  888. }
  889. static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
  890. {
  891. int ret;
  892. av_bprint_clear(bp);
  893. while (*text) {
  894. if (*text == '\\' && text[1]) {
  895. av_bprint_chars(bp, text[1], 1);
  896. text += 2;
  897. } else if (*text == '%') {
  898. text++;
  899. if ((ret = expand_function(ctx, bp, &text)) < 0)
  900. return ret;
  901. } else {
  902. av_bprint_chars(bp, *text, 1);
  903. text++;
  904. }
  905. }
  906. if (!av_bprint_is_complete(bp))
  907. return AVERROR(ENOMEM);
  908. return 0;
  909. }
  910. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  911. int width, int height,
  912. FFDrawColor *color, int x, int y, int borderw)
  913. {
  914. char *text = s->expanded_text.str;
  915. uint32_t code = 0;
  916. int i, x1, y1;
  917. uint8_t *p;
  918. Glyph *glyph = NULL;
  919. for (i = 0, p = text; *p; i++) {
  920. FT_Bitmap bitmap;
  921. Glyph dummy = { 0 };
  922. GET_UTF8(code, *p++, continue;);
  923. /* skip new line chars, just go to new line */
  924. if (code == '\n' || code == '\r' || code == '\t')
  925. continue;
  926. dummy.code = code;
  927. glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
  928. bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
  929. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  930. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  931. return AVERROR(EINVAL);
  932. x1 = s->positions[i].x+s->x+x - borderw;
  933. y1 = s->positions[i].y+s->y+y - borderw;
  934. ff_blend_mask(&s->dc, color,
  935. frame->data, frame->linesize, width, height,
  936. bitmap.buffer, bitmap.pitch,
  937. bitmap.width, bitmap.rows,
  938. bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  939. 0, x1, y1);
  940. }
  941. return 0;
  942. }
  943. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  944. int width, int height)
  945. {
  946. DrawTextContext *s = ctx->priv;
  947. AVFilterLink *inlink = ctx->inputs[0];
  948. uint32_t code = 0, prev_code = 0;
  949. int x = 0, y = 0, i = 0, ret;
  950. int max_text_line_w = 0, len;
  951. int box_w, box_h;
  952. char *text;
  953. uint8_t *p;
  954. int y_min = 32000, y_max = -32000;
  955. int x_min = 32000, x_max = -32000;
  956. FT_Vector delta;
  957. Glyph *glyph = NULL, *prev_glyph = NULL;
  958. Glyph dummy = { 0 };
  959. time_t now = time(0);
  960. struct tm ltime;
  961. AVBPrint *bp = &s->expanded_text;
  962. av_bprint_clear(bp);
  963. if(s->basetime != AV_NOPTS_VALUE)
  964. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  965. switch (s->exp_mode) {
  966. case EXP_NONE:
  967. av_bprintf(bp, "%s", s->text);
  968. break;
  969. case EXP_NORMAL:
  970. if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
  971. return ret;
  972. break;
  973. case EXP_STRFTIME:
  974. localtime_r(&now, &ltime);
  975. av_bprint_strftime(bp, s->text, &ltime);
  976. break;
  977. }
  978. if (s->tc_opt_string) {
  979. char tcbuf[AV_TIMECODE_STR_SIZE];
  980. av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
  981. av_bprint_clear(bp);
  982. av_bprintf(bp, "%s%s", s->text, tcbuf);
  983. }
  984. if (!av_bprint_is_complete(bp))
  985. return AVERROR(ENOMEM);
  986. text = s->expanded_text.str;
  987. if ((len = s->expanded_text.len) > s->nb_positions) {
  988. if (!(s->positions =
  989. av_realloc(s->positions, len*sizeof(*s->positions))))
  990. return AVERROR(ENOMEM);
  991. s->nb_positions = len;
  992. }
  993. if (s->fontcolor_expr[0]) {
  994. /* If expression is set, evaluate and replace the static value */
  995. av_bprint_clear(&s->expanded_fontcolor);
  996. if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
  997. return ret;
  998. if (!av_bprint_is_complete(&s->expanded_fontcolor))
  999. return AVERROR(ENOMEM);
  1000. av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
  1001. ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
  1002. if (ret)
  1003. return ret;
  1004. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  1005. }
  1006. x = 0;
  1007. y = 0;
  1008. /* load and cache glyphs */
  1009. for (i = 0, p = text; *p; i++) {
  1010. GET_UTF8(code, *p++, continue;);
  1011. /* get glyph */
  1012. dummy.code = code;
  1013. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1014. if (!glyph) {
  1015. ret = load_glyph(ctx, &glyph, code);
  1016. if (ret < 0)
  1017. return ret;
  1018. }
  1019. y_min = FFMIN(glyph->bbox.yMin, y_min);
  1020. y_max = FFMAX(glyph->bbox.yMax, y_max);
  1021. x_min = FFMIN(glyph->bbox.xMin, x_min);
  1022. x_max = FFMAX(glyph->bbox.xMax, x_max);
  1023. }
  1024. s->max_glyph_h = y_max - y_min;
  1025. s->max_glyph_w = x_max - x_min;
  1026. /* compute and save position for each glyph */
  1027. glyph = NULL;
  1028. for (i = 0, p = text; *p; i++) {
  1029. GET_UTF8(code, *p++, continue;);
  1030. /* skip the \n in the sequence \r\n */
  1031. if (prev_code == '\r' && code == '\n')
  1032. continue;
  1033. prev_code = code;
  1034. if (is_newline(code)) {
  1035. max_text_line_w = FFMAX(max_text_line_w, x);
  1036. y += s->max_glyph_h;
  1037. x = 0;
  1038. continue;
  1039. }
  1040. /* get glyph */
  1041. prev_glyph = glyph;
  1042. dummy.code = code;
  1043. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1044. /* kerning */
  1045. if (s->use_kerning && prev_glyph && glyph->code) {
  1046. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  1047. ft_kerning_default, &delta);
  1048. x += delta.x >> 6;
  1049. }
  1050. /* save position */
  1051. s->positions[i].x = x + glyph->bitmap_left;
  1052. s->positions[i].y = y - glyph->bitmap_top + y_max;
  1053. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  1054. else x += glyph->advance;
  1055. }
  1056. max_text_line_w = FFMAX(x, max_text_line_w);
  1057. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
  1058. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
  1059. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  1060. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  1061. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
  1062. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
  1063. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
  1064. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1065. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  1066. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1067. box_w = FFMIN(width - 1 , max_text_line_w);
  1068. box_h = FFMIN(height - 1, y + s->max_glyph_h);
  1069. /* draw box */
  1070. if (s->draw_box)
  1071. ff_blend_rectangle(&s->dc, &s->boxcolor,
  1072. frame->data, frame->linesize, width, height,
  1073. s->x, s->y, box_w, box_h);
  1074. if (s->shadowx || s->shadowy) {
  1075. if ((ret = draw_glyphs(s, frame, width, height,
  1076. &s->shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
  1077. return ret;
  1078. }
  1079. if (s->borderw) {
  1080. if ((ret = draw_glyphs(s, frame, width, height,
  1081. &s->bordercolor, 0, 0, s->borderw)) < 0)
  1082. return ret;
  1083. }
  1084. if ((ret = draw_glyphs(s, frame, width, height,
  1085. &s->fontcolor, 0, 0, 0)) < 0)
  1086. return ret;
  1087. return 0;
  1088. }
  1089. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  1090. {
  1091. AVFilterContext *ctx = inlink->dst;
  1092. AVFilterLink *outlink = ctx->outputs[0];
  1093. DrawTextContext *s = ctx->priv;
  1094. int ret;
  1095. if (s->reload) {
  1096. if ((ret = load_textfile(ctx)) < 0)
  1097. return ret;
  1098. #if CONFIG_LIBFRIBIDI
  1099. if (s->text_shaping)
  1100. if ((ret = shape_text(ctx)) < 0)
  1101. return ret;
  1102. #endif
  1103. }
  1104. s->var_values[VAR_N] = inlink->frame_count+s->start_number;
  1105. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  1106. NAN : frame->pts * av_q2d(inlink->time_base);
  1107. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  1108. s->metadata = av_frame_get_metadata(frame);
  1109. draw_text(ctx, frame, frame->width, frame->height);
  1110. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  1111. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  1112. (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
  1113. s->x, s->y);
  1114. return ff_filter_frame(outlink, frame);
  1115. }
  1116. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  1117. {
  1118. .name = "default",
  1119. .type = AVMEDIA_TYPE_VIDEO,
  1120. .filter_frame = filter_frame,
  1121. .config_props = config_input,
  1122. .needs_writable = 1,
  1123. },
  1124. { NULL }
  1125. };
  1126. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  1127. {
  1128. .name = "default",
  1129. .type = AVMEDIA_TYPE_VIDEO,
  1130. },
  1131. { NULL }
  1132. };
  1133. AVFilter ff_vf_drawtext = {
  1134. .name = "drawtext",
  1135. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  1136. .priv_size = sizeof(DrawTextContext),
  1137. .priv_class = &drawtext_class,
  1138. .init = init,
  1139. .uninit = uninit,
  1140. .query_formats = query_formats,
  1141. .inputs = avfilter_vf_drawtext_inputs,
  1142. .outputs = avfilter_vf_drawtext_outputs,
  1143. .process_command = command,
  1144. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
  1145. };