]> git.sesse.net Git - ffmpeg/blobdiff - libavfilter/vf_drawtext.c
Mark some arrays that never change as const.
[ffmpeg] / libavfilter / vf_drawtext.c
index 53340c84abcbd22aa42aea9a32a265594265b710..5668c8e8e0b23e867a0b99f5ca70ea830b38c4b7 100644 (file)
  * filter by Gustavo Sverzut Barbieri
  */
 
+#include "config.h"
+
+#include <sys/types.h>
 #include <sys/time.h>
+#include <sys/stat.h>
 #include <time.h>
+#include <unistd.h>
+
+#if CONFIG_LIBFONTCONFIG
+#include <fontconfig/fontconfig.h>
+#endif
 
 #include "libavutil/colorspace.h"
 #include "libavutil/common.h"
@@ -38,6 +47,7 @@
 #include "libavutil/random_seed.h"
 #include "libavutil/parseutils.h"
 #include "libavutil/pixdesc.h"
+#include "libavutil/time_internal.h"
 #include "libavutil/tree.h"
 #include "libavutil/lfg.h"
 #include "avfilter.h"
@@ -47,7 +57,6 @@
 #include "video.h"
 
 #include <ft2build.h>
-#include <freetype/config/ftheader.h>
 #include FT_FREETYPE_H
 #include FT_GLYPH_H
 
@@ -97,8 +106,11 @@ enum var_name {
     VAR_VARS_NB
 };
 
