drawtext.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /*
  2. * drawtext.c: print text over the screen
  3. ******************************************************************************
  4. * Options:
  5. * -f <filename> font filename (MANDATORY!!!)
  6. * -s <pixel_size> font size in pixels [default 16]
  7. * -b print background
  8. * -o outline glyphs (use the bg color)
  9. * -x <pos> x position ( >= 0) [default 0]
  10. * -y <pos> y position ( >= 0) [default 0]
  11. * -t <text> text to print (will be passed to strftime())
  12. * MANDATORY: will be used even when -T is used.
  13. * in this case, -t will be used if some error
  14. * occurs
  15. * -T <filename> file with the text (re-read every frame)
  16. * -c <#RRGGBB> foreground color ('internet' way) [default #ffffff]
  17. * -C <#RRGGBB> background color ('internet' way) [default #000000]
  18. *
  19. ******************************************************************************
  20. * Features:
  21. * - True Type, Type1 and others via FreeType2 library
  22. * - Font kerning (better output)
  23. * - Line Wrap (if the text doesn't fit, the next char go to the next line)
  24. * - Background box
  25. * - Outline
  26. ******************************************************************************
  27. * Author: Gustavo Sverzut Barbieri <gsbarbieri@yahoo.com.br>
  28. *
  29. * This file is part of FFmpeg.
  30. *
  31. * FFmpeg is free software; you can redistribute it and/or
  32. * modify it under the terms of the GNU Lesser General Public
  33. * License as published by the Free Software Foundation; either
  34. * version 2.1 of the License, or (at your option) any later version.
  35. *
  36. * FFmpeg is distributed in the hope that it will be useful,
  37. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  38. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  39. * Lesser General Public License for more details.
  40. *
  41. * You should have received a copy of the GNU Lesser General Public
  42. * License along with FFmpeg; if not, write to the Free Software
  43. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  44. */
  45. #define MAXSIZE_TEXT 1024
  46. #include "libavformat/framehook.h"
  47. #include <stdio.h>
  48. #include <stdlib.h>
  49. #include <fcntl.h>
  50. #include <stdarg.h>
  51. #include <string.h>
  52. #include <unistd.h>
  53. #undef time
  54. #include <sys/time.h>
  55. #include <time.h>
  56. #include <ft2build.h>
  57. #include FT_FREETYPE_H
  58. #include FT_GLYPH_H
  59. #define SCALEBITS 10
  60. #define ONE_HALF (1 << (SCALEBITS - 1))
  61. #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
  62. #define RGB_TO_YUV(rgb_color, yuv_color) do { \
  63. yuv_color[0] = (FIX(0.29900) * rgb_color[0] + FIX(0.58700) * rgb_color[1] + FIX(0.11400) * rgb_color[2] + ONE_HALF) >> SCALEBITS; \
  64. yuv_color[2] = ((FIX(0.50000) * rgb_color[0] - FIX(0.41869) * rgb_color[1] - FIX(0.08131) * rgb_color[2] + ONE_HALF - 1) >> SCALEBITS) + 128; \
  65. yuv_color[1] = ((- FIX(0.16874) * rgb_color[0] - FIX(0.33126) * rgb_color[1] + FIX(0.50000) * rgb_color[2] + ONE_HALF - 1) >> SCALEBITS) + 128; \
  66. } while (0)
  67. #define COPY_3(dst,src) { \
  68. dst[0]=src[0]; \
  69. dst[1]=src[1]; \
  70. dst[2]=src[2]; \
  71. }
  72. #define SET_PIXEL(picture, yuv_color, x, y) { \
  73. picture->data[0][ (x) + (y)*picture->linesize[0] ] = yuv_color[0]; \
  74. picture->data[1][ ((x/2) + (y/2)*picture->linesize[1]) ] = yuv_color[1]; \
  75. picture->data[2][ ((x/2) + (y/2)*picture->linesize[2]) ] = yuv_color[2]; \
  76. }
  77. #define GET_PIXEL(picture, yuv_color, x, y) { \
  78. yuv_color[0] = picture->data[0][ (x) + (y)*picture->linesize[0] ]; \
  79. yuv_color[1] = picture->data[1][ (x/2) + (y/2)*picture->linesize[1] ]; \
  80. yuv_color[2] = picture->data[2][ (x/2) + (y/2)*picture->linesize[2] ]; \
  81. }
  82. typedef struct {
  83. unsigned char *text;
  84. char *file;
  85. unsigned int x;
  86. unsigned int y;
  87. int bg;
  88. int outline;
  89. unsigned char bgcolor[3]; /* YUV */
  90. unsigned char fgcolor[3]; /* YUV */
  91. FT_Library library;
  92. FT_Face face;
  93. FT_Glyph glyphs[ 255 ];
  94. FT_Bitmap bitmaps[ 255 ];
  95. int advance[ 255 ];
  96. int bitmap_left[ 255 ];
  97. int bitmap_top[ 255 ];
  98. unsigned int glyphs_index[ 255 ];
  99. int text_height;
  100. int baseline;
  101. int use_kerning;
  102. } ContextInfo;
  103. void Release(void *ctx)
  104. {
  105. if (ctx)
  106. av_free(ctx);
  107. }
  108. static int ParseColor(char *text, unsigned char yuv_color[3])
  109. {
  110. char tmp[3];
  111. unsigned char rgb_color[3];
  112. int i;
  113. tmp[2] = '\0';
  114. if ((!text) || (strlen(text) != 7) || (text[0] != '#') )
  115. return -1;
  116. for (i=0; i < 3; i++)
  117. {
  118. tmp[0] = text[i*2+1];
  119. tmp[1] = text[i*2+2];
  120. rgb_color[i] = strtol(tmp, NULL, 16);
  121. }
  122. RGB_TO_YUV(rgb_color, yuv_color);
  123. return 0;
  124. }
  125. int Configure(void **ctxp, int argc, char *argv[])
  126. {
  127. int c;
  128. int error;
  129. ContextInfo *ci=NULL;
  130. char *font=NULL;
  131. unsigned int size=16;
  132. FT_BBox bbox;
  133. int yMax, yMin;
  134. *ctxp = av_mallocz(sizeof(ContextInfo));
  135. ci = (ContextInfo *) *ctxp;
  136. /* configure Context Info */
  137. ci->text = NULL;
  138. ci->file = NULL;
  139. ci->x = ci->y = 0;
  140. ci->fgcolor[0]=255;
  141. ci->fgcolor[1]=128;
  142. ci->fgcolor[2]=128;
  143. ci->bgcolor[0]=0;
  144. ci->fgcolor[1]=128;
  145. ci->fgcolor[2]=128;
  146. ci->bg = 0;
  147. ci->outline = 0;
  148. ci->text_height = 0;
  149. optind = 1;
  150. while ((c = getopt(argc, argv, "f:t:T:x:y:s:c:C:bo")) > 0) {
  151. switch (c) {
  152. case 'f':
  153. font = optarg;
  154. break;
  155. case 't':
  156. ci->text = av_strdup(optarg);
  157. break;
  158. case 'T':
  159. ci->file = av_strdup(optarg);
  160. break;
  161. case 'x':
  162. ci->x = (unsigned int) atoi(optarg);
  163. break;
  164. case 'y':
  165. ci->y = (unsigned int) atoi(optarg);
  166. break;
  167. case 's':
  168. size = (unsigned int) atoi(optarg);
  169. break;
  170. case 'c':
  171. if (ParseColor(optarg, ci->fgcolor) == -1)
  172. {
  173. av_log(NULL, AV_LOG_ERROR, "Invalid foreground color: '%s'. You must specify the color in the internet way(packaged hex): #RRGGBB, ie: -c #ffffff (for white foreground)\n", optarg);
  174. return -1;
  175. }
  176. break;
  177. case 'C':
  178. if (ParseColor(optarg, ci->bgcolor) == -1)
  179. {
  180. av_log(NULL, AV_LOG_ERROR, "Invalid background color: '%s'. You must specify the color in the internet way(packaged hex): #RRGGBB, ie: -C #ffffff (for white background)\n", optarg);
  181. return -1;
  182. }
  183. break;
  184. case 'b':
  185. ci->bg=1;
  186. break;
  187. case 'o':
  188. ci->outline=1;
  189. break;
  190. case '?':
  191. av_log(NULL, AV_LOG_ERROR, "Unrecognized argument '%s'\n", argv[optind]);
  192. return -1;
  193. }
  194. }
  195. if (!ci->text)
  196. {
  197. av_log(NULL, AV_LOG_ERROR, "No text provided (-t text)\n");
  198. return -1;
  199. }
  200. if (ci->file)
  201. {
  202. FILE *fp;
  203. if ((fp=fopen(ci->file, "r")) == NULL)
  204. {
  205. av_log(NULL, AV_LOG_INFO, "WARNING: The file could not be opened. Using text provided with -t switch: %s", strerror(errno));
  206. }
  207. else
  208. {
  209. fclose(fp);
  210. }
  211. }
  212. if (!font)
  213. {
  214. av_log(NULL, AV_LOG_ERROR, "No font file provided! (-f filename)\n");
  215. return -1;
  216. }
  217. if ((error = FT_Init_FreeType(&(ci->library))) != 0)
  218. {
  219. av_log(NULL, AV_LOG_ERROR, "Could not load FreeType (error# %d).\n", error);
  220. return -1;
  221. }
  222. if ((error = FT_New_Face( ci->library, font, 0, &(ci->face) )) != 0)
  223. {
  224. av_log(NULL, AV_LOG_ERROR, "Could not load face: %s (error# %d).\n", font, error);
  225. return -1;
  226. }
  227. if ((error = FT_Set_Pixel_Sizes( ci->face, 0, size)) != 0)
  228. {
  229. av_log(NULL, AV_LOG_ERROR, "Could not set font size to %d pixels (error# %d).\n", size, error);
  230. return -1;
  231. }
  232. ci->use_kerning = FT_HAS_KERNING(ci->face);
  233. /* load and cache glyphs */
  234. yMax = -32000;
  235. yMin = 32000;
  236. for (c=0; c < 256; c++)
  237. {
  238. /* Load char */
  239. error = FT_Load_Char( ci->face, (unsigned char) c, FT_LOAD_RENDER | FT_LOAD_MONOCHROME );
  240. if (error) continue; /* ignore errors */
  241. /* Save bitmap */
  242. ci->bitmaps[c] = ci->face->glyph->bitmap;
  243. /* Save bitmap left */
  244. ci->bitmap_left[c] = ci->face->glyph->bitmap_left;
  245. /* Save bitmap top */
  246. ci->bitmap_top[c] = ci->face->glyph->bitmap_top;
  247. /* Save advance */
  248. ci->advance[c] = ci->face->glyph->advance.x >> 6;
  249. /* Save glyph */
  250. error = FT_Get_Glyph( ci->face->glyph, &(ci->glyphs[c]) );
  251. /* Save glyph index */
  252. ci->glyphs_index[c] = FT_Get_Char_Index( ci->face, (unsigned char) c );
  253. /* Measure text height to calculate text_height (or the maximum text height) */
  254. FT_Glyph_Get_CBox( ci->glyphs[ c ], ft_glyph_bbox_pixels, &bbox );
  255. if (bbox.yMax > yMax)
  256. yMax = bbox.yMax;
  257. if (bbox.yMin < yMin)
  258. yMin = bbox.yMin;
  259. }
  260. ci->text_height = yMax - yMin;
  261. ci->baseline = yMax;
  262. return 0;
  263. }
  264. static inline void draw_glyph(AVPicture *picture, FT_Bitmap *bitmap, unsigned int x, unsigned int y, unsigned int width, unsigned int height, unsigned char yuv_fgcolor[3], unsigned char yuv_bgcolor[3], int outline)
  265. {
  266. int r, c;
  267. int spixel, dpixel[3], in_glyph=0;
  268. if (bitmap->pixel_mode == ft_pixel_mode_mono)
  269. {
  270. in_glyph = 0;
  271. for (r=0; (r < bitmap->rows) && (r+y < height); r++)
  272. {
  273. for (c=0; (c < bitmap->width) && (c+x < width); c++)
  274. {
  275. /* pixel in the picture (destination) */
  276. GET_PIXEL(picture, dpixel, (c+x), (y+r));
  277. /* pixel in the glyph bitmap (source) */
  278. spixel = bitmap->buffer[r*bitmap->pitch +c/8] & (0x80>>(c%8));
  279. if (spixel)
  280. COPY_3(dpixel, yuv_fgcolor);
  281. if (outline)
  282. {
  283. /* border detection: */
  284. if ( (!in_glyph) && (spixel) )
  285. /* left border detected */
  286. {
  287. in_glyph = 1;
  288. /* draw left pixel border */
  289. if (c-1 >= 0)
  290. SET_PIXEL(picture, yuv_bgcolor, (c+x-1), (y+r));
  291. }
  292. else if ( (in_glyph) && (!spixel) )
  293. /* right border detected */
  294. {
  295. in_glyph = 0;
  296. /* 'draw' right pixel border */
  297. COPY_3(dpixel, yuv_bgcolor);
  298. }
  299. if (in_glyph)
  300. /* see if we have a top/bottom border */
  301. {
  302. /* top */
  303. if ( (r-1 >= 0) && (! bitmap->buffer[(r-1)*bitmap->pitch +c/8] & (0x80>>(c%8))) )
  304. /* we have a top border */
  305. SET_PIXEL(picture, yuv_bgcolor, (c+x), (y+r-1));
  306. /* bottom */
  307. if ( (r+1 < height) && (! bitmap->buffer[(r+1)*bitmap->pitch +c/8] & (0x80>>(c%8))) )
  308. /* we have a bottom border */
  309. SET_PIXEL(picture, yuv_bgcolor, (c+x), (y+r+1));
  310. }
  311. }
  312. SET_PIXEL(picture, dpixel, (c+x), (y+r));
  313. }
  314. }
  315. }
  316. }
  317. static inline void draw_box(AVPicture *picture, unsigned int x, unsigned int y, unsigned int width, unsigned int height, unsigned char yuv_color[3])
  318. {
  319. int i, j;
  320. for (j = 0; (j < height); j++)
  321. for (i = 0; (i < width); i++)
  322. {
  323. SET_PIXEL(picture, yuv_color, (i+x), (y+j));
  324. }
  325. }
  326. void Process(void *ctx, AVPicture *picture, enum PixelFormat pix_fmt, int width, int height, int64_t pts)
  327. {
  328. ContextInfo *ci = (ContextInfo *) ctx;
  329. FT_Face face = ci->face;
  330. FT_GlyphSlot slot = face->glyph;
  331. unsigned char *text = ci->text;
  332. unsigned char c;
  333. int x = 0, y = 0, i=0, size=0;
  334. unsigned char buff[MAXSIZE_TEXT];
  335. unsigned char tbuff[MAXSIZE_TEXT];
  336. time_t now = time(0);
  337. int str_w, str_w_max;
  338. FT_Vector pos[MAXSIZE_TEXT];
  339. FT_Vector delta;
  340. if (ci->file)
  341. {
  342. int fd = open(ci->file, O_RDONLY);
  343. if (fd < 0)
  344. {
  345. text = ci->text;
  346. av_log(NULL, AV_LOG_INFO, "WARNING: The file could not be opened. Using text provided with -t switch: %s", strerror(errno));
  347. }
  348. else
  349. {
  350. int l = read(fd, tbuff, sizeof(tbuff) - 1);
  351. if (l >= 0)
  352. {
  353. tbuff[l] = 0;
  354. text = tbuff;
  355. }
  356. else
  357. {
  358. text = ci->text;
  359. av_log(NULL, AV_LOG_INFO, "WARNING: The file could not be read. Using text provided with -t switch: %s", strerror(errno));
  360. }
  361. close(fd);
  362. }
  363. }
  364. else
  365. {
  366. text = ci->text;
  367. }
  368. strftime(buff, sizeof(buff), text, localtime(&now));
  369. text = buff;
  370. size = strlen(text);
  371. /* measure string size and save glyphs position*/
  372. str_w = str_w_max = 0;
  373. x = ci->x;
  374. y = ci->y;
  375. for (i=0; i < size; i++)
  376. {
  377. c = text[i];
  378. /* kerning */
  379. if ( (ci->use_kerning) && (i > 0) && (ci->glyphs_index[c]) )
  380. {
  381. FT_Get_Kerning( ci->face,
  382. ci->glyphs_index[ text[i-1] ],
  383. ci->glyphs_index[c],
  384. ft_kerning_default,
  385. &delta );
  386. x += delta.x >> 6;
  387. }
  388. if (( (x + ci->advance[ c ]) >= width ) || ( c == '\n' ))
  389. {
  390. str_w = width - ci->x - 1;
  391. y += ci->text_height;
  392. x = ci->x;
  393. }
  394. /* save position */
  395. pos[i].x = x + ci->bitmap_left[c];
  396. pos[i].y = y - ci->bitmap_top[c] + ci->baseline;
  397. x += ci->advance[c];
  398. if (str_w > str_w_max)
  399. str_w_max = str_w;
  400. }
  401. if (ci->bg)
  402. {
  403. /* Check if it doesn't pass the limits */
  404. if ( str_w_max + ci->x >= width )
  405. str_w_max = width - ci->x - 1;
  406. if ( y >= height )
  407. y = height - 1 - 2*ci->y;
  408. /* Draw Background */
  409. draw_box( picture, ci->x, ci->y, str_w_max, y - ci->y, ci->bgcolor );
  410. }
  411. /* Draw Glyphs */
  412. for (i=0; i < size; i++)
  413. {
  414. c = text[i];
  415. if (
  416. ( (c == '_') && (text == ci->text) ) || /* skip '_' (consider as space)
  417. IF text was specified in cmd line
  418. (which doesn't like nested quotes) */
  419. ( c == '\n' ) /* Skip new line char, just go to new line */
  420. )
  421. continue;
  422. /* now, draw to our target surface */
  423. draw_glyph( picture,
  424. &(ci->bitmaps[ c ]),
  425. pos[i].x,
  426. pos[i].y,
  427. width,
  428. height,
  429. ci->fgcolor,
  430. ci->bgcolor,
  431. ci->outline );
  432. /* increment pen position */
  433. x += slot->advance.x >> 6;
  434. }
  435. }