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