31 #include <sys/types.h> 37 #if CONFIG_LIBFONTCONFIG 38 #include <fontconfig/fontconfig.h> 60 #include FT_FREETYPE_H 82 static double drand(
void *opaque,
double min,
double max)
111 #if CONFIG_LIBFONTCONFIG 161 #define OFFSET(x) offsetof(DrawTextContext, x) 162 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM 165 #if CONFIG_LIBFONTCONFIG 183 {
"fix_bounds",
"if true, check and fix text coords to avoid clipping",
193 {
"vertical_layout",
NULL, 0,
AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags =
FLAGS, .unit =
"ft_load_flags" },
197 {
"ignore_global_advance_width",
NULL, 0,
AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags =
FLAGS, .unit =
"ft_load_flags" },
199 {
"ignore_transform",
NULL, 0,
AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags =
FLAGS, .unit =
"ft_load_flags" },
217 #undef __FTERRORS_H__ 218 #define FT_ERROR_START_LIST { 219 #define FT_ERRORDEF(e, v, s) { (e), (s) }, 220 #define FT_ERROR_END_LIST { 0, NULL } }; 229 #define FT_ERRMSG(e) ft_errors[e].err_msg 231 typedef struct Glyph {
243 const Glyph *
a = key, *bb =
b;
244 int64_t diff = (int64_t)a->code - (int64_t)bb->code;
245 return diff > 0 ? 1 : diff < 0 ? -1 : 0;
264 !(glyph->glyph =
av_mallocz(
sizeof(*glyph->glyph)))) {
270 if (FT_Get_Glyph(s->
face->glyph, glyph->glyph)) {
275 glyph->bitmap = s->
face->glyph->bitmap;
276 glyph->bitmap_left = s->
face->glyph->bitmap_left;
277 glyph->bitmap_top = s->
face->glyph->bitmap_top;
278 glyph->advance = s->
face->glyph->advance.x >> 6;
281 FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
305 #if !CONFIG_LIBFONTCONFIG 313 FcPattern *pat, *best;
314 FcResult result = FcResultMatch;
326 if (!(pat = FcPatternCreate()))
329 FcPatternAddString(pat, FC_FAMILY, s->font);
330 FcPatternAddBool(pat, FC_OUTLINE, FcTrue);
331 FcPatternAddDouble(pat, FC_SIZE, (
double)s->
fontsize);
333 FcDefaultSubstitute(pat);
335 if (!FcConfigSubstitute(
NULL, pat, FcMatchPattern)) {
336 FcPatternDestroy(pat);
340 best = FcFontMatch(
NULL, pat, &result);
341 FcPatternDestroy(pat);
343 if (!best || result == FcResultNoMatch) {
345 "Cannot find a valid font for the family %s\n",
350 if (FcPatternGetBool(best, FC_OUTLINE, 0, &fc_bool) != FcResultMatch ||
357 if (FcPatternGetString(best, FC_FAMILY, 0, &fc_string) != FcResultMatch) {
363 if (FcPatternGetString(best, FC_FILE, 0, &fc_string) != FcResultMatch) {
376 FcPatternDestroy(best);
396 "Both text and text file provided. Please provide only one\n");
401 "The text file '%s' could not be read or is empty\n",
406 if (textbuf_size > SIZE_MAX - 1 ||
411 memcpy(s->
text, textbuf, textbuf_size);
412 s->
text[textbuf_size] = 0;
418 "Either text or a valid file must be provided\n");
440 if ((err = FT_Init_FreeType(&(s->
library)))) {
442 "Could not load FreeType: %s\n",
FT_ERRMSG(err));
452 if ((err = FT_Set_Pixel_Sizes(s->
face, 0, s->
fontsize))) {
464 if ((err =
load_glyph(ctx, &glyph,
' ') < 0)) {
509 FT_Done_Face(s->
face);
512 for (i = 0; i < 4; i++) {
521 return c ==
'\n' || c ==
'\r' || c ==
'\f' || c ==
'\v';
527 time_t now = time(0);
532 buf_size = 2 * strlen(s->
text) + 1;
538 if (strftime(buf, buf_size, s->
text, <ime) != 0 || *buf == 0)
554 uint32_t code = 0, prev_code = 0;
555 int x = 0,
y = 0, i = 0, ret;
556 int text_height, baseline;
560 int y_min = 32000, y_max = -32000;
562 Glyph *glyph =
NULL, *prev_glyph =
NULL;
587 for (i = 0, p = text; *p; i++) {
599 y_min =
FFMIN(glyph->bbox.yMin, y_min);
600 y_max =
FFMAX(glyph->bbox.yMax, y_max);
602 text_height = y_max - y_min;
607 for (i = 0, p = text; *p; i++) {
611 if (prev_code ==
'\r' && code ==
'\n')
616 str_w =
FFMAX(str_w, x - s->
x);
629 FT_Get_Kerning(s->
face, prev_glyph->code, glyph->code,
630 ft_kerning_default, &delta);
634 if (x + glyph->bbox.xMax >= width) {
635 str_w =
FFMAX(str_w, x);
641 s->
positions[i].x = x + glyph->bitmap_left;
642 s->
positions[i].y =
y - glyph->bitmap_top + baseline;
644 else x += glyph->advance;
648 y =
FFMIN(
y + text_height, height - 1);
723 #define GET_BITMAP_VAL(r, c) \ 724 bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \ 725 (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \ 726 bitmap->buffer[(r) * bitmap->pitch + (c)] 728 #define SET_PIXEL_YUV(frame, yuva_color, val, x, y, hsub, vsub) { \ 729 luma_pos = ((x) ) + ((y) ) * frame->linesize[0]; \ 730 alpha = yuva_color[3] * alpha_mul * (val) * 129 / 255; \ 731 frame->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * frame->data[0][luma_pos] ) >> 23; \ 732 if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\ 733 chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[1]; \ 734 chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[2]; \ 735 frame->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * frame->data[1][chroma_pos1]) >> 23; \ 736 frame->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * frame->data[2][chroma_pos2]) >> 23; \ 741 unsigned int y,
unsigned int width,
unsigned int height,
746 unsigned int luma_pos, chroma_pos1, chroma_pos2;
749 for (r = 0; r < bitmap->rows && r+y <
height; r++) {
750 for (c = 0; c < bitmap->width && c+x <
width; c++) {
756 SET_PIXEL_YUV(frame, yuva_color, src_val, c+x, y+r, hsub, vsub);
763 #define SET_PIXEL_RGB(frame, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \ 764 p = frame->data[0] + (x) * pixel_step + ((y) * frame->linesize[0]); \ 765 alpha = rgba_color[3] * alpha_mul * (val) * 129 / 255; \ 766 *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \ 767 *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \ 768 *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \ 772 unsigned int x,
unsigned int y,
781 for (r = 0; r < bitmap->rows && r+y <
height; r++) {
782 for (c = 0; c < bitmap->width && c+x <
width; c++) {
788 SET_PIXEL_RGB(frame, rgba_color, src_val, c+x, y+r, pixel_step,
789 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
804 if (color[3] != 0xFF || alpha_mul != 0xFF) {
805 if (is_rgba_packed) {
807 for (j = 0; j <
height; j++)
808 for (i = 0; i <
width; i++)
810 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
812 unsigned int luma_pos, chroma_pos1, chroma_pos2;
813 for (j = 0; j <
height; j++)
814 for (i = 0; i <
width; i++)
819 line, pixel_step, hsub, vsub,
820 x, y, width, height);
835 for (i = 0, p = text; *p; i++) {
840 if (code ==
'\n' || code ==
'\r' || code ==
'\t')
846 if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
847 glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
902 }
else if (d > INT_MAX || d < INT_MIN) {
903 *n = d > INT_MAX ? INT_MAX : INT_MIN;
955 if (s->
x < 0) s->
x = 0;
956 if (s->
y < 0) s->
y = 0;
957 if ((
unsigned)s->
x + (
unsigned)s->
w > inlink->
w)
958 s->
x = inlink->
w - s->
w;
959 if ((
unsigned)s->
y + (
unsigned)s->
h > inlink->
h)
960 s->
y = inlink->
h - s->
h;
963 s->
x &= ~((1 << s->
hsub) - 1);
964 s->
y &= ~((1 << s->
vsub) - 1);
968 s->
x, s->
y, s->
x+s->
w, s->
y+s->
h);
1000 .description =
NULL_IF_CONFIG_SMALL(
"Draw text on top of video frames using libfreetype library."),
1002 .priv_class = &drawtext_class,
1007 .
inputs = avfilter_vf_drawtext_inputs,
1008 .
outputs = avfilter_vf_drawtext_outputs,
int draw
set to zero to prevent drawing
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
#define GET_UTF8(val, GET_BYTE, ERROR)
Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form.
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
This structure describes decoded (raw) audio or video data.
static double drand(void *opaque, double min, double max)
static const AVOption drawtext_options[]
unsigned int fontsize
font size to use
static const char * drawtext_get_name(void *ctx)
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
static const AVFilterPad outputs[]
Main libavfilter public API header.
packed RGB 8:8:8, 24bpp, RGBRGB...
uint8_t * fontfile
font to be used
int h
agreed upon image height
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)
av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (%s)\, len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic ? ac->func_descr_generic :ac->func_descr)
Various defines for YUV<->RGB conversion.
AVFrame * ff_null_get_video_buffer(AVFilterLink *link, int w, int h)
static int draw_text(AVFilterContext *ctx, AVFrame *frame, int width, int height)
static 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 alpha_mul)
uint8_t * text
text to be drawn
uint8_t * box_line[4]
line used for filling the box background
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
#define SET_PIXEL_RGB(frame, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off)
uint8_t log2_chroma_w
Amount to shift the luma width right to find the chroma width.
uint8_t shadowcolor[4]
shadow color
uint8_t boxcolor_rgba[4]
background color in RGBA
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
uint8_t fontcolor_rgba[4]
foreground color in RGBA
struct AVTreeNode * av_tree_node_alloc(void)
Allocate an AVTreeNode.
const char * name
Pad name.
AVFilterLink ** inputs
array of pointers to input links
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
static 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, int alpha_mul)
static int glyph_enu_free(void *opaque, void *elem)
void * av_tree_find(const AVTreeNode *t, void *key, int(*cmp)(void *key, const void *b), void *next[2])
static av_always_inline av_const int isnan(float x)
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
FT_Face face
freetype font face handle
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
static av_cold int init(AVFilterContext *ctx)
packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
static double av_q2d(AVRational a)
Convert rational to double.
static const AVFilterPad avfilter_vf_drawtext_inputs[]
static av_cold void uninit(AVFilterContext *ctx)
FT_Vector * positions
positions for each element in the text
void av_tree_destroy(AVTreeNode *t)
int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen, void *log_ctx)
Put the RGBA values that correspond to color_string in rgba_color.
char * fontcolor_string
font color as string
A filter pad used for either input or output.
uint8_t fontcolor[4]
foreground color
A link between two filters.
void * av_tree_insert(AVTreeNode **tp, void *key, int(*cmp)(void *key, const void *b), AVTreeNode **next)
Insert or remove an element.
double var_values[VAR_VARS_NB]
int width
width and height of the video frame
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
void av_file_unmap(uint8_t *bufptr, size_t size)
Unmap or free the buffer bufptr created by av_file_map().
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
int av_file_map(const char *filename, uint8_t **bufptr, size_t *size, int log_offset, void *log_ctx)
Read the file with name filename, and put its content in a newly allocated buffer or map it with mmap...
uint8_t log2_chroma_h
Amount to shift the luma height right to find the chroma height.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
AVExpr * y_pexpr
parsed expressions for x and y
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
void * priv
private data for use by the filter
int y
position to start drawing text
AVRational time_base
Define the time base used by the PTS of the frames/samples which will pass through this link...
static av_always_inline av_const double round(double x)
static int dtext_prepare_text(AVFilterContext *ctx)
#define GET_BITMAP_VAL(r, c)
packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
static const char *const fun2_names[]
packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
int w
agreed upon image width
static struct tm * localtime_r(const time_t *clock, struct tm *result)
packed RGB 8:8:8, 24bpp, BGRBGR...
int format
agreed upon media format
char * boxcolor_string
box color as string
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
char * av_strdup(const char *s)
Duplicate the string s.
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
size_t expanded_text_size
size in bytes of the expanded_text buffer
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
int pixel_step[4]
distance in bytes between the component of each pixel
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples)
Describe the class of an AVClass context structure.
static const AVFilterPad inputs[]
static const uint8_t color[NB_LEVELS]
struct AVTreeNode * glyphs
rendered glyphs, stored using the UTF-32 char code
int h
dimension of the text block
static int is_newline(uint32_t c)
const char * name
Filter name.
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
AVFilterLink ** outputs
array of pointers to output links
static enum AVPixelFormat pix_fmts[]
struct ft_error ft_errors[]
short int draw_box
draw box around text - true or false
static int config_input(AVFilterLink *inlink)
#define RGB_TO_U_CCIR(r1, g1, b1, shift)
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
#define RGB_TO_V_CCIR(r1, g1, b1, shift)
uint8_t shadowcolor_rgba[4]
shadow color in RGBA
static void update_alpha(DrawTextContext *s)
uint8_t rgba_map[4]
map RGBA offsets to the positions in the packed RGBA format
static const AVClass drawtext_class
static const char *const var_names[]
int use_kerning
font kerning is used - true/false
static int parse_font(AVFilterContext *ctx)
int vsub
chroma subsampling values
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
char * shadowcolor_string
shadow color as string
common internal and external API header
static int glyph_cmp(void *key, const void *b)
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
static int query_formats(AVFilterContext *ctx)
FT_Library library
freetype font library handle
planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
double(* eval_func2)(void *, double a, double b)
static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
static const AVFilterPad avfilter_vf_drawtext_outputs[]
#define RGB_TO_Y_CCIR(r, g, b)
uint8_t * expanded_text
used to contain the strftime()-expanded text
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
AVFilterContext * dst
dest filter
int ff_fill_line_with_color(uint8_t *line[4], int pixel_step[4], int w, uint8_t dst_color[4], enum AVPixelFormat pix_fmt, uint8_t rgba_color[4], int *is_packed_rgba, uint8_t rgba_map_ptr[4])
uint8_t boxcolor[4]
background color
static const eval_func2 fun2[]
planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
int fix_bounds
do we let it go out of frame bounds - t/f
uint32_t av_get_random_seed(void)
Get random data.
char * textfile
file with text to be drawn
static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
Load glyphs corresponding to the UTF-32 codepoint code.
void ff_draw_rectangle(uint8_t *dst[4], int dst_linesize[4], uint8_t *src[4], int pixelstep[4], int hsub, int vsub, int x, int y, int w, int h)
int ft_load_flags
flags used for loading fonts, see FT_LOAD_*
void av_tree_enumerate(AVTreeNode *t, void *opaque, int(*cmp)(void *opaque, void *elem), int(*enu)(void *opaque, void *elem))
Apply enu(opaque, &elem) to all the elements in the tree in a given range.
size_t nb_positions
number of elements of positions array
AVPixelFormat
Pixel format.
static int expand_strftime(DrawTextContext *s)
static 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], int alpha_mul)
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
static int normalize_double(int *n, double d)
#define AV_NOPTS_VALUE
Undefined timestamp value.
#define SET_PIXEL_YUV(frame, yuva_color, val, x, y, hsub, vsub)
simple arithmetic expression evaluator