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