freetype.c 25.7 KB
Newer Older
1 2 3
/*****************************************************************************
 * freetype.c : Put text on the video, using freetype2
 *****************************************************************************
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 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include <stdlib.h>                                      /* malloc(), free() */
#include <string.h>

Jean-Paul Saman's avatar
Jean-Paul Saman committed
31 32 33 34
#ifdef HAVE_LINUX_LIMITS_H
#   include <linux/limits.h>
#endif

35 36
#include <vlc/vlc.h>
#include <vlc/vout.h>
37 38 39 40
#include "osd.h"
#include "vlc_block.h"
#include "vlc_filter.h"

41
#include <math.h>
42 43 44 45 46

#ifdef HAVE_ERRNO_H
#   include <errno.h>
#endif

47 48 49 50
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H

51 52
#ifdef SYS_DARWIN
#define DEFAULT_FONT "/System/Library/Fonts/LucidaGrande.dfont"
53 54
#elif defined( SYS_BEOS )
#define DEFAULT_FONT "/boot/beos/etc/fonts/ttfonts/Swiss721.ttf"
55 56
#elif defined( WIN32 )
#define DEFAULT_FONT "" /* Default font found at run-time */
57
#else
58
#define DEFAULT_FONT "/usr/share/fonts/truetype/freefont/FreeSerifBold.ttf"
59 60
#endif

61 62 63 64
#if defined(HAVE_FRIBIDI)
#include <fribidi/fribidi.h>
#endif

sigmunau's avatar
sigmunau committed
65 66
typedef struct line_desc_t line_desc_t;

67 68 69
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
70 71 72
static int  Create ( vlc_object_t * );
static void Destroy( vlc_object_t * );

73
/* The RenderText call maps to pf_render_string, defined in vlc_filter.h */
74 75
static int RenderText( filter_t *, subpicture_region_t *,
                       subpicture_region_t * );
sigmunau's avatar
sigmunau committed
76
static line_desc_t *NewLine( byte_t * );
gbazin's avatar
 
gbazin committed
77

78 79 80 81
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
#define FONT_TEXT N_("Font")
Sam Hocevar's avatar
Sam Hocevar committed
82
#define FONT_LONGTEXT N_("Font filename")
83
#define FONTSIZE_TEXT N_("Font size in pixels")
Sam Hocevar's avatar
Sam Hocevar committed
84 85 86
#define FONTSIZE_LONGTEXT N_("The size of the fonts used by the osd module. " \
    "If set to something different than 0 this option will override the " \
    "relative font size " )
87
#define OPACITY_TEXT N_("Opacity, 0..255")
88 89
#define OPACITY_LONGTEXT N_("The opacity (inverse of transparency) of " \
    "overlay text. 0 = transparent, 255 = totally opaque. " )
90
#define COLOR_TEXT N_("Text Default Color")
91 92 93
#define COLOR_LONGTEXT N_("The color of overlay text. 1 byte for each color, "\
    "hexadecimal. #000000 = all colors off, 0xFF0000 = just Red, " \
    "0xFFFFFF = all color on [White]" )
94 95
#define FONTSIZER_TEXT N_("Font size")
#define FONTSIZER_LONGTEXT N_("The size of the fonts used by the osd module" )
96

97
static int   pi_sizes[] = { 20, 18, 16, 12, 6 };
98 99
static char *ppsz_sizes_text[] = { N_("Smaller"), N_("Small"), N_("Normal"),
                                   N_("Large"), N_("Larger") };
100 101 102 103 104 105 106 107 108
static int pi_color_values[] = {
  0x00000000, 0x00808080, 0x00C0C0C0, 0x00FFFFFF, 0x00800000,
  0x00FF0000, 0x00FF00FF, 0x00FFFF00, 0x00808000, 0x00008000, 0x00008080, 
  0x0000FF00, 0x00800080, 0x00000080, 0x000000FF, 0x0000FFFF }; 

static char *ppsz_color_descriptions[] = {
  N_("Black"), N_("Gray"), N_("Silver"), N_("White"), N_("Maroon"),
  N_("Red"), N_("Fuchsia"), N_("Yellow"), N_("Olive"), N_("Green"), N_("Teal"),
  N_("Lime"), N_("Purple"), N_("Navy"), N_("Blue"), N_("Aqua") };
109

