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