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