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