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