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