forked from FFmpeg/FFmpeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvf_drawtext.c
1918 lines (1666 loc) · 70 KB
/
vf_drawtext.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2023 Francesco Carusi
* Copyright (c) 2011 Stefano Sabatini
* Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
* Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri@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 vhook/drawtext.c
* filter by Gustavo Sverzut Barbieri
*/
#include "config.h"
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <fenv.h>
#if CONFIG_LIBFONTCONFIG
#include <fontconfig/fontconfig.h>
#endif
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/common.h"
#include "libavutil/eval.h"
#include "libavutil/opt.h"
#include "libavutil/random_seed.h"
#include "libavutil/parseutils.h"
#include "libavutil/time.h"
#include "libavutil/timecode.h"
#include "libavutil/time_internal.h"
#include "libavutil/tree.h"
#include "libavutil/lfg.h"
#include "libavutil/detection_bbox.h"
#include "avfilter.h"
#include "drawutils.h"
#include "formats.h"
#include "internal.h"
#include "textutils.h"
#include "video.h"
#if CONFIG_LIBFRIBIDI
#include <fribidi.h>
#endif
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include FT_STROKER_H
#include <hb.h>
#include <hb-ft.h>
// Ceiling operation for positive integers division
#define POS_CEIL(x, y) ((x)/(y) + ((x)%(y) != 0))
static const char *const var_names[] = {
"dar",
"hsub", "vsub",
"line_h", "lh", ///< line height
"main_h", "h", "H", ///< height of the input video
"main_w", "w", "W", ///< width of the input video
"max_glyph_a", "ascent", ///< max glyph ascender
"max_glyph_d", "descent", ///< min glyph descender
"max_glyph_h", ///< max glyph height
"max_glyph_w", ///< max glyph width
"font_a", ///< font-defined ascent
"font_d", ///< font-defined descent
"top_a", ///< max glyph ascender of the top line
"bottom_d", ///< max glyph descender of the bottom line
"n", ///< number of frame
"sar",
"t", ///< timestamp expressed in seconds
"text_h", "th", ///< height of the rendered text
"text_w", "tw", ///< width of the rendered text
"x",
"y",
"pict_type",
#if FF_API_FRAME_PKT
"pkt_pos",
#endif
#if FF_API_FRAME_PKT
"pkt_size",
#endif
"duration",
NULL
};
static const char *const fun2_names[] = {
"rand"
};
static double drand(void *opaque, double min, double max)
{
return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
}
typedef double (*eval_func2)(void *, double a, double b);
static const eval_func2 fun2[] = {
drand,
NULL
};
enum var_name {
VAR_DAR,
VAR_HSUB, VAR_VSUB,
VAR_LINE_H, VAR_LH,
VAR_MAIN_H, VAR_h, VAR_H,
VAR_MAIN_W, VAR_w, VAR_W,
VAR_MAX_GLYPH_A, VAR_ASCENT,
VAR_MAX_GLYPH_D, VAR_DESCENT,
VAR_MAX_GLYPH_H,
VAR_MAX_GLYPH_W,
VAR_FONT_A,
VAR_FONT_D,
VAR_TOP_A,
VAR_BOTTOM_D,
VAR_N,
VAR_SAR,
VAR_T,
VAR_TEXT_H, VAR_TH,
VAR_TEXT_W, VAR_TW,
VAR_X,
VAR_Y,
VAR_PICT_TYPE,
#if FF_API_FRAME_PKT
VAR_PKT_POS,
#endif
#if FF_API_FRAME_PKT
VAR_PKT_SIZE,
#endif
VAR_DURATION,
VAR_VARS_NB
};
enum expansion_mode {
EXP_NONE,
EXP_NORMAL,
EXP_STRFTIME,
};
enum y_alignment {
YA_TEXT,
YA_BASELINE,
YA_FONT,
};
enum text_alignment {
TA_LEFT = (1 << 0),
TA_RIGHT = (1 << 1),
TA_TOP = (1 << 2),
TA_BOTTOM = (1 << 3),
};
typedef struct HarfbuzzData {
hb_buffer_t* buf;
hb_font_t* font;
unsigned int glyph_count;
hb_glyph_info_t* glyph_info;
hb_glyph_position_t* glyph_pos;
} HarfbuzzData;
/** Information about a single glyph in a text line */
typedef struct GlyphInfo {
uint32_t code; ///< the glyph code point
int x; ///< the x position of the glyph
int y; ///< the y position of the glyph
int shift_x64; ///< the horizontal shift of the glyph in 26.6 units
int shift_y64; ///< the vertical shift of the glyph in 26.6 units
} GlyphInfo;
/** Information about a single line of text */
typedef struct TextLine {
int offset_left64; ///< offset between the origin and
/// the leftmost pixel of the first glyph
int offset_right64; ///< maximum offset between the origin and
/// the rightmost pixel of the last glyph
int width64; ///< width of the line
HarfbuzzData hb_data; ///< libharfbuzz data of this text line
GlyphInfo* glyphs; ///< array of glyphs in this text line
int cluster_offset; ///< the offset at which this line begins
} TextLine;
/** A glyph as loaded and rendered using libfreetype */
typedef struct Glyph {
FT_Glyph glyph;
FT_Glyph border_glyph;
uint32_t code;
unsigned int fontsize;
/** Glyph bitmaps with 1/4 pixel precision in both directions */
FT_BitmapGlyph bglyph[16];
/** Outlined glyph bitmaps with 1/4 pixel precision in both directions */
FT_BitmapGlyph border_bglyph[16];
FT_BBox bbox;
} Glyph;
/** Global text metrics */
typedef struct TextMetrics {
int offset_top64; ///< ascender amount of the first line (in 26.6 units)
int offset_bottom64; ///< descender amount of the last line (in 26.6 units)
int offset_left64; ///< maximum offset between the origin and
/// the leftmost pixel of the first glyph
/// of each line (in 26.6 units)
int offset_right64; ///< maximum offset between the origin and
/// the rightmost pixel of the last glyph
/// of each line (in 26.6 units)
int line_height64; ///< the font-defined line height
int width; ///< width of the longest line - ceil(width64/64)
int height; ///< total height of the text - ceil(height64/64)
int min_y64; ///< minimum value of bbox.yMin among glyphs (in 26.6 units)
int max_y64; ///< maximum value of bbox.yMax among glyphs (in 26.6 units)
int min_x64; ///< minimum value of bbox.xMin among glyphs (in 26.6 units)
int max_x64; ///< maximum value of bbox.xMax among glyphs (in 26.6 units)
// Position of the background box (without borders)
int rect_x; ///< x position of the box
int rect_y; ///< y position of the box
} TextMetrics;
typedef struct DrawTextContext {
const AVClass *class;
int exp_mode; ///< expansion mode to use for the text
FFExpandTextContext expand_text; ///< expand text in case exp_mode == NORMAL
int reinit; ///< tells if the filter is being reinited
#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
AVBPrint expanded_text; ///< used to contain the expanded text
uint8_t *fontcolor_expr; ///< fontcolor expression to evaluate
AVBPrint expanded_fontcolor; ///< used to contain the expanded fontcolor spec
int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
char *textfile; ///< file with text to be drawn
double x; ///< x position to start drawing text
double y; ///< y position to start drawing text
int max_glyph_w; ///< max glyph width
int max_glyph_h; ///< max glyph height
int shadowx, shadowy;
int borderw; ///< border width
char *fontsize_expr; ///< expression for fontsize
AVExpr *fontsize_pexpr; ///< parsed expressions for fontsize
unsigned int fontsize; ///< font size to use
unsigned int default_fontsize; ///< default font size to use
int line_spacing; ///< lines spacing in pixels
short int draw_box; ///< draw box around text - true or false
char *boxborderw; ///< box border width (padding)
/// allowed formats: "all", "vert|oriz", "top|right|bottom|left"
int bb_top; ///< the size of the top box border
int bb_right; ///< the size of the right box border
int bb_bottom; ///< the size of the bottom box border
int bb_left; ///< the size of the left box border
int box_width; ///< the width of box
int box_height; ///< the height of box
int tabsize; ///< tab size
int fix_bounds; ///< do we let it go out of frame bounds - t/f
FFDrawContext dc;
FFDrawColor fontcolor; ///< foreground color
FFDrawColor shadowcolor; ///< shadow color
FFDrawColor bordercolor; ///< border color
FFDrawColor boxcolor; ///< background color
FT_Library library; ///< freetype font library handle
FT_Face face; ///< freetype font face handle
FT_Stroker stroker; ///< freetype stroker handle
struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
char *x_expr; ///< expression for x position
char *y_expr; ///< expression for y position
AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
int64_t basetime; ///< base pts time in the real world for display
double var_values[VAR_VARS_NB];
char *a_expr;
AVExpr *a_pexpr;
int alpha;
AVLFG prng; ///< random
char *tc_opt_string; ///< specified timecode option string
AVRational tc_rate; ///< frame rate for timecode
AVTimecode tc; ///< timecode context
int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
int reload; ///< reload text file at specified frame interval
int start_number; ///< starting frame number for n/frame_num var
char *text_source_string; ///< the string to specify text data source
enum AVFrameSideDataType text_source;
#if CONFIG_LIBFRIBIDI
int text_shaping; ///< 1 to shape the text before drawing it
#endif
AVDictionary *metadata;
int boxw; ///< the value of the boxw parameter
int boxh; ///< the value of the boxh parameter
int text_align; ///< the horizontal and vertical text alignment
int y_align; ///< the value of the y_align parameter
TextLine *lines; ///< computed information about text lines
int line_count; ///< the number of text lines
uint32_t *tab_clusters; ///< the position of tab characters in the text
int tab_count; ///< the number of tab characters
int blank_advance64; ///< the size of the space character
int tab_warning_printed; ///< ensure the tab warning to be printed only once
} DrawTextContext;
#define OFFSET(x) offsetof(DrawTextContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
#define TFLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
static const AVOption drawtext_options[]= {
{"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
{"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, TFLAGS},
{"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
{"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, TFLAGS},
{"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, 0, 0, FLAGS},
{"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, 0, 0, TFLAGS},
{"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, TFLAGS},
{"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, TFLAGS},
{"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, TFLAGS},
{"boxborderw", "set box borders width", OFFSET(boxborderw), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, TFLAGS},
{"line_spacing", "set line spacing in pixels", OFFSET(line_spacing), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
{"fontsize", "set font size", OFFSET(fontsize_expr), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, TFLAGS},
{"text_align", "set text alignment", OFFSET(text_align), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, (TA_LEFT|TA_RIGHT|TA_TOP|TA_BOTTOM), TFLAGS, .unit = "text_align"},
{ "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_LEFT }, .flags = TFLAGS, .unit = "text_align" },
{ "L", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_LEFT }, .flags = TFLAGS, .unit = "text_align" },
{ "right", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_RIGHT }, .flags = TFLAGS, .unit = "text_align" },
{ "R", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_RIGHT }, .flags = TFLAGS, .unit = "text_align" },
{ "center", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_LEFT|TA_RIGHT) }, .flags = TFLAGS, .unit = "text_align" },
{ "C", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_LEFT|TA_RIGHT) }, .flags = TFLAGS, .unit = "text_align" },
{ "top", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_TOP }, .flags = TFLAGS, .unit = "text_align" },
{ "T", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_TOP }, .flags = TFLAGS, .unit = "text_align" },
{ "bottom", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_BOTTOM }, .flags = TFLAGS, .unit = "text_align" },
{ "B", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_BOTTOM }, .flags = TFLAGS, .unit = "text_align" },
{ "middle", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_TOP|TA_BOTTOM) }, .flags = TFLAGS, .unit = "text_align" },
{ "M", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_TOP|TA_BOTTOM) }, .flags = TFLAGS, .unit = "text_align" },
{"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, TFLAGS},
{"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, TFLAGS},
{"boxw", "set box width", OFFSET(boxw), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, TFLAGS},
{"boxh", "set box height", OFFSET(boxh), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, TFLAGS},
{"shadowx", "set shadow x offset", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
{"shadowy", "set shadow y offset", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
{"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
{"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX, TFLAGS},
{"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX, FLAGS},
#if CONFIG_LIBFONTCONFIG
{ "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
#endif
{"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, .unit = "expansion"},
{"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, .unit = "expansion"},
{"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, .unit = "expansion"},
{"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, .unit = "expansion"},
{"y_align", "set the y alignment", OFFSET(y_align), AV_OPT_TYPE_INT, {.i64=YA_TEXT}, 0, 2, TFLAGS, .unit = "y_align"},
{"text", "y is referred to the top of the first text line", OFFSET(y_align), AV_OPT_TYPE_CONST, {.i64=YA_TEXT}, 0, 0, FLAGS, .unit = "y_align"},
{"baseline", "y is referred to the baseline of the first line", OFFSET(y_align), AV_OPT_TYPE_CONST, {.i64=YA_BASELINE}, 0, 0, FLAGS, .unit = "y_align"},
{"font", "y is referred to the font defined line metrics", OFFSET(y_align), AV_OPT_TYPE_CONST, {.i64=YA_FONT}, 0, 0, FLAGS, .unit = "y_align"},
{"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
{"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
{"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
{"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
{"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
{"reload", "reload text file at specified frame interval", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
{"alpha", "apply alpha while rendering", OFFSET(a_expr), AV_OPT_TYPE_STRING, {.str = "1"}, .flags = TFLAGS},
{"fix_bounds", "check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
{"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
{"text_source", "the source of text", OFFSET(text_source_string), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS },
#if CONFIG_LIBFRIBIDI
{"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS},
#endif
/* FT_LOAD_* flags */
{ "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT }, 0, INT_MAX, FLAGS, .unit = "ft_load_flags" },
{ "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
{ "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
{ NULL }
};
AVFILTER_DEFINE_CLASS(drawtext);
#undef __FTERRORS_H__
#define FT_ERROR_START_LIST {
#define FT_ERRORDEF(e, v, s) { (e), (s) },
#define FT_ERROR_END_LIST { 0, NULL } };
static const struct ft_error {
int err;
const char *err_msg;
} ft_errors[] =
#include FT_ERRORS_H
#define FT_ERRMSG(e) ft_errors[e].err_msg
static int glyph_cmp(const void *key, const void *b)
{
const Glyph *a = key, *bb = b;
int64_t diff = (int64_t)a->code - (int64_t)bb->code;
if (diff != 0)
return diff > 0 ? 1 : -1;
else
return FFDIFFSIGN((int64_t)a->fontsize, (int64_t)bb->fontsize);
}
static av_cold int set_fontsize(AVFilterContext *ctx, unsigned int fontsize)
{
int err;
DrawTextContext *s = ctx->priv;
if ((err = FT_Set_Pixel_Sizes(s->face, 0, fontsize))) {
av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
fontsize, FT_ERRMSG(err));
return AVERROR(EINVAL);
}
s->fontsize = fontsize;
return 0;
}
static av_cold int parse_fontsize(AVFilterContext *ctx)
{
DrawTextContext *s = ctx->priv;
int err;
if (s->fontsize_pexpr)
return 0;
if (s->fontsize_expr == NULL)
return AVERROR(EINVAL);
if ((err = av_expr_parse(&s->fontsize_pexpr, s->fontsize_expr, var_names,
NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
return err;
return 0;
}
static av_cold int update_fontsize(AVFilterContext *ctx)
{
DrawTextContext *s = ctx->priv;
unsigned int fontsize = s->default_fontsize;
int err;
double size, roundedsize;
// if no fontsize specified use the default
if (s->fontsize_expr != NULL) {
if ((err = parse_fontsize(ctx)) < 0)
return err;
size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
if (!isnan(size)) {
roundedsize = round(size);
// test for overflow before cast
if (!(roundedsize > INT_MIN && roundedsize < INT_MAX)) {
av_log(ctx, AV_LOG_ERROR, "fontsize overflow\n");
return AVERROR(EINVAL);
}
fontsize = roundedsize;
}
}
if (fontsize == 0)
fontsize = 1;
// no change
if (fontsize == s->fontsize)
return 0;
return set_fontsize(ctx, fontsize);
}
static int load_font_file(AVFilterContext *ctx, const char *path, int index)
{
DrawTextContext *s = ctx->priv;
int err;
err = FT_New_Face(s->library, path, index, &s->face);
if (err) {
#if !CONFIG_LIBFONTCONFIG
av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
s->fontfile, FT_ERRMSG(err));
#endif
return AVERROR(EINVAL);
}
return 0;
}
#if CONFIG_LIBFONTCONFIG
static int load_font_fontconfig(AVFilterContext *ctx)
{
DrawTextContext *s = ctx->priv;
FcConfig *fontconfig;
FcPattern *pat, *best;
FcResult result = FcResultMatch;
FcChar8 *filename;
int index;
double size;
int err = AVERROR(ENOENT);
int parse_err;
fontconfig = FcInitLoadConfigAndFonts();
if (!fontconfig) {
av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
return AVERROR_UNKNOWN;
}
pat = FcNameParse(s->fontfile ? s->fontfile :
(uint8_t *)(intptr_t)"default");
if (!pat) {
av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
return AVERROR(EINVAL);
}
FcPatternAddString(pat, FC_FAMILY, s->font);
parse_err = parse_fontsize(ctx);
if (!parse_err) {
double size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
if (isnan(size)) {
av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
return AVERROR(EINVAL);
}
FcPatternAddDouble(pat, FC_SIZE, size);
}
FcDefaultSubstitute(pat);
if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
FcPatternDestroy(pat);
return AVERROR(ENOMEM);
}
best = FcFontMatch(fontconfig, pat, &result);
FcPatternDestroy(pat);
if (!best || result != FcResultMatch) {
av_log(ctx, AV_LOG_ERROR,
"Cannot find a valid font for the family %s\n",
s->font);
goto fail;
}
if (
FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
return AVERROR(EINVAL);
}
if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
s->font);
goto fail;
}
av_log(ctx, AV_LOG_VERBOSE, "Using \"%s\"\n", filename);
if (parse_err)
s->default_fontsize = size + 0.5;
err = load_font_file(ctx, filename, index);
if (err)
return err;
FcConfigDestroy(fontconfig);
fail:
FcPatternDestroy(best);
return err;
}
#endif
static int load_font(AVFilterContext *ctx)
{
DrawTextContext *s = ctx->priv;
int err;
/* load the face, and set up the encoding, which is by default UTF-8 */
err = load_font_file(ctx, s->fontfile, 0);
if (!err)
return 0;
#if CONFIG_LIBFONTCONFIG
err = load_font_fontconfig(ctx);
if (!err)
return 0;
#endif
return err;
}
#if CONFIG_LIBFRIBIDI
static int shape_text(AVFilterContext *ctx)
{
DrawTextContext *s = ctx->priv;
uint8_t *tmp;
int ret = AVERROR(ENOMEM);
static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
FRIBIDI_FLAGS_ARABIC;
FriBidiChar *unicodestr = NULL;
FriBidiStrIndex len;
FriBidiParType direction = FRIBIDI_PAR_LTR;
FriBidiStrIndex line_start = 0;
FriBidiStrIndex line_end = 0;
FriBidiLevel *embedding_levels = NULL;
FriBidiArabicProp *ar_props = NULL;
FriBidiCharType *bidi_types = NULL;
FriBidiStrIndex i,j;
len = strlen(s->text);
if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
goto out;
}
len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
s->text, len, unicodestr);
bidi_types = av_malloc_array(len, sizeof(*bidi_types));
if (!bidi_types) {
goto out;
}
fribidi_get_bidi_types(unicodestr, len, bidi_types);
embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
if (!embedding_levels) {
goto out;
}
if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
embedding_levels)) {
goto out;
}
ar_props = av_malloc_array(len, sizeof(*ar_props));
if (!ar_props) {
goto out;
}
fribidi_get_joining_types(unicodestr, len, ar_props);
fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
for (line_end = 0, line_start = 0; line_end < len; line_end++) {
if (ff_is_newline(unicodestr[line_end]) || line_end == len - 1) {
if (!fribidi_reorder_line(flags, bidi_types,
line_end - line_start + 1, line_start,
direction, embedding_levels, unicodestr,
NULL)) {
goto out;
}
line_start = line_end + 1;
}
}
/* Remove zero-width fill chars put in by libfribidi */
for (i = 0, j = 0; i < len; i++)
if (unicodestr[i] != FRIBIDI_CHAR_FILL)
unicodestr[j++] = unicodestr[i];
len = j;
if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
/* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
goto out;
}
s->text = tmp;
len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
unicodestr, len, s->text);
ret = 0;
out:
av_free(unicodestr);
av_free(embedding_levels);
av_free(ar_props);
av_free(bidi_types);
return ret;
}
#endif
static enum AVFrameSideDataType text_source_string_parse(const char *text_source_string)
{
av_assert0(text_source_string);
if (!strcmp(text_source_string, "side_data_detection_bboxes")) {
return AV_FRAME_DATA_DETECTION_BBOXES;
} else {
return AVERROR(EINVAL);
}
}
static inline int get_subpixel_idx(int shift_x64, int shift_y64)
{
int idx = (shift_x64 >> 2) + (shift_y64 >> 4);
return idx;
}
// Loads and (optionally) renders a glyph
static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code, int8_t shift_x64, int8_t shift_y64)
{
DrawTextContext *s = ctx->priv;
Glyph dummy = { 0 };
Glyph *glyph;
FT_Vector shift;
struct AVTreeNode *node = NULL;
int ret = 0;
/* get glyph */
dummy.code = code;
dummy.fontsize = s->fontsize;
glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
if (!glyph) {
if (FT_Load_Glyph(s->face, code, s->ft_load_flags)) {
return AVERROR(EINVAL);
}
glyph = av_mallocz(sizeof(*glyph));
if (!glyph) {
ret = AVERROR(ENOMEM);
goto error;
}
glyph->code = code;
glyph->fontsize = s->fontsize;
if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
ret = AVERROR(EINVAL);
goto error;
}
if (s->borderw) {
glyph->border_glyph = glyph->glyph;
if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0)) {
ret = AVERROR_EXTERNAL;
goto error;
}
}
/* measure text height to calculate text_height (or the maximum text height) */
FT_Glyph_Get_CBox(glyph->glyph, FT_GLYPH_BBOX_SUBPIXELS, &glyph->bbox);
/* cache the newly created glyph */
if (!(node = av_tree_node_alloc())) {
ret = AVERROR(ENOMEM);
goto error;
}
av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
} else {
if (s->borderw && !glyph->border_glyph) {
glyph->border_glyph = glyph->glyph;
if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0)) {
ret = AVERROR_EXTERNAL;
goto error;
}
}
}
// Check if a bitmap is needed
if (shift_x64 >= 0 && shift_y64 >= 0) {
// Get the bitmap subpixel index (0 -> 15)
int idx = get_subpixel_idx(shift_x64, shift_y64);
shift.x = shift_x64;
shift.y = shift_y64;
if (!glyph->bglyph[idx]) {
FT_Glyph tmp_glyph = glyph->glyph;
if (FT_Glyph_To_Bitmap(&tmp_glyph, FT_RENDER_MODE_NORMAL, &shift, 0)) {
ret = AVERROR_EXTERNAL;
goto error;
}
glyph->bglyph[idx] = (FT_BitmapGlyph)tmp_glyph;
if (glyph->bglyph[idx]->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
av_log(ctx, AV_LOG_ERROR, "Monocromatic (1bpp) fonts are not supported.\n");
ret = AVERROR(EINVAL);
goto error;
}
}
if (s->borderw && !glyph->border_bglyph[idx]) {
FT_Glyph tmp_glyph = glyph->border_glyph;
if (FT_Glyph_To_Bitmap(&tmp_glyph, FT_RENDER_MODE_NORMAL, &shift, 0)) {
ret = AVERROR_EXTERNAL;
goto error;
}
glyph->border_bglyph[idx] = (FT_BitmapGlyph)tmp_glyph;
}
}
if (glyph_ptr) {
*glyph_ptr = glyph;
}
return 0;
error:
if (glyph && glyph->glyph)
FT_Done_Glyph(glyph->glyph);
av_freep(&glyph);
av_freep(&node);
return ret;
}
// Convert a string formatted as "n1|n2|...|nN" into an integer array
static int string_to_array(const char *source, int *result, int result_size)
{
int counter = 0, size = strlen(source) + 1;
char *saveptr, *curval, *dup = av_malloc(size);
if (!dup)
return 0;
av_strlcpy(dup, source, size);
if (result_size > 0 && (curval = av_strtok(dup, "|", &saveptr))) {
do {
result[counter++] = atoi(curval);
} while ((curval = av_strtok(NULL, "|", &saveptr)) && counter < result_size);
}
av_free(dup);
return counter;
}
static int func_pict_type(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
{
DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
return 0;
}
static int func_pts(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
{
DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
const char *fmt;
const char *strftime_fmt = NULL;
const char *delta = NULL;
double pts = s->var_values[VAR_T];
// argv: pts, FMT, [DELTA, 24HH | strftime_fmt]
fmt = argc >= 1 ? argv[0] : "flt";
if (argc >= 2) {
delta = argv[1];
}
if (argc >= 3) {
if (!strcmp(fmt, "hms")) {
if (!strcmp(argv[2], "24HH")) {
av_log(ctx, AV_LOG_WARNING, "pts third argument 24HH is deprected, use pts:hms24hh instead\n");
fmt = "hms24";
} else {
av_log(ctx, AV_LOG_ERROR, "Invalid argument '%s', '24HH' was expected\n", argv[2]);
return AVERROR(EINVAL);
}
} else {
strftime_fmt = argv[2];
}
}
return ff_print_pts(ctx, bp, pts, delta, fmt, strftime_fmt);
}
static int func_frame_num(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
{
DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
return 0;
}
static int func_metadata(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
{
DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
if (e && e->value)
av_bprintf(bp, "%s", e->value);
else if (argc >= 2)
av_bprintf(bp, "%s", argv[1]);
return 0;
}
static int func_strftime(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
{
const char *strftime_fmt = argc ? argv[0] : NULL;
return ff_print_time(ctx, bp, strftime_fmt, !strcmp(function_name, "localtime"));
}
static int func_eval_expr(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
{
DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
return ff_print_eval_expr(ctx, bp, argv[0],
fun2_names, fun2,
var_names, s->var_values, &s->prng);
}
static int func_eval_expr_int_format(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
{
DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
int ret;
int positions = -1;
/*
* argv[0] expression to be converted to `int`
* argv[1] format: 'x', 'X', 'd' or 'u'
* argv[2] positions printed (optional)
*/
if (argc == 3) {
ret = sscanf(argv[2], "%u", &positions);
if (ret != 1) {
av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
" to print: '%s'\n", argv[2]);
return AVERROR(EINVAL);
}
}
return ff_print_formatted_eval_expr(ctx, bp, argv[0],
fun2_names, fun2,
var_names, s->var_values,
&s->prng,
argv[1][0], positions);
}
static FFExpandTextFunction expand_text_functions[] = {
{ "e", 1, 1, func_eval_expr },
{ "eif", 2, 3, func_eval_expr_int_format },
{ "expr", 1, 1, func_eval_expr },
{ "expr_int_format", 2, 3, func_eval_expr_int_format },
{ "frame_num", 0, 0, func_frame_num },
{ "gmtime", 0, 1, func_strftime },
{ "localtime", 0, 1, func_strftime },
{ "metadata", 1, 2, func_metadata },
{ "n", 0, 0, func_frame_num },
{ "pict_type", 0, 0, func_pict_type },
{ "pts", 0, 3, func_pts }
};
static av_cold int init(AVFilterContext *ctx)
{
int err;
DrawTextContext *s = ctx->priv;
av_expr_free(s->fontsize_pexpr);
s->fontsize_pexpr = NULL;
s->fontsize = 0;
s->default_fontsize = 16;
if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
return AVERROR(EINVAL);
}
if (s->textfile) {
if (s->text) {
av_log(ctx, AV_LOG_ERROR,
"Both text and text file provided. Please provide only one\n");
return AVERROR(EINVAL);
}
if ((err = ff_load_textfile(ctx, (const char *)s->textfile, &s->text, NULL)) < 0)
return err;
}
if (s->reload && !s->textfile)
av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
if (s->tc_opt_string) {
int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
s->tc_opt_string, ctx);
if (ret < 0)
return ret;
if (s->tc24hmax)