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