1 /*****************************************************************************
2 * subsdec.c : text subtitles decoder
3 *****************************************************************************
4 * Copyright (C) 2000-2006 the VideoLAN team
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>
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.
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.
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 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
35 #include <vlc_plugin.h>
37 /*****************************************************************************
39 *****************************************************************************/
40 static int OpenDecoder ( vlc_object_t * );
41 static void CloseDecoder ( vlc_object_t * );
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 ( char * );
49 /*****************************************************************************
51 *****************************************************************************/
52 static const char *ppsz_encodings[] = { DEFAULT_NAME, "ASCII", "UTF-8", "",
53 "ISO-8859-1", "CP1252", "MacRoman", "MacIceland","ISO-8859-15", "",
54 "ISO-8859-2", "CP1250", "MacCentralEurope", "MacCroatian", "MacRomania", "",
55 "ISO-8859-5", "CP1251", "MacCyrillic", "MacUkraine", "KOI8-R", "KOI8-U", "KOI8-RU", "",
56 "ISO-8859-6", "CP1256", "MacArabic", "",
57 "ISO-8859-7", "CP1253", "MacGreek", "",
58 "ISO-8859-8", "CP1255", "MacHebrew", "",
59 "ISO-8859-9", "CP1254", "MacTurkish", "",
60 "ISO-8859-13", "CP1257", "",
61 "ISO-2022-JP", "ISO-2022-JP-1", "ISO-2022-JP-2", "EUC-JP", "SHIFT_JIS", "",
62 "ISO-2022-CN", "ISO-2022-CN-EXT", "EUC-CN", "EUC-TW", "BIG5", "BIG5-HKSCS", "",
63 "ISO-2022-KR", "EUC-KR", "",
64 "MacThai", "KOI8-T", "",
65 "ISO-8859-3", "ISO-8859-4", "ISO-8859-10", "ISO-8859-14", "ISO-8859-16", "",
66 "CP850", "CP862", "CP866", "CP874", "CP932", "CP949", "CP950", "CP1133", "CP1258", "",
68 "UTF-7", "UTF-16", "UTF-16BE", "UTF-16LE", "UTF-32", "UTF-32BE", "UTF-32LE",
69 "C99", "JAVA", "UCS-2", "UCS-2BE", "UCS-2LE", "UCS-4", "UCS-4BE", "UCS-4LE", "",
70 "HZ", "GBK", "GB18030", "JOHAB", "ARMSCII-8",
71 "Georgian-Academy", "Georgian-PS", "TIS-620", "MuleLao-1", "VISCII", "TCVN",
72 "HPROMAN8", "NEXTSTEP" };
74 SSA supports charset selection.
75 The following known charsets are used:
77 0 = Ansi - Western European
82 128 = Japanese (Shift JIS)
85 134 = GB2312 Simplified Chinese
86 136 = Big5 Traditional Chinese
93 204 = Russian (Cyrillic)
95 238 = Eastern European
99 static int pi_justification[] = { 0, 1, 2 };
100 static const char *ppsz_justification_text[] = {N_("Center"),N_("Left"),N_("Right")};
102 #define ENCODING_TEXT N_("Subtitles text encoding")
103 #define ENCODING_LONGTEXT N_("Set the encoding used in text subtitles")
104 #define ALIGN_TEXT N_("Subtitles justification")
105 #define ALIGN_LONGTEXT N_("Set the justification of subtitles")
106 #define AUTODETECT_UTF8_TEXT N_("UTF-8 subtitles autodetection")
107 #define AUTODETECT_UTF8_LONGTEXT N_("This enables automatic detection of " \
108 "UTF-8 encoding within subtitles files.")
109 #define FORMAT_TEXT N_("Formatted Subtitles")
110 #define FORMAT_LONGTEXT N_("Some subtitle formats allow for text formatting. " \
111 "VLC partly implements this, but you can choose to disable all formatting.")
115 set_shortname( _("Subtitles"));
116 set_description( _("Text subtitles decoder") );
117 set_capability( "decoder", 50 );
118 set_callbacks( OpenDecoder, CloseDecoder );
119 set_category( CAT_INPUT );
120 set_subcategory( SUBCAT_INPUT_SCODEC );
122 add_integer( "subsdec-align", 0, NULL, ALIGN_TEXT, ALIGN_LONGTEXT,
124 change_integer_list( pi_justification, ppsz_justification_text, 0 );
125 add_string( "subsdec-encoding", DEFAULT_NAME, NULL,
126 ENCODING_TEXT, ENCODING_LONGTEXT, false );
127 change_string_list( ppsz_encodings, 0, 0 );
128 add_bool( "subsdec-autodetect-utf8", true, NULL,
129 AUTODETECT_UTF8_TEXT, AUTODETECT_UTF8_LONGTEXT, false );
130 add_bool( "subsdec-formatted", true, NULL, FORMAT_TEXT, FORMAT_LONGTEXT,
134 /*****************************************************************************
135 * OpenDecoder: probe the decoder and return score
136 *****************************************************************************
137 * Tries to launch a decoder and return score so that the interface is able
139 *****************************************************************************/
140 static int OpenDecoder( vlc_object_t *p_this )
142 decoder_t *p_dec = (decoder_t*)p_this;
143 decoder_sys_t *p_sys;
146 switch( p_dec->fmt_in.i_codec )
148 case VLC_FOURCC('s','u','b','t'):
149 case VLC_FOURCC('s','s','a',' '):
150 case VLC_FOURCC('t','1','4','0'):
156 p_dec->pf_decode_sub = DecodeBlock;
158 /* Allocate the memory needed to store the decoder's structure */
159 p_dec->p_sys = p_sys = malloc( sizeof( *p_sys ) );
162 msg_Err( p_dec, "out of memory" );
167 memset( p_sys, 0, sizeof( *p_sys ) );
169 p_sys->iconv_handle = (vlc_iconv_t)-1;
170 p_sys->b_autodetect_utf8 = false;
171 p_sys->b_ass = false;
172 p_sys->i_original_height = -1;
173 p_sys->i_original_width = -1;
174 TAB_INIT( p_sys->i_ssa_styles, p_sys->pp_ssa_styles );
175 TAB_INIT( p_sys->i_images, p_sys->pp_images );
177 char *psz_charset = NULL;
179 /* First try demux-specified encoding */
180 if( p_dec->fmt_in.i_codec == VLC_FOURCC('t','1','4','0') )
181 psz_charset = strdup( "UTF-8" ); /* IUT T.140 is always using UTF-8 */
183 if( p_dec->fmt_in.subs.psz_encoding && *p_dec->fmt_in.subs.psz_encoding )
185 psz_charset = strdup (p_dec->fmt_in.subs.psz_encoding);
186 msg_Dbg (p_dec, "trying demuxer-specified character encoding: %s",
187 p_dec->fmt_in.subs.psz_encoding ?: "not specified");
190 /* Second, try configured encoding */
191 if (psz_charset == NULL)
193 psz_charset = var_CreateGetNonEmptyString (p_dec, "subsdec-encoding");
194 if ((psz_charset != NULL) && !strcasecmp (psz_charset, DEFAULT_NAME))
200 msg_Dbg (p_dec, "trying configured character encoding: %s",
201 psz_charset ?: "not specified");
204 /* Third, try "local" encoding with optional UTF-8 autodetection */
205 if (psz_charset == NULL)
207 psz_charset = strdup (GetFallbackEncoding ());
208 msg_Dbg (p_dec, "trying default character encoding: %s",
209 psz_charset ?: "not specified");
211 if (var_CreateGetBool (p_dec, "subsdec-autodetect-utf8"))
213 msg_Dbg (p_dec, "using automatic UTF-8 detection");
214 p_sys->b_autodetect_utf8 = true;
218 /* Forth, don't do character decoding, i.e. assume UTF-8 */
219 if (psz_charset == NULL)
221 psz_charset = strdup ("UTF-8");
222 msg_Dbg (p_dec, "using UTF-8 character encoding" );
225 if ((psz_charset != NULL)
226 && strcasecmp (psz_charset, "UTF-8")
227 && strcasecmp (psz_charset, "utf8"))
229 p_sys->iconv_handle = vlc_iconv_open ("UTF-8", psz_charset);
230 if (p_sys->iconv_handle == (vlc_iconv_t)(-1))
231 msg_Err (p_dec, "cannot convert from %s: %m", psz_charset);
235 var_Create( p_dec, "subsdec-align", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
236 var_Get( p_dec, "subsdec-align", &val );
237 p_sys->i_align = val.i_int;
239 if( p_dec->fmt_in.i_codec == VLC_FOURCC('s','s','a',' ')
240 && var_CreateGetBool( p_dec, "subsdec-formatted" ) )
242 if( p_dec->fmt_in.i_extra > 0 )
243 ParseSSAHeader( p_dec );
249 /****************************************************************************
250 * DecodeBlock: the whole thing
251 ****************************************************************************
252 * This function must be fed with complete subtitles units.
253 ****************************************************************************/
254 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
256 subpicture_t *p_spu = NULL;
258 if( !pp_block || *pp_block == NULL ) return NULL;
260 p_spu = ParseText( p_dec, *pp_block );
262 block_Release( *pp_block );
268 /*****************************************************************************
269 * CloseDecoder: clean up the decoder
270 *****************************************************************************/
271 static void CloseDecoder( vlc_object_t *p_this )
273 decoder_t *p_dec = (decoder_t *)p_this;
274 decoder_sys_t *p_sys = p_dec->p_sys;
276 if( p_sys->iconv_handle != (vlc_iconv_t)-1 )
277 vlc_iconv_close( p_sys->iconv_handle );
279 if( p_sys->pp_ssa_styles )
282 for( i = 0; i < p_sys->i_ssa_styles; i++ )
284 if( !p_sys->pp_ssa_styles[i] )
287 free( p_sys->pp_ssa_styles[i]->psz_stylename );
288 free( p_sys->pp_ssa_styles[i]->font_style.psz_fontname );
289 free( p_sys->pp_ssa_styles[i] );
291 TAB_CLEAN( p_sys->i_ssa_styles, p_sys->pp_ssa_styles );
293 if( p_sys->pp_images )
296 for( i = 0; i < p_sys->i_images; i++ )
298 if( !p_sys->pp_images[i] )
301 if( p_sys->pp_images[i]->p_pic )
302 p_sys->pp_images[i]->p_pic->pf_release( p_sys->pp_images[i]->p_pic );
303 free( p_sys->pp_images[i]->psz_filename );
305 free( p_sys->pp_images[i] );
307 TAB_CLEAN( p_sys->i_images, p_sys->pp_images );
313 /*****************************************************************************
314 * ParseText: parse an text subtitle packet and send it to the video output
315 *****************************************************************************/
316 static subpicture_t *ParseText( decoder_t *p_dec, block_t *p_block )
318 decoder_sys_t *p_sys = p_dec->p_sys;
319 subpicture_t *p_spu = NULL;
320 char *psz_subtitle = NULL;
323 /* We cannot display a subpicture with no date */
324 if( p_block->i_pts == 0 )
326 msg_Warn( p_dec, "subtitle without a date" );
330 /* Check validity of packet data */
331 /* An "empty" line containing only \0 can be used to force
332 and ephemer picture from the screen */
333 if( p_block->i_buffer < 1 )
335 msg_Warn( p_dec, "no subtitle data" );
339 /* Should be resiliant against bad subtitles */
340 psz_subtitle = strndup( (const char *)p_block->p_buffer,
342 if( psz_subtitle == NULL )
345 if( p_sys->iconv_handle == (vlc_iconv_t)-1 )
347 if (EnsureUTF8( psz_subtitle ) == NULL)
349 msg_Err( p_dec, _("failed to convert subtitle encoding.\n"
350 "Try manually setting a character-encoding "
351 "before you open the file.") );
357 if( p_sys->b_autodetect_utf8 )
359 if( IsUTF8( psz_subtitle ) == NULL )
361 msg_Dbg( p_dec, "invalid UTF-8 sequence: "
362 "disabling UTF-8 subtitles autodetection" );
363 p_sys->b_autodetect_utf8 = false;
367 if( !p_sys->b_autodetect_utf8 )
369 size_t inbytes_left = strlen( psz_subtitle );
370 size_t outbytes_left = 6 * inbytes_left;
371 char *psz_new_subtitle = malloc( outbytes_left + 1 );
372 char *psz_convert_buffer_out = psz_new_subtitle;
373 const char *psz_convert_buffer_in = psz_subtitle;
375 size_t ret = vlc_iconv( p_sys->iconv_handle,
376 &psz_convert_buffer_in, &inbytes_left,
377 &psz_convert_buffer_out, &outbytes_left );
379 *psz_convert_buffer_out++ = '\0';
380 free( psz_subtitle );
382 if( ( ret == (size_t)(-1) ) || inbytes_left )
384 free( psz_new_subtitle );
385 msg_Err( p_dec, _("failed to convert subtitle encoding.\n"
386 "Try manually setting a character-encoding "
387 "before you open the file.") );
391 psz_subtitle = realloc( psz_new_subtitle,
392 psz_convert_buffer_out - psz_new_subtitle );
396 /* Create the subpicture unit */
397 p_spu = p_dec->pf_spu_buffer_new( p_dec );
400 msg_Warn( p_dec, "can't get spu buffer" );
401 free( psz_subtitle );
405 p_spu->b_pausable = true;
407 /* Create a new subpicture region */
408 memset( &fmt, 0, sizeof(video_format_t) );
409 fmt.i_chroma = VLC_FOURCC('T','E','X','T');
411 fmt.i_width = fmt.i_height = 0;
412 fmt.i_x_offset = fmt.i_y_offset = 0;
413 p_spu->p_region = p_spu->pf_create_region( VLC_OBJECT(p_dec), &fmt );
414 if( !p_spu->p_region )
416 msg_Err( p_dec, "cannot allocate SPU region" );
417 free( psz_subtitle );
418 p_dec->pf_spu_buffer_del( p_dec, p_spu );
422 /* Decode and format the subpicture unit */
423 if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','s','a',' ') )
425 /* Normal text subs, easy markup */
426 p_spu->p_region->i_align = SUBPICTURE_ALIGN_BOTTOM | p_sys->i_align;
427 p_spu->i_x = p_sys->i_align ? 20 : 0;
430 /* Remove formatting from string */
432 p_spu->p_region->psz_text = StripTags( psz_subtitle );
433 if( var_CreateGetBool( p_dec, "subsdec-formatted" ) )
435 p_spu->p_region->psz_html = CreateHtmlSubtitle( psz_subtitle );
438 p_spu->i_start = p_block->i_pts;
439 p_spu->i_stop = p_block->i_pts + p_block->i_length;
440 p_spu->b_ephemer = (p_block->i_length == 0);
441 p_spu->b_absolute = false;
445 /* Decode SSA/USF strings */
446 if( p_dec->fmt_in.i_codec == VLC_FOURCC('s','s','a',' ') )
447 ParseSSAString( p_dec, psz_subtitle, p_spu );
449 p_spu->i_start = p_block->i_pts;
450 p_spu->i_stop = p_block->i_pts + p_block->i_length;
451 p_spu->b_ephemer = (p_block->i_length == 0);
452 p_spu->b_absolute = false;
453 p_spu->i_original_picture_width = p_sys->i_original_width;
454 p_spu->i_original_picture_height = p_sys->i_original_height;
456 free( psz_subtitle );
461 char* GotoNextLine( char *psz_text )
463 char *p_newline = psz_text;
465 while( p_newline[0] != '\0' )
467 if( p_newline[0] == '\n' || p_newline[0] == '\r' )
470 while( p_newline[0] == '\n' || p_newline[0] == '\r' )
479 /* Function now handles tags with attribute values, and tries
480 * to deal with &' commands too. It no longer modifies the string
481 * in place, so that the original text can be reused
483 static char *StripTags( char *psz_subtitle )
485 char *psz_text_start;
488 psz_text = psz_text_start = malloc( strlen( psz_subtitle ) + 1 );
489 if( !psz_text_start )
492 while( *psz_subtitle )
494 if( *psz_subtitle == '<' )
496 if( strncasecmp( psz_subtitle, "<br/>", 5 ) == 0 )
499 psz_subtitle += strcspn( psz_subtitle, ">" );
501 else if( *psz_subtitle == '&' )
503 if( !strncasecmp( psz_subtitle, "<", 4 ))
506 psz_subtitle += strcspn( psz_subtitle, ";" );
508 else if( !strncasecmp( psz_subtitle, ">", 4 ))
511 psz_subtitle += strcspn( psz_subtitle, ";" );
513 else if( !strncasecmp( psz_subtitle, "&", 5 ))
516 psz_subtitle += strcspn( psz_subtitle, ";" );
518 else if( !strncasecmp( psz_subtitle, """, 6 ))
521 psz_subtitle += strcspn( psz_subtitle, ";" );
525 /* Assume it is just a normal ampersand */
531 *psz_text++ = *psz_subtitle;
537 psz_text_start = realloc( psz_text_start, strlen( psz_text_start ) + 1 );
539 return psz_text_start;
542 /* Try to respect any style tags present in the subtitle string. The main
543 * problem here is a lack of adequate specs for the subtitle formats.
544 * SSA/ASS and USF are both detail spec'ed -- but they are handled elsewhere.
545 * SAMI has a detailed spec, but extensive rework is needed in the demux
546 * code to prevent all this style information being excised, as it presently
548 * That leaves the others - none of which were (I guess) originally intended
549 * to be carrying style information. Over time people have used them that way.
550 * In the absence of specifications from which to work, the tags supported
551 * have been restricted to the simple set permitted by the USF DTD, ie. :
552 * Basic: <br>, <i>, <b>, <u>
564 * There is also the further restriction that the subtitle be well-formed
565 * as an XML entity, ie. the HTML sentence:
566 * <b><i>Bold and Italics</b></i>
567 * doesn't qualify because the tags aren't nested one inside the other.
568 * <text> tags are automatically added to the output to ensure
570 * If the text doesn't qualify for any reason, a NULL string is
571 * returned, and the rendering engine will fall back to the
572 * plain text version of the subtitle.
574 static char *CreateHtmlSubtitle( char *psz_subtitle )
576 char *psz_tag = malloc( ( strlen( psz_subtitle ) / 3 ) + 1 );
577 if( !psz_tag ) return NULL;
578 size_t i_buf_size = strlen( psz_subtitle ) + 100;
579 char *psz_html_start = malloc( i_buf_size );
583 if( psz_html_start != NULL )
585 char *psz_html = psz_html_start;
587 strcpy( psz_html, "<text>" );
590 while( *psz_subtitle )
592 if( *psz_subtitle == '\n' )
594 strcpy( psz_html, "<br/>" );
598 else if( *psz_subtitle == '<' )
600 if( !strncasecmp( psz_subtitle, "<br/>", 5 ))
602 strcpy( psz_html, "<br/>" );
606 else if( !strncasecmp( psz_subtitle, "<b>", 3 ) )
608 strcpy( psz_html, "<b>" );
609 strcat( psz_tag, "b" );
613 else if( !strncasecmp( psz_subtitle, "<i>", 3 ) )
615 strcpy( psz_html, "<i>" );
616 strcat( psz_tag, "i" );
620 else if( !strncasecmp( psz_subtitle, "<u>", 3 ) )
622 strcpy( psz_html, "<u>" );
623 strcat( psz_tag, "u" );
627 else if( !strncasecmp( psz_subtitle, "<font ", 6 ))
629 const char *psz_attribs[] = { "face=\"", "family=\"", "size=\"",
630 "color=\"", "outline-color=\"", "shadow-color=\"",
631 "outline-level=\"", "shadow-level=\"", "back-color=\"",
634 strcpy( psz_html, "<font " );
635 strcat( psz_tag, "f" );
639 while( *psz_subtitle != '>' )
643 for( k=0; psz_attribs[ k ]; k++ )
645 int i_len = strlen( psz_attribs[ k ] );
647 if( !strncasecmp( psz_subtitle, psz_attribs[ k ], i_len ))
649 i_len += strcspn( psz_subtitle + i_len, "\"" ) + 1;
651 strncpy( psz_html, psz_subtitle, i_len );
653 psz_subtitle += i_len;
657 if( psz_attribs[ k ] == NULL )
659 /* Jump over unrecognised tag */
660 int i_len = strcspn( psz_subtitle, "\"" ) + 1;
662 i_len += strcspn( psz_subtitle + i_len, "\"" ) + 1;
663 psz_subtitle += i_len;
665 while (*psz_subtitle == ' ')
666 *psz_html++ = *psz_subtitle++;
668 *psz_html++ = *psz_subtitle++;
670 else if( !strncmp( psz_subtitle, "</", 2 ))
672 bool b_match = false;
673 int i_len = strlen( psz_tag ) - 1;
674 char *psz_lastTag = NULL;
678 psz_lastTag = psz_tag + i_len;
681 switch( *psz_lastTag )
684 b_match = !strncasecmp( psz_subtitle, "</b>", 4 );
688 b_match = !strncasecmp( psz_subtitle, "</i>", 4 );
692 b_match = !strncasecmp( psz_subtitle, "</u>", 4 );
696 b_match = !strncasecmp( psz_subtitle, "</font>", 7 );
703 /* Not well formed -- kill everything */
704 free( psz_html_start );
705 psz_html_start = NULL;
709 strncpy( psz_html, psz_subtitle, i_len );
711 psz_subtitle += i_len;
715 psz_subtitle += strcspn( psz_subtitle, ">" );
718 else if( *psz_subtitle == '&' )
720 if( !strncasecmp( psz_subtitle, "<", 4 ))
722 strcpy( psz_html, "<" );
726 else if( !strncasecmp( psz_subtitle, ">", 4 ))
728 strcpy( psz_html, ">" );
732 else if( !strncasecmp( psz_subtitle, "&", 5 ))
734 strcpy( psz_html, "&" );
740 strcpy( psz_html, "&" );
747 *psz_html = *psz_subtitle;
748 if( psz_html > psz_html_start )
750 /* Check for double whitespace */
751 if((( *psz_html == ' ' ) ||
752 ( *psz_html == '\t' )) &&
753 (( *(psz_html-1) == ' ' ) ||
754 ( *(psz_html-1) == '\t' )))
756 strcpy( psz_html, NO_BREAKING_SPACE );
757 psz_html += strlen( NO_BREAKING_SPACE ) - 1;
764 if( ( size_t )( psz_html - psz_html_start ) > i_buf_size - 10 )
766 int i_len = psz_html - psz_html_start;
769 psz_html_start = realloc( psz_html_start, i_buf_size );
770 psz_html = psz_html_start + i_len;
774 strcpy( psz_html, "</text>" );
777 if( psz_tag[ 0 ] != '\0' )
779 /* Not well formed -- kill everything */
780 free( psz_html_start );
781 psz_html_start = NULL;
783 else if( psz_html_start )
785 /* Shrink the memory requirements */
786 psz_html_start = realloc( psz_html_start, psz_html - psz_html_start + 1 );
790 return psz_html_start;