]> git.sesse.net Git - vlc/blob - modules/codec/subtitles/subsdec.c
Remove inexistent encodings: C99, JAVA and HZ
[vlc] / modules / codec / subtitles / 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  *          Bernie Purcell <bitmap@videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include "subsdec.h"
35 #include <vlc_plugin.h>
36
37 /*****************************************************************************
38  * Local prototypes
39  *****************************************************************************/
40 static int  OpenDecoder   ( vlc_object_t * );
41 static void CloseDecoder  ( vlc_object_t * );
42
43 static subpicture_t   *DecodeBlock   ( decoder_t *, block_t ** );
44 static subpicture_t   *ParseText     ( decoder_t *, block_t * );
45 static char           *StripTags      ( char * );
46 static char           *CreateHtmlSubtitle( int *pi_align, char * );
47
48
49 /*****************************************************************************
50  * Module descriptor.
51  *****************************************************************************/
52 static const char *const ppsz_encodings[] = {
53     DEFAULT_NAME, "ASCII", "UTF-8", "",
54     "ISO-8859-1", "CP1252", "MacRoman", "MacIceland","ISO-8859-15", "",
55     "ISO-8859-2", "CP1250", "MacCentralEurope", "MacCroatian", "MacRomania", "",
56     "ISO-8859-5", "CP1251", "MacCyrillic", "MacUkraine", "KOI8-R", "KOI8-U", "KOI8-RU", "",
57     "ISO-8859-6", "CP1256", "MacArabic", "",
58     "ISO-8859-7", "CP1253", "MacGreek", "",
59     "ISO-8859-8", "CP1255", "MacHebrew", "",
60     "ISO-8859-9", "CP1254", "MacTurkish", "",
61     "ISO-8859-13", "CP1257", "",
62     "ISO-2022-JP", "ISO-2022-JP-1", "ISO-2022-JP-2", "EUC-JP", "SHIFT_JIS", "",
63     "ISO-2022-CN", "ISO-2022-CN-EXT", "EUC-CN", "EUC-TW", "BIG5", "BIG5-HKSCS", "",
64     "ISO-2022-KR", "EUC-KR", "",
65     "MacThai", "KOI8-T", "",
66     "ISO-8859-3", "ISO-8859-4", "ISO-8859-10", "ISO-8859-14", "ISO-8859-16", "",
67     "CP850", "CP862", "CP866", "CP874", "CP932", "CP949", "CP950", "CP1133", "CP1258", "",
68     "Macintosh", "",
69     "UTF-7", "UTF-16", "UTF-16BE", "UTF-16LE", "UTF-32", "UTF-32BE", "UTF-32LE",
70     "UCS-2", "UCS-2BE", "UCS-2LE", "UCS-4", "UCS-4BE", "UCS-4LE", "",
71     "GBK", "GB18030", "JOHAB", "ARMSCII-8",
72     "Georgian-Academy", "Georgian-PS", "TIS-620", "MuleLao-1", "VISCII", "TCVN",
73     "HPROMAN8", "NEXTSTEP" };
74 /*
75 SSA supports charset selection.
76 The following known charsets are used:
77
78 0 = Ansi - Western European
79 1 = default
80 2 = symbol
81 3 = invalid
82 77 = Mac
83 128 = Japanese (Shift JIS)
84 129 = Hangul
85 130 = Johab
86 134 = GB2312 Simplified Chinese
87 136 = Big5 Traditional Chinese
88 161 = Greek
89 162 = Turkish
90 163 = Vietnamese
91 177 = Hebrew
92 178 = Arabic
93 186 = Baltic
94 204 = Russian (Cyrillic)
95 222 = Thai
96 238 = Eastern European
97 254 = PC 437
98 */
99
100 static const int  pi_justification[] = { 0, 1, 2 };
101 static const char *const ppsz_justification_text[] = {
102     N_("Center"),N_("Left"),N_("Right")};
103
104 #define ENCODING_TEXT N_("Subtitles text encoding")
105 #define ENCODING_LONGTEXT N_("Set the encoding used in text subtitles")
106 #define ALIGN_TEXT N_("Subtitles justification")
107 #define ALIGN_LONGTEXT N_("Set the justification of subtitles")
108 #define AUTODETECT_UTF8_TEXT N_("UTF-8 subtitles autodetection")
109 #define AUTODETECT_UTF8_LONGTEXT N_("This enables automatic detection of " \
110             "UTF-8 encoding within subtitles files.")
111 #define FORMAT_TEXT N_("Formatted Subtitles")
112 #define FORMAT_LONGTEXT N_("Some subtitle formats allow for text formatting. " \
113  "VLC partly implements this, but you can choose to disable all formatting.")
114
115
116 vlc_module_begin ()
117     set_shortname( N_("Subtitles"))
118     set_description( N_("Text subtitles decoder") )
119     set_capability( "decoder", 50 )
120     set_callbacks( OpenDecoder, CloseDecoder )
121     set_category( CAT_INPUT )
122     set_subcategory( SUBCAT_INPUT_SCODEC )
123
124     add_integer( "subsdec-align", 0, NULL, ALIGN_TEXT, ALIGN_LONGTEXT,
125                  false )
126         change_integer_list( pi_justification, ppsz_justification_text, NULL )
127     add_string( "subsdec-encoding", DEFAULT_NAME, NULL,
128                 ENCODING_TEXT, ENCODING_LONGTEXT, false )
129         change_string_list( ppsz_encodings, 0, 0 )
130     add_bool( "subsdec-autodetect-utf8", true, NULL,
131               AUTODETECT_UTF8_TEXT, AUTODETECT_UTF8_LONGTEXT, false )
132     add_bool( "subsdec-formatted", true, NULL, FORMAT_TEXT, FORMAT_LONGTEXT,
133                  false )
134 vlc_module_end ()
135
136 /*****************************************************************************
137  * OpenDecoder: probe the decoder and return score
138  *****************************************************************************
139  * Tries to launch a decoder and return score so that the interface is able
140  * to chose.
141  *****************************************************************************/
142 static int OpenDecoder( vlc_object_t *p_this )
143 {
144     decoder_t     *p_dec = (decoder_t*)p_this;
145     decoder_sys_t *p_sys;
146     vlc_value_t    val;
147
148     switch( p_dec->fmt_in.i_codec )
149     {
150         case VLC_FOURCC('s','u','b','t'):
151         case VLC_FOURCC('s','s','a',' '):
152         case VLC_FOURCC('t','1','4','0'):
153             break;
154         default:
155             return VLC_EGENERIC;
156     }
157
158     p_dec->pf_decode_sub = DecodeBlock;
159     p_dec->fmt_out.i_cat = SPU_ES;
160     p_dec->fmt_out.i_codec = 0;
161
162     /* Allocate the memory needed to store the decoder's structure */
163     p_dec->p_sys = p_sys = calloc( 1, sizeof( *p_sys ) );
164     if( p_sys == NULL )
165         return VLC_ENOMEM;
166
167     /* init of p_sys */
168     p_sys->i_align = 0;
169     p_sys->iconv_handle = (vlc_iconv_t)-1;
170     p_sys->b_autodetect_utf8 = false;
171     p_sys->b_ass = false;
172     p_sys->i_original_height = -1;
173     p_sys->i_original_width = -1;
174     TAB_INIT( p_sys->i_ssa_styles, p_sys->pp_ssa_styles );
175     TAB_INIT( p_sys->i_images, p_sys->pp_images );
176
177     char *psz_charset = NULL;
178
179     /* First try demux-specified encoding */
180     if( p_dec->fmt_in.i_codec == VLC_FOURCC('t','1','4','0') )
181         psz_charset = strdup( "UTF-8" ); /* IUT T.140 is always using UTF-8 */
182     else
183     if( p_dec->fmt_in.subs.psz_encoding && *p_dec->fmt_in.subs.psz_encoding )
184     {
185         psz_charset = strdup (p_dec->fmt_in.subs.psz_encoding);
186         msg_Dbg (p_dec, "trying demuxer-specified character encoding: %s",
187                  p_dec->fmt_in.subs.psz_encoding ?: "not specified");
188     }
189
190     /* Second, try configured encoding */
191     if (psz_charset == NULL)
192     {
193         psz_charset = var_CreateGetNonEmptyString (p_dec, "subsdec-encoding");
194         if ((psz_charset != NULL) && !strcasecmp (psz_charset, DEFAULT_NAME))
195         {
196             free (psz_charset);
197             psz_charset = NULL;
198         }
199
200         msg_Dbg (p_dec, "trying configured character encoding: %s",
201                  psz_charset ?: "not specified");
202     }
203
204     /* Third, try "local" encoding with optional UTF-8 autodetection */
205     if (psz_charset == NULL)
206     {
207         psz_charset = strdup (GetFallbackEncoding ());
208         msg_Dbg (p_dec, "trying default character encoding: %s",
209                  psz_charset ?: "not specified");
210
211         if (var_CreateGetBool (p_dec, "subsdec-autodetect-utf8"))
212         {
213             msg_Dbg (p_dec, "using automatic UTF-8 detection");
214             p_sys->b_autodetect_utf8 = true;
215         }
216     }
217
218     /* Forth, don't do character decoding, i.e. assume UTF-8 */
219     if (psz_charset == NULL)
220     {
221         psz_charset = strdup ("UTF-8");
222         msg_Dbg (p_dec, "using UTF-8 character encoding" );
223     }
224
225     if ((psz_charset != NULL)
226      && strcasecmp (psz_charset, "UTF-8")
227      && strcasecmp (psz_charset, "utf8"))
228     {
229         p_sys->iconv_handle = vlc_iconv_open ("UTF-8", psz_charset);
230         if (p_sys->iconv_handle == (vlc_iconv_t)(-1))
231             msg_Err (p_dec, "cannot convert from %s: %m", psz_charset);
232     }
233     free (psz_charset);
234
235     var_Create( p_dec, "subsdec-align", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
236     var_Get( p_dec, "subsdec-align", &val );
237     p_sys->i_align = val.i_int;
238
239     if( p_dec->fmt_in.i_codec == VLC_FOURCC('s','s','a',' ')
240      && var_CreateGetBool( p_dec, "subsdec-formatted" ) )
241     {
242         if( p_dec->fmt_in.i_extra > 0 )
243             ParseSSAHeader( p_dec );
244     }
245
246     return VLC_SUCCESS;
247 }
248
249 /****************************************************************************
250  * DecodeBlock: the whole thing
251  ****************************************************************************
252  * This function must be fed with complete subtitles units.
253  ****************************************************************************/
254 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
255 {
256     subpicture_t *p_spu;
257     block_t *p_block;
258
259     if( !pp_block || *pp_block == NULL )
260         return NULL;
261
262     p_block = *pp_block;
263     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
264     {
265         block_Release( p_block );
266         return NULL;
267     }
268
269     p_spu = ParseText( p_dec, p_block );
270
271     block_Release( p_block );
272     *pp_block = NULL;
273
274     return p_spu;
275 }
276
277 /*****************************************************************************
278  * CloseDecoder: clean up the decoder
279  *****************************************************************************/
280 static void CloseDecoder( vlc_object_t *p_this )
281 {
282     decoder_t *p_dec = (decoder_t *)p_this;
283     decoder_sys_t *p_sys = p_dec->p_sys;
284
285     if( p_sys->iconv_handle != (vlc_iconv_t)-1 )
286         vlc_iconv_close( p_sys->iconv_handle );
287
288     if( p_sys->pp_ssa_styles )
289     {
290         int i;
291         for( i = 0; i < p_sys->i_ssa_styles; i++ )
292         {
293             if( !p_sys->pp_ssa_styles[i] )
294                 continue;
295
296             free( p_sys->pp_ssa_styles[i]->psz_stylename );
297             free( p_sys->pp_ssa_styles[i]->font_style.psz_fontname );
298             free( p_sys->pp_ssa_styles[i] );
299         }
300         TAB_CLEAN( p_sys->i_ssa_styles, p_sys->pp_ssa_styles );
301     }
302     if( p_sys->pp_images )
303     {
304         int i;
305         for( i = 0; i < p_sys->i_images; i++ )
306         {
307             if( !p_sys->pp_images[i] )
308                 continue;
309
310             if( p_sys->pp_images[i]->p_pic )
311                 picture_Release( p_sys->pp_images[i]->p_pic );
312             free( p_sys->pp_images[i]->psz_filename );
313
314             free( p_sys->pp_images[i] );
315         }
316         TAB_CLEAN( p_sys->i_images, p_sys->pp_images );
317     }
318
319     free( p_sys );
320 }
321
322 /*****************************************************************************
323  * ParseText: parse an text subtitle packet and send it to the video output
324  *****************************************************************************/
325 static subpicture_t *ParseText( decoder_t *p_dec, block_t *p_block )
326 {
327     decoder_sys_t *p_sys = p_dec->p_sys;
328     subpicture_t *p_spu = NULL;
329     char *psz_subtitle = NULL;
330     video_format_t fmt;
331
332     /* We cannot display a subpicture with no date */
333     if( p_block->i_pts == 0 )
334     {
335         msg_Warn( p_dec, "subtitle without a date" );
336         return NULL;
337     }
338
339     /* Check validity of packet data */
340     /* An "empty" line containing only \0 can be used to force
341        and ephemer picture from the screen */
342     if( p_block->i_buffer < 1 )
343     {
344         msg_Warn( p_dec, "no subtitle data" );
345         return NULL;
346     }
347
348     /* Should be resiliant against bad subtitles */
349     psz_subtitle = strndup( (const char *)p_block->p_buffer,
350                             p_block->i_buffer );
351     if( psz_subtitle == NULL )
352         return NULL;
353
354     if( p_sys->iconv_handle == (vlc_iconv_t)-1 )
355     {
356         if (EnsureUTF8( psz_subtitle ) == NULL)
357         {
358             msg_Err( p_dec, "failed to convert subtitle encoding.\n"
359                      "Try manually setting a character-encoding "
360                      "before you open the file." );
361         }
362     }
363     else
364     {
365
366         if( p_sys->b_autodetect_utf8 )
367         {
368             if( IsUTF8( psz_subtitle ) == NULL )
369             {
370                 msg_Dbg( p_dec, "invalid UTF-8 sequence: "
371                          "disabling UTF-8 subtitles autodetection" );
372                 p_sys->b_autodetect_utf8 = false;
373             }
374         }
375
376         if( !p_sys->b_autodetect_utf8 )
377         {
378             size_t inbytes_left = strlen( psz_subtitle );
379             size_t outbytes_left = 6 * inbytes_left;
380             char *psz_new_subtitle = malloc( outbytes_left + 1 );
381             char *psz_convert_buffer_out = psz_new_subtitle;
382             const char *psz_convert_buffer_in = psz_subtitle;
383
384             size_t ret = vlc_iconv( p_sys->iconv_handle,
385                                     &psz_convert_buffer_in, &inbytes_left,
386                                     &psz_convert_buffer_out, &outbytes_left );
387
388             *psz_convert_buffer_out++ = '\0';
389             free( psz_subtitle );
390
391             if( ( ret == (size_t)(-1) ) || inbytes_left )
392             {
393                 free( psz_new_subtitle );
394                 msg_Err( p_dec, "failed to convert subtitle encoding.\n"
395                         "Try manually setting a character-encoding "
396                                 "before you open the file." );
397                 return NULL;
398             }
399
400             psz_subtitle = realloc( psz_new_subtitle,
401                                     psz_convert_buffer_out - psz_new_subtitle );
402         }
403     }
404
405     /* Create the subpicture unit */
406     p_spu = decoder_NewSubpicture( p_dec );
407     if( !p_spu )
408     {
409         msg_Warn( p_dec, "can't get spu buffer" );
410         free( psz_subtitle );
411         return NULL;
412     }
413
414     /* Create a new subpicture region */
415     memset( &fmt, 0, sizeof(video_format_t) );
416     fmt.i_chroma = VLC_FOURCC('T','E','X','T');
417     fmt.i_aspect = 0;
418     fmt.i_width = fmt.i_height = 0;
419     fmt.i_x_offset = fmt.i_y_offset = 0;
420     p_spu->p_region = subpicture_region_New( &fmt );
421     if( !p_spu->p_region )
422     {
423         msg_Err( p_dec, "cannot allocate SPU region" );
424         free( psz_subtitle );
425         decoder_DeleteSubpicture( p_dec, p_spu );
426         return NULL;
427     }
428
429     /* Decode and format the subpicture unit */
430     if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','s','a',' ') )
431     {
432         /* Normal text subs, easy markup */
433         p_spu->p_region->i_align = SUBPICTURE_ALIGN_BOTTOM | p_sys->i_align;
434         p_spu->p_region->i_x = p_sys->i_align ? 20 : 0;
435         p_spu->p_region->i_y = 10;
436
437         /* Remove formatting from string */
438
439         p_spu->p_region->psz_text = StripTags( psz_subtitle );
440         if( var_CreateGetBool( p_dec, "subsdec-formatted" ) )
441         {
442             p_spu->p_region->psz_html = CreateHtmlSubtitle( &p_spu->p_region->i_align, psz_subtitle );
443         }
444
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 = false;
449     }
450     else
451     {
452         /* Decode SSA/USF strings */
453         ParseSSAString( p_dec, psz_subtitle, p_spu );
454
455         p_spu->i_start = p_block->i_pts;
456         p_spu->i_stop = p_block->i_pts + p_block->i_length;
457         p_spu->b_ephemer = (p_block->i_length == 0);
458         p_spu->b_absolute = false;
459         p_spu->i_original_picture_width = p_sys->i_original_width;
460         p_spu->i_original_picture_height = p_sys->i_original_height;
461     }
462     free( psz_subtitle );
463
464     return p_spu;
465 }
466
467 char* GotoNextLine( char *psz_text )
468 {
469     char *p_newline = psz_text;
470
471     while( p_newline[0] != '\0' )
472     {
473         if( p_newline[0] == '\n' || p_newline[0] == '\r' )
474         {
475             p_newline++;
476             while( p_newline[0] == '\n' || p_newline[0] == '\r' )
477                 p_newline++;
478             break;
479         }
480         else p_newline++;
481     }
482     return p_newline;
483 }
484
485 /* Function now handles tags with attribute values, and tries
486  * to deal with &' commands too. It no longer modifies the string
487  * in place, so that the original text can be reused
488  */
489 static char *StripTags( char *psz_subtitle )
490 {
491     char *psz_text_start;
492     char *psz_text;
493
494     psz_text = psz_text_start = malloc( strlen( psz_subtitle ) + 1 );
495     if( !psz_text_start )
496         return NULL;
497
498     while( *psz_subtitle )
499     {
500         if( *psz_subtitle == '<' )
501         {
502             if( strncasecmp( psz_subtitle, "<br/>", 5 ) == 0 )
503                 *psz_text++ = '\n';
504
505             psz_subtitle += strcspn( psz_subtitle, ">" );
506         }
507         else if( *psz_subtitle == '&' )
508         {
509             if( !strncasecmp( psz_subtitle, "&lt;", 4 ))
510             {
511                 *psz_text++ = '<';
512                 psz_subtitle += strcspn( psz_subtitle, ";" );
513             }
514             else if( !strncasecmp( psz_subtitle, "&gt;", 4 ))
515             {
516                 *psz_text++ = '>';
517                 psz_subtitle += strcspn( psz_subtitle, ";" );
518             }
519             else if( !strncasecmp( psz_subtitle, "&amp;", 5 ))
520             {
521                 *psz_text++ = '&';
522                 psz_subtitle += strcspn( psz_subtitle, ";" );
523             }
524             else if( !strncasecmp( psz_subtitle, "&quot;", 6 ))
525             {
526                 *psz_text++ = '\"';
527                 psz_subtitle += strcspn( psz_subtitle, ";" );
528             }
529             else
530             {
531                 /* Assume it is just a normal ampersand */
532                 *psz_text++ = '&';
533             }
534         }
535         else
536         {
537             *psz_text++ = *psz_subtitle;
538         }
539
540         psz_subtitle++;
541     }
542     *psz_text = '\0';
543     psz_text_start = realloc( psz_text_start, strlen( psz_text_start ) + 1 );
544
545     return psz_text_start;
546 }
547
548 /* Try to respect any style tags present in the subtitle string. The main
549  * problem here is a lack of adequate specs for the subtitle formats.
550  * SSA/ASS and USF are both detail spec'ed -- but they are handled elsewhere.
551  * SAMI has a detailed spec, but extensive rework is needed in the demux
552  * code to prevent all this style information being excised, as it presently
553  * does.
554  * That leaves the others - none of which were (I guess) originally intended
555  * to be carrying style information. Over time people have used them that way.
556  * In the absence of specifications from which to work, the tags supported
557  * have been restricted to the simple set permitted by the USF DTD, ie. :
558  *  Basic: <br>, <i>, <b>, <u>
559  *  Extended: <font>
560  *    Attributes: face
561  *                family
562  *                size
563  *                color
564  *                outline-color
565  *                shadow-color
566  *                outline-level
567  *                shadow-level
568  *                back-color
569  *                alpha
570  * There is also the further restriction that the subtitle be well-formed
571  * as an XML entity, ie. the HTML sentence:
572  *        <b><i>Bold and Italics</b></i>
573  * doesn't qualify because the tags aren't nested one inside the other.
574  * <text> tags are automatically added to the output to ensure
575  * well-formedness.
576  * If the text doesn't qualify for any reason, a NULL string is
577  * returned, and the rendering engine will fall back to the
578  * plain text version of the subtitle.
579  */
580 static void HtmlNPut( char **ppsz_html, const char *psz_text, int i_max )
581 {
582     const int i_len = strlen(psz_text);
583
584     strncpy( *ppsz_html, psz_text, i_max );
585     *ppsz_html += __MIN(i_max,i_len);
586 }
587
588 static void HtmlPut( char **ppsz_html, const char *psz_text )
589 {
590     strcpy( *ppsz_html, psz_text );
591     *ppsz_html += strlen(psz_text);
592 }
593 static void HtmlCopy( char **ppsz_html, char **ppsz_subtitle, const char *psz_text )
594 {
595     HtmlPut( ppsz_html, psz_text );
596     *ppsz_subtitle += strlen(psz_text);
597 }
598
599 static char *CreateHtmlSubtitle( int *pi_align, char *psz_subtitle )
600 {
601     /* */
602     char *psz_tag = malloc( ( strlen( psz_subtitle ) / 3 ) + 1 );
603     if( !psz_tag )
604         return NULL;
605     psz_tag[ 0 ] = '\0';
606
607     /* */
608     size_t i_buf_size = strlen( psz_subtitle ) + 100;
609     char   *psz_html_start = malloc( i_buf_size );
610     char   *psz_html = psz_html_start;
611     if( psz_html_start == NULL )
612     {
613         free( psz_tag );
614         return NULL;
615     }
616     psz_html[0] = '\0';
617
618     bool b_has_align = false;
619
620     HtmlPut( &psz_html, "<text>" );
621
622     /* */
623     while( *psz_subtitle )
624     {
625         if( *psz_subtitle == '\n' )
626         {
627             HtmlPut( &psz_html, "<br/>" );
628             psz_subtitle++;
629         }
630         else if( *psz_subtitle == '<' )
631         {
632             if( !strncasecmp( psz_subtitle, "<br/>", 5 ))
633             {
634                 HtmlCopy( &psz_html, &psz_subtitle, "<br/>" );
635             }
636             else if( !strncasecmp( psz_subtitle, "<b>", 3 ) )
637             {
638                 HtmlCopy( &psz_html, &psz_subtitle, "<b>" );
639                 strcat( psz_tag, "b" );
640             }
641             else if( !strncasecmp( psz_subtitle, "<i>", 3 ) )
642             {
643                 HtmlCopy( &psz_html, &psz_subtitle, "<i>" );
644                 strcat( psz_tag, "i" );
645             }
646             else if( !strncasecmp( psz_subtitle, "<u>", 3 ) )
647             {
648                 HtmlCopy( &psz_html, &psz_subtitle, "<u>" );
649                 strcat( psz_tag, "u" );
650             }
651             else if( !strncasecmp( psz_subtitle, "<font ", 6 ))
652             {
653                 const char *psz_attribs[] = { "face=", "family=", "size=",
654                         "color=", "outline-color=", "shadow-color=",
655                         "outline-level=", "shadow-level=", "back-color=",
656                         "alpha=", NULL };
657
658                 HtmlCopy( &psz_html, &psz_subtitle, "<font " );
659                 strcat( psz_tag, "f" );
660
661                 while( *psz_subtitle != '>' )
662                 {
663                     int  k;
664
665                     for( k=0; psz_attribs[ k ]; k++ )
666                     {
667                         int i_len = strlen( psz_attribs[ k ] );
668
669                         if( !strncasecmp( psz_subtitle, psz_attribs[k], i_len ) )
670                         {
671                             /* */
672                             HtmlPut( &psz_html, psz_attribs[k] );
673                             psz_subtitle += i_len;
674
675                             /* */
676                             if( *psz_subtitle == '"' )
677                             {
678                                 psz_subtitle++;
679                                 i_len = strcspn( psz_subtitle, "\"" );
680                             }
681                             else
682                             {
683                                 i_len = strcspn( psz_subtitle, " \t>" );
684                             }
685                             HtmlPut( &psz_html, "\"" );
686                             if( !strcmp( psz_attribs[ k ], "color=" ) && *psz_subtitle >= '0' && *psz_subtitle <= '9' )
687                                 HtmlPut( &psz_html, "#" );
688                             HtmlNPut( &psz_html, psz_subtitle, i_len );
689                             HtmlPut( &psz_html, "\"" );
690
691                             psz_subtitle += i_len;
692                             if( *psz_subtitle == '\"' )
693                                 psz_subtitle++;
694                             break;
695                         }
696                     }
697                     if( psz_attribs[ k ] == NULL )
698                     {
699                         /* Jump over unrecognised tag */
700                         int i_len = strcspn( psz_subtitle, "\"" ) + 1;
701
702                         i_len += strcspn( psz_subtitle + i_len, "\"" ) + 1;
703                         psz_subtitle += i_len;
704                     }
705                     while (*psz_subtitle == ' ')
706                         *psz_html++ = *psz_subtitle++;
707                 }
708                 *psz_html++ = *psz_subtitle++;
709             }
710             else if( !strncmp( psz_subtitle, "</", 2 ))
711             {
712                 bool   b_match     = false;
713                 bool   b_ignore    = false;
714                 int    i_len       = strlen( psz_tag ) - 1;
715                 char  *psz_lastTag = NULL;
716
717                 if( i_len >= 0 )
718                 {
719                     psz_lastTag = psz_tag + i_len;
720                     i_len = 0;
721
722                     switch( *psz_lastTag )
723                     {
724                     case 'b':
725                         b_match = !strncasecmp( psz_subtitle, "</b>", 4 );
726                         i_len   = 4;
727                         break;
728                     case 'i':
729                         b_match = !strncasecmp( psz_subtitle, "</i>", 4 );
730                         i_len   = 4;
731                         break;
732                     case 'u':
733                         b_match = !strncasecmp( psz_subtitle, "</u>", 4 );
734                         i_len   = 4;
735                         break;
736                     case 'f':
737                         b_match = !strncasecmp( psz_subtitle, "</font>", 7 );
738                         i_len   = 7;
739                         break;
740                     case 'I':
741                         i_len = strcspn( psz_subtitle, ">" );
742                         b_match = psz_subtitle[i_len] == '>';
743                         b_ignore = true;
744                         if( b_match )
745                             i_len++;
746                         break;
747                     }
748                 }
749                 if( !b_match )
750                 {
751                     /* Not well formed -- kill everything */
752                     free( psz_html_start );
753                     psz_html_start = NULL;
754                     break;
755                 }
756                 *psz_lastTag = '\0';
757                 if( !b_ignore )
758                     HtmlNPut( &psz_html, psz_subtitle, i_len );
759
760                 psz_subtitle += i_len;
761             }
762             else if( ( psz_subtitle[1] < 'a' || psz_subtitle[1] > 'z' ) &&
763                      ( psz_subtitle[1] < 'A' || psz_subtitle[1] > 'Z' ) )
764             {
765                 /* We have a single < */
766                 HtmlPut( &psz_html, "&lt;" );
767                 psz_subtitle++;
768             }
769             else
770             {
771                 /* We have an unknown tag or a single < */
772
773                 /* Search for the next tag or end of tag or end of string */
774                 char *psz_stop = psz_subtitle + 1 + strcspn( &psz_subtitle[1], "<>" );
775                 char *psz_closing = strstr( psz_subtitle, "/>" );
776
777                 if( psz_closing && psz_closing < psz_stop )
778                 {
779                     /* We have a self closed tag, remove it */
780                     psz_subtitle = &psz_closing[2];
781                 }
782                 else if( *psz_stop == '>' )
783                 {
784                     char psz_match[256];
785
786                     snprintf( psz_match, sizeof(psz_match), "</%s", &psz_subtitle[1] );
787                     psz_match[strcspn( psz_match, " \t>" )] = '\0';
788
789                     if( strstr( psz_subtitle, psz_match ) )
790                     {
791                         /* We have the closing tag, ignore it TODO */
792                         psz_subtitle = &psz_stop[1];
793                         strcat( psz_tag, "I" );
794                     }
795                     else
796                     {
797                         int i_len = psz_stop + 1 - psz_subtitle;
798
799                         /* Copy the whole data */
800                         for( ; i_len > 0; i_len--, psz_subtitle++ )
801                         {
802                             if( *psz_subtitle == '<' )
803                                 HtmlPut( &psz_html, "&lt;" );
804                             else if( *psz_subtitle == '>' )
805                                 HtmlPut( &psz_html, "&gt;" );
806                             else
807                                 *psz_html++ = *psz_subtitle;
808                         }
809                     }
810                 }
811                 else
812                 {
813                     /* We have a single < */
814                     HtmlPut( &psz_html, "&lt;" );
815                     psz_subtitle++;
816                 }
817             }
818         }
819         else if( *psz_subtitle == '&' )
820         {
821             if( !strncasecmp( psz_subtitle, "&lt;", 4 ))
822             {
823                 HtmlCopy( &psz_html, &psz_subtitle, "&lt;" );
824             }
825             else if( !strncasecmp( psz_subtitle, "&gt;", 4 ))
826             {
827                 HtmlCopy( &psz_html, &psz_subtitle, "&gt;" );
828             }
829             else if( !strncasecmp( psz_subtitle, "&amp;", 5 ))
830             {
831                 HtmlCopy( &psz_html, &psz_subtitle, "&amp;" );
832             }
833             else
834             {
835                 HtmlPut( &psz_html, "&amp;" );
836                 psz_subtitle++;
837             }
838         }
839         else if( *psz_subtitle == '>' )
840         {
841             HtmlPut( &psz_html, "&gt;" );
842             psz_subtitle++;
843         }
844         else if( psz_subtitle[0] == '{' && psz_subtitle[1] == '\\' &&
845                  strchr( psz_subtitle, '}' ) )
846         {
847             /* Check for forced alignment */
848             if( !b_has_align &&
849                 !strncmp( psz_subtitle, "{\\an", 4 ) && psz_subtitle[4] >= '1' && psz_subtitle[4] <= '9' && psz_subtitle[5] == '}' )
850             {
851                 static const int pi_vertical[3] = { SUBPICTURE_ALIGN_BOTTOM, 0, SUBPICTURE_ALIGN_TOP };
852                 static const int pi_horizontal[3] = { SUBPICTURE_ALIGN_LEFT, 0, SUBPICTURE_ALIGN_RIGHT };
853                 const int i_id = psz_subtitle[4] - '1';
854
855                 b_has_align = true;
856                 *pi_align = pi_vertical[i_id/3] | pi_horizontal[i_id%3];
857             }
858             /* TODO fr -> rotation */
859
860             /* Hide {\stupidity} */
861             psz_subtitle = strchr( psz_subtitle, '}' ) + 1;
862         }
863         else
864         {
865             *psz_html = *psz_subtitle;
866             if( psz_html > psz_html_start )
867             {
868                 /* Check for double whitespace */
869                 if( ( *psz_html == ' '  || *psz_html == '\t' ) &&
870                     ( *(psz_html-1) == ' ' || *(psz_html-1) == '\t' ) )
871                 {
872                     HtmlPut( &psz_html, NO_BREAKING_SPACE );
873                     psz_html--;
874                 }
875             }
876             psz_html++;
877             psz_subtitle++;
878         }
879
880         if( ( size_t )( psz_html - psz_html_start ) > i_buf_size - 50 )
881         {
882             const int i_len = psz_html - psz_html_start;
883
884             i_buf_size += 200;
885             char *psz_new = realloc( psz_html_start, i_buf_size );
886             if( !psz_new )
887                 break;
888             psz_html_start = psz_new;
889             psz_html = &psz_new[i_len];
890         }
891     }
892     if( psz_html_start )
893     {
894         static const char *psz_text_close = "</text>";
895         static const char *psz_tag_long = "/font>";
896
897         /* Realloc for closing tags and shrink memory */
898         const size_t i_length = (size_t)( psz_html - psz_html_start );
899
900         const size_t i_size = i_length + strlen(psz_tag_long) * strlen(psz_tag) + strlen(psz_text_close) + 1;
901         char *psz_new = realloc( psz_html_start, i_size );
902         if( psz_new )
903         {
904             psz_html_start = psz_new;
905             psz_html = &psz_new[i_length];
906
907             /* Close not well formed subtitle */
908             while( *psz_tag )
909             {
910                 /* */
911                 char *psz_last = &psz_tag[strlen(psz_tag)-1];
912                 switch( *psz_last )
913                 {
914                 case 'b':
915                     HtmlPut( &psz_html, "</b>" );
916                     break;
917                 case 'i':
918                     HtmlPut( &psz_html, "</i>" );
919                     break;
920                 case 'u':
921                     HtmlPut( &psz_html, "</u>" );
922                     break;
923                 case 'f':
924                     HtmlPut( &psz_html, "/font>" );
925                     break;
926                 case 'I':
927                     break;
928                 }
929
930                 *psz_last = '\0';
931             }
932             HtmlPut( &psz_html, psz_text_close );
933         }
934     }
935     free( psz_tag );
936
937     return psz_html_start;
938 }
939