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