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