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