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 *****************************************************************************/
33 /*****************************************************************************
35 *****************************************************************************/
36 static int OpenDecoder ( vlc_object_t * );
37 static void CloseDecoder ( vlc_object_t * );
39 static subpicture_t *DecodeBlock ( decoder_t *, block_t ** );
40 static subpicture_t *ParseText ( decoder_t *, block_t * );
41 static char *StripTags ( char * );
42 static char *CreateHtmlSubtitle ( char * );
45 /*****************************************************************************
47 *****************************************************************************/
48 static const char *ppsz_encodings[] = { DEFAULT_NAME, "ASCII", "UTF-8", "",
49 "ISO-8859-1", "CP1252", "MacRoman", "MacIceland","ISO-8859-15", "",
50 "ISO-8859-2", "CP1250", "MacCentralEurope", "MacCroatian", "MacRomania", "",
51 "ISO-8859-5", "CP1251", "MacCyrillic", "MacUkraine", "KOI8-R", "KOI8-U", "KOI8-RU", "",
52 "ISO-8859-6", "CP1256", "MacArabic", "",
53 "ISO-8859-7", "CP1253", "MacGreek", "",
54 "ISO-8859-8", "CP1255", "MacHebrew", "",
55 "ISO-8859-9", "CP1254", "MacTurkish", "",
56 "ISO-8859-13", "CP1257", "",
57 "ISO-2022-JP", "ISO-2022-JP-1", "ISO-2022-JP-2", "EUC-JP", "SHIFT_JIS", "",
58 "ISO-2022-CN", "ISO-2022-CN-EXT", "EUC-CN", "EUC-TW", "BIG5", "BIG5-HKSCS", "",
59 "ISO-2022-KR", "EUC-KR", "",
60 "MacThai", "KOI8-T", "",
61 "ISO-8859-3", "ISO-8859-4", "ISO-8859-10", "ISO-8859-14", "ISO-8859-16", "",
62 "CP850", "CP862", "CP866", "CP874", "CP932", "CP949", "CP950", "CP1133", "CP1258", "",
64 "UTF-7", "UTF-16", "UTF-16BE", "UTF-16LE", "UTF-32", "UTF-32BE", "UTF-32LE",
65 "C99", "JAVA", "UCS-2", "UCS-2BE", "UCS-2LE", "UCS-4", "UCS-4BE", "UCS-4LE", "",
66 "HZ", "GBK", "GB18030", "JOHAB", "ARMSCII-8",
67 "Georgian-Academy", "Georgian-PS", "TIS-620", "MuleLao-1", "VISCII", "TCVN",
68 "HPROMAN8", "NEXTSTEP" };
70 SSA supports charset selection.
71 The following known charsets are used:
73 0 = Ansi - Western European
78 128 = Japanese (Shift JIS)
81 134 = GB2312 Simplified Chinese
82 136 = Big5 Traditional Chinese
89 204 = Russian (Cyrillic)
91 238 = Eastern European
95 static int pi_justification[] = { 0, 1, 2 };
96 static const char *ppsz_justification_text[] = {N_("Center"),N_("Left"),N_("Right")};
98 #define ENCODING_TEXT N_("Subtitles text encoding")
99 #define ENCODING_LONGTEXT N_("Set the encoding used in text subtitles")
100 #define ALIGN_TEXT N_("Subtitles justification")
101 #define ALIGN_LONGTEXT N_("Set the justification of subtitles")
102 #define AUTODETECT_UTF8_TEXT N_("UTF-8 subtitles autodetection")
103 #define AUTODETECT_UTF8_LONGTEXT N_("This enables automatic detection of " \
104 "UTF-8 encoding within subtitles files.")
105 #define FORMAT_TEXT N_("Formatted Subtitles")
106 #define FORMAT_LONGTEXT N_("Some subtitle formats allow for text formatting. " \
107 "VLC partly implements this, but you can choose to disable all formatting.")
111 set_shortname( _("Subtitles"));
112 set_description( _("Text subtitles decoder") );
113 set_capability( "decoder", 50 );
114 set_callbacks( OpenDecoder, CloseDecoder );
115 set_category( CAT_INPUT );
116 set_subcategory( SUBCAT_INPUT_SCODEC );
118 add_integer( "subsdec-align", 0, NULL, ALIGN_TEXT, ALIGN_LONGTEXT,
120 change_integer_list( pi_justification, ppsz_justification_text, 0 );
121 add_string( "subsdec-encoding", DEFAULT_NAME, NULL,
122 ENCODING_TEXT, ENCODING_LONGTEXT, VLC_FALSE );
123 change_string_list( ppsz_encodings, 0, 0 );
124 add_bool( "subsdec-autodetect-utf8", VLC_TRUE, NULL,
125 AUTODETECT_UTF8_TEXT, AUTODETECT_UTF8_LONGTEXT, VLC_FALSE );
126 add_bool( "subsdec-formatted", VLC_TRUE, NULL, FORMAT_TEXT, FORMAT_LONGTEXT,
130 /*****************************************************************************
131 * OpenDecoder: probe the decoder and return score
132 *****************************************************************************
133 * Tries to launch a decoder and return score so that the interface is able
135 *****************************************************************************/
136 static int OpenDecoder( vlc_object_t *p_this )
138 decoder_t *p_dec = (decoder_t*)p_this;
139 decoder_sys_t *p_sys;
142 switch( p_dec->fmt_in.i_codec )
144 case VLC_FOURCC('s','u','b','t'):
145 case VLC_FOURCC('s','s','a',' '):
146 case VLC_FOURCC('t','1','4','0'):
152 p_dec->pf_decode_sub = DecodeBlock;
154 /* Allocate the memory needed to store the decoder's structure */
155 p_dec->p_sys = p_sys = malloc( sizeof( *p_sys ) );
158 msg_Err( p_dec, "out of memory" );
163 memset( p_sys, 0, sizeof( *p_sys ) );
165 p_sys->iconv_handle = (vlc_iconv_t)-1;
166 p_sys->b_autodetect_utf8 = VLC_FALSE;
167 p_sys->b_ass = VLC_FALSE;
168 p_sys->i_original_height = -1;
169 p_sys->i_original_width = -1;
170 TAB_INIT( p_sys->i_ssa_styles, p_sys->pp_ssa_styles );
171 TAB_INIT( p_sys->i_images, p_sys->pp_images );
173 char *psz_charset = NULL;
175 if( p_dec->fmt_in.i_codec == VLC_FOURCC('t','1','4','0') )
176 psz_charset = strdup( "UTF-8" ); /* IUT T.140 is always using UTF-8 */
178 /* First try demux-specified encoding */
179 if( p_dec->fmt_in.subs.psz_encoding && *p_dec->fmt_in.subs.psz_encoding )
181 psz_charset = strdup (p_dec->fmt_in.subs.psz_encoding);
182 msg_Dbg (p_dec, "trying demuxer-specified character encoding: %s",
183 p_dec->fmt_in.subs.psz_encoding ?: "not specified");
186 /* Second, try configured encoding */
187 if (psz_charset == NULL)
189 psz_charset = var_CreateGetNonEmptyString (p_dec, "subsdec-encoding");
190 if ((psz_charset != NULL) && !strcasecmp (psz_charset, DEFAULT_NAME))
196 msg_Dbg (p_dec, "trying configured character encoding: %s",
197 psz_charset ?: "not specified");
200 /* Third, try "local" encoding with optional UTF-8 autodetection */
201 if (psz_charset == NULL)
203 psz_charset = strdup (GetFallbackEncoding ());
204 msg_Dbg (p_dec, "trying default character encoding: %s",
205 psz_charset ?: "not specified");
207 if (var_CreateGetBool (p_dec, "subsdec-autodetect-utf8"))
209 msg_Dbg (p_dec, "using automatic UTF-8 detection");
210 p_sys->b_autodetect_utf8 = VLC_TRUE;
214 if (psz_charset == NULL)
216 psz_charset = strdup ("UTF-8");
217 msg_Dbg (p_dec, "trying hard-coded character encoding: %s",
218 psz_charset ? psz_charset : "error");
221 if (psz_charset == NULL)
227 if (strcasecmp (psz_charset, "UTF-8") && 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: %s", psz_charset,
236 var_Create( p_dec, "subsdec-align", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
237 var_Get( p_dec, "subsdec-align", &val );
238 p_sys->i_align = val.i_int;
240 if( p_dec->fmt_in.i_codec == VLC_FOURCC('s','s','a',' ')
241 && var_CreateGetBool( p_dec, "subsdec-formatted" ) )
243 if( p_dec->fmt_in.i_extra > 0 )
244 ParseSSAHeader( p_dec );
250 /****************************************************************************
251 * DecodeBlock: the whole thing
252 ****************************************************************************
253 * This function must be fed with complete subtitles units.
254 ****************************************************************************/
255 static subpicture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
257 subpicture_t *p_spu = NULL;
259 if( !pp_block || *pp_block == NULL ) return NULL;
261 p_spu = ParseText( p_dec, *pp_block );
263 block_Release( *pp_block );
269 /*****************************************************************************
270 * CloseDecoder: clean up the decoder
271 *****************************************************************************/
272 static void CloseDecoder( vlc_object_t *p_this )
274 decoder_t *p_dec = (decoder_t *)p_this;
275 decoder_sys_t *p_sys = p_dec->p_sys;
277 if( p_sys->iconv_handle != (vlc_iconv_t)-1 )
278 vlc_iconv_close( p_sys->iconv_handle );
280 if( p_sys->pp_ssa_styles )
283 for( i = 0; i < p_sys->i_ssa_styles; i++ )
285 if( !p_sys->pp_ssa_styles[i] )
288 if( p_sys->pp_ssa_styles[i]->psz_stylename )
289 free( p_sys->pp_ssa_styles[i]->psz_stylename );
290 if( p_sys->pp_ssa_styles[i]->font_style.psz_fontname )
291 free( p_sys->pp_ssa_styles[i]->font_style.psz_fontname );
292 if( p_sys->pp_ssa_styles[i] )
293 free( p_sys->pp_ssa_styles[i] );
295 TAB_CLEAN( p_sys->i_ssa_styles, p_sys->pp_ssa_styles );
297 if( p_sys->pp_images )
300 for( i = 0; i < p_sys->i_images; i++ )
302 if( !p_sys->pp_images[i] )
305 if( p_sys->pp_images[i]->p_pic )
306 p_sys->pp_images[i]->p_pic->pf_release( p_sys->pp_images[i]->p_pic );
307 if( p_sys->pp_images[i]->psz_filename )
308 free( p_sys->pp_images[i]->psz_filename );
310 free( p_sys->pp_images[i] );
312 TAB_CLEAN( p_sys->i_images, p_sys->pp_images );
318 /*****************************************************************************
319 * ParseText: parse an text subtitle packet and send it to the video output
320 *****************************************************************************/
321 static subpicture_t *ParseText( decoder_t *p_dec, block_t *p_block )
323 decoder_sys_t *p_sys = p_dec->p_sys;
324 subpicture_t *p_spu = NULL;
325 char *psz_subtitle = NULL;
328 /* We cannot display a subpicture with no date */
329 if( p_block->i_pts == 0 )
331 msg_Warn( p_dec, "subtitle without a date" );
335 /* Check validity of packet data */
336 /* An "empty" line containing only \0 can be used to force
337 and ephemer picture from the screen */
338 if( p_block->i_buffer < 1 )
340 msg_Warn( p_dec, "no subtitle data" );
344 /* Should be resiliant against bad subtitles */
345 psz_subtitle = strndup( (const char *)p_block->p_buffer,
347 if( psz_subtitle == NULL )
350 if( p_sys->iconv_handle == (vlc_iconv_t)-1 )
352 if (EnsureUTF8( psz_subtitle ) == NULL)
354 msg_Err( p_dec, _("failed to convert subtitle encoding.\n"
355 "Try manually setting a character-encoding "
356 "before you open the file.") );
362 if( p_sys->b_autodetect_utf8 )
364 if( IsUTF8( psz_subtitle ) == NULL )
366 msg_Dbg( p_dec, "invalid UTF-8 sequence: "
367 "disabling UTF-8 subtitles autodetection" );
368 p_sys->b_autodetect_utf8 = VLC_FALSE;
372 if( !p_sys->b_autodetect_utf8 )
374 size_t inbytes_left = strlen( psz_subtitle );
375 size_t outbytes_left = 6 * inbytes_left;
376 char *psz_new_subtitle = malloc( outbytes_left + 1 );
377 char *psz_convert_buffer_out = psz_new_subtitle;
378 const char *psz_convert_buffer_in = psz_subtitle;
380 size_t ret = vlc_iconv( p_sys->iconv_handle,
381 &psz_convert_buffer_in, &inbytes_left,
382 &psz_convert_buffer_out, &outbytes_left );
384 *psz_convert_buffer_out++ = '\0';
385 free( psz_subtitle );
387 if( ( ret == (size_t)(-1) ) || inbytes_left )
389 free( psz_new_subtitle );
390 msg_Err( p_dec, _("failed to convert subtitle encoding.\n"
391 "Try manually setting a character-encoding "
392 "before you open the file.") );
396 psz_subtitle = realloc( psz_new_subtitle,
397 psz_convert_buffer_out - psz_new_subtitle );
401 /* Create the subpicture unit */
402 p_spu = p_dec->pf_spu_buffer_new( p_dec );
405 msg_Warn( p_dec, "can't get spu buffer" );
406 if( psz_subtitle ) free( psz_subtitle );
410 p_spu->b_pausable = VLC_TRUE;
412 /* Create a new subpicture region */
413 memset( &fmt, 0, sizeof(video_format_t) );
414 fmt.i_chroma = VLC_FOURCC('T','E','X','T');
416 fmt.i_width = fmt.i_height = 0;
417 fmt.i_x_offset = fmt.i_y_offset = 0;
418 p_spu->p_region = p_spu->pf_create_region( VLC_OBJECT(p_dec), &fmt );
419 if( !p_spu->p_region )
421 msg_Err( p_dec, "cannot allocate SPU region" );
422 if( psz_subtitle ) free( psz_subtitle );
423 p_dec->pf_spu_buffer_del( p_dec, p_spu );
427 /* Decode and format the subpicture unit */
428 if( p_dec->fmt_in.i_codec != VLC_FOURCC('s','s','a',' ') )
430 /* Normal text subs, easy markup */
431 p_spu->p_region->i_align = SUBPICTURE_ALIGN_BOTTOM | p_sys->i_align;
432 p_spu->i_x = p_sys->i_align ? 20 : 0;
435 /* Remove formatting from string */
437 p_spu->p_region->psz_text = StripTags( psz_subtitle );
438 if( var_CreateGetBool( p_dec, "subsdec-formatted" ) )
440 p_spu->p_region->psz_html = CreateHtmlSubtitle( psz_subtitle );
443 p_spu->i_start = p_block->i_pts;
444 p_spu->i_stop = p_block->i_pts + p_block->i_length;
445 p_spu->b_ephemer = (p_block->i_length == 0);
446 p_spu->b_absolute = VLC_FALSE;
450 /* Decode SSA/USF strings */
451 if( p_dec->fmt_in.i_codec == VLC_FOURCC('s','s','a',' ') )
452 ParseSSAString( p_dec, psz_subtitle, p_spu );
454 p_spu->i_start = p_block->i_pts;
455 p_spu->i_stop = p_block->i_pts + p_block->i_length;
456 p_spu->b_ephemer = (p_block->i_length == 0);
457 p_spu->b_absolute = VLC_FALSE;
458 p_spu->i_original_picture_width = p_sys->i_original_width;
459 p_spu->i_original_picture_height = p_sys->i_original_height;
461 if( psz_subtitle ) free( psz_subtitle );
466 char* GotoNextLine( char *psz_text )
468 char *p_newline = psz_text;
470 while( p_newline[0] != '\0' )
472 if( p_newline[0] == '\n' || p_newline[0] == '\r' )
475 while( p_newline[0] == '\n' || p_newline[0] == '\r' )
484 /* Function now handles tags with attribute values, and tries
485 * to deal with &' commands too. It no longer modifies the string
486 * in place, so that the original text can be reused
488 static char *StripTags( char *psz_subtitle )
490 char *psz_text_start;
493 psz_text = psz_text_start = malloc( strlen( psz_subtitle ) + 1 );
494 if( !psz_text_start )
497 while( *psz_subtitle )
499 if( *psz_subtitle == '<' )
501 if( strncasecmp( psz_subtitle, "<br/>", 5 ) == 0 )
504 psz_subtitle += strcspn( psz_subtitle, ">" );
506 else if( *psz_subtitle == '&' )
508 if( !strncasecmp( psz_subtitle, "<", 4 ))
511 psz_subtitle += strcspn( psz_subtitle, ";" );
513 else if( !strncasecmp( psz_subtitle, ">", 4 ))
516 psz_subtitle += strcspn( psz_subtitle, ";" );
518 else if( !strncasecmp( psz_subtitle, "&", 5 ))
521 psz_subtitle += strcspn( psz_subtitle, ";" );
523 else if( !strncasecmp( psz_subtitle, """, 6 ))
526 psz_subtitle += strcspn( psz_subtitle, ";" );
530 /* Assume it is just a normal ampersand */
536 *psz_text++ = *psz_subtitle;
542 psz_text_start = realloc( psz_text_start, strlen( psz_text_start ) + 1 );
544 return psz_text_start;
547 /* Try to respect any style tags present in the subtitle string. The main
548 * problem here is a lack of adequate specs for the subtitle formats.
549 * SSA/ASS and USF are both detail spec'ed -- but they are handled elsewhere.
550 * SAMI has a detailed spec, but extensive rework is needed in the demux
551 * code to prevent all this style information being excised, as it presently
553 * That leaves the others - none of which were (I guess) originally intended
554 * to be carrying style information. Over time people have used them that way.
555 * In the absence of specifications from which to work, the tags supported
556 * have been restricted to the simple set permitted by the USF DTD, ie. :
557 * Basic: <br>, <i>, <b>, <u>
569 * There is also the further restriction that the subtitle be well-formed
570 * as an XML entity, ie. the HTML sentence:
571 * <b><i>Bold and Italics</b></i>
572 * doesn't qualify because the tags aren't nested one inside the other.
573 * <text> tags are automatically added to the output to ensure
575 * If the text doesn't qualify for any reason, a NULL string is
576 * returned, and the rendering engine will fall back to the
577 * plain text version of the subtitle.
579 static char *CreateHtmlSubtitle( char *psz_subtitle )
581 char psz_tagStack[ 100 ];
582 size_t i_buf_size = strlen( psz_subtitle ) + 100;
583 char *psz_html_start = malloc( i_buf_size );
585 psz_tagStack[ 0 ] = '\0';
587 if( psz_html_start != NULL )
589 char *psz_html = psz_html_start;
591 strcpy( psz_html, "<text>" );
594 while( *psz_subtitle )
596 if( *psz_subtitle == '\n' )
598 strcpy( psz_html, "<br/>" );
602 else if( *psz_subtitle == '<' )
604 if( !strncasecmp( psz_subtitle, "<br/>", 5 ))
606 strcpy( psz_html, "<br/>" );
610 else if( !strncasecmp( psz_subtitle, "<b>", 3 ) )
612 strcpy( psz_html, "<b>" );
613 strcat( psz_tagStack, "b" );
617 else if( !strncasecmp( psz_subtitle, "<i>", 3 ) )
619 strcpy( psz_html, "<i>" );
620 strcat( psz_tagStack, "i" );
624 else if( !strncasecmp( psz_subtitle, "<u>", 3 ) )
626 strcpy( psz_html, "<u>" );
627 strcat( psz_tagStack, "u" );
631 else if( !strncasecmp( psz_subtitle, "<font ", 6 ))
633 const char *psz_attribs[] = { "face=\"", "family=\"", "size=\"",
634 "color=\"", "outline-color=\"", "shadow-color=\"",
635 "outline-level=\"", "shadow-level=\"", "back-color=\"",
638 strcpy( psz_html, "<font " );
639 strcat( psz_tagStack, "f" );
643 while( *psz_subtitle != '>' )
647 for( k=0; psz_attribs[ k ]; k++ )
649 int i_len = strlen( psz_attribs[ k ] );
651 if( !strncasecmp( psz_subtitle, psz_attribs[ k ], i_len ))
653 i_len += strcspn( psz_subtitle + i_len, "\"" ) + 1;
655 strncpy( psz_html, psz_subtitle, i_len );
657 psz_subtitle += i_len;
661 if( psz_attribs[ k ] == NULL )
663 /* Jump over unrecognised tag */
664 int i_len = strcspn( psz_subtitle, "\"" ) + 1;
666 i_len += strcspn( psz_subtitle + i_len, "\"" ) + 1;
667 psz_subtitle += i_len;
669 while (*psz_subtitle == ' ')
670 *psz_html++ = *psz_subtitle++;
672 *psz_html++ = *psz_subtitle++;
674 else if( !strncmp( psz_subtitle, "</", 2 ))
676 vlc_bool_t b_match = VLC_FALSE;
677 int i_len = strlen( psz_tagStack ) - 1;
678 char *psz_lastTag = NULL;
682 psz_lastTag = psz_tagStack + i_len;
685 switch( *psz_lastTag )
688 b_match = !strncasecmp( psz_subtitle, "</b>", 4 );
692 b_match = !strncasecmp( psz_subtitle, "</i>", 4 );
696 b_match = !strncasecmp( psz_subtitle, "</u>", 4 );
700 b_match = !strncasecmp( psz_subtitle, "</font>", 7 );
707 /* Not well formed -- kill everything */
708 free( psz_html_start );
709 psz_html_start = NULL;
713 strncpy( psz_html, psz_subtitle, i_len );
715 psz_subtitle += i_len;
719 psz_subtitle += strcspn( psz_subtitle, ">" );
722 else if( *psz_subtitle == '&' )
724 if( !strncasecmp( psz_subtitle, "<", 4 ))
726 strcpy( psz_html, "<" );
730 else if( !strncasecmp( psz_subtitle, ">", 4 ))
732 strcpy( psz_html, ">" );
736 else if( !strncasecmp( psz_subtitle, "&", 5 ))
738 strcpy( psz_html, "&" );
744 strcpy( psz_html, "&" );
751 *psz_html = *psz_subtitle;
752 if( psz_html > psz_html_start )
754 /* Check for double whitespace */
755 if((( *psz_html == ' ' ) ||
756 ( *psz_html == '\t' )) &&
757 (( *(psz_html-1) == ' ' ) ||
758 ( *(psz_html-1) == '\t' )))
760 strcpy( psz_html, NO_BREAKING_SPACE );
761 psz_html += strlen( NO_BREAKING_SPACE ) - 1;
768 if( ( size_t )( psz_html - psz_html_start ) > i_buf_size - 10 )
770 int i_len = psz_html - psz_html_start;
773 psz_html_start = realloc( psz_html_start, i_buf_size );
774 psz_html = psz_html_start + i_len;
778 strcpy( psz_html, "</text>" );
781 if( psz_tagStack[ 0 ] != '\0' )
783 /* Not well formed -- kill everything */
784 free( psz_html_start );
785 psz_html_start = NULL;
787 else if( psz_html_start )
789 /* Shrink the memory requirements */
790 psz_html_start = realloc( psz_html_start, psz_html - psz_html_start + 1 );
793 return psz_html_start;