]> git.sesse.net Git - vlc/blob - modules/demux/subtitle.c
Don't include config.h from the headers - refs #297.
[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 * );
141 static int  ParseSubRip     ( demux_t *, subtitle_t * );
142 static int  ParseSubViewer  ( demux_t *, subtitle_t * );
143 static int  ParseSSA        ( demux_t *, subtitle_t * );
144 static int  ParseVplayer    ( demux_t *, subtitle_t * );
145 static int  ParseSami       ( demux_t *, subtitle_t * );
146 static int  ParseDVDSubtitle( demux_t *, subtitle_t * );
147 static int  ParseMPL2       ( demux_t *, subtitle_t * );
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* );
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* );
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             break;
378
379         p_sys->i_subtitles++;
380     }
381     /* Unload */
382     TextUnload( &p_sys->txt );
383
384     msg_Dbg(p_demux, "loaded %d subtitles", p_sys->i_subtitles );
385
386     /* Fix subtitle (order and time) *** */
387     p_sys->i_subtitle = 0;
388     p_sys->i_length = 0;
389     if( p_sys->i_subtitles > 0 )
390     {
391         p_sys->i_length = p_sys->subtitle[p_sys->i_subtitles-1].i_stop;
392         /* +1 to avoid 0 */
393         if( p_sys->i_length <= 0 )
394             p_sys->i_length = p_sys->subtitle[p_sys->i_subtitles-1].i_start+1;
395     }
396
397     /* *** add subtitle ES *** */
398     if( p_sys->i_type == SUB_TYPE_SSA1 ||
399              p_sys->i_type == SUB_TYPE_SSA2_4 ||
400              p_sys->i_type == SUB_TYPE_ASS )
401     {
402         es_format_Init( &fmt, SPU_ES, VLC_FOURCC( 's','s','a',' ' ) );
403     }
404     else
405     {
406         es_format_Init( &fmt, SPU_ES, VLC_FOURCC( 's','u','b','t' ) );
407     }
408     if( p_sys->psz_header != NULL )
409     {
410         fmt.i_extra = strlen( p_sys->psz_header ) + 1;
411         fmt.p_extra = strdup( p_sys->psz_header );
412     }
413     p_sys->es = es_out_Add( p_demux->out, &fmt );
414
415     return VLC_SUCCESS;
416 }
417
418 /*****************************************************************************
419  * Close: Close subtitle demux
420  *****************************************************************************/
421 static void Close( vlc_object_t *p_this )
422 {
423     demux_t *p_demux = (demux_t*)p_this;
424     demux_sys_t *p_sys = p_demux->p_sys;
425     int i;
426
427     for( i = 0; i < p_sys->i_subtitles; i++ )
428     {
429         if( p_sys->subtitle[i].psz_text )
430             free( p_sys->subtitle[i].psz_text );
431     }
432     if( p_sys->subtitle )
433         free( p_sys->subtitle );
434
435     free( p_sys );
436 }
437
438 /*****************************************************************************
439  * Control:
440  *****************************************************************************/
441 static int Control( demux_t *p_demux, int i_query, va_list args )
442 {
443     demux_sys_t *p_sys = p_demux->p_sys;
444     int64_t *pi64, i64;
445     double *pf, f;
446
447     switch( i_query )
448     {
449         case DEMUX_GET_LENGTH:
450             pi64 = (int64_t*)va_arg( args, int64_t * );
451             *pi64 = p_sys->i_length;
452             return VLC_SUCCESS;
453
454         case DEMUX_GET_TIME:
455             pi64 = (int64_t*)va_arg( args, int64_t * );
456             if( p_sys->i_subtitle < p_sys->i_subtitles )
457             {
458                 *pi64 = p_sys->subtitle[p_sys->i_subtitle].i_start;
459                 return VLC_SUCCESS;
460             }
461             return VLC_EGENERIC;
462
463         case DEMUX_SET_TIME:
464             i64 = (int64_t)va_arg( args, int64_t );
465             p_sys->i_subtitle = 0;
466             while( p_sys->i_subtitle < p_sys->i_subtitles &&
467                    p_sys->subtitle[p_sys->i_subtitle].i_start < i64 )
468             {
469                 p_sys->i_subtitle++;
470             }
471
472             if( p_sys->i_subtitle >= p_sys->i_subtitles )
473                 return VLC_EGENERIC;
474             return VLC_SUCCESS;
475
476         case DEMUX_GET_POSITION:
477             pf = (double*)va_arg( args, double * );
478             if( p_sys->i_subtitle >= p_sys->i_subtitles )
479             {
480                 *pf = 1.0;
481             }
482             else if( p_sys->i_subtitles > 0 )
483             {
484                 *pf = (double)p_sys->subtitle[p_sys->i_subtitle].i_start /
485                       (double)p_sys->i_length;
486             }
487             else
488             {
489                 *pf = 0.0;
490             }
491             return VLC_SUCCESS;
492
493         case DEMUX_SET_POSITION:
494             f = (double)va_arg( args, double );
495             i64 = f * p_sys->i_length;
496
497             p_sys->i_subtitle = 0;
498             while( p_sys->i_subtitle < p_sys->i_subtitles &&
499                    p_sys->subtitle[p_sys->i_subtitle].i_start < i64 )
500             {
501                 p_sys->i_subtitle++;
502             }
503             if( p_sys->i_subtitle >= p_sys->i_subtitles )
504                 return VLC_EGENERIC;
505             return VLC_SUCCESS;
506
507         case DEMUX_SET_NEXT_DEMUX_TIME:
508             p_sys->i_next_demux_date = (int64_t)va_arg( args, int64_t );
509             return VLC_SUCCESS;
510
511         case DEMUX_GET_FPS:
512         case DEMUX_GET_META:
513         case DEMUX_GET_ATTACHMENTS:
514         case DEMUX_GET_TITLE_INFO:
515         case DEMUX_HAS_UNSUPPORTED_META:
516             return VLC_EGENERIC;
517
518         default:
519             msg_Err( p_demux, "unknown query %d in subtitle control", i_query );
520             return VLC_EGENERIC;
521     }
522 }
523
524 /*****************************************************************************
525  * Demux: Send subtitle to decoder
526  *****************************************************************************/
527 static int Demux( demux_t *p_demux )
528 {
529     demux_sys_t *p_sys = p_demux->p_sys;
530     int64_t i_maxdate;
531
532     if( p_sys->i_subtitle >= p_sys->i_subtitles )
533         return 0;
534
535     i_maxdate = p_sys->i_next_demux_date - var_GetTime( p_demux->p_parent, "spu-delay" );;
536     if( i_maxdate <= 0 && p_sys->i_subtitle < p_sys->i_subtitles )
537     {
538         /* Should not happen */
539         i_maxdate = p_sys->subtitle[p_sys->i_subtitle].i_start + 1;
540     }
541
542     while( p_sys->i_subtitle < p_sys->i_subtitles &&
543            p_sys->subtitle[p_sys->i_subtitle].i_start < i_maxdate )
544     {
545         block_t *p_block;
546         int i_len = strlen( p_sys->subtitle[p_sys->i_subtitle].psz_text ) + 1;
547
548         if( i_len <= 1 )
549         {
550             /* empty subtitle */
551             p_sys->i_subtitle++;
552             continue;
553         }
554
555         if( ( p_block = block_New( p_demux, i_len ) ) == NULL )
556         {
557             p_sys->i_subtitle++;
558             continue;
559         }
560
561         if( p_sys->subtitle[p_sys->i_subtitle].i_start < 0 )
562         {
563             p_sys->i_subtitle++;
564             continue;
565         }
566
567         p_block->i_pts = p_sys->subtitle[p_sys->i_subtitle].i_start;
568         p_block->i_dts = p_block->i_pts;
569         if( p_sys->subtitle[p_sys->i_subtitle].i_stop > 0 )
570         {
571             p_block->i_length =
572                 p_sys->subtitle[p_sys->i_subtitle].i_stop - p_block->i_pts;
573         }
574
575         memcpy( p_block->p_buffer,
576                 p_sys->subtitle[p_sys->i_subtitle].psz_text, i_len );
577         if( p_block->i_pts > 0 )
578         {
579             es_out_Send( p_demux->out, p_sys->es, p_block );
580         }
581         else
582         {
583             block_Release( p_block );
584         }
585         p_sys->i_subtitle++;
586     }
587
588     /* */
589     p_sys->i_next_demux_date = 0;
590
591     return 1;
592 }
593
594 /*****************************************************************************
595  * Fix: fix time stamp and order of subtitle
596  *****************************************************************************/
597 #ifdef USE_THIS_UNUSED_PIECE_OF_CODE
598 static void Fix( demux_t *p_demux )
599 {
600     demux_sys_t *p_sys = p_demux->p_sys;
601     vlc_bool_t b_done;
602     int     i_index;
603
604     /* *** fix order (to be sure...) *** */
605     /* We suppose that there are near in order and this durty bubble sort
606      * wont take too much time
607      */
608     do
609     {
610         b_done = VLC_TRUE;
611         for( i_index = 1; i_index < p_sys->i_subtitles; i_index++ )
612         {
613             if( p_sys->subtitle[i_index].i_start <
614                     p_sys->subtitle[i_index - 1].i_start )
615             {
616                 subtitle_t sub_xch;
617                 memcpy( &sub_xch,
618                         p_sys->subtitle + i_index - 1,
619                         sizeof( subtitle_t ) );
620                 memcpy( p_sys->subtitle + i_index - 1,
621                         p_sys->subtitle + i_index,
622                         sizeof( subtitle_t ) );
623                 memcpy( p_sys->subtitle + i_index,
624                         &sub_xch,
625                         sizeof( subtitle_t ) );
626                 b_done = VLC_FALSE;
627             }
628         }
629     } while( !b_done );
630 }
631 #endif
632
633 static int TextLoad( text_t *txt, stream_t *s )
634 {
635     int   i_line_max;
636
637     /* init txt */
638     i_line_max          = 500;
639     txt->i_line_count   = 0;
640     txt->i_line         = 0;
641     txt->line           = calloc( i_line_max, sizeof( char * ) );
642
643     /* load the complete file */
644     for( ;; )
645     {
646         char *psz = stream_ReadLine( s );
647
648         if( psz == NULL )
649             break;
650
651         txt->line[txt->i_line_count++] = psz;
652         if( txt->i_line_count >= i_line_max )
653         {
654             i_line_max += 100;
655             txt->line = realloc( txt->line, i_line_max * sizeof( char * ) );
656         }
657     }
658
659     if( txt->i_line_count <= 0 )
660     {
661         free( txt->line );
662         return VLC_EGENERIC;
663     }
664
665     return VLC_SUCCESS;
666 }
667 static void TextUnload( text_t *txt )
668 {
669     int i;
670
671     for( i = 0; i < txt->i_line_count; i++ )
672     {
673         free( txt->line[i] );
674     }
675     free( txt->line );
676     txt->i_line       = 0;
677     txt->i_line_count = 0;
678 }
679
680 static char *TextGetLine( text_t *txt )
681 {
682     if( txt->i_line >= txt->i_line_count )
683         return( NULL );
684
685     return txt->line[txt->i_line++];
686 }
687 static void TextPreviousLine( text_t *txt )
688 {
689     if( txt->i_line > 0 )
690         txt->i_line--;
691 }
692
693 /*****************************************************************************
694  * Specific Subtitle function
695  *****************************************************************************/
696 /* ParseMicroDvd:
697  *  Format:
698  *      {n1}{n2}Line1|Line2|Line3....
699  *  where n1 and n2 are the video frame number (n2 can be empty)
700  */
701 static int ParseMicroDvd( demux_t *p_demux, subtitle_t *p_subtitle )
702 {
703     demux_sys_t *p_sys = p_demux->p_sys;
704     text_t      *txt = &p_sys->txt;
705     char *psz_text;
706     int  i_start;
707     int  i_stop;
708     int  i;
709
710     for( ;; )
711     {
712         const char *s = TextGetLine( txt );
713         if( !s )
714             return VLC_EGENERIC;
715
716         psz_text = malloc( strlen(s) + 1 );
717         if( !psz_text )
718             return VLC_ENOMEM;
719
720         i_start = 0;
721         i_stop  = 0;
722         if( sscanf( s, "{%d}{}%[^\r\n]", &i_start, psz_text ) == 2 ||
723             sscanf( s, "{%d}{%d}%[^\r\n]", &i_start, &i_stop, psz_text ) == 3)
724         {
725             float f_fps;
726             if( i_start != 1 || i_stop != 1 )
727                 break;
728
729             /* We found a possible setting of the framerate "{1}{1}23.976" */
730             /* Check if it's usable, and if the sub-fps is not set */
731             f_fps = us_strtod( psz_text, NULL );
732             if( f_fps > 0.0 && var_GetFloat( p_demux, "sub-fps" ) <= 0.0 )
733                 p_sys->i_microsecperframe = (int64_t)((float)1000000 / f_fps);
734         }
735         free( psz_text );
736     }
737
738     /* replace | by \n */
739     for( i = 0; psz_text[i] != '\0'; i++ )
740     {
741         if( psz_text[i] == '|' )
742             psz_text[i] = '\n';
743     }
744
745     /* */
746     p_subtitle->i_start  = i_start * p_sys->i_microsecperframe;
747     p_subtitle->i_stop   = i_stop  * p_sys->i_microsecperframe;
748     p_subtitle->psz_text = psz_text;
749     return VLC_SUCCESS;
750 }
751
752 /* ParseSubRipSubViewer
753  *  Format SubRip
754  *      n
755  *      h1:m1:s1,d1 --> h2:m2:s2,d2
756  *      Line1
757  *      Line2
758  *      ....
759  *      [Empty line]
760  *  Format SubViewer v1/v2
761  *      h1:m1:s1.d1,h2:m2:s2.d2
762  *      Line1[br]Line2
763  *      Line3
764  *      ...
765  *      [empty line]
766  *  We ignore line number for SubRip
767  */
768 static int ParseSubRipSubViewer( demux_t *p_demux, subtitle_t *p_subtitle,
769                                  const char *psz_fmt,
770                                  vlc_bool_t b_replace_br )
771 {
772     demux_sys_t *p_sys = p_demux->p_sys;
773     text_t      *txt = &p_sys->txt;
774     char    *psz_text;
775
776     for( ;; )
777     {
778         const char *s = TextGetLine( txt );
779         int h1, m1, s1, d1, h2, m2, s2, d2;
780
781         if( !s )
782             return VLC_EGENERIC;
783
784         if( sscanf( s, psz_fmt,
785                     &h1, &m1, &s1, &d1,
786                     &h2, &m2, &s2, &d2 ) == 8 )
787         {
788             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
789                                     (int64_t)m1 * 60*1000 +
790                                     (int64_t)s1 * 1000 +
791                                     (int64_t)d1 ) * 1000;
792
793             p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
794                                     (int64_t)m2 * 60*1000 +
795                                     (int64_t)s2 * 1000 +
796                                     (int64_t)d2 ) * 1000;
797             break;
798         }
799     }
800
801     /* Now read text until an empty line */
802     psz_text = strdup("");
803     if( !psz_text )
804         return VLC_ENOMEM;
805     for( ;; )
806     {
807         const char *s = TextGetLine( txt );
808         int i_len;
809         int i_old;
810
811         if( !s )
812         {
813             free( psz_text );
814             return VLC_EGENERIC;
815         }
816
817         i_len = strlen( s );
818         if( i_len <= 0 )
819         {
820             p_subtitle->psz_text = psz_text;
821             return VLC_SUCCESS;
822         }
823
824         i_old = strlen( psz_text );
825         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
826         if( !psz_text )
827             return VLC_ENOMEM;
828         strcat( psz_text, s );
829         strcat( psz_text, "\n" );
830
831         /* replace [br] by \n */
832         if( b_replace_br )
833         {
834             char *p;
835  
836             while( ( p = strstr( psz_text, "[br]" ) ) )
837             {
838                 *p++ = '\n';
839                 memmove( p, &p[3], strlen(&p[3])+1 );
840             }
841         }
842     }
843 }
844 /* ParseSubRip
845  */
846 static int  ParseSubRip( demux_t *p_demux, subtitle_t *p_subtitle )
847 {
848     return ParseSubRipSubViewer( p_demux, p_subtitle,
849                                  "%d:%d:%d,%d --> %d:%d:%d,%d",
850                                  VLC_FALSE );
851 }
852 /* ParseSubViewer
853  */
854 static int  ParseSubViewer( demux_t *p_demux, subtitle_t *p_subtitle )
855 {
856     return ParseSubRipSubViewer( p_demux, p_subtitle,
857                                  "%d:%d:%d.%d,%d:%d:%d.%d",
858                                  VLC_TRUE );
859 }
860
861 /* ParseSSA
862  */
863 static int  ParseSSA( demux_t *p_demux, subtitle_t *p_subtitle )
864 {
865     demux_sys_t *p_sys = p_demux->p_sys;
866     text_t      *txt = &p_sys->txt;
867
868     for( ;; )
869     {
870         const char *s = TextGetLine( txt );
871         int h1, m1, s1, c1, h2, m2, s2, c2;
872         char *psz_text;
873
874         if( !s )
875             return VLC_EGENERIC;
876
877         /* We expect (SSA2-4):
878          * Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
879          * Dialogue: Marked=0,0:02:40.65,0:02:41.79,Wolf main,Cher,0000,0000,0000,,Et les enregistrements de ses ondes delta ?
880          *
881          * 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.
882          */
883
884         /* For ASS:
885          * Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
886          * Dialogue: Layer#,0:02:40.65,0:02:41.79,Wolf main,Cher,0000,0000,0000,,Et les enregistrements de ses ondes delta ?
887          */
888         psz_text = malloc( 2 + strlen( s ) + 1 );
889         if( !psz_text )
890             return VLC_ENOMEM;
891
892         if( sscanf( s,
893                     "Dialogue: %*[^,],%d:%d:%d.%d,%d:%d:%d.%d,%[^\r\n]",
894                     &h1, &m1, &s1, &c1,
895                     &h2, &m2, &s2, &c2,
896                     psz_text ) == 9 )
897         {
898             /* The dec expects: ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text */
899             /* (Layer comes from ASS specs ... it's empty for SSA.) */
900             if( p_sys->i_type == SUB_TYPE_SSA1 )
901             {
902                 /* SSA1 has only 8 commas before the text starts, not 9 */
903                 memmove( &psz_text[1], psz_text, strlen(psz_text)+1 );
904                 psz_text[0] = ',';
905             }
906             else
907             {
908                 /* ReadOrder, Layer, %s(rest of fields) */
909                 memmove( &psz_text[2], psz_text, strlen(psz_text)+1 );
910                 psz_text[0] = ',';
911                 psz_text[1] = ',';
912             }
913
914             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
915                                     (int64_t)m1 * 60*1000 +
916                                     (int64_t)s1 * 1000 +
917                                     (int64_t)c1 * 10 ) * 1000;
918             p_subtitle->i_stop  = ( (int64_t)h2 * 3600*1000 +
919                                     (int64_t)m2 * 60*1000 +
920                                     (int64_t)s2 * 1000 +
921                                     (int64_t)c2 * 10 ) * 1000;
922             p_subtitle->psz_text = psz_text;
923             return VLC_SUCCESS;
924         }
925         free( psz_text );
926
927         /* All the other stuff we add to the header field */
928         if( !p_sys->psz_header )
929             p_sys->psz_header = strdup( "" );
930         if( !p_sys->psz_header )
931             return VLC_ENOMEM;
932
933         p_sys->psz_header =
934             realloc( p_sys->psz_header,
935                      strlen( p_sys->psz_header ) + strlen( s ) + 2 );
936         strcat( p_sys->psz_header,  s );
937         strcat( p_sys->psz_header, "\n" );
938     }
939 }
940
941 /* ParseVplayer
942  *  Format
943  *      h:m:s:Line1|Line2|Line3....
944  *  or
945  *      h:m:s Line1|Line2|Line3....
946  */
947 static int  ParseVplayer( demux_t *p_demux, subtitle_t *p_subtitle )
948 {
949     demux_sys_t *p_sys = p_demux->p_sys;
950     text_t      *txt = &p_sys->txt;
951     char *psz_text;
952     int i;
953
954     for( ;; )
955     {
956         const char *s = TextGetLine( txt );
957         int h1, m1, s1;
958
959         if( !s )
960             return VLC_EGENERIC;
961
962         psz_text = malloc( strlen( s ) + 1 );
963         if( !psz_text )
964             return VLC_ENOMEM;
965
966         if( sscanf( s, "%d:%d:%d%*c%[^\r\n]",
967                     &h1, &m1, &s1, psz_text ) == 4 )
968         {
969             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
970                                     (int64_t)m1 * 60*1000 +
971                                     (int64_t)s1 * 1000 ) * 1000;
972             p_subtitle->i_stop  = 0;
973             break;
974         }
975         free( psz_text );
976     }
977
978     /* replace | by \n */
979     for( i = 0; psz_text[i] != '\0'; i++ )
980     {
981         if( psz_text[i] == '|' )
982             psz_text[i] = '\n';
983     }
984     p_subtitle->psz_text = psz_text;
985     return VLC_SUCCESS;
986 }
987
988 /* ParseSami
989  */
990 static char *ParseSamiSearch( text_t *txt,
991                               char *psz_start, const char *psz_str )
992 {
993     if( psz_start && strcasestr( psz_start, psz_str ) )
994     {
995         char *s = strcasestr( psz_start, psz_str );
996         return &s[strlen( psz_str )];
997     }
998
999     for( ;; )
1000     {
1001         char *p = TextGetLine( txt );
1002         if( !p )
1003             return NULL;
1004
1005         if( strcasestr( p, psz_str ) )
1006         {
1007             char *s = strcasestr( p, psz_str );
1008             return &s[strlen( psz_str )];
1009         }
1010     }
1011 }
1012 static int  ParseSami( demux_t *p_demux, subtitle_t *p_subtitle )
1013 {
1014     demux_sys_t *p_sys = p_demux->p_sys;
1015     text_t      *txt = &p_sys->txt;
1016
1017     char *s;
1018     int64_t i_start;
1019
1020     unsigned int i_text;
1021     char text[8192]; /* Arbitrary but should be long enough */
1022
1023     /* search "Start=" */
1024     if( !( s = ParseSamiSearch( txt, NULL, "Start=" ) ) )
1025         return VLC_EGENERIC;
1026
1027     /* get start value */
1028     i_start = strtol( s, &s, 0 );
1029
1030     /* search <P */
1031     if( !( s = ParseSamiSearch( txt, s, "<P" ) ) )
1032         return VLC_EGENERIC;
1033
1034     /* search > */
1035     if( !( s = ParseSamiSearch( txt, s, ">" ) ) )
1036         return VLC_EGENERIC;
1037
1038     i_text = 0;
1039     text[0] = '\0';
1040     /* now get all txt until  a "Start=" line */
1041     for( ;; )
1042     {
1043         char c = '\0';
1044         /* Search non empty line */
1045         while( s && *s == '\0' )
1046             s = TextGetLine( txt );
1047         if( !s )
1048             break;
1049
1050         if( *s == '<' )
1051         {
1052             if( !strncasecmp( s, "<br", 3 ) )
1053             {
1054                 c = '\n';
1055             }
1056             else if( strcasestr( s, "Start=" ) )
1057             {
1058                 TextPreviousLine( txt );
1059                 break;
1060             }
1061             s = ParseSamiSearch( txt, s, ">" );
1062         }
1063         else if( !strncmp( s, "&nbsp;", 6 ) )
1064         {
1065             c = ' ';
1066             s += 6;
1067         }
1068         else if( *s == '\t' )
1069         {
1070             c = ' ';
1071             s++;
1072         }
1073         else
1074         {
1075             c = *s;
1076             s++;
1077         }
1078         if( c != '\0' && i_text+1 < sizeof(text) )
1079         {
1080             text[i_text++] = c;
1081             text[i_text] = '\0';
1082         }
1083     }
1084
1085     p_subtitle->i_start = i_start * 1000;
1086     p_subtitle->i_stop  = 0;
1087     p_subtitle->psz_text = strdup( text );
1088
1089     return VLC_SUCCESS;
1090 }
1091
1092 /* ParseDVDSubtitle
1093  *  Format
1094  *      {T h1:m1:s1:c1
1095  *      Line1
1096  *      Line2
1097  *      ...
1098  *      }
1099  * TODO it can have a header
1100  *      { HEAD
1101  *          ...
1102  *          CODEPAGE=...
1103  *          FORMAT=...
1104  *          LANG=English
1105  *      }
1106  *      LANG support would be cool
1107  *      CODEPAGE is probably mandatory FIXME
1108  */
1109 static int ParseDVDSubtitle( demux_t *p_demux, subtitle_t *p_subtitle )
1110 {
1111     demux_sys_t *p_sys = p_demux->p_sys;
1112     text_t      *txt = &p_sys->txt;
1113     char *psz_text;
1114
1115     for( ;; )
1116     {
1117         const char *s = TextGetLine( txt );
1118         int h1, m1, s1, c1;
1119
1120         if( !s )
1121             return VLC_EGENERIC;
1122
1123         if( sscanf( s,
1124                     "{T %d:%d:%d:%d",
1125                     &h1, &m1, &s1, &c1 ) == 4 )
1126         {
1127             p_subtitle->i_start = ( (int64_t)h1 * 3600*1000 +
1128                                     (int64_t)m1 * 60*1000 +
1129                                     (int64_t)s1 * 1000 +
1130                                     (int64_t)c1 * 10) * 1000;
1131             p_subtitle->i_stop = 0;
1132             break;
1133         }
1134     }
1135
1136     /* Now read text until a line containing "}" */
1137     psz_text = strdup("");
1138     if( !psz_text )
1139         return VLC_ENOMEM;
1140     for( ;; )
1141     {
1142         const char *s = TextGetLine( txt );
1143         int i_len;
1144         int i_old;
1145
1146         if( !s )
1147         {
1148             free( psz_text );
1149             return VLC_EGENERIC;
1150         }
1151
1152         i_len = strlen( s );
1153         if( i_len == 1 && s[0] == '}')
1154         {
1155             p_subtitle->psz_text = psz_text;
1156             return VLC_SUCCESS;
1157         }
1158
1159         i_old = strlen( psz_text );
1160         psz_text = realloc( psz_text, i_old + i_len + 1 + 1 );
1161         if( !psz_text )
1162             return VLC_ENOMEM;
1163         strcat( psz_text, s );
1164         strcat( psz_text, "\n" );
1165     }
1166 }
1167
1168 /* ParseMPL2
1169  *  Format
1170  *     [n1][n2]Line1|Line2|Line3...
1171  *  where n1 and n2 are the video frame number (n2 can be empty)
1172  */
1173 static int ParseMPL2( demux_t *p_demux, subtitle_t *p_subtitle )
1174 {
1175     demux_sys_t *p_sys = p_demux->p_sys;
1176     text_t      *txt = &p_sys->txt;
1177     char *psz_text;
1178     int i;
1179
1180     for( ;; )
1181     {
1182         const char *s = TextGetLine( txt );
1183         int i_start;
1184         int i_stop;
1185
1186         if( !s )
1187             return VLC_EGENERIC;
1188
1189         psz_text = malloc( strlen(s) + 1 );
1190         if( !psz_text )
1191             return VLC_ENOMEM;
1192
1193         i_start = 0;
1194         i_stop  = 0;
1195         if( sscanf( s, "[%d][] %[^\r\n]", &i_start, psz_text ) == 2 ||
1196             sscanf( s, "[%d][%d] %[^\r\n]", &i_start, &i_stop, psz_text ) == 3)
1197         {
1198             p_subtitle->i_start = (int64_t)i_start * 100000;
1199             p_subtitle->i_stop  = (int64_t)i_stop  * 100000;
1200             break;
1201         }
1202         free( psz_text );
1203     }
1204
1205     /* replace | by \n */
1206     for( i = 0; psz_text[i] != '\0'; )
1207     {
1208         if( psz_text[i] == '|' )
1209             psz_text[i] = '\n';
1210
1211         /* Remove italic */
1212         if( psz_text[i] == '/' && ( i == 0 || psz_text[i-1] == '\n' ) )
1213             memmove( &psz_text[i], &psz_text[i+1], strlen(&psz_text[i+1])+1 );
1214         else
1215             i++;
1216     }
1217     p_subtitle->psz_text = psz_text;
1218     return VLC_SUCCESS;
1219 }
1220