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