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