h264_metadata: Add option to delete filler data
[libav.git] / libavfilter / vf_drawtext.c
CommitLineData
a5b64584
SS
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 *
5ac4952a 6 * This file is part of Libav.
a5b64584 7 *
5ac4952a 8 * Libav is free software; you can redistribute it and/or
a5b64584
SS
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 *
5ac4952a 13 * Libav is distributed in the hope that it will be useful,
a5b64584
SS
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
5ac4952a 19 * License along with Libav; if not, write to the Free Software
a5b64584
SS
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
24 * @file
124e2884 25 * drawtext filter, based on the original vhook/drawtext.c
a5b64584
SS
26 * filter by Gustavo Sverzut Barbieri
27 */
28
f1b239ec
LB
29#include "config.h"
30
31#include <sys/types.h>
a5b64584 32#include <sys/time.h>
f1b239ec 33#include <sys/stat.h>
a5b64584 34#include <time.h>
f1b239ec
LB
35#include <unistd.h>
36
37#if CONFIG_LIBFONTCONFIG
38#include <fontconfig/fontconfig.h>
39#endif
a5b64584
SS
40
41#include "libavutil/colorspace.h"
33e11284 42#include "libavutil/common.h"
a5b64584 43#include "libavutil/file.h"
2cf74eca 44#include "libavutil/eval.h"
a5b64584 45#include "libavutil/opt.h"
2cf74eca 46#include "libavutil/mathematics.h"
f5edfc9e 47#include "libavutil/random_seed.h"
a5b64584
SS
48#include "libavutil/parseutils.h"
49#include "libavutil/pixdesc.h"
6b9b42cc 50#include "libavutil/time_internal.h"
a5b64584 51#include "libavutil/tree.h"
f5edfc9e 52#include "libavutil/lfg.h"
a5b64584
SS
53#include "avfilter.h"
54#include "drawutils.h"
b74a1da4 55#include "formats.h"
9d0bfc50 56#include "internal.h"
c04c533f 57#include "video.h"
a5b64584 58
a5b64584 59#include <ft2build.h>
a5b64584
SS
60#include FT_FREETYPE_H
61#include FT_GLYPH_H
62
b0f29db5 63static const char *const var_names[] = {
2cf74eca
LB
64 "E",
65 "PHI",
66 "PI",
67 "main_w", "W", ///< width of the main video
68 "main_h", "H", ///< height of the main video
69 "text_w", "w", ///< width of the overlay text
70 "text_h", "h", ///< height of the overlay text
71 "x",
72 "y",
73 "n", ///< number of processed frames
74 "t", ///< timestamp expressed in seconds
75 NULL
76};
77
b0f29db5
AC
78static const char *const fun2_names[] = {
79 "rand"
f5edfc9e
LB
80};
81
82static double drand(void *opaque, double min, double max)
83{
78212cef 84 return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
f5edfc9e
LB
85}
86
87typedef double (*eval_func2)(void *, double a, double b);
88
89static const eval_func2 fun2[] = {
90 drand,
91 NULL
92};
93
2cf74eca
LB
94enum var_name {
95 VAR_E,
96 VAR_PHI,
97 VAR_PI,
98 VAR_MAIN_W, VAR_MW,
99 VAR_MAIN_H, VAR_MH,
100 VAR_TEXT_W, VAR_TW,
101 VAR_TEXT_H, VAR_TH,
102 VAR_X,
103 VAR_Y,
104 VAR_N,
105 VAR_T,
106 VAR_VARS_NB
107};
108
58400ac1 109typedef struct DrawTextContext {
a5b64584 110 const AVClass *class;
f1b239ec
LB
111#if CONFIG_LIBFONTCONFIG
112 uint8_t *font; ///< font to be used
113#endif
a5b64584
SS
114 uint8_t *fontfile; ///< font to be used
115 uint8_t *text; ///< text to be drawn
3fd53def
SS
116 uint8_t *expanded_text; ///< used to contain the strftime()-expanded text
117 size_t expanded_text_size; ///< size in bytes of the expanded_text buffer
a5b64584
SS
118 int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
119 FT_Vector *positions; ///< positions for each element in the text
3fd53def 120 size_t nb_positions; ///< number of elements of positions array
a5b64584 121 char *textfile; ///< file with text to be drawn
a2fb4bcb
LB
122 int x, y; ///< position to start drawing text
123 int w, h; ///< dimension of the text block
c5420f10 124 int shadowx, shadowy;
a5b64584
SS
125 unsigned int fontsize; ///< font size to use
126 char *fontcolor_string; ///< font color as string
127 char *boxcolor_string; ///< box color as string
c5420f10 128 char *shadowcolor_string; ///< shadow color as string
a5b64584
SS
129 uint8_t fontcolor[4]; ///< foreground color
130 uint8_t boxcolor[4]; ///< background color
c5420f10 131 uint8_t shadowcolor[4]; ///< shadow color
a5b64584
SS
132 uint8_t fontcolor_rgba[4]; ///< foreground color in RGBA
133 uint8_t boxcolor_rgba[4]; ///< background color in RGBA
c5420f10 134 uint8_t shadowcolor_rgba[4]; ///< shadow color in RGBA
a5b64584
SS
135
136 short int draw_box; ///< draw box around text - true or false
137 int use_kerning; ///< font kerning is used - true/false
138 int tabsize; ///< tab size
e496c45d 139 int fix_bounds; ///< do we let it go out of frame bounds - t/f
a5b64584
SS
140
141 FT_Library library; ///< freetype font library handle
142 FT_Face face; ///< freetype font face handle
143 struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
144 int hsub, vsub; ///< chroma subsampling values
145 int is_packed_rgb;
146 int pixel_step[4]; ///< distance in bytes between the component of each pixel
147 uint8_t rgba_map[4]; ///< map RGBA offsets to the positions in the packed RGBA format
148 uint8_t *box_line[4]; ///< line used for filling the box background
2cf74eca
LB
149 char *x_expr, *y_expr;
150 AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
151 double var_values[VAR_VARS_NB];
73585620
LB
152 char *d_expr;
153 AVExpr *d_pexpr;
2cf74eca 154 int draw; ///< set to zero to prevent drawing
9b2c57be
LB
155 char *a_expr;
156 AVExpr *a_pexpr;
157 int alpha;
f5edfc9e 158 AVLFG prng; ///< random
a5b64584
SS
159} DrawTextContext;
160
161#define OFFSET(x) offsetof(DrawTextContext, x)
8ec464c6 162#define FLAGS AV_OPT_FLAG_VIDEO_PARAM
a5b64584
SS
163
164static const AVOption drawtext_options[]= {
f1b239ec
LB
165#if CONFIG_LIBFONTCONFIG
166 { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
167#endif
8ec464c6
AK
168 { "fontfile", NULL, OFFSET(fontfile), AV_OPT_TYPE_STRING, .flags = FLAGS },
169 { "text", NULL, OFFSET(text), AV_OPT_TYPE_STRING, .flags = FLAGS },
170 { "textfile", NULL, OFFSET(textfile), AV_OPT_TYPE_STRING, .flags = FLAGS },
171 { "fontcolor", NULL, OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, { .str = "black" }, .flags = FLAGS },
172 { "boxcolor", NULL, OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, { .str = "white" }, .flags = FLAGS },
173 { "shadowcolor", NULL, OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, { .str = "black" }, .flags = FLAGS },
174 { "box", NULL, OFFSET(draw_box), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
71f29410 175 { "fontsize", NULL, OFFSET(fontsize), AV_OPT_TYPE_INT, { .i64 = 16 }, 1, 1024, FLAGS },
8ec464c6
AK
176 { "x", NULL, OFFSET(x_expr), AV_OPT_TYPE_STRING, { .str = "0" }, .flags = FLAGS },
177 { "y", NULL, OFFSET(y_expr), AV_OPT_TYPE_STRING, { .str = "0" }, .flags = FLAGS },
178 { "shadowx", NULL, OFFSET(shadowx), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS },
179 { "shadowy", NULL, OFFSET(shadowy), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS },
180 { "tabsize", NULL, OFFSET(tabsize), AV_OPT_TYPE_INT, { .i64 = 4 }, 0, INT_MAX, FLAGS },
181 { "draw", "if false do not draw", OFFSET(d_expr), AV_OPT_TYPE_STRING, { .str = "1" }, .flags = FLAGS },
9b2c57be 182 { "alpha", "apply alpha while rendering", OFFSET(a_expr), AV_OPT_TYPE_STRING, { .str = "1" }, .flags = FLAGS },
8ec464c6
AK
183 { "fix_bounds", "if true, check and fix text coords to avoid clipping",
184 OFFSET(fix_bounds), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS },
185
186 /* FT_LOAD_* flags */
187 { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT | FT_LOAD_RENDER}, 0, INT_MAX, FLAGS, "ft_load_flags" },
188 { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
189 { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
190 { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
191 { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
192 { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
193 { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
194 { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
195 { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
196 { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
197 { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
198 { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
199 { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
200 { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
201 { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
202 { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
203 { NULL},
a5b64584
SS
204};
205
206static const char *drawtext_get_name(void *ctx)
207{
208 return "drawtext";
209}
210
211static const AVClass drawtext_class = {
97cfe1d8
DB
212 .class_name = "DrawTextContext",
213 .item_name = drawtext_get_name,
214 .option = drawtext_options,
a5b64584
SS
215};
216
217#undef __FTERRORS_H__
218#define FT_ERROR_START_LIST {
219#define FT_ERRORDEF(e, v, s) { (e), (s) },
220#define FT_ERROR_END_LIST { 0, NULL } };
221
fd9212f2 222static const struct ft_error {
a5b64584
SS
223 int err;
224 const char *err_msg;
85baef4f 225} ft_errors[] =
a5b64584
SS
226#include FT_ERRORS_H
227
228#define FT_ERRMSG(e) ft_errors[e].err_msg
229
58400ac1 230typedef struct Glyph {
a5b64584
SS
231 FT_Glyph *glyph;
232 uint32_t code;
233 FT_Bitmap bitmap; ///< array holding bitmaps of font
234 FT_BBox bbox;
235 int advance;
236 int bitmap_left;
237 int bitmap_top;
238} Glyph;
239
240static int glyph_cmp(void *key, const void *b)
241{
242 const Glyph *a = key, *bb = b;
243 int64_t diff = (int64_t)a->code - (int64_t)bb->code;
244 return diff > 0 ? 1 : diff < 0 ? -1 : 0;
245}
246
247/**
248 * Load glyphs corresponding to the UTF-32 codepoint code.
249 */
250static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
251{
d3735f7a 252 DrawTextContext *s = ctx->priv;
a5b64584
SS
253 Glyph *glyph;
254 struct AVTreeNode *node = NULL;
255 int ret;
256
d3735f7a
AK
257 /* load glyph into s->face->glyph */
258 if (FT_Load_Char(s->face, code, s->ft_load_flags))
a5b64584
SS
259 return AVERROR(EINVAL);
260
261 /* save glyph */
262 if (!(glyph = av_mallocz(sizeof(*glyph))) ||
263 !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
264 ret = AVERROR(ENOMEM);
265 goto error;
266 }
267 glyph->code = code;
268
d3735f7a 269 if (FT_Get_Glyph(s->face->glyph, glyph->glyph)) {
a5b64584
SS
270 ret = AVERROR(EINVAL);
271 goto error;
272 }
273
d3735f7a
AK
274 glyph->bitmap = s->face->glyph->bitmap;
275 glyph->bitmap_left = s->face->glyph->bitmap_left;
276 glyph->bitmap_top = s->face->glyph->bitmap_top;
277 glyph->advance = s->face->glyph->advance.x >> 6;
a5b64584
SS
278
279 /* measure text height to calculate text_height (or the maximum text height) */
280 FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
281
282 /* cache the newly created glyph */
b68aac7e 283 if (!(node = av_tree_node_alloc())) {
a5b64584
SS
284 ret = AVERROR(ENOMEM);
285 goto error;
286 }
d3735f7a 287 av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
a5b64584
SS
288
289 if (glyph_ptr)
290 *glyph_ptr = glyph;
291 return 0;
292
293error:
294 if (glyph)
295 av_freep(&glyph->glyph);
296 av_freep(&glyph);
297 av_freep(&node);
298 return ret;
299}
300
f1b239ec 301static int parse_font(AVFilterContext *ctx)
a5b64584 302{
d3735f7a 303 DrawTextContext *s = ctx->priv;
f1b239ec 304#if !CONFIG_LIBFONTCONFIG
d3735f7a 305 if (!s->fontfile) {
a5b64584
SS
306 av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
307 return AVERROR(EINVAL);
308 }
309
f1b239ec
LB
310 return 0;
311#else
312 FcPattern *pat, *best;
313 FcResult result = FcResultMatch;
314
315 FcBool fc_bool;
316 FcChar8* fc_string;
317 int err = AVERROR(ENOENT);
318
319 if (s->fontfile)
320 return 0;
321
322 if (!FcInit())
323 return AVERROR_UNKNOWN;
324
325 if (!(pat = FcPatternCreate()))
326 return AVERROR(ENOMEM);
327
328 FcPatternAddString(pat, FC_FAMILY, s->font);
329 FcPatternAddBool(pat, FC_OUTLINE, FcTrue);
330 FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
331
332 FcDefaultSubstitute(pat);
333
334 if (!FcConfigSubstitute(NULL, pat, FcMatchPattern)) {
335 FcPatternDestroy(pat);
336 return AVERROR(ENOMEM);
337 }
338
339 best = FcFontMatch(NULL, pat, &result);
340 FcPatternDestroy(pat);
341
342 if (!best || result == FcResultNoMatch) {
343 av_log(ctx, AV_LOG_ERROR,
344 "Cannot find a valid font for the family %s\n",
345 s->font);
346 goto fail;
347 }
348
349 if (FcPatternGetBool(best, FC_OUTLINE, 0, &fc_bool) != FcResultMatch ||
350 !fc_bool) {
351 av_log(ctx, AV_LOG_ERROR, "Outline not available for %s\n",
352 s->font);
353 goto fail;
354 }
355
356 if (FcPatternGetString(best, FC_FAMILY, 0, &fc_string) != FcResultMatch) {
357 av_log(ctx, AV_LOG_ERROR, "No matches for %s\n",
358 s->font);
359 goto fail;
360 }
361
362 if (FcPatternGetString(best, FC_FILE, 0, &fc_string) != FcResultMatch) {
363 av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
364 s->font);
365 goto fail;
366 }
367
368 s->fontfile = av_strdup(fc_string);
369 if (!s->fontfile)
370 err = AVERROR(ENOMEM);
371 else
372 err = 0;
373
374fail:
375 FcPatternDestroy(best);
376 return err;
377#endif
378}
379
380static av_cold int init(AVFilterContext *ctx)
381{
382 int err;
383 DrawTextContext *s = ctx->priv;
384 Glyph *glyph;
385
386 if ((err = parse_font(ctx)) < 0)
387 return err;
388
d3735f7a 389 if (s->textfile) {
a5b64584
SS
390 uint8_t *textbuf;
391 size_t textbuf_size;
392
d3735f7a 393 if (s->text) {
a5b64584
SS
394 av_log(ctx, AV_LOG_ERROR,
395 "Both text and text file provided. Please provide only one\n");
396 return AVERROR(EINVAL);
397 }
d3735f7a 398 if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
a5b64584
SS
399 av_log(ctx, AV_LOG_ERROR,
400 "The text file '%s' could not be read or is empty\n",
d3735f7a 401 s->textfile);
a5b64584
SS
402 return err;
403 }
404
f4017925
LB
405 if (textbuf_size > SIZE_MAX - 1 ||
406 !(s->text = av_malloc(textbuf_size + 1))) {
407 av_file_unmap(textbuf, textbuf_size);
a5b64584 408 return AVERROR(ENOMEM);
f4017925 409 }
d3735f7a
AK
410 memcpy(s->text, textbuf, textbuf_size);
411 s->text[textbuf_size] = 0;
a5b64584
SS
412 av_file_unmap(textbuf, textbuf_size);
413 }
414
d3735f7a 415 if (!s->text) {
a5b64584
SS
416 av_log(ctx, AV_LOG_ERROR,
417 "Either text or a valid file must be provided\n");
418 return AVERROR(EINVAL);
419 }
420
d3735f7a 421 if ((err = av_parse_color(s->fontcolor_rgba, s->fontcolor_string, -1, ctx))) {
a5b64584 422 av_log(ctx, AV_LOG_ERROR,
d3735f7a 423 "Invalid font color '%s'\n", s->fontcolor_string);
a5b64584
SS
424 return err;
425 }
426
d3735f7a 427 if ((err = av_parse_color(s->boxcolor_rgba, s->boxcolor_string, -1, ctx))) {
a5b64584 428 av_log(ctx, AV_LOG_ERROR,
d3735f7a 429 "Invalid box color '%s'\n", s->boxcolor_string);
a5b64584
SS
430 return err;
431 }
432
d3735f7a 433 if ((err = av_parse_color(s->shadowcolor_rgba, s->shadowcolor_string, -1, ctx))) {
c5420f10 434 av_log(ctx, AV_LOG_ERROR,
d3735f7a 435 "Invalid shadow color '%s'\n", s->shadowcolor_string);
c5420f10
MN
436 return err;
437 }
438
d3735f7a 439 if ((err = FT_Init_FreeType(&(s->library)))) {
a5b64584
SS
440 av_log(ctx, AV_LOG_ERROR,
441 "Could not load FreeType: %s\n", FT_ERRMSG(err));
442 return AVERROR(EINVAL);
443 }
444
445 /* load the face, and set up the encoding, which is by default UTF-8 */
d3735f7a 446 if ((err = FT_New_Face(s->library, s->fontfile, 0, &s->face))) {
a5b64584 447 av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
d3735f7a 448 s->fontfile, FT_ERRMSG(err));
a5b64584
SS
449 return AVERROR(EINVAL);
450 }
d3735f7a 451 if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
a5b64584 452 av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
d3735f7a 453 s->fontsize, FT_ERRMSG(err));
a5b64584
SS
454 return AVERROR(EINVAL);
455 }
456
d3735f7a 457 s->use_kerning = FT_HAS_KERNING(s->face);
a5b64584
SS
458
459 /* load the fallback glyph with code 0 */
460 load_glyph(ctx, NULL, 0);
461
462 /* set the tabsize in pixels */
463 if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
464 av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
465 return err;
466 }
d3735f7a 467 s->tabsize *= glyph->advance;
a5b64584 468
a5b64584
SS
469 return 0;
470}
471
472static int query_formats(AVFilterContext *ctx)
473{
716d413c
AK
474 static const enum AVPixelFormat pix_fmts[] = {
475 AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
476 AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
477 AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
478 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P,
479 AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P,
480 AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV440P,
481 AV_PIX_FMT_NONE
a5b64584
SS
482 };
483
b74a1da4 484 ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
a5b64584
SS
485 return 0;
486}
487
488static int glyph_enu_free(void *opaque, void *elem)
489{
490 av_free(elem);
491 return 0;
492}
493
494static av_cold void uninit(AVFilterContext *ctx)
495{
d3735f7a 496 DrawTextContext *s = ctx->priv;
a5b64584
SS
497 int i;
498
3fb29588
AK
499 av_expr_free(s->x_pexpr);
500 av_expr_free(s->y_pexpr);
501 av_expr_free(s->d_pexpr);
502 s->x_pexpr = s->y_pexpr = s->d_pexpr = NULL;
d3735f7a
AK
503 av_freep(&s->expanded_text);
504 av_freep(&s->positions);
505 av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
506 av_tree_destroy(s->glyphs);
507 s->glyphs = 0;
508 FT_Done_Face(s->face);
509 FT_Done_FreeType(s->library);
a5b64584
SS
510
511 for (i = 0; i < 4; i++) {
d3735f7a
AK
512 av_freep(&s->box_line[i]);
513 s->pixel_step[i] = 0;
a5b64584
SS
514 }
515
516}
517
ec11ff84
LB
518static inline int is_newline(uint32_t c)
519{
d4b63054 520 return c == '\n' || c == '\r' || c == '\f' || c == '\v';
ec11ff84
LB
521}
522
98c9ade9 523static int expand_strftime(DrawTextContext *s)
ec11ff84 524{
ec11ff84 525 struct tm ltime;
98c9ade9 526 time_t now = time(0);
d3735f7a
AK
527 uint8_t *buf = s->expanded_text;
528 int buf_size = s->expanded_text_size;
ec11ff84
LB
529
530 if (!buf)
98c9ade9 531 buf_size = 2 * strlen(s->text) + 1;
ec11ff84
LB
532
533 localtime_r(&now, &ltime);
534
535 while ((buf = av_realloc(buf, buf_size))) {
536 *buf = 1;
d3735f7a 537 if (strftime(buf, buf_size, s->text, &ltime) != 0 || *buf == 0)
ec11ff84
LB
538 break;
539 buf_size *= 2;
540 }
541
542 if (!buf)
543 return AVERROR(ENOMEM);
98c9ade9 544 s->expanded_text = buf;
d3735f7a 545 s->expanded_text_size = buf_size;
ec11ff84 546
98c9ade9
LB
547 return 0;
548}
549
550static int dtext_prepare_text(AVFilterContext *ctx)
551{
552 DrawTextContext *s = ctx->priv;
553 uint32_t code = 0, prev_code = 0;
554 int x = 0, y = 0, i = 0, ret;
555 int text_height, baseline;
556 char *text;
557 uint8_t *p;
558 int str_w = 0, len;
559 int y_min = 32000, y_max = -32000;
560 FT_Vector delta;
561 Glyph *glyph = NULL, *prev_glyph = NULL;
562 Glyph dummy = { 0 };
563 int width = ctx->inputs[0]->w;
564 int height = ctx->inputs[0]->h;
565
566 ret = expand_strftime(s);
567 if (ret < 0)
568 return ret;
569
570 text = s->expanded_text ? s->expanded_text : s->text;
571
d3735f7a
AK
572 if ((len = strlen(text)) > s->nb_positions) {
573 FT_Vector *p = av_realloc(s->positions,
574 len * sizeof(*s->positions));
ec11ff84 575 if (!p) {
d3735f7a
AK
576 av_freep(s->positions);
577 s->nb_positions = 0;
ec11ff84
LB
578 return AVERROR(ENOMEM);
579 } else {
d3735f7a
AK
580 s->positions = p;
581 s->nb_positions = len;
ec11ff84
LB
582 }
583 }
584
585 /* load and cache glyphs */
586 for (i = 0, p = text; *p; i++) {
587 GET_UTF8(code, *p++, continue;);
588
589 /* get glyph */
590 dummy.code = code;
d3735f7a 591 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
e7f0bc8c 592 if (!glyph) {
ec11ff84 593 ret = load_glyph(ctx, &glyph, code);
e7f0bc8c
AU
594 if (ret)
595 return ret;
596 }
ec11ff84
LB
597
598 y_min = FFMIN(glyph->bbox.yMin, y_min);
599 y_max = FFMAX(glyph->bbox.yMax, y_max);
600 }
601 text_height = y_max - y_min;
602 baseline = y_max;
603
604 /* compute and save position for each glyph */
605 glyph = NULL;
606 for (i = 0, p = text; *p; i++) {
607 GET_UTF8(code, *p++, continue;);
608
609 /* skip the \n in the sequence \r\n */
610 if (prev_code == '\r' && code == '\n')
611 continue;
612
613 prev_code = code;
614 if (is_newline(code)) {
d3735f7a 615 str_w = FFMAX(str_w, x - s->x);
ec11ff84
LB
616 y += text_height;
617 x = 0;
618 continue;
619 }
620
621 /* get glyph */
622 prev_glyph = glyph;
623 dummy.code = code;
d3735f7a 624 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
ec11ff84
LB
625
626 /* kerning */
d3735f7a
AK
627 if (s->use_kerning && prev_glyph && glyph->code) {
628 FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
ec11ff84
LB
629 ft_kerning_default, &delta);
630 x += delta.x >> 6;
631 }
632
633 if (x + glyph->bbox.xMax >= width) {
634 str_w = FFMAX(str_w, x);
635 y += text_height;
636 x = 0;
637 }
638
639 /* save position */
d3735f7a
AK
640 s->positions[i].x = x + glyph->bitmap_left;
641 s->positions[i].y = y - glyph->bitmap_top + baseline;
642 if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
ec11ff84
LB
643 else x += glyph->advance;
644 }
645
646 str_w = FFMIN(width - 1, FFMAX(str_w, x));
647 y = FFMIN(y + text_height, height - 1);
648
d3735f7a
AK
649 s->w = str_w;
650 s->var_values[VAR_TEXT_W] = s->var_values[VAR_TW] = s->w;
651 s->h = y;
652 s->var_values[VAR_TEXT_H] = s->var_values[VAR_TH] = s->h;
ec11ff84
LB
653
654 return 0;
655}
656
657
a5b64584
SS
658static int config_input(AVFilterLink *inlink)
659{
ec11ff84 660 AVFilterContext *ctx = inlink->dst;
d3735f7a 661 DrawTextContext *s = ctx->priv;
59ee9f78 662 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
a5b64584
SS
663 int ret;
664
d3735f7a
AK
665 s->hsub = pix_desc->log2_chroma_w;
666 s->vsub = pix_desc->log2_chroma_h;
a5b64584 667
d3735f7a
AK
668 s->var_values[VAR_E ] = M_E;
669 s->var_values[VAR_PHI] = M_PHI;
670 s->var_values[VAR_PI ] = M_PI;
2cf74eca 671
d3735f7a
AK
672 s->var_values[VAR_MAIN_W] =
673 s->var_values[VAR_MW] = ctx->inputs[0]->w;
674 s->var_values[VAR_MAIN_H] =
675 s->var_values[VAR_MH] = ctx->inputs[0]->h;
2cf74eca 676
d3735f7a
AK
677 s->var_values[VAR_X] = 0;
678 s->var_values[VAR_Y] = 0;
d3735f7a 679 s->var_values[VAR_T] = NAN;
2cf74eca 680
d3735f7a 681 av_lfg_init(&s->prng, av_get_random_seed());
2cf74eca 682
3fb29588
AK
683 av_expr_free(s->x_pexpr);
684 av_expr_free(s->y_pexpr);
685 av_expr_free(s->d_pexpr);
686 s->x_pexpr = s->y_pexpr = s->d_pexpr = NULL;
d3735f7a 687 if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
f5edfc9e 688 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
d3735f7a 689 (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
f5edfc9e 690 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
d3735f7a 691 (ret = av_expr_parse(&s->d_pexpr, s->d_expr, var_names,
9b2c57be
LB
692 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
693 (ret = av_expr_parse(&s->a_pexpr, s->a_expr, var_names,
f5edfc9e 694 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
2cf74eca
LB
695 return AVERROR(EINVAL);
696
a5b64584 697 if ((ret =
d3735f7a
AK
698 ff_fill_line_with_color(s->box_line, s->pixel_step,
699 inlink->w, s->boxcolor,
700 inlink->format, s->boxcolor_rgba,
701 &s->is_packed_rgb, s->rgba_map)) < 0)
a5b64584
SS
702 return ret;
703
d3735f7a
AK
704 if (!s->is_packed_rgb) {
705 uint8_t *rgba = s->fontcolor_rgba;
706 s->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
707 s->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
708 s->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
709 s->fontcolor[3] = rgba[3];
710 rgba = s->shadowcolor_rgba;
711 s->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
712 s->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
713 s->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
714 s->shadowcolor[3] = rgba[3];
a5b64584
SS
715 }
716
d3735f7a 717 s->draw = 1;
2cf74eca
LB
718
719 return dtext_prepare_text(ctx);
a5b64584
SS
720}
721
722#define GET_BITMAP_VAL(r, c) \
723 bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
724 (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
725 bitmap->buffer[(r) * bitmap->pitch + (c)]
726
7e350379
AK
727#define SET_PIXEL_YUV(frame, yuva_color, val, x, y, hsub, vsub) { \
728 luma_pos = ((x) ) + ((y) ) * frame->linesize[0]; \
9b2c57be 729 alpha = yuva_color[3] * alpha_mul * (val) * 129 / 255; \
7e350379 730 frame->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * frame->data[0][luma_pos] ) >> 23; \
a5b81c31 731 if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
7e350379
AK
732 chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[1]; \
733 chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[2]; \
734 frame->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * frame->data[1][chroma_pos1]) >> 23; \
735 frame->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * frame->data[2][chroma_pos2]) >> 23; \
a5b81c31 736 }\
a5b64584
SS
737}
738
7e350379 739static inline int draw_glyph_yuv(AVFrame *frame, FT_Bitmap *bitmap, unsigned int x,
a5b64584 740 unsigned int y, unsigned int width, unsigned int height,
9b2c57be
LB
741 const uint8_t yuva_color[4], int hsub, int vsub,
742 int alpha_mul)
a5b64584
SS
743{
744 int r, c, alpha;
745 unsigned int luma_pos, chroma_pos1, chroma_pos2;
965fdda0 746 uint8_t src_val;
a5b64584
SS
747
748 for (r = 0; r < bitmap->rows && r+y < height; r++) {
749 for (c = 0; c < bitmap->width && c+x < width; c++) {
a5b64584
SS
750 /* get intensity value in the glyph bitmap (source) */
751 src_val = GET_BITMAP_VAL(r, c);
752 if (!src_val)
753 continue;
754
7e350379 755 SET_PIXEL_YUV(frame, yuva_color, src_val, c+x, y+r, hsub, vsub);
a5b64584
SS
756 }
757 }
758
759 return 0;
760}
761
7e350379
AK
762#define SET_PIXEL_RGB(frame, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
763 p = frame->data[0] + (x) * pixel_step + ((y) * frame->linesize[0]); \
9b2c57be 764 alpha = rgba_color[3] * alpha_mul * (val) * 129 / 255; \
3953a880
MN
765 *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
766 *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
767 *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
a5b64584
SS
768}
769
7e350379 770static inline int draw_glyph_rgb(AVFrame *frame, FT_Bitmap *bitmap,
a5b64584
SS
771 unsigned int x, unsigned int y,
772 unsigned int width, unsigned int height, int pixel_step,
9b2c57be
LB
773 const uint8_t rgba_color[4], const uint8_t rgba_map[4],
774 int alpha_mul)
a5b64584
SS
775{
776 int r, c, alpha;
777 uint8_t *p;
965fdda0 778 uint8_t src_val;
a5b64584
SS
779
780 for (r = 0; r < bitmap->rows && r+y < height; r++) {
781 for (c = 0; c < bitmap->width && c+x < width; c++) {
a5b64584
SS
782 /* get intensity value in the glyph bitmap (source) */
783 src_val = GET_BITMAP_VAL(r, c);
784 if (!src_val)
785 continue;
786
7e350379 787 SET_PIXEL_RGB(frame, rgba_color, src_val, c+x, y+r, pixel_step,
a5b64584
SS
788 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
789 }
790 }
791
792 return 0;
793}
794
7e350379 795static inline void drawbox(AVFrame *frame, unsigned int x, unsigned int y,
a5b64584
SS
796 unsigned int width, unsigned int height,
797 uint8_t *line[4], int pixel_step[4], uint8_t color[4],
9b2c57be
LB
798 int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4],
799 int alpha_mul)
a5b64584
SS
800{
801 int i, j, alpha;
802
9b2c57be 803 if (color[3] != 0xFF || alpha_mul != 0xFF) {
a5b64584
SS
804 if (is_rgba_packed) {
805 uint8_t *p;
806 for (j = 0; j < height; j++)
807 for (i = 0; i < width; i++)
7e350379 808 SET_PIXEL_RGB(frame, color, 255, i+x, y+j, pixel_step[0],
a5b64584
SS
809 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
810 } else {
811 unsigned int luma_pos, chroma_pos1, chroma_pos2;
812 for (j = 0; j < height; j++)
813 for (i = 0; i < width; i++)
7e350379 814 SET_PIXEL_YUV(frame, color, 255, i+x, y+j, hsub, vsub);
a5b64584
SS
815 }
816 } else {
7e350379 817 ff_draw_rectangle(frame->data, frame->linesize,
a5b64584
SS
818 line, pixel_step, hsub, vsub,
819 x, y, width, height);
820 }
821}
822
d3735f7a 823static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
9b2c57be
LB
824 int width, int height,
825 const uint8_t rgbcolor[4], const uint8_t yuvcolor[4],
826 int x, int y)
e73127a4 827{
fe026ba9 828 char *text = s->expanded_text;
e73127a4
MN
829 uint32_t code = 0;
830 int i;
831 uint8_t *p;
832 Glyph *glyph = NULL;
833
834 for (i = 0, p = text; *p; i++) {
835 Glyph dummy = { 0 };
836 GET_UTF8(code, *p++, continue;);
837
838 /* skip new line chars, just go to new line */
839 if (code == '\n' || code == '\r' || code == '\t')
840 continue;
841
842 dummy.code = code;
8ddfa5ae 843 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
e73127a4
MN
844
845 if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
846 glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
847 return AVERROR(EINVAL);
848
d3735f7a 849 if (s->is_packed_rgb) {
7e350379 850 draw_glyph_rgb(frame, &glyph->bitmap,
d3735f7a 851 s->positions[i].x+x, s->positions[i].y+y, width, height,
9b2c57be 852 s->pixel_step[0], rgbcolor, s->rgba_map, s->alpha);
e73127a4 853 } else {
7e350379 854 draw_glyph_yuv(frame, &glyph->bitmap,
d3735f7a 855 s->positions[i].x+x, s->positions[i].y+y, width, height,
9b2c57be 856 yuvcolor, s->hsub, s->vsub, s->alpha);
e73127a4
MN
857 }
858 }
859
860 return 0;
861}
862
7e350379 863static int draw_text(AVFilterContext *ctx, AVFrame *frame,
a2fb4bcb
LB
864 int width, int height)
865{
d3735f7a 866 DrawTextContext *s = ctx->priv;
a2fb4bcb
LB
867 int ret;
868
a5b64584 869 /* draw box */
d3735f7a
AK
870 if (s->draw_box)
871 drawbox(frame, s->x, s->y, s->w, s->h,
872 s->box_line, s->pixel_step, s->boxcolor,
873 s->hsub, s->vsub, s->is_packed_rgb,
9b2c57be 874 s->rgba_map, s->alpha);
d3735f7a
AK
875
876 if (s->shadowx || s->shadowy) {
877 if ((ret = draw_glyphs(s, frame, width, height,
878 s->shadowcolor_rgba,
879 s->shadowcolor,
880 s->x + s->shadowx,
881 s->y + s->shadowy)) < 0)
c5420f10
MN
882 return ret;
883 }
884
d3735f7a
AK
885 if ((ret = draw_glyphs(s, frame, width, height,
886 s->fontcolor_rgba,
887 s->fontcolor,
888 s->x,
889 s->y)) < 0)
e73127a4 890 return ret;
a5b64584
SS
891
892 return 0;
893}
894
2cf74eca
LB
895static inline int normalize_double(int *n, double d)
896{
897 int ret = 0;
898
899 if (isnan(d)) {
900 ret = AVERROR(EINVAL);
901 } else if (d > INT_MAX || d < INT_MIN) {
902 *n = d > INT_MAX ? INT_MAX : INT_MIN;
903 ret = AVERROR(EINVAL);
904 } else
905 *n = round(d);
906
907 return ret;
908}
909
9b2c57be
LB
910static void update_alpha(DrawTextContext *s)
911{
912 double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
913
914 if (isnan(alpha))
915 return;
916
917 if (alpha >= 1.0)
918 s->alpha = 255;
919 else if (alpha <= 0)
920 s->alpha = 0;
921 else
922 s->alpha = 256 * alpha;
923}
924
7e350379 925static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
2cf74eca
LB
926{
927 AVFilterContext *ctx = inlink->dst;
d3735f7a 928 DrawTextContext *s = ctx->priv;
ebc8d974 929 int ret = 0;
2cf74eca 930
ebc8d974 931 if ((ret = dtext_prepare_text(ctx)) < 0) {
2cf74eca 932 av_log(ctx, AV_LOG_ERROR, "Can't draw text\n");
7e350379 933 av_frame_free(&frame);
ebc8d974 934 return ret;
2cf74eca
LB
935 }
936
d3735f7a 937 s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
565e4993 938 NAN : frame->pts * av_q2d(inlink->time_base);
d3735f7a
AK
939 s->var_values[VAR_X] =
940 av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
941 s->var_values[VAR_Y] =
942 av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
943 s->var_values[VAR_X] =
944 av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
945
946 s->draw = av_expr_eval(s->d_pexpr, s->var_values, &s->prng);
947
9b2c57be
LB
948 update_alpha(s);
949
d3735f7a
AK
950 normalize_double(&s->x, s->var_values[VAR_X]);
951 normalize_double(&s->y, s->var_values[VAR_Y]);
952
953 if (s->fix_bounds) {
954 if (s->x < 0) s->x = 0;
955 if (s->y < 0) s->y = 0;
956 if ((unsigned)s->x + (unsigned)s->w > inlink->w)
957 s->x = inlink->w - s->w;
958 if ((unsigned)s->y + (unsigned)s->h > inlink->h)
959 s->y = inlink->h - s->h;
e496c45d 960 }
2cf74eca 961
d3735f7a
AK
962 s->x &= ~((1 << s->hsub) - 1);
963 s->y &= ~((1 << s->vsub) - 1);
2cf74eca 964
1a3eb042 965 av_log(ctx, AV_LOG_TRACE, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
d3735f7a
AK
966 (int)s->var_values[VAR_N], s->var_values[VAR_T],
967 s->x, s->y, s->x+s->w, s->y+s->h);
2cf74eca 968
d3735f7a 969 if (s->draw)
7e350379 970 draw_text(inlink->dst, frame, frame->width, frame->height);
a5b64584 971
d3735f7a 972 s->var_values[VAR_N] += 1.0;
2cf74eca 973
565e4993 974 return ff_filter_frame(inlink->dst->outputs[0], frame);
a5b64584
SS
975}
976
568c70e7
MR
977static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
978 {
979 .name = "default",
980 .type = AVMEDIA_TYPE_VIDEO,
981 .get_video_buffer = ff_null_get_video_buffer,
565e4993 982 .filter_frame = filter_frame,
568c70e7 983 .config_props = config_input,
7e350379 984 .needs_writable = 1,
568c70e7
MR
985 },
986 { NULL }
987};
988
989static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
990 {
991 .name = "default",
992 .type = AVMEDIA_TYPE_VIDEO,
993 },
994 { NULL }
995};
996
cd43ca04 997AVFilter ff_vf_drawtext = {
a5b64584
SS
998 .name = "drawtext",
999 .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1000 .priv_size = sizeof(DrawTextContext),
8ec464c6 1001 .priv_class = &drawtext_class,
a5b64584
SS
1002 .init = init,
1003 .uninit = uninit,
1004 .query_formats = query_formats,
1005
568c70e7
MR
1006 .inputs = avfilter_vf_drawtext_inputs,
1007 .outputs = avfilter_vf_drawtext_outputs,
a5b64584 1008};