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