110
vlc_module_begin();
111 112
    set_shortname( _("Freetype"));
    set_description( _("Freetype2 font renderer") );
zorglub's avatar
zorglub committed
113 114
    set_category( CAT_VIDEO );
    set_subcategory( SUBCAT_VIDEO_TEXT );
gbazin's avatar
 
gbazin committed
115 116 117

    add_file( "freetype-font", DEFAULT_FONT, NULL, FONT_TEXT, FONT_LONGTEXT,
              VLC_FALSE );
118

gbazin's avatar
 
gbazin committed
119 120
    add_integer( "freetype-fontsize", 0, NULL, FONTSIZE_TEXT,
                 FONTSIZE_LONGTEXT, VLC_TRUE );
121

122
    /* opacity valid on 0..255, with default 255 = fully opaque */
123 124
    add_integer_with_range( "freetype-opacity", 255, 0, 255, NULL,
        OPACITY_TEXT, OPACITY_LONGTEXT, VLC_FALSE );
125

126
    /* hook to the color values list, with default 0x00ffffff = white */
127 128
    add_integer( "freetype-color", 0x00FFFFFF, NULL, COLOR_TEXT,
                 COLOR_LONGTEXT, VLC_TRUE );
129 130
        change_integer_list( pi_color_values, ppsz_color_descriptions, 0 );

gbazin's avatar
 
gbazin committed
131 132 133 134
    add_integer( "freetype-rel-fontsize", 16, NULL, FONTSIZER_TEXT,
                 FONTSIZER_LONGTEXT, VLC_FALSE );
        change_integer_list( pi_sizes, ppsz_sizes_text, 0 );

135 136 137 138 139
    set_capability( "text renderer", 100 );
    add_shortcut( "text" );
    set_callbacks( Create, Destroy );
vlc_module_end();

sigmunau's avatar
sigmunau committed
140 141
struct line_desc_t
{
142
    /** NULL-terminated list of glyphs making the string */
sigmunau's avatar
sigmunau committed
143
    FT_BitmapGlyph *pp_glyphs;
144
    /** list of relative positions for the glyphs */
sigmunau's avatar
sigmunau committed
145
    FT_Vector      *p_glyph_pos;
146

sigmunau's avatar
sigmunau committed
147 148
    int             i_height;
    int             i_width;
149 150 151
    int             i_red, i_green, i_blue;
    int             i_alpha;

sigmunau's avatar
sigmunau committed
152
    line_desc_t    *p_next;
153 154
};

155 156
static int Render( filter_t *, subpicture_region_t *, line_desc_t *, int, int);
static void FreeLines( line_desc_t * );
157
static void FreeLine( line_desc_t * );
158

159
/*****************************************************************************
160
 * filter_sys_t: freetype local data
161 162
 *****************************************************************************
 * This structure is part of the video output thread descriptor.
163
 * It describes the freetype specific properties of an output thread.
164
 *****************************************************************************/
165
struct filter_sys_t
166 167 168 169
{
    FT_Library     p_library;   /* handle to library     */
    FT_Face        p_face;      /* handle to face object */
    vlc_bool_t     i_use_kerning;
170 171
    uint8_t        i_font_opacity;
    int            i_font_color;
172
    int            i_font_size;
173 174 175 176 177 178 179 180 181
};

/*****************************************************************************
 * Create: allocates osd-text video thread output method
 *****************************************************************************
 * This function allocates and initializes a Clone vout method.
 *****************************************************************************/
