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