vf_drawtext.c 31 KB

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