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