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