]> git.sesse.net Git - vlc/blob - modules/codec/subsdec.c
Missing #includes
[vlc] / modules / codec / subsdec.c
1 /*****************************************************************************
2  * subsdec.c : text subtitles decoder
3  *****************************************************************************
4  * Copyright (C) 2000-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Derk-Jan Hartman <hartman at videolan dot org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <vlc/vlc.h>
30 #include <vlc_vout.h>
31 #include <vlc_codec.h>
32
33 #include <vlc_osd.h>
34 #include <vlc_filter.h>
35 #include <vlc_charset.h>
36 #include <errno.h>
37 #include <string.h>
38
39 typedef struct
40 {
41     char *          psz_stylename; /* The name of the style, no comma's allowed */
42     text_style_t    font_style;
43     int             i_align;
44     int             i_margin_h;
45     int             i_margin_v;
46 }  ssa_style_t;
47
48 /*****************************************************************************
49  * decoder_sys_t : decoder descriptor
50  *****************************************************************************/
51 struct decoder_sys_t
52 {
53     vlc_bool_t          b_ass;                           /* The subs are ASS */
54     int                 i_original_height;
55     int                 i_original_width;
56     int                 i_align;          /* Subtitles alignment on the vout */
57     vlc_iconv_t         iconv_handle;            /* handle to iconv instance */
58     vlc_bool_t          b_autodetect_utf8;
59
60     ssa_style_t         **pp_ssa_styles;
61     int                 i_ssa_styles;
62 };
63
64 /*****************************************************************************
65  * Local prototypes
66  *****************************************************************************/
67 static int  OpenDecoder   ( vlc_object_t * );
68 static void CloseDecoder  ( vlc_object_t * );
69
70 static subpicture_t *DecodeBlock   ( decoder_t *, block_t ** );
71 static subpicture_t *ParseText     ( decoder_t *, block_t * );
72 static void         ParseSSAHeader ( decoder_t * );
73 static void         ParseSSAString ( decoder_t *, char *, subpicture_t * );
74 static void         ParseColor     ( decoder_t *, char *, int *, int * );
75 static void         StripTags      ( char * );
76
77 #define DEFAULT_NAME "Default"
78 #define MAX_LINE 8192
79
80 /*****************************************************************************
81  * Module descriptor.
82  *****************************************************************************/
83 static const char *ppsz_encodings[] = { DEFAULT_NAME, "ASCII", "UTF-8", "",
84     "ISO-8859-1", "CP1252", "MacRoman", "MacIceland","ISO-8859-15", "",
85     "ISO-8859-2", "CP1250", "MacCentralEurope", "MacCroatian", "MacRomania", "",
86     "ISO-8859-5", "CP1251", "MacCyrillic", "MacUkraine", "KOI8-R", "KOI8-U", "KOI8-RU", "",
87     "ISO-8859-6", "CP1256", "MacArabic", "",
88     "ISO-8859-7", "CP1253", "MacGreek", "",
89     "ISO-8859-8", "CP1255", "MacHebrew", "",
90     "ISO-8859-9", "CP1254", "MacTurkish", "",
91     "ISO-8859-13", "CP1257", "",
92     "ISO-2022-JP", "ISO-2022-JP-1", "ISO-2022-JP-2", "EUC-JP", "SHIFT_JIS", "",
93     "ISO-2022-CN", "ISO-2022-CN-EXT", "EUC-CN", "EUC-TW", "BIG5", "BIG5-HKSCS", "",
94     "ISO-2022-KR", "EUC-KR", "",
95     "MacThai", "KOI8-T", "",
96     "ISO-8859-3", "ISO-8859-4", "ISO-8859-10", "ISO-8859-14", "ISO-8859-16", "",
97     "CP850", "CP862", "CP866", "CP874", "CP932", "CP949", "CP950", "CP1133", "CP1258", "",
98     "Macintosh", "",
99     "UTF-7", "UTF-16", "UTF-16BE", "UTF-16LE", "UTF-32", "UTF-32BE", "UTF-32LE",
100     "C99", "JAVA", "UCS-2", "UCS-2BE", "UCS-2LE", "UCS-4", "UCS-4BE", "UCS-4LE", "",
101     "HZ", "GBK", "GB18030", "JOHAB", "ARMSCII-8",
102     "Georgian-Academy", "Georgian-PS", "TIS-620", "MuleLao-1", "VISCII", "TCVN",
103     "HPROMAN8", "NEXTSTEP" };
104 /*
105 SSA supports charset selection.
106 The following known charsets are used:
107
108 0 = Ansi - Western European
109 1 = default
110 2 = symbol
111 3 = invalid
112 77 = Mac
113 128 = Japanese (Shift JIS)
114 129 = Hangul
115 130 = Johab
116 134 = GB2312 Simplified Chinese
117 136 = Big5 Traditional Chinese
118 161 = Greek
119 162 = Turkish
120 163 = Vietnamese
121 177 = Hebrew
122 178 = Arabic
123 186 = Baltic
124 204 = Russian (Cyrillic)
125 222 = Thai
126 238 = Eastern European
127 254 = PC 437
128 */
129
130 static int  pi_justification[] = { 0, 1, 2 };
131 static const char *ppsz_justification_text[] = {N_("Center"),N_("Left"),N_("Right")};
132
133 #define ENCODING_TEXT N_("Subtitles text encoding")
134 #define ENCODING_LONGTEXT N_("Set the encoding used in text subtitles")
135 #define ALIGN_TEXT N_("Subtitles justification")
136 #define ALIGN_LONGTEXT N_("Set the justification of subtitles")
137 #define AUTODETECT_UTF8_TEXT N_("UTF-8 subtitles autodetection")
138 #define AUTODETECT_UTF8_LONGTEXT N_("This enables automatic detection of " \
139             "UTF-8 encoding within subtitles files.")
140 #define FORMAT_TEXT N_("Formatted Subtitles")
141 #define FORMAT_LONGTEXT N_("Some subtitle formats allow for text formatting. " \
142  "VLC partly implements this, but you can choose to disable all formatting.")
143
144
145 vlc_module_begin();
146     set_shortname( _("Subtitles"));
147     set_description( _("Text subtitles decoder") );
148     set_capability( "decoder", 50 );
149     set_callbacks( OpenDecoder, CloseDecoder );
150     set_category( CAT_INPUT );
151     set_subcategory( SUBCAT_INPUT_SCODEC );
152
153     add_integer( "subsdec-align", 0, NULL, ALIGN_TEXT, ALIGN_LONGTEXT,
154                  VLC_FALSE );
155         change_integer_list( pi_justification, ppsz_justification_text, 0 );
156     add_string( "subsdec-encoding", DEFAULT_NAME, NULL,
157                 ENCODING_TEXT, ENCODING_LONGTEXT, VLC_FALSE );
158         change_string_list( ppsz_encodings, 0, 0 );
159     add_bool( "subsdec-autodetect-utf8", VLC_TRUE, NULL,
160               AUTODETECT_UTF8_TEXT, AUTODETECT_UTF8_LONGTEXT, VLC_FALSE );
161     add_bool( "subsdec-formatted", VLC_TRUE, NULL, FORMAT_TEXT, FORMAT_LONGTEXT,
162                  VLC_FALSE );
163 vlc_module_end();
164
165 /*****************************************************************************
166  * OpenDecoder: probe the decoder and return score
167  *****************************************************************************
168  * Tries to launch a decoder and return score so that the interface is able
169  * to chose.
170  *****************************************************************************/
171 static int OpenDecoder( vlc_object_t *p_this )
172 {
173     decoder_t     *p_dec = (decoder_t*)p_this;
174     decoder_sys_t *p_sys;
175     vlc_value_t    val;
176
177     if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','u','b','t') &&
178         p_dec->fmt_in.i_codec != VLC_FOURCC('s','s','a',' ') )
179     {
180         return VLC_EGENERIC;
181     }
182
183     p_dec->pf_decode_sub = DecodeBlock;
184
185     /* Allocate the memory needed to store the decoder's structure */
186     if( ( p_dec->p_sys = p_sys =
187           (decoder_sys_t *)calloc(1, sizeof(decoder_sys_t)) ) == NULL )
188     {
189         msg_Err( p_dec, "out of memory" );
190         return VLC_ENOMEM;
191     }
192
193     /* init of p_sys */
194     p_sys->i_align = 0;
195     p_sys->iconv_handle = (vlc_iconv_t)-1;
196     p_sys->b_autodetect_utf8 = VLC_FALSE;
197     p_sys->b_ass = VLC_FALSE;
198     p_sys->i_original_height = -1;
199     p_sys->i_original_width = -1;
200     p_sys->pp_ssa_styles = NULL;
201     p_sys->i_ssa_styles = 0;
202
203     char *psz_charset = NULL;
204     /* First try demux-specified encoding */
205     if( p_dec->fmt_in.subs.psz_encoding && *p_dec->fmt_in.subs.psz_encoding )
206     {
207         psz_charset = strdup (p_dec->fmt_in.subs.psz_encoding);
208         msg_Dbg (p_dec, "trying demuxer-specified character encoding: %s",
209                  p_dec->fmt_in.subs.psz_encoding ?: "not specified");
210     }
211
212     /* Second, try configured encoding */
213     if (psz_charset == NULL)
214     {
215         psz_charset = var_CreateGetNonEmptyString (p_dec, "subsdec-encoding");
216         if ((psz_charset != NULL) && !strcasecmp (psz_charset, DEFAULT_NAME))
217         {
218             free (psz_charset);
219             psz_charset = NULL;
220         }
221
222         msg_Dbg (p_dec, "trying configured character encoding: %s",
223                  psz_charset ?: "not specified");
224     }
225
226     /* Third, try "local" encoding with optional UTF-8 autodetection */
227     if (psz_charset == NULL)
228     {
229         psz_charset = strdup (GetFallbackEncoding ());
230         msg_Dbg (p_dec, "trying default character encoding: %s",
231                  psz_charset ?: "not specified");
232
233         if (var_CreateGetBool (p_dec, "subsdec-autodetect-utf8"))
234         {
235             msg_Dbg (p_dec, "using automatic UTF-8 detection");
236             p_sys->b_autodetect_utf8 = VLC_TRUE;
237         }
238     }
239
240     if (psz_charset == NULL)
241     {
242         psz_charset = strdup ("UTF-8");
243         msg_Dbg (p_dec, "trying hard-coded character encoding: %s",
244                  psz_charset ?: "error");
245     }
246
247     if (psz_charset == NULL)
248     {
249         free (p_sys);
250         return VLC_ENOMEM;
251     }
252
253     if (strcasecmp (psz_charset, "UTF-8") && strcasecmp (psz_charset, "utf8"))
254     {
255         p_sys->iconv_handle = vlc_iconv_open ("UTF-8", psz_charset);
256         if (p_sys->iconv_handle == (vlc_iconv_t)(-1))
257             msg_Err (p_dec, "cannot convert from %s: %s", psz_charset,
258                      strerror (errno));
259     }
260     free (psz_charset);
261
262     var_Create( p_dec, "subsdec-align", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
263     var_Get( p_dec, "subsdec-align", &val );
264     p_sys->i_align = val.i_int;
265
266     if( p_dec->fmt_in.i_codec == VLC_FOURCC('s','s','a',' ') && var_CreateGetBool( p_dec, "subsdec-formatted" ) )
267     {
268         if( p_dec->fmt_in.i_extra > 0 )
269             ParseSSAHeader( p_dec );
270     }
271
272     return VLC_SUCCESS;
273 }
274
275 /****************************************************************************
276  * DecodeBlock: the whole thing
277  ****************************************************************************
278  * This function must be fed with complete subtitles units.
279  ****************************************************************************/
280 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
281 {
282     subpicture_t *p_spu = NULL;
283
284     if( !pp_block || *pp_block == NULL ) return NULL;
285
286     p_spu = ParseText( p_dec, *pp_block );
287
288     block_Release( *pp_block );
289     *pp_block = NULL;
290
291     return p_spu;
292 }
293
294 /*****************************************************************************
295  * CloseDecoder: clean up the decoder
296  *****************************************************************************/
297 static void CloseDecoder( vlc_object_t *p_this )
298 {
299     decoder_t *p_dec = (decoder_t *)p_this;
300     decoder_sys_t *p_sys = p_dec->p_sys;
301
302     if( p_sys->iconv_handle != (vlc_iconv_t)-1 )
303     {
304         vlc_iconv_close( p_sys->iconv_handle );
305     }
306
307     if( p_sys->pp_ssa_styles )
308     {
309         int i;
310         for( i = 0; i < p_sys->i_ssa_styles; i++ )
311         {
312             if( p_sys->pp_ssa_styles[i]->psz_stylename ) free( p_sys->pp_ssa_styles[i]->psz_stylename );
313             p_sys->pp_ssa_styles[i]->psz_stylename = NULL;
314             if( p_sys->pp_ssa_styles[i]->font_style.psz_fontname ) free( p_sys->pp_ssa_styles[i]->font_style.psz_fontname );
315             p_sys->pp_ssa_styles[i]->font_style.psz_fontname = NULL;
316             if( p_sys->pp_ssa_styles[i] ) free( p_sys->pp_ssa_styles[i] ); p_sys->pp_ssa_styles[i] = NULL;
317         }
318         free( p_sys->pp_ssa_styles ); p_sys->pp_ssa_styles = NULL;
319     }
320
321     free( p_sys );
322 }
323
324 /*****************************************************************************
325  * ParseText: parse an text subtitle packet and send it to the video output
326  *****************************************************************************/
327 static subpicture_t *ParseText( decoder_t *p_dec, block_t *p_block )
328 {
329     decoder_sys_t *p_sys = p_dec->p_sys;
330     subpicture_t *p_spu = NULL;
331     char *psz_subtitle = NULL;
332     video_format_t fmt;
333
334     /* We cannot display a subpicture with no date */
335     if( p_block->i_pts == 0 )
336     {
337         msg_Warn( p_dec, "subtitle without a date" );
338         return NULL;
339     }
340
341     /* Check validity of packet data */
342     /* An "empty" line containing only \0 can be used to force
343        and ephemer picture from the screen */
344     if( p_block->i_buffer < 1 )
345     {
346         msg_Warn( p_dec, "no subtitle data" );
347         return NULL;
348     }
349
350     /* Should be resiliant against bad subtitles */
351     psz_subtitle = strndup( (const char *)p_block->p_buffer,
352                             p_block->i_buffer );
353     if( psz_subtitle == NULL )
354         return NULL;
355
356     if( p_sys->iconv_handle == (vlc_iconv_t)-1 )
357     {
358         if (EnsureUTF8( psz_subtitle ) == NULL)
359         {
360             msg_Err( p_dec, _("failed to convert subtitle encoding.\n"
361                      "Try manually setting a character-encoding "
362                      "before you open the file.") );
363         }
364     }
365     else
366     {
367
368         if( p_sys->b_autodetect_utf8 )
369         {
370             if( IsUTF8( psz_subtitle ) == NULL )
371             {
372                 msg_Dbg( p_dec, "invalid UTF-8 sequence: "
373                          "disabling UTF-8 subtitles autodetection" );
374                 p_sys->b_autodetect_utf8 = VLC_FALSE;
375             }
376         }
377
378         if( !p_sys->b_autodetect_utf8 )
379         {
380             size_t inbytes_left = strlen( psz_subtitle );
381             size_t outbytes_left = 6 * inbytes_left;
382             char *psz_new_subtitle = malloc( outbytes_left + 1 );
383             char *psz_convert_buffer_out = psz_new_subtitle;
384             const char *psz_convert_buffer_in = psz_subtitle;
385
386             size_t ret = vlc_iconv( p_sys->iconv_handle,
387                                     &psz_convert_buffer_in, &inbytes_left,
388                                     &psz_convert_buffer_out, &outbytes_left );
389
390             *psz_convert_buffer_out++ = '\0';
391             free( psz_subtitle );
392
393             if( ( ret == (size_t)(-1) ) || inbytes_left )
394             {
395                 free( psz_new_subtitle );
396                 msg_Err( p_dec, _("failed to convert subtitle encoding.\n"
397                         "Try manually setting a character-encoding "
398                                 "before you open the file.") );
399                 return NULL;
400             }
401
402             psz_subtitle = realloc( psz_new_subtitle,
403                                     psz_convert_buffer_out - psz_new_subtitle );
404         }
405     }
406
407     /* Create the subpicture unit */
408     p_spu = p_dec->pf_spu_buffer_new( p_dec );
409     if( !p_spu )
410     {
411         msg_Warn( p_dec, "can't get spu buffer" );
412         if( psz_subtitle ) free( psz_subtitle );
413         return NULL;
414     }
415
416     p_spu->b_pausable = VLC_TRUE;
417
418     /* Create a new subpicture region */
419     memset( &fmt, 0, sizeof(video_format_t) );
420     fmt.i_chroma = VLC_FOURCC('T','E','X','T');
421     fmt.i_aspect = 0;
422     fmt.i_width = fmt.i_height = 0;
423     fmt.i_x_offset = fmt.i_y_offset = 0;
424     p_spu->p_region = p_spu->pf_create_region( VLC_OBJECT(p_dec), &fmt );
425     if( !p_spu->p_region )
426     {
427         msg_Err( p_dec, "cannot allocate SPU region" );
428         if( psz_subtitle ) free( psz_subtitle );
429         p_dec->pf_spu_buffer_del( p_dec, p_spu );
430         return NULL;
431     }
432
433     /* Decode and format the subpicture unit */
434     if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','s','a',' ') )
435     {
436         /* Normal text subs, easy markup */
437         p_spu->i_flags = SUBPICTURE_ALIGN_BOTTOM | p_sys->i_align;
438         p_spu->i_x = p_sys->i_align ? 20 : 0;
439         p_spu->i_y = 10;
440
441         /* Remove formatting from string */
442         StripTags( psz_subtitle );
443
444         p_spu->p_region->psz_text = psz_subtitle;
445         p_spu->i_start = p_block->i_pts;
446         p_spu->i_stop = p_block->i_pts + p_block->i_length;
447         p_spu->b_ephemer = (p_block->i_length == 0);
448         p_spu->b_absolute = VLC_FALSE;
449     }
450     else
451     {
452         /* Decode SSA strings */
453         ParseSSAString( p_dec, psz_subtitle, p_spu );
454         p_spu->i_start = p_block->i_pts;
455         p_spu->i_stop = p_block->i_pts + p_block->i_length;
456         p_spu->b_ephemer = (p_block->i_length == 0);
457         p_spu->b_absolute = VLC_FALSE;
458         p_spu->i_original_picture_width = p_sys->i_original_width;
459         p_spu->i_original_picture_height = p_sys->i_original_height;
460         if( psz_subtitle ) free( psz_subtitle );
461     }
462     return p_spu;
463 }
464
465 static void ParseSSAString( decoder_t *p_dec, char *psz_subtitle, subpicture_t *p_spu_in )
466 {
467     /* We expect MKV formatted SSA:
468      * ReadOrder, Layer, Style, CharacterName, MarginL, MarginR,
469      * MarginV, Effect, Text */
470     decoder_sys_t   *p_sys = p_dec->p_sys;
471     subpicture_t    *p_spu = p_spu_in;
472     ssa_style_t     *p_style = NULL;
473     char            *psz_new_subtitle = NULL;
474     char            *psz_buffer_sub = NULL;
475     char            *psz_style = NULL;
476     char            *psz_style_start = NULL;
477     char            *psz_style_end = NULL;
478     int             i_text = 0, i_comma = 0, i_strlen = 0, i;
479     int             i_margin_l = 0, i_margin_r = 0, i_margin_v = 0;
480
481     psz_buffer_sub = psz_subtitle;
482
483     i_comma = 0;
484     while( i_comma < 8 && *psz_buffer_sub != '\0' )
485     {
486         if( *psz_buffer_sub == ',' )
487         {
488             i_comma++;
489             if( i_comma == 2 ) psz_style_start = &psz_buffer_sub[1];
490             if( i_comma == 3 ) psz_style_end = &psz_buffer_sub[0];
491             if( i_comma == 4 ) i_margin_l = (int)strtol( psz_buffer_sub+1, NULL, 10 );
492             if( i_comma == 5 ) i_margin_r = (int)strtol( psz_buffer_sub+1, NULL, 10 );
493             if( i_comma == 6 ) i_margin_v = (int)strtol( psz_buffer_sub+1, NULL, 10 );
494         }
495         psz_buffer_sub++;
496     }
497
498     if( *psz_buffer_sub == '\0' && i_comma == 8 )
499     {
500         msg_Dbg( p_dec, "couldn't find all fields in this SSA line" );
501         return;
502     }
503
504     psz_new_subtitle = malloc( strlen( psz_buffer_sub ) + 1);
505     i_text = 0;
506     while( psz_buffer_sub[0] != '\0' )
507     {
508         if( psz_buffer_sub[0] == '\\' && psz_buffer_sub[1] == 'n' )
509         {
510             psz_new_subtitle[i_text] = ' ';
511             i_text++;
512             psz_buffer_sub += 2;
513         }
514         else if( psz_buffer_sub[0] == '\\' && psz_buffer_sub[1] == 'N' )
515         {
516             psz_new_subtitle[i_text] = '\n';
517             i_text++;
518             psz_buffer_sub += 2;
519         }
520         else if( psz_buffer_sub[0] == '{' &&
521                  psz_buffer_sub[1] == '\\' )
522         {
523             /* SSA control code */
524             while( psz_buffer_sub[0] != '\0' &&
525                    psz_buffer_sub[0] != '}' )
526             {
527                 psz_buffer_sub++;
528             }
529             psz_buffer_sub++;
530         }
531         else
532         {
533             psz_new_subtitle[i_text] = psz_buffer_sub[0];
534             i_text++;
535             psz_buffer_sub++;
536         }
537     }
538     psz_new_subtitle[i_text] = '\0';
539
540     i_strlen = __MAX( psz_style_end - psz_style_start, 0);
541     psz_style = (char *)malloc( i_strlen + 1);
542     psz_style = memcpy( psz_style, psz_style_start, i_strlen );
543     psz_style[i_strlen] = '\0';
544
545     for( i = 0; i < p_sys->i_ssa_styles; i++ )
546     {
547         if( !strcmp( p_sys->pp_ssa_styles[i]->psz_stylename, psz_style ) )
548             p_style = p_sys->pp_ssa_styles[i];
549     }
550     if( psz_style ) free( psz_style );
551
552     p_spu->p_region->psz_text = psz_new_subtitle;
553     if( p_style == NULL )
554     {
555         p_spu->i_flags = SUBPICTURE_ALIGN_BOTTOM | p_sys->i_align;
556         p_spu->i_x = p_sys->i_align ? 20 : 0;
557         p_spu->i_y = 10;
558     }
559     else
560     {
561         msg_Dbg( p_dec, "style is: %s", p_style->psz_stylename);
562         p_spu->p_region->p_style = &p_style->font_style;
563         p_spu->i_flags = p_style->i_align;
564         if( p_style->i_align & SUBPICTURE_ALIGN_LEFT )
565         {
566             p_spu->i_x = (i_margin_l) ? i_margin_l : p_style->i_margin_h;
567         }
568         else if( p_style->i_align & SUBPICTURE_ALIGN_RIGHT ) 
569         {
570             p_spu->i_x = (i_margin_r) ? i_margin_r : p_style->i_margin_h;
571         }
572         p_spu->i_y = (i_margin_v) ? i_margin_v : p_style->i_margin_v;
573     }
574 }
575
576 static char* GotoNextLine( char *psz_text )
577 {
578     char *p_newline = psz_text;
579
580     while( p_newline[0] != '\0' )
581     {
582         if( p_newline[0] == '\n' || p_newline[0] == '\r' )
583         {
584             p_newline++;
585             while( p_newline[0] == '\n' || p_newline[0] == '\r' )
586                 p_newline++;
587             break;
588         }
589         else p_newline++;
590     }
591     return p_newline;
592 }
593
594 /*****************************************************************************
595  * ParseColor: SSA stores color in BBGGRR, in ASS it uses AABBGGRR
596  * The string value in the string can be a pure integer, or hexadecimal &HBBGGRR
597  *****************************************************************************/
598 static void ParseColor( decoder_t *p_dec, char *psz_color, int *pi_color, int *pi_alpha )
599 {
600     int i_color = 0;
601     if( !strncasecmp( psz_color, "&H", 2 ) )
602     {
603         /* textual HEX representation */
604         i_color = (int) strtol( psz_color+2, NULL, 16 );
605     }
606     else i_color = (int) strtol( psz_color, NULL, 0 );
607
608     *pi_color = 0;
609     *pi_color |= ( ( i_color & 0x000000FF ) << 16 ); /* Red */
610     *pi_color |= ( ( i_color & 0x0000FF00 ) );       /* Green */
611     *pi_color |= ( ( i_color & 0x00FF0000 ) >> 16 ); /* Blue */
612
613     if( pi_alpha != NULL )
614         *pi_alpha = ( i_color & 0xFF000000 ) >> 24;
615 }
616
617 /*****************************************************************************
618  * ParseSSAHeader: Retrieve global formatting information etc
619  *****************************************************************************/
620 static void ParseSSAHeader( decoder_t *p_dec )
621 {
622     decoder_sys_t *p_sys = p_dec->p_sys;
623     char *psz_parser = NULL;
624     char *psz_header = malloc( p_dec->fmt_in.i_extra+1 );
625     int i_section_type = 1;
626
627     memcpy( psz_header, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
628     psz_header[ p_dec->fmt_in.i_extra] = '\0';
629
630     /* Handle [Script Info] section */
631     psz_parser = strcasestr( psz_header, "[Script Info]" );
632     if( psz_parser == NULL ) goto eof;
633
634     psz_parser = GotoNextLine( psz_parser );
635
636     while( psz_parser[0] != '\0' )
637     {
638         int temp;
639         char buffer_text[MAX_LINE + 1];
640
641         if( psz_parser[0] == '!' || psz_parser[0] == ';' ) /* comment */;
642         else if( sscanf( psz_parser, "PlayResX: %d", &temp ) == 1 )
643             p_sys->i_original_width = ( temp > 0 ) ? temp : -1;
644         else if( sscanf( psz_parser, "PlayResY: %d", &temp ) == 1 )
645             p_sys->i_original_height = ( temp > 0 ) ? temp : -1;
646         else if( sscanf( psz_parser, "Script Type: %8192s", buffer_text ) == 1 )
647         {
648             if( !strcasecmp( buffer_text, "V4.00+" ) ) p_sys->b_ass = VLC_TRUE;
649         }
650         else if( !strncasecmp( psz_parser, "[V4 Styles]", 11 ) )
651             i_section_type = 1;
652         else if( !strncasecmp( psz_parser, "[V4+ Styles]", 12) )
653         {
654             i_section_type = 2;
655             p_sys->b_ass = VLC_TRUE;
656         }
657         else if( !strncasecmp( psz_parser, "[Events]", 8 ) )
658             i_section_type = 4;
659         else if( !strncasecmp( psz_parser, "Style:", 6 ) )
660         {
661             int i_font_size, i_bold, i_italic, i_border, i_outline, i_shadow, i_underline,
662                 i_strikeout, i_scale_x, i_scale_y, i_spacing, i_align, i_margin_l, i_margin_r, i_margin_v;
663
664             char psz_temp_stylename[MAX_LINE+1];
665             char psz_temp_fontname[MAX_LINE+1];
666             char psz_temp_color1[MAX_LINE+1];
667             char psz_temp_color2[MAX_LINE+1];
668             char psz_temp_color3[MAX_LINE+1];
669             char psz_temp_color4[MAX_LINE+1];
670
671             if( i_section_type == 1 ) /* V4 */
672             {
673                 if( sscanf( psz_parser, "Style: %8192[^,],%8192[^,],%d,%8192[^,],%8192[^,],%8192[^,],%8192[^,],%d,%d,%d,%d,%d,%d,%d,%d,%d%*[^\r\n]",
674                     psz_temp_stylename, psz_temp_fontname, &i_font_size,
675                     psz_temp_color1, psz_temp_color2, psz_temp_color3, psz_temp_color4, &i_bold, &i_italic,
676                     &i_border, &i_outline, &i_shadow, &i_align, &i_margin_l, &i_margin_r, &i_margin_v ) == 16 )
677                 {
678                     ssa_style_t *p_style = malloc( sizeof(ssa_style_t) );
679
680                     p_style->psz_stylename = strdup( psz_temp_stylename );
681                     p_style->font_style.psz_fontname = strdup( psz_temp_fontname );
682                     p_style->font_style.i_font_size = i_font_size;
683
684                     ParseColor( p_dec, psz_temp_color1, &p_style->font_style.i_font_color, NULL );
685                     ParseColor( p_dec, psz_temp_color4, &p_style->font_style.i_shadow_color, NULL );
686                     p_style->font_style.i_outline_color = p_style->font_style.i_shadow_color;
687                     p_style->font_style.i_font_alpha = p_style->font_style.i_outline_alpha = p_style->font_style.i_shadow_alpha = 0x00;
688                     p_style->font_style.i_style_flags = 0;
689                     if( i_bold ) p_style->font_style.i_style_flags |= STYLE_BOLD;
690                     if( i_italic ) p_style->font_style.i_style_flags |= STYLE_ITALIC;
691
692                     if( i_border == 1 ) p_style->font_style.i_style_flags |= (STYLE_ITALIC | STYLE_OUTLINE);
693                     else if( i_border == 3 )
694                     {
695                         p_style->font_style.i_style_flags |= STYLE_BACKGROUND;
696                         p_style->font_style.i_background_color = p_style->font_style.i_shadow_color;
697                         p_style->font_style.i_background_alpha = p_style->font_style.i_shadow_alpha;
698                     }
699                     p_style->font_style.i_shadow_width = i_shadow;
700                     p_style->font_style.i_outline_width = i_outline;
701
702                     p_style->i_align = 0;
703                     if( i_align == 1 || i_align == 5 || i_align == 9 ) p_style->i_align |= SUBPICTURE_ALIGN_LEFT;
704                     if( i_align == 3 || i_align == 7 || i_align == 11 ) p_style->i_align |= SUBPICTURE_ALIGN_RIGHT;
705                     if( i_align < 4 ) p_style->i_align |= SUBPICTURE_ALIGN_BOTTOM;
706                     else if( i_align < 8 ) p_style->i_align |= SUBPICTURE_ALIGN_TOP; 
707
708                     p_style->i_margin_h = ( p_style->i_align & SUBPICTURE_ALIGN_RIGHT ) ? i_margin_r : i_margin_l;
709                     p_style->i_margin_v = i_margin_v;
710
711                     TAB_APPEND( p_sys->i_ssa_styles, p_sys->pp_ssa_styles, p_style );
712                 }
713                 else msg_Warn( p_dec, "SSA v4 styleline parsing failed" );
714             }
715             else if( i_section_type == 2 ) /* V4+ */
716             {
717                 /* Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour,
718                    Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline,
719                    Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
720                 */
721                 if( sscanf( psz_parser, "Style: %8192[^,],%8192[^,],%d,%8192[^,],%8192[^,],%8192[^,],%8192[^,],%d,%d,%d,%d,%d,%d,%d,%*f,%d,%d,%d,%d,%d,%d,%d%*[^\r\n]",
722                     psz_temp_stylename, psz_temp_fontname, &i_font_size,
723                     psz_temp_color1, psz_temp_color2, psz_temp_color3, psz_temp_color4, &i_bold, &i_italic,
724                     &i_underline, &i_strikeout, &i_scale_x, &i_scale_y, &i_spacing, &i_border, &i_outline,
725                     &i_shadow, &i_align, &i_margin_l, &i_margin_r, &i_margin_v ) == 21 )
726                 {
727                     ssa_style_t *p_style = malloc( sizeof(ssa_style_t) );
728
729                     p_style->psz_stylename = strdup( psz_temp_stylename );
730                     p_style->font_style.psz_fontname = strdup( psz_temp_fontname );
731                     p_style->font_style.i_font_size = i_font_size;
732                     msg_Dbg( p_dec, psz_temp_color1 );
733                     ParseColor( p_dec, psz_temp_color1, &p_style->font_style.i_font_color, &p_style->font_style.i_font_alpha );
734                     ParseColor( p_dec, psz_temp_color3, &p_style->font_style.i_outline_color, &p_style->font_style.i_outline_alpha );
735                     ParseColor( p_dec, psz_temp_color4, &p_style->font_style.i_shadow_color, &p_style->font_style.i_shadow_alpha );
736
737                     p_style->font_style.i_style_flags = 0;
738                     if( i_bold ) p_style->font_style.i_style_flags |= STYLE_BOLD;
739                     if( i_italic ) p_style->font_style.i_style_flags |= STYLE_ITALIC;
740                     if( i_underline ) p_style->font_style.i_style_flags |= STYLE_UNDERLINE;
741                     if( i_strikeout ) p_style->font_style.i_style_flags |= STYLE_STRIKEOUT;
742                     if( i_border == 1 ) p_style->font_style.i_style_flags |= (STYLE_ITALIC | STYLE_OUTLINE);
743                     else if( i_border == 3 )
744                     {
745                         p_style->font_style.i_style_flags |= STYLE_BACKGROUND;
746                         p_style->font_style.i_background_color = p_style->font_style.i_shadow_color;
747                         p_style->font_style.i_background_alpha = p_style->font_style.i_shadow_alpha;
748                     }
749                     p_style->font_style.i_shadow_width  = ( i_border == 1 ) ? i_shadow : 0;
750                     p_style->font_style.i_outline_width = ( i_border == 1 ) ? i_outline : 0;
751                     p_style->font_style.i_spacing = i_spacing;
752                     //p_style->font_style.f_angle = f_angle;
753
754                     p_style->i_align = 0;
755                     if( i_align == 0x1 || i_align == 0x4 || i_align == 0x1 ) p_style->i_align |= SUBPICTURE_ALIGN_LEFT;
756                     if( i_align == 0x3 || i_align == 0x6 || i_align == 0x9 ) p_style->i_align |= SUBPICTURE_ALIGN_RIGHT;
757                     if( i_align == 0x7 || i_align == 0x8 || i_align == 0x9 ) p_style->i_align |= SUBPICTURE_ALIGN_TOP;
758                     if( i_align == 0x1 || i_align == 0x2 || i_align == 0x3 ) p_style->i_align |= SUBPICTURE_ALIGN_BOTTOM;
759                     p_style->i_margin_h = ( p_style->i_align & SUBPICTURE_ALIGN_RIGHT ) ? i_margin_r : i_margin_l;
760                     p_style->i_margin_v = i_margin_v;
761
762                     /*TODO: Ignored: angle i_scale_x|y (fontscaling), i_encoding */
763                     TAB_APPEND( p_sys->i_ssa_styles, p_sys->pp_ssa_styles, p_style );
764                 }
765                 else msg_Dbg( p_dec, "SSA V4+ styleline parsing failed" );
766             }
767         }
768         psz_parser = GotoNextLine( psz_parser );
769     }
770
771 eof:
772     if( psz_header ) free( psz_header );
773     return;
774 }
775
776 static void StripTags( char *psz_text )
777 {
778     int i_left_moves = 0;
779     vlc_bool_t b_inside_tag = VLC_FALSE;
780     int i = 0;
781     int i_tag_start = -1;
782     while( psz_text[ i ] )
783     {
784         if( !b_inside_tag )
785         {
786             if( psz_text[ i ] == '<' )
787             {
788                 b_inside_tag = VLC_TRUE;
789                 i_tag_start = i;
790             }
791             psz_text[ i - i_left_moves ] = psz_text[ i ];
792         }
793         else
794         {
795             if( ( psz_text[ i ] == ' ' ) ||
796                 ( psz_text[ i ] == '\t' ) ||
797                 ( psz_text[ i ] == '\n' ) ||
798                 ( psz_text[ i ] == '\r' ) )
799             {
800                 b_inside_tag = VLC_FALSE;
801                 i_tag_start = -1;
802             }
803             else if( psz_text[ i ] == '>' )
804             {
805                 i_left_moves += i - i_tag_start + 1;
806                 i_tag_start = -1;
807                 b_inside_tag = VLC_FALSE;
808             }
809             else
810             {
811                 psz_text[ i - i_left_moves ] = psz_text[ i ];
812             }
813         }
814         i++;
815     }
816     psz_text[ i - i_left_moves ] = '\0';
817 }