vf_drawtext.c 31 KB

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