-typedef struct {
+typedef struct DrawTextContext {
     const AVClass *class;
+#if CONFIG_LIBFONTCONFIG
+    uint8_t *font;              ///< font to be used
+#endif
     uint8_t *fontfile;              ///< font to be used
     uint8_t *text;                  ///< text to be drawn
     uint8_t *expanded_text;         ///< used to contain the strftime()-expanded text
@@ -140,6 +152,9 @@ typedef struct {
     char   *d_expr;
     AVExpr *d_pexpr;
     int draw;                       ///< set to zero to prevent drawing
+    char   *a_expr;
+    AVExpr *a_pexpr;
+    int alpha;
     AVLFG  prng;                    ///< random
 } DrawTextContext;
 
@@ -147,6 +162,9 @@ typedef struct {
 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM
 
 static const AVOption drawtext_options[]= {
+#if CONFIG_LIBFONTCONFIG
+    { "font",        "Font name",            OFFSET(font),               AV_OPT_TYPE_STRING, { .str = "Sans" },           .flags = FLAGS },
+#endif
     { "fontfile",    NULL,                   OFFSET(fontfile),           AV_OPT_TYPE_STRING,                              .flags = FLAGS },
     { "text",        NULL,                   OFFSET(text),               AV_OPT_TYPE_STRING,                              .flags = FLAGS },
     { "textfile",    NULL,                   OFFSET(textfile),           AV_OPT_TYPE_STRING,                              .flags = FLAGS },
@@ -154,13 +172,14 @@ static const AVOption drawtext_options[]= {
     { "boxcolor",    NULL,                   OFFSET(boxcolor_string),    AV_OPT_TYPE_STRING, { .str = "white" },          .flags = FLAGS },
     { "shadowcolor", NULL,                   OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, { .str = "black" },          .flags = FLAGS },
     { "box",         NULL,                   OFFSET(draw_box),           AV_OPT_TYPE_INT,    { .i64 = 0       }, 0,       1,       FLAGS },
-    { "fontsize",    NULL,                   OFFSET(fontsize),           AV_OPT_TYPE_INT,    { .i64 = 16      }, 1,       72,      FLAGS },
+    { "fontsize",    NULL,                   OFFSET(fontsize),           AV_OPT_TYPE_INT,    { .i64 = 16      }, 1,       1024,    FLAGS },
     { "x",           NULL,                   OFFSET(x_expr),             AV_OPT_TYPE_STRING, { .str = "0"     },          .flags = FLAGS },
     { "y",           NULL,                   OFFSET(y_expr),             AV_OPT_TYPE_STRING, { .str = "0"     },          .flags = FLAGS },
     { "shadowx",     NULL,                   OFFSET(shadowx),            AV_OPT_TYPE_INT,    { .i64 = 0       }, INT_MIN, INT_MAX, FLAGS },
     { "shadowy",     NULL,                   OFFSET(shadowy),            AV_OPT_TYPE_INT,    { .i64 = 0       }, INT_MIN, INT_MAX, FLAGS },
     { "tabsize",     NULL,                   OFFSET(tabsize),            AV_OPT_TYPE_INT,    { .i64 = 4       }, 0,       INT_MAX, FLAGS },
     { "draw",        "if false do not draw", OFFSET(d_expr),             AV_OPT_TYPE_STRING, { .str = "1"     },          .flags = FLAGS },
+    { "alpha",       "apply alpha while rendering", OFFSET(a_expr),      AV_OPT_TYPE_STRING, { .str = "1"     },          .flags = FLAGS },
     { "fix_bounds",  "if true, check and fix text coords to avoid clipping",
                                             OFFSET(fix_bounds),          AV_OPT_TYPE_INT,    { .i64 = 1       }, 0,       1,       FLAGS },
 
@@ -200,16 +219,15 @@ static const AVClass drawtext_class = {
 #define FT_ERRORDEF(e, v, s) { (e), (s) },
 #define FT_ERROR_END_LIST { 0, NULL } };
 
-struct ft_error
-{
+static const struct ft_error {
     int err;
     const char *err_msg;
-} static ft_errors[] =
+} ft_errors[] =
 #include FT_ERRORS_H
 
 #define FT_ERRMSG(e) ft_errors[e].err_msg
 
-typedef struct {
+typedef struct Glyph {
     FT_Glyph *glyph;
     uint32_t code;
     FT_Bitmap bitmap; ///< array holding bitmaps of font
@@ -280,17 +298,94 @@ error:
     return ret;
 }
 
-static av_cold int init(AVFilterContext *ctx)
+static int parse_font(AVFilterContext *ctx)
 {
-    int err;
     DrawTextContext *s = ctx->priv;
-    Glyph *glyph;
-
+#if !CONFIG_LIBFONTCONFIG
     if (!s->fontfile) {
         av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
         return AVERROR(EINVAL);
     }
 
+    return 0;
+#else
+    FcPattern *pat, *best;
+    FcResult result = FcResultMatch;
+
+    FcBool fc_bool;
+    FcChar8* fc_string;
+    int err = AVERROR(ENOENT);
+
+    if (s->fontfile)
+        return 0;
+
+    if (!FcInit())
+        return AVERROR_UNKNOWN;
+
+    if (!(pat = FcPatternCreate()))
+        return AVERROR(ENOMEM);
+
+    FcPatternAddString(pat, FC_FAMILY, s->font);
+    FcPatternAddBool(pat, FC_OUTLINE, FcTrue);
+    FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
+
+    FcDefaultSubstitute(pat);
+
+    if (!FcConfigSubstitute(NULL, pat, FcMatchPattern)) {
+        FcPatternDestroy(pat);
+        return AVERROR(ENOMEM);
+    }
+
+    best = FcFontMatch(NULL, pat, &result);
+    FcPatternDestroy(pat);
+
+    if (!best || result == FcResultNoMatch) {
+         av_log(ctx, AV_LOG_ERROR,
+                "Cannot find a valid font for the family %s\n",
+                s->font);
+        goto fail;
+    }
+
+    if (FcPatternGetBool(best, FC_OUTLINE, 0, &fc_bool) != FcResultMatch ||
+        !fc_bool) {
+        av_log(ctx, AV_LOG_ERROR, "Outline not available for %s\n",
+               s->font);
+        goto fail;
+    }
+
+    if (FcPatternGetString(best, FC_FAMILY, 0, &fc_string) != FcResultMatch) {
+        av_log(ctx, AV_LOG_ERROR, "No matches for %s\n",
+               s->font);
+        goto fail;
+    }
+
+    if (FcPatternGetString(best, FC_FILE, 0, &fc_string) != FcResultMatch) {
+        av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
+               s->font);
+        goto fail;
+    }
+
+    s->fontfile = av_strdup(fc_string);
+    if (!s->fontfile)
+        err = AVERROR(ENOMEM);
+    else
+        err = 0;
+
+fail:
+    FcPatternDestroy(best);
+    return err;
+#endif
+}
+
+static av_cold int init(AVFilterContext *ctx)
+{
+    int err;
+    DrawTextContext *s = ctx->priv;
+    Glyph *glyph;
+
+    if ((err = parse_font(ctx)) < 0)
+        return err;
+
     if (s->textfile) {
         uint8_t *textbuf;
         size_t textbuf_size;
@@ -307,8 +402,11 @@ static av_cold int init(AVFilterContext *ctx)
             return err;
         }
 
-        if (!(s->text = av_malloc(textbuf_size+1)))
+        if (textbuf_size > SIZE_MAX - 1 ||
+            !(s->text = av_malloc(textbuf_size + 1))) {
+            av_file_unmap(textbuf, textbuf_size);
             return AVERROR(ENOMEM);
+        }
         memcpy(s->text, textbuf, textbuf_size);
         s->text[textbuf_size] = 0;
         av_file_unmap(textbuf, textbuf_size);
@@ -368,10 +466,6 @@ static av_cold int init(AVFilterContext *ctx)
     }
     s->tabsize *= glyph->advance;
 
-#if !HAVE_LOCALTIME_R
-    av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
-#endif
-
     return 0;
 }
 
@@ -426,30 +520,15 @@ static inline int is_newline(uint32_t c)
     return c == '\n' || c == '\r' || c == '\f' || c == '\v';
 }
 
-static int dtext_prepare_text(AVFilterContext *ctx)
+static int expand_strftime(DrawTextContext *s)
 {
-    DrawTextContext *s = ctx->priv;
-    uint32_t code = 0, prev_code = 0;
-    int x = 0, y = 0, i = 0, ret;
-    int text_height, baseline;
-    char *text = s->text;
-    uint8_t *p;
-    int str_w = 0, len;
-    int y_min = 32000, y_max = -32000;
-    FT_Vector delta;
-    Glyph *glyph = NULL, *prev_glyph = NULL;
-    Glyph dummy = { 0 };
-    int width  = ctx->inputs[0]->w;
-    int height = ctx->inputs[0]->h;
-
-#if HAVE_LOCALTIME_R
-    time_t now = time(0);
     struct tm ltime;
+    time_t now   = time(0);
     uint8_t *buf = s->expanded_text;
     int buf_size = s->expanded_text_size;
 
     if (!buf)
-        buf_size = 2*strlen(s->text)+1;
+        buf_size = 2 * strlen(s->text) + 1;
 
     localtime_r(&now, &ltime);
 
@@ -462,9 +541,33 @@ static int dtext_prepare_text(AVFilterContext *ctx)
 
     if (!buf)
         return AVERROR(ENOMEM);
-    text = s->expanded_text = buf;
+    s->expanded_text      = buf;
     s->expanded_text_size = buf_size;
-#endif
+
+    return 0;
+}
+
+static int dtext_prepare_text(AVFilterContext *ctx)
+{
+    DrawTextContext *s = ctx->priv;
+    uint32_t code = 0, prev_code = 0;
+    int x = 0, y = 0, i = 0, ret;
+    int text_height, baseline;
+    char *text;
+    uint8_t *p;
+    int str_w = 0, len;
+    int y_min = 32000, y_max = -32000;
+    FT_Vector delta;
+    Glyph *glyph = NULL, *prev_glyph = NULL;
+    Glyph dummy = { 0 };
+    int width  = ctx->inputs[0]->w;
+    int height = ctx->inputs[0]->h;
+
+    ret = expand_strftime(s);
+    if (ret < 0)
+        return ret;
+
+    text = s->expanded_text ? s->expanded_text : s->text;
 
     if ((len = strlen(text)) > s->nb_positions) {
         FT_Vector *p = av_realloc(s->positions,
@@ -586,6 +689,8 @@ static int config_input(AVFilterLink *inlink)
         (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
         (ret = av_expr_parse(&s->d_pexpr, s->d_expr, var_names,
+                             NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
+        (ret = av_expr_parse(&s->a_pexpr, s->a_expr, var_names,
                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
         return AVERROR(EINVAL);
 
@@ -621,7 +726,7 @@ static int config_input(AVFilterLink *inlink)
 
 #define SET_PIXEL_YUV(frame, yuva_color, val, x, y, hsub, vsub) {           \
     luma_pos    = ((x)          ) + ((y)          ) * frame->linesize[0]; \
-    alpha = yuva_color[3] * (val) * 129;                               \
+    alpha = yuva_color[3] * alpha_mul * (val) * 129 / 255; \
     frame->data[0][luma_pos]    = (alpha * yuva_color[0] + (255*255*129 - alpha) * frame->data[0][luma_pos]   ) >> 23; \
     if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
         chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[1]; \
@@ -633,7 +738,8 @@ static int config_input(AVFilterLink *inlink)
 
 static inline int draw_glyph_yuv(AVFrame *frame, FT_Bitmap *bitmap, unsigned int x,
                                  unsigned int y, unsigned int width, unsigned int height,
-                                 const uint8_t yuva_color[4], int hsub, int vsub)
+                                 const uint8_t yuva_color[4], int hsub, int vsub,
+                                 int alpha_mul)
 {
     int r, c, alpha;
     unsigned int luma_pos, chroma_pos1, chroma_pos2;
@@ -655,7 +761,7 @@ static inline int draw_glyph_yuv(AVFrame *frame, FT_Bitmap *bitmap, unsigned int
 
 #define SET_PIXEL_RGB(frame, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
     p   = frame->data[0] + (x) * pixel_step + ((y) * frame->linesize[0]); \
-    alpha = rgba_color[3] * (val) * 129;                              \
+    alpha = rgba_color[3] * alpha_mul * (val) * 129 / 255;                           \
     *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
     *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
     *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
@@ -664,7 +770,8 @@ static inline int draw_glyph_yuv(AVFrame *frame, FT_Bitmap *bitmap, unsigned int
 static inline int draw_glyph_rgb(AVFrame *frame, FT_Bitmap *bitmap,
                                  unsigned int x, unsigned int y,
                                  unsigned int width, unsigned int height, int pixel_step,
-                                 const uint8_t rgba_color[4], const uint8_t rgba_map[4])
+                                 const uint8_t rgba_color[4], const uint8_t rgba_map[4],
+                                 int alpha_mul)
 {
     int r, c, alpha;
     uint8_t *p;
@@ -688,11 +795,12 @@ static inline int draw_glyph_rgb(AVFrame *frame, FT_Bitmap *bitmap,
 static inline void drawbox(AVFrame *frame, unsigned int x, unsigned int y,
                            unsigned int width, unsigned int height,
                            uint8_t *line[4], int pixel_step[4], uint8_t color[4],
-                           int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
+                           int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4],
+                           int alpha_mul)
 {
     int i, j, alpha;
 
-    if (color[3] != 0xFF) {
+    if (color[3] != 0xFF || alpha_mul != 0xFF) {
         if (is_rgba_packed) {
             uint8_t *p;
             for (j = 0; j < height; j++)
@@ -713,9 +821,11 @@ static inline void drawbox(AVFrame *frame, unsigned int x, unsigned int y,
 }
 
 static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
-                       int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
+                       int width, int height,
+                       const uint8_t rgbcolor[4], const uint8_t yuvcolor[4],
+                       int x, int y)
 {
-    char *text = HAVE_LOCALTIME_R ? s->expanded_text : s->text;
+    char *text = s->expanded_text;
     uint32_t code = 0;
     int i;
     uint8_t *p;
@@ -730,7 +840,7 @@ static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
             continue;
 
         dummy.code = code;
-        glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
+        glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
 
         if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
             glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
@@ -739,11 +849,11 @@ static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
         if (s->is_packed_rgb) {
             draw_glyph_rgb(frame, &glyph->bitmap,
                            s->positions[i].x+x, s->positions[i].y+y, width, height,
-                           s->pixel_step[0], rgbcolor, s->rgba_map);
+                           s->pixel_step[0], rgbcolor, s->rgba_map, s->alpha);
         } else {
             draw_glyph_yuv(frame, &glyph->bitmap,
                            s->positions[i].x+x, s->positions[i].y+y, width, height,
-                           yuvcolor, s->hsub, s->vsub);
+                           yuvcolor, s->hsub, s->vsub, s->alpha);
         }
     }
 
@@ -761,7 +871,7 @@ static int draw_text(AVFilterContext *ctx, AVFrame *frame,
         drawbox(frame, s->x, s->y, s->w, s->h,
                 s->box_line, s->pixel_step, s->boxcolor,
                 s->hsub, s->vsub, s->is_packed_rgb,
-                s->rgba_map);
+                s->rgba_map, s->alpha);
 
     if (s->shadowx || s->shadowy) {
         if ((ret = draw_glyphs(s, frame, width, height,
@@ -797,6 +907,21 @@ static inline int normalize_double(int *n, double d)
     return ret;
 }
 
+static void update_alpha(DrawTextContext *s)
+{
+    double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
+
+    if (isnan(alpha))
+        return;
+
+    if (alpha >= 1.0)
+        s->alpha = 255;
+    else if (alpha <= 0)
+        s->alpha = 0;
+    else
+        s->alpha = 256 * alpha;
+}
+
 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
 {
     AVFilterContext *ctx = inlink->dst;
@@ -820,6 +945,8 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
 
     s->draw = av_expr_eval(s->d_pexpr, s->var_values, &s->prng);
 
+    update_alpha(s);
+
     normalize_double(&s->x, s->var_values[VAR_X]);
     normalize_double(&s->y, s->var_values[VAR_Y]);
 
@@ -835,7 +962,7 @@ static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
     s->x &= ~((1 << s->hsub) - 1);
     s->y &= ~((1 << s->vsub) - 1);
 
-    av_dlog(ctx, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
+    av_log(ctx, AV_LOG_TRACE, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
             (int)s->var_values[VAR_N], s->var_values[VAR_T],
             s->x, s->y, s->x+s->w, s->y+s->h);
 
@@ -867,7 +994,7 @@ static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
     { NULL }
 };
 
-AVFilter avfilter_vf_drawtext = {
+AVFilter ff_vf_drawtext = {
     .name          = "drawtext",
     .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
     .priv_size     = sizeof(DrawTextContext),