]> git.sesse.net Git - vlc/blob - modules/misc/freetype.c
* Set the default font on Mac OS X to the system font.
[vlc] / modules / misc / freetype.c
1 /*****************************************************************************
2  * freetype.c : Put text on the video, using freetype2
3  *****************************************************************************
4  * Copyright (C) 2002, 2003 VideoLAN
5  * $Id: freetype.c,v 1.6 2003/07/20 21:41:13 hartman Exp $
6  *
7  * Authors: Sigmund Augdal <sigmunau@idi.ntnu.no>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28 #include <string.h>
29
30 #include <vlc/vlc.h>
31 #include <vlc/vout.h>
32 #include <osd.h>
33 #include <math.h>
34
35 #include <ft2build.h>
36 #include FT_FREETYPE_H
37 #include FT_GLYPH_H
38
39 #ifdef SYS_DARWIN
40 #define DEFAULT_FONT "/System/Library/Fonts/LucidaGrande.dfont"
41 #else
42 #define DEFAULT_FONT ""
43 #endif
44
45 /*****************************************************************************
46  * Local prototypes
47  *****************************************************************************/
48 static int  Create    ( vlc_object_t * );
49 static void Destroy   ( vlc_object_t * );
50
51 static void Render    ( vout_thread_t *, picture_t *,
52                         const subpicture_t * );
53 static void RenderI420( vout_thread_t *, picture_t *,
54                         const subpicture_t * );
55 static int  AddText   ( vout_thread_t *, byte_t *, text_style_t *, int,
56                         int, int, mtime_t, mtime_t );
57 static int GetUnicodeCharFromUTF8( byte_t ** );
58
59 /*****************************************************************************
60  * Module descriptor
61  *****************************************************************************/
62 #define FONT_TEXT N_("Font")
63 #define FONT_LONGTEXT N_("Filename of Font")
64 #define FONTSIZE_TEXT N_("Font size")
65 #define FONTSIZE_LONGTEXT N_("The size of the fonts used by the osd module" )
66
67 vlc_module_begin();
68     add_category_hint( N_("Fonts"), NULL, VLC_FALSE );
69     add_file( "freetype-font", DEFAULT_FONT, NULL, FONT_TEXT, FONT_LONGTEXT, VLC_FALSE );
70     add_integer( "freetype-fontsize", 16, NULL, FONTSIZE_TEXT, FONTSIZE_LONGTEXT, VLC_FALSE );
71     set_description( _("freetype2 font renderer") );
72     set_capability( "text renderer", 100 );
73     add_shortcut( "text" );
74     set_callbacks( Create, Destroy );
75 vlc_module_end();
76
77 /**
78  Describes a string to be displayed on the video, or a linked list of
79  such
80 */
81 struct subpicture_sys_t
82 {
83     int            i_x_margin;
84     int            i_y_margin;
85     int            i_width;
86     int            i_height;
87     int            i_flags;
88     /** The string associated with this subpicture */
89     byte_t        *psz_text;
90     /** NULL-terminated list of glyphs making the string */
91     FT_BitmapGlyph      *pp_glyphs;
92     /** list of relative positions for the glyphs */
93     FT_Vector     *p_glyph_pos;
94 };
95
96 /*****************************************************************************
97  * vout_sys_t: osd_text local data
98  *****************************************************************************
99  * This structure is part of the video output thread descriptor.
100  * It describes the osd-text specific properties of an output thread.
101  *****************************************************************************/
102 struct text_renderer_sys_t
103 {
104     FT_Library     p_library;   /* handle to library     */
105     FT_Face        p_face;      /* handle to face object */
106     vlc_mutex_t   *lock;
107     vlc_bool_t     i_use_kerning;
108     uint8_t        pi_gamma[256];
109 };
110 /* more prototypes */
111 //static void ComputeBoundingBox( subpicture_sys_t * );
112 static void FreeString( subpicture_t * );
113
114 /*****************************************************************************
115  * Create: allocates osd-text video thread output method
116  *****************************************************************************
117  * This function allocates and initializes a Clone vout method.
118  *****************************************************************************/
119 #define gamma_value 2.0
120 static int Create( vlc_object_t *p_this )
121 {
122     vout_thread_t *p_vout = (vout_thread_t *)p_this;
123     char *psz_fontfile;
124     int i, i_error;
125     double gamma_inv = 1.0f / gamma_value;
126
127     /* Allocate structure */
128     p_vout->p_text_renderer_data = malloc( sizeof( text_renderer_sys_t ) );
129     if( p_vout->p_text_renderer_data == NULL )
130     {
131         msg_Err( p_vout, "out of memory" );
132         return VLC_ENOMEM;
133     }
134
135     for (i = 0; i < 256; i++) {
136         p_vout->p_text_renderer_data->pi_gamma[i] =
137             (uint8_t)( pow( (double)i / 255.0f, gamma_inv) * 255.0f );
138         //msg_Dbg( p_vout, "%d", p_vout->p_text_renderer_data->pi_gamma[i]);
139     }
140
141     /* Look what method was requested */
142     psz_fontfile = config_GetPsz( p_vout, "freetype-font" );
143     i_error = FT_Init_FreeType( &p_vout->p_text_renderer_data->p_library );
144     if( i_error )
145     {
146         msg_Err( p_vout, "couldn't initialize freetype" );
147         free( p_vout->p_text_renderer_data );
148         return VLC_EGENERIC;
149     }
150     i_error = FT_New_Face( p_vout->p_text_renderer_data->p_library,
151                            psz_fontfile, 0,
152                            &p_vout->p_text_renderer_data->p_face );
153     if( i_error == FT_Err_Unknown_File_Format )
154     {
155         msg_Err( p_vout, "file %s have unknown format", psz_fontfile );
156         FT_Done_FreeType( p_vout->p_text_renderer_data->p_library );
157         free( p_vout->p_text_renderer_data );
158         return VLC_EGENERIC;
159     }
160     else if( i_error )
161     {
162         msg_Err( p_vout, "failed to load font file" );
163         FT_Done_FreeType( p_vout->p_text_renderer_data->p_library );
164         free( p_vout->p_text_renderer_data );
165         return VLC_EGENERIC;
166     }
167     i_error = FT_Select_Charmap( p_vout->p_text_renderer_data->p_face,
168                                  ft_encoding_unicode );
169     if ( i_error )
170     {
171         msg_Err( p_vout, "Font has no unicode translation table" );
172         FT_Done_Face( p_vout->p_text_renderer_data->p_face );
173         FT_Done_FreeType( p_vout->p_text_renderer_data->p_library );
174         free( p_vout->p_text_renderer_data );
175         return VLC_EGENERIC;
176     }
177
178     p_vout->p_text_renderer_data->i_use_kerning =
179         FT_HAS_KERNING(p_vout->p_text_renderer_data->p_face);
180
181     i_error = FT_Set_Pixel_Sizes( p_vout->p_text_renderer_data->p_face, 0,
182                                   config_GetInt( p_vout, "freetype-fontsize" ) );
183     if( i_error )
184     {
185         msg_Err( p_vout, "couldn't set font size to %d",
186                  config_GetInt( p_vout, "osd-fontsize" ) );
187         free( p_vout->p_text_renderer_data );
188         return VLC_EGENERIC;
189     }
190     p_vout->pf_add_string = AddText;
191     return VLC_SUCCESS;
192 }
193
194 /*****************************************************************************
195  * Destroy: destroy Clone video thread output method
196  *****************************************************************************
197  * Clean up all data and library connections
198  *****************************************************************************/
199 static void Destroy( vlc_object_t *p_this )
200 {
201     vout_thread_t *p_vout = (vout_thread_t *)p_this;
202     FT_Done_Face( p_vout->p_text_renderer_data->p_face );
203     FT_Done_FreeType( p_vout->p_text_renderer_data->p_library );
204     free( p_vout->p_text_renderer_data );
205 }
206
207 /*****************************************************************************
208  * Render: place string in picture
209  *****************************************************************************
210  * This function merges the previously rendered freetype glyphs into a picture
211  *****************************************************************************/
212 static void Render( vout_thread_t *p_vout, picture_t *p_pic,
213                     const subpicture_t *p_subpic )
214 {
215     switch( p_vout->output.i_chroma )
216     {
217         /* I420 target, no scaling */
218         case VLC_FOURCC('I','4','2','0'):
219         case VLC_FOURCC('I','Y','U','V'):
220         case VLC_FOURCC('Y','V','1','2'):
221             RenderI420( p_vout, p_pic, p_subpic );
222             break;
223 #if 0
224         /* RV16 target, scaling */
225         case VLC_FOURCC('R','V','1','6'):
226             RenderRV16( p_vout, p_pic, p_spu, p_spu->p_sys->b_crop );
227             break;
228
229         /* RV32 target, scaling */
230         case VLC_FOURCC('R','V','2','4'):
231         case VLC_FOURCC('R','V','3','2'):
232             RenderRV32( p_vout, p_pic, p_spu, p_spu->p_sys->b_crop );
233             break;
234
235         /* NVidia overlay, no scaling */
236         case VLC_FOURCC('Y','U','Y','2'):
237             RenderYUY2( p_vout, p_pic, p_spu, p_spu->p_sys->b_crop );
238             break;
239 #endif
240         default:
241             msg_Err( p_vout, "unknown chroma, can't render SPU" );
242             break;
243     }
244 }
245
246 static void RenderI420( vout_thread_t *p_vout, picture_t *p_pic,
247                     const subpicture_t *p_subpic )
248 {
249     subpicture_sys_t *p_string = p_subpic->p_sys;
250     int i_plane, x, y, pen_x, pen_y;
251     unsigned int i;
252
253     for( i_plane = 0 ; i_plane < p_pic->i_planes ; i_plane++ )
254     {
255         uint8_t *p_in;
256         int i_pitch = p_pic->p[i_plane].i_pitch;
257
258         p_in = p_pic->p[i_plane].p_pixels;
259
260         if ( i_plane == 0 )
261         {
262             if ( p_string->i_flags & OSD_ALIGN_BOTTOM )
263             {
264                 pen_y = p_pic->p[i_plane].i_lines - p_string->i_height -
265                     p_string->i_y_margin;
266             }
267             else
268             {
269                 pen_y = p_string->i_y_margin;
270             }
271             if ( p_string->i_flags & OSD_ALIGN_RIGHT )
272             {
273                 pen_x = i_pitch - p_string->i_width
274                     - p_string->i_x_margin;
275             }
276             else
277             {
278                 pen_x = p_string->i_x_margin;
279             }
280
281             for( i = 0; p_string->pp_glyphs[i] != NULL; i++ )
282             {
283                 if( p_string->pp_glyphs[i] )
284                 {
285                     FT_BitmapGlyph p_glyph = p_string->pp_glyphs[ i ];
286 #define alpha p_vout->p_text_renderer_data->pi_gamma[ p_glyph->bitmap.buffer[ x + y * p_glyph->bitmap.width ] ]
287 #define pixel p_in[ ( p_string->p_glyph_pos[ i ].y + pen_y + y - p_glyph->top ) * i_pitch+x + pen_x + p_string->p_glyph_pos[ i ].x + p_glyph->left ]
288                     for(y = 0; y < p_glyph->bitmap.rows; y++ )
289                     {
290                         for( x = 0; x < p_glyph->bitmap.width; x++ )
291                         {
292                             // pixel = alpha;
293                             // pixel = (pixel^alpha)^pixel;
294                             pixel = ( ( pixel * ( 255 - alpha ) ) >> 8 ) +
295                                 ( 255 * alpha >> 8 );
296 #undef alpha
297 #undef pixel
298                         }
299                     }
300                 }
301             }
302         }
303         else
304         {
305             if ( p_string->i_flags & OSD_ALIGN_BOTTOM )
306             {
307                 pen_y = p_pic->p[i_plane].i_lines - ( p_string->i_height>>1) -
308                     (p_string->i_y_margin>>1);
309             }
310             else
311             {
312                 pen_y = p_string->i_y_margin >> 1;
313             }
314             if ( p_string->i_flags & OSD_ALIGN_RIGHT )
315             {
316                 pen_x = i_pitch - ( p_string->i_width >> 1 )
317                     - ( p_string->i_x_margin >> 1 );
318             }
319             else
320             {
321                 pen_x = p_string->i_x_margin >> 1;
322             }
323
324             for( i = 0; p_string->pp_glyphs[i] != NULL; i++ )
325             {
326                 if( p_string->pp_glyphs[i] )
327                 {
328                     FT_BitmapGlyph p_glyph = p_string->pp_glyphs[ i ];
329 #define alpha p_vout->p_text_renderer_data->pi_gamma[ p_glyph->bitmap.buffer[ ( x + y * p_glyph->bitmap.width ) ] ]
330 #define pixel p_in[ ( (p_string->p_glyph_pos[ i ].y>>1) + pen_y + (y>>1) -  ( p_glyph->top >> 1 ) ) * i_pitch + ( x >> 1 ) + pen_x + ( p_string->p_glyph_pos[ i ].x >> 1 ) + ( p_glyph->left >>1) ]
331                     for( y = 0; y < p_glyph->bitmap.rows; y+=2 )
332                     {
333                         for( x = 0; x < p_glyph->bitmap.width; x+=2 )
334                         {
335                             // pixel = alpha;
336                             // pixel = (pixel^alpha)^pixel;
337                             pixel = ( ( pixel * ( 0xFF - alpha ) ) >> 8 ) +
338                                 ( 0x80 * alpha >> 8 );
339 #undef alpha
340 #undef pixel
341                         }
342                     }
343                 }
344             }
345         }
346     }
347 }
348
349 /**
350  * This function receives a string and creates a subpicture for it. It
351  * also calculates the size needed for this string, and renders the
352  * needed glyphs into memory. It is used as pf_add_string callback in
353  * the vout method by this module
354  */
355 static int AddText ( vout_thread_t *p_vout, byte_t *psz_string,
356                      text_style_t *p_style, int i_flags, int i_hmargin,
357                      int i_vmargin, mtime_t i_start, mtime_t i_stop )
358 {
359     subpicture_sys_t *p_string;
360     int i, i_pen_y, i_pen_x, i_error, i_glyph_index, i_previous, i_char;
361     subpicture_t *p_subpic;
362     FT_BBox line;
363     FT_BBox glyph_size;
364     FT_Vector result;
365     FT_Glyph tmp_glyph;
366
367     result.x = 0;
368     result.y = 0;
369     line.xMin = 0;
370     line.xMax = 0;
371     line.yMin = 0;
372     line.yMax = 0;
373
374     /* Create and initialize a subpicture */
375     p_subpic = vout_CreateSubPicture( p_vout, MEMORY_SUBPICTURE );
376     if ( p_subpic == NULL )
377     {
378         return VLC_EGENERIC;
379     }
380     p_subpic->pf_render = Render;
381     p_subpic->pf_destroy = FreeString;
382     p_subpic->i_start = i_start;
383     p_subpic->i_stop = i_stop;
384     if( i_stop == 0 )
385     {
386         p_subpic->b_ephemer = VLC_TRUE;
387     }
388     else
389     {
390         p_subpic->b_ephemer = VLC_FALSE;
391     }
392
393     /* Create and initialize private data for the subpicture */
394     p_string = malloc( sizeof(subpicture_sys_t) );
395     if ( p_string == NULL )
396     {
397         vout_DestroySubPicture( p_vout, p_subpic );
398         return VLC_ENOMEM;
399     }
400     p_subpic->p_sys = p_string;
401     p_string->i_flags = i_flags;
402     p_string->i_x_margin = i_hmargin;
403     p_string->i_y_margin = i_vmargin;
404
405     p_string->psz_text = strdup( psz_string );
406     p_string->pp_glyphs = malloc( sizeof(FT_GlyphSlot)
407                                   * ( strlen( p_string->psz_text ) + 1 ) );
408     if( p_string->pp_glyphs == NULL )
409     {
410         msg_Err( p_vout, "Out of memory" );
411         return VLC_ENOMEM;
412     }
413     p_string->p_glyph_pos = malloc( sizeof( FT_Vector )
414                                   * strlen( p_string->psz_text ) );
415     if( p_string->p_glyph_pos == NULL )
416     {
417         msg_Err( p_vout, "Out of memory" );
418         return VLC_ENOMEM;
419     }
420
421     /* Calculate relative glyph positions and a bounding box for the
422      * entire string */
423     i_pen_x = 0;
424     i_pen_y = 0;
425     i_previous = 0;
426     i = 0;
427     while( *psz_string )
428     {
429         i_char = GetUnicodeCharFromUTF8( &psz_string );
430 #define face p_vout->p_text_renderer_data->p_face
431 #define glyph face->glyph
432         if ( i_char == '\n' )
433         {
434             i_pen_x = 0;
435             result.x = __MAX( result.x, line.xMax );
436             result.y += face->height >> 6;
437             line.xMin = 0;
438             line.xMax = 0;
439             line.yMin = 0;
440             line.yMax = 0;
441             i_pen_y += face->height >> 6;
442             continue;
443         }
444         i_glyph_index = FT_Get_Char_Index( face, i_char );
445         if ( p_vout->p_text_renderer_data->i_use_kerning && i_glyph_index
446             && i_previous )
447         {
448             FT_Vector delta;
449             FT_Get_Kerning( face, i_previous, i_glyph_index,
450                             ft_kerning_default, &delta );
451             i_pen_x += delta.x >> 6;
452
453         }
454         p_string->p_glyph_pos[ i ].x = i_pen_x;
455         p_string->p_glyph_pos[ i ].y = i_pen_y;
456         i_error = FT_Load_Glyph( face, i_glyph_index, FT_LOAD_DEFAULT );
457         if ( i_error )
458         {
459             msg_Err( p_vout, "FT_Load_Glyph returned %d", i_error );
460             return VLC_EGENERIC;
461         }
462         i_error = FT_Get_Glyph( glyph, &tmp_glyph );
463         if ( i_error )
464         {
465             msg_Err( p_vout, "FT_Get_Glyph returned %d", i_error );
466             return VLC_EGENERIC;
467         }
468         FT_Glyph_Get_CBox( tmp_glyph, ft_glyph_bbox_pixels, &glyph_size );
469         i_error = FT_Glyph_To_Bitmap( &tmp_glyph,
470                                       ft_render_mode_normal,
471                                       &p_string->p_glyph_pos[i],
472                                       1 );
473         if ( i_error ) continue;
474         p_string->pp_glyphs[ i ] = (FT_BitmapGlyph)tmp_glyph;
475
476         /* Do rest */
477         line.xMax = p_string->p_glyph_pos[i].x + glyph_size.xMax - glyph_size.xMin;
478         line.yMax = __MAX( line.yMax, glyph_size.yMax );
479         line.yMin = __MIN( line.yMin, glyph_size.yMin );
480
481         i_previous = i_glyph_index;
482         i_pen_x += glyph->advance.x >> 6;
483         i++;
484     }
485     p_string->pp_glyphs[i] = NULL;
486     result.x = __MAX( result.x, line.xMax );
487     result.y += line.yMax - line.yMin;
488     p_string->i_height = result.y;
489     p_string->i_width = result.x;
490     msg_Dbg( p_vout, "string height is %d, width is %d",
491              p_string->i_height, p_string->i_width );
492     msg_Dbg( p_vout, "adding string \"%s\" at (%d,%d) start_date "I64Fd
493              " end_date" I64Fd, p_string->psz_text, p_string->i_x_margin,
494              p_string->i_y_margin, i_start, i_stop );
495     vout_DisplaySubPicture( p_vout, p_subpic );
496     return VLC_SUCCESS;
497 }
498
499 static void FreeString( subpicture_t *p_subpic )
500 {
501     unsigned int i;
502     subpicture_sys_t *p_string = p_subpic->p_sys;
503     for ( i = 0; p_string->pp_glyphs[ i ] != NULL; i++ )
504     {
505         FT_Done_Glyph( (FT_Glyph)p_string->pp_glyphs[ i ] );
506     }
507     free( p_string->psz_text );
508     free( p_string->p_glyph_pos );
509     free( p_string->pp_glyphs );
510     free( p_string );
511 }
512
513 /* convert one or more utf8 bytes into a unicode character */
514 static int GetUnicodeCharFromUTF8( byte_t **ppsz_utf8_string )
515 {
516     int i_remaining_bytes, i_char = 0;
517     if( ( **ppsz_utf8_string & 0xFC ) == 0xFC )
518     {
519         i_char = **ppsz_utf8_string & 1;
520         i_remaining_bytes = 5;
521     }
522     else if( ( **ppsz_utf8_string & 0xF8 ) == 0xF8 )
523     {
524         i_char = **ppsz_utf8_string & 3;
525         i_remaining_bytes = 4;
526     }
527     else if( ( **ppsz_utf8_string & 0xF0 ) == 0xF0 )
528     {
529         i_char = **ppsz_utf8_string & 7;
530         i_remaining_bytes = 3;
531     }
532     else if( ( **ppsz_utf8_string & 0xE0 ) == 0xE0 )
533     {
534         i_char = **ppsz_utf8_string & 15;
535         i_remaining_bytes = 2;
536     }
537     else if( ( **ppsz_utf8_string & 0xC0 ) == 0xC0 )
538     {
539         i_char = **ppsz_utf8_string & 31;
540         i_remaining_bytes = 1;
541     }
542     else
543     {
544         i_char = **ppsz_utf8_string;
545         i_remaining_bytes = 0;
546     }
547     while( i_remaining_bytes )
548     {
549         (*ppsz_utf8_string)++;
550         i_remaining_bytes--;
551         i_char = ( i_char << 6 ) + ( **ppsz_utf8_string & 0x3F );
552     }
553     (*ppsz_utf8_string)++;
554     return i_char;
555 }