vf_drawtext.c
Go to the documentation of this file.
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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
29 #include <sys/time.h>
30 #include <time.h>
31 
32 #include "libavutil/colorspace.h"
33 #include "libavutil/file.h"
34 #include "libavutil/eval.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/random_seed.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/pixdesc.h"
40 #include "libavutil/tree.h"
41 #include "libavutil/lfg.h"
42 #include "avfilter.h"
43 #include "drawutils.h"
44 
45 #undef time
46 
47 #include <ft2build.h>
48 #include FT_FREETYPE_H
49 #include FT_GLYPH_H
50 
51 static const char *var_names[] = {
52  "E",
53  "PHI",
54  "PI",
55  "main_w", "W",
56  "main_h", "H",
57  "text_w", "w",
58  "text_h", "h",
59  "x",
60  "y",
61  "n",
62  "t",
63  NULL
64 };
65 
66 static const char *fun2_names[] = {
67  "rand",
68 };
69 
70 static double drand(void *opaque, double min, double max)
71 {
72  return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
73 }
74 
75 typedef double (*eval_func2)(void *, double a, double b);
76 
77 static const eval_func2 fun2[] = {
78  drand,
79  NULL
80 };
81 
82 enum var_name {
95 };
96 
97 typedef struct {
98  const AVClass *class;
99  uint8_t *fontfile;
100  uint8_t *text;
101  uint8_t *expanded_text;
104  FT_Vector *positions;
105  size_t nb_positions;
106  char *textfile;
107  int x, y;
108  int w, h;
109  int shadowx, shadowy;
110  unsigned int fontsize;
114  uint8_t fontcolor[4];
115  uint8_t boxcolor[4];
116  uint8_t shadowcolor[4];
117  uint8_t fontcolor_rgba[4];
118  uint8_t boxcolor_rgba[4];
119  uint8_t shadowcolor_rgba[4];
120 
121  short int draw_box;
123  int tabsize;
124 
125  FT_Library library;
126  FT_Face face;
127  struct AVTreeNode *glyphs;
128  int hsub, vsub;
130  int pixel_step[4];
131  uint8_t rgba_map[4];
132  uint8_t *box_line[4];
133  char *x_expr, *y_expr;
134  AVExpr *x_pexpr, *y_pexpr;
135  double var_values[VAR_VARS_NB];
136  char *d_expr;
138  int draw;
141 
142 #define OFFSET(x) offsetof(DrawTextContext, x)
143 
144 static const AVOption drawtext_options[]= {
145 {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
146 {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
147 {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
148 {"fontcolor","set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
149 {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
150 {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
151 {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
152 {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.dbl=16}, 1, 72 },
153 {"x", "set x", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
154 {"y", "set y", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
155 {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
156 {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
157 {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.dbl=4}, 0, INT_MAX },
158 {"draw", "if false do not draw", OFFSET(d_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX },
159 
160 /* FT_LOAD_* flags */
161 {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.dbl=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, 0, "ft_load_flags" },
162 {"default", "set default", 0, AV_OPT_TYPE_CONST, {FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
163 {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
164 {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
165 {"render", "set render", 0, AV_OPT_TYPE_CONST, {FT_LOAD_RENDER}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
166 {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
167 {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
168 {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
169 {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
170 {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
171 {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
172 {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
173 {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
174 {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
175 {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
176 {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
177 {NULL},
178 };
179 
180 static const char *drawtext_get_name(void *ctx)
181 {
182  return "drawtext";
183 }
184 
185 static const AVClass drawtext_class = {
186  "DrawTextContext",
188  drawtext_options
189 };
190 
191 #undef __FTERRORS_H__
192 #define FT_ERROR_START_LIST {
193 #define FT_ERRORDEF(e, v, s) { (e), (s) },
194 #define FT_ERROR_END_LIST { 0, NULL } };
195 
196 struct ft_error
197 {
198  int err;
199  const char *err_msg;
200 } static ft_errors[] =
201 #include FT_ERRORS_H
202 
203 #define FT_ERRMSG(e) ft_errors[e].err_msg
204 
205 typedef struct {
206  FT_Glyph *glyph;
207  uint32_t code;
208  FT_Bitmap bitmap;
209  FT_BBox bbox;
210  int advance;
211  int bitmap_left;
212  int bitmap_top;
213 } Glyph;
214 
215 static int glyph_cmp(void *key, const void *b)
216 {
217  const Glyph *a = key, *bb = b;
218  int64_t diff = (int64_t)a->code - (int64_t)bb->code;
219  return diff > 0 ? 1 : diff < 0 ? -1 : 0;
220 }
221 
225 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
226 {
227  DrawTextContext *dtext = ctx->priv;
228  Glyph *glyph;
229  struct AVTreeNode *node = NULL;
230  int ret;
231 
232  /* load glyph into dtext->face->glyph */
233  if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
234  return AVERROR(EINVAL);
235 
236  /* save glyph */
237  if (!(glyph = av_mallocz(sizeof(*glyph))) ||
238  !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
239  ret = AVERROR(ENOMEM);
240  goto error;
241  }
242  glyph->code = code;
243 
244  if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
245  ret = AVERROR(EINVAL);
246  goto error;
247  }
248 
249  glyph->bitmap = dtext->face->glyph->bitmap;
250  glyph->bitmap_left = dtext->face->glyph->bitmap_left;
251  glyph->bitmap_top = dtext->face->glyph->bitmap_top;
252  glyph->advance = dtext->face->glyph->advance.x >> 6;
253 
254  /* measure text height to calculate text_height (or the maximum text height) */
255  FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
256 
257  /* cache the newly created glyph */
258  if (!(node = av_mallocz(av_tree_node_size))) {
259  ret = AVERROR(ENOMEM);
260  goto error;
261  }
262  av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
263 
264  if (glyph_ptr)
265  *glyph_ptr = glyph;
266  return 0;
267 
268 error:
269  if (glyph)
270  av_freep(&glyph->glyph);
271  av_freep(&glyph);
272  av_freep(&node);
273  return ret;
274 }
275 
276 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
277 {
278  int err;
279  DrawTextContext *dtext = ctx->priv;
280  Glyph *glyph;
281 
282  dtext->class = &drawtext_class;
283  av_opt_set_defaults(dtext);
284  dtext->fontcolor_string = av_strdup("black");
285  dtext->boxcolor_string = av_strdup("white");
286  dtext->shadowcolor_string = av_strdup("black");
287 
288  if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
289  av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
290  return err;
291  }
292 
293  if (!dtext->fontfile) {
294  av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
295  return AVERROR(EINVAL);
296  }
297 
298  if (dtext->textfile) {
299  uint8_t *textbuf;
300  size_t textbuf_size;
301 
302  if (dtext->text) {
303  av_log(ctx, AV_LOG_ERROR,
304  "Both text and text file provided. Please provide only one\n");
305  return AVERROR(EINVAL);
306  }
307  if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
308  av_log(ctx, AV_LOG_ERROR,
309  "The text file '%s' could not be read or is empty\n",
310  dtext->textfile);
311  return err;
312  }
313 
314  if (!(dtext->text = av_malloc(textbuf_size+1)))
315  return AVERROR(ENOMEM);
316  memcpy(dtext->text, textbuf, textbuf_size);
317  dtext->text[textbuf_size] = 0;
318  av_file_unmap(textbuf, textbuf_size);
319  }
320 
321  if (!dtext->text) {
322  av_log(ctx, AV_LOG_ERROR,
323  "Either text or a valid file must be provided\n");
324  return AVERROR(EINVAL);
325  }
326 
327  if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
328  av_log(ctx, AV_LOG_ERROR,
329  "Invalid font color '%s'\n", dtext->fontcolor_string);
330  return err;
331  }
332 
333  if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
334  av_log(ctx, AV_LOG_ERROR,
335  "Invalid box color '%s'\n", dtext->boxcolor_string);
336  return err;
337  }
338 
339  if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
340  av_log(ctx, AV_LOG_ERROR,
341  "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
342  return err;
343  }
344 
345  if ((err = FT_Init_FreeType(&(dtext->library)))) {
346  av_log(ctx, AV_LOG_ERROR,
347  "Could not load FreeType: %s\n", FT_ERRMSG(err));
348  return AVERROR(EINVAL);
349  }
350 
351  /* load the face, and set up the encoding, which is by default UTF-8 */
352  if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
353  av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
354  dtext->fontfile, FT_ERRMSG(err));
355  return AVERROR(EINVAL);
356  }
357  if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
358  av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
359  dtext->fontsize, FT_ERRMSG(err));
360  return AVERROR(EINVAL);
361  }
362 
363  dtext->use_kerning = FT_HAS_KERNING(dtext->face);
364 
365  /* load the fallback glyph with code 0 */
366  load_glyph(ctx, NULL, 0);
367 
368  /* set the tabsize in pixels */
369  if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
370  av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
371  return err;
372  }
373  dtext->tabsize *= glyph->advance;
374 
375 #if !HAVE_LOCALTIME_R
376  av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
377 #endif
378 
379  return 0;
380 }
381 
383 {
384  static const enum PixelFormat pix_fmts[] = {
392  };
393 
395  return 0;
396 }
397 
398 static int glyph_enu_free(void *opaque, void *elem)
399 {
400  av_free(elem);
401  return 0;
402 }
403 
404 static av_cold void uninit(AVFilterContext *ctx)
405 {
406  DrawTextContext *dtext = ctx->priv;
407  int i;
408 
409  av_freep(&dtext->fontfile);
410  av_freep(&dtext->text);
411  av_freep(&dtext->expanded_text);
412  av_freep(&dtext->fontcolor_string);
413  av_freep(&dtext->boxcolor_string);
414  av_freep(&dtext->positions);
415  av_freep(&dtext->shadowcolor_string);
417  av_tree_destroy(dtext->glyphs);
418  dtext->glyphs = 0;
419  FT_Done_Face(dtext->face);
420  FT_Done_FreeType(dtext->library);
421 
422  for (i = 0; i < 4; i++) {
423  av_freep(&dtext->box_line[i]);
424  dtext->pixel_step[i] = 0;
425  }
426 
427 }
428 
429 static inline int is_newline(uint32_t c)
430 {
431  return c == '\n' || c == '\r' || c == '\f' || c == '\v';
432 }
433 
435 {
436  DrawTextContext *dtext = ctx->priv;
437  uint32_t code = 0, prev_code = 0;
438  int x = 0, y = 0, i = 0, ret;
439  int text_height, baseline;
440  char *text = dtext->text;
441  uint8_t *p;
442  int str_w = 0, len;
443  int y_min = 32000, y_max = -32000;
444  FT_Vector delta;
445  Glyph *glyph = NULL, *prev_glyph = NULL;
446  Glyph dummy = { 0 };
447  int width = ctx->inputs[0]->w;
448  int height = ctx->inputs[0]->h;
449 
450 #if HAVE_LOCALTIME_R
451  time_t now = time(0);
452  struct tm ltime;
453  uint8_t *buf = dtext->expanded_text;
454  int buf_size = dtext->expanded_text_size;
455 
456  if (!buf)
457  buf_size = 2*strlen(dtext->text)+1;
458 
459  localtime_r(&now, &ltime);
460 
461  while ((buf = av_realloc(buf, buf_size))) {
462  *buf = 1;
463  if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
464  break;
465  buf_size *= 2;
466  }
467 
468  if (!buf)
469  return AVERROR(ENOMEM);
470  text = dtext->expanded_text = buf;
471  dtext->expanded_text_size = buf_size;
472 #endif
473 
474  if ((len = strlen(text)) > dtext->nb_positions) {
475  FT_Vector *p = av_realloc(dtext->positions,
476  len * sizeof(*dtext->positions));
477  if (!p) {
478  av_freep(dtext->positions);
479  dtext->nb_positions = 0;
480  return AVERROR(ENOMEM);
481  } else {
482  dtext->positions = p;
483  dtext->nb_positions = len;
484  }
485  }
486 
487  /* load and cache glyphs */
488  for (i = 0, p = text; *p; i++) {
489  GET_UTF8(code, *p++, continue;);
490 
491  /* get glyph */
492  dummy.code = code;
493  glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
494  if (!glyph)
495  ret = load_glyph(ctx, &glyph, code);
496  if (ret) return ret;
497 
498  y_min = FFMIN(glyph->bbox.yMin, y_min);
499  y_max = FFMAX(glyph->bbox.yMax, y_max);
500  }
501  text_height = y_max - y_min;
502  baseline = y_max;
503 
504  /* compute and save position for each glyph */
505  glyph = NULL;
506  for (i = 0, p = text; *p; i++) {
507  GET_UTF8(code, *p++, continue;);
508 
509  /* skip the \n in the sequence \r\n */
510  if (prev_code == '\r' && code == '\n')
511  continue;
512 
513  prev_code = code;
514  if (is_newline(code)) {
515  str_w = FFMAX(str_w, x - dtext->x);
516  y += text_height;
517  x = 0;
518  continue;
519  }
520 
521  /* get glyph */
522  prev_glyph = glyph;
523  dummy.code = code;
524  glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
525 
526  /* kerning */
527  if (dtext->use_kerning && prev_glyph && glyph->code) {
528  FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
529  ft_kerning_default, &delta);
530  x += delta.x >> 6;
531  }
532 
533  if (x + glyph->bbox.xMax >= width) {
534  str_w = FFMAX(str_w, x);
535  y += text_height;
536  x = 0;
537  }
538 
539  /* save position */
540  dtext->positions[i].x = x + glyph->bitmap_left;
541  dtext->positions[i].y = y - glyph->bitmap_top + baseline;
542  if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
543  else x += glyph->advance;
544  }
545 
546  str_w = FFMIN(width - 1, FFMAX(str_w, x));
547  y = FFMIN(y + text_height, height - 1);
548 
549  dtext->w = str_w;
550  dtext->h = y;
551 
552  return 0;
553 }
554 
555 
556 static int config_input(AVFilterLink *inlink)
557 {
558  AVFilterContext *ctx = inlink->dst;
559  DrawTextContext *dtext = ctx->priv;
560  const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
561  int ret;
562 
563  dtext->hsub = pix_desc->log2_chroma_w;
564  dtext->vsub = pix_desc->log2_chroma_h;
565 
566  dtext->var_values[VAR_E ] = M_E;
567  dtext->var_values[VAR_PHI] = M_PHI;
568  dtext->var_values[VAR_PI ] = M_PI;
569 
570  dtext->var_values[VAR_MAIN_W] =
571  dtext->var_values[VAR_MW] = ctx->inputs[0]->w;
572  dtext->var_values[VAR_MAIN_H] =
573  dtext->var_values[VAR_MH] = ctx->inputs[0]->h;
574 
575  dtext->var_values[VAR_X] = 0;
576  dtext->var_values[VAR_Y] = 0;
577  dtext->var_values[VAR_N] = 0;
578  dtext->var_values[VAR_T] = NAN;
579 
580  av_lfg_init(&dtext->prng, av_get_random_seed());
581 
582  if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
583  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
584  (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
585  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
586  (ret = av_expr_parse(&dtext->d_pexpr, dtext->d_expr, var_names,
587  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
588  return AVERROR(EINVAL);
589 
590  if ((ret =
592  inlink->w, dtext->boxcolor,
593  inlink->format, dtext->boxcolor_rgba,
594  &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
595  return ret;
596 
597  if (!dtext->is_packed_rgb) {
598  uint8_t *rgba = dtext->fontcolor_rgba;
599  dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
600  dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
601  dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
602  dtext->fontcolor[3] = rgba[3];
603  rgba = dtext->shadowcolor_rgba;
604  dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
605  dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
606  dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
607  dtext->shadowcolor[3] = rgba[3];
608  }
609 
610  dtext->draw = 1;
611 
612  return dtext_prepare_text(ctx);
613 }
614 
615 #define GET_BITMAP_VAL(r, c) \
616  bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
617  (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
618  bitmap->buffer[(r) * bitmap->pitch + (c)]
619 
620 #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) { \
621  luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
622  alpha = yuva_color[3] * (val) * 129; \
623  picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos] ) >> 23; \
624  if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
625  chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
626  chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
627  picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
628  picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
629  }\
630 }
631 
632 static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
633  unsigned int y, unsigned int width, unsigned int height,
634  const uint8_t yuva_color[4], int hsub, int vsub)
635 {
636  int r, c, alpha;
637  unsigned int luma_pos, chroma_pos1, chroma_pos2;
638  uint8_t src_val;
639 
640  for (r = 0; r < bitmap->rows && r+y < height; r++) {
641  for (c = 0; c < bitmap->width && c+x < width; c++) {
642  /* get intensity value in the glyph bitmap (source) */
643  src_val = GET_BITMAP_VAL(r, c);
644  if (!src_val)
645  continue;
646 
647  SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
648  }
649  }
650 
651  return 0;
652 }
653 
654 #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
655  p = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
656  alpha = rgba_color[3] * (val) * 129; \
657  *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
658  *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
659  *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
660 }
661 
662 static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
663  unsigned int x, unsigned int y,
664  unsigned int width, unsigned int height, int pixel_step,
665  const uint8_t rgba_color[4], const uint8_t rgba_map[4])
666 {
667  int r, c, alpha;
668  uint8_t *p;
669  uint8_t src_val;
670 
671  for (r = 0; r < bitmap->rows && r+y < height; r++) {
672  for (c = 0; c < bitmap->width && c+x < width; c++) {
673  /* get intensity value in the glyph bitmap (source) */
674  src_val = GET_BITMAP_VAL(r, c);
675  if (!src_val)
676  continue;
677 
678  SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
679  rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
680  }
681  }
682 
683  return 0;
684 }
685 
686 static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
687  unsigned int width, unsigned int height,
688  uint8_t *line[4], int pixel_step[4], uint8_t color[4],
689  int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
690 {
691  int i, j, alpha;
692 
693  if (color[3] != 0xFF) {
694  if (is_rgba_packed) {
695  uint8_t *p;
696  for (j = 0; j < height; j++)
697  for (i = 0; i < width; i++)
698  SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
699  rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
700  } else {
701  unsigned int luma_pos, chroma_pos1, chroma_pos2;
702  for (j = 0; j < height; j++)
703  for (i = 0; i < width; i++)
704  SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
705  }
706  } else {
707  ff_draw_rectangle(picref->data, picref->linesize,
708  line, pixel_step, hsub, vsub,
709  x, y, width, height);
710  }
711 }
712 
713 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
714  int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
715 {
716  char *text = HAVE_LOCALTIME_R ? dtext->expanded_text : dtext->text;
717  uint32_t code = 0;
718  int i;
719  uint8_t *p;
720  Glyph *glyph = NULL;
721 
722  for (i = 0, p = text; *p; i++) {
723  Glyph dummy = { 0 };
724  GET_UTF8(code, *p++, continue;);
725 
726  /* skip new line chars, just go to new line */
727  if (code == '\n' || code == '\r' || code == '\t')
728  continue;
729 
730  dummy.code = code;
731  glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
732 
733  if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
734  glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
735  return AVERROR(EINVAL);
736 
737  if (dtext->is_packed_rgb) {
738  draw_glyph_rgb(picref, &glyph->bitmap,
739  dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
740  dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
741  } else {
742  draw_glyph_yuv(picref, &glyph->bitmap,
743  dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
744  yuvcolor, dtext->hsub, dtext->vsub);
745  }
746  }
747 
748  return 0;
749 }
750 
751 static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
752  int width, int height)
753 {
754  DrawTextContext *dtext = ctx->priv;
755  int ret;
756 
757  /* draw box */
758  if (dtext->draw_box)
759  drawbox(picref, dtext->x, dtext->y, dtext->w, dtext->h,
760  dtext->box_line, dtext->pixel_step, dtext->boxcolor,
761  dtext->hsub, dtext->vsub, dtext->is_packed_rgb,
762  dtext->rgba_map);
763 
764  if (dtext->shadowx || dtext->shadowy) {
765  if ((ret = draw_glyphs(dtext, picref, width, height,
766  dtext->shadowcolor_rgba,
767  dtext->shadowcolor,
768  dtext->x + dtext->shadowx,
769  dtext->y + dtext->shadowy)) < 0)
770  return ret;
771  }
772 
773  if ((ret = draw_glyphs(dtext, picref, width, height,
774  dtext->fontcolor_rgba,
775  dtext->fontcolor,
776  dtext->x,
777  dtext->y)) < 0)
778  return ret;
779 
780  return 0;
781 }
782 
783 static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
784 
785 static inline int normalize_double(int *n, double d)
786 {
787  int ret = 0;
788 
789  if (isnan(d)) {
790  ret = AVERROR(EINVAL);
791  } else if (d > INT_MAX || d < INT_MIN) {
792  *n = d > INT_MAX ? INT_MAX : INT_MIN;
793  ret = AVERROR(EINVAL);
794  } else
795  *n = round(d);
796 
797  return ret;
798 }
799 
800 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
801 {
802  AVFilterContext *ctx = inlink->dst;
803  DrawTextContext *dtext = ctx->priv;
804  int fail = 0;
805 
806  if (dtext_prepare_text(ctx) < 0) {
807  av_log(ctx, AV_LOG_ERROR, "Can't draw text\n");
808  fail = 1;
809  }
810 
811  dtext->var_values[VAR_T] = inpicref->pts == AV_NOPTS_VALUE ?
812  NAN : inpicref->pts * av_q2d(inlink->time_base);
813  dtext->var_values[VAR_X] =
814  av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
815  dtext->var_values[VAR_Y] =
816  av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
817  dtext->var_values[VAR_X] =
818  av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
819 
820  dtext->draw = fail ? 0 :
821  av_expr_eval(dtext->d_pexpr, dtext->var_values, &dtext->prng);
822 
823  normalize_double(&dtext->x, dtext->var_values[VAR_X]);
824  normalize_double(&dtext->y, dtext->var_values[VAR_Y]);
825 
826  if (dtext->x < 0) dtext->x = 0;
827  if (dtext->y < 0) dtext->y = 0;
828  if ((unsigned)dtext->x + (unsigned)dtext->w > inlink->w)
829  dtext->x = inlink->w - dtext->w;
830  if ((unsigned)dtext->y + (unsigned)dtext->h > inlink->h)
831  dtext->y = inlink->h - dtext->h;
832 
833  dtext->x &= ~((1 << dtext->hsub) - 1);
834  dtext->y &= ~((1 << dtext->vsub) - 1);
835 
836  av_dlog(ctx, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
837  (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
838  dtext->x, dtext->y, dtext->x+dtext->w, dtext->y+dtext->h);
839 
840  avfilter_start_frame(inlink->dst->outputs[0], inpicref);
841 }
842 
843 static void end_frame(AVFilterLink *inlink)
844 {
845  AVFilterLink *outlink = inlink->dst->outputs[0];
846  AVFilterBufferRef *picref = inlink->cur_buf;
847  DrawTextContext *dtext = inlink->dst->priv;
848 
849  if (dtext->draw)
850  draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
851 
852  dtext->var_values[VAR_N] += 1.0;
853 
854  avfilter_draw_slice(outlink, 0, picref->video->h, 1);
855  avfilter_end_frame(outlink);
856 }
857 
859  .name = "drawtext",
860  .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
861  .priv_size = sizeof(DrawTextContext),
862  .init = init,
863  .uninit = uninit,
865 
866  .inputs = (AVFilterPad[]) {{ .name = "default",
867  .type = AVMEDIA_TYPE_VIDEO,
868  .get_video_buffer = avfilter_null_get_video_buffer,
869  .start_frame = start_frame,
870  .draw_slice = null_draw_slice,
871  .end_frame = end_frame,
872  .config_props = config_input,
873  .min_perms = AV_PERM_WRITE |
874  AV_PERM_READ,
875  .rej_perms = AV_PERM_PRESERVE },
876  { .name = NULL}},
877  .outputs = (AVFilterPad[]) {{ .name = "default",
878  .type = AVMEDIA_TYPE_VIDEO, },
879  { .name = NULL}},
880 };