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