]> git.sesse.net Git - vlc/blob - modules/demux/subtitle.c
Fixed potential sscanf buffer overflow in :
[vlc] / modules / demux / subtitle.c
1 /*****************************************************************************
2  * subtitle.c: Demux for subtitle text files.
3  *****************************************************************************
4  * Copyright (C) 1999-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Derk-Jan Hartman <hartman at videolan dot org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29 #include <vlc_input.h>
30
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include <errno.h>
35 #ifdef HAVE_SYS_TYPES_H
36 #   include <sys/types.h>
37 #endif
38 #include <ctype.h>
39
40 #include <vlc_demux.h>
41 #include <vlc_charset.h>
42
43 /*****************************************************************************
44  * Module descriptor
45  *****************************************************************************/
46 static int  Open ( vlc_object_t *p_this );
47 static void Close( vlc_object_t *p_this );
48
49 #define SUB_DELAY_LONGTEXT \
50     N_("Apply a delay to all subtitles (in 1/10s, eg 100 means 10s).")
51 #define SUB_FPS_LONGTEXT \
52     N_("Override the normal frames per second settings. " \
53     "This will only work with MicroDVD and SubRIP (SRT) subtitles.")
54 #define SUB_TYPE_LONGTEXT \
55     N_("Force the subtiles format. Valid values are : \"microdvd\", " \
56     "\"subrip\",  \"ssa1\", \"ssa2-4\", \"ass\", \"vplayer\" " \
57     "\"sami\", \"dvdsubtitle\", \"mpl2\" and \"auto\" (meaning autodetection, this " \
58     "should always work).")
59 static const char *ppsz_sub_type[] =
60 {
61     "auto", "microdvd", "subrip", "subviewer", "ssa1",
62     "ssa2-4", "ass", "vplayer", "sami", "dvdsubtitle", "mpl2"
63 };
64
65 vlc_module_begin();
66     set_shortname( _("Subtitles"));
67     set_description( _("Text subtitles parser") );
68     set_capability( "demux2", 0 );
69     set_category( CAT_INPUT );
70     set_subcategory( SUBCAT_INPUT_DEMUX );
71     add_float( "sub-fps", 0.0, NULL,
72                N_("Frames per second"),
73                SUB_FPS_LONGTEXT, VLC_TRUE );
74     add_integer( "sub-delay", 0, NULL,
75                N_("Subtitles delay"),
76                SUB_DELAY_LONGTEXT, VLC_TRUE );
77     add_string( "sub-type", "auto", NULL, N_("Subtitles format"),
78                 SUB_TYPE_LONGTEXT, VLC_TRUE );
79         change_string_list( ppsz_sub_type, NULL, NULL );
80     set_callbacks( Open, Close );
81
82     add_shortcut( "subtitle" );
83 vlc_module_end();
84
85 /*****************************************************************************
86  * Prototypes:
87  *****************************************************************************/
88 enum
89 {
90     SUB_TYPE_UNKNOWN = -1,
91     SUB_TYPE_MICRODVD,
92     SUB_TYPE_SUBRIP,
93     SUB_TYPE_SSA1,
94     SUB_TYPE_SSA2_4,
95     SUB_TYPE_ASS,
96     SUB_TYPE_VPLAYER,
97     SUB_TYPE_SAMI,
98     SUB_TYPE_SUBVIEWER,
99     SUB_TYPE_DVDSUBTITLE,
100     SUB_TYPE_MPL2
101 };
102
103 typedef struct
104 {
105     int     i_line_count;
106     int     i_line;
107     char    **line;
108 } text_t;
109 static int  TextLoad( text_t *, stream_t *s );
110 static void TextUnload( text_t * );
111
112 typedef struct
113 {
114     int64_t i_start;
115     int64_t i_stop;
116
117     char    *psz_text;
118 } subtitle_t;
119
120
121 struct demux_sys_t
122 {
123     int         i_type;
124     text_t      txt;
125     es_out_id_t *es;
126
127     int64_t     i_next_demux_date;
128     int64_t     i_microsecperframe;
129
130     char        *psz_header;
131     int         i_subtitle;
132     int         i_subtitles;
133     subtitle_t  *subtitle;
134
135     int64_t     i_length;
136 };
137
138 static int  ParseMicroDvd   ( demux_t *, subtitle_t * );
139 static int  ParseSubRip     ( demux_t *, subtitle_t * );
140 static int  ParseSubViewer  ( demux_t *, subtitle_t * );
141 static int  ParseSSA        ( demux_t *, subtitle_t * );
142 static int  ParseVplayer    ( demux_t *, subtitle_t * );
143 static int  ParseSami       ( demux_t *, subtitle_t * );
144 static int  ParseDVDSubtitle( demux_t *, subtitle_t * );
145 static int  ParseMPL2       ( demux_t *, subtitle_t * );
146
147 static struct
148 {
149     const char *psz_type_name;
150     int  i_type;
151     const char *psz_name;
152     int  (*pf_read)( demux_t *, subtitle_t* );
153 } sub_read_subtitle_function [] =
154 {
155     { "microdvd",   SUB_TYPE_MICRODVD,    "MicroDVD",    ParseMicroDvd },
156     { "subrip",     SUB_TYPE_SUBRIP,      "SubRIP",      ParseSubRip },
157     { "subviewer",  SUB_TYPE_SUBVIEWER,   "SubViewer",   ParseSubViewer },
158     { "ssa1",       SUB_TYPE_SSA1,        "SSA-1",       ParseSSA },
159     { "ssa2-4",     SUB_TYPE_SSA2_4,      "SSA-2/3/4",   ParseSSA },
160     { "ass",        SUB_TYPE_ASS,         "SSA/ASS",     ParseSSA },
161     { "vplayer",    SUB_TYPE_VPLAYER,     "VPlayer",     ParseVplayer },
162     { "sami",       SUB_TYPE_SAMI,        "SAMI",        ParseSami },
163     { "dvdsubtitle",SUB_TYPE_DVDSUBTITLE, "DVDSubtitle", ParseDVDSubtitle },
164     { "mpl2",       SUB_TYPE_MPL2,        "MPL2",        ParseMPL2 },
165     { NULL,         SUB_TYPE_UNKNOWN,     "Unknown",     NULL }
166 };
167
168 static int Demux( demux_t * );
169 static int Control( demux_t *, int, va_list );
170
171 /*static void Fix( demux_t * );*/
172
173 /*****************************************************************************
174  * Module initializer
175  *****************************************************************************/
176 static int Open ( vlc_object_t *p_this )
177 {
178     demux_t        *p_demux = (demux_t*)p_this;
179     demux_sys_t    *p_sys;
180     es_format_t    fmt;
181     input_thread_t *p_input;
182     float          f_fps;
183     char           *psz_type;
184     int  (*pf_read)( demux_t *, subtitle_t* );
185     int            i, i_max;
186
187     if( strcmp( p_demux->psz_demux, "subtitle" ) )
188     {
189         msg_Dbg( p_demux, "subtitle demux discarded" );
190         return VLC_EGENERIC;
191     }
192
193     p_demux->pf_demux = Demux;
194     p_demux->pf_control = Control;
195     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
196     p_sys->psz_header         = NULL;
197     p_sys->i_subtitle         = 0;
198     p_sys->i_subtitles        = 0;
199     p_sys->subtitle           = NULL;
200     p_sys->i_microsecperframe = 40000;
201
202     /* Get the FPS */
203     p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT );
204     if( p_input )
205     {
206         f_fps = var_GetFloat( p_input, "sub-original-fps" );
207         if( f_fps >= 1.0 )
208             p_sys->i_microsecperframe = (int64_t)( (float)1000000 / f_fps );
209
210         msg_Dbg( p_demux, "Movie fps: %f", f_fps );
211         vlc_object_release( p_input );
212     }
213
214     /* Check for override of the fps */
215     f_fps = var_CreateGetFloat( p_demux, "sub-fps" );
216     if( f_fps >= 1.0 )
217     {
218         p_sys->i_microsecperframe = (int64_t)( (float)1000000 / f_fps );
219         msg_Dbg( p_demux, "Override subtitle fps %f", f_fps );
220     }
221
222     /* Get or probe the type */
223     p_sys->i_type = SUB_TYPE_UNKNOWN;
224     psz_type = var_CreateGetString( p_demux, "sub-type" );
225     if( *psz_type )
226     {
227         int i;
228
229         for( i = 0; ; i++ )
230         {
231             if( sub_read_subtitle_function[i].psz_type_name == NULL )
232                 break;
233
234             if( !strcmp( sub_read_subtitle_function[i].psz_type_name,
235                          psz_type ) )
236             {
237                 p_sys->i_type = sub_read_subtitle_function[i].i_type;
238                 break;
239             }
240         }
241     }
242     free( psz_type );
243
244     /* Probe if unknown type */
245     if( p_sys->i_type == SUB_TYPE_UNKNOWN )
246     {
247         int     i_try;
248         char    *s = NULL;
249
250         msg_Dbg( p_demux, "autodetecting subtitle format" );
251         for( i_try = 0; i_try < 256; i_try++ )
252         {
253             int i_dummy;
254
255             if( ( s = stream_ReadLine( p_demux->s ) ) == NULL )
256                 break;
257
258             if( strcasestr( s, "<SAMI>" ) )
259             {
260                 p_sys->i_type = SUB_TYPE_SAMI;
261                 break;
262             }
263             else if( sscanf( s, "{%d}{%d}", &i_dummy, &i_dummy ) == 2 ||
264                      sscanf( s, "{%d}{}", &i_dummy ) == 1)
265             {
266                 p_sys->i_type = SUB_TYPE_MICRODVD;
267                 break;
268             }
269             else if( sscanf( s,
270                              "%d:%d:%d,%d --> %d:%d:%d,%d",
271                              &i_dummy,&i_dummy,&i_dummy,&i_dummy,
272                              &i_dummy,&i_dummy,&i_dummy,&i_dummy ) == 8 )
273             {
274                 p_sys->i_type = SUB_TYPE_SUBRIP;
275                 break;
276             }
277             else if( !strncasecmp( s, "!: This is a Sub Station Alpha v1", 33 ) )
278             {
279                 p_sys->i_type = SUB_TYPE_SSA1;
280                 break;
281             }
282             else if( !strncasecmp( s, "ScriptType: v4.00+", 18 ) )
283             {
284                 p_sys->i_type = SUB_TYPE_ASS;
285                 break;
286             }
287             else if( !strncasecmp( s, "ScriptType: v4.00", 17 ) )
288             {
289                 p_sys->i_type = SUB_TYPE_SSA2_4;
290                 break;
291             }
292             else if( !strncasecmp( s, "Dialogue: Marked", 16  ) )
293             {
294                 p_sys->i_type = SUB_TYPE_SSA2_4;
295                 break;
296             }
297             else if( !strncasecmp( s, "Dialogue:", 9  ) )
298             {
299                 p_sys->i_type = SUB_TYPE_ASS;
300                 break;
301             }
302             else if( strcasestr( s, "[INFORMATION]" ) )
303             {
304                 p_sys->i_type = SUB_TYPE_SUBVIEWER; /* I hope this will work */
305                 break;
306             }
307             else if( sscanf( s, "%d:%d:%d:", &i_dummy, &i_dummy, &i_dummy ) == 3 ||
308                      sscanf( s, "%d:%d:%d ", &i_dummy, &i_dummy, &i_dummy ) == 3 )
309             {
310                 p_sys->i_type = SUB_TYPE_VPLAYER;
311                 break;
312             }
313             else if( sscanf( s, "{T %d:%d:%d:%d", &i_dummy, &i_dummy,
314                              &i_dummy, &i_dummy ) == 4 )
315             {
316                 p_sys->i_type = SUB_TYPE_DVDSUBTITLE;
317                 break;
318             }
319             else if( sscanf( s, "[%d][%d]", &i_dummy, &i_dummy ) == 2 ||
320                      sscanf( s, "[%d][]", &i_dummy ) == 1)
321             {
322                 p_sys->i_type = SUB_TYPE_MPL2;
323                 break;
324             }
325
326             free( s );
327             s = NULL;
328         }
329
330         if( s ) free( s );
331
332         /* It will nearly always work even for non seekable stream thanks the
333          * caching system, and if it fails we lose just a few sub */
334         if( stream_Seek( p_demux->s, 0 ) )
335         {
336             msg_Warn( p_demux, "failed to rewind" );
337         }
338     }
339     if( p_sys->i_type == SUB_TYPE_UNKNOWN )
340     {
341         msg_Err( p_demux, "failed to recognize subtitle type" );
342         free( p_sys );
343         return VLC_EGENERIC;
344     }
345
346     for( i = 0; ; i++ )
347     {
348         if( sub_read_subtitle_function[i].i_type == p_sys->i_type )
349         {
350             msg_Dbg( p_demux, "detected %s format",
351                      sub_read_subtitle_function[i].psz_name );
352             pf_read = sub_read_subtitle_function[i].pf_read;
353             break;
354         }
355     }
356
357     msg_Dbg( p_demux, "loading all subtitles..." );
358
359     /* Load the whole file */
360     TextLoad( &p_sys->txt, p_demux->s );
361
362     /* Parse it */
363     for( i_max = 0;; )
364     {
365         if( p_sys->i_subtitles >= i_max )
366         {
367             i_max += 500;
368             if( !( p_sys->subtitle = realloc( p_sys->subtitle,
369                                               sizeof(subtitle_t) * i_max ) ) )
370             {
371                 msg_Err( p_demux, "out of memory");
372                 if( p_sys->subtitle != NULL )
373                     free( p_sys->subtitle );
374                 TextUnload( &p_sys->txt );
375                 free( p_sys );
376                 return VLC_ENOMEM;
377             }
378         }
379
380         if( pf_read( p_demux, &p_sys->subtitle[p_sys->i_subtitles] ) )
381             break;
382
383         p_sys->i_subtitles++;
384     }
385     /* Unload */
386     TextUnload( &p_sys->txt );
387
388     msg_Dbg(p_demux, "loaded %d subtitles", p_sys->i_subtitles );
389
390     /* Fix subtitle (order and time) *** */
391     p_sys->i_subtitle = 0;
392     p_sys->i_length = 0;
393     if( p_sys->i_subtitles > 0 )
394     {
395         p_sys->i_length = p_sys->subtitle[p_sys->i_subtitles-1].i_stop;
396         /* +1 to avoid 0 */
397         if( p_sys->i_length <= 0 )
398             p_sys->i_length = p_sys->subtitle[p_sys->i_subtitles-1].i_start+1;
399     }
400
401     /* *** add subtitle ES *** */
402     if( p_sys->i_type == SUB_TYPE_SSA1 ||
403              p_sys->i_type == SUB_TYPE_SSA2_4 ||
404              p_sys->i_type == SUB_TYPE_ASS )
405     {
406         es_format_Init( &fmt, SPU_ES, VLC_FOURCC( 's','s','a',' ' ) );
407     }
408     else
409     {
410         es_format_Init( &fmt, SPU_ES, VLC_FOURCC( 's','u','b','t' ) );
411     }
412     if( p_sys->psz_header != NULL )
413     {
414         fmt.i_extra = strlen( p_sys->psz_header ) + 1;
415         fmt.p_extra = strdup( p_sys->psz_header );
416     }
417     p_sys->es = es_out_Add( p_demux->out, &fmt );
418
419     return VLC_SUCCESS;
420 }
421
422 /*****************************************************************************
423  * Close: Close subtitle demux
424  *****************************************************************************/
425 static void Close( vlc_object_t *p_this )
426 {
427     demux_t *p_demux = (demux_t*)p_this;
428     demux_sys_t *p_sys = p_demux->p_sys;
429     int i;
430
431     for( i = 0; i < p_sys->i_subtitles; i++ )
432     {
433         if( p_sys->subtitle[i].psz_text )
434             free( p_sys->subtitle[i].psz_text );
435     }
436     if( p_sys->subtitle )
437         free( p_sys->subtitle );
438
439     free( p_sys );
440 }
441
442 /*****************************************************************************
443  * Control:
444  *****************************************************************************/
445 static int Control( demux_t *p_demux, int i_query, va_list args )
446 {
447     demux_sys_t *p_sys = p_demux->p_sys;
448     int64_t *pi64, i64;
449     double *pf, f;
450
451     switch( i_query )
452     {
453         case DEMUX_GET_LENGTH:
454             pi64 = (int64_t*)va_arg( args, int64_t * );
455             *pi64 = p_sys->i_length;
456             return VLC_SUCCESS;
457
458         case DEMUX_GET_TIME:
459             pi64 = (int64_t*)va_arg( args, int64_t * );
460             if( p_sys->i_subtitle < p_sys->i_subtitles )
461             {
462                 *pi64 = p_sys->subtitle[p_sys->i_subtitle].i_start;
463                 return VLC_SUCCESS;
464             }
465             return VLC_EGENERIC;
466
467         case DEMUX_SET_TIME:
468             i64 = (int64_t)va_arg( args, int64_t );
469             p_sys->i_subtitle = 0;
470             while( p_sys->i_subtitle < p_sys->i_subtitles &&
471                    p_sys->subtitle[p_sys->i_subtitle].i_start < i64 )
472             {
473                 p_sys->i_subtitle++;
474             }
475
476             if( p_sys->i_subtitle >= p_sys->i_subtitles )
477                 return VLC_EGENERIC;
478             return VLC_SUCCESS;
479
480         case DEMUX_GET_POSITION:
481             pf = (double*)va_arg( args, double * );
482             if( p_sys->i_subtitle >= p_sys->i_subtitles )
483             {
484                 *pf = 1.0;
485             }
486             else if( p_sys->i_subtitles > 0 )
487             {
488                 *pf = (double)p_sys->subtitle[p_sys->i_subtitle].i_start /
489                       (double)p_sys->i_length;
490             }
491             else
492             {
493                 *pf = 0.0;
494             }
495             return VLC_SUCCESS;
496
497         case DEMUX_SET_POSITION:
498             f = (double)va_arg( args, double );
499             i64 = f * p_sys->i_length;
500
501             p_sys->i_subtitle = 0;
502             while( p_sys->i_subtitle < p_sys->i_subtitles &&
503                    p_sys->subtitle[p_sys->i_subtitle].i_start < i64 )
504             {
505                 p_sys->i_subtitle++;
506             }
507             if( p_sys->i_subtitle >= p_sys->i_subtitles )
508                 return VLC_EGENERIC;
509             return VLC_SUCCESS;
510
511         case DEMUX_SET_NEXT_DEMUX_TIME:
512             p_sys->i_next_demux_date = (int64_t)va_arg( args, int64_t );
513             return VLC_SUCCESS;
514
515         case DEMUX_GET_FPS:
516         case DEMUX_GET_META:
517         case DEMUX_GET_ATTACHMENTS:
518         case DEMUX_GET_TITLE_INFO:
519             return VLC_EGENERIC;
520
521         default:
522             msg_Err( p_demux, "unknown query in subtitle control" );
523             return VLC_EGENERIC;
524     }
525 }
526
527 /*****************************************************************************
528  * Demux: Send subtitle to decoder
529  *****************************************************************************/
530 static int Demux( demux_t *p_demux )
531 {
532     demux_sys_t *p_sys = p_demux->p_sys;
533     int64_t i_maxdate;
534
535     if( p_sys->i_subtitle >= p_sys->i_subtitles )
536         return 0;
537
538     i_maxdate = p_sys->i_next_demux_date - var_GetTime( p_demux->p_parent, "spu-delay" );;
539     if( i_maxdate <= 0 && p_sys->i_subtitle < p_sys->i_subtitles )
540     {
541         /* Should not happen */
542         i_maxdate = p_sys->subtitle[p_sys->i_subtitle].i_start + 1;
543     }
544
545     while( p_sys->i_subtitle < p_sys->i_subtitles &&
546            p_sys->subtitle[p_sys->i_subtitle].i_start < i_maxdate )
547     {
548         block_t *p_block;
549         int i_len = strlen( p_sys->subtitle[p_sys->i_subtitle].psz_text ) + 1;
550
551         if( i_len <= 1 )
552         {
553             /* empty subtitle */
554             p_sys->i_subtitle++;
555             continue;
556         }
557
558         if( ( p_block = block_New( p_demux, i_len ) ) == NULL )
559         {
560             p_sys->i_subtitle++;
561             continue;
562         }
563
564         if( p_sys->subtitle[p_sys->i_subtitle].i_start < 0 )
565         {
566             p_sys->i_subtitle++;
567             continue;
568         }
569
570         p_block->i_pts = p_sys->subtitle[p_sys->i_subtitle].i_start;
571         p_block->i_dts = p_block->i_pts;
572         if( p_sys->subtitle[p_sys->i_subtitle].i_stop > 0 )
573         {
574             p_block->i_length =
575                 p_sys->subtitle[p_sys->i_subtitle].i_stop - p_block->i_pts;
576         }
577
578         memcpy( p_block->p_buffer,
579                 p_sys->subtitle[p_sys->i_subtitle].psz_text, i_len );
580         if( p_block->i_pts > 0 )
581         {
582             es_out_Send( p_demux->out, p_sys->es, p_block );
583         }
584         else
585         {
586             block_Release( p_block );
587         }
588         p_sys->i_subtitle++;
589     }
590
591     /* */
592     p_sys->i_next_demux_date = 0;
593
594     return 1;
595 }
596
597 /*****************************************************************************
598  * Fix: fix time stamp and order of subtitle
599  *****************************************************************************/
600 #ifdef USE_THIS_UNUSED_PIECE_OF_CODE
601 static void Fix( demux_t *p_demux )
602 {
603     demux_sys_t *p_sys = p_demux->p_sys;
604     vlc_bool_t b_done;
605     int     i_index;
606
607     /* *** fix order (to be sure...) *** */
608     /* We suppose that there are near in order and this durty bubble sort
609      * wont take too much time
610      */
611     do
612     {
613         b_done = VLC_TRUE;
614         for( i_index = 1; i_index < p_sys->i_subtitles; i_index++ )
615         {
616             if( p_sys->subtitle[i_index].i_start <
617                     p_sys->subtitle[i_index - 1].i_start )
618             {
619                 subtitle_t sub_xch;
620                 memcpy( &sub_xch,
621                         p_sys->subtitle + i_index - 1,
622                         sizeof( subtitle_t ) );
623                 memcpy( p_sys->subtitle + i_index - 1,
624                         p_sys->subtitle + i_index,
625                         sizeof( subtitle_t ) );
626                 memcpy( p_sys->subtitle + i_index,
627                         &sub_xch,
628                         sizeof( subtitle_t ) );
629                 b_done = VLC_FALSE;
630             }
631         }
632     } while( !b_done );
633 }
634 #endif
635
636 static int TextLoad( text_t *txt, stream_t *s )
637 {
638     int   i_line_max;
639
640     /* init txt */
641     i_line_max          = 500;
642     txt->i_line_count   = 0;
643     txt->i_line         = 0;
644     txt->line           = calloc( i_line_max, sizeof( char * ) );
645
646     /* load the complete file */
647     for( ;; )
648     {
649         char *psz = stream_ReadLine( s );
650
651         if( psz == NULL )
652             break;
653
654         txt->line[txt->i_line_count++] = psz;
655         if( txt->i_line_count >= i_line_max )
656         {
657             i_line_max += 100;
658             txt->line = realloc( txt->line, i_line_max * sizeof( char * ) );
659         }
660     }
661
662     if( txt->i_line_count <= 0 )
663     {
664         free( txt->line );
665         return VLC_EGENERIC;
666     }
667
668     return VLC_SUCCESS;
669 }
670 static void TextUnload( text_t *txt )
671 {
672     int i;
673
674     for( i = 0; i < txt->i_line_count; i++ )
675     {
676         free( txt->line[i] );
677     }
678     free( txt->line );
679     txt->i_line       = 0;
680     txt->i_line_count = 0;
681 }
682
683 static char *TextGetLine( text_t *txt )
684 {
685     if( txt->i_line >= txt->i_line_count )
686         return( NULL );
687
688     return txt->line[txt->i_line++];
689 }
690 static void TextPreviousLine( text_t *txt )
691 {
692     if( txt->i_line > 0 )
693         txt->i_line--;
694 }
695
696 /*****************************************************************************
697  * Specific Subtitle function
698  *****************************************************************************/
699 /* ParseMicroDvd:
700  *  Format:
701  *      {n1}{n2}Line1|Line2|Line3....
702  *  where n1 and n2 are the video frame number (n2 can be empty)
703  */
704 static int ParseMicroDvd( demux_t *p_demux, subtitle_t *p_subtitle )
705 {
706     demux_sys_t *p_sys = p_demux->p_sys;
707     text_t      *txt = &p_sys->txt;
708     char *psz_text;
709     int  i_start;
710     int  i_stop;
711     int  i;
712
713     for( ;; )
714     {
715         const char *s = TextGetLine( txt );
716         if( !s )
717             return VLC_EGENERIC;
718
719         psz_text = malloc( strlen(s) + 1 );
720         if( !psz_text )
721             return VLC_ENOMEM;
722
723         i_start = 0;
724         i_stop  = 0;
725         if( sscanf( s, "{%d}{}%[^\r\n]", &i_start, psz_text ) == 2 ||
726             sscanf( s, "{%d}{%d}%[^\r\n]", &i_start, &i_stop, psz_text ) == 3)
727         {
728             float f_fps;
729             if( i_start != 1 || i_stop != 1 )
730                 break;
731
732             /* We found a possible setting of the framerate "{1}{1}23.976" */
733             /* Check if it's usable, and if the sub-fps is not set */
734             f_fps = us_strtod( psz_text, NULL );
735             if( f_fps > 0.0 && var_GetFloat( p_demux, "sub-fps" ) <= 0.0 )
736                 p_sys->i_microsecperframe = (int64_t)((float)1000000 / f_fps);
737         }
738         free( psz_text );
739     }
740
741     /* replace | by \n */
742     for( i = 0; psz_text[i] != '\0'; i++ )
743     {
744         if( psz_text[i] == '|' )
745             psz_text[i] = '\n';
746     }
747
748     /* */
749     p_subtitle->i_start  = i_start * p_sys->i_microsecperframe;
750     p_subtitle->i_stop   = i_stop  * p_sys->i_microsecperframe;
751     p_subtitle->psz_text = psz_text;
752     return VLC_SUCCESS;
753 }
754
755 /* ParseSubRipSubViewer
756  *  Format SubRip
757  *      n
758  *      h1:m1:s1,d1 --> h2:m2:s2,d2
759  *      Line1
760  *      Line2
761  *      ....
762  *      [Empty line]
763  *  Format SubViewer v1/v2
764  *      h1:m1:s1.d1,h2:m2:s2.d2
765  *      Line1[br]Line2
766  *      Line3
767  *      ...
768  *      [empty line]
769  *  We ignore line number for SubRip
770  */
771 static int ParseSubRipSubViewer( demux_t *p_demux, subtitle_t *p_subtitle,
772                                  const char *psz_fmt,
773                                  vlc_bool_t b_replace_br )
774 {
775     demux_sys_t *p_sys = p_demux->p_sys;
776     text_t      *txt = &p_sys->txt;
777     char    *psz_text;
778
779     for( ;; )
780     {
781         const char *s = TextGetLine( txt );
782         int h1, m1, s1, d1, h2, m2, s2, d2;
783
784         if( !s )
785             return VLC_EGENERIC;
786
787         if( sscanf( s, psz_fmt,
788                     &h1, &m1, &s1, &d1,
789                     &h2, &m2, &s2, &d2 ) == 8 )
790         {
791             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
792                                     (int64_t)m1 * 60*1000 +
793                                     (int64_t)s1 * 1000 +
794                                     (int64_t)d1 ) * 1000;
795
796             p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
797                                     (int64_t)m2 * 60*1000 +
798                                     (int64_t)s2 * 1000 +
799                                     (int64_t)d2 ) * 1000;
800             break;
801         }
802     }
803
804     /* Now read text until an empty line */
805     psz_text = strdup("");
806     if( !psz_text )
807         return VLC_ENOMEM;
808     for( ;; )
809     {
810         const char *s = TextGetLine( txt );
811         int i_len;
812         int i_old;
813
814         if( !s )
815         {
816             free( psz_text );
817             return VLC_EGENERIC;
818         }
819
820         i_len = strlen( s );
821         if( i_len <= 0 )
822         {
823             p_subtitle->psz_text = psz_text;
824             return VLC_SUCCESS;
825         }
826
827         i_old = strlen( psz_text );
828         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
829         if( !psz_text )
830             return VLC_ENOMEM;
831         strcat( psz_text, s );
832         strcat( psz_text, "\n" );
833
834         /* replace [br] by \n */
835         if( b_replace_br )
836         {
837             char *p;
838             
839             while( ( p = strstr( psz_text, "[br]" ) ) )
840             {
841                 *p++ = '\n';
842                 memmove( p, &p[3], strlen(&p[3])+1 );
843             }
844         }
845     }
846 }
847 /* ParseSubRip
848  */
849 static int  ParseSubRip( demux_t *p_demux, subtitle_t *p_subtitle )
850 {
851     return ParseSubRipSubViewer( p_demux, p_subtitle,
852                                  "%d:%d:%d,%d --> %d:%d:%d,%d",
853                                  VLC_FALSE );
854 }
855 /* ParseSubViewer
856  */
857 static int  ParseSubViewer( demux_t *p_demux, subtitle_t *p_subtitle )
858 {
859     return ParseSubRipSubViewer( p_demux, p_subtitle,
860                                  "%d:%d:%d.%d,%d:%d:%d.%d",
861                                  VLC_TRUE );
862 }
863
864 /* ParseSSA
865  */
866 static int  ParseSSA( demux_t *p_demux, subtitle_t *p_subtitle )
867 {
868     demux_sys_t *p_sys = p_demux->p_sys;
869     text_t      *txt = &p_sys->txt;
870
871     for( ;; )
872     {
873         const char *s = TextGetLine( txt );
874         int h1, m1, s1, c1, h2, m2, s2, c2;
875         char *psz_text;
876
877         if( !s )
878             return VLC_EGENERIC;
879
880         /* We expect (SSA2-4):
881          * Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
882          * Dialogue: Marked=0,0:02:40.65,0:02:41.79,Wolf main,Cher,0000,0000,0000,,Et les enregistrements de ses ondes delta ?
883          *
884          * SSA-1 is similar but only has 8 commas up untill the subtitle text. Probably the Effect field is no present, but not 100 % sure.
885          */
886
887         /* For ASS:
888          * Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
889          * Dialogue: Layer#,0:02:40.65,0:02:41.79,Wolf main,Cher,0000,0000,0000,,Et les enregistrements de ses ondes delta ?
890          */
891         psz_text = malloc( 2 + strlen( s ) + 1 );
892         if( !psz_text )
893             return VLC_ENOMEM;
894
895         if( sscanf( s,
896                     "Dialogue: %*[^,],%d:%d:%d.%d,%d:%d:%d.%d,%[^\r\n]",
897                     &h1, &m1, &s1, &c1,
898                     &h2, &m2, &s2, &c2,
899                     psz_text ) == 9 )
900         {
901             /* The dec expects: ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text */
902             /* (Layer comes from ASS specs ... it's empty for SSA.) */
903             if( p_sys->i_type == SUB_TYPE_SSA1 )
904             {
905                 /* SSA1 has only 8 commas before the text starts, not 9 */
906                 memmove( &psz_text[1], psz_text, strlen(psz_text)+1 );
907                 psz_text[0] = ',';
908             }
909             else
910             {
911                 /* ReadOrder, Layer, %s(rest of fields) */
912                 memmove( &psz_text[2], psz_text, strlen(psz_text)+1 );
913                 psz_text[0] = ',';
914                 psz_text[1] = ',';
915             }
916
917             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
918                                     (int64_t)m1 * 60*1000 +
919                                     (int64_t)s1 * 1000 +
920                                     (int64_t)c1 * 10 ) * 1000;
921             p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
922                                     (int64_t)m2 * 60*1000 +
923                                     (int64_t)s2 * 1000 +
924                                     (int64_t)c2 * 10 ) * 1000;
925             p_subtitle->psz_text = psz_text;
926             return VLC_SUCCESS;
927         }
928         free( psz_text );
929
930         /* All the other stuff we add to the header field */
931         if( !p_sys->psz_header )
932             p_sys->psz_header = strdup( "" );
933         if( !p_sys->psz_header )
934             return VLC_ENOMEM;
935
936         p_sys->psz_header =
937             realloc( p_sys->psz_header,
938                      strlen( p_sys->psz_header ) + strlen( s ) + 2 );
939         strcat( p_sys->psz_header,  s );
940         strcat( p_sys->psz_header, "\n" );
941     }
942 }
943
944 /* ParseVplayer
945  *  Format
946  *      h:m:s:Line1|Line2|Line3....
947  *  or
948  *      h:m:s Line1|Line2|Line3....
949  */
950 static int  ParseVplayer( demux_t *p_demux, subtitle_t *p_subtitle )
951 {
952     demux_sys_t *p_sys = p_demux->p_sys;
953     text_t      *txt = &p_sys->txt;
954     char *psz_text;
955     int i;
956
957     for( ;; )
958     {
959         const char *s = TextGetLine( txt );
960         int h1, m1, s1;
961
962         if( !s )
963             return VLC_EGENERIC;
964
965         psz_text = malloc( strlen( s ) + 1 );
966         if( !psz_text )
967             return VLC_ENOMEM;
968
969         if( sscanf( s, "%d:%d:%d%*c%[^\r\n]",
970                     &h1, &m1, &s1, psz_text ) == 4 )
971         {
972             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
973                                     (int64_t)m1 * 60*1000 +
974                                     (int64_t)s1 * 1000 ) * 1000;
975             p_subtitle->i_stop  = 0;
976             break;
977         }
978         free( psz_text );
979     }
980
981     /* replace | by \n */
982     for( i = 0; psz_text[i] != '\0'; i++ )
983     {
984         if( psz_text[i] == '|' )
985             psz_text[i] = '\n';
986     }
987     p_subtitle->psz_text = psz_text;
988     return VLC_SUCCESS;
989 }
990
991 /* ParseSami
992  */
993 static char *ParseSamiSearch( text_t *txt,
994                               char *psz_start, const char *psz_str )
995 {
996     if( psz_start && strcasestr( psz_start, psz_str ) )
997     {
998         char *s = strcasestr( psz_start, psz_str );
999         return &s[strlen( psz_str )];
1000     }
1001
1002     for( ;; )
1003     {
1004         char *p = TextGetLine( txt );
1005         if( !p )
1006             return NULL;
1007
1008         if( strcasestr( p, psz_str ) )
1009         {
1010             char *s = strcasestr( p, psz_str );
1011             return &s[strlen( psz_str )];
1012         }
1013     }
1014 }
1015 static int  ParseSami( demux_t *p_demux, subtitle_t *p_subtitle )
1016 {
1017     demux_sys_t *p_sys = p_demux->p_sys;
1018     text_t      *txt = &p_sys->txt;
1019
1020     char *s;
1021     int64_t i_start;
1022
1023     unsigned int i_text;
1024     char text[8192]; /* Arbitrary but should be long enough */
1025
1026     /* search "Start=" */
1027     if( !( s = ParseSamiSearch( txt, NULL, "Start=" ) ) )
1028         return VLC_EGENERIC;
1029
1030     /* get start value */
1031     i_start = strtol( s, &s, 0 );
1032
1033     /* search <P */
1034     if( !( s = ParseSamiSearch( txt, s, "<P" ) ) )
1035         return VLC_EGENERIC;
1036
1037     /* search > */
1038     if( !( s = ParseSamiSearch( txt, s, ">" ) ) )
1039         return VLC_EGENERIC;
1040
1041     i_text = 0;
1042     text[0] = '\0';
1043     /* now get all txt until  a "Start=" line */
1044     for( ;; )
1045     {
1046         char c = '\0';
1047         /* Search non empty line */
1048         while( s && *s == '\0' )
1049             s = TextGetLine( txt );
1050         if( !s )
1051             break;
1052
1053         if( *s == '<' )
1054         {
1055             if( !strncasecmp( s, "<br", 3 ) )
1056             {
1057                 c = '\n';
1058             }
1059             else if( strcasestr( s, "Start=" ) )
1060             {
1061                 TextPreviousLine( txt );
1062                 break;
1063             }
1064             s = ParseSamiSearch( txt, s, ">" );
1065         }
1066         else if( !strncmp( s, "&nbsp;", 6 ) )
1067         {
1068             c = ' ';
1069             s += 6;
1070         }
1071         else if( *s == '\t' )
1072         {
1073             c = ' ';
1074             s++;
1075         }
1076         else
1077         {
1078             c = *s;
1079             s++;
1080         }
1081         if( c != '\0' && i_text+1 < sizeof(text) )
1082         {
1083             text[i_text++] = c;
1084             text[i_text] = '\0';
1085         }
1086     }
1087
1088     p_subtitle->i_start = i_start * 1000;
1089     p_subtitle->i_stop  = 0;
1090     p_subtitle->psz_text = strdup( text );
1091
1092     return VLC_SUCCESS;
1093 }
1094
1095 /* ParseDVDSubtitle
1096  *  Format
1097  *      {T h1:m1:s1:c1
1098  *      Line1
1099  *      Line2
1100  *      ...
1101  *      }
1102  * TODO it can have a header
1103  *      { HEAD
1104  *          ...
1105  *          CODEPAGE=...
1106  *          FORMAT=...
1107  *          LANG=English
1108  *      }
1109  *      LANG support would be cool
1110  *      CODEPAGE is probably mandatory FIXME
1111  */
1112 static int ParseDVDSubtitle( demux_t *p_demux, subtitle_t *p_subtitle )
1113 {
1114     demux_sys_t *p_sys = p_demux->p_sys;
1115     text_t      *txt = &p_sys->txt;
1116     char *psz_text;
1117
1118     for( ;; )
1119     {
1120         const char *s = TextGetLine( txt );
1121         int h1, m1, s1, c1;
1122
1123         if( !s )
1124             return VLC_EGENERIC;
1125
1126         if( sscanf( s,
1127                     "{T %d:%d:%d:%d",
1128                     &h1, &m1, &s1, &c1 ) == 4 )
1129         {
1130             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1131                                     (int64_t)m1 * 60*1000 +
1132                                     (int64_t)s1 * 1000 +
1133                                     (int64_t)c1 * 10) * 1000;
1134             p_subtitle->i_stop = 0;
1135             break;
1136         }
1137     }
1138
1139     /* Now read text until a line containing "}" */
1140     psz_text = strdup("");
1141     if( !psz_text )
1142         return VLC_ENOMEM;
1143     for( ;; )
1144     {
1145         const char *s = TextGetLine( txt );
1146         int i_len;
1147         int i_old;
1148
1149         if( !s )
1150         {
1151             free( psz_text );
1152             return VLC_EGENERIC;
1153         }
1154
1155         i_len = strlen( s );
1156         if( i_len == 1 && s[0] == '}')
1157         {
1158             p_subtitle->psz_text = psz_text;
1159             return VLC_SUCCESS;
1160         }
1161
1162         i_old = strlen( psz_text );
1163         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
1164         if( !psz_text )
1165             return VLC_ENOMEM;
1166         strcat( psz_text, s );
1167         strcat( psz_text, "\n" );
1168     }
1169 }
1170
1171 /* ParseMPL2
1172  *  Format
1173  *     [n1][n2]Line1|Line2|Line3...
1174  *  where n1 and n2 are the video frame number (n2 can be empty)
1175  */
1176 static int ParseMPL2( demux_t *p_demux, subtitle_t *p_subtitle )
1177 {
1178     demux_sys_t *p_sys = p_demux->p_sys;
1179     text_t      *txt = &p_sys->txt;
1180     char *psz_text;
1181     int i;
1182
1183     for( ;; )
1184     {
1185         const char *s = TextGetLine( txt );
1186         int i_start;
1187         int i_stop;
1188
1189         if( !s )
1190             return VLC_EGENERIC;
1191
1192         psz_text = malloc( strlen(s) + 1 );
1193
1194         i_start = 0;
1195         i_stop  = 0;
1196         if( sscanf( s, "[%d][] %[^\r\n]", &i_start, psz_text ) == 2 ||
1197             sscanf( s, "[%d][%d] %[^\r\n]", &i_start, &i_stop, psz_text ) == 3)
1198         {
1199             p_subtitle->i_start = (int64_t)i_start * 100000;
1200             p_subtitle->i_stop  = (int64_t)i_stop  * 100000;
1201             break;
1202         }
1203         free( psz_text );
1204     }
1205
1206     /* replace | by \n */
1207     for( i = 0; psz_text[i] != '\0'; )
1208     {
1209         if( psz_text[i] == '|' )
1210             psz_text[i] = '\n';
1211
1212         /* Remove italic */
1213         if( psz_text[i] == '/' && ( i == 0 || psz_text[i-1] == '\n' ) )
1214             memmove( &psz_text[i], &psz_text[i+1], strlen(&psz_text[i+1])+1 );
1215         else
1216             i++;
1217     }
1218     p_subtitle->psz_text = psz_text;
1219     return VLC_SUCCESS;
1220 }
1221