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