]> git.sesse.net Git - vlc/blob - modules/misc/freetype.c
* Introduced a new text_style_t
[vlc] / modules / misc / freetype.c
1 /*****************************************************************************
2  * freetype.c : Put text on the video, using freetype2
3  *****************************************************************************
4  * Copyright (C) 2002 - 2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Sigmund Augdal Helberg <dnumgis@videolan.org>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>                                      /* malloc(), free() */
29 #include <string.h>
30
31 #ifdef HAVE_LINUX_LIMITS_H
32 #   include <linux/limits.h>
33 #endif
34
35 #include <vlc/vlc.h>
36 #include <vlc/vout.h>
37 #include "vlc_osd.h"
38 #include "vlc_block.h"
39 #include "vlc_filter.h"
40
41 #include <math.h>
42
43 #ifdef HAVE_ERRNO_H
44 #   include <errno.h>
45 #endif
46
47 #include <ft2build.h>
48 #include FT_FREETYPE_H
49 #include FT_GLYPH_H
50
51 #ifdef __APPLE__
52 #define DEFAULT_FONT "/System/Library/Fonts/LucidaGrande.dfont"
53 #elif defined( SYS_BEOS )
54 #define DEFAULT_FONT "/boot/beos/etc/fonts/ttfonts/Swiss721.ttf"
55 #elif defined( WIN32 )
56 #define DEFAULT_FONT "" /* Default font found at run-time */
57 #else
58 #define DEFAULT_FONT "/usr/share/fonts/truetype/freefont/FreeSerifBold.ttf"
59 #endif
60
61 #if defined(HAVE_FRIBIDI)
62 #include <fribidi/fribidi.h>
63 #endif
64
65 typedef struct line_desc_t line_desc_t;
66
67 /*****************************************************************************
68  * Local prototypes
69  *****************************************************************************/
70 static int  Create ( vlc_object_t * );
71 static void Destroy( vlc_object_t * );
72
73 /* The RenderText call maps to pf_render_string, defined in vlc_filter.h */
74 static int RenderText( filter_t *, subpicture_region_t *,
75                        subpicture_region_t * );
76 static line_desc_t *NewLine( byte_t * );
77
78 static int SetFontSize( filter_t *, int );
79
80 /*****************************************************************************
81  * Module descriptor
82  *****************************************************************************/
83 #define FONT_TEXT N_("Font")
84 #define FONT_LONGTEXT N_("Font filename")
85 #define FONTSIZE_TEXT N_("Font size in pixels")
86 #define FONTSIZE_LONGTEXT N_("The size of the fonts used by the osd module. " \
87     "If set to something different than 0 this option will override the " \
88     "relative font size " )
89 #define OPACITY_TEXT N_("Opacity, 0..255")
90 #define OPACITY_LONGTEXT N_("The opacity (inverse of transparency) of " \
91     "overlay text. 0 = transparent, 255 = totally opaque. " )
92 #define COLOR_TEXT N_("Text Default Color")
93 #define COLOR_LONGTEXT N_("The color of overlay text. 1 byte for each color, "\
94     "hexadecimal. #000000 = all colors off, 0xFF0000 = just Red, " \
95     "0xFFFFFF = all color on [White]" )
96 #define FONTSIZER_TEXT N_("Font size")
97 #define FONTSIZER_LONGTEXT N_("The size of the fonts used by the osd module" )
98
99 static int   pi_sizes[] = { 20, 18, 16, 12, 6 };
100 static char *ppsz_sizes_text[] = { N_("Smaller"), N_("Small"), N_("Normal"),
101                                    N_("Large"), N_("Larger") };
102 #define YUVP_TEXT N_("Use yuvp renderer")
103 #define YUVP_LONGTEXT N_("Render into paletized YUV. Needed to encode into dvbsubs")
104 #define EFFECT_TEXT N_("Font Effect")
105 #define EFFECT_LONGTEXT N_("Select effects to apply to rendered text")
106
107 #define EFFECT_BACKGROUND  1 
108 #define EFFECT_OUTLINE     2
109 #define EFFECT_OUTLINE_FAT 3
110
111 static int   pi_effects[] = { 1, 2, 3 };
112 static char *ppsz_effects_text[] = { N_("Background"),N_("Outline"),
113                                      N_("Fat Outline") };
114 static int pi_color_values[] = {
115   0x00000000, 0x00808080, 0x00C0C0C0, 0x00FFFFFF, 0x00800000,
116   0x00FF0000, 0x00FF00FF, 0x00FFFF00, 0x00808000, 0x00008000, 0x00008080, 
117   0x0000FF00, 0x00800080, 0x00000080, 0x000000FF, 0x0000FFFF }; 
118
119 static char *ppsz_color_descriptions[] = {
120   N_("Black"), N_("Gray"), N_("Silver"), N_("White"), N_("Maroon"),
121   N_("Red"), N_("Fuchsia"), N_("Yellow"), N_("Olive"), N_("Green"), N_("Teal"),
122   N_("Lime"), N_("Purple"), N_("Navy"), N_("Blue"), N_("Aqua") };
123
124 vlc_module_begin();
125     set_shortname( _("Text renderer"));
126     set_description( _("Freetype2 font renderer") );
127     set_category( CAT_VIDEO );
128     set_subcategory( SUBCAT_VIDEO_SUBPIC );
129
130     add_file( "freetype-font", DEFAULT_FONT, NULL, FONT_TEXT, FONT_LONGTEXT,
131               VLC_FALSE );
132
133     add_integer( "freetype-fontsize", 0, NULL, FONTSIZE_TEXT,
134                  FONTSIZE_LONGTEXT, VLC_TRUE );
135
136     /* opacity valid on 0..255, with default 255 = fully opaque */
137     add_integer_with_range( "freetype-opacity", 255, 0, 255, NULL,
138         OPACITY_TEXT, OPACITY_LONGTEXT, VLC_TRUE );
139
140     /* hook to the color values list, with default 0x00ffffff = white */
141     add_integer( "freetype-color", 0x00FFFFFF, NULL, COLOR_TEXT,
142                  COLOR_LONGTEXT, VLC_FALSE );
143         change_integer_list( pi_color_values, ppsz_color_descriptions, 0 );
144
145     add_integer( "freetype-rel-fontsize", 16, NULL, FONTSIZER_TEXT,
146                  FONTSIZER_LONGTEXT, VLC_FALSE );
147         change_integer_list( pi_sizes, ppsz_sizes_text, 0 );
148     add_integer( "freetype-effect", 2, NULL, EFFECT_TEXT,
149                  EFFECT_LONGTEXT, VLC_FALSE );
150         change_integer_list( pi_effects, ppsz_effects_text, 0 );
151
152     add_bool( "freetype-yuvp", 0, NULL, YUVP_TEXT,
153               YUVP_LONGTEXT, VLC_TRUE );
154     set_capability( "text renderer", 100 );
155     add_shortcut( "text" );
156     set_callbacks( Create, Destroy );
157 vlc_module_end();
158
159 struct line_desc_t
160 {
161     /** NULL-terminated list of glyphs making the string */
162     FT_BitmapGlyph *pp_glyphs;
163     /** list of relative positions for the glyphs */
164     FT_Vector      *p_glyph_pos;
165
166     int             i_height;
167     int             i_width;
168     int             i_red, i_green, i_blue;
169     int             i_alpha;
170
171     line_desc_t    *p_next;
172 };
173
174 static int Render( filter_t *, subpicture_region_t *, line_desc_t *, int, int);
175 static void FreeLines( line_desc_t * );
176 static void FreeLine( line_desc_t * );
177
178 /*****************************************************************************
179  * filter_sys_t: freetype local data
180  *****************************************************************************
181  * This structure is part of the video output thread descriptor.
182  * It describes the freetype specific properties of an output thread.
183  *****************************************************************************/
184 struct filter_sys_t
185 {
186     FT_Library     p_library;   /* handle to library     */
187     FT_Face        p_face;      /* handle to face object */
188     vlc_bool_t     i_use_kerning;
189     uint8_t        i_font_opacity;
190     int            i_font_color;
191     int            i_font_size;
192     int            i_effect;
193
194     int            i_default_font_size;
195     int            i_display_height;
196 };
197
198 /*****************************************************************************
199  * Create: allocates osd-text video thread output method
200  *****************************************************************************
201  * This function allocates and initializes a Clone vout method.
202  *****************************************************************************/
203 static int Create( vlc_object_t *p_this )
204 {
205     filter_t *p_filter = (filter_t *)p_this;
206     filter_sys_t *p_sys;
207     char *psz_fontfile = NULL;
208     int i_error;
209     vlc_value_t val;
210
211     /* Allocate structure */
212     p_filter->p_sys = p_sys = malloc( sizeof( filter_sys_t ) );
213     if( !p_sys )
214     {
215         msg_Err( p_filter, "out of memory" );
216         return VLC_ENOMEM;
217     }
218     p_sys->p_face = 0;
219     p_sys->p_library = 0;
220     p_sys->i_font_size = 0;
221     p_sys->i_display_height = 0;
222
223     var_Create( p_filter, "freetype-font",
224                 VLC_VAR_STRING | VLC_VAR_DOINHERIT );
225     var_Create( p_filter, "freetype-fontsize",
226                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
227     var_Create( p_filter, "freetype-rel-fontsize",
228                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
229     var_Create( p_filter, "freetype-opacity",
230                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
231     var_Create( p_filter, "freetype-effect",
232                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
233     var_Get( p_filter, "freetype-opacity", &val );
234     p_sys->i_font_opacity = __MAX( __MIN( val.i_int, 255 ), 0 );
235     var_Create( p_filter, "freetype-color",
236                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
237     var_Get( p_filter, "freetype-color", &val );
238     p_sys->i_font_color = __MAX( __MIN( val.i_int, 0xFFFFFF ), 0 );
239     p_sys->i_effect = var_GetInteger( p_filter, "freetype-effect" );
240     
241     /* Look what method was requested */
242     var_Get( p_filter, "freetype-font", &val );
243     psz_fontfile = val.psz_string;
244     if( !psz_fontfile || !*psz_fontfile )
245     {
246         if( psz_fontfile ) free( psz_fontfile );
247         psz_fontfile = (char *)malloc( PATH_MAX + 1 );
248 #ifdef WIN32
249         GetWindowsDirectory( psz_fontfile, PATH_MAX + 1 );
250         strcat( psz_fontfile, "\\fonts\\arial.ttf" );
251 #elif __APPLE__
252         strcpy( psz_fontfile, DEFAULT_FONT );
253 #else
254         msg_Err( p_filter, "user didn't specify a font" );
255         goto error;
256 #endif
257     }
258
259     i_error = FT_Init_FreeType( &p_sys->p_library );
260     if( i_error )
261     {
262         msg_Err( p_filter, "couldn't initialize freetype" );
263         goto error;
264     }
265
266     i_error = FT_New_Face( p_sys->p_library, psz_fontfile ? psz_fontfile : "",
267                            0, &p_sys->p_face );
268     if( i_error == FT_Err_Unknown_File_Format )
269     {
270         msg_Err( p_filter, "file %s have unknown format", psz_fontfile );
271         goto error;
272     }
273     else if( i_error )
274     {
275         msg_Err( p_filter, "failed to load font file %s", psz_fontfile );
276         goto error;
277     }
278
279     i_error = FT_Select_Charmap( p_sys->p_face, ft_encoding_unicode );
280     if( i_error )
281     {
282         msg_Err( p_filter, "Font has no unicode translation table" );
283         goto error;
284     }
285
286     p_sys->i_use_kerning = FT_HAS_KERNING( p_sys->p_face );
287
288     var_Get( p_filter, "freetype-fontsize", &val );
289     p_sys->i_default_font_size = val.i_int;
290     if( SetFontSize( p_filter, 0 ) != VLC_SUCCESS ) goto error;
291
292     if( psz_fontfile ) free( psz_fontfile );
293     p_filter->pf_render_text = RenderText;
294     return VLC_SUCCESS;
295
296  error:
297     if( p_sys->p_face ) FT_Done_Face( p_sys->p_face );
298     if( p_sys->p_library ) FT_Done_FreeType( p_sys->p_library );
299     if( psz_fontfile ) free( psz_fontfile );
300     free( p_sys );
301     return VLC_EGENERIC;
302 }
303
304 /*****************************************************************************
305  * Destroy: destroy Clone video thread output method
306  *****************************************************************************
307  * Clean up all data and library connections
308  *****************************************************************************/
309 static void Destroy( vlc_object_t *p_this )
310 {
311     filter_t *p_filter = (filter_t *)p_this;
312     filter_sys_t *p_sys = p_filter->p_sys;
313
314     FT_Done_Face( p_sys->p_face );
315     FT_Done_FreeType( p_sys->p_library );
316     free( p_sys );
317 }
318
319 /*****************************************************************************
320  * Render: place string in picture
321  *****************************************************************************
322  * This function merges the previously rendered freetype glyphs into a picture
323  *****************************************************************************/
324 static int Render( filter_t *p_filter, subpicture_region_t *p_region,
325                    line_desc_t *p_line, int i_width, int i_height )
326 {
327     static uint8_t pi_gamma[16] =
328         {0x00, 0x52, 0x84, 0x96, 0xb8, 0xca, 0xdc, 0xee, 0xff,
329           0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
330
331     uint8_t *p_dst;
332     video_format_t fmt;
333     int i, x, y, i_pitch;
334     uint8_t i_y; /* YUV values, derived from incoming RGB */
335     int8_t i_u, i_v;
336     subpicture_region_t *p_region_tmp;
337
338     /* Create a new subpicture region */
339     memset( &fmt, 0, sizeof(video_format_t) );
340     fmt.i_chroma = VLC_FOURCC('Y','U','V','P');
341     fmt.i_aspect = 0;
342     fmt.i_width = fmt.i_visible_width = i_width + 4;
343     fmt.i_height = fmt.i_visible_height = i_height + 4;
344     fmt.i_x_offset = fmt.i_y_offset = 0;
345     p_region_tmp = spu_CreateRegion( p_filter, &fmt );
346     if( !p_region_tmp )
347     {
348         msg_Err( p_filter, "cannot allocate SPU region" );
349         return VLC_EGENERIC;
350     }
351
352     p_region->fmt = p_region_tmp->fmt;
353     p_region->picture = p_region_tmp->picture;
354     free( p_region_tmp );
355
356     /* Calculate text color components */
357     i_y = (uint8_t)(( 66 * p_line->i_red  + 129 * p_line->i_green +
358                       25 * p_line->i_blue + 128) >> 8) +  16;
359     i_u = (int8_t)(( -38 * p_line->i_red  -  74 * p_line->i_green +
360                      112 * p_line->i_blue + 128) >> 8) + 128;
361     i_v = (int8_t)(( 112 * p_line->i_red  -  94 * p_line->i_green -
362                       18 * p_line->i_blue + 128) >> 8) + 128;
363
364     /* Build palette */
365     fmt.p_palette->i_entries = 16;
366     for( i = 0; i < 8; i++ )
367     {
368         fmt.p_palette->palette[i][0] = 0;
369         fmt.p_palette->palette[i][1] = 0x80;
370         fmt.p_palette->palette[i][2] = 0x80;
371         fmt.p_palette->palette[i][3] = pi_gamma[i];
372         fmt.p_palette->palette[i][3] =
373             (int)fmt.p_palette->palette[i][3] * (255 - p_line->i_alpha) / 255;
374     }
375     for( i = 8; i < fmt.p_palette->i_entries; i++ )
376     {
377         fmt.p_palette->palette[i][0] = i * 16 * i_y / 256;
378         fmt.p_palette->palette[i][1] = i_u;
379         fmt.p_palette->palette[i][2] = i_v;
380         fmt.p_palette->palette[i][3] = pi_gamma[i];
381         fmt.p_palette->palette[i][3] =
382             (int)fmt.p_palette->palette[i][3] * (255 - p_line->i_alpha) / 255;
383     }
384
385     p_dst = p_region->picture.Y_PIXELS;
386     i_pitch = p_region->picture.Y_PITCH;
387
388     /* Initialize the region pixels */
389     memset( p_dst, 0, i_pitch * p_region->fmt.i_height );
390
391     for( ; p_line != NULL; p_line = p_line->p_next )
392     {
393         int i_glyph_tmax = 0;
394         int i_bitmap_offset, i_offset, i_align_offset = 0;
395         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
396         {
397             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
398             i_glyph_tmax = __MAX( i_glyph_tmax, p_glyph->top );
399         }
400
401         if( p_region->p_style && p_line->i_width < i_width )
402         {
403             if( p_region->p_style->i_text_align == SUBPICTURE_ALIGN_RIGHT )
404             {
405                 i_align_offset = i_width - p_line->i_width;
406             }
407             else if( p_region->p_style->i_text_align != SUBPICTURE_ALIGN_LEFT )
408             {
409                 i_align_offset = ( i_width - p_line->i_width ) / 2;
410             }
411         }
412
413         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
414         {
415             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
416
417             i_offset = ( p_line->p_glyph_pos[ i ].y +
418                 i_glyph_tmax - p_glyph->top + 2 ) *
419                 i_pitch + p_line->p_glyph_pos[ i ].x + p_glyph->left + 2 +
420                 i_align_offset;
421
422             for( y = 0, i_bitmap_offset = 0; y < p_glyph->bitmap.rows; y++ )
423             {
424                 for( x = 0; x < p_glyph->bitmap.width; x++, i_bitmap_offset++ )
425                 {
426                     if( p_glyph->bitmap.buffer[i_bitmap_offset] )
427                         p_dst[i_offset+x] =
428                          ((int)p_glyph->bitmap.buffer[i_bitmap_offset] + 8)/16;
429                 }
430                 i_offset += i_pitch;
431             }
432         }
433     }
434
435     /* Outlining (find something better than nearest neighbour filtering ?) */
436     if( 1 )
437     {
438         uint8_t *p_dst = p_region->picture.Y_PIXELS;
439         uint8_t *p_top = p_dst; /* Use 1st line as a cache */
440         uint8_t left, current;
441
442         for( y = 1; y < (int)fmt.i_height - 1; y++ )
443         {
444             if( y > 1 ) memcpy( p_top, p_dst, fmt.i_width );
445             p_dst += p_region->picture.Y_PITCH;
446             left = 0;
447
448             for( x = 1; x < (int)fmt.i_width - 1; x++ )
449             {
450                 current = p_dst[x];
451                 p_dst[x] = ( 8 * (int)p_dst[x] + left + p_dst[x+1] + p_top[x -1]+ p_top[x] + p_top[x+1] +
452                              p_dst[x -1 + p_region->picture.Y_PITCH ] + p_dst[x + p_region->picture.Y_PITCH] + p_dst[x + 1 + p_region->picture.Y_PITCH]) / 16;
453                 left = current;
454             }
455         }
456         memset( p_top, 0, fmt.i_width );
457     }
458
459     return VLC_SUCCESS;
460 }
461
462 static void DrawBlack( line_desc_t *p_line, int i_width, subpicture_region_t *p_region, int xoffset, int yoffset )
463 {
464     uint8_t *p_dst = p_region->picture.A_PIXELS;
465     int i_pitch = p_region->picture.A_PITCH;
466     int x,y;
467
468     for( ; p_line != NULL; p_line = p_line->p_next )
469     {
470         int i_glyph_tmax=0, i = 0;
471         int i_bitmap_offset, i_offset, i_align_offset = 0;
472         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
473         {
474             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
475             i_glyph_tmax = __MAX( i_glyph_tmax, p_glyph->top );
476         }
477
478         if( p_region->p_style && p_line->i_width < i_width )
479         {
480             if( p_region->p_style->i_text_align == SUBPICTURE_ALIGN_RIGHT )
481             {
482                 i_align_offset = i_width - p_line->i_width;
483             }
484             else if( p_region->p_style->i_text_align != SUBPICTURE_ALIGN_LEFT )
485             {
486                 i_align_offset = ( i_width - p_line->i_width ) / 2;
487             }
488         }
489
490         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
491         {
492             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
493
494             i_offset = ( p_line->p_glyph_pos[ i ].y +
495                 i_glyph_tmax - p_glyph->top + 3 + yoffset ) *
496                 i_pitch + p_line->p_glyph_pos[ i ].x + p_glyph->left + 3 +
497                 i_align_offset +xoffset;
498
499             for( y = 0, i_bitmap_offset = 0; y < p_glyph->bitmap.rows; y++ )
500             {
501                 for( x = 0; x < p_glyph->bitmap.width; x++, i_bitmap_offset++ )
502                 {
503                     if( p_glyph->bitmap.buffer[i_bitmap_offset] )
504                         if( p_dst[i_offset+x] <
505                             ((int)p_glyph->bitmap.buffer[i_bitmap_offset]) )
506                             p_dst[i_offset+x] =
507                                 ((int)p_glyph->bitmap.buffer[i_bitmap_offset]);
508                 }
509                 i_offset += i_pitch;
510             }
511         }
512     }
513     
514 }
515
516 /*****************************************************************************
517  * Render: place string in picture
518  *****************************************************************************
519  * This function merges the previously rendered freetype glyphs into a picture
520  *****************************************************************************/
521 static int RenderYUVA( filter_t *p_filter, subpicture_region_t *p_region,
522                    line_desc_t *p_line, int i_width, int i_height )
523 {
524     static uint8_t pi_gamma[16] =
525         {0x00, 0x52, 0x84, 0x96, 0xb8, 0xca, 0xdc, 0xee, 0xff,
526           0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
527
528     uint8_t *p_dst_y,*p_dst_u,*p_dst_v,*p_dst_a;
529     video_format_t fmt;
530     int i, x, y, i_pitch, i_alpha;
531     uint8_t i_y, i_u, i_v; /* YUV values, derived from incoming RGB */
532     subpicture_region_t *p_region_tmp;
533
534     if( i_width == 0 || i_height == 0 )
535         return VLC_SUCCESS;
536
537     /* Create a new subpicture region */
538     memset( &fmt, 0, sizeof(video_format_t) );
539     fmt.i_chroma = VLC_FOURCC('Y','U','V','A');
540     fmt.i_aspect = 0;
541     fmt.i_width = fmt.i_visible_width = i_width + 6;
542     fmt.i_height = fmt.i_visible_height = i_height + 6;
543     fmt.i_x_offset = fmt.i_y_offset = 0;
544     p_region_tmp = spu_CreateRegion( p_filter, &fmt );
545     if( !p_region_tmp )
546     {
547         msg_Err( p_filter, "cannot allocate SPU region" );
548         return VLC_EGENERIC;
549     }
550
551     p_region->fmt = p_region_tmp->fmt;
552     p_region->picture = p_region_tmp->picture;
553     free( p_region_tmp );
554
555     /* Calculate text color components */
556     i_y = (uint8_t)__MIN(abs( 2104 * p_line->i_red  + 4130 * p_line->i_green +
557                       802 * p_line->i_blue + 4096 + 131072 ) >> 13, 235);
558     i_u = (uint8_t)__MIN(abs( -1214 * p_line->i_red  + -2384 * p_line->i_green +
559                      3598 * p_line->i_blue + 4096 + 1048576) >> 13, 240);
560     i_v = (uint8_t)__MIN(abs( 3598 * p_line->i_red + -3013 * p_line->i_green +
561                       -585 * p_line->i_blue + 4096 + 1048576) >> 13, 240);
562     i_alpha = p_line->i_alpha;
563
564     p_dst_y = p_region->picture.Y_PIXELS;
565     p_dst_u = p_region->picture.U_PIXELS;
566     p_dst_v = p_region->picture.V_PIXELS;
567     p_dst_a = p_region->picture.A_PIXELS;
568     i_pitch = p_region->picture.A_PITCH;
569
570     /* Initialize the region pixels */
571     if( p_filter->p_sys->i_effect != EFFECT_BACKGROUND )
572     {
573         memset( p_dst_y, 0x00, i_pitch * p_region->fmt.i_height );
574         memset( p_dst_u, 0x80, i_pitch * p_region->fmt.i_height );
575         memset( p_dst_v, 0x80, i_pitch * p_region->fmt.i_height );
576         memset( p_dst_a, 0, i_pitch * p_region->fmt.i_height );
577     }
578     else
579     {
580         memset( p_dst_y, 0x0, i_pitch * p_region->fmt.i_height );
581         memset( p_dst_u, 0x80, i_pitch * p_region->fmt.i_height );
582         memset( p_dst_v, 0x80, i_pitch * p_region->fmt.i_height );
583         memset( p_dst_a, 0x80, i_pitch * p_region->fmt.i_height );
584     }
585     if( p_filter->p_sys->i_effect == EFFECT_OUTLINE ||
586         p_filter->p_sys->i_effect == EFFECT_OUTLINE_FAT )
587     {
588         DrawBlack( p_line, i_width, p_region,  0,  0);
589         DrawBlack( p_line, i_width, p_region, -1,  0);
590         DrawBlack( p_line, i_width, p_region,  0, -1);
591         DrawBlack( p_line, i_width, p_region,  1,  0);
592         DrawBlack( p_line, i_width, p_region,  0,  1);
593     }
594     
595     if( p_filter->p_sys->i_effect == EFFECT_OUTLINE_FAT )
596     {
597         DrawBlack( p_line, i_width, p_region, -1, -1);
598         DrawBlack( p_line, i_width, p_region, -1,  1);
599         DrawBlack( p_line, i_width, p_region,  1, -1);
600         DrawBlack( p_line, i_width, p_region,  1,  1);
601
602         DrawBlack( p_line, i_width, p_region, -2,  0);
603         DrawBlack( p_line, i_width, p_region,  0, -2);
604         DrawBlack( p_line, i_width, p_region,  2,  0);
605         DrawBlack( p_line, i_width, p_region,  0,  2);
606
607         DrawBlack( p_line, i_width, p_region, -2, -2);
608         DrawBlack( p_line, i_width, p_region, -2,  2);
609         DrawBlack( p_line, i_width, p_region,  2, -2);
610         DrawBlack( p_line, i_width, p_region,  2,  2);
611
612         DrawBlack( p_line, i_width, p_region, -3,  0);
613         DrawBlack( p_line, i_width, p_region,  0, -3);
614         DrawBlack( p_line, i_width, p_region,  3,  0);
615         DrawBlack( p_line, i_width, p_region,  0,  3);
616     }
617
618     for( ; p_line != NULL; p_line = p_line->p_next )
619     {
620         int i_glyph_tmax = 0;
621         int i_bitmap_offset, i_offset, i_align_offset = 0;
622         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
623         {
624             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
625             i_glyph_tmax = __MAX( i_glyph_tmax, p_glyph->top );
626         }
627
628         if( p_region->p_style && p_line->i_width < i_width )
629         {
630             if( p_region->p_style->i_text_align == SUBPICTURE_ALIGN_RIGHT )
631             {
632                 i_align_offset = i_width - p_line->i_width;
633             }
634             else if( p_region->p_style->i_text_align != SUBPICTURE_ALIGN_LEFT )
635             {
636                 i_align_offset = ( i_width - p_line->i_width ) / 2;
637             }
638         }
639
640         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
641         {
642             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
643
644             i_offset = ( p_line->p_glyph_pos[ i ].y +
645                 i_glyph_tmax - p_glyph->top + 3 ) *
646                 i_pitch + p_line->p_glyph_pos[ i ].x + p_glyph->left + 3 +
647                 i_align_offset;
648
649             for( y = 0, i_bitmap_offset = 0; y < p_glyph->bitmap.rows; y++ )
650             {
651                 for( x = 0; x < p_glyph->bitmap.width; x++, i_bitmap_offset++ )
652                 {
653                     if( p_glyph->bitmap.buffer[i_bitmap_offset] )
654                     {
655                         p_dst_y[i_offset+x] = ((p_dst_y[i_offset+x] *(255-(int)p_glyph->bitmap.buffer[i_bitmap_offset])) +
656                                               i_y * ((int)p_glyph->bitmap.buffer[i_bitmap_offset])) >> 8;
657
658                         p_dst_u[i_offset+x] = i_u;
659                         p_dst_v[i_offset+x] = i_v;
660                         
661                         if( p_filter->p_sys->i_effect == EFFECT_BACKGROUND )
662                             p_dst_a[i_offset+x] = 0xff;
663                     }
664                 }
665                 i_offset += i_pitch;
666             }
667         }
668     }
669     
670     /* Apply the alpha setting */
671     for( i = 0; i < (int)fmt.i_height * i_pitch; i++ )
672         p_dst_a[i] = p_dst_a[i] * (255 - i_alpha) / 255;
673
674     return VLC_SUCCESS;
675 }
676
677 /**
678  * This function renders a text subpicture region into another one.
679  * It also calculates the size needed for this string, and renders the
680  * needed glyphs into memory. It is used as pf_add_string callback in
681  * the vout method by this module
682  */
683 static int RenderText( filter_t *p_filter, subpicture_region_t *p_region_out,
684                        subpicture_region_t *p_region_in )
685 {
686     filter_sys_t *p_sys = p_filter->p_sys;
687     line_desc_t  *p_lines = 0, *p_line = 0, *p_next = 0, *p_prev = 0;
688     int i, i_pen_y, i_pen_x, i_error, i_glyph_index, i_previous;
689     uint32_t *psz_unicode, *psz_unicode_orig = 0, i_char, *psz_line_start;
690     int i_string_length;
691     char *psz_string;
692     vlc_iconv_t iconv_handle = (vlc_iconv_t)(-1);
693     int i_font_color, i_font_alpha, i_font_size, i_red, i_green, i_blue;
694
695     FT_BBox line;
696     FT_BBox glyph_size;
697     FT_Vector result;
698     FT_Glyph tmp_glyph;
699
700     /* Sanity check */
701     if( !p_region_in || !p_region_out ) return VLC_EGENERIC;
702     psz_string = p_region_in->psz_text;
703     if( !psz_string || !*psz_string ) return VLC_EGENERIC;
704
705     if( p_region_in->p_style )
706     {
707         i_font_color = __MAX( __MIN( p_region_in->p_style->i_font_color, 0xFFFFFF ), 0 );
708         i_font_alpha = __MAX( __MIN( p_region_in->p_style->i_font_alpha, 255 ), 0 );
709         i_font_size  = __MAX( __MIN( p_region_in->p_style->i_font_size, 255 ), 0 );
710     }
711     else
712     {
713         i_font_color = p_sys->i_font_color;
714         i_font_alpha = 255 - p_sys->i_font_opacity;
715         i_font_size  = p_sys->i_default_font_size;
716     }
717
718     if( i_font_color == 0xFFFFFF ) i_font_color = p_sys->i_font_color;
719     if( !i_font_alpha ) i_font_alpha = 255 - p_sys->i_font_opacity;
720     SetFontSize( p_filter, i_font_size );
721
722     i_red   = ( i_font_color & 0x00FF0000 ) >> 16;
723     i_green = ( i_font_color & 0x0000FF00 ) >>  8;
724     i_blue  =   i_font_color & 0x000000FF;
725
726     result.x =  result.y = 0;
727     line.xMin = line.xMax = line.yMin = line.yMax = 0;
728
729     psz_unicode = psz_unicode_orig =
730         malloc( ( strlen(psz_string) + 1 ) * sizeof(uint32_t) );
731     if( psz_unicode == NULL )
732     {
733         msg_Err( p_filter, "out of memory" );
734         goto error;
735     }
736 #if defined(WORDS_BIGENDIAN)
737     iconv_handle = vlc_iconv_open( "UCS-4BE", "UTF-8" );
738 #else
739     iconv_handle = vlc_iconv_open( "UCS-4LE", "UTF-8" );
740 #endif
741     if( iconv_handle == (vlc_iconv_t)-1 )
742     {
743         msg_Warn( p_filter, "unable to do conversion" );
744         goto error;
745     }
746
747     {
748         char *p_in_buffer, *p_out_buffer;
749         size_t i_in_bytes, i_out_bytes, i_out_bytes_left, i_ret;
750         i_in_bytes = strlen( psz_string );
751         i_out_bytes = i_in_bytes * sizeof( uint32_t );
752         i_out_bytes_left = i_out_bytes;
753         p_in_buffer = psz_string;
754         p_out_buffer = (char *)psz_unicode;
755         i_ret = vlc_iconv( iconv_handle, &p_in_buffer, &i_in_bytes,
756                            &p_out_buffer, &i_out_bytes_left );
757
758         vlc_iconv_close( iconv_handle );
759
760         if( i_in_bytes )
761         {
762             msg_Warn( p_filter, "failed to convert string to unicode (%s), "
763                       "bytes left %d", strerror(errno), (int)i_in_bytes );
764             goto error;
765         }
766         *(uint32_t*)p_out_buffer = 0;
767         i_string_length = (i_out_bytes - i_out_bytes_left) / sizeof(uint32_t);
768     }
769
770 #if defined(HAVE_FRIBIDI)
771     {
772         uint32_t *p_fribidi_string;
773         int start_pos, pos = 0;
774         
775         p_fribidi_string = malloc( (i_string_length + 1) * sizeof(uint32_t) );
776
777         /* Do bidi conversion line-by-line */
778         while(pos < i_string_length)
779         {
780             while(pos < i_string_length) {
781                 i_char = psz_unicode[pos];
782                 if (i_char != '\r' && i_char != '\n')
783                     break;
784                 p_fribidi_string[pos] = i_char;
785                 ++pos;
786             }
787             start_pos = pos;
788             while(pos < i_string_length) {
789                 i_char = psz_unicode[pos];
790                 if (i_char == '\r' || i_char == '\n')
791                     break;
792                 ++pos;
793             }
794             if (pos > start_pos)
795             {
796                 FriBidiCharType base_dir = FRIBIDI_TYPE_LTR;
797                 fribidi_log2vis((FriBidiChar*)psz_unicode + start_pos, pos - start_pos,
798                                 &base_dir, (FriBidiChar*)p_fribidi_string + start_pos, 0, 0, 0);
799             }
800         }
801
802         free( psz_unicode_orig );
803         psz_unicode = psz_unicode_orig = p_fribidi_string;
804         p_fribidi_string[ i_string_length ] = 0;
805     }
806 #endif
807
808     /* Calculate relative glyph positions and a bounding box for the
809      * entire string */
810     if( !(p_line = NewLine( (byte_t *)psz_string )) )
811     {
812         msg_Err( p_filter, "out of memory" );
813         goto error;
814     }
815     p_lines = p_line;
816     i_pen_x = i_pen_y = 0;
817     i_previous = i = 0;
818     psz_line_start = psz_unicode;
819
820 #define face p_sys->p_face
821 #define glyph face->glyph
822
823     while( *psz_unicode )
824     {
825         i_char = *psz_unicode++;
826         if( i_char == '\r' ) /* ignore CR chars wherever they may be */
827         {
828             continue;
829         }
830
831         if( i_char == '\n' )
832         {
833             psz_line_start = psz_unicode;
834             if( !(p_next = NewLine( (byte_t *)psz_string )) )
835             {
836                 msg_Err( p_filter, "out of memory" );
837                 goto error;
838             }
839             p_line->p_next = p_next;
840             p_line->i_width = line.xMax;
841             p_line->i_height = face->size->metrics.height >> 6;
842             p_line->pp_glyphs[ i ] = NULL;
843             p_line->i_alpha = i_font_alpha;
844             p_line->i_red = i_red;
845             p_line->i_green = i_green;
846             p_line->i_blue = i_blue;
847             p_prev = p_line;
848             p_line = p_next;
849             result.x = __MAX( result.x, line.xMax );
850             result.y += face->size->metrics.height >> 6;
851             i_pen_x = 0;
852             i_previous = i = 0;
853             line.xMin = line.xMax = line.yMin = line.yMax = 0;
854             i_pen_y += face->size->metrics.height >> 6;
855 #if 0
856             msg_Dbg( p_filter, "Creating new line, i is %d", i );
857 #endif
858             continue;
859         }
860
861         i_glyph_index = FT_Get_Char_Index( face, i_char );
862         if( p_sys->i_use_kerning && i_glyph_index
863             && i_previous )
864         {
865             FT_Vector delta;
866             FT_Get_Kerning( face, i_previous, i_glyph_index,
867                             ft_kerning_default, &delta );
868             i_pen_x += delta.x >> 6;
869
870         }
871         p_line->p_glyph_pos[ i ].x = i_pen_x;
872         p_line->p_glyph_pos[ i ].y = i_pen_y;
873         i_error = FT_Load_Glyph( face, i_glyph_index, FT_LOAD_DEFAULT );
874         if( i_error )
875         {
876             msg_Err( p_filter, "FT_Load_Glyph returned %d", i_error );
877             goto error;
878         }
879         i_error = FT_Get_Glyph( glyph, &tmp_glyph );
880         if( i_error )
881         {
882             msg_Err( p_filter, "FT_Get_Glyph returned %d", i_error );
883             goto error;
884         }
885         FT_Glyph_Get_CBox( tmp_glyph, ft_glyph_bbox_pixels, &glyph_size );
886         i_error = FT_Glyph_To_Bitmap( &tmp_glyph, ft_render_mode_normal, 0, 1);
887         if( i_error )
888         {
889             FT_Done_Glyph( tmp_glyph );
890             continue;
891         }
892         p_line->pp_glyphs[ i ] = (FT_BitmapGlyph)tmp_glyph;
893
894         /* Do rest */
895         line.xMax = p_line->p_glyph_pos[i].x + glyph_size.xMax -
896             glyph_size.xMin + ((FT_BitmapGlyph)tmp_glyph)->left;
897         if( line.xMax > (int)p_filter->fmt_out.video.i_visible_width - 20 )
898         {
899             p_line->pp_glyphs[ i ] = NULL;
900             FreeLine( p_line );
901             p_line = NewLine( (byte_t *)psz_string );
902             if( p_prev ) p_prev->p_next = p_line;
903             else p_lines = p_line;
904
905             while( psz_unicode > psz_line_start && *psz_unicode != ' ' )
906             {
907                 psz_unicode--;
908             }
909             if( psz_unicode == psz_line_start )
910             {
911                 msg_Warn( p_filter, "unbreakable string" );
912                 goto error;
913             }
914             else
915             {
916                 *psz_unicode = '\n';
917             }
918             psz_unicode = psz_line_start;
919             i_pen_x = 0;
920             i_previous = i = 0;
921             line.xMin = line.xMax = line.yMin = line.yMax = 0;
922             continue;
923         }
924         line.yMax = __MAX( line.yMax, glyph_size.yMax );
925         line.yMin = __MIN( line.yMin, glyph_size.yMin );
926
927         i_previous = i_glyph_index;
928         i_pen_x += glyph->advance.x >> 6;
929         i++;
930     }
931
932     p_line->i_width = line.xMax;
933     p_line->i_height = face->size->metrics.height >> 6;
934     p_line->pp_glyphs[ i ] = NULL;
935     p_line->i_alpha = i_font_alpha;
936     p_line->i_red = i_red;
937     p_line->i_green = i_green;
938     p_line->i_blue = i_blue;
939     result.x = __MAX( result.x, line.xMax );
940     result.y += line.yMax - line.yMin;
941
942 #undef face
943 #undef glyph
944
945     p_region_out->i_x = p_region_in->i_x;
946     p_region_out->i_y = p_region_in->i_y;
947
948     if( config_GetInt( p_filter, "freetype-yuvp" ) )
949         Render( p_filter, p_region_out, p_lines, result.x, result.y );
950     else
951         RenderYUVA( p_filter, p_region_out, p_lines, result.x, result.y );
952
953     if( psz_unicode_orig ) free( psz_unicode_orig );
954     FreeLines( p_lines );
955     return VLC_SUCCESS;
956
957  error:
958     if( psz_unicode_orig ) free( psz_unicode_orig );
959     FreeLines( p_lines );
960     return VLC_EGENERIC;
961 }
962
963 static void FreeLine( line_desc_t *p_line )
964 {
965     unsigned int i;
966     for( i = 0; p_line->pp_glyphs[ i ] != NULL; i++ )
967     {
968         FT_Done_Glyph( (FT_Glyph)p_line->pp_glyphs[ i ] );
969     }
970     free( p_line->pp_glyphs );
971     free( p_line->p_glyph_pos );
972     free( p_line );
973 }
974
975 static void FreeLines( line_desc_t *p_lines )
976 {
977     line_desc_t *p_line, *p_next;
978
979     if( !p_lines ) return;
980
981     for( p_line = p_lines; p_line != NULL; p_line = p_next )
982     {
983         p_next = p_line->p_next;
984         FreeLine( p_line );
985     }
986 }
987
988 static line_desc_t *NewLine( byte_t *psz_string )
989 {
990     int i_count;
991     line_desc_t *p_line = malloc( sizeof(line_desc_t) );
992
993     if( !p_line ) return NULL;
994     p_line->i_height = 0;
995     p_line->i_width = 0;
996     p_line->p_next = NULL;
997
998     /* We don't use CountUtf8Characters() here because we are not acutally
999      * sure the string is utf8. Better be safe than sorry. */
1000     i_count = strlen( (char *)psz_string );
1001
1002     p_line->pp_glyphs = malloc( sizeof(FT_BitmapGlyph) * ( i_count + 1 ) );
1003     if( p_line->pp_glyphs == NULL )
1004     {
1005         free( p_line );
1006         return NULL;
1007     }
1008     p_line->pp_glyphs[0] = NULL;
1009
1010     p_line->p_glyph_pos = malloc( sizeof( FT_Vector ) * i_count + 1 );
1011     if( p_line->p_glyph_pos == NULL )
1012     {
1013         free( p_line->pp_glyphs );
1014         free( p_line );
1015         return NULL;
1016     }
1017
1018     return p_line;
1019 }
1020
1021 static int SetFontSize( filter_t *p_filter, int i_size )
1022 {
1023     filter_sys_t *p_sys = p_filter->p_sys;
1024
1025     if( i_size && i_size == p_sys->i_font_size ) return VLC_SUCCESS;
1026
1027     if( !i_size )
1028     {
1029         vlc_value_t val;
1030
1031         if( !p_sys->i_default_font_size &&
1032             p_sys->i_display_height == (int)p_filter->fmt_out.video.i_height )
1033             return VLC_SUCCESS;
1034
1035         if( p_sys->i_default_font_size )
1036         {
1037             i_size = p_sys->i_default_font_size;
1038         }
1039         else
1040         {
1041             var_Get( p_filter, "freetype-rel-fontsize", &val );
1042             i_size = (int)p_filter->fmt_out.video.i_height / val.i_int;
1043             p_filter->p_sys->i_display_height =
1044                 p_filter->fmt_out.video.i_height;
1045         }
1046         if( i_size <= 0 )
1047         {
1048             msg_Warn( p_filter, "Invalid fontsize, using 12" );
1049             i_size = 12;
1050         }
1051
1052         msg_Dbg( p_filter, "Using fontsize: %i", i_size );
1053     }
1054
1055     p_sys->i_font_size = i_size;
1056
1057     if( FT_Set_Pixel_Sizes( p_sys->p_face, 0, i_size ) )
1058     {
1059         msg_Err( p_filter, "couldn't set font size to %d", i_size );
1060         return VLC_EGENERIC;
1061     }
1062
1063     return VLC_SUCCESS;
1064 }