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