]> git.sesse.net Git - vlc/blob - modules/codec/subtitles/subsdec.c
Merge branch 1.0-bugfix
[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_CODEC_SUBT:
236         case VLC_CODEC_SSA:
237         case VLC_CODEC_ITU_T140:
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_CODEC_ITU_T140 )
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 ?
273                  p_dec->fmt_in.subs.psz_encoding : "not specified");
274     }
275
276     /* Second, try configured encoding */
277     if (psz_charset == NULL)
278     {
279         psz_charset = var_CreateGetNonEmptyString (p_dec, "subsdec-encoding");
280         msg_Dbg (p_dec, "trying configured character encoding: %s",
281                  psz_charset ? psz_charset : "not specified");
282     }
283
284     /* Third, try "local" encoding with optional UTF-8 autodetection */
285     if (psz_charset == NULL)
286     {
287         psz_charset = strdup (GetFallbackEncoding ());
288         msg_Dbg (p_dec, "trying default character encoding: %s",
289                  psz_charset ? psz_charset : "not specified");
290
291         if (var_CreateGetBool (p_dec, "subsdec-autodetect-utf8"))
292         {
293             msg_Dbg (p_dec, "using automatic UTF-8 detection");
294             p_sys->b_autodetect_utf8 = true;
295         }
296     }
297
298     /* Forth, don't do character decoding, i.e. assume UTF-8 */
299     if (psz_charset == NULL)
300     {
301         psz_charset = strdup ("UTF-8");
302         msg_Dbg (p_dec, "using UTF-8 character encoding" );
303     }
304
305     if ((psz_charset != NULL)
306      && strcasecmp (psz_charset, "UTF-8")
307      && strcasecmp (psz_charset, "utf8"))
308     {
309         p_sys->iconv_handle = vlc_iconv_open ("UTF-8", psz_charset);
310         if (p_sys->iconv_handle == (vlc_iconv_t)(-1))
311             msg_Err (p_dec, "cannot convert from %s: %m", psz_charset);
312     }
313     free (psz_charset);
314
315     var_Create( p_dec, "subsdec-align", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
316     var_Get( p_dec, "subsdec-align", &val );
317     p_sys->i_align = val.i_int;
318
319     if( p_dec->fmt_in.i_codec == VLC_CODEC_SSA
320      && var_CreateGetBool( p_dec, "subsdec-formatted" ) )
321     {
322         if( p_dec->fmt_in.i_extra > 0 )
323             ParseSSAHeader( p_dec );
324     }
325
326     return VLC_SUCCESS;
327 }
328
329 /****************************************************************************
330  * DecodeBlock: the whole thing
331  ****************************************************************************
332  * This function must be fed with complete subtitles units.
333  ****************************************************************************/
334 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
335 {
336     subpicture_t *p_spu;
337     block_t *p_block;
338
339     if( !pp_block || *pp_block == NULL )
340         return NULL;
341
342     p_block = *pp_block;
343     if( p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
344     {
345         block_Release( p_block );
346         return NULL;
347     }
348
349     p_spu = ParseText( p_dec, p_block );
350
351     block_Release( p_block );
352     *pp_block = NULL;
353
354     return p_spu;
355 }
356
357 /*****************************************************************************
358  * CloseDecoder: clean up the decoder
359  *****************************************************************************/
360 static void CloseDecoder( vlc_object_t *p_this )
361 {
362     decoder_t *p_dec = (decoder_t *)p_this;
363     decoder_sys_t *p_sys = p_dec->p_sys;
364
365     if( p_sys->iconv_handle != (vlc_iconv_t)-1 )
366         vlc_iconv_close( p_sys->iconv_handle );
367
368     if( p_sys->pp_ssa_styles )
369     {
370         int i;
371         for( i = 0; i < p_sys->i_ssa_styles; i++ )
372         {
373             if( !p_sys->pp_ssa_styles[i] )
374                 continue;
375
376             free( p_sys->pp_ssa_styles[i]->psz_stylename );
377             free( p_sys->pp_ssa_styles[i]->font_style.psz_fontname );
378             free( p_sys->pp_ssa_styles[i] );
379         }
380         TAB_CLEAN( p_sys->i_ssa_styles, p_sys->pp_ssa_styles );
381     }
382     if( p_sys->pp_images )
383     {
384         int i;
385         for( i = 0; i < p_sys->i_images; i++ )
386         {
387             if( !p_sys->pp_images[i] )
388                 continue;
389
390             if( p_sys->pp_images[i]->p_pic )
391                 picture_Release( p_sys->pp_images[i]->p_pic );
392             free( p_sys->pp_images[i]->psz_filename );
393
394             free( p_sys->pp_images[i] );
395         }
396         TAB_CLEAN( p_sys->i_images, p_sys->pp_images );
397     }
398
399     free( p_sys );
400 }
401
402 /*****************************************************************************
403  * ParseText: parse an text subtitle packet and send it to the video output
404  *****************************************************************************/
405 static subpicture_t *ParseText( decoder_t *p_dec, block_t *p_block )
406 {
407     decoder_sys_t *p_sys = p_dec->p_sys;
408     subpicture_t *p_spu = NULL;
409     char *psz_subtitle = NULL;
410     video_format_t fmt;
411
412     /* We cannot display a subpicture with no date */
413     if( p_block->i_pts == 0 )
414     {
415         msg_Warn( p_dec, "subtitle without a date" );
416         return NULL;
417     }
418
419     /* Check validity of packet data */
420     /* An "empty" line containing only \0 can be used to force
421        and ephemer picture from the screen */
422     if( p_block->i_buffer < 1 )
423     {
424         msg_Warn( p_dec, "no subtitle data" );
425         return NULL;
426     }
427
428     /* Should be resiliant against bad subtitles */
429     psz_subtitle = strndup( (const char *)p_block->p_buffer,
430                             p_block->i_buffer );
431     if( psz_subtitle == NULL )
432         return NULL;
433
434     if( p_sys->iconv_handle == (vlc_iconv_t)-1 )
435     {
436         if (EnsureUTF8( psz_subtitle ) == NULL)
437         {
438             msg_Err( p_dec, "failed to convert subtitle encoding.\n"
439                      "Try manually setting a character-encoding "
440                      "before you open the file." );
441         }
442     }
443     else
444     {
445
446         if( p_sys->b_autodetect_utf8 )
447         {
448             if( IsUTF8( psz_subtitle ) == NULL )
449             {
450                 msg_Dbg( p_dec, "invalid UTF-8 sequence: "
451                          "disabling UTF-8 subtitles autodetection" );
452                 p_sys->b_autodetect_utf8 = false;
453             }
454         }
455
456         if( !p_sys->b_autodetect_utf8 )
457         {
458             size_t inbytes_left = strlen( psz_subtitle );
459             size_t outbytes_left = 6 * inbytes_left;
460             char *psz_new_subtitle = malloc( outbytes_left + 1 );
461             char *psz_convert_buffer_out = psz_new_subtitle;
462             const char *psz_convert_buffer_in = psz_subtitle;
463
464             size_t ret = vlc_iconv( p_sys->iconv_handle,
465                                     &psz_convert_buffer_in, &inbytes_left,
466                                     &psz_convert_buffer_out, &outbytes_left );
467
468             *psz_convert_buffer_out++ = '\0';
469             free( psz_subtitle );
470
471             if( ( ret == (size_t)(-1) ) || inbytes_left )
472             {
473                 free( psz_new_subtitle );
474                 msg_Err( p_dec, "failed to convert subtitle encoding.\n"
475                         "Try manually setting a character-encoding "
476                                 "before you open the file." );
477                 return NULL;
478             }
479
480             psz_subtitle = realloc( psz_new_subtitle,
481                                     psz_convert_buffer_out - psz_new_subtitle );
482         }
483     }
484
485     /* Create the subpicture unit */
486     p_spu = decoder_NewSubpicture( p_dec );
487     if( !p_spu )
488     {
489         msg_Warn( p_dec, "can't get spu buffer" );
490         free( psz_subtitle );
491         return NULL;
492     }
493
494     /* Create a new subpicture region */
495     memset( &fmt, 0, sizeof(video_format_t) );
496     fmt.i_chroma = VLC_CODEC_TEXT;
497     fmt.i_aspect = 0;
498     fmt.i_width = fmt.i_height = 0;
499     fmt.i_x_offset = fmt.i_y_offset = 0;
500     p_spu->p_region = subpicture_region_New( &fmt );
501     if( !p_spu->p_region )
502     {
503         msg_Err( p_dec, "cannot allocate SPU region" );
504         free( psz_subtitle );
505         decoder_DeleteSubpicture( p_dec, p_spu );
506         return NULL;
507     }
508
509     /* Decode and format the subpicture unit */
510     if( p_dec->fmt_in.i_codec != VLC_CODEC_SSA )
511     {
512         /* Normal text subs, easy markup */
513         p_spu->p_region->i_align = SUBPICTURE_ALIGN_BOTTOM | p_sys->i_align;
514         p_spu->p_region->i_x = p_sys->i_align ? 20 : 0;
515         p_spu->p_region->i_y = 10;
516
517         /* Remove formatting from string */
518
519         p_spu->p_region->psz_text = StripTags( psz_subtitle );
520         if( var_CreateGetBool( p_dec, "subsdec-formatted" ) )
521         {
522             p_spu->p_region->psz_html = CreateHtmlSubtitle( &p_spu->p_region->i_align, psz_subtitle );
523         }
524
525         p_spu->i_start = p_block->i_pts;
526         p_spu->i_stop = p_block->i_pts + p_block->i_length;
527         p_spu->b_ephemer = (p_block->i_length == 0);
528         p_spu->b_absolute = false;
529     }
530     else
531     {
532         /* Decode SSA/USF strings */
533         ParseSSAString( p_dec, psz_subtitle, p_spu );
534
535         p_spu->i_start = p_block->i_pts;
536         p_spu->i_stop = p_block->i_pts + p_block->i_length;
537         p_spu->b_ephemer = (p_block->i_length == 0);
538         p_spu->b_absolute = false;
539         p_spu->i_original_picture_width = p_sys->i_original_width;
540         p_spu->i_original_picture_height = p_sys->i_original_height;
541     }
542     free( psz_subtitle );
543
544     return p_spu;
545 }
546
547 char* GotoNextLine( char *psz_text )
548 {
549     char *p_newline = psz_text;
550
551     while( p_newline[0] != '\0' )
552     {
553         if( p_newline[0] == '\n' || p_newline[0] == '\r' )
554         {
555             p_newline++;
556             while( p_newline[0] == '\n' || p_newline[0] == '\r' )
557                 p_newline++;
558             break;
559         }
560         else p_newline++;
561     }
562     return p_newline;
563 }
564
565 /* Function now handles tags with attribute values, and tries
566  * to deal with &' commands too. It no longer modifies the string
567  * in place, so that the original text can be reused
568  */
569 static char *StripTags( char *psz_subtitle )
570 {
571     char *psz_text_start;
572     char *psz_text;
573
574     psz_text = psz_text_start = malloc( strlen( psz_subtitle ) + 1 );
575     if( !psz_text_start )
576         return NULL;
577
578     while( *psz_subtitle )
579     {
580         if( *psz_subtitle == '<' )
581         {
582             if( strncasecmp( psz_subtitle, "<br/>", 5 ) == 0 )
583                 *psz_text++ = '\n';
584
585             psz_subtitle += strcspn( psz_subtitle, ">" );
586         }
587         else if( *psz_subtitle == '&' )
588         {
589             if( !strncasecmp( psz_subtitle, "&lt;", 4 ))
590             {
591                 *psz_text++ = '<';
592                 psz_subtitle += strcspn( psz_subtitle, ";" );
593             }
594             else if( !strncasecmp( psz_subtitle, "&gt;", 4 ))
595             {
596                 *psz_text++ = '>';
597                 psz_subtitle += strcspn( psz_subtitle, ";" );
598             }
599             else if( !strncasecmp( psz_subtitle, "&amp;", 5 ))
600             {
601                 *psz_text++ = '&';
602                 psz_subtitle += strcspn( psz_subtitle, ";" );
603             }
604             else if( !strncasecmp( psz_subtitle, "&quot;", 6 ))
605             {
606                 *psz_text++ = '\"';
607                 psz_subtitle += strcspn( psz_subtitle, ";" );
608             }
609             else
610             {
611                 /* Assume it is just a normal ampersand */
612                 *psz_text++ = '&';
613             }
614         }
615         else
616         {
617             *psz_text++ = *psz_subtitle;
618         }
619
620         psz_subtitle++;
621     }
622     *psz_text = '\0';
623     psz_text_start = realloc( psz_text_start, strlen( psz_text_start ) + 1 );
624
625     return psz_text_start;
626 }
627
628 /* Try to respect any style tags present in the subtitle string. The main
629  * problem here is a lack of adequate specs for the subtitle formats.
630  * SSA/ASS and USF are both detail spec'ed -- but they are handled elsewhere.
631  * SAMI has a detailed spec, but extensive rework is needed in the demux
632  * code to prevent all this style information being excised, as it presently
633  * does.
634  * That leaves the others - none of which were (I guess) originally intended
635  * to be carrying style information. Over time people have used them that way.
636  * In the absence of specifications from which to work, the tags supported
637  * have been restricted to the simple set permitted by the USF DTD, ie. :
638  *  Basic: <br>, <i>, <b>, <u>
639  *  Extended: <font>
640  *    Attributes: face
641  *                family
642  *                size
643  *                color
644  *                outline-color
645  *                shadow-color
646  *                outline-level
647  *                shadow-level
648  *                back-color
649  *                alpha
650  * There is also the further restriction that the subtitle be well-formed
651  * as an XML entity, ie. the HTML sentence:
652  *        <b><i>Bold and Italics</b></i>
653  * doesn't qualify because the tags aren't nested one inside the other.
654  * <text> tags are automatically added to the output to ensure
655  * well-formedness.
656  * If the text doesn't qualify for any reason, a NULL string is
657  * returned, and the rendering engine will fall back to the
658  * plain text version of the subtitle.
659  */
660 static void HtmlNPut( char **ppsz_html, const char *psz_text, int i_max )
661 {
662     const int i_len = strlen(psz_text);
663
664     strncpy( *ppsz_html, psz_text, i_max );
665     *ppsz_html += __MIN(i_max,i_len);
666 }
667
668 static void HtmlPut( char **ppsz_html, const char *psz_text )
669 {
670     strcpy( *ppsz_html, psz_text );
671     *ppsz_html += strlen(psz_text);
672 }
673 static void HtmlCopy( char **ppsz_html, char **ppsz_subtitle, const char *psz_text )
674 {
675     HtmlPut( ppsz_html, psz_text );
676     *ppsz_subtitle += strlen(psz_text);
677 }
678
679 static char *CreateHtmlSubtitle( int *pi_align, char *psz_subtitle )
680 {
681     /* */
682     char *psz_tag = malloc( ( strlen( psz_subtitle ) / 3 ) + 1 );
683     if( !psz_tag )
684         return NULL;
685     psz_tag[ 0 ] = '\0';
686
687     /* */
688     size_t i_buf_size = strlen( psz_subtitle ) + 100;
689     char   *psz_html_start = malloc( i_buf_size );
690     char   *psz_html = psz_html_start;
691     if( psz_html_start == NULL )
692     {
693         free( psz_tag );
694         return NULL;
695     }
696     psz_html[0] = '\0';
697
698     bool b_has_align = false;
699
700     HtmlPut( &psz_html, "<text>" );
701
702     /* */
703     while( *psz_subtitle )
704     {
705         if( *psz_subtitle == '\n' )
706         {
707             HtmlPut( &psz_html, "<br/>" );
708             psz_subtitle++;
709         }
710         else if( *psz_subtitle == '<' )
711         {
712             if( !strncasecmp( psz_subtitle, "<br/>", 5 ))
713             {
714                 HtmlCopy( &psz_html, &psz_subtitle, "<br/>" );
715             }
716             else if( !strncasecmp( psz_subtitle, "<b>", 3 ) )
717             {
718                 HtmlCopy( &psz_html, &psz_subtitle, "<b>" );
719                 strcat( psz_tag, "b" );
720             }
721             else if( !strncasecmp( psz_subtitle, "<i>", 3 ) )
722             {
723                 HtmlCopy( &psz_html, &psz_subtitle, "<i>" );
724                 strcat( psz_tag, "i" );
725             }
726             else if( !strncasecmp( psz_subtitle, "<u>", 3 ) )
727             {
728                 HtmlCopy( &psz_html, &psz_subtitle, "<u>" );
729                 strcat( psz_tag, "u" );
730             }
731             else if( !strncasecmp( psz_subtitle, "<font ", 6 ))
732             {
733                 const char *psz_attribs[] = { "face=", "family=", "size=",
734                         "color=", "outline-color=", "shadow-color=",
735                         "outline-level=", "shadow-level=", "back-color=",
736                         "alpha=", NULL };
737
738                 HtmlCopy( &psz_html, &psz_subtitle, "<font " );
739                 strcat( psz_tag, "f" );
740
741                 while( *psz_subtitle != '>' )
742                 {
743                     int  k;
744
745                     for( k=0; psz_attribs[ k ]; k++ )
746                     {
747                         int i_len = strlen( psz_attribs[ k ] );
748
749                         if( !strncasecmp( psz_subtitle, psz_attribs[k], i_len ) )
750                         {
751                             /* */
752                             HtmlPut( &psz_html, psz_attribs[k] );
753                             psz_subtitle += i_len;
754
755                             /* */
756                             if( *psz_subtitle == '"' )
757                             {
758                                 psz_subtitle++;
759                                 i_len = strcspn( psz_subtitle, "\"" );
760                             }
761                             else
762                             {
763                                 i_len = strcspn( psz_subtitle, " \t>" );
764                             }
765                             HtmlPut( &psz_html, "\"" );
766                             if( !strcmp( psz_attribs[ k ], "color=" ) && *psz_subtitle >= '0' && *psz_subtitle <= '9' )
767                                 HtmlPut( &psz_html, "#" );
768                             HtmlNPut( &psz_html, psz_subtitle, i_len );
769                             HtmlPut( &psz_html, "\"" );
770
771                             psz_subtitle += i_len;
772                             if( *psz_subtitle == '\"' )
773                                 psz_subtitle++;
774                             break;
775                         }
776                     }
777                     if( psz_attribs[ k ] == NULL )
778                     {
779                         /* Jump over unrecognised tag */
780                         int i_len = strcspn( psz_subtitle, "\"" ) + 1;
781
782                         i_len += strcspn( psz_subtitle + i_len, "\"" ) + 1;
783                         psz_subtitle += i_len;
784                     }
785                     while (*psz_subtitle == ' ')
786                         *psz_html++ = *psz_subtitle++;
787                 }
788                 *psz_html++ = *psz_subtitle++;
789             }
790             else if( !strncmp( psz_subtitle, "</", 2 ))
791             {
792                 bool   b_match     = false;
793                 bool   b_ignore    = false;
794                 int    i_len       = strlen( psz_tag ) - 1;
795                 char  *psz_lastTag = NULL;
796
797                 if( i_len >= 0 )
798                 {
799                     psz_lastTag = psz_tag + i_len;
800                     i_len = 0;
801
802                     switch( *psz_lastTag )
803                     {
804                     case 'b':
805                         b_match = !strncasecmp( psz_subtitle, "</b>", 4 );
806                         i_len   = 4;
807                         break;
808                     case 'i':
809                         b_match = !strncasecmp( psz_subtitle, "</i>", 4 );
810                         i_len   = 4;
811                         break;
812                     case 'u':
813                         b_match = !strncasecmp( psz_subtitle, "</u>", 4 );
814                         i_len   = 4;
815                         break;
816                     case 'f':
817                         b_match = !strncasecmp( psz_subtitle, "</font>", 7 );
818                         i_len   = 7;
819                         break;
820                     case 'I':
821                         i_len = strcspn( psz_subtitle, ">" );
822                         b_match = psz_subtitle[i_len] == '>';
823                         b_ignore = true;
824                         if( b_match )
825                             i_len++;
826                         break;
827                     }
828                 }
829                 if( !b_match )
830                 {
831                     /* Not well formed -- kill everything */
832                     free( psz_html_start );
833                     psz_html_start = NULL;
834                     break;
835                 }
836                 *psz_lastTag = '\0';
837                 if( !b_ignore )
838                     HtmlNPut( &psz_html, psz_subtitle, i_len );
839
840                 psz_subtitle += i_len;
841             }
842             else if( ( psz_subtitle[1] < 'a' || psz_subtitle[1] > 'z' ) &&
843                      ( psz_subtitle[1] < 'A' || psz_subtitle[1] > 'Z' ) )
844             {
845                 /* We have a single < */
846                 HtmlPut( &psz_html, "&lt;" );
847                 psz_subtitle++;
848             }
849             else
850             {
851                 /* We have an unknown tag or a single < */
852
853                 /* Search for the next tag or end of tag or end of string */
854                 char *psz_stop = psz_subtitle + 1 + strcspn( &psz_subtitle[1], "<>" );
855                 char *psz_closing = strstr( psz_subtitle, "/>" );
856
857                 if( psz_closing && psz_closing < psz_stop )
858                 {
859                     /* We have a self closed tag, remove it */
860                     psz_subtitle = &psz_closing[2];
861                 }
862                 else if( *psz_stop == '>' )
863                 {
864                     char psz_match[256];
865
866                     snprintf( psz_match, sizeof(psz_match), "</%s", &psz_subtitle[1] );
867                     psz_match[strcspn( psz_match, " \t>" )] = '\0';
868
869                     if( strstr( psz_subtitle, psz_match ) )
870                     {
871                         /* We have the closing tag, ignore it TODO */
872                         psz_subtitle = &psz_stop[1];
873                         strcat( psz_tag, "I" );
874                     }
875                     else
876                     {
877                         int i_len = psz_stop + 1 - psz_subtitle;
878
879                         /* Copy the whole data */
880                         for( ; i_len > 0; i_len--, psz_subtitle++ )
881                         {
882                             if( *psz_subtitle == '<' )
883                                 HtmlPut( &psz_html, "&lt;" );
884                             else if( *psz_subtitle == '>' )
885                                 HtmlPut( &psz_html, "&gt;" );
886                             else
887                                 *psz_html++ = *psz_subtitle;
888                         }
889                     }
890                 }
891                 else
892                 {
893                     /* We have a single < */
894                     HtmlPut( &psz_html, "&lt;" );
895                     psz_subtitle++;
896                 }
897             }
898         }
899         else if( *psz_subtitle == '&' )
900         {
901             if( !strncasecmp( psz_subtitle, "&lt;", 4 ))
902             {
903                 HtmlCopy( &psz_html, &psz_subtitle, "&lt;" );
904             }
905             else if( !strncasecmp( psz_subtitle, "&gt;", 4 ))
906             {
907                 HtmlCopy( &psz_html, &psz_subtitle, "&gt;" );
908             }
909             else if( !strncasecmp( psz_subtitle, "&amp;", 5 ))
910             {
911                 HtmlCopy( &psz_html, &psz_subtitle, "&amp;" );
912             }
913             else
914             {
915                 HtmlPut( &psz_html, "&amp;" );
916                 psz_subtitle++;
917             }
918         }
919         else if( *psz_subtitle == '>' )
920         {
921             HtmlPut( &psz_html, "&gt;" );
922             psz_subtitle++;
923         }
924         else if( psz_subtitle[0] == '{' && psz_subtitle[1] == '\\' &&
925                  strchr( psz_subtitle, '}' ) )
926         {
927             /* Check for forced alignment */
928             if( !b_has_align &&
929                 !strncmp( psz_subtitle, "{\\an", 4 ) && psz_subtitle[4] >= '1' && psz_subtitle[4] <= '9' && psz_subtitle[5] == '}' )
930             {
931                 static const int pi_vertical[3] = { SUBPICTURE_ALIGN_BOTTOM, 0, SUBPICTURE_ALIGN_TOP };
932                 static const int pi_horizontal[3] = { SUBPICTURE_ALIGN_LEFT, 0, SUBPICTURE_ALIGN_RIGHT };
933                 const int i_id = psz_subtitle[4] - '1';
934
935                 b_has_align = true;
936                 *pi_align = pi_vertical[i_id/3] | pi_horizontal[i_id%3];
937             }
938             /* TODO fr -> rotation */
939
940             /* Hide {\stupidity} */
941             psz_subtitle = strchr( psz_subtitle, '}' ) + 1;
942         }
943         else
944         {
945             *psz_html = *psz_subtitle;
946             if( psz_html > psz_html_start )
947             {
948                 /* Check for double whitespace */
949                 if( ( *psz_html == ' '  || *psz_html == '\t' ) &&
950                     ( *(psz_html-1) == ' ' || *(psz_html-1) == '\t' ) )
951                 {
952                     HtmlPut( &psz_html, NO_BREAKING_SPACE );
953                     psz_html--;
954                 }
955             }
956             psz_html++;
957             psz_subtitle++;
958         }
959
960         if( ( size_t )( psz_html - psz_html_start ) > i_buf_size - 50 )
961         {
962             const int i_len = psz_html - psz_html_start;
963
964             i_buf_size += 200;
965             char *psz_new = realloc( psz_html_start, i_buf_size );
966             if( !psz_new )
967                 break;
968             psz_html_start = psz_new;
969             psz_html = &psz_new[i_len];
970         }
971     }
972     if( psz_html_start )
973     {
974         static const char *psz_text_close = "</text>";
975         static const char *psz_tag_long = "/font>";
976
977         /* Realloc for closing tags and shrink memory */
978         const size_t i_length = (size_t)( psz_html - psz_html_start );
979
980         const size_t i_size = i_length + strlen(psz_tag_long) * strlen(psz_tag) + strlen(psz_text_close) + 1;
981         char *psz_new = realloc( psz_html_start, i_size );
982         if( psz_new )
983         {
984             psz_html_start = psz_new;
985             psz_html = &psz_new[i_length];
986
987             /* Close not well formed subtitle */
988             while( *psz_tag )
989             {
990                 /* */
991                 char *psz_last = &psz_tag[strlen(psz_tag)-1];
992                 switch( *psz_last )
993                 {
994                 case 'b':
995                     HtmlPut( &psz_html, "</b>" );
996                     break;
997                 case 'i':
998                     HtmlPut( &psz_html, "</i>" );
999                     break;
1000                 case 'u':
1001                     HtmlPut( &psz_html, "</u>" );
1002                     break;
1003                 case 'f':
1004                     HtmlPut( &psz_html, "/font>" );
1005                     break;
1006                 case 'I':
1007                     break;
1008                 }
1009
1010                 *psz_last = '\0';
1011             }
1012             HtmlPut( &psz_html, psz_text_close );
1013         }
1014     }
1015     free( psz_tag );
1016
1017     return psz_html_start;
1018 }
1019