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