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