static int Create( vlc_object_t *p_this )
{
182 183 184
    filter_t *p_filter = (filter_t *)p_this;
    filter_sys_t *p_sys;
    char *psz_fontfile = NULL;
185
    int i_error;
186
    vlc_value_t val;
187

188
    /* Allocate structure */
189 190
    p_sys = malloc( sizeof( filter_sys_t ) );
    if( !p_sys )
191
    {
192
        msg_Err( p_filter, "out of memory" );
193 194
        return VLC_ENOMEM;
    }
195 196
    p_sys->p_face = 0;
    p_sys->p_library = 0;
197
    p_sys->i_font_size = 0;
198

199 200
    var_Create( p_filter, "freetype-font",
                VLC_VAR_STRING | VLC_VAR_DOINHERIT );
201
    var_Create( p_filter, "freetype-fontsize",
gbazin's avatar
 
gbazin committed
202
                VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
203
    var_Create( p_filter, "freetype-rel-fontsize",
204
                VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
205 206
    var_Create( p_filter, "freetype-opacity",
                VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
207
    var_Get( p_filter, "freetype-opacity", &val );
208
    p_sys->i_font_opacity = __MAX( __MIN( val.i_int, 255 ), 0 );
209 210
    var_Create( p_filter, "freetype-color",
                VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
211
    var_Get( p_filter, "freetype-color", &val );
212
    p_sys->i_font_color = __MAX( __MIN( val.i_int, 0xFFFFFF ), 0 );
213

214
    /* Look what method was requested */
215
    var_Get( p_filter, "freetype-font", &val );
gbazin's avatar
 
gbazin committed
216
    psz_fontfile = val.psz_string;
gbazin's avatar
 
gbazin committed
217 218 219
    if( !psz_fontfile || !*psz_fontfile )
    {
        if( psz_fontfile ) free( psz_fontfile );
220 221 222
        psz_fontfile = (char *)malloc( PATH_MAX + 1 );
#ifdef WIN32
        GetWindowsDirectory( psz_fontfile, PATH_MAX + 1 );
gbazin's avatar
 
gbazin committed
223
        strcat( psz_fontfile, "\\fonts\\arial.ttf" );
224
#elif SYS_DARWIN
gbazin's avatar
 
gbazin committed
225
        strcpy( psz_fontfile, DEFAULT_FONT );
gbazin's avatar
 
gbazin committed
226
#else
227 228
        msg_Err( p_filter, "user didn't specify a font" );
        goto error;
gbazin's avatar
 
gbazin committed
229
#endif
230
    }
gbazin's avatar
 
gbazin committed
231

232
    i_error = FT_Init_FreeType( &p_sys->p_library );
233 234
    if( i_error )
    {
235 236
        msg_Err( p_filter, "couldn't initialize freetype" );
        goto error;
237
    }
gbazin's avatar
 
gbazin committed
238

239 240
    i_error = FT_New_Face( p_sys->p_library, psz_fontfile ? psz_fontfile : "",
                           0, &p_sys->p_face );
241 242
    if( i_error == FT_Err_Unknown_File_Format )
    {
243 244
        msg_Err( p_filter, "file %s have unknown format", psz_fontfile );
        goto error;
245 246 247
    }
    else if( i_error )
    {
248 249
        msg_Err( p_filter, "failed to load font file %s", psz_fontfile );
        goto error;
250
    }
gbazin's avatar
 
gbazin committed
251

252
    i_error = FT_Select_Charmap( p_sys->p_face, ft_encoding_unicode );
253
    if( i_error )
254
    {
255 256
        msg_Err( p_filter, "Font has no unicode translation table" );
        goto error;
257
    }
258

259
    p_sys->i_use_kerning = FT_HAS_KERNING( p_sys->p_face );
260

261
    
262
    var_Get( p_filter, "freetype-fontsize", &val );
263
    if( val.i_int )
264
    {
265
        p_sys->i_font_size = val.i_int;
266 267 268
    }
    else
    {
269
        var_Get( p_filter, "freetype-rel-fontsize", &val );
270
        p_sys->i_font_size = (int)p_filter->fmt_out.video.i_height / val.i_int;
271
    }
272
    if( p_sys->i_font_size <= 0 )
273 274
    {
        msg_Warn( p_filter, "Invalid fontsize, using 12" );
275
        p_sys->i_font_size = 12;
276
    }
277
    msg_Dbg( p_filter, "Using fontsize: %i", p_sys->i_font_size );
278

279
    i_error = FT_Set_Pixel_Sizes( p_sys->p_face, 0, p_sys->i_font_size );
280 281
    if( i_error )
    {
282
        msg_Err( p_filter, "couldn't set font size to %d", p_sys->i_font_size );
283
        goto error;
284
    }
285 286

    if( psz_fontfile ) free( psz_fontfile );
287
    p_filter->pf_render_text = RenderText;
288
    p_filter->p_sys = p_sys;
289
    return VLC_SUCCESS;
290 291 292 293 294 295 296

 error:
    if( p_sys->p_face ) FT_Done_Face( p_sys->p_face );
    if( p_sys->p_library ) FT_Done_FreeType( p_sys->p_library );
    if( psz_fontfile ) free( psz_fontfile );
    free( p_sys );
    return VLC_EGENERIC;
297 298 299 300 301 302 303 304
}

/*****************************************************************************
 * Destroy: destroy Clone video thread output method
 *****************************************************************************
 * Clean up all data and library connections
 *****************************************************************************/
static void Destroy( vlc_object_t *p_this )
305
{
306 307
    filter_t *p_filter = (filter_t *)p_this;
    filter_sys_t *p_sys = p_filter->p_sys;
308

309 310 311
    FT_Done_Face( p_sys->p_face );
    FT_Done_FreeType( p_sys->p_library );
    free( p_sys );
312 313 314 315 316 317 318
}

/*****************************************************************************
 * Render: place string in picture
 *****************************************************************************
 * This function merges the previously rendered freetype glyphs into a picture
 *****************************************************************************/
319 320
static int Render( filter_t *p_filter, subpicture_region_t *p_region,
                   line_desc_t *p_line, int i_width, int i_height )
321
{
322
    uint8_t *p_dst;
323 324
    video_format_t fmt;
    int i, x, y, i_pitch;
325 326 327
    uint8_t i_y; /* YUV values, derived from incoming RGB */
    int8_t i_u, i_v;
    subpicture_region_t *p_region_tmp;
328 329 330

    /* Create a new subpicture region */
    memset( &fmt, 0, sizeof(video_format_t) );
331
    fmt.i_chroma = VLC_FOURCC('Y','U','V','P');
332
    fmt.i_aspect = VOUT_ASPECT_FACTOR;
333 334
    fmt.i_width = fmt.i_visible_width = i_width + 2;
    fmt.i_height = fmt.i_visible_height = i_height + 2;
335
    fmt.i_x_offset = fmt.i_y_offset = 0;
336 337
    p_region_tmp = spu_CreateRegion( p_filter, &fmt );
    if( !p_region_tmp )
338
    {
339
        msg_Err( p_filter, "cannot allocate SPU region" );
340
        return VLC_EGENERIC;
341
    }
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    p_region->fmt = p_region_tmp->fmt;
    p_region->picture = p_region_tmp->picture;
    free( p_region_tmp );

    /* Calculate text color components */
    i_y = (uint8_t)(( 66 * p_line->i_red  + 129 * p_line->i_green +
                      25 * p_line->i_blue + 128) >> 8) +  16;
    i_u = (int8_t)(( -38 * p_line->i_red  -  74 * p_line->i_green +
                     112 * p_line->i_blue + 128) >> 8) + 128;
    i_v = (int8_t)(( 112 * p_line->i_red  -  94 * p_line->i_green -
                      18 * p_line->i_blue + 128) >> 8) + 128;

    /* Build palette */
    fmt.p_palette->i_entries = 256;
    for( i = 0; i < fmt.p_palette->i_entries; i++ )
    {
        fmt.p_palette->palette[i][0] = i * i_y / 256;
        fmt.p_palette->palette[i][1] = i_u;
        fmt.p_palette->palette[i][2] = i_v;
362
        fmt.p_palette->palette[i][3] = i + (255 - i) / 16;
363
        fmt.p_palette->palette[i][3] =
364
            (int)fmt.p_palette->palette[i][3] * (255 - p_line->i_alpha) / 255;
365 366 367 368
    }
    fmt.p_palette->palette[0][3] = 0;

    p_dst = p_region->picture.Y_PIXELS;
369
    i_pitch = p_region->picture.Y_PITCH;
370

371
    /* Initialize the region pixels */
372
    memset( p_dst, 0, i_pitch * p_region->fmt.i_height );
373

374
    for( ; p_line != NULL; p_line = p_line->p_next )
375 376 377
    {
        int i_glyph_tmax = 0;
        int i_bitmap_offset, i_offset;
sigmunau's avatar
sigmunau committed
378 379 380
        for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
        {
            FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
381
            i_glyph_tmax = __MAX( i_glyph_tmax, p_glyph->top );
sigmunau's avatar
sigmunau committed
382
        }
383

sigmunau's avatar
sigmunau committed
384 385 386
        for( i = 0; p_line->pp_glyphs[i] != NULL; i++ )
        {
            FT_BitmapGlyph p_glyph = p_line->pp_glyphs[ i ];
387 388 389 390 391 392

            i_offset = ( p_line->p_glyph_pos[ i ].y +
                i_glyph_tmax - p_glyph->top + 1 ) *
                i_pitch + p_line->p_glyph_pos[ i ].x + p_glyph->left + 1;

            for( y = 0, i_bitmap_offset = 0; y < p_glyph->bitmap.rows; y++ )
sigmunau's avatar
sigmunau committed
393
            {
394
                for( x = 0; x < p_glyph->bitmap.width; x++, i_bitmap_offset++ )
sigmunau's avatar
sigmunau committed
395
                {
396
                    if( !p_glyph->bitmap.buffer[i_bitmap_offset] )
397 398 399
                        continue;

                    i_offset -= i_pitch;
400 401
                    p_dst[i_offset + x] = ((uint16_t)p_dst[i_offset + x]*2 +
                      p_glyph->bitmap.buffer[i_bitmap_offset])/3;
402
                    i_offset += i_pitch; x--;
403 404
                    p_dst[i_offset + x] = ((uint16_t)p_dst[i_offset + x]*2 +
                      p_glyph->bitmap.buffer[i_bitmap_offset])/3;
405
                    x += 2;
406 407
                    p_dst[i_offset + x] = ((uint16_t)p_dst[i_offset + x]*2 +
                      p_glyph->bitmap.buffer[i_bitmap_offset])/3;
408
                    i_offset += i_pitch; x--;
409 410
                    p_dst[i_offset + x] = ((uint16_t)p_dst[i_offset + x]*2 +
                      p_glyph->bitmap.buffer[i_bitmap_offset])/3;
411
                    i_offset -= i_pitch;
sigmunau's avatar
sigmunau committed
412
                }
413
                i_offset += i_pitch;
sigmunau's avatar
sigmunau committed
414
            }
415 416

            i_offset = ( p_line->p_glyph_pos[ i ].y +
417
                i_glyph_tmax - p_glyph->top + 1 ) *
418 419 420
                i_pitch + p_line->p_glyph_pos[ i ].x + p_glyph->left + 1;

            for( y = 0, i_bitmap_offset = 0; y < p_glyph->bitmap.rows; y++ )
sigmunau's avatar
sigmunau committed
421
            {
422 423
               for( x = 0; x < p_glyph->bitmap.width; x++, i_bitmap_offset++ )
               {
424 425
                 if( p_glyph->bitmap.buffer[i_bitmap_offset] > 16 )
                   p_dst[i_offset+x] = p_glyph->bitmap.buffer[i_bitmap_offset];
426 427
               }
               i_offset += i_pitch;
sigmunau's avatar
sigmunau committed
428 429 430
            }
        }
    }
431 432

    return VLC_SUCCESS;
sigmunau's avatar
sigmunau committed
433
}
434

435
/**
436 437
 * This function renders a text subpicture region into another one.
 * It also calculates the size needed for this string, and renders the
438 439 440
 * needed glyphs into memory. It is used as pf_add_string callback in
 * the vout method by this module
 */
441 442
static int RenderText( filter_t *p_filter, subpicture_region_t *p_region_out,
                       subpicture_region_t *p_region_in )
443
{
444
    filter_sys_t *p_sys = p_filter->p_sys;
445
    line_desc_t  *p_lines = 0, *p_line = 0, *p_next = 0, *p_prev = 0;
446
    int i, i_pen_y, i_pen_x, i_error, i_glyph_index, i_previous;
447
    uint32_t *psz_unicode, *psz_unicode_orig = 0, i_char, *psz_line_start;
448
    int i_string_length;
449
    char *psz_string;
450
    vlc_iconv_t iconv_handle = (vlc_iconv_t)(-1);
451
    int i_font_color, i_font_alpha, i_font_size, i_red, i_green, i_blue;
452

453 454 455
    FT_BBox line;
    FT_BBox glyph_size;
    FT_Vector result;
456
    FT_Glyph tmp_glyph;
457

gbazin's avatar
 
gbazin committed
458
    /* Sanity check */
459 460 461 462
    if( !p_region_in || !p_region_out ) return VLC_EGENERIC;
    psz_string = p_region_in->psz_text;
    if( !psz_string || !*psz_string ) return VLC_EGENERIC;

463
    i_font_color = __MAX( __MIN( p_region_in->i_text_color, 0xFFFFFF ), 0 );
464 465
    if( i_font_color == 0xFFFFFF ) i_font_color = p_sys->i_font_color;

466
    i_font_alpha = __MAX( __MIN( p_region_in->i_text_alpha, 255 ), 0 );
467 468
    if( !i_font_alpha ) i_font_alpha = 255 - p_sys->i_font_opacity;

469
    i_font_size  = __MAX( __MIN( p_region_in->i_text_size, 255 ), 0 );
470 471 472 473 474 475 476 477
    if( !i_font_size ) i_font_size  = p_sys->i_font_size;

    i_red   = ( i_font_color & 0x00FF0000 ) >> 16;
    i_green = ( i_font_color & 0x0000FF00 ) >>  8;
    i_blue  =   i_font_color & 0x000000FF;

    result.x =  result.y = 0;
    line.xMin = line.xMax = line.yMin = line.yMax = 0;
sigmunau's avatar
sigmunau committed
478

479 480 481
    psz_unicode = psz_unicode_orig =
        malloc( ( strlen(psz_string) + 1 ) * sizeof(uint32_t) );
    if( psz_unicode == NULL )
482
    {
zorglub's avatar
zorglub committed
483
        msg_Err( p_filter, "out of memory" );
484 485
        goto error;
    }
sigmunau's avatar
sigmunau committed
486
#if defined(WORDS_BIGENDIAN)
487
    iconv_handle = vlc_iconv_open( "UCS-4BE", "UTF-8" );
488
#else
489
    iconv_handle = vlc_iconv_open( "UCS-4LE", "UTF-8" );
sigmunau's avatar
sigmunau committed
490
#endif
491
    if( iconv_handle == (vlc_iconv_t)-1 )
492
    {
493
        msg_Warn( p_filter, "unable to do conversion" );
494 495
        goto error;
    }
496

497 498 499
    /* Set up the glyphs for the desired font size.  By definition,
       p_sys->i_font_size is a valid value, else the initial Create would
       have failed. Using -1 as a flag to use the freetype-fontsize */
500
    if ( i_font_size < 0 )  
501
    {
502
            FT_Set_Pixel_Sizes( p_sys->p_face, 0, p_sys->i_font_size );
503 504 505
    }
    else          
    {
506
        i_error = FT_Set_Pixel_Sizes( p_sys->p_face, 0, i_font_size );
507 508
        if( i_error )
        {
509 510 511
            msg_Warn( p_filter, "Invalid font size to RenderText, using %d", 
                      p_sys->i_font_size );
            FT_Set_Pixel_Sizes( p_sys->p_face, 0, p_sys->i_font_size );
512 513 514
        }
    }

515
    {
516
        char *p_in_buffer, *p_out_buffer;
sigmunau's avatar
sigmunau committed
517
        size_t i_in_bytes, i_out_bytes, i_out_bytes_left, i_ret;
518 519 520 521
        i_in_bytes = strlen( psz_string );
        i_out_bytes = i_in_bytes * sizeof( uint32_t );
        i_out_bytes_left = i_out_bytes;
        p_in_buffer = psz_string;
522
        p_out_buffer = (char *)psz_unicode;
523 524 525 526 527
        i_ret = vlc_iconv( iconv_handle, &p_in_buffer, &i_in_bytes,
                           &p_out_buffer, &i_out_bytes_left );

        vlc_iconv_close( iconv_handle );

528 529
        if( i_in_bytes )
        {
zorglub's avatar
zorglub committed
530
            msg_Warn( p_filter, "failed to convert string to unicode (%s), "
531
                      "bytes left %d", strerror(errno), i_in_bytes );
532 533
            goto error;
        }
534
        *(uint32_t*)p_out_buffer = 0;
535
        i_string_length = (i_out_bytes - i_out_bytes_left) / sizeof(uint32_t);
536
    }
537

538 539 540 541
#if defined(HAVE_FRIBIDI)
    {
        uint32_t *p_fribidi_string;
        FriBidiCharType base_dir = FRIBIDI_TYPE_ON;
542
        p_fribidi_string = malloc( (i_string_length + 1) * sizeof(uint32_t) );
543
        fribidi_log2vis( (FriBidiChar*)psz_unicode, i_string_length,
544
                         &base_dir, (FriBidiChar*)p_fribidi_string, 0, 0, 0 );
545 546
        free( psz_unicode_orig );
        psz_unicode = psz_unicode_orig = p_fribidi_string;
547 548 549
        p_fribidi_string[ i_string_length ] = 0;
    }
#endif
550

sigmunau's avatar
sigmunau committed
551 552
    /* Calculate relative glyph positions and a bounding box for the
     * entire string */
553
    if( !(p_line = NewLine( psz_string )) )
554
    {
zorglub's avatar
zorglub committed
555
        msg_Err( p_filter, "out of memory" );
gbazin's avatar
 
gbazin committed
556
        goto error;
557
    }
558 559 560
    p_lines = p_line;
    i_pen_x = i_pen_y = 0;
    i_previous = i = 0;
561
    psz_line_start = psz_unicode;
gbazin's avatar
 
gbazin committed
562

563
#define face p_sys->p_face
gbazin's avatar
 
gbazin committed
564 565
#define glyph face->glyph

566
    while( *psz_unicode )
567
    {
568
        i_char = *psz_unicode++;
569
        if( i_char == '\r' ) /* ignore CR chars wherever they may be */
570 571 572
        {
            continue;
        }
gbazin's avatar
 
gbazin committed
573

574
        if( i_char == '\n' )
575
        {
576
            psz_line_start = psz_unicode;
577
            if( !(p_next = NewLine( psz_string )) )
sigmunau's avatar
sigmunau committed
578
            {
zorglub's avatar
zorglub committed
579
                msg_Err( p_filter, "out of memory" );
gbazin's avatar
 
gbazin committed
580
                goto error;
sigmunau's avatar
sigmunau committed
581 582 583 584 585
            }
            p_line->p_next = p_next;
            p_line->i_width = line.xMax;
            p_line->i_height = face->size->metrics.height >> 6;
            p_line->pp_glyphs[ i ] = NULL;
586 587 588 589
            p_line->i_alpha = i_font_alpha;
            p_line->i_red = i_red;
            p_line->i_green = i_green;
            p_line->i_blue = i_blue;
590
            p_prev = p_line;
sigmunau's avatar
sigmunau committed
591
            p_line = p_next;
592
            result.x = __MAX( result.x, line.xMax );
sigmunau's avatar
sigmunau committed
593 594
            result.y += face->size->metrics.height >> 6;
            i_pen_x = 0;
595 596
            i_previous = i = 0;
            line.xMin = line.xMax = line.yMin = line.yMax = 0;
sigmunau's avatar
sigmunau committed
597
            i_pen_y += face->size->metrics.height >> 6;
598 599 600
#if 0
            msg_Dbg( p_filter, "Creating new line, i is %d", i );
#endif
601 602
            continue;
        }
gbazin's avatar
 
gbazin committed
603

604
        i_glyph_index = FT_Get_Char_Index( face, i_char );
605
        if( p_sys->i_use_kerning && i_glyph_index
606 607 608 609 610 611
            && i_previous )
        {
            FT_Vector delta;
            FT_Get_Kerning( face, i_previous, i_glyph_index,
                            ft_kerning_default, &delta );
            i_pen_x += delta.x >> 6;
612

613
        }
sigmunau's avatar
sigmunau committed
614 615
        p_line->p_glyph_pos[ i ].x = i_pen_x;
        p_line->p_glyph_pos[ i ].y = i_pen_y;
616
        i_error = FT_Load_Glyph( face, i_glyph_index, FT_LOAD_DEFAULT );
617
        if( i_error )
618
        {
619
            msg_Err( p_filter, "FT_Load_Glyph returned %d", i_error );
gbazin's avatar
 
gbazin committed
620
            goto error;
621
        }
622
        i_error = FT_Get_Glyph( glyph, &tmp_glyph );
623
        if( i_error )
624
        {
625
            msg_Err( p_filter, "FT_Get_Glyph returned %d", i_error );
gbazin's avatar
 
gbazin committed
626
            goto error;
627
        }
628
        FT_Glyph_Get_CBox( tmp_glyph, ft_glyph_bbox_pixels, &glyph_size );
629
        i_error = FT_Glyph_To_Bitmap( &tmp_glyph, ft_render_mode_normal, 0, 1);
630
        if( i_error ) continue;
sigmunau's avatar
sigmunau committed
631
        p_line->pp_glyphs[ i ] = (FT_BitmapGlyph)tmp_glyph;
632

633
        /* Do rest */
634 635 636
        line.xMax = p_line->p_glyph_pos[i].x + glyph_size.xMax -
            glyph_size.xMin + ((FT_BitmapGlyph)tmp_glyph)->left;
        if( line.xMax > (int)p_filter->fmt_out.video.i_visible_width - 20 )
637 638 639 640
        {
            p_line->pp_glyphs[ i ] = NULL;
            FreeLine( p_line );
            p_line = NewLine( psz_string );
641 642 643
            if( p_prev ) p_prev->p_next = p_line;
            else p_lines = p_line;

644 645 646 647 648 649
            while( psz_unicode > psz_line_start && *psz_unicode != ' ' )
            {
                psz_unicode--;
            }
            if( psz_unicode == psz_line_start )
            {
zorglub's avatar
zorglub committed
650
                msg_Warn( p_filter, "unbreakable string" );
651 652 653 654 655 656 657 658
                goto error;
            }
            else
            {
                *psz_unicode = '\n';
            }
            psz_unicode = psz_line_start;
            i_pen_x = 0;
659 660
            i_previous = i = 0;
            line.xMin = line.xMax = line.yMin = line.yMax = 0;
zorglub's avatar
zorglub committed
661
            continue;
662
        }
663 664
        line.yMax = __MAX( line.yMax, glyph_size.yMax );
        line.yMin = __MIN( line.yMin, glyph_size.yMin );
665

666 667
        i_previous = i_glyph_index;
        i_pen_x += glyph->advance.x >> 6;
668
        i++;
669
    }
670

sigmunau's avatar
sigmunau committed
671 672 673
    p_line->i_width = line.xMax;
    p_line->i_height = face->size->metrics.height >> 6;
    p_line->pp_glyphs[ i ] = NULL;
674 675 676 677
    p_line->i_alpha = i_font_alpha;
    p_line->i_red = i_red;
    p_line->i_green = i_green;
    p_line->i_blue = i_blue;
678 679
    result.x = __MAX( result.x, line.xMax );
    result.y += line.yMax - line.yMin;
gbazin's avatar
 
gbazin committed
680 681 682

#undef face
#undef glyph
683

684 685 686 687 688
    p_region_out->i_x = p_region_in->i_x;
    p_region_out->i_y = p_region_in->i_y;

    Render( p_filter, p_region_out, p_line, result.x, result.y );

689
    if( psz_unicode_orig ) free( psz_unicode_orig );
690 691
    FreeLines( p_lines );
    return VLC_SUCCESS;
692

gbazin's avatar
 
gbazin committed
693
 error:
694
    if( psz_unicode_orig ) free( psz_unicode_orig );
695 696
    FreeLines( p_lines );
    return VLC_EGENERIC;
697 698
}

699
static void FreeLine( line_desc_t *p_line )
700 701
{
    unsigned int i;
702 703 704 705 706 707 708 709 710
    for( i = 0; p_line->pp_glyphs[ i ] != NULL; i++ )
    {
        FT_Done_Glyph( (FT_Glyph)p_line->pp_glyphs[ i ] );
    }
    free( p_line->pp_glyphs );
    free( p_line->p_glyph_pos );
    free( p_line );
}

711
static void FreeLines( line_desc_t *p_lines )
712
{
sigmunau's avatar
sigmunau committed
713
    line_desc_t *p_line, *p_next;
gbazin's avatar
 
gbazin committed
714

715
    if( !p_lines ) return;
gbazin's avatar
 
gbazin committed
716

717
    for( p_line = p_lines; p_line != NULL; p_line = p_next )
718
    {
sigmunau's avatar
sigmunau committed
719
        p_next = p_line->p_next;
720
        FreeLine( p_line );
721 722 723
    }
}

sigmunau's avatar
sigmunau committed
724 725
static line_desc_t *NewLine( byte_t *psz_string )
{
gbazin's avatar
 
gbazin committed
726 727
    int i_count;
    line_desc_t *p_line = malloc( sizeof(line_desc_t) );
728 729

    if( !p_line ) return NULL;
sigmunau's avatar
sigmunau committed
730 731 732
    p_line->i_height = 0;
    p_line->i_width = 0;
    p_line->p_next = NULL;
gbazin's avatar
 
gbazin committed
733 734 735 736 737

    /* We don't use CountUtf8Characters() here because we are not acutally
     * sure the string is utf8. Better be safe than sorry. */
    i_count = strlen( psz_string );