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