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