PS: fix length computation
[vlc.git] / modules / demux / ps.c
1 /*****************************************************************************
2  * ps.c: Program Stream demux module for VLC.
3  *****************************************************************************
4  * Copyright (C) 2004-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_demux.h>
35
36 #include "ps.h"
37
38 /* TODO:
39  *  - re-add pre-scanning.
40  *  - ...
41  */
42
43 #define TIME_TEXT N_("Trust MPEG timestamps")
44 #define TIME_LONGTEXT N_("Normally we use the timestamps of the MPEG files " \
45     "to calculate position and duration. However sometimes this might not " \
46     "be usable. Disable this option to calculate from the bitrate instead." )
47
48 /*****************************************************************************
49  * Module descriptor
50  *****************************************************************************/
51 static int  OpenForce( vlc_object_t * );
52 static int  Open   ( vlc_object_t * );
53 static void Close  ( vlc_object_t * );
54
55 vlc_module_begin ()
56     set_description( N_("MPEG-PS demuxer") )
57     set_shortname( N_("PS") )
58     set_category( CAT_INPUT )
59     set_subcategory( SUBCAT_INPUT_DEMUX )
60     set_capability( "demux", 1 )
61     set_callbacks( OpenForce, Close )
62     add_shortcut( "ps" )
63
64     add_bool( "ps-trust-timestamps", true, TIME_TEXT,
65                  TIME_LONGTEXT, true )
66         change_safe ()
67
68     add_submodule ()
69     set_description( N_("MPEG-PS demuxer") )
70     set_capability( "demux", 8 )
71     set_callbacks( Open, Close )
72     add_shortcut( "ps" )
73 vlc_module_end ()
74
75 /*****************************************************************************
76  * Local prototypes
77  *****************************************************************************/
78
79 struct demux_sys_t
80 {
81     ps_psm_t    psm;
82     ps_track_t  tk[PS_TK_COUNT];
83
84     int64_t     i_scr;
85     int64_t     i_last_scr;
86     int         i_mux_rate;
87     int64_t     i_length;
88     int         i_time_track;
89     int64_t     i_current_pts;
90
91     int         i_aob_mlp_count;
92
93     bool  b_lost_sync;
94     bool  b_have_pack;
95     bool  b_seekable;
96 };
97
98 static int Demux  ( demux_t *p_demux );
99 static int Control( demux_t *p_demux, int i_query, va_list args );
100
101 static int      ps_pkt_resynch( stream_t *, uint32_t *pi_code );
102 static block_t *ps_pkt_read   ( stream_t *, uint32_t i_code );
103
104 /*****************************************************************************
105  * Open
106  *****************************************************************************/
107 static int OpenCommon( vlc_object_t *p_this, bool b_force )
108 {
109     demux_t     *p_demux = (demux_t*)p_this;
110     demux_sys_t *p_sys;
111
112     const uint8_t *p_peek;
113
114     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
115     {
116         msg_Err( p_demux, "cannot peek" );
117         return VLC_EGENERIC;
118     }
119
120     if( memcmp( p_peek, "\x00\x00\x01", 3 ) || ( p_peek[3] < 0xb9 ) )
121     {
122         if( !b_force )
123             return VLC_EGENERIC;
124
125         msg_Warn( p_demux, "this does not look like an MPEG PS stream, "
126                   "continuing anyway" );
127     }
128
129     /* Fill p_demux field */
130     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
131     if( !p_sys ) return VLC_ENOMEM;
132
133     p_demux->pf_demux = Demux;
134     p_demux->pf_control = Control;
135
136     /* Init p_sys */
137     p_sys->i_mux_rate = 0;
138     p_sys->i_scr      = -1;
139     p_sys->i_last_scr = -1;
140     p_sys->i_length   = -1;
141     p_sys->i_current_pts = (mtime_t) 0;
142     p_sys->i_time_track = -1;
143     p_sys->i_aob_mlp_count = 0;
144
145     p_sys->b_lost_sync = false;
146     p_sys->b_have_pack = false;
147     p_sys->b_seekable  = false;
148
149     stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
150
151     ps_psm_init( &p_sys->psm );
152     ps_track_init( p_sys->tk );
153
154     /* TODO prescanning of ES */
155
156     return VLC_SUCCESS;
157 }
158
159 static int OpenForce( vlc_object_t *p_this )
160 {
161     return OpenCommon( p_this, true );
162 }
163
164 static int Open( vlc_object_t *p_this )
165 {
166     return OpenCommon( p_this, ((demux_t *)p_this)->b_force );
167 }
168
169 /*****************************************************************************
170  * Close
171  *****************************************************************************/
172 static void Close( vlc_object_t *p_this )
173 {
174     demux_t     *p_demux = (demux_t*)p_this;
175     demux_sys_t *p_sys = p_demux->p_sys;
176     int i;
177
178     for( i = 0; i < PS_TK_COUNT; i++ )
179     {
180         ps_track_t *tk = &p_sys->tk[i];
181         if( tk->b_seen )
182         {
183             es_format_Clean( &tk->fmt );
184             if( tk->es ) es_out_Del( p_demux->out, tk->es );
185         }
186     }
187
188     ps_psm_destroy( &p_sys->psm );
189
190     free( p_sys );
191 }
192
193 static int Demux2( demux_t *p_demux, bool b_end )
194 {
195     demux_sys_t *p_sys = p_demux->p_sys;
196     int i_ret, i_id;
197     uint32_t i_code;
198     block_t *p_pkt;
199
200     i_ret = ps_pkt_resynch( p_demux->s, &i_code );
201     if( i_ret < 0 )
202     {
203         return 0;
204     }
205     else if( i_ret == 0 )
206     {
207         if( !p_sys->b_lost_sync )
208             msg_Warn( p_demux, "garbage at input, trying to resync..." );
209
210         p_sys->b_lost_sync = true;
211         return 1;
212     }
213
214     if( p_sys->b_lost_sync ) msg_Warn( p_demux, "found sync code" );
215     p_sys->b_lost_sync = false;
216
217     if( ( p_pkt = ps_pkt_read( p_demux->s, i_code ) ) == NULL )
218     {
219         return 0;
220     }
221     if( (i_id = ps_pkt_id( p_pkt )) >= 0xc0 )
222     {
223         ps_track_t *tk = &p_sys->tk[PS_ID_TO_TK(i_id)];
224         if( !ps_pkt_parse_pes( p_pkt, tk->i_skip ) && p_pkt->i_pts > VLC_TS_INVALID )
225         {
226             if( b_end && p_pkt->i_pts > tk->i_last_pts )
227             {
228                 tk->i_last_pts = p_pkt->i_pts;
229             }
230             else if ( tk->i_first_pts == -1 )
231             {
232                 tk->i_first_pts = p_pkt->i_pts;
233             }
234         }
235     }
236     block_Release( p_pkt );
237     return 1;
238 }
239
240 static void FindLength( demux_t *p_demux )
241 {
242     demux_sys_t *p_sys = p_demux->p_sys;
243     int64_t i_current_pos = -1, i_size = 0, i_end = 0;
244
245     if( !var_CreateGetBool( p_demux, "ps-trust-timestamps" ) )
246         return;
247
248     if( p_sys->i_length == -1 ) /* First time */
249     {
250         p_sys->i_length = 0;
251         /* Check beginning */
252         int i = 0;
253         i_current_pos = stream_Tell( p_demux->s );
254         while( vlc_object_alive (p_demux) && i < 40 && Demux2( p_demux, false ) > 0 ) i++;
255
256         /* Check end */
257         i_size = stream_Size( p_demux->s );
258         i_end = VLC_CLIP( i_size, 0, 200000 );
259         stream_Seek( p_demux->s, i_size - i_end );
260
261         i = 0;
262         while( vlc_object_alive (p_demux) && i < 400 && Demux2( p_demux, true ) > 0 ) i++;
263         if( i_current_pos >= 0 ) stream_Seek( p_demux->s, i_current_pos );
264     }
265
266     /* Find the longest track */
267     for( int i = 0; i < PS_TK_COUNT; i++ )
268     {
269         ps_track_t *tk = &p_sys->tk[i];
270         if( tk->i_last_pts > 0 &&
271             tk->i_last_pts > tk->i_first_pts )
272         {
273             int64_t i_length = (int64_t)tk->i_last_pts - tk->i_first_pts;
274             if( i_length > p_sys->i_length )
275             {
276                 p_sys->i_length = i_length;
277                 p_sys->i_time_track = i;
278                 msg_Dbg( p_demux, "we found a length of: %"PRId64 "s", p_sys->i_length / CLOCK_FREQ );
279             }
280         }
281     }
282 }
283
284 /*****************************************************************************
285  * Demux:
286  *****************************************************************************/
287 static int Demux( demux_t *p_demux )
288 {
289     demux_sys_t *p_sys = p_demux->p_sys;
290     int i_ret, i_id, i_mux_rate;
291     uint32_t i_code;
292     block_t *p_pkt;
293
294     i_ret = ps_pkt_resynch( p_demux->s, &i_code );
295     if( i_ret < 0 )
296     {
297         return 0;
298     }
299     else if( i_ret == 0 )
300     {
301         if( !p_sys->b_lost_sync )
302             msg_Warn( p_demux, "garbage at input, trying to resync..." );
303
304         p_sys->b_lost_sync = true;
305         return 1;
306     }
307
308     if( p_sys->b_lost_sync ) msg_Warn( p_demux, "found sync code" );
309     p_sys->b_lost_sync = false;
310
311     if( p_sys->i_length < 0 && p_sys->b_seekable )
312         FindLength( p_demux );
313
314     if( ( p_pkt = ps_pkt_read( p_demux->s, i_code ) ) == NULL )
315     {
316         return 0;
317     }
318
319     switch( i_code )
320     {
321     case 0x1b9:
322         block_Release( p_pkt );
323         break;
324
325     case 0x1ba:
326         if( !ps_pkt_parse_pack( p_pkt, &p_sys->i_scr, &i_mux_rate ) )
327         {
328             p_sys->i_last_scr = p_sys->i_scr;
329             if( !p_sys->b_have_pack ) p_sys->b_have_pack = true;
330             /* done later on to work around bad vcd/svcd streams */
331             /* es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_scr ); */
332             if( i_mux_rate > 0 ) p_sys->i_mux_rate = i_mux_rate;
333         }
334         block_Release( p_pkt );
335         break;
336
337     case 0x1bb:
338         if( !ps_pkt_parse_system( p_pkt, &p_sys->psm, p_sys->tk ) )
339         {
340             int i;
341             for( i = 0; i < PS_TK_COUNT; i++ )
342             {
343                 ps_track_t *tk = &p_sys->tk[i];
344
345                 if( tk->b_seen && !tk->es && tk->fmt.i_cat != UNKNOWN_ES )
346                 {
347                     tk->es = es_out_Add( p_demux->out, &tk->fmt );
348                 }
349             }
350         }
351         block_Release( p_pkt );
352         break;
353
354     case 0x1bc:
355         if( p_sys->psm.i_version == 0xFFFF )
356             msg_Dbg( p_demux, "contains a PSM");
357
358         ps_psm_fill( &p_sys->psm, p_pkt, p_sys->tk, p_demux->out );
359         block_Release( p_pkt );
360         break;
361
362     default:
363         if( (i_id = ps_pkt_id( p_pkt )) >= 0xc0 )
364         {
365             /* Small heuristic to improve MLP detection from AOB */
366             if( i_id == 0xa001 &&
367                 p_sys->i_aob_mlp_count < 500 )
368             {
369                 p_sys->i_aob_mlp_count++;
370             }
371             else if( i_id == 0xbda1 &&
372                      p_sys->i_aob_mlp_count > 0 )
373             {
374                 p_sys->i_aob_mlp_count--;
375                 i_id = 0xa001;
376             }
377
378             bool b_new = false;
379             ps_track_t *tk = &p_sys->tk[PS_ID_TO_TK(i_id)];
380
381             if( !tk->b_seen )
382             {
383                 if( !ps_track_fill( tk, &p_sys->psm, i_id, p_pkt ) )
384                 {
385                     tk->es = es_out_Add( p_demux->out, &tk->fmt );
386                     b_new = true;
387                 }
388                 else
389                 {
390                     msg_Dbg( p_demux, "es id=0x%x format unknown", i_id );
391                 }
392                 tk->b_seen = true;
393             }
394
395             /* The popular VCD/SVCD subtitling WinSubMux does not
396              * renumber the SCRs when merging subtitles into the PES */
397             if( tk->b_seen &&
398                 ( tk->fmt.i_codec == VLC_CODEC_OGT ||
399                   tk->fmt.i_codec == VLC_CODEC_CVD ) )
400             {
401                 p_sys->i_scr = -1;
402                 p_sys->i_last_scr = -1;
403             }
404
405             if( p_sys->i_scr >= 0 )
406                 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_scr );
407
408             p_sys->i_scr = -1;
409
410             if( tk->b_seen && tk->es &&
411                 !ps_pkt_parse_pes( p_pkt, tk->i_skip ) )
412             {
413                 if( !b_new && !p_sys->b_have_pack &&
414                     (tk->fmt.i_cat == AUDIO_ES) &&
415                     (p_pkt->i_pts > VLC_TS_INVALID) )
416                 {
417                     /* A hack to sync the A/V on PES files. */
418                     msg_Dbg( p_demux, "force SCR: %"PRId64, p_pkt->i_pts );
419                     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_pkt->i_pts );
420                 }
421                 if( tk->fmt.i_codec == VLC_CODEC_TELETEXT &&
422                     p_pkt->i_pts <= VLC_TS_INVALID && p_sys->i_last_scr >= 0 )
423                 {
424                     /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
425                      * In this case use the last SCR + 40ms */
426                     p_pkt->i_pts = VLC_TS_0 + p_sys->i_last_scr + 40000;
427                 }
428
429                 if( (int64_t)p_pkt->i_pts > p_sys->i_current_pts )
430                 {
431                     p_sys->i_current_pts = (int64_t)p_pkt->i_pts;
432                 }
433
434                 es_out_Send( p_demux->out, tk->es, p_pkt );
435             }
436             else
437             {
438                 block_Release( p_pkt );
439             }
440         }
441         else
442         {
443             block_Release( p_pkt );
444         }
445         break;
446     }
447
448     demux_UpdateTitleFromStream( p_demux );
449     return 1;
450 }
451
452 /*****************************************************************************
453  * Control:
454  *****************************************************************************/
455 static int Control( demux_t *p_demux, int i_query, va_list args )
456 {
457     demux_sys_t *p_sys = p_demux->p_sys;
458     double f, *pf;
459     int64_t i64, *pi64;
460
461     switch( i_query )
462     {
463         case DEMUX_GET_POSITION:
464             pf = (double*) va_arg( args, double* );
465             i64 = stream_Size( p_demux->s );
466             if( i64 > 0 )
467             {
468                 double current = stream_Tell( p_demux->s );
469                 *pf = current / (double)i64;
470             }
471             else
472             {
473                 *pf = 0.0;
474             }
475             return VLC_SUCCESS;
476
477         case DEMUX_SET_POSITION:
478             f = (double) va_arg( args, double );
479             i64 = stream_Size( p_demux->s );
480             p_sys->i_current_pts = 0;
481             p_sys->i_last_scr = -1;
482
483             return stream_Seek( p_demux->s, (int64_t)(i64 * f) );
484
485         case DEMUX_GET_TIME:
486             pi64 = (int64_t*)va_arg( args, int64_t * );
487             if( p_sys->i_time_track >= 0 && p_sys->i_current_pts > 0 )
488             {
489                 *pi64 = p_sys->i_current_pts - p_sys->tk[p_sys->i_time_track].i_first_pts;
490                 return VLC_SUCCESS;
491             }
492             if( p_sys->i_mux_rate > 0 )
493             {
494                 *pi64 = (int64_t)1000000 * ( stream_Tell( p_demux->s ) / 50 ) /
495                     p_sys->i_mux_rate;
496                 return VLC_SUCCESS;
497             }
498             *pi64 = 0;
499             return VLC_EGENERIC;
500
501         case DEMUX_GET_LENGTH:
502             pi64 = (int64_t*)va_arg( args, int64_t * );
503             if( p_sys->i_length > 0 )
504             {
505                 *pi64 = p_sys->i_length;
506                 return VLC_SUCCESS;
507             }
508             else if( p_sys->i_mux_rate > 0 )
509             {
510                 *pi64 = (int64_t)1000000 * ( stream_Size( p_demux->s ) / 50 ) /
511                     p_sys->i_mux_rate;
512                 return VLC_SUCCESS;
513             }
514             *pi64 = 0;
515             return VLC_EGENERIC;
516
517         case DEMUX_SET_TIME:
518             i64 = (int64_t)va_arg( args, int64_t );
519             if( p_sys->i_time_track >= 0 && p_sys->i_current_pts > 0 )
520             {
521                 int64_t i_now = p_sys->i_current_pts - p_sys->tk[p_sys->i_time_track].i_first_pts;
522                 int64_t i_pos = stream_Tell( p_demux->s );
523
524                 if( !i_now )
525                     return i64 ? VLC_EGENERIC : VLC_SUCCESS;
526
527                 p_sys->i_current_pts = 0;
528                 p_sys->i_last_scr = -1;
529                 i_pos *= (float)i64 / (float)i_now;
530                 stream_Seek( p_demux->s, i_pos );
531                 return VLC_SUCCESS;
532             }
533             return VLC_EGENERIC;
534
535         case DEMUX_GET_TITLE_INFO:
536         {
537             struct input_title_t ***v = va_arg( args, struct input_title_t*** );
538             int *c = va_arg( args, int * );
539
540             *va_arg( args, int* ) = 0; /* Title offset */
541             *va_arg( args, int* ) = 0; /* Chapter offset */
542             return stream_Control( p_demux->s, STREAM_GET_TITLE_INFO, v, c );
543         }
544
545         case DEMUX_SET_TITLE:
546             return stream_vaControl( p_demux->s, STREAM_SET_TITLE, args );
547
548         case DEMUX_SET_SEEKPOINT:
549             return stream_vaControl( p_demux->s, STREAM_SET_SEEKPOINT, args );
550
551         case DEMUX_GET_META:
552             return stream_vaControl( p_demux->s, STREAM_GET_META, args );
553
554         case DEMUX_GET_FPS:
555         default:
556             return VLC_EGENERIC;
557     }
558 }
559
560 /*****************************************************************************
561  * Divers:
562  *****************************************************************************/
563
564 /* PSResynch: resynch on a system startcode
565  *  It doesn't skip more than 512 bytes
566  *  -1 -> error, 0 -> not synch, 1 -> ok
567  */
568 static int ps_pkt_resynch( stream_t *s, uint32_t *pi_code )
569 {
570     const uint8_t *p_peek;
571     int     i_peek;
572     int     i_skip;
573
574     if( stream_Peek( s, &p_peek, 4 ) < 4 )
575     {
576         return -1;
577     }
578     if( p_peek[0] == 0 && p_peek[1] == 0 && p_peek[2] == 1 &&
579         p_peek[3] >= 0xb9 )
580     {
581         *pi_code = 0x100 | p_peek[3];
582         return 1;
583     }
584
585     if( ( i_peek = stream_Peek( s, &p_peek, 512 ) ) < 4 )
586     {
587         return -1;
588     }
589     i_skip = 0;
590
591     for( ;; )
592     {
593         if( i_peek < 4 )
594         {
595             break;
596         }
597         if( p_peek[0] == 0 && p_peek[1] == 0 && p_peek[2] == 1 &&
598             p_peek[3] >= 0xb9 )
599         {
600             *pi_code = 0x100 | p_peek[3];
601             return stream_Read( s, NULL, i_skip ) == i_skip ? 1 : -1;
602         }
603
604         p_peek++;
605         i_peek--;
606         i_skip++;
607     }
608     return stream_Read( s, NULL, i_skip ) == i_skip ? 0 : -1;
609 }
610
611 static block_t *ps_pkt_read( stream_t *s, uint32_t i_code )
612 {
613     const uint8_t *p_peek;
614     int i_peek = stream_Peek( s, &p_peek, 14 );
615     if( i_peek < 4 )
616         return NULL;
617
618     int i_size = ps_pkt_size( p_peek, i_peek );
619     if( i_size <= 6 && p_peek[3] > 0xba )
620     {
621         /* Special case, search the next start code */
622         i_size = 6;
623         for( ;; )
624         {
625             i_peek = stream_Peek( s, &p_peek, i_size + 1024 );
626             if( i_peek <= i_size + 4 )
627             {
628                 return NULL;
629             }
630             while( i_size <= i_peek - 4 )
631             {
632                 if( p_peek[i_size] == 0x00 && p_peek[i_size+1] == 0x00 &&
633                     p_peek[i_size+2] == 0x01 && p_peek[i_size+3] >= 0xb9 )
634                 {
635                     return stream_Block( s, i_size );
636                 }
637                 i_size++;
638             }
639         }
640     }
641     else
642     {
643         /* Normal case */
644         return stream_Block( s, i_size );
645     }
646
647     VLC_UNUSED(i_code);
648     return NULL;
649 }