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