]> git.sesse.net Git - vlc/blob - modules/codec/subsdec.c
20e677d71de2c03540065b6bd30a1c5c932b8ae0
[vlc] / modules / codec / subsdec.c
1 /*****************************************************************************
2  * subsdec.c : text subtitles decoder
3  *****************************************************************************
4  * Copyright (C) 2000-2006 VLC authors and VideoLAN
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 it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * 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 <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_codec.h>
37 #include <vlc_charset.h>
38
39 #include "substext.h"
40
41 /*****************************************************************************
42  * Module descriptor.
43  *****************************************************************************/
44 static const char *const ppsz_encodings[] = {
45     "",
46     "system",
47     "UTF-8",
48     "UTF-16",
49     "UTF-16BE",
50     "UTF-16LE",
51     "GB18030",
52     "ISO-8859-15",
53     "Windows-1252",
54     "IBM850",
55     "ISO-8859-2",
56     "Windows-1250",
57     "ISO-8859-3",
58     "ISO-8859-10",
59     "Windows-1251",
60     "KOI8-R",
61     "KOI8-U",
62     "ISO-8859-6",
63     "Windows-1256",
64     "ISO-8859-7",
65     "Windows-1253",
66     "ISO-8859-8",
67     "Windows-1255",
68     "ISO-8859-9",
69     "Windows-1254",
70     "ISO-8859-11",
71     "Windows-874",
72     "ISO-8859-13",
73     "Windows-1257",
74     "ISO-8859-14",
75     "ISO-8859-16",
76     "ISO-2022-CN-EXT",
77     "EUC-CN",
78     "ISO-2022-JP-2",
79     "EUC-JP",
80     "Shift_JIS",
81     "CP949",
82     "ISO-2022-KR",
83     "Big5",
84     "ISO-2022-TW",
85     "Big5-HKSCS",
86     "VISCII",
87     "Windows-1258",
88 };
89
90 static const char *const ppsz_encoding_names[] = {
91     /* xgettext:
92       The character encoding name in parenthesis corresponds to that used for
93       the GetACP translation. "Windows-1252" applies to Western European
94       languages using the Latin alphabet. */
95     N_("Default (Windows-1252)"),
96     N_("System codeset"),
97     N_("Universal (UTF-8)"),
98     N_("Universal (UTF-16)"),
99     N_("Universal (big endian UTF-16)"),
100     N_("Universal (little endian UTF-16)"),
101     N_("Universal, Chinese (GB18030)"),
102
103   /* ISO 8859 and the likes */
104     /* 1 */
105     N_("Western European (Latin-9)"), /* mostly superset of Latin-1 */
106     N_("Western European (Windows-1252)"),
107     N_("Western European (IBM 00850)"),
108     /* 2 */
109     N_("Eastern European (Latin-2)"),
110     N_("Eastern European (Windows-1250)"),
111     /* 3 */
112     N_("Esperanto (Latin-3)"),
113     /* 4 */
114     N_("Nordic (Latin-6)"), /* Latin 6 supersedes Latin 4 */
115     /* 5 */
116     N_("Cyrillic (Windows-1251)"), /* ISO 8859-5 is not practically used */
117     N_("Russian (KOI8-R)"),
118     N_("Ukrainian (KOI8-U)"),
119     /* 6 */
120     N_("Arabic (ISO 8859-6)"),
121     N_("Arabic (Windows-1256)"),
122     /* 7 */
123     N_("Greek (ISO 8859-7)"),
124     N_("Greek (Windows-1253)"),
125     /* 8 */
126     N_("Hebrew (ISO 8859-8)"),
127     N_("Hebrew (Windows-1255)"),
128     /* 9 */
129     N_("Turkish (ISO 8859-9)"),
130     N_("Turkish (Windows-1254)"),
131     /* 10 -> 4 */
132     /* 11 */
133     N_("Thai (TIS 620-2533/ISO 8859-11)"),
134     N_("Thai (Windows-874)"),
135     /* 13 */
136     N_("Baltic (Latin-7)"),
137     N_("Baltic (Windows-1257)"),
138     /* 12 -> /dev/null */
139     /* 14 */
140     N_("Celtic (Latin-8)"),
141     /* 15 -> 1 */
142     /* 16 */
143     N_("South-Eastern European (Latin-10)"),
144   /* CJK families */
145     N_("Simplified Chinese (ISO-2022-CN-EXT)"),
146     N_("Simplified Chinese Unix (EUC-CN)"),
147     N_("Japanese (7-bits JIS/ISO-2022-JP-2)"),
148     N_("Japanese Unix (EUC-JP)"),
149     N_("Japanese (Shift JIS)"),
150     N_("Korean (EUC-KR/CP949)"),
151     N_("Korean (ISO-2022-KR)"),
152     N_("Traditional Chinese (Big5)"),
153     N_("Traditional Chinese Unix (EUC-TW)"),
154     N_("Hong-Kong Supplementary (HKSCS)"),
155   /* Other */
156     N_("Vietnamese (VISCII)"),
157     N_("Vietnamese (Windows-1258)"),
158 };
159
160 static const int  pi_justification[] = { 0, 1, 2 };
161 static const char *const ppsz_justification_text[] = {
162     N_("Center"),N_("Left"),N_("Right")};
163
164 #define ENCODING_TEXT N_("Subtitles text encoding")
165 #define ENCODING_LONGTEXT N_("Set the encoding used in text subtitles")
166 #define ALIGN_TEXT N_("Subtitles justification")
167 #define ALIGN_LONGTEXT N_("Set the justification of subtitles")
168 #define AUTODETECT_UTF8_TEXT N_("UTF-8 subtitles autodetection")
169 #define AUTODETECT_UTF8_LONGTEXT N_("This enables automatic detection of " \
170             "UTF-8 encoding within subtitles files.")
171 #define FORMAT_TEXT N_("Formatted Subtitles")
172 #define FORMAT_LONGTEXT N_("Some subtitle formats allow for text formatting. " \
173  "VLC partly implements this, but you can choose to disable all formatting.")
174
175 static int  OpenDecoder   ( vlc_object_t * );
176 static void CloseDecoder  ( vlc_object_t * );
177
178 vlc_module_begin ()
179     set_shortname( N_("Subtitles"))
180     set_description( N_("Text subtitles decoder") )
181     set_capability( "decoder", 50 )
182     set_callbacks( OpenDecoder, CloseDecoder )
183     set_category( CAT_INPUT )
184     set_subcategory( SUBCAT_INPUT_SCODEC )
185
186     add_integer( "subsdec-align", 0, ALIGN_TEXT, ALIGN_LONGTEXT,
187                  false )
188         change_integer_list( pi_justification, ppsz_justification_text )
189     add_string( "subsdec-encoding", "",
190                 ENCODING_TEXT, ENCODING_LONGTEXT, false )
191         change_string_list( ppsz_encodings, ppsz_encoding_names )
192     add_bool( "subsdec-autodetect-utf8", true,
193               AUTODETECT_UTF8_TEXT, AUTODETECT_UTF8_LONGTEXT, false )
194     add_bool( "subsdec-formatted", true, FORMAT_TEXT, FORMAT_LONGTEXT,
195                  false )
196 vlc_module_end ()
197
198 /*****************************************************************************
199  * Local prototypes
200  *****************************************************************************/
201 #define NO_BREAKING_SPACE  "&#160;"
202
203 struct decoder_sys_t
204 {
205     int                 i_align;          /* Subtitles alignment on the vout */
206
207     vlc_iconv_t         iconv_handle;            /* handle to iconv instance */
208     bool                b_autodetect_utf8;
209 };
210
211
212 static subpicture_t   *DecodeBlock   ( decoder_t *, block_t ** );
213 static subpicture_t   *ParseText     ( decoder_t *, block_t * );
214 static char           *StripTags      ( char * );
215 static char           *CreateHtmlSubtitle( int *pi_align, char * );
216
217 /*****************************************************************************
218  * OpenDecoder: probe the decoder and return score
219  *****************************************************************************
220  * Tries to launch a decoder and return score so that the interface is able
221  * to chose.
222  *****************************************************************************/
223 static int OpenDecoder( vlc_object_t *p_this )
224 {
225     decoder_t     *p_dec = (decoder_t*)p_this;
226     decoder_sys_t *p_sys;
227
228     switch( p_dec->fmt_in.i_codec )
229     {
230         case VLC_CODEC_SUBT:
231         case VLC_CODEC_ITU_T140:
232             break;
233         default:
234             return VLC_EGENERIC;
235     }
236
237     p_dec->pf_decode_sub = DecodeBlock;
238     p_dec->fmt_out.i_cat = SPU_ES;
239     p_dec->fmt_out.i_codec = 0;
240
241     /* Allocate the memory needed to store the decoder's structure */
242     p_dec->p_sys = p_sys = calloc( 1, sizeof( *p_sys ) );
243     if( p_sys == NULL )
244         return VLC_ENOMEM;
245
246     /* init of p_sys */
247     p_sys->i_align = 0;
248     p_sys->iconv_handle = (vlc_iconv_t)-1;
249     p_sys->b_autodetect_utf8 = false;
250
251     const char *encoding;
252     char *var = NULL;
253
254     /* First try demux-specified encoding */
255     if( p_dec->fmt_in.i_codec == VLC_CODEC_ITU_T140 )
256         encoding = "UTF-8"; /* IUT T.140 is always using UTF-8 */
257     else
258     if( p_dec->fmt_in.subs.psz_encoding && *p_dec->fmt_in.subs.psz_encoding )
259     {
260         encoding = p_dec->fmt_in.subs.psz_encoding;
261         msg_Dbg (p_dec, "trying demuxer-specified character encoding: %s",
262                  encoding);
263     }
264     else
265     {
266         /* Second, try configured encoding */
267         if ((var = var_InheritString (p_dec, "subsdec-encoding")) != NULL)
268         {
269             msg_Dbg (p_dec, "trying configured character encoding: %s", var);
270             if (!strcmp (var, "system"))
271             {
272                 free (var);
273                 var = NULL;
274                 encoding = "";
275                 /* ^ iconv() treats "" as nl_langinfo(CODESET) */
276             }
277             else
278                 encoding = var;
279         }
280         else
281         /* Third, try "local" encoding */
282         {
283         /* xgettext:
284            The Windows ANSI code page most commonly used for this language.
285            VLC uses this as a guess of the subtitle files character set
286            (if UTF-8 and UTF-16 autodetection fails).
287            Western European languages normally use "CP1252", which is a
288            Microsoft-variant of ISO 8859-1. That suits the Latin alphabet.
289            Other scripts use other code pages.
290
291            This MUST be a valid iconv character set. If unsure, please refer
292            the VideoLAN translators mailing list. */
293             encoding = vlc_pgettext("GetACP", "CP1252");
294             msg_Dbg (p_dec, "trying default character encoding: %s", encoding);
295         }
296
297         /* Check UTF-8 autodetection */
298         if (var_InheritBool (p_dec, "subsdec-autodetect-utf8"))
299         {
300             msg_Dbg (p_dec, "using automatic UTF-8 detection");
301             p_sys->b_autodetect_utf8 = true;
302         }
303     }
304
305     if (strcasecmp (encoding, "UTF-8") && strcasecmp (encoding, "utf8"))
306     {
307         p_sys->iconv_handle = vlc_iconv_open ("UTF-8", encoding);
308         if (p_sys->iconv_handle == (vlc_iconv_t)(-1))
309             msg_Err (p_dec, "cannot convert from %s: %m", encoding);
310     }
311     free (var);
312
313     p_sys->i_align = var_InheritInteger( p_dec, "subsdec-align" );
314
315     return VLC_SUCCESS;
316 }
317
318 /****************************************************************************
319  * DecodeBlock: the whole thing
320  ****************************************************************************
321  * This function must be fed with complete subtitles units.
322  ****************************************************************************/
323 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
324 {
325     subpicture_t *p_spu;
326     block_t *p_block;
327
328     if( !pp_block || *pp_block == NULL )
329         return NULL;
330
331     p_block = *pp_block;
332     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
333     {
334         block_Release( p_block );
335         return NULL;
336     }
337
338     p_spu = ParseText( p_dec, p_block );
339
340     block_Release( p_block );
341     *pp_block = NULL;
342
343     return p_spu;
344 }
345
346 /*****************************************************************************
347  * CloseDecoder: clean up the decoder
348  *****************************************************************************/
349 static void CloseDecoder( vlc_object_t *p_this )
350 {
351     decoder_t *p_dec = (decoder_t *)p_this;
352     decoder_sys_t *p_sys = p_dec->p_sys;
353
354     if( p_sys->iconv_handle != (vlc_iconv_t)-1 )
355         vlc_iconv_close( p_sys->iconv_handle );
356
357     free( p_sys );
358 }
359
360 /*****************************************************************************
361  * ParseText: parse an text subtitle packet and send it to the video output
362  *****************************************************************************/
363 static subpicture_t *ParseText( decoder_t *p_dec, block_t *p_block )
364 {
365     decoder_sys_t *p_sys = p_dec->p_sys;
366     subpicture_t *p_spu = NULL;
367     char *psz_subtitle = NULL;
368
369     /* We cannot display a subpicture with no date */
370     if( p_block->i_pts <= VLC_TS_INVALID )
371     {
372         msg_Warn( p_dec, "subtitle without a date" );
373         return NULL;
374     }
375
376     /* Check validity of packet data */
377     /* An "empty" line containing only \0 can be used to force
378        and ephemer picture from the screen */
379     if( p_block->i_buffer < 1 )
380     {
381         msg_Warn( p_dec, "no subtitle data" );
382         return NULL;
383     }
384
385     /* Should be resiliant against bad subtitles */
386     psz_subtitle = malloc( p_block->i_buffer + 1 );
387     if( psz_subtitle == NULL )
388         return NULL;
389     memcpy( psz_subtitle, p_block->p_buffer, p_block->i_buffer );
390     psz_subtitle[p_block->i_buffer] = '\0';
391
392     if( p_sys->iconv_handle == (vlc_iconv_t)-1 )
393     {
394         if (EnsureUTF8( psz_subtitle ) == NULL)
395         {
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         }
400     }
401     else
402     {
403
404         if( p_sys->b_autodetect_utf8 )
405         {
406             if( IsUTF8( psz_subtitle ) == NULL )
407             {
408                 msg_Dbg( p_dec, "invalid UTF-8 sequence: "
409                          "disabling UTF-8 subtitles autodetection" );
410                 p_sys->b_autodetect_utf8 = false;
411             }
412         }
413
414         if( !p_sys->b_autodetect_utf8 )
415         {
416             size_t inbytes_left = strlen( psz_subtitle );
417             size_t outbytes_left = 6 * inbytes_left;
418             char *psz_new_subtitle = xmalloc( outbytes_left + 1 );
419             char *psz_convert_buffer_out = psz_new_subtitle;
420             const char *psz_convert_buffer_in = psz_subtitle;
421
422             size_t ret = vlc_iconv( p_sys->iconv_handle,
423                                     &psz_convert_buffer_in, &inbytes_left,
424                                     &psz_convert_buffer_out, &outbytes_left );
425
426             *psz_convert_buffer_out++ = '\0';
427             free( psz_subtitle );
428
429             if( ( ret == (size_t)(-1) ) || inbytes_left )
430             {
431                 free( psz_new_subtitle );
432                 msg_Err( p_dec, "failed to convert subtitle encoding.\n"
433                         "Try manually setting a character-encoding "
434                                 "before you open the file." );
435                 return NULL;
436             }
437
438             psz_subtitle = realloc( psz_new_subtitle,
439                                     psz_convert_buffer_out - psz_new_subtitle );
440             if( !psz_subtitle )
441                 psz_subtitle = psz_new_subtitle;
442         }
443     }
444
445     /* Create the subpicture unit */
446     p_spu = decoder_NewSubpictureText( p_dec );
447     if( !p_spu )
448     {
449         free( psz_subtitle );
450         return NULL;
451     }
452     p_spu->i_start    = p_block->i_pts;
453     p_spu->i_stop     = p_block->i_pts + p_block->i_length;
454     p_spu->b_ephemer  = (p_block->i_length == 0);
455     p_spu->b_absolute = false;
456
457     subpicture_updater_sys_t *p_spu_sys = p_spu->updater.p_sys;
458
459     p_spu_sys->align = SUBPICTURE_ALIGN_BOTTOM | p_sys->i_align;
460     p_spu_sys->text  = StripTags( psz_subtitle );
461     if( var_InheritBool( p_dec, "subsdec-formatted" ) )
462         p_spu_sys->html = CreateHtmlSubtitle( &p_spu_sys->align, psz_subtitle );
463
464     free( psz_subtitle );
465
466     return p_spu;
467 }
468
469 /* Function now handles tags with attribute values, and tries
470  * to deal with &' commands too. It no longer modifies the string
471  * in place, so that the original text can be reused
472  */
473 static char *StripTags( char *psz_subtitle )
474 {
475     char *psz_text_start;
476     char *psz_text;
477
478     psz_text = psz_text_start = malloc( strlen( psz_subtitle ) + 1 );
479     if( !psz_text_start )
480         return NULL;
481
482     while( *psz_subtitle )
483     {
484         if( *psz_subtitle == '<' )
485         {
486             if( strncasecmp( psz_subtitle, "<br/>", 5 ) == 0 )
487                 *psz_text++ = '\n';
488
489             psz_subtitle += strcspn( psz_subtitle, ">" );
490         }
491         else if( *psz_subtitle == '&' )
492         {
493             if( !strncasecmp( psz_subtitle, "&lt;", 4 ))
494             {
495                 *psz_text++ = '<';
496                 psz_subtitle += strcspn( psz_subtitle, ";" );
497             }
498             else if( !strncasecmp( psz_subtitle, "&gt;", 4 ))
499             {
500                 *psz_text++ = '>';
501                 psz_subtitle += strcspn( psz_subtitle, ";" );
502             }
503             else if( !strncasecmp( psz_subtitle, "&amp;", 5 ))
504             {
505                 *psz_text++ = '&';
506                 psz_subtitle += strcspn( psz_subtitle, ";" );
507             }
508             else if( !strncasecmp( psz_subtitle, "&quot;", 6 ))
509             {
510                 *psz_text++ = '\"';
511                 psz_subtitle += strcspn( psz_subtitle, ";" );
512             }
513             else
514             {
515                 /* Assume it is just a normal ampersand */
516                 *psz_text++ = '&';
517             }
518         }
519         else
520         {
521             *psz_text++ = *psz_subtitle;
522         }
523
524         /* Security fix: Account for the case where input ends early */
525         if( *psz_subtitle == '\0' ) break;
526
527         psz_subtitle++;
528     }
529     *psz_text = '\0';
530     char *psz = realloc( psz_text_start, strlen( psz_text_start ) + 1 );
531     if( psz ) psz_text_start = psz;
532
533     return psz_text_start;
534 }
535
536 /* Try to respect any style tags present in the subtitle string. The main
537  * problem here is a lack of adequate specs for the subtitle formats.
538  * SSA/ASS and USF are both detail spec'ed -- but they are handled elsewhere.
539  * SAMI has a detailed spec, but extensive rework is needed in the demux
540  * code to prevent all this style information being excised, as it presently
541  * does.
542  * That leaves the others - none of which were (I guess) originally intended
543  * to be carrying style information. Over time people have used them that way.
544  * In the absence of specifications from which to work, the tags supported
545  * have been restricted to the simple set permitted by the USF DTD, ie. :
546  *  Basic: <br>, <i>, <b>, <u>, <s>
547  *  Extended: <font>
548  *    Attributes: face
549  *                family
550  *                size
551  *                color
552  *                outline-color
553  *                shadow-color
554  *                outline-level
555  *                shadow-level
556  *                back-color
557  *                alpha
558  * There is also the further restriction that the subtitle be well-formed
559  * as an XML entity, ie. the HTML sentence:
560  *        <b><i>Bold and Italics</b></i>
561  * doesn't qualify because the tags aren't nested one inside the other.
562  * <text> tags are automatically added to the output to ensure
563  * well-formedness.
564  * If the text doesn't qualify for any reason, a NULL string is
565  * returned, and the rendering engine will fall back to the
566  * plain text version of the subtitle.
567  */
568 static void HtmlNPut( char **ppsz_html, const char *psz_text, int i_max )
569 {
570     const int i_len = strlen(psz_text);
571
572     strncpy( *ppsz_html, psz_text, i_max );
573     *ppsz_html += __MIN(i_max,i_len);
574 }
575
576 static void HtmlPut( char **ppsz_html, const char *psz_text )
577 {
578     strcpy( *ppsz_html, psz_text );
579     *ppsz_html += strlen(psz_text);
580 }
581 static void HtmlCopy( char **ppsz_html, char **ppsz_subtitle, const char *psz_text )
582 {
583     HtmlPut( ppsz_html, psz_text );
584     *ppsz_subtitle += strlen(psz_text);
585 }
586
587 static char *CreateHtmlSubtitle( int *pi_align, char *psz_subtitle )
588 {
589     /* */
590     char *psz_tag = malloc( ( strlen( psz_subtitle ) / 3 ) + 1 );
591     if( !psz_tag )
592         return NULL;
593     psz_tag[ 0 ] = '\0';
594
595     /* */
596     //Oo + 100 ???
597     size_t i_buf_size = strlen( psz_subtitle ) + 100;
598     char   *psz_html_start = malloc( i_buf_size );
599     char   *psz_html = psz_html_start;
600     if( psz_html_start == NULL )
601     {
602         free( psz_tag );
603         return NULL;
604     }
605     psz_html[0] = '\0';
606
607     bool b_has_align = false;
608
609     HtmlPut( &psz_html, "<text>" );
610
611     /* */
612     while( *psz_subtitle )
613     {
614         if( *psz_subtitle == '\n' )
615         {
616             HtmlPut( &psz_html, "<br/>" );
617             psz_subtitle++;
618         }
619         else if( *psz_subtitle == '<' )
620         {
621             if( !strncasecmp( psz_subtitle, "<br/>", 5 ))
622             {
623                 HtmlCopy( &psz_html, &psz_subtitle, "<br/>" );
624             }
625             else if( !strncasecmp( psz_subtitle, "<b>", 3 ) )
626             {
627                 HtmlCopy( &psz_html, &psz_subtitle, "<b>" );
628                 strcat( psz_tag, "b" );
629             }
630             else if( !strncasecmp( psz_subtitle, "<i>", 3 ) )
631             {
632                 HtmlCopy( &psz_html, &psz_subtitle, "<i>" );
633                 strcat( psz_tag, "i" );
634             }
635             else if( !strncasecmp( psz_subtitle, "<u>", 3 ) )
636             {
637                 HtmlCopy( &psz_html, &psz_subtitle, "<u>" );
638                 strcat( psz_tag, "u" );
639             }
640             else if( !strncasecmp( psz_subtitle, "<s>", 3 ) )
641             {
642                 HtmlCopy( &psz_html, &psz_subtitle, "<s>" );
643                 strcat( psz_tag, "s" );
644             }
645             else if( !strncasecmp( psz_subtitle, "<font ", 6 ))
646             {
647                 const char *psz_attribs[] = { "face=", "family=", "size=",
648                         "color=", "outline-color=", "shadow-color=",
649                         "outline-level=", "shadow-level=", "back-color=",
650                         "alpha=", NULL };
651
652                 HtmlCopy( &psz_html, &psz_subtitle, "<font " );
653                 strcat( psz_tag, "f" );
654
655                 /* <font       color= */
656                 while (*psz_subtitle == ' ')
657                     psz_subtitle++;
658
659                 while( *psz_subtitle != '>' )
660                 {
661                     int  k;
662
663                     for( k=0; psz_attribs[ k ]; k++ )
664                     {
665                         int i_len = strlen( psz_attribs[ k ] );
666
667                         if( !strncasecmp( psz_subtitle, psz_attribs[k], i_len ) )
668                         {
669                             /* */
670                             HtmlPut( &psz_html, psz_attribs[k] );
671                             psz_subtitle += i_len;
672
673                             /* <font       color=   red */
674                             while (*psz_subtitle == ' ')
675                                 psz_subtitle++;
676
677                             /* */
678                             if( *psz_subtitle == '"' )
679                             {
680                                 psz_subtitle++;
681                                 i_len = strcspn( psz_subtitle, "\"" );
682                             }
683                             else if( *psz_subtitle == '\'' )
684                             {
685                                 psz_subtitle++;
686                                 i_len = strcspn( psz_subtitle, "'" );
687                             }
688                             else
689                             {
690                                 i_len = strcspn( psz_subtitle, " \t>" );
691                             }
692                             HtmlPut( &psz_html, "\"" );
693                             HtmlNPut( &psz_html, psz_subtitle, i_len );
694                             HtmlPut( &psz_html, "\"" );
695
696                             psz_subtitle += i_len;
697                             if( *psz_subtitle == '\"' || *psz_subtitle == '\'' )
698                                 psz_subtitle++;
699                             break;
700                         }
701                     }
702                     if( psz_attribs[ k ] == NULL )
703                     {
704                         /* Jump over unrecognised tag */
705                         int i_len = strcspn( psz_subtitle, "\"" );
706                         if( psz_subtitle[i_len] == '\"' )
707                         {
708                             i_len += 1 + strcspn( &psz_subtitle[i_len + 1], "\"" );
709                             if( psz_subtitle[i_len] == '\"' )
710                                 i_len++;
711                         }
712                         /* Not a tag, something else we do not understand */
713                         if( i_len == 0 )
714                             psz_subtitle++;
715
716                         psz_subtitle += i_len;
717                     }
718
719                     while (*psz_subtitle == ' ')
720                         *psz_html++ = *psz_subtitle++;
721                 }
722                 *psz_html++ = '>';
723                 psz_subtitle++;
724             }
725             else if( !strncmp( psz_subtitle, "</", 2 ))
726             {
727                 bool   b_match     = false;
728                 bool   b_ignore    = false;
729                 int    i_len       = strlen( psz_tag ) - 1;
730                 char  *psz_lastTag = NULL;
731
732                 if( i_len >= 0 )
733                 {
734                     psz_lastTag = psz_tag + i_len;
735                     i_len = 0;
736
737                     switch( *psz_lastTag )
738                     {
739                     case 'b':
740                         b_match = !strncasecmp( psz_subtitle, "</b>", 4 );
741                         i_len   = 4;
742                         break;
743                     case 'i':
744                         b_match = !strncasecmp( psz_subtitle, "</i>", 4 );
745                         i_len   = 4;
746                         break;
747                     case 'u':
748                         b_match = !strncasecmp( psz_subtitle, "</u>", 4 );
749                         i_len   = 4;
750                         break;
751                     case 's':
752                         b_match = !strncasecmp( psz_subtitle, "</s>", 4 );
753                         i_len   = 4;
754                         break;
755                     case 'f':
756                         b_match = !strncasecmp( psz_subtitle, "</font>", 7 );
757                         i_len   = 7;
758                         break;
759                     case 'I':
760                         i_len = strcspn( psz_subtitle, ">" );
761                         b_match = psz_subtitle[i_len] == '>';
762                         b_ignore = true;
763                         if( b_match )
764                             i_len++;
765                         break;
766                     }
767                 }
768                 if( !b_match )
769                 {
770                     /* Not well formed -- kill everything */
771                     free( psz_html_start );
772                     psz_html_start = NULL;
773                     break;
774                 }
775                 *psz_lastTag = '\0';
776                 if( !b_ignore )
777                     HtmlNPut( &psz_html, psz_subtitle, i_len );
778
779                 psz_subtitle += i_len;
780             }
781             else if( ( psz_subtitle[1] < 'a' || psz_subtitle[1] > 'z' ) &&
782                      ( psz_subtitle[1] < 'A' || psz_subtitle[1] > 'Z' ) )
783             {
784                 /* We have a single < */
785                 HtmlPut( &psz_html, "&lt;" );
786                 psz_subtitle++;
787             }
788             else
789             {
790                 /* We have an unknown tag or a single < */
791
792                 /* Search for the next tag or end of tag or end of string */
793                 char *psz_stop = psz_subtitle + 1 + strcspn( &psz_subtitle[1], "<>" );
794                 char *psz_closing = strstr( psz_subtitle, "/>" );
795
796                 if( psz_closing && psz_closing < psz_stop )
797                 {
798                     /* We have a self closed tag, remove it */
799                     psz_subtitle = &psz_closing[2];
800                 }
801                 else if( *psz_stop == '>' )
802                 {
803                     char psz_match[256];
804
805                     snprintf( psz_match, sizeof(psz_match), "</%s", &psz_subtitle[1] );
806                     psz_match[strcspn( psz_match, " \t>" )] = '\0';
807
808                     if( strstr( psz_subtitle, psz_match ) )
809                     {
810                         /* We have the closing tag, ignore it TODO */
811                         psz_subtitle = &psz_stop[1];
812                         strcat( psz_tag, "I" );
813                     }
814                     else
815                     {
816                         int i_len = psz_stop + 1 - psz_subtitle;
817
818                         /* Copy the whole data */
819                         for( ; i_len > 0; i_len--, psz_subtitle++ )
820                         {
821                             if( *psz_subtitle == '<' )
822                                 HtmlPut( &psz_html, "&lt;" );
823                             else if( *psz_subtitle == '>' )
824                                 HtmlPut( &psz_html, "&gt;" );
825                             else
826                                 *psz_html++ = *psz_subtitle;
827                         }
828                     }
829                 }
830                 else
831                 {
832                     /* We have a single < */
833                     HtmlPut( &psz_html, "&lt;" );
834                     psz_subtitle++;
835                 }
836             }
837         }
838         else if( *psz_subtitle == '&' )
839         {
840             if( !strncasecmp( psz_subtitle, "&lt;", 4 ))
841             {
842                 HtmlCopy( &psz_html, &psz_subtitle, "&lt;" );
843             }
844             else if( !strncasecmp( psz_subtitle, "&gt;", 4 ))
845             {
846                 HtmlCopy( &psz_html, &psz_subtitle, "&gt;" );
847             }
848             else if( !strncasecmp( psz_subtitle, "&amp;", 5 ))
849             {
850                 HtmlCopy( &psz_html, &psz_subtitle, "&amp;" );
851             }
852             else
853             {
854                 HtmlPut( &psz_html, "&amp;" );
855                 psz_subtitle++;
856             }
857         }
858         else if( *psz_subtitle == '>' )
859         {
860             HtmlPut( &psz_html, "&gt;" );
861             psz_subtitle++;
862         }
863         else if( psz_subtitle[0] == '{' && psz_subtitle[1] == '\\' &&
864                  strchr( psz_subtitle, '}' ) )
865         {
866             /* Check for forced alignment */
867             if( !b_has_align &&
868                 !strncmp( psz_subtitle, "{\\an", 4 ) && psz_subtitle[4] >= '1' && psz_subtitle[4] <= '9' && psz_subtitle[5] == '}' )
869             {
870                 static const int pi_vertical[3] = { SUBPICTURE_ALIGN_BOTTOM, 0, SUBPICTURE_ALIGN_TOP };
871                 static const int pi_horizontal[3] = { SUBPICTURE_ALIGN_LEFT, 0, SUBPICTURE_ALIGN_RIGHT };
872                 const int i_id = psz_subtitle[4] - '1';
873
874                 b_has_align = true;
875                 *pi_align = pi_vertical[i_id/3] | pi_horizontal[i_id%3];
876             }
877             /* TODO fr -> rotation */
878
879             /* Hide {\stupidity} */
880             psz_subtitle = strchr( psz_subtitle, '}' ) + 1;
881         }
882         else if( psz_subtitle[0] == '{' &&
883                 ( psz_subtitle[1] == 'Y' || psz_subtitle[1] == 'y' )
884                 && psz_subtitle[2] == ':' && strchr( psz_subtitle, '}' ) )
885         {
886             // FIXME: We don't do difference between Y and y, and we should.
887             if( psz_subtitle[3] == 'i' )
888             {
889                 HtmlPut( &psz_html, "<i>" );
890                 strcat( psz_tag, "i" );
891             }
892             if( psz_subtitle[3] == 'b' )
893             {
894                 HtmlPut( &psz_html, "<b>" );
895                 strcat( psz_tag, "b" );
896             }
897             if( psz_subtitle[3] == 'u' )
898             {
899                 HtmlPut( &psz_html, "<u>" );
900                 strcat( psz_tag, "u" );
901             }
902             psz_subtitle = strchr( psz_subtitle, '}' ) + 1;
903         }
904         else if( psz_subtitle[0] == '{' &&  psz_subtitle[2] == ':' && strchr( psz_subtitle, '}' ) )
905         {
906             // Hide other {x:y} atrocities, like {c:$bbggrr} or {P:x}
907             psz_subtitle = strchr( psz_subtitle, '}' ) + 1;
908         }
909         else if( psz_subtitle[0] == '\\' && psz_subtitle[1] )
910         {
911             if( psz_subtitle[1] == 'N' || psz_subtitle[1] == 'n' )
912             {
913                 HtmlPut( &psz_html, "<br/>" );
914                 psz_subtitle += 2;
915             }
916             else if( psz_subtitle[1] == 'h' )
917             {
918                 /* Non breakable space */
919                 HtmlPut( &psz_html, NO_BREAKING_SPACE );
920                 psz_subtitle += 2;
921             }
922             else
923             {
924                 HtmlPut( &psz_html, "\\" );
925                 psz_subtitle++;
926             }
927         }
928         else
929         {
930             *psz_html = *psz_subtitle;
931             if( psz_html > psz_html_start )
932             {
933                 /* Check for double whitespace */
934                 if( ( *psz_html == ' '  || *psz_html == '\t' ) &&
935                     ( *(psz_html-1) == ' ' || *(psz_html-1) == '\t' ) )
936                 {
937                     HtmlPut( &psz_html, NO_BREAKING_SPACE );
938                     psz_html--;
939                 }
940             }
941             psz_html++;
942             psz_subtitle++;
943         }
944
945         if( ( size_t )( psz_html - psz_html_start ) > i_buf_size - 50 )
946         {
947             const int i_len = psz_html - psz_html_start;
948
949             i_buf_size += 200;
950             char *psz_new = realloc( psz_html_start, i_buf_size );
951             if( !psz_new )
952                 break;
953             psz_html_start = psz_new;
954             psz_html = &psz_new[i_len];
955         }
956     }
957     if( psz_html_start )
958     {
959         static const char *psz_text_close = "</text>";
960         static const char *psz_tag_long = "/font>";
961
962         /* Realloc for closing tags and shrink memory */
963         const size_t i_length = (size_t)( psz_html - psz_html_start );
964
965         const size_t i_size = i_length + strlen(psz_tag_long) * strlen(psz_tag) + strlen(psz_text_close) + 1;
966         char *psz_new = realloc( psz_html_start, i_size );
967         if( psz_new )
968         {
969             psz_html_start = psz_new;
970             psz_html = &psz_new[i_length];
971
972             /* Close not well formed subtitle */
973             while( *psz_tag )
974             {
975                 /* */
976                 char *psz_last = &psz_tag[strlen(psz_tag)-1];
977                 switch( *psz_last )
978                 {
979                 case 'b':
980                     HtmlPut( &psz_html, "</b>" );
981                     break;
982                 case 'i':
983                     HtmlPut( &psz_html, "</i>" );
984                     break;
985                 case 'u':
986                     HtmlPut( &psz_html, "</u>" );
987                     break;
988                 case 's':
989                     HtmlPut( &psz_html, "</s>" );
990                     break;
991                 case 'f':
992                     HtmlPut( &psz_html, "</font>" );
993                     break;
994                 case 'I':
995                     break;
996                 }
997
998                 *psz_last = '\0';
999             }
1000             HtmlPut( &psz_html, psz_text_close );
1001         }
1002     }
1003     free( psz_tag );
1004
1005     return psz_html_start;
1006 }
1007