]> git.sesse.net Git - vlc/blob - modules/misc/freetype.c
FSF address change.
[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 SYS_DARWIN
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 static int pi_color_values[] = {
103   0x00000000, 0x00808080, 0x00C0C0C0, 0x00FFFFFF, 0x00800000,
104   0x00FF0000, 0x00FF00FF, 0x00FFFF00, 0x00808000, 0x00008000, 0x00008080, 
105   0x0000FF00, 0x00800080, 0x00000080, 0x000000FF, 0x0000FFFF }; 
106
107 static char *ppsz_color_descriptions[] = {
108   N_("Black"), N_("Gray"), N_("Silver"), N_("White"), N_("Maroon"),
109   N_("Red"), N_("Fuchsia"), N_("Yellow"), N_("Olive"), N_("Green"), N_("Teal"),
110   N_("Lime"), N_("Purple"), N_("Navy"), N_("Blue"), N_("Aqua") };
111
112 vlc_module_begin();
113     set_shortname( _("Text renderer"));
114     set_description( _("Freetype2 font renderer") );
115     set_category( CAT_VIDEO );
116     set_subcategory( SUBCAT_VIDEO_SUBPIC );
117
118     add_file( "freetype-font", DEFAULT_FONT, NULL, FONT_TEXT, FONT_LONGTEXT,
119               VLC_FALSE );
120
121     add_integer( "freetype-fontsize", 0, NULL, FONTSIZE_TEXT,
122                  FONTSIZE_LONGTEXT, VLC_TRUE );
123
124     /* opacity valid on 0..255, with default 255 = fully opaque */
125     add_integer_with_range( "freetype-opacity", 255, 0, 255, NULL,
126         OPACITY_TEXT, OPACITY_LONGTEXT, VLC_TRUE );
127
128     /* hook to the color values list, with default 0x00ffffff = white */
129     add_integer( "freetype-color", 0x00FFFFFF, NULL, COLOR_TEXT,
130                  COLOR_LONGTEXT, VLC_FALSE );
131         change_integer_list( pi_color_values, ppsz_color_descriptions, 0 );
132
133     add_integer( "freetype-rel-fontsize", 16, NULL, FONTSIZER_TEXT,
134                  FONTSIZER_LONGTEXT, VLC_FALSE );
135         change_integer_list( pi_sizes, ppsz_sizes_text, 0 );
136
137     set_capability( "text renderer", 100 );
138     add_shortcut( "text" );
139     set_callbacks( Create, Destroy );
140 vlc_module_end();
141
142 struct line_desc_t
143 {
144     /** NULL-terminated list of glyphs making the string */
145     FT_BitmapGlyph *pp_glyphs;
146     /** list of relative positions for the glyphs */
147     FT_Vector      *p_glyph_pos;
148
149     int             i_height;
150     int             i_width;
151     int             i_red, i_green, i_blue;
152     int             i_alpha;
153
154     line_desc_t    *p_next;
155 };
156
157 static int Render( filter_t *, subpicture_region_t *, line_desc_t *, int, int);
158 static void FreeLines( line_desc_t * );
159 static void FreeLine( line_desc_t * );
160
161 /*****************************************************************************
162  * filter_sys_t: freetype local data
163  *****************************************************************************
164  * This structure is part of the video output thread descriptor.
165  * It describes the freetype specific properties of an output thread.
166  *****************************************************************************/
167 struct filter_sys_t
168 {
169     FT_Library     p_library;   /* handle to library     */
170     FT_Face        p_face;      /* handle to face object */
171     vlc_bool_t     i_use_kerning;
172     uint8_t        i_font_opacity;
173     int            i_font_color;
174     int            i_font_size;
175
176     int            i_default_font_size;
177     int            i_display_height;
178 };
179
180 /*****************************************************************************
181  * Create: allocates osd-text video thread output method
182  *****************************************************************************
183  * This function allocates and initializes a Clone vout method.
184  *****************************************************************************/
185 static int Create( vlc_object_t *p_this )
186 {
187     filter_t *p_filter = (filter_t *)p_this;
188     filter_sys_t *p_sys;
189     char *psz_fontfile = NULL;
190     int i_error;
191     vlc_value_t val;
192
193     /* Allocate structure */
194     p_filter->p_sys = p_sys = malloc( sizeof( filter_sys_t ) );
195     if( !p_sys )
196     {
197         msg_Err( p_filter, "out of memory" );
198         return VLC_ENOMEM;
199     }
200     p_sys->p_face = 0;
201     p_sys->p_library = 0;
202     p_sys->i_font_size = 0;
203     p_sys->i_display_height = 0;
204
205     var_Create( p_filter, "freetype-font",
206                 VLC_VAR_STRING | VLC_VAR_DOINHERIT );
207     var_Create( p_filter, "freetype-fontsize",
208                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
209     var_Create( p_filter, "freetype-rel-fontsize",
210                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
211     var_Create( p_filter, "freetype-opacity",
212                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
213     var_Get( p_filter, "freetype-opacity", &val );
214     p_sys->i_font_opacity = __MAX( __MIN( val.i_int, 255 ), 0 );
215     var_Create( p_filter, "freetype-color",
216                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
217     var_Get( p_filter, "freetype-color", &val );
218     p_sys->i_font_color = __MAX( __MIN( val.i_int, 0xFFFFFF ), 0 );
219
220     /* Look what method was requested */
221     var_Get( p_filter, "freetype-font", &val );
222     psz_fontfile = val.psz_string;
223     if( !psz_fontfile || !*psz_fontfile )
224     {
225         if( psz_fontfile ) free( psz_fontfile );
226         psz_fontfile = (char *)malloc( PATH_MAX + 1 );
227 #ifdef WIN32
228         GetWindowsDirectory( psz_fontfile, PATH_MAX + 1 );
229         strcat( psz_fontfile, "\\fonts\\arial.ttf" );
230 #elif SYS_DARWIN
231         strcpy( psz_fontfile, DEFAULT_FONT );
232 #else
233         msg_Err( p_filter, "user didn't specify a font" );
234         goto error;
235 #endif
236     }
237
238     i_error = FT_Init_FreeType( &p_sys->p_library );
239     if( i_error )
240     {
241         msg_Err( p_filter, "couldn't initialize freetype" );
242         goto error;
243     }
244
245     i_error = FT_New_Face( p_sys->p_library, psz_fontfile ? psz_fontfile : "",
246                            0, &p_sys->p_face );
247     if( i_error == FT_Err_Unknown_File_Format )
248     {
249         msg_Err( p_filter, "file %s have unknown format", psz_fontfile );
250         goto error;
251     }
252     else if( i_error )
253     {
254         msg_Err( p_filter, "failed to load font file %s", psz_fontfile );
255         goto error;
256     }
257
258     i_error = FT_Select_Charmap( p_sys->p_face, ft_encoding_unicode );
259     if( i_error )
260     {
261         msg_Err( p_filter, "Font has no unicode translation table" );
262         goto error;
263     }
264
265     p_sys->i_use_kerning = FT_HAS_KERNING( p_sys->p_face );
266
267     var_Get( p_filter, "freetype-fontsize", &val );
268     p_sys->i_default_font_size = val.i_int;
269     if( SetFontSize( p_filter, 0 ) != VLC_SUCCESS ) goto error;
270
271     if( psz_fontfile ) free( psz_fontfile );
272     p_filter->pf_render_text = RenderText;
273     return VLC_SUCCESS;
274
275  error:
276     if( p_sys->p_face ) FT_Done_Face( p_sys->p_face );
277     if( p_sys->p_library ) FT_Done_FreeType( p_sys->p_library );
278     if( psz_fontfile ) free( psz_fontfile );
279     free( p_sys );
280     return VLC_EGENERIC;
281 }
282
283 /*****************************************************************************
284  * Destroy: destroy Clone video thread output method
285  *****************************************************************************
286  * Clean up all data and library connections
287  *****************************************************************************/
288 static void Destroy( vlc_object_t *p_this )
289 {
290     filter_t *p_filter = (filter_t *)p_this;
291     filter_sys_t *p_sys = p_filter->p_sys;
292
293     FT_Done_Face( p_sys->p_face );
294     FT_Done_FreeType( p_sys->p_library );
295     free( p_sys );
296 }
297
298 /*****************************************************************************
299  * Render: place string in picture
300  *****************************************************************************
301  * This function merges the previously rendered freetype glyphs into a picture
302  *****************************************************************************/
303 static int Render( filter_t *p_filter, subpicture_region_t *p_region,
304                    line_desc_t *p_line, int i_width, int i_height )
305 {
306     static uint8_t pi_gamma[16] =
307         {0x00, 0x52, 0x84, 0x96, 0xb8, 0xca, 0xdc, 0xee, 0xff,
308           0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
309
310     uint8_t *p_dst;
311     video_format_t fmt;
312     int i, x, y, i_pitch;
313     uint8_t i_y; /* YUV values, derived from incoming RGB */
314     int8_t i_u, i_v;
315     subpicture_region_t *p_region_tmp;
316
317     /* Create a new subpicture region */
318     memset( &fmt, 0, sizeof(video_format_t) );
319     fmt.i_chroma = VLC_FOURCC('Y','U','V','P');
320     fmt.i_aspect = 0;
321     fmt.i_width = fmt.i_visible_width = i_width + 4;
322     fmt.i_height = fmt.i_visible_height = i_height + 4;
323     fmt.i_x_offset = fmt.i_y_offset = 0;
324     p_region_tmp = spu_CreateRegion( p_filter, &fmt );
325     if( !p_region_tmp )
326     {
327         msg_Err( p_filter, "cannot allocate SPU region" );
328         return VLC_EGENERIC;
329     }
330
331     p_region->fmt = p_region_tmp->fmt;
332     p_region->picture = p_region_tmp->picture;
333     free( p_region_tmp );
334
335     /* Calculate text color components */
336     i_y = (uint8_t)(( 66 * p_line->i_red  + 129 * p_line->i_green +
337                       25 * p_line->i_blue + 128) >> 8) +  16;
338     i_u = (int8_t)(( -38 * p_line->i_red  -  74 * p_line->i_green +
339                      112 * p_line->i_blue + 128) >> 8) + 128;
340     i_v = (int8_t)(( 112 * p_line->i_red  -  94 * p_line->i_green -
341                       18 * p_line->i_blue + 128) >> 8) + 128;
342
343     /* Build palette */
344     fmt.p_palette->i_entries = 16;
345     for( i = 0; i < 8; i++ )
346     {
347         fmt.p_palette->palette[i][0] = 0;
348         fmt.p_palette->palette[i][1] = 0x80;
349         fmt.p_palette->palette[i][2] = 0x80;
350         fmt.p_palette->palette[i][3] = pi_gamma[i];
351         fmt.p_palette->palette[i][3] =
352             (int)fmt.p_palette->palette[i][3] * (255 - p_line->i_alpha) / 255;
353     }
354     for( i = 8; i < fmt.p_palette->i_entries; i++ )
355     {
356         fmt.p_palette->palette[i][0] = i * 16 * i_y / 256;
357         fmt.p_palette->palette[i][1] = i_u;
358         fmt.p_palette->palette[i][2] = i_v;
359         fmt.p_palette->palette[i][3] = pi_gamma[i];
360         fmt.p_palette->palette[i][3] =
361             (int)fmt.p_palette->palette[i][3] * (255 - p_line->i_alpha) / 255;
362     }
363
364     p_dst = p_region->picture.Y_PIXELS;
365     i_pitch = p_region->picture.Y_PITCH;
366
367     /* Initialize the region pixels */
368     memset( p_dst, 0, i_pitch * p_region->fmt.i_height );
369
370     for( ; p_line != NULL; p_line = p_line->p_next )
371     {
372         int i_glyph_tmax = 0;
373         int i_bitmap_offset, i_offset, i_align_offset = 0;
374         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
375         {
376             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
377             i_glyph_tmax = __MAX( i_glyph_tmax, p_glyph->top );
378         }
379
380         if( p_line->i_width < i_width )
381         {
382             if( p_region->i_text_align == SUBPICTURE_ALIGN_RIGHT )
383             {
384                 i_align_offset = i_width - p_line->i_width;
385             }
386             else if( p_region->i_text_align != SUBPICTURE_ALIGN_LEFT )
387             {
388                 i_align_offset = ( i_width - p_line->i_width ) / 2;
389             }
390         }
391
392         for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
393         {
394             FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
395
396             i_offset = ( p_line->p_glyph_pos[ i ].y +
397                 i_glyph_tmax - p_glyph->top + 2 ) *
398                 i_pitch + p_line->p_glyph_pos[ i ].x + p_glyph->left + 2 +
399                 i_align_offset;
400
401             for( y = 0, i_bitmap_offset = 0; y < p_glyph->bitmap.rows; y++ )
402             {
403                 for( x = 0; x < p_glyph->bitmap.width; x++, i_bitmap_offset++ )
404                 {
405                     if( p_glyph->bitmap.buffer[i_bitmap_offset] )
406                         p_dst[i_offset+x] =
407                          ((int)p_glyph->bitmap.buffer[i_bitmap_offset] + 8)/16;
408                 }
409                 i_offset += i_pitch;
410             }
411         }
412     }
413
414     /* Outlining (find something better than nearest neighbour filtering ?) */
415     if( 1 )
416     {
417         uint8_t *p_dst = p_region->picture.Y_PIXELS;
418         uint8_t *p_top = p_dst; /* Use 1st line as a cache */
419         uint8_t left, current;
420
421         for( y = 1; y < (int)fmt.i_height - 1; y++ )
422         {
423             if( y > 1 ) memcpy( p_top, p_dst, fmt.i_width );
424             p_dst += p_region->picture.Y_PITCH;
425             left = 0;
426
427             for( x = 1; x < (int)fmt.i_width - 1; x++ )
428             {
429                 current = p_dst[x];
430                 p_dst[x] = ( 8 * (int)p_dst[x] + left + p_dst[x+1] + p_top[x -1]+ p_top[x] + p_top[x+1] +
431                              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;
432                 left = current;
433             }
434         }
435         memset( p_top, 0, fmt.i_width );
436     }
437
438     return VLC_SUCCESS;
439 }
440
441 /**
442  * This function renders a text subpicture region into another one.
443  * It also calculates the size needed for this string, and renders the
444  * needed glyphs into memory. It is used as pf_add_string callback in
445  * the vout method by this module
446  */
447 static int RenderText( filter_t *p_filter, subpicture_region_t *p_region_out,
448                        subpicture_region_t *p_region_in )
449 {
450     filter_sys_t *p_sys = p_filter->p_sys;
451     line_desc_t  *p_lines = 0, *p_line = 0, *p_next = 0, *p_prev = 0;
452     int i, i_pen_y, i_pen_x, i_error, i_glyph_index, i_previous;
453     uint32_t *psz_unicode, *psz_unicode_orig = 0, i_char, *psz_line_start;
454     int i_string_length;
455     char *psz_string;
456     vlc_iconv_t iconv_handle = (vlc_iconv_t)(-1);
457     int i_font_color, i_font_alpha, i_font_size, i_red, i_green, i_blue;
458
459     FT_BBox line;
460     FT_BBox glyph_size;
461     FT_Vector result;
462     FT_Glyph tmp_glyph;
463
464     /* Sanity check */
465     if( !p_region_in || !p_region_out ) return VLC_EGENERIC;
466     psz_string = p_region_in->psz_text;
467     if( !psz_string || !*psz_string ) return VLC_EGENERIC;
468
469     i_font_color = __MAX( __MIN( p_region_in->i_text_color, 0xFFFFFF ), 0 );
470     if( i_font_color == 0xFFFFFF ) i_font_color = p_sys->i_font_color;
471
472     i_font_alpha = __MAX( __MIN( p_region_in->i_text_alpha, 255 ), 0 );
473     if( !i_font_alpha ) i_font_alpha = 255 - p_sys->i_font_opacity;
474
475     i_font_size  = __MAX( __MIN( p_region_in->i_text_size, 255 ), 0 );
476     SetFontSize( p_filter, i_font_size );
477
478     i_red   = ( i_font_color & 0x00FF0000 ) >> 16;
479     i_green = ( i_font_color & 0x0000FF00 ) >>  8;
480     i_blue  =   i_font_color & 0x000000FF;
481
482     result.x =  result.y = 0;
483     line.xMin = line.xMax = line.yMin = line.yMax = 0;
484
485     psz_unicode = psz_unicode_orig =
486         malloc( ( strlen(psz_string) + 1 ) * sizeof(uint32_t) );
487     if( psz_unicode == NULL )
488     {
489         msg_Err( p_filter, "out of memory" );
490         goto error;
491     }
492 #if defined(WORDS_BIGENDIAN)
493     iconv_handle = vlc_iconv_open( "UCS-4BE", "UTF-8" );
494 #else
495     iconv_handle = vlc_iconv_open( "UCS-4LE", "UTF-8" );
496 #endif
497     if( iconv_handle == (vlc_iconv_t)-1 )
498     {
499         msg_Warn( p_filter, "unable to do conversion" );
500         goto error;
501     }
502
503     {
504         char *p_in_buffer, *p_out_buffer;
505         size_t i_in_bytes, i_out_bytes, i_out_bytes_left, i_ret;
506         i_in_bytes = strlen( psz_string );
507         i_out_bytes = i_in_bytes * sizeof( uint32_t );
508         i_out_bytes_left = i_out_bytes;
509         p_in_buffer = psz_string;
510         p_out_buffer = (char *)psz_unicode;
511         i_ret = vlc_iconv( iconv_handle, &p_in_buffer, &i_in_bytes,
512                            &p_out_buffer, &i_out_bytes_left );
513
514         vlc_iconv_close( iconv_handle );
515
516         if( i_in_bytes )
517         {
518             msg_Warn( p_filter, "failed to convert string to unicode (%s), "
519                       "bytes left %d", strerror(errno), i_in_bytes );
520             goto error;
521         }
522         *(uint32_t*)p_out_buffer = 0;
523         i_string_length = (i_out_bytes - i_out_bytes_left) / sizeof(uint32_t);
524     }
525
526 #if defined(HAVE_FRIBIDI)
527     {
528         uint32_t *p_fribidi_string;
529         int start_pos, pos = 0;
530         
531         p_fribidi_string = malloc( (i_string_length + 1) * sizeof(uint32_t) );
532
533         /* Do bidi conversion line-by-line */
534         while(pos < i_string_length)
535         {
536             while(pos < i_string_length) {
537                 i_char = psz_unicode[pos];
538                 if (i_char != '\r' && i_char != '\n')
539                     break;
540                 p_fribidi_string[pos] = i_char;
541                 ++pos;
542             }
543             start_pos = pos;
544             while(pos < i_string_length) {
545                 i_char = psz_unicode[pos];
546                 if (i_char == '\r' || i_char == '\n')
547                     break;
548                 ++pos;
549             }
550             if (pos > start_pos)
551             {
552                 FriBidiCharType base_dir = FRIBIDI_TYPE_LTR;
553                 fribidi_log2vis((FriBidiChar*)psz_unicode + start_pos, pos - start_pos,
554                                 &base_dir, (FriBidiChar*)p_fribidi_string + start_pos, 0, 0, 0);
555             }
556         }
557
558         free( psz_unicode_orig );
559         psz_unicode = psz_unicode_orig = p_fribidi_string;
560         p_fribidi_string[ i_string_length ] = 0;
561     }
562 #endif
563
564     /* Calculate relative glyph positions and a bounding box for the
565      * entire string */
566     if( !(p_line = NewLine( psz_string )) )
567     {
568         msg_Err( p_filter, "out of memory" );
569         goto error;
570     }
571     p_lines = p_line;
572     i_pen_x = i_pen_y = 0;
573     i_previous = i = 0;
574     psz_line_start = psz_unicode;
575
576 #define face p_sys->p_face
577 #define glyph face->glyph
578
579     while( *psz_unicode )
580     {
581         i_char = *psz_unicode++;
582         if( i_char == '\r' ) /* ignore CR chars wherever they may be */
583         {
584             continue;
585         }
586
587         if( i_char == '\n' )
588         {
589             psz_line_start = psz_unicode;
590             if( !(p_next = NewLine( psz_string )) )
591             {
592                 msg_Err( p_filter, "out of memory" );
593                 goto error;
594             }
595             p_line->p_next = p_next;
596             p_line->i_width = line.xMax;
597             p_line->i_height = face->size->metrics.height >> 6;
598             p_line->pp_glyphs[ i ] = NULL;
599             p_line->i_alpha = i_font_alpha;
600             p_line->i_red = i_red;
601             p_line->i_green = i_green;
602             p_line->i_blue = i_blue;
603             p_prev = p_line;
604             p_line = p_next;
605             result.x = __MAX( result.x, line.xMax );
606             result.y += face->size->metrics.height >> 6;
607             i_pen_x = 0;
608             i_previous = i = 0;
609             line.xMin = line.xMax = line.yMin = line.yMax = 0;
610             i_pen_y += face->size->metrics.height >> 6;
611 #if 0
612             msg_Dbg( p_filter, "Creating new line, i is %d", i );
613 #endif
614             continue;
615         }
616
617         i_glyph_index = FT_Get_Char_Index( face, i_char );
618         if( p_sys->i_use_kerning && i_glyph_index
619             && i_previous )
620         {
621             FT_Vector delta;
622             FT_Get_Kerning( face, i_previous, i_glyph_index,
623                             ft_kerning_default, &delta );
624             i_pen_x += delta.x >> 6;
625
626         }
627         p_line->p_glyph_pos[ i ].x = i_pen_x;
628         p_line->p_glyph_pos[ i ].y = i_pen_y;
629         i_error = FT_Load_Glyph( face, i_glyph_index, FT_LOAD_DEFAULT );
630         if( i_error )
631         {
632             msg_Err( p_filter, "FT_Load_Glyph returned %d", i_error );
633             goto error;
634         }
635         i_error = FT_Get_Glyph( glyph, &tmp_glyph );
636         if( i_error )
637         {
638             msg_Err( p_filter, "FT_Get_Glyph returned %d", i_error );
639             goto error;
640         }
641         FT_Glyph_Get_CBox( tmp_glyph, ft_glyph_bbox_pixels, &glyph_size );
642         i_error = FT_Glyph_To_Bitmap( &tmp_glyph, ft_render_mode_normal, 0, 1);
643         if( i_error )
644         {
645             FT_Done_Glyph( tmp_glyph );
646             continue;
647         }
648         p_line->pp_glyphs[ i ] = (FT_BitmapGlyph)tmp_glyph;
649
650         /* Do rest */
651         line.xMax = p_line->p_glyph_pos[i].x + glyph_size.xMax -
652             glyph_size.xMin + ((FT_BitmapGlyph)tmp_glyph)->left;
653         if( line.xMax > (int)p_filter->fmt_out.video.i_visible_width - 20 )
654         {
655             p_line->pp_glyphs[ i ] = NULL;
656             FreeLine( p_line );
657             p_line = NewLine( psz_string );
658             if( p_prev ) p_prev->p_next = p_line;
659             else p_lines = p_line;
660
661             while( psz_unicode > psz_line_start && *psz_unicode != ' ' )
662             {
663                 psz_unicode--;
664             }
665             if( psz_unicode == psz_line_start )
666             {
667                 msg_Warn( p_filter, "unbreakable string" );
668                 goto error;
669             }
670             else
671             {
672                 *psz_unicode = '\n';
673             }
674             psz_unicode = psz_line_start;
675             i_pen_x = 0;
676             i_previous = i = 0;
677             line.xMin = line.xMax = line.yMin = line.yMax = 0;
678             continue;
679         }
680         line.yMax = __MAX( line.yMax, glyph_size.yMax );
681         line.yMin = __MIN( line.yMin, glyph_size.yMin );
682
683         i_previous = i_glyph_index;
684         i_pen_x += glyph->advance.x >> 6;
685         i++;
686     }
687
688     p_line->i_width = line.xMax;
689     p_line->i_height = face->size->metrics.height >> 6;
690     p_line->pp_glyphs[ i ] = NULL;
691     p_line->i_alpha = i_font_alpha;
692     p_line->i_red = i_red;
693     p_line->i_green = i_green;
694     p_line->i_blue = i_blue;
695     result.x = __MAX( result.x, line.xMax );
696     result.y += line.yMax - line.yMin;
697
698 #undef face
699 #undef glyph
700
701     p_region_out->i_x = p_region_in->i_x;
702     p_region_out->i_y = p_region_in->i_y;
703
704     Render( p_filter, p_region_out, p_lines, result.x, result.y );
705
706     if( psz_unicode_orig ) free( psz_unicode_orig );
707     FreeLines( p_lines );
708     return VLC_SUCCESS;
709
710  error:
711     if( psz_unicode_orig ) free( psz_unicode_orig );
712     FreeLines( p_lines );
713     return VLC_EGENERIC;
714 }
715
716 static void FreeLine( line_desc_t *p_line )
717 {
718     unsigned int i;
719     for( i = 0; p_line->pp_glyphs[ i ] != NULL; i++ )
720     {
721         FT_Done_Glyph( (FT_Glyph)p_line->pp_glyphs[ i ] );
722     }
723     free( p_line->pp_glyphs );
724     free( p_line->p_glyph_pos );
725     free( p_line );
726 }
727
728 static void FreeLines( line_desc_t *p_lines )
729 {
730     line_desc_t *p_line, *p_next;
731
732     if( !p_lines ) return;
733
734     for( p_line = p_lines; p_line != NULL; p_line = p_next )
735     {
736         p_next = p_line->p_next;
737         FreeLine( p_line );
738     }
739 }
740
741 static line_desc_t *NewLine( byte_t *psz_string )
742 {
743     int i_count;
744     line_desc_t *p_line = malloc( sizeof(line_desc_t) );
745
746     if( !p_line ) return NULL;
747     p_line->i_height = 0;
748     p_line->i_width = 0;
749     p_line->p_next = NULL;
750
751     /* We don't use CountUtf8Characters() here because we are not acutally
752      * sure the string is utf8. Better be safe than sorry. */
753     i_count = strlen( psz_string );
754
755     p_line->pp_glyphs = malloc( sizeof(FT_BitmapGlyph) * ( i_count + 1 ) );
756     if( p_line->pp_glyphs == NULL )
757     {
758         free( p_line );
759         return NULL;
760     }
761     p_line->pp_glyphs[0] = NULL;
762
763     p_line->p_glyph_pos = malloc( sizeof( FT_Vector ) * i_count + 1 );
764     if( p_line->p_glyph_pos == NULL )
765     {
766         free( p_line->pp_glyphs );
767         free( p_line );
768         return NULL;
769     }
770
771     return p_line;
772 }
773
774 static int SetFontSize( filter_t *p_filter, int i_size )
775 {
776     filter_sys_t *p_sys = p_filter->p_sys;
777
778     if( i_size && i_size == p_sys->i_font_size ) return VLC_SUCCESS;
779
780     if( !i_size )
781     {
782         vlc_value_t val;
783
784         if( !p_sys->i_default_font_size &&
785             p_sys->i_display_height == (int)p_filter->fmt_out.video.i_height )
786             return VLC_SUCCESS;
787
788         if( p_sys->i_default_font_size )
789         {
790             i_size = p_sys->i_default_font_size;
791         }
792         else
793         {
794             var_Get( p_filter, "freetype-rel-fontsize", &val );
795             i_size = (int)p_filter->fmt_out.video.i_height / val.i_int;
796             p_filter->p_sys->i_display_height =
797                 p_filter->fmt_out.video.i_height;
798         }
799         if( i_size <= 0 )
800         {
801             msg_Warn( p_filter, "Invalid fontsize, using 12" );
802             i_size = 12;
803         }
804
805         msg_Dbg( p_filter, "Using fontsize: %i", i_size );
806     }
807
808     p_sys->i_font_size = i_size;
809
810     if( FT_Set_Pixel_Sizes( p_sys->p_face, 0, i_size ) )
811     {
812         msg_Err( p_filter, "couldn't set font size to %d", i_size );
813         return VLC_EGENERIC;
814     }
815
816     return VLC_SUCCESS;
817 }