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>
6 * This file is part of FFmpeg.
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.
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.
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
25 * drawtext filter, based on the original FFmpeg vhook/drawtext.c
26 * filter by Gustavo Sverzut Barbieri
32 #include "libavutil/colorspace.h"
33 #include "libavutil/eval.h"
34 #include "libavutil/file.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/pixdesc.h"
38 #include "libavutil/tree.h"
40 #include "drawutils.h"
45 #include <freetype/config/ftheader.h>
46 #include FT_FREETYPE_H
49 static const char *var_names[] = {
53 "w", ///< width of the input video
54 "h", ///< height of the input video
55 "tw", "text_w", ///< width of the rendered text
56 "th", "text_h", ///< height of the rendered text
57 "max_glyph_w", ///< max glyph width
58 "max_glyph_h", ///< max glyph height
59 "max_glyph_a", "ascent", ///< max glyph ascent
60 "max_glyph_d", "descent", ///< min glyph descent
61 "line_h", "lh", ///< line height, same as max_glyph_h
68 "n", ///< number of frame
69 "t", ///< timestamp expressed in seconds
83 VAR_MAX_GLYPH_A, VAR_ASCENT,
84 VAR_MAX_GLYPH_D, VAR_DESCENT,
99 uint8_t *fontfile; ///< font to be used
100 uint8_t *text; ///< text to be drawn
101 uint8_t *expanded_text; ///< used to contain the strftime()-expanded text
102 size_t expanded_text_size; ///< size in bytes of the expanded_text buffer
103 int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
104 FT_Vector *positions; ///< positions for each element in the text
105 size_t nb_positions; ///< number of elements of positions array
106 char *textfile; ///< file with text to be drawn
107 int x; ///< x position to start drawing text
108 int y; ///< y position to start drawing text
109 char *x_expr; ///< expression for x position
110 char *y_expr; ///< expression for y position
111 AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
112 int max_glyph_w; ///< max glyph width
113 int max_glyph_h; ///< max glyph heigth
114 int shadowx, shadowy;
115 unsigned int fontsize; ///< font size to use
116 char *fontcolor_string; ///< font color as string
117 char *boxcolor_string; ///< box color as string
118 char *shadowcolor_string; ///< shadow color as string
119 uint8_t fontcolor[4]; ///< foreground color
120 uint8_t boxcolor[4]; ///< background color
121 uint8_t shadowcolor[4]; ///< shadow color
122 uint8_t fontcolor_rgba[4]; ///< foreground color in RGBA
123 uint8_t boxcolor_rgba[4]; ///< background color in RGBA
124 uint8_t shadowcolor_rgba[4]; ///< shadow color in RGBA
126 short int draw_box; ///< draw box around text - true or false
127 int use_kerning; ///< font kerning is used - true/false
128 int tabsize; ///< tab size
130 FT_Library library; ///< freetype font library handle
131 FT_Face face; ///< freetype font face handle
132 struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
133 int hsub, vsub; ///< chroma subsampling values
135 int pixel_step[4]; ///< distance in bytes between the component of each pixel
136 uint8_t rgba_map[4]; ///< map RGBA offsets to the positions in the packed RGBA format
137 uint8_t *box_line[4]; ///< line used for filling the box background
138 int64_t basetime; ///< base pts time in the real world for display
139 double var_values[VAR_VARS_NB];
142 #define OFFSET(x) offsetof(DrawTextContext, x)
144 static const AVOption drawtext_options[]= {
145 {"fontfile", "set font file", OFFSET(fontfile), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
146 {"text", "set text", OFFSET(text), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
147 {"textfile", "set text file", OFFSET(textfile), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
148 {"fontcolor", "set foreground color", OFFSET(fontcolor_string), FF_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
149 {"boxcolor", "set box color", OFFSET(boxcolor_string), FF_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX },
150 {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), FF_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
151 {"box", "set box", OFFSET(draw_box), FF_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
152 {"fontsize", "set font size", OFFSET(fontsize), FF_OPT_TYPE_INT, {.dbl=16}, 1, INT_MAX },
153 {"x", "set x expression", OFFSET(x_expr), FF_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
154 {"y", "set y expression", OFFSET(y_expr), FF_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
155 {"shadowx", "set x", OFFSET(shadowx), FF_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
156 {"shadowy", "set y", OFFSET(shadowy), FF_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
157 {"tabsize", "set tab size", OFFSET(tabsize), FF_OPT_TYPE_INT, {.dbl=4}, 0, INT_MAX },
158 {"basetime", "set base time", OFFSET(basetime), FF_OPT_TYPE_INT64, {.dbl=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX },
161 /* FT_LOAD_* flags */
162 {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), FF_OPT_TYPE_FLAGS, {.dbl=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, 0, "ft_load_flags" },
163 {"default", "set default", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
164 {"no_scale", "set no_scale", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
165 {"no_hinting", "set no_hinting", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
166 {"render", "set render", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_RENDER}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
167 {"no_bitmap", "set no_bitmap", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
168 {"vertical_layout", "set vertical_layout", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
169 {"force_autohint", "set force_autohint", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
170 {"crop_bitmap", "set crop_bitmap", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
171 {"pedantic", "set pedantic", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
172 {"ignore_global_advance_width", "set ignore_global_advance_width", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
173 {"no_recurse", "set no_recurse", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
174 {"ignore_transform", "set ignore_transform", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
175 {"monochrome", "set monochrome", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
176 {"linear_design", "set linear_design", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
177 {"no_autohint", "set no_autohint", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
181 static const char *drawtext_get_name(void *ctx)
186 static const AVClass drawtext_class = {
192 #undef __FTERRORS_H__
193 #define FT_ERROR_START_LIST {
194 #define FT_ERRORDEF(e, v, s) { (e), (s) },
195 #define FT_ERROR_END_LIST { 0, NULL } };
201 } static ft_errors[] =
204 #define FT_ERRMSG(e) ft_errors[e].err_msg
209 FT_Bitmap bitmap; ///< array holding bitmaps of font
216 static int glyph_cmp(void *key, const void *b)
218 const Glyph *a = key, *bb = b;
219 int64_t diff = (int64_t)a->code - (int64_t)bb->code;
220 return diff > 0 ? 1 : diff < 0 ? -1 : 0;
224 * Load glyphs corresponding to the UTF-32 codepoint code.
226 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
228 DrawTextContext *dtext = ctx->priv;
230 struct AVTreeNode *node = NULL;
233 /* load glyph into dtext->face->glyph */
234 if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
235 return AVERROR(EINVAL);
238 if (!(glyph = av_mallocz(sizeof(*glyph))) ||
239 !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
240 ret = AVERROR(ENOMEM);
245 if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
246 ret = AVERROR(EINVAL);
250 glyph->bitmap = dtext->face->glyph->bitmap;
251 glyph->bitmap_left = dtext->face->glyph->bitmap_left;
252 glyph->bitmap_top = dtext->face->glyph->bitmap_top;
253 glyph->advance = dtext->face->glyph->advance.x >> 6;
255 /* measure text height to calculate text_height (or the maximum text height) */
256 FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
258 /* cache the newly created glyph */
259 if (!(node = av_mallocz(av_tree_node_size))) {
260 ret = AVERROR(ENOMEM);
263 av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
271 av_freep(&glyph->glyph);
277 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
280 DrawTextContext *dtext = ctx->priv;
283 dtext->class = &drawtext_class;
284 av_opt_set_defaults(dtext);
286 if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
287 av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
291 if (!dtext->fontfile) {
292 av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
293 return AVERROR(EINVAL);
296 if (dtext->textfile) {
301 av_log(ctx, AV_LOG_ERROR,
302 "Both text and text file provided. Please provide only one\n");
303 return AVERROR(EINVAL);
305 if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
306 av_log(ctx, AV_LOG_ERROR,
307 "The text file '%s' could not be read or is empty\n",
312 if (!(dtext->text = av_malloc(textbuf_size+1)))
313 return AVERROR(ENOMEM);
314 memcpy(dtext->text, textbuf, textbuf_size);
315 dtext->text[textbuf_size] = 0;
316 av_file_unmap(textbuf, textbuf_size);
320 av_log(ctx, AV_LOG_ERROR,
321 "Either text or a valid file must be provided\n");
322 return AVERROR(EINVAL);
325 if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
326 av_log(ctx, AV_LOG_ERROR,
327 "Invalid font color '%s'\n", dtext->fontcolor_string);
331 if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
332 av_log(ctx, AV_LOG_ERROR,
333 "Invalid box color '%s'\n", dtext->boxcolor_string);
337 if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
338 av_log(ctx, AV_LOG_ERROR,
339 "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
343 if ((err = FT_Init_FreeType(&(dtext->library)))) {
344 av_log(ctx, AV_LOG_ERROR,
345 "Could not load FreeType: %s\n", FT_ERRMSG(err));
346 return AVERROR(EINVAL);
349 /* load the face, and set up the encoding, which is by default UTF-8 */
350 if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
351 av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
352 dtext->fontfile, FT_ERRMSG(err));
353 return AVERROR(EINVAL);
355 if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
356 av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
357 dtext->fontsize, FT_ERRMSG(err));
358 return AVERROR(EINVAL);
361 dtext->use_kerning = FT_HAS_KERNING(dtext->face);
363 /* load the fallback glyph with code 0 */
364 load_glyph(ctx, NULL, 0);
366 /* set the tabsize in pixels */
367 if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
368 av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
371 dtext->tabsize *= glyph->advance;
376 static int query_formats(AVFilterContext *ctx)
378 static const enum PixelFormat pix_fmts[] = {
379 PIX_FMT_ARGB, PIX_FMT_RGBA,
380 PIX_FMT_ABGR, PIX_FMT_BGRA,
381 PIX_FMT_RGB24, PIX_FMT_BGR24,
382 PIX_FMT_YUV420P, PIX_FMT_YUV444P,
383 PIX_FMT_YUV422P, PIX_FMT_YUV411P,
384 PIX_FMT_YUV410P, PIX_FMT_YUV440P,
388 avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
392 static int glyph_enu_free(void *opaque, void *elem)
398 static av_cold void uninit(AVFilterContext *ctx)
400 DrawTextContext *dtext = ctx->priv;
403 av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
404 av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
406 av_freep(&dtext->boxcolor_string);
407 av_freep(&dtext->expanded_text);
408 av_freep(&dtext->fontcolor_string);
409 av_freep(&dtext->fontfile);
410 av_freep(&dtext->shadowcolor_string);
411 av_freep(&dtext->text);
412 av_freep(&dtext->x_expr);
413 av_freep(&dtext->y_expr);
415 av_freep(&dtext->positions);
416 dtext->nb_positions = 0;
418 av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
419 av_tree_destroy(dtext->glyphs);
420 dtext->glyphs = NULL;
422 FT_Done_Face(dtext->face);
423 FT_Done_FreeType(dtext->library);
425 for (i = 0; i < 4; i++) {
426 av_freep(&dtext->box_line[i]);
427 dtext->pixel_step[i] = 0;
431 static int config_input(AVFilterLink *inlink)
433 AVFilterContext *ctx = inlink->dst;
434 DrawTextContext *dtext = inlink->dst->priv;
435 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
438 dtext->hsub = pix_desc->log2_chroma_w;
439 dtext->vsub = pix_desc->log2_chroma_h;
442 ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
443 inlink->w, dtext->boxcolor,
444 inlink->format, dtext->boxcolor_rgba,
445 &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
448 if (!dtext->is_packed_rgb) {
449 uint8_t *rgba = dtext->fontcolor_rgba;
450 dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
451 dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
452 dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
453 dtext->fontcolor[3] = rgba[3];
454 rgba = dtext->shadowcolor_rgba;
455 dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
456 dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
457 dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
458 dtext->shadowcolor[3] = rgba[3];
461 dtext->var_values[VAR_E] = M_E;
462 dtext->var_values[VAR_PHI] = M_PHI;
463 dtext->var_values[VAR_PI] = M_PI;
464 dtext->var_values[VAR_W] = inlink->w;
465 dtext->var_values[VAR_H] = inlink->h;
466 dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
467 dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
468 dtext->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
469 dtext->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
470 dtext->var_values[VAR_X] = NAN;
471 dtext->var_values[VAR_Y] = NAN;
472 dtext->var_values[VAR_N] = 0;
473 dtext->var_values[VAR_T] = NAN;
475 if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
476 NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
477 (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
478 NULL, NULL, NULL, NULL, 0, ctx)) < 0)
479 return AVERROR(EINVAL);
484 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
486 if(!strcmp(cmd, "reinit")){
489 if((ret=init(ctx, arg, NULL)) < 0)
491 return config_input(ctx->inputs[0]);
494 return AVERROR(ENOSYS);
497 #define GET_BITMAP_VAL(r, c) \
498 bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
499 (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
500 bitmap->buffer[(r) * bitmap->pitch + (c)]
502 #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) { \
503 luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
504 alpha = yuva_color[3] * (val) * 129; \
505 picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos] ) >> 23; \
506 if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
507 chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
508 chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
509 picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
510 picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
514 static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
515 int x, int y, int width, int height,
516 const uint8_t yuva_color[4], int hsub, int vsub)
519 unsigned int luma_pos, chroma_pos1, chroma_pos2;
522 for (r = 0; r < bitmap->rows && r+y < height; r++) {
523 for (c = 0; c < bitmap->width && c+x < width; c++) {
524 if (c+x < 0 || r+y < 0)
527 /* get intensity value in the glyph bitmap (source) */
528 src_val = GET_BITMAP_VAL(r, c);
532 SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
539 #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
540 p = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
541 alpha = rgba_color[3] * (val) * 129; \
542 *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
543 *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
544 *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
547 static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
548 int x, int y, int width, int height, int pixel_step,
549 const uint8_t rgba_color[4], const uint8_t rgba_map[4])
555 for (r = 0; r < bitmap->rows && r+y < height; r++) {
556 for (c = 0; c < bitmap->width && c+x < width; c++) {
557 if (c+x < 0 || r+y < 0)
559 /* get intensity value in the glyph bitmap (source) */
560 src_val = GET_BITMAP_VAL(r, c);
564 SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
565 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
572 static inline void drawbox(AVFilterBufferRef *picref, int x, int y,
573 int width, int height,
574 uint8_t *line[4], int pixel_step[4], uint8_t color[4],
575 int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
579 if (color[3] != 0xFF) {
580 if (is_rgba_packed) {
582 for (j = 0; j < height; j++)
583 for (i = 0; i < width; i++)
584 SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
585 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
587 unsigned int luma_pos, chroma_pos1, chroma_pos2;
588 for (j = 0; j < height; j++)
589 for (i = 0; i < width; i++)
590 SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
593 ff_draw_rectangle(picref->data, picref->linesize,
594 line, pixel_step, hsub, vsub,
595 x, y, width, height);
599 static inline int is_newline(uint32_t c)
601 return (c == '\n' || c == '\r' || c == '\f' || c == '\v');
604 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
605 int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
607 char *text = dtext->expanded_text;
613 for (i = 0, p = text; *p; i++) {
615 GET_UTF8(code, *p++, continue;);
617 /* skip new line chars, just go to new line */
618 if (code == '\n' || code == '\r' || code == '\t')
622 glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
624 if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
625 glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
626 return AVERROR(EINVAL);
628 x1 = dtext->positions[i].x+dtext->x+x;
629 y1 = dtext->positions[i].y+dtext->y+y;
631 if (dtext->is_packed_rgb) {
632 draw_glyph_rgb(picref, &glyph->bitmap,
633 x1, y1, width, height,
634 dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
636 draw_glyph_yuv(picref, &glyph->bitmap,
637 x1, y1, width, height,
638 yuvcolor, dtext->hsub, dtext->vsub);
645 static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
646 int width, int height)
648 DrawTextContext *dtext = ctx->priv;
649 uint32_t code = 0, prev_code = 0;
650 int x = 0, y = 0, i = 0, ret;
651 int max_text_line_w = 0, len;
653 char *text = dtext->text;
655 int y_min = 32000, y_max = -32000;
656 int x_min = 32000, x_max = -32000;
658 Glyph *glyph = NULL, *prev_glyph = NULL;
661 time_t now = time(0);
663 uint8_t *buf = dtext->expanded_text;
664 int buf_size = dtext->expanded_text_size;
666 if(dtext->basetime != AV_NOPTS_VALUE)
667 now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
670 buf_size = 2*strlen(dtext->text)+1;
671 buf = av_malloc(buf_size);
675 localtime_r(&now, <ime);
677 if(strchr(dtext->text, '%'))
678 ltime= *localtime(&now);
683 if (strftime(buf, buf_size, dtext->text, <ime) != 0 || *buf == 0)
686 } while ((buf = av_realloc(buf, buf_size)));
689 return AVERROR(ENOMEM);
690 text = dtext->expanded_text = buf;
691 dtext->expanded_text_size = buf_size;
692 if ((len = strlen(text)) > dtext->nb_positions) {
693 if (!(dtext->positions =
694 av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
695 return AVERROR(ENOMEM);
696 dtext->nb_positions = len;
702 /* load and cache glyphs */
703 for (i = 0, p = text; *p; i++) {
704 GET_UTF8(code, *p++, continue;);
708 glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
710 load_glyph(ctx, &glyph, code);
712 y_min = FFMIN(glyph->bbox.yMin, y_min);
713 y_max = FFMAX(glyph->bbox.yMax, y_max);
714 x_min = FFMIN(glyph->bbox.xMin, x_min);
715 x_max = FFMAX(glyph->bbox.xMax, x_max);
717 dtext->max_glyph_h = y_max - y_min;
718 dtext->max_glyph_w = x_max - x_min;
720 /* compute and save position for each glyph */
722 for (i = 0, p = text; *p; i++) {
723 GET_UTF8(code, *p++, continue;);
725 /* skip the \n in the sequence \r\n */
726 if (prev_code == '\r' && code == '\n')
730 if (is_newline(code)) {
731 max_text_line_w = FFMAX(max_text_line_w, x);
732 y += dtext->max_glyph_h;
740 glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
743 if (dtext->use_kerning && prev_glyph && glyph->code) {
744 FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
745 ft_kerning_default, &delta);
750 dtext->positions[i].x = x + glyph->bitmap_left;
751 dtext->positions[i].y = y - glyph->bitmap_top + y_max;
752 if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
753 else x += glyph->advance;
756 max_text_line_w = FFMAX(x, max_text_line_w);
758 dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
759 dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
761 dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
762 dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
763 dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
764 dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
766 dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
768 dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, NULL);
769 dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, NULL);
770 dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, NULL);
772 dtext->x &= ~((1 << dtext->hsub) - 1);
773 dtext->y &= ~((1 << dtext->vsub) - 1);
775 box_w = FFMIN(width - 1 , max_text_line_w);
776 box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
780 drawbox(picref, dtext->x, dtext->y, box_w, box_h,
781 dtext->box_line, dtext->pixel_step, dtext->boxcolor_rgba,
782 dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);
784 if (dtext->shadowx || dtext->shadowy) {
785 if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor_rgba,
786 dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
790 if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor_rgba,
791 dtext->fontcolor, 0, 0)) < 0)
797 static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
799 static void end_frame(AVFilterLink *inlink)
801 AVFilterContext *ctx = inlink->dst;
802 AVFilterLink *outlink = ctx->outputs[0];
803 DrawTextContext *dtext = ctx->priv;
804 AVFilterBufferRef *picref = inlink->cur_buf;
806 dtext->var_values[VAR_T] = picref->pts == AV_NOPTS_VALUE ?
807 NAN : picref->pts * av_q2d(inlink->time_base);
809 draw_text(ctx, picref, picref->video->w, picref->video->h);
811 av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
812 (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
813 (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
816 dtext->var_values[VAR_N] += 1.0;
818 avfilter_draw_slice(outlink, 0, picref->video->h, 1);
819 avfilter_end_frame(outlink);
822 AVFilter avfilter_vf_drawtext = {
824 .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
825 .priv_size = sizeof(DrawTextContext),
828 .query_formats = query_formats,
830 .inputs = (AVFilterPad[]) {{ .name = "default",
831 .type = AVMEDIA_TYPE_VIDEO,
832 .get_video_buffer = avfilter_null_get_video_buffer,
833 .start_frame = avfilter_null_start_frame,
834 .draw_slice = null_draw_slice,
835 .end_frame = end_frame,
836 .config_props = config_input,
837 .min_perms = AV_PERM_WRITE |
839 .rej_perms = AV_PERM_PRESERVE },
841 .outputs = (AVFilterPad[]) {{ .name = "default",
842 .type = AVMEDIA_TYPE_VIDEO, },
844 .process_command = command,