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