]> git.sesse.net Git - vlc/blob - modules/demux/subtitle.c
Plugins: include vlc_common.h directly instead of vlc/vlc.h
[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  *          Jean-Baptiste Kempf <jb@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_input.h>
37
38 #include <errno.h>
39 #ifdef HAVE_SYS_TYPES_H
40 #   include <sys/types.h>
41 #endif
42 #include <ctype.h>
43
44 #include <vlc_demux.h>
45 #include <vlc_charset.h>
46
47 /*****************************************************************************
48  * Module descriptor
49  *****************************************************************************/
50 static int  Open ( vlc_object_t *p_this );
51 static void Close( vlc_object_t *p_this );
52
53 #define SUB_DELAY_LONGTEXT \
54     N_("Apply a delay to all subtitles (in 1/10s, eg 100 means 10s).")
55 #define SUB_FPS_LONGTEXT \
56     N_("Override the normal frames per second settings. " \
57     "This will only work with MicroDVD and SubRIP (SRT) subtitles.")
58 #define SUB_TYPE_LONGTEXT \
59     N_("Force the subtiles format. Valid values are : \"microdvd\", " \
60     "\"subrip\", \"subviewer\", \"ssa1\", \"ssa2-4\", \"ass\", \"vplayer\", " \
61     "\"sami\", \"dvdsubtitle\", \"mpl2\", \"aqt\", \"pjs\", "\
62     "\"mpsub\", \"jacosub\", \"psb\", \"realtext\", \"dks\", \"subviewer1\", " \
63     " and \"auto\" (meaning autodetection, this should always work).")
64
65 static const char *const ppsz_sub_type[] =
66 {
67     "auto", "microdvd", "subrip", "subviewer", "ssa1",
68     "ssa2-4", "ass", "vplayer", "sami", "dvdsubtitle", "mpl2",
69     "aqt", "pjs", "mpsub", "jacosub", "psb", "realtext", "dks",
70     "subviewer1"
71 };
72
73 vlc_module_begin();
74     set_shortname( N_("Subtitles"));
75     set_description( N_("Text subtitles parser") );
76     set_capability( "demux", 0 );
77     set_category( CAT_INPUT );
78     set_subcategory( SUBCAT_INPUT_DEMUX );
79     add_float( "sub-fps", 0.0, NULL,
80                N_("Frames per second"),
81                SUB_FPS_LONGTEXT, true );
82     add_integer( "sub-delay", 0, NULL,
83                N_("Subtitles delay"),
84                SUB_DELAY_LONGTEXT, true );
85     add_string( "sub-type", "auto", NULL, N_("Subtitles format"),
86                 SUB_TYPE_LONGTEXT, true );
87         change_string_list( ppsz_sub_type, NULL, NULL );
88     set_callbacks( Open, Close );
89
90     add_shortcut( "subtitle" );
91 vlc_module_end();
92
93 /*****************************************************************************
94  * Prototypes:
95  *****************************************************************************/
96 enum
97 {
98     SUB_TYPE_UNKNOWN = -1,
99     SUB_TYPE_MICRODVD,
100     SUB_TYPE_SUBRIP,
101     SUB_TYPE_SSA1,
102     SUB_TYPE_SSA2_4,
103     SUB_TYPE_ASS,
104     SUB_TYPE_VPLAYER,
105     SUB_TYPE_SAMI,
106     SUB_TYPE_SUBVIEWER, /* SUBVIEWER 2 */
107     SUB_TYPE_DVDSUBTITLE, /* Mplayer calls it subviewer2 */
108     SUB_TYPE_MPL2,
109     SUB_TYPE_AQT,
110     SUB_TYPE_PJS,
111     SUB_TYPE_MPSUB,
112     SUB_TYPE_JACOSUB,
113     SUB_TYPE_PSB,
114     SUB_TYPE_RT,
115     SUB_TYPE_DKS,
116     SUB_TYPE_SUBVIEW1 /* SUBVIEWER 1 - mplayer calls it subrip09,
117                          and Gnome subtitles SubViewer 1.0 */
118 };
119
120 typedef struct
121 {
122     int     i_line_count;
123     int     i_line;
124     char    **line;
125 } text_t;
126
127 static int  TextLoad( text_t *, stream_t *s );
128 static void TextUnload( text_t * );
129
130 typedef struct
131 {
132     int64_t i_start;
133     int64_t i_stop;
134
135     char    *psz_text;
136 } subtitle_t;
137
138
139 struct demux_sys_t
140 {
141     int         i_type;
142     text_t      txt;
143     es_out_id_t *es;
144
145     int64_t     i_next_demux_date;
146     int64_t     i_microsecperframe;
147
148     char        *psz_header;
149     int         i_subtitle;
150     int         i_subtitles;
151     subtitle_t  *subtitle;
152
153     int64_t     i_length;
154 };
155
156 static int  ParseMicroDvd   ( demux_t *, subtitle_t *, int );
157 static int  ParseSubRip     ( demux_t *, subtitle_t *, int );
158 static int  ParseSubViewer  ( demux_t *, subtitle_t *, int );
159 static int  ParseSSA        ( demux_t *, subtitle_t *, int );
160 static int  ParseVplayer    ( demux_t *, subtitle_t *, int );
161 static int  ParseSami       ( demux_t *, subtitle_t *, int );
162 static int  ParseDVDSubtitle( demux_t *, subtitle_t *, int );
163 static int  ParseMPL2       ( demux_t *, subtitle_t *, int );
164 static int  ParseAQT        ( demux_t *, subtitle_t *, int );
165 static int  ParsePJS        ( demux_t *, subtitle_t *, int );
166 static int  ParseMPSub      ( demux_t *, subtitle_t *, int );
167 static int  ParseJSS        ( demux_t *, subtitle_t *, int );
168 static int  ParsePSB        ( demux_t *, subtitle_t *, int );
169 static int  ParseRealText   ( demux_t *, subtitle_t *, int );
170 static int  ParseDKS        ( demux_t *, subtitle_t *, int );
171 static int  ParseSubViewer1 ( demux_t *, subtitle_t *, int );
172
173 static struct
174 {
175     const char *psz_type_name;
176     int  i_type;
177     const char *psz_name;
178     int  (*pf_read)( demux_t *, subtitle_t*, int );
179 } sub_read_subtitle_function [] =
180 {
181     { "microdvd",   SUB_TYPE_MICRODVD,    "MicroDVD",    ParseMicroDvd },
182     { "subrip",     SUB_TYPE_SUBRIP,      "SubRIP",      ParseSubRip },
183     { "subviewer",  SUB_TYPE_SUBVIEWER,   "SubViewer",   ParseSubViewer },
184     { "ssa1",       SUB_TYPE_SSA1,        "SSA-1",       ParseSSA },
185     { "ssa2-4",     SUB_TYPE_SSA2_4,      "SSA-2/3/4",   ParseSSA },
186     { "ass",        SUB_TYPE_ASS,         "SSA/ASS",     ParseSSA },
187     { "vplayer",    SUB_TYPE_VPLAYER,     "VPlayer",     ParseVplayer },
188     { "sami",       SUB_TYPE_SAMI,        "SAMI",        ParseSami },
189     { "dvdsubtitle",SUB_TYPE_DVDSUBTITLE, "DVDSubtitle", ParseDVDSubtitle },
190     { "mpl2",       SUB_TYPE_MPL2,        "MPL2",        ParseMPL2 },
191     { "aqt",        SUB_TYPE_AQT,         "AQTitle",     ParseAQT },
192     { "pjs",        SUB_TYPE_PJS,         "PhoenixSub",  ParsePJS },
193     { "mpsub",      SUB_TYPE_MPSUB,       "MPSub",       ParseMPSub },
194     { "jacosub",    SUB_TYPE_JACOSUB,     "JacoSub",     ParseJSS },
195     { "psb",        SUB_TYPE_PSB,         "PowerDivx",   ParsePSB },
196     { "realtext",   SUB_TYPE_RT,          "RealText",    ParseRealText },
197     { "dks",        SUB_TYPE_DKS,         "DKS",         ParseDKS },
198     { "subviewer1", SUB_TYPE_SUBVIEW1,    "Subviewer 1", ParseSubViewer1 },
199     { NULL,         SUB_TYPE_UNKNOWN,     "Unknown",     NULL }
200 };
201
202 static int Demux( demux_t * );
203 static int Control( demux_t *, int, va_list );
204
205 /*static void Fix( demux_t * );*/
206
207 /*****************************************************************************
208  * Module initializer
209  *****************************************************************************/
210 static int Open ( vlc_object_t *p_this )
211 {
212     demux_t        *p_demux = (demux_t*)p_this;
213     demux_sys_t    *p_sys;
214     es_format_t    fmt;
215     float          f_fps;
216     char           *psz_type;
217     int  (*pf_read)( demux_t *, subtitle_t*, int );
218     int            i, i_max;
219
220     if( !p_demux->b_force )
221     {
222         msg_Dbg( p_demux, "subtitle demux discarded" );
223         return VLC_EGENERIC;
224     }
225
226     p_demux->pf_demux = Demux;
227     p_demux->pf_control = Control;
228     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
229     if( p_sys == NULL )
230         return VLC_ENOMEM;
231
232     p_sys->psz_header         = NULL;
233     p_sys->i_subtitle         = 0;
234     p_sys->i_subtitles        = 0;
235     p_sys->subtitle           = NULL;
236     p_sys->i_microsecperframe = 40000;
237
238     /* Get the FPS */
239     f_fps = var_CreateGetFloat( p_demux, "sub-original-fps" ); /* FIXME */
240     if( f_fps >= 1.0 )
241         p_sys->i_microsecperframe = (int64_t)( (float)1000000 / f_fps );
242
243     msg_Dbg( p_demux, "Movie fps: %f", f_fps );
244
245     /* Check for override of the fps */
246     f_fps = var_CreateGetFloat( p_demux, "sub-fps" );
247     if( f_fps >= 1.0 )
248     {
249         p_sys->i_microsecperframe = (int64_t)( (float)1000000 / f_fps );
250         msg_Dbg( p_demux, "Override subtitle fps %f", f_fps );
251     }
252
253     /* Get or probe the type */
254     p_sys->i_type = SUB_TYPE_UNKNOWN;
255     psz_type = var_CreateGetString( p_demux, "sub-type" );
256     if( *psz_type )
257     {
258         int i;
259
260         for( i = 0; ; i++ )
261         {
262             if( sub_read_subtitle_function[i].psz_type_name == NULL )
263                 break;
264
265             if( !strcmp( sub_read_subtitle_function[i].psz_type_name,
266                          psz_type ) )
267             {
268                 p_sys->i_type = sub_read_subtitle_function[i].i_type;
269                 break;
270             }
271         }
272     }
273     free( psz_type );
274
275     /* Probe if unknown type */
276     if( p_sys->i_type == SUB_TYPE_UNKNOWN )
277     {
278         int     i_try;
279         char    *s = NULL;
280
281         msg_Dbg( p_demux, "autodetecting subtitle format" );
282         for( i_try = 0; i_try < 256; i_try++ )
283         {
284             int i_dummy;
285             char p_dummy;
286
287             if( ( s = stream_ReadLine( p_demux->s ) ) == NULL )
288                 break;
289
290             if( strcasestr( s, "<SAMI>" ) )
291             {
292                 p_sys->i_type = SUB_TYPE_SAMI;
293                 break;
294             }
295             else if( sscanf( s, "{%d}{%d}", &i_dummy, &i_dummy ) == 2 ||
296                      sscanf( s, "{%d}{}", &i_dummy ) == 1)
297             {
298                 p_sys->i_type = SUB_TYPE_MICRODVD;
299                 break;
300             }
301             else if( sscanf( s,
302                              "%d:%d:%d,%d --> %d:%d:%d,%d",
303                              &i_dummy,&i_dummy,&i_dummy,&i_dummy,
304                              &i_dummy,&i_dummy,&i_dummy,&i_dummy ) == 8 )
305             {
306                 p_sys->i_type = SUB_TYPE_SUBRIP;
307                 break;
308             }
309             else if( !strncasecmp( s, "!: This is a Sub Station Alpha v1", 33 ) )
310             {
311                 p_sys->i_type = SUB_TYPE_SSA1;
312                 break;
313             }
314             else if( !strncasecmp( s, "ScriptType: v4.00+", 18 ) )
315             {
316                 p_sys->i_type = SUB_TYPE_ASS;
317                 break;
318             }
319             else if( !strncasecmp( s, "ScriptType: v4.00", 17 ) )
320             {
321                 p_sys->i_type = SUB_TYPE_SSA2_4;
322                 break;
323             }
324             else if( !strncasecmp( s, "Dialogue: Marked", 16  ) )
325             {
326                 p_sys->i_type = SUB_TYPE_SSA2_4;
327                 break;
328             }
329             else if( !strncasecmp( s, "Dialogue:", 9  ) )
330             {
331                 p_sys->i_type = SUB_TYPE_ASS;
332                 break;
333             }
334             else if( strcasestr( s, "[INFORMATION]" ) )
335             {
336                 p_sys->i_type = SUB_TYPE_SUBVIEWER; /* I hope this will work */
337                 break;
338             }
339             else if( sscanf( s, "%d:%d:%d.%d %d:%d:%d",
340                                  &i_dummy, &i_dummy, &i_dummy, &i_dummy,
341                                  &i_dummy, &i_dummy, &i_dummy ) == 7 ||
342                      sscanf( s, "@%d @%d", &i_dummy, &i_dummy) == 2)
343             {
344                 p_sys->i_type = SUB_TYPE_JACOSUB;
345                 break;
346             }
347             else if( sscanf( s, "%d:%d:%d:", &i_dummy, &i_dummy, &i_dummy ) == 3 ||
348                      sscanf( s, "%d:%d:%d ", &i_dummy, &i_dummy, &i_dummy ) == 3 )
349             {
350                 p_sys->i_type = SUB_TYPE_VPLAYER;
351                 break;
352             }
353             else if( sscanf( s, "{T %d:%d:%d:%d", &i_dummy, &i_dummy,
354                              &i_dummy, &i_dummy ) == 4 )
355             {
356                 p_sys->i_type = SUB_TYPE_DVDSUBTITLE;
357                 break;
358             }
359             else if( sscanf( s, "[%d:%d:%d]%c",
360                      &i_dummy, &i_dummy, &i_dummy, &p_dummy ) == 4 )
361             {
362                 p_sys->i_type = SUB_TYPE_DKS;
363                 break;
364             }
365             else if( strstr( s, "*** START SCRIPT" ) )
366             {
367                 p_sys->i_type = SUB_TYPE_SUBVIEW1;
368                 break;
369             }
370             else if( sscanf( s, "[%d][%d]", &i_dummy, &i_dummy ) == 2 ||
371                      sscanf( s, "[%d][]", &i_dummy ) == 1)
372             {
373                 p_sys->i_type = SUB_TYPE_MPL2;
374                 break;
375             }
376             else if( sscanf (s, "FORMAT=%d", &i_dummy) == 1 ||
377                      ( sscanf (s, "FORMAT=TIM%c", &p_dummy) == 1
378                        && p_dummy =='E' ) )
379             {
380                 p_sys->i_type = SUB_TYPE_MPSUB;
381                 break;
382             }
383             else if( sscanf( s, "-->> %d", &i_dummy) == 1 )
384             {
385                 p_sys->i_type = SUB_TYPE_AQT;
386                 break;
387             }
388             else if( sscanf( s, "%d,%d,", &i_dummy, &i_dummy ) == 2 )
389             {
390                 p_sys->i_type = SUB_TYPE_PJS;
391                 break;
392             }
393             else if( sscanf( s, "{%d:%d:%d}",
394                                 &i_dummy, &i_dummy, &i_dummy ) == 3 )
395             {
396                 p_sys->i_type = SUB_TYPE_PSB;
397                 break;
398             }
399             else if( strcasestr( s, "<time" ) )
400             {
401                 p_sys->i_type = SUB_TYPE_RT;
402                 break;
403             }
404
405             free( s );
406             s = NULL;
407         }
408
409         free( s );
410
411         /* It will nearly always work even for non seekable stream thanks the
412          * caching system, and if it fails we lose just a few sub */
413         if( stream_Seek( p_demux->s, 0 ) )
414         {
415             msg_Warn( p_demux, "failed to rewind" );
416         }
417     }
418
419     /* Quit on unknown subtitles */
420     if( p_sys->i_type == SUB_TYPE_UNKNOWN )
421     {
422         msg_Err( p_demux, "failed to recognize subtitle type" );
423         free( p_sys );
424         return VLC_EGENERIC;
425     }
426
427     for( i = 0; ; i++ )
428     {
429         if( sub_read_subtitle_function[i].i_type == p_sys->i_type )
430         {
431             msg_Dbg( p_demux, "detected %s format",
432                      sub_read_subtitle_function[i].psz_name );
433             pf_read = sub_read_subtitle_function[i].pf_read;
434             break;
435         }
436     }
437
438     msg_Dbg( p_demux, "loading all subtitles..." );
439
440     /* Load the whole file */
441     TextLoad( &p_sys->txt, p_demux->s );
442
443     /* Parse it */
444     for( i_max = 0;; )
445     {
446         if( p_sys->i_subtitles >= i_max )
447         {
448             i_max += 500;
449             if( !( p_sys->subtitle = realloc( p_sys->subtitle,
450                                               sizeof(subtitle_t) * i_max ) ) )
451             {
452                 msg_Err( p_demux, "out of memory");
453                 free( p_sys->subtitle );
454                 TextUnload( &p_sys->txt );
455                 free( p_sys );
456                 return VLC_ENOMEM;
457             }
458         }
459
460         if( pf_read( p_demux, &p_sys->subtitle[p_sys->i_subtitles],
461                      p_sys->i_subtitles ) )
462             break;
463
464         p_sys->i_subtitles++;
465     }
466     /* Unload */
467     TextUnload( &p_sys->txt );
468
469     msg_Dbg(p_demux, "loaded %d subtitles", p_sys->i_subtitles );
470
471     /* Fix subtitle (order and time) *** */
472     p_sys->i_subtitle = 0;
473     p_sys->i_length = 0;
474     if( p_sys->i_subtitles > 0 )
475     {
476         p_sys->i_length = p_sys->subtitle[p_sys->i_subtitles-1].i_stop;
477         /* +1 to avoid 0 */
478         if( p_sys->i_length <= 0 )
479             p_sys->i_length = p_sys->subtitle[p_sys->i_subtitles-1].i_start+1;
480     }
481
482     /* *** add subtitle ES *** */
483     if( p_sys->i_type == SUB_TYPE_SSA1 ||
484              p_sys->i_type == SUB_TYPE_SSA2_4 ||
485              p_sys->i_type == SUB_TYPE_ASS )
486     {
487         es_format_Init( &fmt, SPU_ES, VLC_FOURCC( 's','s','a',' ' ) );
488     }
489     else
490     {
491         es_format_Init( &fmt, SPU_ES, VLC_FOURCC( 's','u','b','t' ) );
492     }
493     if( p_sys->psz_header != NULL )
494     {
495         fmt.i_extra = strlen( p_sys->psz_header ) + 1;
496         fmt.p_extra = strdup( p_sys->psz_header );
497     }
498     p_sys->es = es_out_Add( p_demux->out, &fmt );
499
500     return VLC_SUCCESS;
501 }
502
503 /*****************************************************************************
504  * Close: Close subtitle demux
505  *****************************************************************************/
506 static void Close( vlc_object_t *p_this )
507 {
508     demux_t *p_demux = (demux_t*)p_this;
509     demux_sys_t *p_sys = p_demux->p_sys;
510     int i;
511
512     for( i = 0; i < p_sys->i_subtitles; i++ )
513         free( p_sys->subtitle[i].psz_text );
514     free( p_sys->subtitle );
515
516     free( p_sys );
517 }
518
519 /*****************************************************************************
520  * Control:
521  *****************************************************************************/
522 static int Control( demux_t *p_demux, int i_query, va_list args )
523 {
524     demux_sys_t *p_sys = p_demux->p_sys;
525     int64_t *pi64, i64;
526     double *pf, f;
527
528     switch( i_query )
529     {
530         case DEMUX_GET_LENGTH:
531             pi64 = (int64_t*)va_arg( args, int64_t * );
532             *pi64 = p_sys->i_length;
533             return VLC_SUCCESS;
534
535         case DEMUX_GET_TIME:
536             pi64 = (int64_t*)va_arg( args, int64_t * );
537             if( p_sys->i_subtitle < p_sys->i_subtitles )
538             {
539                 *pi64 = p_sys->subtitle[p_sys->i_subtitle].i_start;
540                 return VLC_SUCCESS;
541             }
542             return VLC_EGENERIC;
543
544         case DEMUX_SET_TIME:
545             i64 = (int64_t)va_arg( args, int64_t );
546             p_sys->i_subtitle = 0;
547             while( p_sys->i_subtitle < p_sys->i_subtitles &&
548                    p_sys->subtitle[p_sys->i_subtitle].i_start < i64 )
549             {
550                 p_sys->i_subtitle++;
551             }
552
553             if( p_sys->i_subtitle >= p_sys->i_subtitles )
554                 return VLC_EGENERIC;
555             return VLC_SUCCESS;
556
557         case DEMUX_GET_POSITION:
558             pf = (double*)va_arg( args, double * );
559             if( p_sys->i_subtitle >= p_sys->i_subtitles )
560             {
561                 *pf = 1.0;
562             }
563             else if( p_sys->i_subtitles > 0 )
564             {
565                 *pf = (double)p_sys->subtitle[p_sys->i_subtitle].i_start /
566                       (double)p_sys->i_length;
567             }
568             else
569             {
570                 *pf = 0.0;
571             }
572             return VLC_SUCCESS;
573
574         case DEMUX_SET_POSITION:
575             f = (double)va_arg( args, double );
576             i64 = f * p_sys->i_length;
577
578             p_sys->i_subtitle = 0;
579             while( p_sys->i_subtitle < p_sys->i_subtitles &&
580                    p_sys->subtitle[p_sys->i_subtitle].i_start < i64 )
581             {
582                 p_sys->i_subtitle++;
583             }
584             if( p_sys->i_subtitle >= p_sys->i_subtitles )
585                 return VLC_EGENERIC;
586             return VLC_SUCCESS;
587
588         case DEMUX_SET_NEXT_DEMUX_TIME:
589             p_sys->i_next_demux_date = (int64_t)va_arg( args, int64_t );
590             return VLC_SUCCESS;
591
592         case DEMUX_GET_FPS:
593         case DEMUX_GET_META:
594         case DEMUX_GET_ATTACHMENTS:
595         case DEMUX_GET_TITLE_INFO:
596         case DEMUX_HAS_UNSUPPORTED_META:
597             return VLC_EGENERIC;
598
599         default:
600             msg_Err( p_demux, "unknown query %d in subtitle control", i_query );
601             return VLC_EGENERIC;
602     }
603 }
604
605 /*****************************************************************************
606  * Demux: Send subtitle to decoder
607  *****************************************************************************/
608 static int Demux( demux_t *p_demux )
609 {
610     demux_sys_t *p_sys = p_demux->p_sys;
611     int64_t i_maxdate;
612
613     if( p_sys->i_subtitle >= p_sys->i_subtitles )
614         return 0;
615
616     i_maxdate = p_sys->i_next_demux_date - var_GetTime( p_demux->p_parent, "spu-delay" );;
617     if( i_maxdate <= 0 && p_sys->i_subtitle < p_sys->i_subtitles )
618     {
619         /* Should not happen */
620         i_maxdate = p_sys->subtitle[p_sys->i_subtitle].i_start + 1;
621     }
622
623     while( p_sys->i_subtitle < p_sys->i_subtitles &&
624            p_sys->subtitle[p_sys->i_subtitle].i_start < i_maxdate )
625     {
626         block_t *p_block;
627         int i_len = strlen( p_sys->subtitle[p_sys->i_subtitle].psz_text ) + 1;
628
629         if( i_len <= 1 )
630         {
631             /* empty subtitle */
632             p_sys->i_subtitle++;
633             continue;
634         }
635
636         if( ( p_block = block_New( p_demux, i_len ) ) == NULL )
637         {
638             p_sys->i_subtitle++;
639             continue;
640         }
641
642         if( p_sys->subtitle[p_sys->i_subtitle].i_start < 0 )
643         {
644             p_sys->i_subtitle++;
645             continue;
646         }
647
648         p_block->i_pts = p_sys->subtitle[p_sys->i_subtitle].i_start;
649         p_block->i_dts = p_block->i_pts;
650         if( p_sys->subtitle[p_sys->i_subtitle].i_stop > 0 )
651         {
652             p_block->i_length =
653                 p_sys->subtitle[p_sys->i_subtitle].i_stop - p_block->i_pts;
654         }
655
656         memcpy( p_block->p_buffer,
657                 p_sys->subtitle[p_sys->i_subtitle].psz_text, i_len );
658         if( p_block->i_pts > 0 )
659         {
660             es_out_Send( p_demux->out, p_sys->es, p_block );
661         }
662         else
663         {
664             block_Release( p_block );
665         }
666         p_sys->i_subtitle++;
667     }
668
669     /* */
670     p_sys->i_next_demux_date = 0;
671
672     return 1;
673 }
674
675 /*****************************************************************************
676  * Fix: fix time stamp and order of subtitle
677  *****************************************************************************/
678 #ifdef USE_THIS_UNUSED_PIECE_OF_CODE
679 static void Fix( demux_t *p_demux )
680 {
681     demux_sys_t *p_sys = p_demux->p_sys;
682     bool b_done;
683     int     i_index;
684
685     /* *** fix order (to be sure...) *** */
686     /* We suppose that there are near in order and this durty bubble sort
687      * wont take too much time
688      */
689     do
690     {
691         b_done = true;
692         for( i_index = 1; i_index < p_sys->i_subtitles; i_index++ )
693         {
694             if( p_sys->subtitle[i_index].i_start <
695                     p_sys->subtitle[i_index - 1].i_start )
696             {
697                 subtitle_t sub_xch;
698                 memcpy( &sub_xch,
699                         p_sys->subtitle + i_index - 1,
700                         sizeof( subtitle_t ) );
701                 memcpy( p_sys->subtitle + i_index - 1,
702                         p_sys->subtitle + i_index,
703                         sizeof( subtitle_t ) );
704                 memcpy( p_sys->subtitle + i_index,
705                         &sub_xch,
706                         sizeof( subtitle_t ) );
707                 b_done = false;
708             }
709         }
710     } while( !b_done );
711 }
712 #endif
713
714 static int TextLoad( text_t *txt, stream_t *s )
715 {
716     int   i_line_max;
717
718     /* init txt */
719     i_line_max          = 500;
720     txt->i_line_count   = 0;
721     txt->i_line         = 0;
722     txt->line           = calloc( i_line_max, sizeof( char * ) );
723
724     /* load the complete file */
725     for( ;; )
726     {
727         char *psz = stream_ReadLine( s );
728
729         if( psz == NULL )
730             break;
731
732         txt->line[txt->i_line_count++] = psz;
733         if( txt->i_line_count >= i_line_max )
734         {
735             i_line_max += 100;
736             txt->line = realloc( txt->line, i_line_max * sizeof( char * ) );
737         }
738     }
739
740     if( txt->i_line_count <= 0 )
741     {
742         free( txt->line );
743         return VLC_EGENERIC;
744     }
745
746     return VLC_SUCCESS;
747 }
748 static void TextUnload( text_t *txt )
749 {
750     int i;
751
752     for( i = 0; i < txt->i_line_count; i++ )
753     {
754         free( txt->line[i] );
755     }
756     free( txt->line );
757     txt->i_line       = 0;
758     txt->i_line_count = 0;
759 }
760
761 static char *TextGetLine( text_t *txt )
762 {
763     if( txt->i_line >= txt->i_line_count )
764         return( NULL );
765
766     return txt->line[txt->i_line++];
767 }
768 static void TextPreviousLine( text_t *txt )
769 {
770     if( txt->i_line > 0 )
771         txt->i_line--;
772 }
773
774 /*****************************************************************************
775  * Specific Subtitle function
776  *****************************************************************************/
777 /* ParseMicroDvd:
778  *  Format:
779  *      {n1}{n2}Line1|Line2|Line3....
780  *  where n1 and n2 are the video frame number (n2 can be empty)
781  */
782 static int ParseMicroDvd( demux_t *p_demux, subtitle_t *p_subtitle,
783                           int i_idx )
784 {
785     VLC_UNUSED( i_idx );
786     demux_sys_t *p_sys = p_demux->p_sys;
787     text_t      *txt = &p_sys->txt;
788     char *psz_text;
789     int  i_start;
790     int  i_stop;
791     int  i;
792
793     for( ;; )
794     {
795         const char *s = TextGetLine( txt );
796         if( !s )
797             return VLC_EGENERIC;
798
799         psz_text = malloc( strlen(s) + 1 );
800         if( !psz_text )
801             return VLC_ENOMEM;
802
803         i_start = 0;
804         i_stop  = 0;
805         if( sscanf( s, "{%d}{}%[^\r\n]", &i_start, psz_text ) == 2 ||
806             sscanf( s, "{%d}{%d}%[^\r\n]", &i_start, &i_stop, psz_text ) == 3)
807         {
808             float f_fps;
809             if( i_start != 1 || i_stop != 1 )
810                 break;
811
812             /* We found a possible setting of the framerate "{1}{1}23.976" */
813             /* Check if it's usable, and if the sub-fps is not set */
814             f_fps = us_strtod( psz_text, NULL );
815             if( f_fps > 0.0 && var_GetFloat( p_demux, "sub-fps" ) <= 0.0 )
816                 p_sys->i_microsecperframe = (int64_t)((float)1000000 / f_fps);
817         }
818         free( psz_text );
819     }
820
821     /* replace | by \n */
822     for( i = 0; psz_text[i] != '\0'; i++ )
823     {
824         if( psz_text[i] == '|' )
825             psz_text[i] = '\n';
826     }
827
828     /* */
829     p_subtitle->i_start  = i_start * p_sys->i_microsecperframe;
830     p_subtitle->i_stop   = i_stop  * p_sys->i_microsecperframe;
831     p_subtitle->psz_text = psz_text;
832     return VLC_SUCCESS;
833 }
834
835 /* ParseSubRipSubViewer
836  *  Format SubRip
837  *      n
838  *      h1:m1:s1,d1 --> h2:m2:s2,d2
839  *      Line1
840  *      Line2
841  *      ....
842  *      [Empty line]
843  *  Format SubViewer v1/v2
844  *      h1:m1:s1.d1,h2:m2:s2.d2
845  *      Line1[br]Line2
846  *      Line3
847  *      ...
848  *      [empty line]
849  *  We ignore line number for SubRip
850  */
851 static int ParseSubRipSubViewer( demux_t *p_demux, subtitle_t *p_subtitle,
852                                  const char *psz_fmt,
853                                  bool b_replace_br )
854 {
855     demux_sys_t *p_sys = p_demux->p_sys;
856     text_t      *txt = &p_sys->txt;
857     char    *psz_text;
858
859     for( ;; )
860     {
861         const char *s = TextGetLine( txt );
862         int h1, m1, s1, d1, h2, m2, s2, d2;
863
864         if( !s )
865             return VLC_EGENERIC;
866
867         if( sscanf( s, psz_fmt,
868                     &h1, &m1, &s1, &d1,
869                     &h2, &m2, &s2, &d2 ) == 8 )
870         {
871             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
872                                     (int64_t)m1 * 60*1000 +
873                                     (int64_t)s1 * 1000 +
874                                     (int64_t)d1 ) * 1000;
875
876             p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
877                                     (int64_t)m2 * 60*1000 +
878                                     (int64_t)s2 * 1000 +
879                                     (int64_t)d2 ) * 1000;
880             break;
881         }
882     }
883
884     /* Now read text until an empty line */
885     psz_text = strdup("");
886     if( !psz_text )
887         return VLC_ENOMEM;
888     for( ;; )
889     {
890         const char *s = TextGetLine( txt );
891         int i_len;
892         int i_old;
893
894         if( !s )
895         {
896             free( psz_text );
897             return VLC_EGENERIC;
898         }
899
900         i_len = strlen( s );
901         if( i_len <= 0 )
902         {
903             p_subtitle->psz_text = psz_text;
904             return VLC_SUCCESS;
905         }
906
907         i_old = strlen( psz_text );
908         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
909         if( !psz_text )
910             return VLC_ENOMEM;
911         strcat( psz_text, s );
912         strcat( psz_text, "\n" );
913
914         /* replace [br] by \n */
915         if( b_replace_br )
916         {
917             char *p;
918
919             while( ( p = strstr( psz_text, "[br]" ) ) )
920             {
921                 *p++ = '\n';
922                 memmove( p, &p[3], strlen(&p[3])+1 );
923             }
924         }
925     }
926 }
927 /* ParseSubRip
928  */
929 static int  ParseSubRip( demux_t *p_demux, subtitle_t *p_subtitle,
930                          int i_idx )
931 {
932     VLC_UNUSED( i_idx );
933     return ParseSubRipSubViewer( p_demux, p_subtitle,
934                                  "%d:%d:%d,%d --> %d:%d:%d,%d",
935                                  false );
936 }
937 /* ParseSubViewer
938  */
939 static int  ParseSubViewer( demux_t *p_demux, subtitle_t *p_subtitle,
940                             int i_idx )
941 {
942     VLC_UNUSED( i_idx );
943
944     return ParseSubRipSubViewer( p_demux, p_subtitle,
945                                  "%d:%d:%d.%d,%d:%d:%d.%d",
946                                  true );
947 }
948
949 /* ParseSSA
950  */
951 static int  ParseSSA( demux_t *p_demux, subtitle_t *p_subtitle,
952                       int i_idx )
953 {
954     demux_sys_t *p_sys = p_demux->p_sys;
955     text_t      *txt = &p_sys->txt;
956
957     for( ;; )
958     {
959         const char *s = TextGetLine( txt );
960         int h1, m1, s1, c1, h2, m2, s2, c2;
961         char *psz_text;
962         char temp[16];
963
964         if( !s )
965             return VLC_EGENERIC;
966
967         /* We expect (SSA2-4):
968          * Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
969          * Dialogue: Marked=0,0:02:40.65,0:02:41.79,Wolf main,Cher,0000,0000,0000,,Et les enregistrements de ses ondes delta ?
970          *
971          * 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.
972          */
973
974         /* For ASS:
975          * Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
976          * Dialogue: Layer#,0:02:40.65,0:02:41.79,Wolf main,Cher,0000,0000,0000,,Et les enregistrements de ses ondes delta ?
977          */
978
979         /* The output text is - at least, not removing numbers - 18 chars shorter than the input text. */
980         psz_text = malloc( strlen(s) );
981         if( !psz_text )
982             return VLC_ENOMEM;
983
984         if( sscanf( s,
985                     "Dialogue: %15[^,],%d:%d:%d.%d,%d:%d:%d.%d,%[^\r\n]",
986                     temp,
987                     &h1, &m1, &s1, &c1,
988                     &h2, &m2, &s2, &c2,
989                     psz_text ) == 10 )
990         {
991             /* The dec expects: ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text */
992             /* (Layer comes from ASS specs ... it's empty for SSA.) */
993             if( p_sys->i_type == SUB_TYPE_SSA1 )
994             {
995                 /* SSA1 has only 8 commas before the text starts, not 9 */
996                 memmove( &psz_text[1], psz_text, strlen(psz_text)+1 );
997                 psz_text[0] = ',';
998             }
999             else
1000             {
1001                 int i_layer = ( p_sys->i_type == SUB_TYPE_ASS ) ? atoi( temp ) : 0;
1002
1003                 /* ReadOrder, Layer, %s(rest of fields) */
1004                 snprintf( temp, sizeof(temp), "%d,%d,", i_idx, i_layer );
1005                 memmove( psz_text + strlen(temp), psz_text, strlen(psz_text)+1 );
1006                 memcpy( psz_text, temp, strlen(temp) );
1007             }
1008
1009             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1010                                     (int64_t)m1 * 60*1000 +
1011                                     (int64_t)s1 * 1000 +
1012                                     (int64_t)c1 * 10 ) * 1000;
1013             p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
1014                                     (int64_t)m2 * 60*1000 +
1015                                     (int64_t)s2 * 1000 +
1016                                     (int64_t)c2 * 10 ) * 1000;
1017             p_subtitle->psz_text = psz_text;
1018             return VLC_SUCCESS;
1019         }
1020         free( psz_text );
1021
1022         /* All the other stuff we add to the header field */
1023         if( !p_sys->psz_header )
1024             p_sys->psz_header = strdup( "" );
1025         if( !p_sys->psz_header )
1026             return VLC_ENOMEM;
1027
1028         p_sys->psz_header =
1029             realloc( p_sys->psz_header,
1030                      strlen( p_sys->psz_header ) + strlen( s ) + 2 );
1031         strcat( p_sys->psz_header,  s );
1032         strcat( p_sys->psz_header, "\n" );
1033     }
1034 }
1035
1036 /* ParseVplayer
1037  *  Format
1038  *      h:m:s:Line1|Line2|Line3....
1039  *  or
1040  *      h:m:s Line1|Line2|Line3....
1041  */
1042 static int ParseVplayer( demux_t *p_demux, subtitle_t *p_subtitle,
1043                           int i_idx )
1044 {
1045     VLC_UNUSED( i_idx );
1046
1047     demux_sys_t *p_sys = p_demux->p_sys;
1048     text_t      *txt = &p_sys->txt;
1049     char *psz_text;
1050     int i;
1051
1052     for( ;; )
1053     {
1054         const char *s = TextGetLine( txt );
1055         int h1, m1, s1;
1056
1057         if( !s )
1058             return VLC_EGENERIC;
1059
1060         psz_text = malloc( strlen( s ) + 1 );
1061         if( !psz_text )
1062             return VLC_ENOMEM;
1063
1064         if( sscanf( s, "%d:%d:%d%*c%[^\r\n]",
1065                     &h1, &m1, &s1, psz_text ) == 4 )
1066         {
1067             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1068                                     (int64_t)m1 * 60*1000 +
1069                                     (int64_t)s1 * 1000 ) * 1000;
1070             p_subtitle->i_stop  = 0;
1071             break;
1072         }
1073         free( psz_text );
1074     }
1075
1076     /* replace | by \n */
1077     for( i = 0; psz_text[i] != '\0'; i++ )
1078     {
1079         if( psz_text[i] == '|' )
1080             psz_text[i] = '\n';
1081     }
1082     p_subtitle->psz_text = psz_text;
1083     return VLC_SUCCESS;
1084 }
1085
1086 /* ParseSami
1087  */
1088 static char *ParseSamiSearch( text_t *txt,
1089                               char *psz_start, const char *psz_str )
1090 {
1091     if( psz_start && strcasestr( psz_start, psz_str ) )
1092     {
1093         char *s = strcasestr( psz_start, psz_str );
1094         return &s[strlen( psz_str )];
1095     }
1096
1097     for( ;; )
1098     {
1099         char *p = TextGetLine( txt );
1100         if( !p )
1101             return NULL;
1102
1103         if( strcasestr( p, psz_str ) )
1104         {
1105             char *s = strcasestr( p, psz_str );
1106             return &s[strlen( psz_str )];
1107         }
1108     }
1109 }
1110 static int  ParseSami( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1111 {
1112     VLC_UNUSED( i_idx );
1113     demux_sys_t *p_sys = p_demux->p_sys;
1114     text_t      *txt = &p_sys->txt;
1115
1116     char *s;
1117     int64_t i_start;
1118
1119     unsigned int i_text;
1120     char text[8192]; /* Arbitrary but should be long enough */
1121
1122     /* search "Start=" */
1123     if( !( s = ParseSamiSearch( txt, NULL, "Start=" ) ) )
1124         return VLC_EGENERIC;
1125
1126     /* get start value */
1127     i_start = strtol( s, &s, 0 );
1128
1129     /* search <P */
1130     if( !( s = ParseSamiSearch( txt, s, "<P" ) ) )
1131         return VLC_EGENERIC;
1132
1133     /* search > */
1134     if( !( s = ParseSamiSearch( txt, s, ">" ) ) )
1135         return VLC_EGENERIC;
1136
1137     i_text = 0;
1138     text[0] = '\0';
1139     /* now get all txt until  a "Start=" line */
1140     for( ;; )
1141     {
1142         char c = '\0';
1143         /* Search non empty line */
1144         while( s && *s == '\0' )
1145             s = TextGetLine( txt );
1146         if( !s )
1147             break;
1148
1149         if( *s == '<' )
1150         {
1151             if( !strncasecmp( s, "<br", 3 ) )
1152             {
1153                 c = '\n';
1154             }
1155             else if( strcasestr( s, "Start=" ) )
1156             {
1157                 TextPreviousLine( txt );
1158                 break;
1159             }
1160             s = ParseSamiSearch( txt, s, ">" );
1161         }
1162         else if( !strncmp( s, "&nbsp;", 6 ) )
1163         {
1164             c = ' ';
1165             s += 6;
1166         }
1167         else if( *s == '\t' )
1168         {
1169             c = ' ';
1170             s++;
1171         }
1172         else
1173         {
1174             c = *s;
1175             s++;
1176         }
1177         if( c != '\0' && i_text+1 < sizeof(text) )
1178         {
1179             text[i_text++] = c;
1180             text[i_text] = '\0';
1181         }
1182     }
1183
1184     p_subtitle->i_start = i_start * 1000;
1185     p_subtitle->i_stop  = 0;
1186     p_subtitle->psz_text = strdup( text );
1187
1188     return VLC_SUCCESS;
1189 }
1190
1191 /* ParseDVDSubtitle
1192  *  Format
1193  *      {T h1:m1:s1:c1
1194  *      Line1
1195  *      Line2
1196  *      ...
1197  *      }
1198  * TODO it can have a header
1199  *      { HEAD
1200  *          ...
1201  *          CODEPAGE=...
1202  *          FORMAT=...
1203  *          LANG=English
1204  *      }
1205  *      LANG support would be cool
1206  *      CODEPAGE is probably mandatory FIXME
1207  */
1208 static int ParseDVDSubtitle( demux_t *p_demux, subtitle_t *p_subtitle,
1209                              int i_idx )
1210 {
1211     VLC_UNUSED( i_idx );
1212
1213     demux_sys_t *p_sys = p_demux->p_sys;
1214     text_t      *txt = &p_sys->txt;
1215     char *psz_text;
1216
1217     for( ;; )
1218     {
1219         const char *s = TextGetLine( txt );
1220         int h1, m1, s1, c1;
1221
1222         if( !s )
1223             return VLC_EGENERIC;
1224
1225         if( sscanf( s,
1226                     "{T %d:%d:%d:%d",
1227                     &h1, &m1, &s1, &c1 ) == 4 )
1228         {
1229             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1230                                     (int64_t)m1 * 60*1000 +
1231                                     (int64_t)s1 * 1000 +
1232                                     (int64_t)c1 * 10) * 1000;
1233             p_subtitle->i_stop = 0;
1234             break;
1235         }
1236     }
1237
1238     /* Now read text until a line containing "}" */
1239     psz_text = strdup("");
1240     if( !psz_text )
1241         return VLC_ENOMEM;
1242     for( ;; )
1243     {
1244         const char *s = TextGetLine( txt );
1245         int i_len;
1246         int i_old;
1247
1248         if( !s )
1249         {
1250             free( psz_text );
1251             return VLC_EGENERIC;
1252         }
1253
1254         i_len = strlen( s );
1255         if( i_len == 1 && s[0] == '}')
1256         {
1257             p_subtitle->psz_text = psz_text;
1258             return VLC_SUCCESS;
1259         }
1260
1261         i_old = strlen( psz_text );
1262         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
1263         if( !psz_text )
1264             return VLC_ENOMEM;
1265         strcat( psz_text, s );
1266         strcat( psz_text, "\n" );
1267     }
1268 }
1269
1270 /* ParseMPL2
1271  *  Format
1272  *     [n1][n2]Line1|Line2|Line3...
1273  *  where n1 and n2 are the video frame number (n2 can be empty)
1274  */
1275 static int ParseMPL2( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1276 {
1277     VLC_UNUSED( i_idx );
1278
1279     demux_sys_t *p_sys = p_demux->p_sys;
1280     text_t      *txt = &p_sys->txt;
1281     char *psz_text;
1282     int i;
1283
1284     for( ;; )
1285     {
1286         const char *s = TextGetLine( txt );
1287         int i_start;
1288         int i_stop;
1289
1290         if( !s )
1291             return VLC_EGENERIC;
1292
1293         psz_text = malloc( strlen(s) + 1 );
1294         if( !psz_text )
1295             return VLC_ENOMEM;
1296
1297         i_start = 0;
1298         i_stop  = 0;
1299         if( sscanf( s, "[%d][] %[^\r\n]", &i_start, psz_text ) == 2 ||
1300             sscanf( s, "[%d][%d] %[^\r\n]", &i_start, &i_stop, psz_text ) == 3)
1301         {
1302             p_subtitle->i_start = (int64_t)i_start * 100000;
1303             p_subtitle->i_stop  = (int64_t)i_stop  * 100000;
1304             break;
1305         }
1306         free( psz_text );
1307     }
1308
1309     for( i = 0; psz_text[i] != '\0'; )
1310     {
1311         /* replace | by \n */
1312         if( psz_text[i] == '|' )
1313             psz_text[i] = '\n';
1314
1315         /* Remove italic */
1316         if( psz_text[i] == '/' && ( i == 0 || psz_text[i-1] == '\n' ) )
1317             memmove( &psz_text[i], &psz_text[i+1], strlen(&psz_text[i+1])+1 );
1318         else
1319             i++;
1320     }
1321     p_subtitle->psz_text = psz_text;
1322     return VLC_SUCCESS;
1323 }
1324
1325 static int ParseAQT( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1326 {
1327     VLC_UNUSED( i_idx );
1328
1329     demux_sys_t *p_sys = p_demux->p_sys;
1330     text_t      *txt = &p_sys->txt;
1331     char *psz_text = strdup( "" );
1332     int i_old = 0;
1333     int i_firstline = 1;
1334
1335     for( ;; )
1336     {
1337         int t; /* Time */
1338
1339         const char *s = TextGetLine( txt );
1340
1341         if( !s )
1342             return VLC_EGENERIC;
1343
1344         /* Data Lines */
1345         if( sscanf (s, "-->> %d", &t) == 1)
1346         {
1347             p_subtitle->i_start = (int64_t)t; /* * FPS*/
1348             p_subtitle->i_stop  = 0;
1349
1350             /* Starting of a subtitle */
1351             if( i_firstline )
1352             {
1353                 i_firstline = 0;
1354             }
1355             /* We have been too far: end of the subtitle, begin of next */
1356             else
1357             {
1358                 TextPreviousLine( txt );
1359                 break;
1360             }
1361         }
1362         /* Text Lines */
1363         else
1364         {
1365             i_old = strlen( psz_text ) + 1;
1366             psz_text = realloc( psz_text, i_old + strlen( s ) + 1 );
1367             if( !psz_text )
1368                  return VLC_ENOMEM;
1369             strcat( psz_text, s );
1370             strcat( psz_text, "\n" );
1371             if( txt->i_line == txt->i_line_count )
1372                 break;
1373         }
1374     }
1375     p_subtitle->psz_text = psz_text;
1376     return VLC_SUCCESS;
1377 }
1378
1379 static int ParsePJS( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1380 {
1381     VLC_UNUSED( i_idx );
1382
1383     demux_sys_t *p_sys = p_demux->p_sys;
1384     text_t      *txt = &p_sys->txt;
1385     char *psz_text;
1386     int i;
1387
1388     for( ;; )
1389     {
1390         const char *s = TextGetLine( txt );
1391         int t1, t2;
1392
1393         if( !s )
1394             return VLC_EGENERIC;
1395
1396         psz_text = malloc( strlen(s) + 1 );
1397         if( !psz_text )
1398             return VLC_ENOMEM;
1399
1400         /* Data Lines */
1401         if( sscanf (s, "%d,%d,\"%[^\n\r]", &t1, &t2, psz_text ) == 3 )
1402         {
1403             /* 1/10th of second ? Frame based ? FIXME */
1404             p_subtitle->i_start = 10 * t1;
1405             p_subtitle->i_stop = 10 * t2;
1406             /* Remove latest " */
1407             psz_text[ strlen(psz_text) - 1 ] = '\0';
1408
1409             break;
1410         }
1411         free( psz_text );
1412     }
1413
1414     /* replace | by \n */
1415     for( i = 0; psz_text[i] != '\0'; i++ )
1416     {
1417         if( psz_text[i] == '|' )
1418             psz_text[i] = '\n';
1419     }
1420
1421     p_subtitle->psz_text = psz_text;
1422     msg_Dbg( p_demux, "%s", psz_text );
1423     return VLC_SUCCESS;
1424 }
1425
1426 static float mpsub_total = 0.0;
1427 static float mpsub_factor = 0.0;
1428
1429 static int ParseMPSub( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1430 {
1431     VLC_UNUSED( i_idx );
1432
1433     demux_sys_t *p_sys = p_demux->p_sys;
1434     text_t      *txt = &p_sys->txt;
1435     char *psz_text = strdup( "" );
1436
1437     for( ;; )
1438     {
1439         float f1, f2;
1440         char p_dummy;
1441         char *psz_temp;
1442
1443         const char *s = TextGetLine( txt );
1444         if( !s )
1445             return VLC_EGENERIC;
1446
1447         if( strstr( s, "FORMAT" ) )
1448         {
1449             if( sscanf (s, "FORMAT=TIM%c", &p_dummy ) == 1 && p_dummy == 'E')
1450             {
1451                 mpsub_factor = 100.0;
1452                 break;
1453             }
1454
1455             psz_temp = malloc( strlen(s) );
1456             if( !psz_temp )
1457                 return VLC_ENOMEM;
1458
1459             if( sscanf( s, "FORMAT=%[^\r\n]", psz_temp ) )
1460             {
1461                 float f_fps;
1462                 f_fps = us_strtod( psz_temp, NULL );
1463                 if( f_fps > 0.0 && var_GetFloat( p_demux, "sub-fps" ) <= 0.0 )
1464                     var_SetFloat( p_demux, "sub-fps", f_fps );
1465
1466                 mpsub_factor = 1.0;
1467                 free( psz_temp );
1468                 break;
1469             }
1470             free( psz_temp );
1471         }
1472         /* Data Lines */
1473         f1 = us_strtod( s, &psz_temp );
1474         if( *psz_temp )
1475         {
1476             f2 = us_strtod( psz_temp, NULL );
1477             mpsub_total += f1 * mpsub_factor;
1478             p_subtitle->i_start = (int64_t)(10000.0 * mpsub_total);
1479             mpsub_total += f2 * mpsub_factor;
1480             p_subtitle->i_stop = (int64_t)(10000.0 * mpsub_total);
1481             break;
1482         }
1483     }
1484
1485     for( ;; )
1486     {
1487         const char *s = TextGetLine( txt );
1488
1489         if( !s )
1490             return VLC_EGENERIC;
1491
1492         int i_len = strlen( s );
1493         if( i_len == 0 )
1494             break;
1495
1496         int i_old = strlen( psz_text );
1497
1498         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
1499         if( !psz_text )
1500              return VLC_ENOMEM;
1501
1502         strcat( psz_text, s );
1503         strcat( psz_text, "\n" );
1504     }
1505
1506     p_subtitle->psz_text = psz_text;
1507     return VLC_SUCCESS;
1508 }
1509
1510 static int ParseJSS( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1511 {
1512     VLC_UNUSED( i_idx );
1513
1514     demux_sys_t  *p_sys = p_demux->p_sys;
1515     text_t       *txt = &p_sys->txt;
1516     char         *psz_text, *psz_orig;
1517     char         *psz_text2, *psz_orig2;
1518     int h1, h2, m1, m2, s1, s2, f1, f2;
1519
1520     static int i_comment = 0;
1521
1522     static int jss_time_resolution = 30;
1523     static int jss_time_shift = 0;
1524
1525     /* Parse the main lines */
1526     for( ;; )
1527     {
1528         const char *s = TextGetLine( txt );
1529         if( !s )
1530             return VLC_EGENERIC;
1531
1532         psz_orig = malloc( strlen( s ) + 1 );
1533         if( !psz_orig )
1534             return VLC_ENOMEM;
1535         psz_text = psz_orig;
1536
1537         /* Complete time lines */
1538         if( sscanf( s, "%d:%d:%d.%d %d:%d:%d.%d %[^\n\r]",
1539                     &h1, &m1, &s1, &f1, &h2, &m2, &s2, &f2, psz_text ) == 9 )
1540         {
1541             p_subtitle->i_start = ( (int64_t)( h1 *3600 + m1 * 60 + s1 ) +
1542                 (int64_t)( ( f1 +  jss_time_shift ) /  jss_time_resolution ) )
1543                 * 1000000;
1544             p_subtitle->i_stop = ( (int64_t)( h2 *3600 + m2 * 60 + s2 ) +
1545                 (int64_t)( ( f2 +  jss_time_shift ) /  jss_time_resolution ) )
1546                 * 1000000;
1547             break;
1548         }
1549         /* Short time lines */
1550         else if( sscanf( s, "@%d @%d %[^\n\r]", &f1, &f2, psz_text ) == 3 )
1551         {
1552             p_subtitle->i_start = (int64_t)(
1553                     ( f1 + jss_time_shift ) / jss_time_resolution * 1000000.0 );
1554             p_subtitle->i_stop = (int64_t)(
1555                     ( f2 + jss_time_shift ) / jss_time_resolution * 1000000.0 );
1556             break;
1557         }
1558         /* General Directive lines */
1559         /* Only TIME and SHIFT are supported so far */
1560         else if( s[0] == '#' )
1561         {
1562             int h = 0, m =0, sec = 1, f = 1;
1563             unsigned shift = 1;
1564             int inv = 1;
1565
1566             strcpy( psz_text, s );
1567
1568             switch( toupper( psz_text[1] ) )
1569             {
1570             case 'S':
1571                  shift = isalpha( psz_text[2] ) ? 6 : 2 ;
1572
1573                  if( sscanf( &psz_text[shift], "%d", &h ) )
1574                  {
1575                      /* Negative shifting */
1576                      if( h < 0 )
1577                      {
1578                          h *= -1;
1579                          inv = -1;
1580                      }
1581
1582                      if( sscanf( &psz_text[shift], "%*d:%d", &m ) )
1583                      {
1584                          if( sscanf( &psz_text[shift], "%*d:%*d:%d", &sec ) )
1585                          {
1586                              sscanf( &psz_text[shift], "%*d:%*d:%*d.%d", &f );
1587                          }
1588                          else
1589                          {
1590                              h = 0;
1591                              sscanf( &psz_text[shift], "%d:%d.%d",
1592                                      &m, &sec, &f );
1593                              m *= inv;
1594                          }
1595                      }
1596                      else
1597                      {
1598                          h = m = 0;
1599                          sscanf( &psz_text[shift], "%d.%d", &sec, &f);
1600                          sec *= inv;
1601                      }
1602                      jss_time_shift = ( ( h * 3600 + m * 60 + sec )
1603                          * jss_time_resolution + f ) * inv;
1604                  }
1605                  break;
1606
1607             case 'T':
1608                 shift = isalpha( psz_text[2] ) ? 8 : 2 ;
1609
1610                 sscanf( &psz_text[shift], "%d", &jss_time_resolution );
1611                 break;
1612             }
1613             free( psz_orig );
1614             continue;
1615         }
1616         else
1617             /* Unkown type line, probably a comment */
1618         {
1619             free( psz_orig );
1620             continue;
1621         }
1622     }
1623         
1624         while( psz_text[ strlen( psz_text ) - 1 ] == '\\' )
1625         {
1626         const char *s2 = TextGetLine( txt );
1627
1628         if( !s2 )
1629             return VLC_EGENERIC;
1630
1631         int i_len = strlen( s2 );
1632         if( i_len == 0 )
1633             break;
1634
1635         int i_old = strlen( psz_text );
1636
1637         psz_text = realloc( psz_text, i_old + i_len + 1 );
1638         if( !psz_text )
1639              return VLC_ENOMEM;
1640
1641                 psz_orig = psz_text;
1642         strcat( psz_text, s2 );
1643         }
1644
1645     /* Skip the blanks */
1646     while( *psz_text == ' ' || *psz_text == '\t' ) psz_text++;
1647
1648     /* Parse the directives */
1649     if( isalpha( *psz_text ) || *psz_text == '[' )
1650     {
1651         while( *psz_text != ' ' )
1652         { psz_text++ ;};
1653
1654         /* Directives are NOT parsed yet */
1655         /* This has probably a better place in a decoder ? */
1656         /* directive = malloc( strlen( psz_text ) + 1 );
1657            if( sscanf( psz_text, "%s %[^\n\r]", directive, psz_text2 ) == 2 )*/
1658     }
1659
1660     /* Skip the blanks after directives */
1661     while( *psz_text == ' ' || *psz_text == '\t' ) psz_text++;
1662
1663     /* Clean all the lines from inline comments and other stuffs */
1664     psz_orig2 = calloc( strlen( psz_text) + 1, 1 );
1665     psz_text2 = psz_orig2;
1666
1667     for( ; *psz_text != '\0' && *psz_text != '\n' && *psz_text != '\r'; )
1668     {
1669         switch( *psz_text )
1670         {
1671         case '{':
1672             i_comment++;
1673             break;
1674         case '}':
1675             if( i_comment )
1676             {
1677                 i_comment = 0;
1678                 if( (*(psz_text + 1 ) ) == ' ' ) psz_text++;
1679             }
1680             break;
1681         case '~':
1682             if( !i_comment )
1683             {
1684                 *psz_text2 = ' ';
1685                 psz_text2++;
1686             }
1687             break;
1688         case ' ':
1689         case '\t':
1690             if( (*(psz_text + 1 ) ) == ' ' || (*(psz_text + 1 ) ) == '\t' )
1691                 break;
1692             if( !i_comment )
1693             {
1694                 *psz_text2 = ' ';
1695                 psz_text2++;
1696             }
1697             break;
1698         case '\\':
1699             if( (*(psz_text + 1 ) ) == 'n' )
1700             {
1701                 *psz_text2 = '\n';
1702                 psz_text++;
1703                 psz_text2++;
1704                 break;
1705             }
1706             if( ( toupper(*(psz_text + 1 ) ) == 'C' ) ||
1707                     ( toupper(*(psz_text + 1 ) ) == 'F' ) )
1708             {
1709                 psz_text++; psz_text++;
1710                 break;
1711             }
1712             if( (*(psz_text + 1 ) ) == 'B' || (*(psz_text + 1 ) ) == 'b' ||
1713                 (*(psz_text + 1 ) ) == 'I' || (*(psz_text + 1 ) ) == 'i' ||
1714                 (*(psz_text + 1 ) ) == 'U' || (*(psz_text + 1 ) ) == 'u' ||
1715                 (*(psz_text + 1 ) ) == 'D' || (*(psz_text + 1 ) ) == 'N' )
1716             {
1717                 psz_text++;
1718                 break;
1719             }
1720             if( (*(psz_text + 1 ) ) == '~' || (*(psz_text + 1 ) ) == '{' ||
1721                 (*(psz_text + 1 ) ) == '\\' )
1722                 psz_text++;
1723             else if( *(psz_text + 1 ) == '\r' ||  *(psz_text + 1 ) == '\n' ||
1724                      *(psz_text + 1 ) == '\0' )
1725             {
1726                                 psz_text++;
1727             }
1728             break;
1729         default:
1730             if( !i_comment )
1731             {
1732                 *psz_text2 = *psz_text;
1733                 psz_text2++;
1734             }
1735         }
1736         psz_text++;
1737     }
1738
1739     p_subtitle->psz_text = psz_orig2;
1740     msg_Dbg( p_demux, "%s", p_subtitle->psz_text );
1741     free( psz_orig );
1742     return VLC_SUCCESS;
1743 }
1744
1745 static int ParsePSB( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1746 {
1747     VLC_UNUSED( i_idx );
1748
1749     demux_sys_t *p_sys = p_demux->p_sys;
1750     text_t      *txt = &p_sys->txt;
1751     char *psz_text;
1752     int i;
1753
1754     for( ;; )
1755     {
1756         int h1, m1, s1;
1757         int h2, m2, s2;
1758         const char *s = TextGetLine( txt );
1759
1760         if( !s )
1761             return VLC_EGENERIC;
1762
1763         psz_text = malloc( strlen( s ) + 1 );
1764         if( !psz_text )
1765             return VLC_ENOMEM;
1766
1767         if( sscanf( s, "{%d:%d:%d}{%d:%d:%d}%[^\r\n]",
1768                     &h1, &m1, &s1, &h2, &m2, &s2, psz_text ) == 7 )
1769         {
1770             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1771                                     (int64_t)m1 * 60*1000 +
1772                                     (int64_t)s1 * 1000 ) * 1000;
1773             p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
1774                                     (int64_t)m2 * 60*1000 +
1775                                     (int64_t)s2 * 1000 ) * 1000;
1776             break;
1777         }
1778         free( psz_text );
1779     }
1780
1781     /* replace | by \n */
1782     for( i = 0; psz_text[i] != '\0'; i++ )
1783     {
1784         if( psz_text[i] == '|' )
1785             psz_text[i] = '\n';
1786     }
1787     p_subtitle->psz_text = psz_text;
1788     return VLC_SUCCESS;
1789 }
1790
1791 static int64_t ParseRealTime( char *psz, int *h, int *m, int *s, int *f )
1792 {
1793     if( strlen( psz ) == 0 ) return 0;
1794     if( sscanf( psz, "%d:%d:%d.%d", h, m, s, f ) == 4 ||
1795             sscanf( psz, "%d:%d.%d", m, s, f ) == 3 ||
1796             sscanf( psz, "%d.%d", s, f ) == 2 ||
1797             sscanf( psz, "%d:%d", m, s ) == 2 ||
1798             sscanf( psz, "%d", s ) == 1 )
1799     {
1800         return (int64_t)((( *h * 60 + *m ) * 60 ) + *s ) * 1000 * 1000
1801                + (int64_t)*f * 10 * 1000;
1802     }
1803     else return VLC_EGENERIC;
1804 }
1805
1806 static int ParseRealText( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1807 {
1808     VLC_UNUSED( i_idx );
1809     demux_sys_t *p_sys = p_demux->p_sys;
1810     text_t      *txt = &p_sys->txt;
1811     char *psz_text;
1812     char psz_end[12]= "", psz_begin[12] = "";
1813
1814     for( ;; )
1815     {
1816         int h1 = 0, m1 = 0, s1 = 0, f1 = 0;
1817         int h2 = 0, m2 = 0, s2 = 0, f2 = 0;
1818         const char *s = TextGetLine( txt );
1819
1820         if( !s )
1821             return VLC_EGENERIC;
1822
1823         psz_text = malloc( strlen( s ) + 1 );
1824         if( !psz_text )
1825             return VLC_ENOMEM;
1826
1827         /* Find the good begining. This removes extra spaces at the beginning
1828            of the line.*/
1829         char *psz_temp = strcasestr( s, "<time");
1830         if( psz_temp != NULL )
1831         {
1832             /* Line has begin and end */
1833             if( ( sscanf( psz_temp,
1834                   "<%*[t|T]ime %*[b|B]egin=\"%[^\"]\" %*[e|E]nd=\"%[^\"]%*[^>]%[^\n\r]",
1835                             psz_begin, psz_end, psz_text) != 3 ) &&
1836                     /* Line has begin and no end */
1837                     ( sscanf( psz_temp,
1838                               "<%*[t|T]ime %*[b|B]egin=\"%[^\"]\"%*[^>]%[^\n\r]",
1839                               psz_begin, psz_text ) != 2) )
1840                 /* Line is not recognized */
1841             {
1842                 free( psz_text );
1843                 continue;
1844             }
1845
1846             /* Get the times */
1847             int64_t i_time = ParseRealTime( psz_begin, &h1, &m1, &s1, &f1 );
1848             if( i_time >= 0)
1849             {
1850                 p_subtitle->i_start = i_time;
1851             }
1852
1853             i_time = ParseRealTime( psz_end, &h2, &m2, &s2, &f2 );
1854             if( i_time >= 0 )
1855             {
1856                 p_subtitle->i_stop = i_time;
1857             }
1858             break;
1859         }
1860         /* Line is not recognized */
1861         else continue;
1862         free( psz_text );
1863     }
1864
1865     /* Get the following Lines */
1866     for( ;; )
1867     {
1868         const char *s = TextGetLine( txt );
1869
1870         if( !s )
1871             return VLC_EGENERIC;
1872
1873         int i_len = strlen( s );
1874         if( i_len == 0 ) break;
1875
1876         if( strcasestr( s, "<time" ) ||
1877             strcasestr( s, "<clear/") )
1878         {
1879             TextPreviousLine( txt );
1880             break;
1881         }
1882
1883         int i_old = strlen( psz_text );
1884
1885         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
1886         if( !psz_text )
1887             return VLC_ENOMEM;
1888
1889         strcat( psz_text, s );
1890         strcat( psz_text, "\n" );
1891     }
1892
1893     /* Remove the starting ">" that remained after the sscanf */
1894     memmove( &psz_text[0], &psz_text[1], strlen( psz_text ) );
1895
1896     p_subtitle->psz_text = psz_text;
1897
1898     return VLC_SUCCESS;
1899 }
1900
1901 static int ParseDKS( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1902 {
1903     VLC_UNUSED( i_idx );
1904
1905     demux_sys_t *p_sys = p_demux->p_sys;
1906     text_t      *txt = &p_sys->txt;
1907     char *psz_text;
1908
1909     for( ;; )
1910     {
1911         int h1, m1, s1;
1912         int h2, m2, s2;
1913         char *s = TextGetLine( txt );
1914
1915         if( !s )
1916             return VLC_EGENERIC;
1917
1918         psz_text = malloc( strlen( s ) + 1 );
1919         if( !psz_text )
1920             return VLC_ENOMEM;
1921
1922         if( sscanf( s, "[%d:%d:%d]%[^\r\n]",
1923                     &h1, &m1, &s1, psz_text ) == 4 )
1924         {
1925             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1926                                     (int64_t)m1 * 60*1000 +
1927                                     (int64_t)s1 * 1000 ) * 1000;
1928
1929             char *s = TextGetLine( txt );
1930             if( !s )
1931                 return VLC_EGENERIC;
1932
1933             if( sscanf( s, "[%d:%d:%d]", &h2, &m2, &s2 ) == 3 )
1934                 p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
1935                                         (int64_t)m2 * 60*1000 +
1936                                         (int64_t)s2 * 1000 ) * 1000;
1937             break;
1938         }
1939         free( psz_text );
1940     }
1941
1942     /* replace [br] by \n */
1943     char *p;
1944     while( ( p = strstr( psz_text, "[br]" ) ) )
1945     {
1946         *p++ = '\n';
1947         memmove( p, &p[3], strlen(&p[3])+1 );
1948     }
1949
1950     p_subtitle->psz_text = psz_text;
1951     return VLC_SUCCESS;
1952 }
1953
1954 static int ParseSubViewer1( demux_t *p_demux, subtitle_t *p_subtitle, int i_idx )
1955 {
1956     VLC_UNUSED( i_idx );
1957
1958     demux_sys_t *p_sys = p_demux->p_sys;
1959     text_t      *txt = &p_sys->txt;
1960     char *psz_text;
1961
1962     for( ;; )
1963     {
1964         int h1, m1, s1;
1965         int h2, m2, s2;
1966         char *s = TextGetLine( txt );
1967
1968         if( !s )
1969             return VLC_EGENERIC;
1970
1971         if( sscanf( s, "[%d:%d:%d]", &h1, &m1, &s1 ) == 3 )
1972         {
1973             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1974                                     (int64_t)m1 * 60*1000 +
1975                                     (int64_t)s1 * 1000 ) * 1000;
1976
1977             char *s = TextGetLine( txt );
1978             if( !s )
1979                 return VLC_EGENERIC;
1980
1981             psz_text = strdup( s );
1982             if( !psz_text )
1983                 return VLC_ENOMEM;
1984
1985             s = TextGetLine( txt );
1986             if( !s )
1987                 return VLC_EGENERIC;
1988
1989             if( sscanf( s, "[%d:%d:%d]", &h2, &m2, &s2 ) == 3 )
1990                 p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
1991                                         (int64_t)m2 * 60*1000 +
1992                                         (int64_t)s2 * 1000 ) * 1000;
1993             break;
1994         }
1995     }
1996
1997     p_subtitle->psz_text = psz_text;
1998
1999     return VLC_SUCCESS;
2000 }
2001