ppm vhook follow up patch by (Charles Yates <charles dot yates at pandora dot be>)
[libav.git] / vhook / drawtext.c
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 library is free software; you can redistribute it and/or
30 * modify it under the terms of the GNU Lesser General Public
31 * License as published by the Free Software Foundation; either
32 * version 2 of the License, or (at your option) any later version.
33 *
34 * This library is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
37 * Lesser General Public License for more details.
38 *
39 * You should have received a copy of the GNU Lesser General Public
40 * License along with this library; if not, write to the Free Software
41 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
42 */
43
44 #define MAXSIZE_TEXT 1024
45
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <fcntl.h>
49 #include <stdarg.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <sys/time.h>
53 #include <time.h>
54
55 #include "framehook.h"
56
57 #include <ft2build.h>
58 #include FT_FREETYPE_H
59 #include FT_GLYPH_H
60
61 #define RGB_TO_YUV(rgb_color, yuv_color) { \
62 yuv_color[0] = ( 0.257 * rgb_color[0]) + (0.504 * rgb_color[1]) + (0.098 * rgb_color[2]) + 16; \
63 yuv_color[2] = ( 0.439 * rgb_color[0]) - (0.368 * rgb_color[1]) - (0.071 * rgb_color[2]) + 128; \
64 yuv_color[1] = (-0.148 * rgb_color[0]) - (0.291 * rgb_color[1]) + (0.439 * rgb_color[2]) + 128; \
65 }
66
67 #define COPY_3(dst,src) { \
68 dst[0]=src[0]; \
69 dst[1]=src[1]; \
70 dst[2]=src[2]; \
71 }
72
73
74
75 #define SET_PIXEL(picture, yuv_color, x, y) { \
76 picture->data[0][ (x) + (y)*picture->linesize[0] ] = yuv_color[0]; \
77 picture->data[1][ ((x/2) + (y/2)*picture->linesize[1]) ] = yuv_color[1]; \
78 picture->data[2][ ((x/2) + (y/2)*picture->linesize[2]) ] = yuv_color[2]; \
79 }
80
81 #define GET_PIXEL(picture, yuv_color, x, y) { \
82 yuv_color[0] = picture->data[0][ (x) + (y)*picture->linesize[0] ]; \
83 yuv_color[1] = picture->data[1][ (x/2) + (y/2)*picture->linesize[1] ]; \
84 yuv_color[2] = picture->data[2][ (x/2) + (y/2)*picture->linesize[2] ]; \
85 }
86
87
88 typedef struct {
89 unsigned char *text;
90 unsigned char *file;
91 unsigned int x;
92 unsigned int y;
93 int bg;
94 int outline;
95 unsigned char bgcolor[3]; /* YUV */
96 unsigned char fgcolor[3]; /* YUV */
97 FT_Library library;
98 FT_Face face;
99 FT_Glyph glyphs[ 255 ];
100 FT_Bitmap bitmaps[ 255 ];
101 int advance[ 255 ];
102 int bitmap_left[ 255 ];
103 int bitmap_top[ 255 ];
104 unsigned int glyphs_index[ 255 ];
105 int text_height;
106 int baseline;
107 int use_kerning;
108 } ContextInfo;
109
110
111 void Release(void *ctx)
112 {
113 if (ctx)
114 av_free(ctx);
115 }
116
117
118 int ParseColor(char *text, unsigned char yuv_color[3])
119 {
120 char tmp[3];
121 unsigned char rgb_color[3];
122 int i;
123
124 tmp[2] = '\0';
125
126 if ((!text) || (strlen(text) != 7) || (text[0] != '#') )
127 return -1;
128
129 for (i=0; i < 3; i++)
130 {
131 tmp[0] = text[i*2+1];
132 tmp[1] = text[i*2+2];
133
134 rgb_color[i] = strtol(tmp, NULL, 16);
135 }
136
137 RGB_TO_YUV(rgb_color, yuv_color);
138
139 return 0;
140 }
141
142 int Configure(void **ctxp, int argc, char *argv[])
143 {
144 int c;
145 int error;
146 ContextInfo *ci=NULL;
147 char *font=NULL;
148 unsigned int size=16;
149 FT_BBox bbox;
150 int yMax, yMin;
151 *ctxp = av_mallocz(sizeof(ContextInfo));
152 ci = (ContextInfo *) *ctxp;
153
154 /* configure Context Info */
155 ci->text = NULL;
156 ci->file = NULL;
157 ci->x = ci->y = 0;
158 ci->fgcolor[0]=255;
159 ci->fgcolor[1]=128;
160 ci->fgcolor[2]=128;
161 ci->bgcolor[0]=0;
162 ci->fgcolor[1]=128;
163 ci->fgcolor[2]=128;
164 ci->bg = 0;
165 ci->outline = 0;
166 ci->text_height = 0;
167
168 optind = 0;
169 while ((c = getopt(argc, argv, "f:t:T:x:y:s:c:C:bo")) > 0) {
170 switch (c) {
171 case 'f':
172 font = optarg;
173 break;
174 case 't':
175 ci->text = av_strdup(optarg);
176 break;
177 case 'T':
178 ci->file = av_strdup(optarg);
179 break;
180 case 'x':
181 ci->x = (unsigned int) atoi(optarg);
182 break;
183 case 'y':
184 ci->y = (unsigned int) atoi(optarg);
185 break;
186 case 's':
187 size = (unsigned int) atoi(optarg);
188 break;
189 case 'c':
190 if (ParseColor(optarg, ci->fgcolor) == -1)
191 {
192 fprintf(stderr, "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);
193 return -1;
194 }
195 break;
196 case 'C':
197 if (ParseColor(optarg, ci->bgcolor) == -1)
198 {
199 fprintf(stderr, "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);
200 return -1;
201 }
202 break;
203 case 'b':
204 ci->bg=1;
205 break;
206 case 'o':
207 ci->outline=1;
208 break;
209 case '?':
210 fprintf(stderr, "ERROR: Unrecognized argument '%s'\n", argv[optind]);
211 return -1;
212 }
213 }
214
215 if (!ci->text)
216 {
217 fprintf(stderr,"ERROR: No text provided (-t text)\n");
218 return -1;
219 }
220
221 if (ci->file)
222 {
223 FILE *fp;
224 if ((fp=fopen(ci->file, "r")) == NULL)
225 {
226 perror("WARNING: the file could not be opened. Using text provided with -t switch. ");
227 }
228 else
229 {
230 fclose(fp);
231 }
232 }
233
234 if (!font)
235 {
236 fprintf(stderr,"ERROR: No font file provided! (-f filename)\n");
237 return -1;
238 }
239
240 if ((error = FT_Init_FreeType(&(ci->library))) != 0)
241 {
242 fprintf(stderr,"ERROR: Could not load FreeType (error# %d)\n",error);
243 return -1;
244 }
245
246 if ((error = FT_New_Face( ci->library, font, 0, &(ci->face) )) != 0)
247 {
248 fprintf(stderr,"ERROR: Could not load face: %s (error# %d)\n",font, error);
249 return -1;
250 }
251
252 if ((error = FT_Set_Pixel_Sizes( ci->face, 0, size)) != 0)
253 {
254 fprintf(stderr,"ERROR: Could not set font size to %d pixels (error# %d)\n",size, error);
255 return -1;
256 }
257
258 ci->use_kerning = FT_HAS_KERNING(ci->face);
259
260 /* load and cache glyphs */
261 yMax = -32000;
262 yMin = 32000;
263 for (c=0; c < 256; c++)
264 {
265 /* Load char */
266 error = FT_Load_Char( ci->face, (unsigned char) c, FT_LOAD_RENDER | FT_LOAD_MONOCHROME );
267 if (error) continue; /* ignore errors */
268
269 /* Save bitmap */
270 ci->bitmaps[c] = ci->face->glyph->bitmap;
271 /* Save bitmap left */
272 ci->bitmap_left[c] = ci->face->glyph->bitmap_left;
273 /* Save bitmap top */
274 ci->bitmap_top[c] = ci->face->glyph->bitmap_top;
275
276 /* Save advance */
277 ci->advance[c] = ci->face->glyph->advance.x >> 6;
278
279 /* Save glyph */
280 error = FT_Get_Glyph( ci->face->glyph, &(ci->glyphs[c]) );
281 /* Save glyph index */
282 ci->glyphs_index[c] = FT_Get_Char_Index( ci->face, (unsigned char) c );
283
284 /* Measure text height to calculate text_height (or the maximum text height) */
285 FT_Glyph_Get_CBox( ci->glyphs[ c ], ft_glyph_bbox_pixels, &bbox );
286 if (bbox.yMax > yMax)
287 yMax = bbox.yMax;
288 if (bbox.yMin < yMin)
289 yMin = bbox.yMin;
290
291 }
292
293 ci->text_height = yMax - yMin;
294 ci->baseline = yMax;
295
296 return 0;
297 }
298
299
300
301
302 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)
303 {
304 int r, c;
305 int spixel, dpixel[3], in_glyph=0;
306
307 if (bitmap->pixel_mode == ft_pixel_mode_mono)
308 {
309 in_glyph = 0;
310 for (r=0; (r < bitmap->rows) && (r+y < height); r++)
311 {
312 for (c=0; (c < bitmap->width) && (c+x < width); c++)
313 {
314 /* pixel in the picture (destination) */
315 GET_PIXEL(picture, dpixel, (c+x), (y+r));
316
317 /* pixel in the glyph bitmap (source) */
318 spixel = bitmap->buffer[r*bitmap->pitch +c/8] & (0x80>>(c%8));
319
320 if (spixel)
321 COPY_3(dpixel, yuv_fgcolor);
322
323 if (outline)
324 {
325 /* border detection: */
326 if ( (!in_glyph) && (spixel) )
327 /* left border detected */
328 {
329 in_glyph = 1;
330 /* draw left pixel border */
331 if (c-1 >= 0)
332 SET_PIXEL(picture, yuv_bgcolor, (c+x-1), (y+r));
333 }
334 else if ( (in_glyph) && (!spixel) )
335 /* right border detected */
336 {
337 in_glyph = 0;
338 /* 'draw' right pixel border */
339 COPY_3(dpixel, yuv_bgcolor);
340 }
341
342 if (in_glyph)
343 /* see if we have a top/bottom border */
344 {
345 /* top */
346 if ( (r-1 >= 0) && (! bitmap->buffer[(r-1)*bitmap->pitch +c/8] & (0x80>>(c%8))) )
347 /* we have a top border */
348 SET_PIXEL(picture, yuv_bgcolor, (c+x), (y+r-1));
349
350 /* bottom */
351 if ( (r+1 < height) && (! bitmap->buffer[(r+1)*bitmap->pitch +c/8] & (0x80>>(c%8))) )
352 /* we have a bottom border */
353 SET_PIXEL(picture, yuv_bgcolor, (c+x), (y+r+1));
354
355 }
356 }
357
358 SET_PIXEL(picture, dpixel, (c+x), (y+r));
359 }
360 }
361 }
362 }
363
364
365 inline void draw_box(AVPicture *picture, unsigned int x, unsigned int y, unsigned int width, unsigned int height, unsigned char yuv_color[3])
366 {
367 int i, j;
368
369 for (j = 0; (j < height); j++)
370 for (i = 0; (i < width); i++)
371 {
372 SET_PIXEL(picture, yuv_color, (i+x), (y+j));
373 }
374
375 }
376
377
378
379
380 void Process(void *ctx, AVPicture *picture, enum PixelFormat pix_fmt, int width, int height, int64_t pts)
381 {
382 ContextInfo *ci = (ContextInfo *) ctx;
383 FT_Face face = ci->face;
384 FT_GlyphSlot slot = face->glyph;
385 unsigned char *text = ci->text;
386 unsigned char c;
387 int x = 0, y = 0, i=0, size=0;
388 unsigned char buff[MAXSIZE_TEXT];
389 unsigned char tbuff[MAXSIZE_TEXT];
390 time_t now = time(0);
391 int str_w, str_w_max;
392 FT_Vector pos[MAXSIZE_TEXT];
393 FT_Vector delta;
394
395 if (ci->file)
396 {
397 int fd = open(ci->file, O_RDONLY);
398
399 if (fd < 0)
400 {
401 text = ci->text;
402 perror("WARNING: the file could not be opened. Using text provided with -t switch. ");
403 }
404 else
405 {
406 int l = read(fd, tbuff, sizeof(tbuff) - 1);
407
408 if (l >= 0)
409 {
410 tbuff[l] = 0;
411 text = tbuff;
412 }
413 else
414 {
415 text = ci->text;
416 perror("WARNING: the file could not be opened. Using text provided with -t switch. ");
417 }
418 close(fd);
419 }
420 }
421 else
422 {
423 text = ci->text;
424 }
425
426 strftime(buff, sizeof(buff), text, localtime(&now));
427
428 text = buff;
429
430 size = strlen(text);
431
432
433
434
435 /* measure string size and save glyphs position*/
436 str_w = str_w_max = 0;
437 x = ci->x;
438 y = ci->y;
439 for (i=0; i < size; i++)
440 {
441 c = text[i];
442
443 /* kerning */
444 if ( (ci->use_kerning) && (i > 0) && (ci->glyphs_index[c]) )
445 {
446 FT_Get_Kerning( ci->face,
447 ci->glyphs_index[ text[i-1] ],
448 ci->glyphs_index[c],
449 ft_kerning_default,
450 &delta );
451
452 x += delta.x >> 6;
453 }
454
455 if (( (x + ci->advance[ c ]) >= width ) || ( c == '\n' ))
456 {
457 str_w = width - ci->x - 1;
458
459 y += ci->text_height;
460 x = ci->x;
461 }
462
463
464 /* save position */
465 pos[i].x = x + ci->bitmap_left[c];
466 pos[i].y = y - ci->bitmap_top[c] + ci->baseline;
467
468
469 x += ci->advance[c];
470
471
472 if (str_w > str_w_max)
473 str_w_max = str_w;
474
475 }
476
477
478
479
480 if (ci->bg)
481 {
482 /* Check if it doesn't pass the limits */
483 if ( str_w_max + ci->x >= width )
484 str_w_max = width - ci->x - 1;
485 if ( y >= height )
486 y = height - 1 - 2*ci->y;
487
488 /* Draw Background */
489 draw_box( picture, ci->x, ci->y, str_w_max, y - ci->y, ci->bgcolor );
490 }
491
492
493
494 /* Draw Glyphs */
495 for (i=0; i < size; i++)
496 {
497 c = text[i];
498
499 if (
500 ( (c == '_') && (text == ci->text) ) || /* skip '_' (consider as space)
501 IF text was specified in cmd line
502 (which doesn't like neasted quotes) */
503 ( c == '\n' ) /* Skip new line char, just go to new line */
504 )
505 continue;
506
507 /* now, draw to our target surface */
508 draw_glyph( picture,
509 &(ci->bitmaps[ c ]),
510 pos[i].x,
511 pos[i].y,
512 width,
513 height,
514 ci->fgcolor,
515 ci->bgcolor,
516 ci->outline );
517
518 /* increment pen position */
519 x += slot->advance.x >> 6;
520 }
521
522
523 }
524