[PATCH] lavfi: add drawtext filter
Stefano Sabatini
stefano.sabatini-lala
Tue Sep 28 16:09:27 CEST 2010
Port drawtext filter by Hemanth from the libavfilter soc repo, with
the following additions:
* support to generic load libfreetype options
* support to anti-aliased glyph rendering
* support to UTF-8 text and Unicode chars rendering
---
configure | 6 +
doc/filters.texi | 81 ++++++
libavfilter/Makefile | 1 +
libavfilter/allfilters.c | 1 +
libavfilter/vf_drawtext.c | 609 +++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 698 insertions(+), 0 deletions(-)
create mode 100644 libavfilter/vf_drawtext.c
diff --git a/configure b/configure
index ed2934d..97999a5 100755
--- a/configure
+++ b/configure
@@ -169,6 +169,7 @@ External library support:
and libraw1394 [no]
--enable-libdirac enable Dirac support via libdirac [no]
--enable-libfaac enable FAAC support via libfaac [no]
+ --enable-libfreetype enable libfreetype [no]
--enable-libgsm enable GSM support via libgsm [no]
--enable-libmp3lame enable MP3 encoding via libmp3lame [no]
--enable-libnut enable NUT (de)muxing via libnut,
@@ -896,6 +897,7 @@ CONFIG_LIST="
libdc1394
libdirac
libfaac
+ libfreetype
libgsm
libmp3lame
libnut
@@ -1041,6 +1043,7 @@ HAVE_LIST="
llrintf
local_aligned_16
local_aligned_8
+ localtime_r
log2
log2f
loongson
@@ -1422,6 +1425,7 @@ udp_protocol_deps="network"
# filters
blackframe_filter_deps="gpl"
cropdetect_filter_deps="gpl"
+drawtext_filter_deps="libfreetype"
frei0r_filter_deps="frei0r dlopen strtok_r"
frei0r_src_filter_deps="frei0r dlopen strtok_r"
hqdn3d_filter_deps="gpl"
@@ -2735,6 +2739,7 @@ check_func getrusage
check_struct "sys/time.h sys/resource.h" "struct rusage" ru_maxrss
check_func inet_aton $network_extralibs
check_func isatty
+check_func localtime_r
check_func ${malloc_prefix}memalign && enable memalign
check_func mkstemp
check_func mmap
@@ -2821,6 +2826,7 @@ enabled libdirac && add_cflags $(pkg-config --cflags dirac) &&
require libdirac libdirac_decoder/dirac_parser.h dirac_decoder_init $(pkg-config --libs dirac) &&
require libdirac libdirac_encoder/dirac_encoder.h dirac_encoder_init $(pkg-config --libs dirac)
enabled libfaac && require2 libfaac "stdint.h faac.h" faacEncGetVersion -lfaac
+enabled libfreetype && add_cflags $(pkg-config --cflags freetype2) && require libfreetype ft2build.h FT_Init_FreeType -lfreetype
enabled libgsm && require libgsm gsm/gsm.h gsm_create -lgsm
enabled libmp3lame && require "libmp3lame >= 3.98.3" lame/lame.h lame_set_VBR_quality -lmp3lame
enabled libnut && require libnut libnut.h nut_demuxer_init -lnut
diff --git a/doc/filters.texi b/doc/filters.texi
index 042ea13..17bcb4f 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -353,6 +353,87 @@ drawbox
drawbox=10:20:200:60:red@@0.5"
@end example
+ at section drawtext
+
+Draw text string or text from specified file on top of video using the
+libfreetype library.
+The filter also recognizes strftime() sequences in the provided text and
+expands them accordingly. Check the documentation of strftime().
+
+To enable compilation of this filter you need to configure FFmpeg with
+--enable-libfreetype.
+
+The filter accepts parameters as a list of @var{key}=@var{value} pairs,
+separated by ":".
+
+The description of the accepted parameters follows.
+
+ at table @option
+
+ at item fontfile
+The font file to be used for drawing text. Path must be included.
+This parameter is mandatory.
+
+ at item text
+The text string to be drawn.
+This parameter is mandatory if no file is specified.
+
+ at item textfile
+A text file containing text to be drawn. Max of 1024 characters are
+read from the file.
+
+This parameter is mandatory if no text string is specified.
+
+If both text and textfile are specified, an error is thrown.
+
+ at item x, y
+The offsets where text will be drawn within the video frame.
+Relative to the top/left border of the output image.
+
+The default value of @var{x} and @var{y} is 0.
+
+ at item fontsize
+The font size to be used for drawing text.
+The default value of @var{size} is 16.
+
+ at item fgcolor
+The foreground color to be used for drawing text.
+Either a string (e.g. "red") or in 0xRRGGBB[AA] format
+(e.g. "0xff000033"), possibly followed by an alpha specifier.
+The default value of @var{fgcolor} is "black".
+
+ at item bgcolor
+The background color to be used for drawing box around text or drawing
+text outline based on option selected.
+Either a string (e.g. "yellow") or in 0xRRGGBB[AA] format
+(e.g. "0xff00ff"), possibly followed by an alpha specifier.
+
+The default value of @var{bgcolor} is "white".
+
+ at item box
+Used to draw a box around text using background color.
+Value should be either 1 (enable) or 0 (disable).
+The default value of @var{box} is 0.
+
+ at item outline
+Used to draw an outline around text using background color.
+Value should be either 1 (enable) or 0 (disable).
+The default value of @var{outline} is 0.
+
+ at end table
+
+ at example
+drawtext="fontfile=FreeSerif.ttf: text='Test Text': x=100: y=50: fontsize=24:
+ fgcolor=yellow@@0.2: bgcolor=red@@0.2: box=1"
+ at end example
+
+Draw 'Test Text' with font FreeSerif of size 24 at (100,50), text color is yellow,
+background color is red, draw a box around text. Both the text and the
+box have an opacity of 20%.
+
+Note that the double quotes are not necessary if spaces are not used within
+the parameter list.
+
@section fifo
Buffer input images and send them when they are requested.
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index abb68c8..3babeb9 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -25,6 +25,7 @@ OBJS-$(CONFIG_COPY_FILTER) += vf_copy.o
OBJS-$(CONFIG_CROP_FILTER) += vf_crop.o
OBJS-$(CONFIG_CROPDETECT_FILTER) += vf_cropdetect.o
OBJS-$(CONFIG_DRAWBOX_FILTER) += vf_drawbox.o
+OBJS-$(CONFIG_DRAWTEXT_FILTER) += vf_drawtext.o
OBJS-$(CONFIG_FIFO_FILTER) += vf_fifo.o
OBJS-$(CONFIG_FORMAT_FILTER) += vf_format.o
OBJS-$(CONFIG_FREI0R_FILTER) += vf_frei0r.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index cb29c2f..347a728 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -45,6 +45,7 @@ void avfilter_register_all(void)
REGISTER_FILTER (CROP, crop, vf);
REGISTER_FILTER (CROPDETECT, cropdetect, vf);
REGISTER_FILTER (DRAWBOX, drawbox, vf);
+ REGISTER_FILTER (DRAWTEXT, drawtext, vf);
REGISTER_FILTER (FIFO, fifo, vf);
REGISTER_FILTER (FORMAT, format, vf);
REGISTER_FILTER (FREI0R, frei0r, vf);
diff --git a/libavfilter/vf_drawtext.c b/libavfilter/vf_drawtext.c
new file mode 100644
index 0000000..1eec7dd
--- /dev/null
+++ b/libavfilter/vf_drawtext.c
@@ -0,0 +1,609 @@
+/*
+ * Copyright (c) 2011 Stefano Sabatini
+ * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
+ * Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri at yahoo.com.br>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * drawtext filter, based on the original FFmpeg vhook/drawtext.c
+ * filter by Gustavo Sverzut Barbieri
+ */
+
+#include <sys/time.h>
+#include <time.h>
+
+#include "libavutil/colorspace.h"
+#include "libavutil/file.h"
+#include "libavutil/opt.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/tree.h"
+#include "avfilter.h"
+
+#undef time
+
+#include <ft2build.h>
+#include <freetype/config/ftheader.h>
+#include FT_FREETYPE_H
+#include FT_GLYPH_H
+
+#define MAX_EXPANDED_TEXT_SIZE 2048
+
+typedef struct {
+ const AVClass *class;
+ char *fontfile; ///< font to be used
+ char *text; ///< text to be drawn
+ /** buffer containing the text expanded by strftime */
+ char expanded_text[MAX_EXPANDED_TEXT_SIZE];
+ /** positions for each element in the text */
+ FT_Vector positions[MAX_EXPANDED_TEXT_SIZE];
+ char *textfile; ///< file with text to be drawn
+ unsigned int x; ///< x position to start drawing text
+ unsigned int y; ///< y position to start drawing text
+ unsigned int fontsize; ///< font size to use
+ char *fgcolor_string; ///< foreground color as string
+ char *bgcolor_string; ///< background color as string
+ unsigned char fgcolor[4]; ///< foreground color in YUV
+ unsigned char bgcolor[4]; ///< background color in YUV
+ short int draw_box; ///< draw box around text - true or false
+ short int outline; ///< draw outline in bg color around text
+ int text_height; ///< height of a font symbol
+ int baseline; ///< baseline to draw fonts from
+ int use_kerning; ///< font kerning is used - true/false
+ FT_Library library; ///< freetype font library handle
+ FT_Face face; ///< freetype font face handle
+ struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
+ int ftload_flags; ///< flags used for loading fonts, see FT_LOAD_*
+ int hsub, vsub; ///< chroma subsampling values
+} DrawTextContext;
+
+#define OFFSET(x) offsetof(DrawTextContext, x)
+
+static const AVOption drawtext_options[]= {
+{"fontfile", "set font file", OFFSET(fontfile), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
+{"text", "set text", OFFSET(text), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
+{"textfile", "set text file", OFFSET(textfile), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
+{"fgcolor", "set foreground color", OFFSET(fgcolor_string), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
+{"bgcolor", "set background color", OFFSET(bgcolor_string), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
+{"box", "set box", OFFSET(draw_box), FF_OPT_TYPE_INT, 0, 0, 1 },
+{"outline", "set outline", OFFSET(outline), FF_OPT_TYPE_INT, 0, 0, 1 },
+{"fontsize", "set font size", OFFSET(fontsize), FF_OPT_TYPE_INT, 16, 1, 72 },
+{"x", "set x", OFFSET(x), FF_OPT_TYPE_INT, 0, 0, INT_MAX },
+{"y", "set y", OFFSET(y), FF_OPT_TYPE_INT, 0, 0, INT_MAX },
+
+/* FT_LOAD_* flags */
+{"ftload", "set font loading flags for libfreetype", OFFSET(ftload_flags), FF_OPT_TYPE_FLAGS, FT_LOAD_DEFAULT|FT_LOAD_RENDER, 0, INT_MAX, 0, "ftload" },
+{"default", "set DEFAULT", 0, FF_OPT_TYPE_CONST, FT_LOAD_DEFAULT, INT_MIN, INT_MAX, 0, "ftload" },
+{"no_scale", "set NO_SCALE", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_SCALE, INT_MIN, INT_MAX, 0, "ftload" },
+{"no_hinting", "set NO_HINTING", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_HINTING, INT_MIN, INT_MAX, 0, "ftload" },
+{"render", "set RENDER", 0, FF_OPT_TYPE_CONST, FT_LOAD_RENDER, INT_MIN, INT_MAX, 0, "ftload" },
+{"no_bitmap", "set NO_BITMAP", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_BITMAP, INT_MIN, INT_MAX, 0, "ftload" },
+{"vertical_layout", "set VERTICAL_LAYOUT", 0, FF_OPT_TYPE_CONST, FT_LOAD_VERTICAL_LAYOUT, INT_MIN, INT_MAX, 0, "ftload" },
+{"force_autohint", "set FORCE_AUTOHINT", 0, FF_OPT_TYPE_CONST, FT_LOAD_FORCE_AUTOHINT, INT_MIN, INT_MAX, 0, "ftload" },
+{"crop_bitmap", "set CROP_BITMAP", 0, FF_OPT_TYPE_CONST, FT_LOAD_CROP_BITMAP, INT_MIN, INT_MAX, 0, "ftload" },
+{"pedantic", "set PEDANTIC", 0, FF_OPT_TYPE_CONST, FT_LOAD_PEDANTIC, INT_MIN, INT_MAX, 0, "ftload" },
+{"ignore_global_advance_width", "set IGNORE_GLOBAL_ADVANCE_WIDTH", 0, FF_OPT_TYPE_CONST, FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH, INT_MIN, INT_MAX, 0, "ftload" },
+{"no_recurse", "set NO_RECURSE", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_RECURSE, INT_MIN, INT_MAX, 0, "ftload" },
+{"ignore_transform", "set IGNORE_TRANSFORM", 0, FF_OPT_TYPE_CONST, FT_LOAD_IGNORE_TRANSFORM, INT_MIN, INT_MAX, 0, "ftload" },
+{"monochrome", "set MONOCHROME", 0, FF_OPT_TYPE_CONST, FT_LOAD_MONOCHROME, INT_MIN, INT_MAX, 0, "ftload" },
+{"linear_design", "set LINEAR_DESIGN", 0, FF_OPT_TYPE_CONST, FT_LOAD_LINEAR_DESIGN, INT_MIN, INT_MAX, 0, "ftload" },
+{"no_autohint", "set NO_AUTOHINT", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_AUTOHINT, INT_MIN, INT_MAX, 0, "ftload" },
+{NULL},
+};
+
+static const char *drawtext_get_name(void *ctx)
+{
+ return "drawtext";
+}
+
+static const AVClass drawtext_class = {
+ "DrawTextContext",
+ drawtext_get_name,
+ drawtext_options
+};
+
+#undef __FTERRORS_H__
+#define FT_ERROR_START_LIST {
+#define FT_ERRORDEF(e, v, s) { (e), (s) },
+#define FT_ERROR_END_LIST { 0, NULL } };
+
+struct ft_error
+{
+ int err;
+ const char *err_msg;
+} static ft_errors[] =
+#include FT_ERRORS_H
+
+#define FT_ERRMSG(e) ft_errors[e].err_msg
+
+static inline int get_yuv_color(uint8_t yuva[4], char *color_str, void *log_ctx)
+{
+ uint8_t rgba[4];
+ uint8_t err;
+ if ((err = av_parse_color(rgba, color_str, -1, log_ctx)))
+ return err;
+
+ yuva[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
+ yuva[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
+ yuva[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
+ yuva[3] = rgba[3];
+
+ return 0;
+}
+
+typedef struct {
+ FT_Glyph *glyph;
+ uint32_t code;
+ FT_Bitmap bitmap; ///< array holding bitmaps of font
+ int advance;
+ int bitmap_left;
+ int bitmap_top;
+} Glyph;
+
+static int glyph_cmp(const Glyph *a, const Glyph *b)
+{
+ int64_t diff = (int64_t)a->code - (int64_t)b->code;
+ return diff > 0 ? 1 : diff < 0 ? -1 : 0;
+}
+
+/**
+ * Loads glyphs corresponding to the UTF-32 codepoint code.
+ */
+static int load_glyph(AVFilterContext *ctx, uint32_t code, int *y_min, int *y_max)
+{
+ DrawTextContext *dtext = ctx->priv;
+ FT_BBox bbox;
+ Glyph *glyph = av_mallocz(sizeof(Glyph));
+ struct AVTreeNode *node = NULL;
+ int ret;
+
+ /* load glyph into dtext->face->glyph */
+ ret = FT_Load_Char(dtext->face, code, dtext->ftload_flags);
+ if (ret)
+ return AVERROR(EINVAL);
+
+ /* save glyph */
+ glyph->code = code;
+ glyph->glyph = av_mallocz(sizeof(FT_Glyph));
+ ret = FT_Get_Glyph(dtext->face->glyph, glyph->glyph);
+ if (ret)
+ return AVERROR(EINVAL);
+
+ glyph->bitmap = dtext->face->glyph->bitmap;
+ glyph->bitmap_left = dtext->face->glyph->bitmap_left;
+ glyph->bitmap_top = dtext->face->glyph->bitmap_top;
+ glyph->advance = dtext->face->glyph->advance.x >> 6;
+
+ /* cache the newly created glyph */
+ if (!node)
+ node = av_mallocz(av_tree_node_size);
+ av_tree_insert(&dtext->glyphs, glyph, (void *)glyph_cmp, &node);
+
+ /* measure text height to calculate text_height (or the maximum text height) */
+ FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &bbox);
+ *y_min = FFMIN(bbox.yMin, *y_min);
+ *y_max = FFMAX(bbox.yMax, *y_max);
+
+ return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+ uint32_t code;
+ uint8_t *p;
+ int err;
+ int y_max, y_min;
+ DrawTextContext *dtext = ctx->priv;
+
+ dtext->class = &drawtext_class;
+ av_opt_set_defaults2(dtext, 0, 0);
+ dtext->fgcolor_string = av_strdup("black");
+ dtext->bgcolor_string = av_strdup("white");
+
+ if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
+ av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
+ return err;
+ }
+
+ if (!dtext->fontfile) {
+ av_log(ctx, AV_LOG_ERROR,
+ "No font filename provided\n");
+ return AVERROR(EINVAL);
+ }
+
+ if (dtext->textfile) {
+ uint8_t *textbuf;
+ size_t textbuf_size;
+
+ if (dtext->text) {
+ av_log(ctx, AV_LOG_ERROR,
+ "Both text and text file provided. Please provide only one\n");
+ return AVERROR(EINVAL);
+ }
+ if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
+ av_log(ctx, AV_LOG_ERROR,
+ "The text file '%s' could not be read or is empty\n",
+ dtext->textfile);
+ return err;
+ }
+
+ if (!(dtext->text = av_malloc(textbuf_size+1)))
+ return AVERROR(ENOMEM);
+ memcpy(dtext->text, textbuf, textbuf_size);
+ dtext->text[textbuf_size] = 0;
+ av_file_unmap(textbuf, textbuf_size);
+ }
+
+ if (!dtext->text) {
+ av_log(ctx, AV_LOG_ERROR,
+ "Either text or a valid file must be provided\n");
+ return AVERROR(EINVAL);
+ }
+
+ if ((err = get_yuv_color(dtext->fgcolor, dtext->fgcolor_string, ctx))) {
+ av_log(ctx, AV_LOG_ERROR,
+ "Invalid foreground color '%s'\n", dtext->fgcolor_string);
+ return err;
+ }
+
+ if ((err = get_yuv_color(dtext->bgcolor, dtext->bgcolor_string, ctx))) {
+ av_log(ctx, AV_LOG_ERROR,
+ "Invalid background color '%s'\n", dtext->fgcolor_string);
+ return err;
+ }
+
+ if ((err = FT_Init_FreeType(&(dtext->library)))) {
+ av_log(ctx, AV_LOG_ERROR,
+ "Could not load FreeType: %s\n", FT_ERRMSG(err));
+ return AVERROR(EINVAL);
+ }
+
+ /* load the face, and set up the encoding, which is by default UTF-8 */
+ if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
+ av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
+ dtext->fontfile, FT_ERRMSG(err));
+ return AVERROR(EINVAL);
+ }
+ if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
+ av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
+ dtext->fontsize, FT_ERRMSG(err));
+ return AVERROR(EINVAL);
+ }
+
+ dtext->use_kerning = FT_HAS_KERNING(dtext->face);
+
+ /* load and cache glyphs */
+ y_min = 32000;
+ y_max = -32000;
+
+ /* load ASCII chars */
+ for (code = 0; code < 256; code++)
+ load_glyph(ctx, code, &y_min, &y_max);
+
+ /* load all the other non-ASCII chars presented in the UTF-8 sequence */
+ for (p = dtext->text; *p; ) {
+ GET_UTF8(code, *p++, continue;);
+ load_glyph(ctx, code, &y_min, &y_max);
+ }
+
+ dtext->text_height = y_max - y_min;
+ dtext->baseline = y_max;
+
+#if !HAVE_LOCALTIME_R
+ av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
+#endif
+
+ return 0;
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+ /* FIXME: Add support for other formats */
+ enum PixelFormat pix_fmts[] = {
+ PIX_FMT_YUV420P, PIX_FMT_YUV444P, PIX_FMT_YUV422P,
+ PIX_FMT_YUV411P, PIX_FMT_YUV410P,
+ PIX_FMT_YUV440P, PIX_FMT_NONE
+ };
+
+ avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+ return 0;
+}
+
+static int glyph_enu_free(void *opaque, void *elem)
+{
+ av_free(elem);
+ return 0;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+ DrawTextContext *dtext = ctx->priv;
+ av_freep(&dtext->fontfile);
+ av_freep(&dtext->text);
+ av_freep(&dtext->fgcolor_string);
+ av_freep(&dtext->bgcolor_string);
+ av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
+ av_tree_destroy(dtext->glyphs);
+ dtext->glyphs = 0;
+ FT_Done_Face(dtext->face);
+ FT_Done_FreeType(dtext->library);
+}
+
+static int config_input(AVFilterLink *inlink)
+{
+ DrawTextContext *dtext = inlink->dst->priv;
+ const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
+
+ dtext->hsub = pix_desc->log2_chroma_w;
+ dtext->vsub = pix_desc->log2_chroma_h;
+ return 0;
+}
+
+#define SET_PIXEL(picref, yuv_color, val, x, y, hsub, vsub) { \
+ luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
+ chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
+ chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
+ alpha = (yuv_color[3] * (val)) / 255; \
+ picref->data[0][luma_pos] = (alpha * yuv_color[0] + (255 - alpha) * picref->data[0][luma_pos]) >> 8; \
+ alpha = (yuv_color[3] * (val)) / 224; \
+ picref->data[1][chroma_pos1] = 16 + (alpha * (yuv_color[1]-16) + (224 - alpha) * (picref->data[1][chroma_pos1]-16)) / 224; \
+ picref->data[2][chroma_pos2] = 16 + (alpha * (yuv_color[2]-16) + (224 - alpha) * (picref->data[2][chroma_pos2]-16)) / 224; \
+}
+
+#define GET_PIXEL(dst_yuv_color, picref, x, y, hsub, vsub) { \
+ dst_yuv_color[0] = picref->data[0][ (x) + (y) * picref->linesize[0]]; \
+ dst_yuv_color[1] = picref->data[1][((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]]; \
+ dst_yuv_color[2] = picref->data[2][((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]]; \
+}
+
+#define GET_BITMAP_VAL(r, c) \
+ bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
+ (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
+ bitmap->buffer[(r) * bitmap->pitch + (c)] \
+
+static inline int draw_glyph(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
+ unsigned int y, unsigned int width, unsigned int height,
+ unsigned char yuv_fgcolor[4], unsigned char yuv_bgcolor[4],
+ short int outline, int hsub, int vsub)
+{
+ int r, c, alpha;
+ unsigned int luma_pos, chroma_pos1, chroma_pos2;
+ uint8_t src_val, dst_pixel[4], in_glyph = 0;
+
+ if (bitmap->pixel_mode != FT_PIXEL_MODE_MONO &&
+ bitmap->pixel_mode != FT_PIXEL_MODE_GRAY)
+ return AVERROR(EINVAL);
+
+ in_glyph = 0;
+ for (r = 0; r < bitmap->rows && r+y < height; r++) {
+ for (c = 0; c < bitmap->width && c+x < width; c++) {
+ /* get pixel in the picref (destination) */
+ GET_PIXEL(dst_pixel, picref, c+x, y+r, hsub, vsub);
+
+ /* get intensity value in the glyph bitmap (source) */
+ src_val = GET_BITMAP_VAL(r, c);
+ if (src_val)
+ memcpy(dst_pixel, yuv_fgcolor, 4);
+
+ if (outline) {
+ /* border detection: */
+ if (!in_glyph && src_val) {
+ /* left border detected */
+ in_glyph = 1;
+ /* draw left pixel border */
+ if (c-1 >= 0)
+ SET_PIXEL(picref, yuv_bgcolor, src_val, c+x-1, y+r, hsub, vsub);
+ } else if (in_glyph && !src_val) {
+ /* right border detected */
+ in_glyph = 0;
+ /* 'draw' right pixel border */
+ memcpy(dst_pixel, yuv_bgcolor, 4);
+ }
+
+ if (in_glyph) {
+ /* see if we have a top/bottom border */
+ /* top border detection */
+ if (r-1 >= 0 && !(src_val = GET_BITMAP_VAL(r-1, c)))
+ /* draw top border */
+ SET_PIXEL(picref, yuv_bgcolor, src_val, c+x, y+r-1, hsub, vsub);
+
+ /* bottom border detection */
+ if (r+1 < height && !(src_val = GET_BITMAP_VAL(r+1, c)))
+ /* draw bottom border */
+ SET_PIXEL(picref, yuv_bgcolor, src_val, c+x, y+r+1, hsub, vsub);
+ }
+ }
+
+ SET_PIXEL(picref, dst_pixel, src_val, c+x, y+r, hsub, vsub);
+ }
+ }
+
+ return 0;
+}
+
+static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
+ unsigned int width, unsigned int height,
+ unsigned char yuv_color[4], int hsub, int vsub)
+{
+ int i, plane, alpha;
+ uint8_t *p;
+
+ if (yuv_color[3] != 0xFF) {
+ unsigned int j, luma_pos, chroma_pos1, chroma_pos2;
+
+ for (j = 0; j < height; j++)
+ for (i = 0; i < width; i++)
+ SET_PIXEL(picref, yuv_color, 255, i+x, y+j, hsub, vsub);
+
+ } else {
+ for (plane = 0; plane < 3 && picref->data[plane]; plane++) {
+ int hsub1 = plane == 1 || plane == 2 ? hsub : 0;
+ int vsub1 = plane == 1 || plane == 2 ? vsub : 0;
+
+ p = picref->data[plane] +
+ (y >> vsub1) * picref->linesize[plane] + (x >> hsub1);
+ for (i = 0; i < height >> vsub1; i++) {
+ memset(p, yuv_color[plane], width >> hsub1);
+ p += picref->linesize[plane];
+ }
+ }
+ }
+}
+
+static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
+ int width, int height)
+{
+ DrawTextContext *dtext = ctx->priv;
+ FT_Face face = dtext->face;
+ char *text = dtext->text;
+ uint32_t code = 0;
+ int x = 0, y = 0, i = 0;
+ uint8_t *p;
+ int str_w, str_w_max;
+ FT_Vector delta;
+ Glyph *glyph = NULL, *prev_glyph = NULL;
+ Glyph dummy = { 0 };
+ Glyph *glyph0 = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
+
+#if HAVE_LOCALTIME_R
+ time_t now = time(0);
+ struct tm ltime;
+ size_t expanded_text_len;
+
+ dtext->expanded_text[0] = '\1';
+ expanded_text_len = strftime(dtext->expanded_text, MAX_EXPANDED_TEXT_SIZE,
+ text, localtime_r(&now, <ime));
+
+ if (expanded_text_len == 0 && dtext->expanded_text[0] != '\0') {
+ av_log(ctx, AV_LOG_WARNING,
+ "String expanded by strftime() is too big");
+ return AVERROR(EINVAL);
+ }
+ text = dtext->expanded_text;
+#endif
+
+ /* measure text size and save glyphs position */
+ str_w = str_w_max = 0;
+ x = dtext->x;
+ y = dtext->y;
+
+ for (i = 0, p = text; *p; i++) {
+ GET_UTF8(code, *p++, continue;);
+
+ /* get glyph */
+ prev_glyph = glyph;
+ dummy.code = code;
+ glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
+ if (!glyph)
+ glyph = glyph0;
+
+ /* kerning */
+ if (dtext->use_kerning && prev_glyph && glyph->code) {
+ FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
+ ft_kerning_default, &delta);
+ x += delta.x >> 6;
+ }
+
+ if (x + glyph->advance >= width || code == '\n' || code == '\r') {
+ if (code != '\n' || code != '\r')
+ str_w_max = width - dtext->x - 1;
+ y += dtext->text_height;
+ x = dtext->x;
+ }
+
+ /* save position */
+ dtext->positions[i].x = x + glyph->bitmap_left;
+ dtext->positions[i].y = y - glyph->bitmap_top + dtext->baseline;
+ x += glyph->advance;
+ str_w += glyph->advance;
+ }
+ y += dtext->text_height;
+ if (str_w_max == 0)
+ str_w_max = str_w;
+
+ if (dtext->draw_box) {
+ /* Check if it doesn't pass the limits */
+ str_w_max = FFMIN(str_w_max, width - dtext->x - 1);
+ y = FFMIN(y, height - 1);
+
+ /* draw background */
+ drawbox(picref, dtext->x, dtext->y, str_w_max, y-dtext->y,
+ dtext->bgcolor, dtext->hsub, dtext->vsub);
+ }
+
+ /* draw glyphs */
+ for (i = 0, p = text; *p; i++) {
+ Glyph dummy = { 0 };
+ GET_UTF8(code, *p++, continue;);
+
+ /* skip new line char, just go to new line */
+ if (code == '\n' || code == '\r')
+ continue;
+
+ dummy.code = code;
+ glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
+ if (!glyph)
+ glyph = glyph0;
+
+ draw_glyph(picref, &glyph->bitmap,
+ dtext->positions[i].x, dtext->positions[i].y, width, height,
+ dtext->fgcolor, dtext->bgcolor, dtext->outline,
+ dtext->hsub, dtext->vsub);
+
+ /* increment pen position */
+ x += face->glyph->advance.x >> 6;
+ }
+
+ return 0;
+}
+
+static void end_frame(AVFilterLink *inlink)
+{
+ AVFilterLink *outlink = inlink->dst->outputs[0];
+ AVFilterBufferRef *picref = inlink->cur_buf;
+
+ draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
+
+ avfilter_draw_slice(outlink, 0, picref->video->h, 1);
+ avfilter_end_frame(outlink);
+}
+
+AVFilter avfilter_vf_drawtext = {
+ .name = "drawtext",
+ .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
+ .priv_size = sizeof(DrawTextContext),
+ .init = init,
+ .uninit = uninit,
+ .query_formats = query_formats,
+
+ .inputs = (AVFilterPad[]) {{ .name = "default",
+ .type = AVMEDIA_TYPE_VIDEO,
+ .get_video_buffer = avfilter_null_get_video_buffer,
+ .start_frame = avfilter_null_start_frame,
+ .end_frame = end_frame,
+ .config_props = config_input,
+ .min_perms = AV_PERM_WRITE |
+ AV_PERM_READ,
+ .rej_perms = AV_PERM_PRESERVE },
+ { .name = NULL}},
+ .outputs = (AVFilterPad[]) {{ .name = "default",
+ .type = AVMEDIA_TYPE_VIDEO, },
+ { .name = NULL}},
+};
--
1.7.2.3
--45Z9DzgjV8m4Oswq--
More information about the ffmpeg-devel
mailing list