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