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