]> git.sesse.net Git - vlc/blob - modules/misc/quartztext.c
Strip out whitespace
[vlc] / modules / misc / quartztext.c
1 /*****************************************************************************
2  * quartztext.c : Put text on the video, using Mac OS X Quartz Engine
3  *****************************************************************************
4  * Copyright (C) 2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Bernie Purcell <bitmap@videolan.org>
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 //////////////////////////////////////////////////////////////////////////////
25 // Preamble
26 //////////////////////////////////////////////////////////////////////////////
27
28 #include <vlc/vlc.h>
29 #include <vlc_vout.h>
30 #include <vlc_osd.h>
31 #include <vlc_block.h>
32 #include <vlc_filter.h>
33 #include <vlc_stream.h>
34 #include <vlc_xml.h>
35 #include <vlc_input.h>
36
37 #include <math.h>
38
39 #include <Carbon/Carbon.h>
40
41 #define DEFAULT_FONT           "Verdana"
42 #define DEFAULT_FONT_COLOR     0xffffff
43 #define DEFAULT_REL_FONT_SIZE  16
44
45 #define VERTICAL_MARGIN 3
46 #define HORIZONTAL_MARGIN 10
47
48 //////////////////////////////////////////////////////////////////////////////
49 // Local prototypes
50 //////////////////////////////////////////////////////////////////////////////
51 static int  Create ( vlc_object_t * );
52 static void Destroy( vlc_object_t * );
53
54 static int LoadFontsFromAttachments( filter_t *p_filter );
55
56 static int RenderText( filter_t *, subpicture_region_t *,
57                        subpicture_region_t * );
58 static int RenderHtml( filter_t *, subpicture_region_t *,
59                        subpicture_region_t * );
60
61 static int RenderYUVA( filter_t *p_filter, subpicture_region_t *p_region,
62                        UniChar *psz_utfString, uint32_t i_text_len,
63                        uint32_t i_runs, uint32_t *pi_run_lengths,
64                        ATSUStyle *pp_styles );
65 static ATSUStyle CreateStyle( char *psz_fontname, int i_font_size,
66                               int i_font_color, int i_font_alpha,
67                               vlc_bool_t b_bold, vlc_bool_t b_italic,
68                               vlc_bool_t b_uline );
69 //////////////////////////////////////////////////////////////////////////////
70 // Module descriptor
71 //////////////////////////////////////////////////////////////////////////////
72
73 // The preferred way to set font style information is for it to come from the
74 // subtitle file, and for it to be rendered with RenderHtml instead of
75 // RenderText. This module, unlike Freetype, doesn't provide any options to
76 // override the fallback font selection used when this style information is
77 // absent.
78 vlc_module_begin();
79     set_shortname( _("Mac Text renderer"));
80     set_description( _("Quartz font renderer") );
81     set_category( CAT_VIDEO );
82     set_subcategory( SUBCAT_VIDEO_SUBPIC );
83
84     set_capability( "text renderer", 120 );
85     add_shortcut( "text" );
86     set_callbacks( Create, Destroy );
87 vlc_module_end();
88
89 typedef struct font_stack_t font_stack_t;
90 struct font_stack_t
91 {
92     char          *psz_name;
93     int            i_size;
94     int            i_color;
95     int            i_alpha;
96
97     font_stack_t  *p_next;
98 };
99
100 typedef struct offscreen_bitmap_t offscreen_bitmap_t;
101 struct offscreen_bitmap_t
102 {
103     uint8_t       *p_data;
104     int            i_bitsPerChannel;
105     int            i_bitsPerPixel;
106     int            i_bytesPerPixel;
107     int            i_bytesPerRow;
108 };
109
110 //////////////////////////////////////////////////////////////////////////////
111 // filter_sys_t: quartztext local data
112 //////////////////////////////////////////////////////////////////////////////
113 // This structure is part of the video output thread descriptor.
114 // It describes the freetype specific properties of an output thread.
115 //////////////////////////////////////////////////////////////////////////////
116 struct filter_sys_t
117 {
118     char          *psz_font_name;
119     uint8_t        i_font_opacity;
120     int            i_font_color;
121     int            i_font_size;
122
123     ATSFontContainerRef    *p_fonts;
124     int                     i_fonts;
125 };
126
127 //////////////////////////////////////////////////////////////////////////////
128 // Create: allocates osd-text video thread output method
129 //////////////////////////////////////////////////////////////////////////////
130 // This function allocates and initializes a Clone vout method.
131 //////////////////////////////////////////////////////////////////////////////
132 static int Create( vlc_object_t *p_this )
133 {
134     filter_t *p_filter = (filter_t *)p_this;
135     filter_sys_t *p_sys;
136
137     // Allocate structure
138     p_filter->p_sys = p_sys = malloc( sizeof( filter_sys_t ) );
139     if( !p_sys )
140     {
141         msg_Err( p_filter, "out of memory" );
142         return VLC_ENOMEM;
143     }
144     p_sys->psz_font_name  = strdup( DEFAULT_FONT );
145     p_sys->i_font_opacity = 255;
146     p_sys->i_font_color   = DEFAULT_FONT_COLOR;
147     p_sys->i_font_size    = p_filter->fmt_out.video.i_height / DEFAULT_REL_FONT_SIZE;
148
149     p_filter->pf_render_text = RenderText;
150     p_filter->pf_render_html = RenderHtml;
151
152     p_sys->p_fonts = NULL;
153     p_sys->i_fonts = 0;
154
155     LoadFontsFromAttachments( p_filter );
156
157     return VLC_SUCCESS;
158 }
159
160 //////////////////////////////////////////////////////////////////////////////
161 // Destroy: destroy Clone video thread output method
162 //////////////////////////////////////////////////////////////////////////////
163 // Clean up all data and library connections
164 //////////////////////////////////////////////////////////////////////////////
165 static void Destroy( vlc_object_t *p_this )
166 {
167     filter_t *p_filter = (filter_t *)p_this;
168     filter_sys_t *p_sys = p_filter->p_sys;
169
170     if( p_sys->p_fonts )
171     {
172         int   k;
173
174         for( k = 0; k < p_sys->i_fonts; k++ )
175         {
176             ATSFontDeactivate( p_sys->p_fonts[k], NULL, kATSOptionFlagsDefault );
177         }
178
179         free( p_sys->p_fonts );
180     }
181
182     if( p_sys->psz_font_name ) free( p_sys->psz_font_name );
183
184     free( p_sys );
185 }
186
187 //////////////////////////////////////////////////////////////////////////////
188 // Make any TTF/OTF fonts present in the attachments of the media file
189 // available to the Quartz engine for text rendering
190 //////////////////////////////////////////////////////////////////////////////
191 static int LoadFontsFromAttachments( filter_t *p_filter )
192 {
193     filter_sys_t         *p_sys = p_filter->p_sys;
194     input_thread_t       *p_input;
195     input_attachment_t  **pp_attachments;
196     int                   i_attachments_cnt;
197     int                   k;
198     int                   rv = VLC_SUCCESS;
199
200     p_input = (input_thread_t *)vlc_object_find( p_filter, VLC_OBJECT_INPUT, FIND_PARENT );
201     if( ! p_input )
202         return VLC_EGENERIC;
203
204     if( VLC_SUCCESS != input_Control( p_input, INPUT_GET_ATTACHMENTS, &pp_attachments, &i_attachments_cnt ))
205         return VLC_EGENERIC;
206
207     p_sys->i_fonts = 0;
208     p_sys->p_fonts = malloc( i_attachments_cnt * sizeof( ATSFontContainerRef ) );
209     if(! p_sys->p_fonts )
210         rv = VLC_ENOMEM;
211
212     for( k = 0; k < i_attachments_cnt; k++ )
213     {
214         input_attachment_t *p_attach = pp_attachments[k];
215
216         if( p_sys->p_fonts )
217         {
218             if(( !strcmp( p_attach->psz_mime, "application/x-truetype-font" ) || // TTF
219                  !strcmp( p_attach->psz_mime, "application/x-font-otf" ) ) &&    // OTF
220                ( p_attach->i_data > 0 ) &&
221                ( p_attach->p_data != NULL ) )
222             {
223                 ATSFontContainerRef  container;
224
225                 if( noErr == ATSFontActivateFromMemory( p_attach->p_data,
226                                                         p_attach->i_data,
227                                                         kATSFontContextLocal,
228                                                         kATSFontFormatUnspecified,
229                                                         NULL,
230                                                         kATSOptionFlagsDefault,
231                                                         &container ))
232                 {
233                     p_sys->p_fonts[ p_sys->i_fonts++ ] = container;
234                 }
235             }
236         }
237         vlc_input_attachment_Delete( p_attach );
238     }
239     free( pp_attachments );
240
241     return rv;
242 }
243
244 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
245 // Original version of these functions available on:
246 // http://developer.apple.com/documentation/Carbon/Conceptual/QuickDrawToQuartz2D/tq_color/chapter_4_section_3.html
247
248 #define kGenericRGBProfilePathStr "/System/Library/ColorSync/Profiles/Generic RGB Profile.icc"
249
250 static CMProfileRef OpenGenericProfile( void )
251 {
252     static CMProfileRef cached_rgb_prof = NULL;
253
254     // Create the profile reference only once
255     if( cached_rgb_prof == NULL )
256     {
257         OSStatus            err;
258         CMProfileLocation   loc;
259
260         loc.locType = cmPathBasedProfile;
261         strcpy( loc.u.pathLoc.path, kGenericRGBProfilePathStr );
262
263         err = CMOpenProfile( &cached_rgb_prof, &loc );
264
265         if( err != noErr )
266         {
267             cached_rgb_prof = NULL;
268         }
269     }
270
271     if( cached_rgb_prof )
272     {
273         // Clone the profile reference so that the caller has
274         // their own reference, not our cached one.
275         CMCloneProfileRef( cached_rgb_prof );
276     }
277
278     return cached_rgb_prof;
279 }
280
281 static CGColorSpaceRef CreateGenericRGBColorSpace( void )
282 {
283     static CGColorSpaceRef p_generic_rgb_cs = NULL;
284
285     if( p_generic_rgb_cs == NULL )
286     {
287         CMProfileRef generic_rgb_prof = OpenGenericProfile();
288
289         if( generic_rgb_prof )
290         {
291             p_generic_rgb_cs = CGColorSpaceCreateWithPlatformColorSpace( generic_rgb_prof );
292
293             CMCloseProfile( generic_rgb_prof );
294         }
295     }
296
297     return p_generic_rgb_cs;
298 }
299 #endif
300
301 static char *EliminateCRLF( char *psz_string )
302 {
303     char *p;
304     char *q;
305
306     for( p = psz_string; p && *p; p++ )
307     {
308         if( ( *p == '\r' ) && ( *(p+1) == '\n' ) )
309         {
310             for( q = p + 1; *q; q++ )
311                 *( q - 1 ) = *q;
312
313             *( q - 1 ) = '\0';
314         }
315     }
316     return psz_string;
317 }
318
319 // Convert UTF-8 string to UTF-16 character array -- internal Mac Endian-ness ;
320 // we don't need to worry about bidirectional text conversion as ATSUI should
321 // handle that for us automatically
322 static void ConvertToUTF16( const char *psz_utf8_str, uint32_t *pi_strlen, UniChar **ppsz_utf16_str )
323 {
324     CFStringRef   p_cfString;
325     int           i_string_length;
326
327     p_cfString = CFStringCreateWithCString( NULL, psz_utf8_str, kCFStringEncodingUTF8 );
328     i_string_length = CFStringGetLength( p_cfString );
329
330     if( pi_strlen )
331         *pi_strlen = i_string_length;
332
333     if( !*ppsz_utf16_str )
334         *ppsz_utf16_str = (UniChar *) calloc( i_string_length, sizeof( UniChar ) );
335
336     CFStringGetCharacters( p_cfString, CFRangeMake( 0, i_string_length ), *ppsz_utf16_str );
337
338     CFRelease( p_cfString );
339 }
340
341 // Renders a text subpicture region into another one.
342 // It is used as pf_add_string callback in the vout method by this module
343 static int RenderText( filter_t *p_filter, subpicture_region_t *p_region_out,
344                        subpicture_region_t *p_region_in )
345 {
346     filter_sys_t *p_sys = p_filter->p_sys;
347     UniChar      *psz_utf16_str = NULL;
348     uint32_t      i_string_length;
349     char         *psz_string;
350     int           i_font_color, i_font_alpha, i_font_size;
351
352     // Sanity check
353     if( !p_region_in || !p_region_out ) return VLC_EGENERIC;
354     psz_string = p_region_in->psz_text;
355     if( !psz_string || !*psz_string ) return VLC_EGENERIC;
356
357     if( p_region_in->p_style )
358     {
359         i_font_color = __MAX( __MIN( p_region_in->p_style->i_font_color, 0xFFFFFF ), 0 );
360         i_font_alpha = __MAX( __MIN( p_region_in->p_style->i_font_alpha, 255 ), 0 );
361         i_font_size  = __MAX( __MIN( p_region_in->p_style->i_font_size, 255 ), 0 );
362     }
363     else
364     {
365         i_font_color = p_sys->i_font_color;
366         i_font_alpha = 255 - p_sys->i_font_opacity;
367         i_font_size  = p_sys->i_font_size;
368     }
369
370     if( !i_font_alpha ) i_font_alpha = 255 - p_sys->i_font_opacity;
371
372     ConvertToUTF16( EliminateCRLF( psz_string ), &i_string_length, &psz_utf16_str );
373
374     p_region_out->i_x = p_region_in->i_x;
375     p_region_out->i_y = p_region_in->i_y;
376
377     if( psz_utf16_str != NULL )
378     {
379         ATSUStyle p_style = CreateStyle( p_sys->psz_font_name, i_font_size,
380                                          i_font_color, i_font_alpha,
381                                          VLC_FALSE, VLC_FALSE, VLC_FALSE );
382         if( p_style )
383         {
384             RenderYUVA( p_filter, p_region_out, psz_utf16_str, i_string_length,
385                         1, &i_string_length, &p_style );
386         }
387
388         ATSUDisposeStyle( p_style );
389         free( psz_utf16_str );
390     }
391
392     return VLC_SUCCESS;
393 }
394
395
396 static ATSUStyle CreateStyle( char *psz_fontname, int i_font_size, int i_font_color, int i_font_alpha,
397                               vlc_bool_t b_bold, vlc_bool_t b_italic, vlc_bool_t b_uline )
398 {
399     ATSUStyle   p_style;
400     OSStatus    status;
401     uint32_t    i_tag_cnt;
402
403     float f_red   = (float)(( i_font_color & 0x00FF0000 ) >> 16) / 255.0;
404     float f_green = (float)(( i_font_color & 0x0000FF00 ) >>  8) / 255.0;
405     float f_blue  = (float)(  i_font_color & 0x000000FF        ) / 255.0;
406     float f_alpha = ( 255.0 - (float)i_font_alpha) / 255.0;
407
408     ATSUFontID           font;
409     Fixed                font_size  = IntToFixed( i_font_size );
410     ATSURGBAlphaColor    font_color = { f_red, f_green, f_blue, f_alpha };
411     Boolean              bold       = b_bold;
412     Boolean              italic     = b_italic;
413     Boolean              uline      = b_uline;
414
415     ATSUAttributeTag tags[]        = { kATSUSizeTag, kATSURGBAlphaColorTag, kATSUQDItalicTag,
416                                        kATSUQDBoldfaceTag, kATSUQDUnderlineTag, kATSUFontTag };
417     ByteCount sizes[]              = { sizeof( Fixed ), sizeof( ATSURGBAlphaColor ), sizeof( Boolean ),
418                                        sizeof( Boolean ), sizeof( Boolean ), sizeof( ATSUFontID )};
419     ATSUAttributeValuePtr values[] = { &font_size, &font_color, &italic, &bold, &uline, &font };
420
421     i_tag_cnt = sizeof( tags ) / sizeof( ATSUAttributeTag );
422
423     status = ATSUFindFontFromName( psz_fontname,
424                                    strlen( psz_fontname ),
425                                    kFontFullName,
426                                    kFontNoPlatform,
427                                    kFontNoScript,
428                                    kFontNoLanguageCode,
429                                    &font );
430
431     if( status != noErr )
432     {
433         // If we can't find a suitable font, just do everything else
434         i_tag_cnt--;
435     }
436
437     if( noErr == ATSUCreateStyle( &p_style ) )
438     {
439         if( noErr == ATSUSetAttributes( p_style, i_tag_cnt, tags, sizes, values ) )
440         {
441             return p_style;
442         }
443         ATSUDisposeStyle( p_style );
444     }
445     return NULL;
446 }
447
448 static int PushFont( font_stack_t **p_font, const char *psz_name, int i_size,
449                      int i_color, int i_alpha )
450 {
451     font_stack_t *p_new;
452
453     if( !p_font )
454         return VLC_EGENERIC;
455
456     p_new = malloc( sizeof( font_stack_t ) );
457     p_new->p_next = NULL;
458
459     if( psz_name )
460         p_new->psz_name = strdup( psz_name );
461     else
462         p_new->psz_name = NULL;
463
464     p_new->i_size   = i_size;
465     p_new->i_color  = i_color;
466     p_new->i_alpha  = i_alpha;
467
468     if( !*p_font )
469     {
470         *p_font = p_new;
471     }
472     else
473     {
474         font_stack_t *p_last;
475
476         for( p_last = *p_font;
477              p_last->p_next;
478              p_last = p_last->p_next )
479         ;
480
481         p_last->p_next = p_new;
482     }
483     return VLC_SUCCESS;
484 }
485
486 static int PopFont( font_stack_t **p_font )
487 {
488     font_stack_t *p_last, *p_next_to_last;
489
490     if( !p_font || !*p_font )
491         return VLC_EGENERIC;
492
493     p_next_to_last = NULL;
494     for( p_last = *p_font;
495          p_last->p_next;
496          p_last = p_last->p_next )
497     {
498         p_next_to_last = p_last;
499     }
500
501     if( p_next_to_last )
502         p_next_to_last->p_next = NULL;
503     else
504         *p_font = NULL;
505
506     free( p_last->psz_name );
507     free( p_last );
508
509     return VLC_SUCCESS;
510 }
511
512 static int PeekFont( font_stack_t **p_font, char **psz_name, int *i_size,
513                      int *i_color, int *i_alpha )
514 {
515     font_stack_t *p_last;
516
517     if( !p_font || !*p_font )
518         return VLC_EGENERIC;
519
520     for( p_last=*p_font;
521          p_last->p_next;
522          p_last=p_last->p_next )
523     ;
524
525     *psz_name = p_last->psz_name;
526     *i_size   = p_last->i_size;
527     *i_color  = p_last->i_color;
528     *i_alpha  = p_last->i_alpha;
529
530     return VLC_SUCCESS;
531 }
532
533 static ATSUStyle GetStyleFromFontStack( filter_sys_t *p_sys, font_stack_t **p_fonts,
534                               vlc_bool_t b_bold, vlc_bool_t b_italic, vlc_bool_t b_uline )
535 {
536     ATSUStyle   p_style = NULL;
537
538     char  *psz_fontname = NULL;
539     int    i_font_color = p_sys->i_font_color;
540     int    i_font_alpha = 0;
541     int    i_font_size  = p_sys->i_font_size;
542
543     if( VLC_SUCCESS == PeekFont( p_fonts, &psz_fontname, &i_font_size, &i_font_color, &i_font_alpha ) )
544     {
545         p_style = CreateStyle( psz_fontname, i_font_size, i_font_color, i_font_alpha,
546                                b_bold, b_italic, b_uline );
547     }
548     return p_style;
549 }
550
551 static void ProcessNodes( filter_t *p_filter, xml_reader_t *p_xml_reader,
552                           text_style_t *p_font_style, UniChar *psz_text, int *pi_len,
553                           uint32_t *pi_runs, uint32_t **ppi_run_lengths,
554                           ATSUStyle **ppp_styles)
555 {
556     filter_sys_t *p_sys          = p_filter->p_sys;
557     UniChar      *psz_text_orig  = psz_text;
558     font_stack_t *p_fonts        = NULL;
559
560     char *psz_node  = NULL;
561
562     vlc_bool_t b_italic = VLC_FALSE;
563     vlc_bool_t b_bold   = VLC_FALSE;
564     vlc_bool_t b_uline  = VLC_FALSE;
565
566     if( p_font_style )
567     {
568         PushFont( &p_fonts,
569                   p_font_style->psz_fontname,
570                   p_font_style->i_font_size,
571                   p_font_style->i_font_color,
572                   p_font_style->i_font_alpha );
573
574         if( p_font_style->i_style_flags & STYLE_BOLD )
575             b_bold = VLC_TRUE;
576         if( p_font_style->i_style_flags & STYLE_ITALIC )
577             b_italic = VLC_TRUE;
578         if( p_font_style->i_style_flags & STYLE_UNDERLINE )
579             b_uline = VLC_TRUE;
580     }
581     else
582     {
583         PushFont( &p_fonts, p_sys->psz_font_name, p_sys->i_font_size, p_sys->i_font_color, 0 );
584     }
585
586     while ( ( xml_ReaderRead( p_xml_reader ) == 1 ) )
587     {
588         switch ( xml_ReaderNodeType( p_xml_reader ) )
589         {
590             case XML_READER_NONE:
591                 break;
592             case XML_READER_ENDELEM:
593                 psz_node = xml_ReaderName( p_xml_reader );
594
595                 if( psz_node )
596                 {
597                     if( !strcasecmp( "font", psz_node ) )
598                         PopFont( &p_fonts );
599                     else if( !strcasecmp( "b", psz_node ) )
600                         b_bold   = VLC_FALSE;
601                     else if( !strcasecmp( "i", psz_node ) )
602                         b_italic = VLC_FALSE;
603                     else if( !strcasecmp( "u", psz_node ) )
604                         b_uline  = VLC_FALSE;
605
606                     free( psz_node );
607                 }
608                 break;
609             case XML_READER_STARTELEM:
610                 psz_node = xml_ReaderName( p_xml_reader );
611                 if( psz_node )
612                 {
613                     if( !strcasecmp( "font", psz_node ) )
614                     {
615                         char *psz_fontname = NULL;
616                         int   i_font_color = 0xffffff;
617                         int   i_font_alpha = 0;
618                         int   i_font_size  = 24;
619
620                         // Default all attributes to the top font in the stack -- in case not
621                         // all attributes are specified in the sub-font
622                         if( VLC_SUCCESS == PeekFont( &p_fonts, &psz_fontname, &i_font_size, &i_font_color, &i_font_alpha ))
623                         {
624                             psz_fontname = strdup( psz_fontname );
625                         }
626
627                         while ( xml_ReaderNextAttr( p_xml_reader ) == VLC_SUCCESS )
628                         {
629                             char *psz_name = xml_ReaderName ( p_xml_reader );
630                             char *psz_value = xml_ReaderValue ( p_xml_reader );
631
632                             if( psz_name && psz_value )
633                             {
634                                 if( !strcasecmp( "face", psz_name ) )
635                                 {
636                                     if( psz_fontname ) free( psz_fontname );
637                                     psz_fontname = strdup( psz_value );
638                                 }
639                                 else if( !strcasecmp( "size", psz_name ) )
640                                 {
641                                     if( ( *psz_value == '+' ) || ( *psz_value == '-' ) )
642                                     {
643                                         int i_value = atoi( psz_value );
644
645                                         if( ( i_value >= -5 ) && ( i_value <= 5 ) )
646                                             i_font_size += ( i_value * i_font_size ) / 10;
647                                         else if( i_value < -5 )
648                                             i_font_size = - i_value;
649                                         else if( i_value > 5 )
650                                             i_font_size = i_value;
651                                     }
652                                     else
653                                         i_font_size = atoi( psz_value );
654                                 }
655                                 else if( !strcasecmp( "color", psz_name )  &&
656                                          ( psz_value[0] == '#' ) )
657                                 {
658                                     i_font_color = strtol( psz_value+1, NULL, 16 );
659                                     i_font_color &= 0x00ffffff;
660                                 }
661                                 else if( !strcasecmp( "alpha", psz_name ) &&
662                                          ( psz_value[0] == '#' ) )
663                                 {
664                                     i_font_alpha = strtol( psz_value+1, NULL, 16 );
665                                     i_font_alpha &= 0xff;
666                                 }
667                                 free( psz_name );
668                                 free( psz_value );
669                             }
670                         }
671                         PushFont( &p_fonts, psz_fontname, i_font_size, i_font_color, i_font_alpha );
672                         free( psz_fontname );
673                     }
674                     else if( !strcasecmp( "b", psz_node ) )
675                     {
676                         b_bold = VLC_TRUE;
677                     }
678                     else if( !strcasecmp( "i", psz_node ) )
679                     {
680                         b_italic = VLC_TRUE;
681                     }
682                     else if( !strcasecmp( "u", psz_node ) )
683                     {
684                         b_uline = VLC_TRUE;
685                     }
686                     else if( !strcasecmp( "br", psz_node ) )
687                     {
688                         uint32_t i_string_length;
689
690                         ConvertToUTF16( "\n", &i_string_length, &psz_text );
691                         psz_text += i_string_length;
692
693                         (*pi_runs)++;
694
695                         if( *ppp_styles )
696                             *ppp_styles = (ATSUStyle *) realloc( *ppp_styles, *pi_runs * sizeof( ATSUStyle ) );
697                         else
698                             *ppp_styles = (ATSUStyle *) malloc( *pi_runs * sizeof( ATSUStyle ) );
699
700                         (*ppp_styles)[ *pi_runs - 1 ] = GetStyleFromFontStack( p_sys, &p_fonts, b_bold, b_italic, b_uline );
701
702                         if( *ppi_run_lengths )
703                             *ppi_run_lengths = (uint32_t *) realloc( *ppi_run_lengths, *pi_runs * sizeof( uint32_t ) );
704                         else
705                             *ppi_run_lengths = (uint32_t *) malloc( *pi_runs * sizeof( uint32_t ) );
706
707                         (*ppi_run_lengths)[ *pi_runs - 1 ] = i_string_length;
708                     }
709                     free( psz_node );
710                 }
711                 break;
712             case XML_READER_TEXT:
713                 psz_node = xml_ReaderValue( p_xml_reader );
714                 if( psz_node )
715                 {
716                     uint32_t i_string_length;
717
718                     // Turn any multiple-whitespaces into single spaces
719                     char *s = strpbrk( psz_node, "\t\r\n " );
720                     while( s )
721                     {
722                         int i_whitespace = strspn( s, "\t\r\n " );
723
724                         if( i_whitespace > 1 )
725                             memmove( &s[1],
726                                      &s[i_whitespace],
727                                      strlen( s ) - i_whitespace + 1 );
728                         *s++ = ' ';
729
730                         s = strpbrk( s, "\t\r\n " );
731                     }
732
733                     ConvertToUTF16( psz_node, &i_string_length, &psz_text );
734                     psz_text += i_string_length;
735
736                     (*pi_runs)++;
737
738                     if( *ppp_styles )
739                         *ppp_styles = (ATSUStyle *) realloc( *ppp_styles, *pi_runs * sizeof( ATSUStyle ) );
740                     else
741                         *ppp_styles = (ATSUStyle *) malloc( *pi_runs * sizeof( ATSUStyle ) );
742
743                     (*ppp_styles)[ *pi_runs - 1 ] = GetStyleFromFontStack( p_sys, &p_fonts, b_bold, b_italic, b_uline );
744
745                     if( *ppi_run_lengths )
746                         *ppi_run_lengths = (uint32_t *) realloc( *ppi_run_lengths, *pi_runs * sizeof( uint32_t ) );
747                     else
748                         *ppi_run_lengths = (uint32_t *) malloc( *pi_runs * sizeof( uint32_t ) );
749
750                     (*ppi_run_lengths)[ *pi_runs - 1 ] = i_string_length;
751
752                     free( psz_node );
753                 }
754                 break;
755         }
756     }
757
758     *pi_len = psz_text - psz_text_orig;
759
760     while( VLC_SUCCESS == PopFont( &p_fonts ) );
761 }
762
763 static int RenderHtml( filter_t *p_filter, subpicture_region_t *p_region_out,
764                        subpicture_region_t *p_region_in )
765 {
766     int          rv = VLC_SUCCESS;
767     stream_t     *p_sub = NULL;
768     xml_t        *p_xml = NULL;
769     xml_reader_t *p_xml_reader = NULL;
770
771     if( !p_region_in || !p_region_in->psz_html )
772         return VLC_EGENERIC;
773
774     p_sub = stream_MemoryNew( VLC_OBJECT(p_filter),
775                               (uint8_t *) p_region_in->psz_html,
776                               strlen( p_region_in->psz_html ),
777                               VLC_TRUE );
778     if( p_sub )
779     {
780         p_xml = xml_Create( p_filter );
781         if( p_xml )
782         {
783             p_xml_reader = xml_ReaderCreate( p_xml, p_sub );
784             if( p_xml_reader )
785             {
786                 UniChar    *psz_text;
787                 int         i_len;
788                 uint32_t    i_runs = 0;
789                 uint32_t   *pi_run_lengths = NULL;
790                 ATSUStyle  *pp_styles = NULL;
791
792                 psz_text = (UniChar *) calloc( strlen( p_region_in->psz_html ), sizeof( UniChar ) );
793                 if( psz_text )
794                 {
795                     uint32_t k;
796
797                     ProcessNodes( p_filter, p_xml_reader, p_region_in->p_style, psz_text,
798                                   &i_len, &i_runs, &pi_run_lengths, &pp_styles );
799
800                     p_region_out->i_x = p_region_in->i_x;
801                     p_region_out->i_y = p_region_in->i_y;
802
803                     RenderYUVA( p_filter, p_region_out, psz_text, i_len, i_runs, pi_run_lengths, pp_styles);
804
805                     for( k=0; k<i_runs; k++)
806                         ATSUDisposeStyle( pp_styles[k] );
807                     free( pp_styles );
808                     free( pi_run_lengths );
809
810                     free( psz_text );
811                 }
812
813                 xml_ReaderDelete( p_xml, p_xml_reader );
814             }
815             xml_Delete( p_xml );
816         }
817         stream_Delete( p_sub );
818     }
819
820     return rv;
821 }
822
823 static CGContextRef CreateOffScreenContext( int i_width, int i_height,
824                          offscreen_bitmap_t **pp_memory, CGColorSpaceRef *pp_colorSpace )
825 {
826     offscreen_bitmap_t *p_bitmap;
827     CGContextRef        p_context = NULL;
828
829     p_bitmap = (offscreen_bitmap_t *) malloc( sizeof( offscreen_bitmap_t ));
830     if( p_bitmap )
831     {
832         p_bitmap->i_bitsPerChannel = 8;
833         p_bitmap->i_bitsPerPixel   = 4 * p_bitmap->i_bitsPerChannel; // A,R,G,B
834         p_bitmap->i_bytesPerPixel  = p_bitmap->i_bitsPerPixel / 8;
835         p_bitmap->i_bytesPerRow    = i_width * p_bitmap->i_bytesPerPixel;
836
837         p_bitmap->p_data = calloc( i_height, p_bitmap->i_bytesPerRow );
838
839 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4
840         *pp_colorSpace = CGColorSpaceCreateWithName( kCGColorSpaceGenericRGB );
841 #else
842         *pp_colorSpace = CreateGenericRGBColorSpace();
843 #endif
844
845         if( p_bitmap->p_data && *pp_colorSpace )
846         {
847             p_context = CGBitmapContextCreate( p_bitmap->p_data, i_width, i_height,
848                                 p_bitmap->i_bitsPerChannel, p_bitmap->i_bytesPerRow,
849                                 *pp_colorSpace, kCGImageAlphaPremultipliedFirst);
850         }
851         if( p_context )
852         {
853 #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_1
854             // OS X 10.1 doesn't support weak linking of this call which is only available
855             // int 10.4 and later
856             if( CGContextSetAllowsAntialiasing != NULL )
857             {
858                 CGContextSetAllowsAntialiasing( p_context, true );
859             }
860 #endif
861         }
862         *pp_memory = p_bitmap;
863     }
864
865     return p_context;
866 }
867
868 static offscreen_bitmap_t *Compose( int i_text_align, UniChar *psz_utf16_str, uint32_t i_text_len,
869                                     uint32_t i_runs, uint32_t *pi_run_lengths, ATSUStyle *pp_styles,
870                                     int i_width, int i_height, int *pi_textblock_height )
871 {
872     offscreen_bitmap_t  *p_offScreen  = NULL;
873     CGColorSpaceRef      p_colorSpace = NULL;
874     CGContextRef         p_context = NULL;
875
876     p_context = CreateOffScreenContext( i_width, i_height, &p_offScreen, &p_colorSpace );
877
878     if( p_context )
879     {
880         ATSUTextLayout p_textLayout;
881         OSStatus status = noErr;
882
883         status = ATSUCreateTextLayoutWithTextPtr( psz_utf16_str, 0, i_text_len, i_text_len,
884                                                   i_runs,
885                                                   (const UniCharCount *) pi_run_lengths,
886                                                   pp_styles,
887                                                   &p_textLayout );
888         if( status == noErr )
889         {
890             // Attach our offscreen Image Graphics Context to the text style
891             // and setup the line alignment (have to specify the line width
892             // also in order for our chosen alignment to work)
893
894             Fract   alignment  = kATSUStartAlignment;
895             Fixed   line_width = Long2Fix( i_width - HORIZONTAL_MARGIN * 2 );
896
897             ATSUAttributeTag tags[]        = { kATSUCGContextTag, kATSULineFlushFactorTag, kATSULineWidthTag };
898             ByteCount sizes[]              = { sizeof( CGContextRef ), sizeof( Fract ), sizeof( Fixed ) };
899             ATSUAttributeValuePtr values[] = { &p_context, &alignment, &line_width };
900
901             int i_tag_cnt = sizeof( tags ) / sizeof( ATSUAttributeTag );
902
903             if( i_text_align == SUBPICTURE_ALIGN_RIGHT )
904             {
905                 alignment = kATSUEndAlignment;
906             }
907             else if( i_text_align != SUBPICTURE_ALIGN_LEFT )
908             {
909                 alignment = kATSUCenterAlignment;
910             }
911
912             ATSUSetLayoutControls( p_textLayout, i_tag_cnt, tags, sizes, values );
913
914             // let ATSUI deal with characters not-in-our-specified-font
915             ATSUSetTransientFontMatching( p_textLayout, true );
916
917             Fixed x = Long2Fix( HORIZONTAL_MARGIN );
918             Fixed y = Long2Fix( i_height );
919
920             // Set the line-breaks and draw individual lines
921             uint32_t i_start = 0;
922             uint32_t i_end = i_text_len;
923
924             // Set up black outlining of the text --
925             CGContextSetRGBStrokeColor( p_context, 0, 0, 0, 0.5 );
926             CGContextSetTextDrawingMode( p_context, kCGTextFillStroke );
927
928             do
929             {
930                 // ATSUBreakLine will automatically pick up any manual '\n's also
931                 status = ATSUBreakLine( p_textLayout, i_start, line_width, true, (UniCharArrayOffset *) &i_end );
932                 if( ( status == noErr ) || ( status == kATSULineBreakInWord ) )
933                 {
934                     Fixed     ascent;
935                     Fixed     descent;
936                     uint32_t  i_actualSize;
937
938                     // Come down far enough to fit the height of this line --
939                     ATSUGetLineControl( p_textLayout, i_start, kATSULineAscentTag,
940                                     sizeof( Fixed ), &ascent, (ByteCount *) &i_actualSize );
941
942                     // Quartz uses an upside-down co-ordinate space -> y values decrease as
943                     // you move down the page
944                     y -= ascent;
945
946                     // Set the outlining for this line to be dependant on the size of the line -
947                     // make it about 5% of the ascent, with a minimum at 1.0
948                     float f_thickness = FixedToFloat( ascent ) * 0.05;
949                     CGContextSetLineWidth( p_context, (( f_thickness > 1.0 ) ? 1.0 : f_thickness ));
950
951                     ATSUDrawText( p_textLayout, i_start, i_end - i_start, x, y );
952
953                     // and now prepare for the next line by coming down far enough for our
954                     // descent
955                     ATSUGetLineControl( p_textLayout, i_start, kATSULineDescentTag,
956                                     sizeof( Fixed ), &descent, (ByteCount *) &i_actualSize );
957                     y -= descent;
958
959                     i_start = i_end;
960                 }
961                 else
962                     break;
963             }
964             while( i_end < i_text_len );
965
966             *pi_textblock_height = i_height - Fix2Long( y );
967             CGContextFlush( p_context );
968
969             ATSUDisposeTextLayout( p_textLayout );
970         }
971
972         CGContextRelease( p_context );
973     }
974     if( p_colorSpace ) CGColorSpaceRelease( p_colorSpace );
975
976     return p_offScreen;
977 }
978
979 static int RenderYUVA( filter_t *p_filter, subpicture_region_t *p_region, UniChar *psz_utf16_str,
980                        uint32_t i_text_len, uint32_t i_runs, uint32_t *pi_run_lengths, ATSUStyle *pp_styles )
981 {
982     offscreen_bitmap_t *p_offScreen = NULL;
983     int      i_textblock_height = 0;
984
985     int i_width = p_filter->fmt_out.video.i_visible_width;
986     int i_height = p_filter->fmt_out.video.i_visible_height;
987     int i_text_align = p_region->i_align & 0x3;
988
989     if( !psz_utf16_str )
990     {
991         msg_Err( p_filter, "Invalid argument to RenderYUVA" );
992         return VLC_EGENERIC;
993     }
994
995     p_offScreen = Compose( i_text_align, psz_utf16_str, i_text_len,
996                            i_runs, pi_run_lengths, pp_styles,
997                            i_width, i_height, &i_textblock_height );
998
999     if( !p_offScreen )
1000     {
1001         msg_Err( p_filter, "No offscreen buffer" );
1002         return VLC_EGENERIC;
1003     }
1004
1005     uint8_t *p_dst_y,*p_dst_u,*p_dst_v,*p_dst_a;
1006     video_format_t fmt;
1007     int x, y, i_offset, i_pitch;
1008     uint8_t i_y, i_u, i_v; // YUV values, derived from incoming RGB
1009     subpicture_region_t *p_region_tmp;
1010
1011     // Create a new subpicture region
1012     memset( &fmt, 0, sizeof(video_format_t) );
1013     fmt.i_chroma = VLC_FOURCC('Y','U','V','A');
1014     fmt.i_aspect = 0;
1015     fmt.i_width = fmt.i_visible_width = i_width;
1016     fmt.i_height = fmt.i_visible_height = i_textblock_height + VERTICAL_MARGIN * 2;
1017     fmt.i_x_offset = fmt.i_y_offset = 0;
1018     p_region_tmp = spu_CreateRegion( p_filter, &fmt );
1019     if( !p_region_tmp )
1020     {
1021         msg_Err( p_filter, "cannot allocate SPU region" );
1022         return VLC_EGENERIC;
1023     }
1024     p_region->fmt = p_region_tmp->fmt;
1025     p_region->picture = p_region_tmp->picture;
1026     free( p_region_tmp );
1027
1028     p_dst_y = p_region->picture.Y_PIXELS;
1029     p_dst_u = p_region->picture.U_PIXELS;
1030     p_dst_v = p_region->picture.V_PIXELS;
1031     p_dst_a = p_region->picture.A_PIXELS;
1032     i_pitch = p_region->picture.A_PITCH;
1033
1034     i_offset = VERTICAL_MARGIN *i_pitch;
1035     for( y=0; y<i_textblock_height; y++)
1036     {
1037         for( x=0; x<i_width; x++)
1038         {
1039             int i_alpha = p_offScreen->p_data[ y * p_offScreen->i_bytesPerRow + x * p_offScreen->i_bytesPerPixel     ];
1040             int i_red   = p_offScreen->p_data[ y * p_offScreen->i_bytesPerRow + x * p_offScreen->i_bytesPerPixel + 1 ];
1041             int i_green = p_offScreen->p_data[ y * p_offScreen->i_bytesPerRow + x * p_offScreen->i_bytesPerPixel + 2 ];
1042             int i_blue  = p_offScreen->p_data[ y * p_offScreen->i_bytesPerRow + x * p_offScreen->i_bytesPerPixel + 3 ];
1043
1044             i_y = (uint8_t)__MIN(abs( 2104 * i_red  + 4130 * i_green +
1045                               802 * i_blue + 4096 + 131072 ) >> 13, 235);
1046             i_u = (uint8_t)__MIN(abs( -1214 * i_red  + -2384 * i_green +
1047                              3598 * i_blue + 4096 + 1048576) >> 13, 240);
1048             i_v = (uint8_t)__MIN(abs( 3598 * i_red + -3013 * i_green +
1049                               -585 * i_blue + 4096 + 1048576) >> 13, 240);
1050
1051             p_dst_y[ i_offset + x ] = i_y;
1052             p_dst_u[ i_offset + x ] = i_u;
1053             p_dst_v[ i_offset + x ] = i_v;
1054             p_dst_a[ i_offset + x ] = i_alpha;
1055         }
1056         i_offset += i_pitch;
1057     }
1058
1059     free( p_offScreen->p_data );
1060     free( p_offScreen );
1061
1062     return VLC_SUCCESS;
1063 }