]> git.sesse.net Git - vlc/blob - src/input/mpeg_system.c
* Changed code for handling b_die in bitstream ;
[vlc] / src / input / mpeg_system.c
1 /*****************************************************************************
2  * mpeg_system.c: TS, PS and PES management
3  *****************************************************************************
4  * Copyright (C) 1998, 1999, 2000 VideoLAN
5  * $Id: mpeg_system.c,v 1.26 2001/01/10 19:22:11 massiot Exp $
6  *
7  * Authors: 
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 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 General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include "defs.h"
28
29 #include <stdlib.h>
30
31 #include "config.h"
32 #include "common.h"
33 #include "threads.h"
34 #include "mtime.h"
35
36 #include "intf_msg.h"
37
38 #include "stream_control.h"
39 #include "input_ext-intf.h"
40 #include "input_ext-dec.h"
41
42 #include "input.h"
43 #include "mpeg_system.h"
44
45 #include "main.h"                           /* AC3/MPEG channel, SPU channel */
46
47 /*****************************************************************************
48  * Local prototypes
49  *****************************************************************************/
50
51
52 /*
53  * PES Packet management
54  */
55
56 /*****************************************************************************
57  * MoveChunk
58  *****************************************************************************
59  * Small utility function used to parse discontinuous headers safely. Copies
60  * i_buf_len bytes of data to a buffer and returns the size copied.
61  * This is a variation on the theme of input_ext-dec.h:GetChunk().
62  *****************************************************************************/
63 static __inline__ size_t MoveChunk( byte_t * p_dest,
64                                     data_packet_t ** pp_data_src,
65                                     byte_t ** pp_src,
66                                     size_t i_buf_len )
67 {
68     ptrdiff_t           i_available;
69
70     if( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
71             >= i_buf_len )
72     {
73         if( p_dest != NULL )
74             memcpy( p_dest, *pp_src, i_buf_len );
75         *pp_src += i_buf_len;
76         return( i_buf_len );
77     }
78     else
79     {
80         size_t          i_init_len = i_buf_len;
81
82         do
83         {
84             if( p_dest != NULL )
85                 memcpy( p_dest, *pp_src, i_available );
86             *pp_data_src = (*pp_data_src)->p_next;
87             i_buf_len -= i_available;
88             p_dest += i_available;
89             if( *pp_data_src == NULL )
90             {
91                 *pp_src = NULL;
92                 return( i_init_len - i_buf_len );
93             }
94             *pp_src = (*pp_data_src)->p_payload_start;
95         }
96         while( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
97                 <= i_buf_len );
98
99         if( i_buf_len )
100         {
101             if( p_dest != NULL )
102                 memcpy( p_dest, *pp_src, i_buf_len );
103             *pp_src += i_buf_len;
104         }
105         return( i_init_len );
106     }
107 }
108
109 /*****************************************************************************
110  * input_ParsePES
111  *****************************************************************************
112  * Parse a finished PES packet and analyze its header.
113  *****************************************************************************/
114 #define PES_HEADER_SIZE     7
115 void input_ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
116 {
117     data_packet_t * p_data;
118     byte_t *        p_byte;
119     byte_t          p_header[PES_HEADER_SIZE];
120     int             i_done;
121
122 #define p_pes (p_es->p_pes)
123
124     //intf_DbgMsg("End of PES packet %p", p_pes);
125
126     /* Parse the header. The header has a variable length, but in order
127      * to improve the algorithm, we will read the 14 bytes we may be
128      * interested in */
129     p_data = p_pes->p_first;
130     p_byte = p_data->p_payload_start;
131     i_done = 0;
132
133     if( MoveChunk( p_header, &p_data, &p_byte, PES_HEADER_SIZE )
134             != PES_HEADER_SIZE )
135     {
136         intf_WarnMsg( 3, "PES packet too short to have a header" );
137         p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
138         p_pes = NULL;
139         return;
140     }
141
142     /* Get the PES size if defined */
143     p_es->i_pes_real_size = U16_AT(p_header + 4) + 6;
144
145     /* First read the 6 header bytes common to all PES packets:
146      * use them to test the PES validity */
147     if( (p_header[0] || p_header[1] || (p_header[2] != 1)) )
148     {
149         /* packet_start_code_prefix != 0x000001 */
150         intf_ErrMsg( "PES packet doesn't start with 0x000001 : data loss" );
151         p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
152         p_pes = NULL;
153     }
154     else
155     {
156         int i_pes_header_size, i_payload_size;
157
158         if ( p_es->i_pes_real_size &&
159              (p_es->i_pes_real_size != p_pes->i_pes_size) )
160         {
161             /* PES_packet_length is set and != total received payload */
162             /* Warn the decoder that the data may be corrupt. */
163             intf_WarnMsg( 3, "PES sizes do not match : packet corrupted" );
164             p_pes->b_messed_up = 1;
165         }
166
167         switch( p_es->i_stream_id )
168         {
169         case 0xBC:  /* Program stream map */
170         case 0xBE:  /* Padding */
171         case 0xBF:  /* Private stream 2 */
172         case 0xB0:  /* ECM */
173         case 0xB1:  /* EMM */
174         case 0xFF:  /* Program stream directory */
175         case 0xF2:  /* DSMCC stream */
176         case 0xF8:  /* ITU-T H.222.1 type E stream */
177             /* The payload begins immediately after the 6 bytes header, so
178              * we have finished with the parsing */
179             i_pes_header_size = 6;
180             break;
181
182         default:
183             if( (p_header[6] & 0xC0) == 0x80 )
184             {
185                 /* MPEG-2 : the PES header contains at least 3 more bytes. */
186                 size_t      i_max_len;
187                 boolean_t   b_has_pts, b_has_dts;
188                 byte_t      p_full_header[12];
189
190                 p_pes->b_data_alignment = p_header[6] & 0x04;
191
192                 i_max_len = MoveChunk( p_full_header, &p_data, &p_byte, 12 );
193                 if( i_max_len < 2 )
194                 {
195                     intf_WarnMsg( 3,
196                             "PES packet too short to have a MPEG-2 header" );
197                     p_input->p_plugin->pf_delete_pes( p_input->p_method_data,
198                                                       p_pes );
199                     p_pes = NULL;
200                     return;
201                 }
202
203                 b_has_pts = p_full_header[0] & 0x80;
204                 b_has_dts = p_full_header[0] & 0x40;
205                 i_pes_header_size = p_full_header[1] + 9;
206
207                 /* Now parse the optional header extensions */
208                 if( b_has_pts )
209                 {
210                     if( i_max_len < 7 )
211                     {
212                         intf_WarnMsg( 3,
213                             "PES packet too short to have a MPEG-2 header" );
214                         p_input->p_plugin->pf_delete_pes(
215                                                       p_input->p_method_data,
216                                                       p_pes );
217                         p_pes = NULL;
218                         return;
219                     }
220                     p_pes->i_pts =
221                     ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
222                       (((mtime_t)U16_AT(p_full_header + 3) << 14) - (1 << 14)) |
223                       ((mtime_t)U16_AT(p_full_header + 5) >> 1) ) * 300;
224                     p_pes->i_pts /= 27;
225
226                     if( b_has_dts )
227                     {
228                         if( i_max_len < 12 )
229                         {
230                             intf_WarnMsg( 3,
231                               "PES packet too short to have a MPEG-2 header" );
232                             p_input->p_plugin->pf_delete_pes(
233                                     p_input->p_method_data,
234                                     p_pes );
235                             p_pes = NULL;
236                             return;
237                         }
238                         p_pes->i_dts =
239                         ( ((mtime_t)(p_full_header[7] & 0x0E) << 29) |
240                           (((mtime_t)U16_AT(p_full_header + 8) << 14)
241                                 - (1 << 14)) |
242                           ((mtime_t)U16_AT(p_full_header + 10) >> 1) ) * 300;
243                         p_pes->i_dts /= 27;
244                     }
245                 }
246             }
247             else
248             {
249                 /* Probably MPEG-1 */
250                 boolean_t       b_has_pts, b_has_dts;
251
252                 i_pes_header_size = 6;
253                 p_data = p_pes->p_first;
254                 p_byte = p_data->p_payload_start;
255                 /* Cannot fail because the previous one succeeded. */
256                 MoveChunk( NULL, &p_data, &p_byte, 6 );
257
258                 while( *p_byte == 0xFF && i_pes_header_size < 22 )
259                 {
260                     i_pes_header_size++;
261                     if( MoveChunk( NULL, &p_data, &p_byte, 1 ) != 1 )
262                     {
263                         intf_WarnMsg( 3,
264                             "PES packet too short to have a MPEG-1 header" );
265                         p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
266                         p_pes = NULL;
267                         return;
268                     }
269                 }
270                 if( i_pes_header_size == 22 )
271                 {
272                     intf_ErrMsg( "Too much MPEG-1 stuffing" );
273                     p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
274                     p_pes = NULL;
275                     return;
276                 }
277
278                 if( (*p_byte & 0xC0) == 0x40 )
279                 {
280                     /* Don't ask why... --Meuuh */
281                     /* Erm... why ? --Sam */
282                     /* Well... According to the recommendation, it is for
283                      * STD_buffer_scale and STD_buffer_size. --Meuuh */
284                     i_pes_header_size += 2;
285                     if( MoveChunk( NULL, &p_data, &p_byte, 2 ) != 2 )
286                     {
287                         intf_WarnMsg( 3,
288                             "PES packet too short to have a MPEG-1 header" );
289                         p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
290                         p_pes = NULL;
291                         return;
292                     }
293                 }
294
295                 i_pes_header_size++;
296
297                 b_has_pts = *p_byte & 0x20;
298                 b_has_dts = *p_byte & 0x10;
299
300                 if( b_has_pts )
301                 {
302                     byte_t      p_ts[5];
303
304                     i_pes_header_size += 4;
305                     if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
306                     {
307                         intf_WarnMsg( 3,
308                             "PES packet too short to have a MPEG-1 header" );
309                         p_input->p_plugin->pf_delete_pes(
310                                             p_input->p_method_data, p_pes );
311                         p_pes = NULL;
312                         return;
313                     }
314
315                     p_pes->i_pts =
316                       ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
317                         (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
318                         ((mtime_t)U16_AT(p_ts + 3) >> 1) ) * 300;
319                     p_pes->i_pts /= 27;
320
321                     if( b_has_dts )
322                     {
323                         i_pes_header_size += 5;
324                         if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
325                         {
326                             intf_WarnMsg( 3,
327                               "PES packet too short to have a MPEG-1 header" );
328                             p_input->p_plugin->pf_delete_pes(
329                                     p_input->p_method_data, p_pes );
330                             p_pes = NULL;
331                             return;
332                         }
333
334                         p_pes->i_dts =
335                             ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
336                               (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
337                               ((mtime_t)U16_AT(p_ts + 3) >> 1) ) * 300;
338                         p_pes->i_dts /= 27;
339                     }
340                 }
341             }
342
343             /* PTS management */
344             if( p_pes->i_pts )
345             {
346                 //intf_Msg("%lld", p_pes->i_pts);
347                 switch( p_es->p_pgrm->i_synchro_state )
348                 {
349                 case SYNCHRO_NOT_STARTED:
350                 case SYNCHRO_START:
351                     p_pes->i_pts = p_pes->i_dts = 0;
352                     break;
353
354                 case SYNCHRO_REINIT: /* We skip a PES | Why ?? --Meuuh */
355                     p_pes->i_pts = p_pes->i_dts = 0;
356                     p_es->p_pgrm->i_synchro_state = SYNCHRO_START;
357                     break;
358
359                 case SYNCHRO_OK:
360                     p_pes->i_pts += p_es->p_pgrm->delta_cr
361                                          + p_es->p_pgrm->delta_absolute
362                                          + DEFAULT_PTS_DELAY;
363                     if( p_pes->i_dts )
364                     {
365                         p_pes->i_dts += p_es->p_pgrm->delta_cr
366                                              + p_es->p_pgrm->delta_absolute
367                                              + DEFAULT_PTS_DELAY;
368                     }
369                     break;
370                 }
371             }
372             break;
373         }
374
375         if( p_es->i_stream_id == 0xbd )
376         {
377             /* With private stream 1, the first byte of the payload
378              * is a stream_private_id, so skip it. */
379             i_pes_header_size++;
380         }
381
382         /* Now we've parsed the header, we just have to indicate in some
383          * specific data packets where the PES payload begins (renumber
384          * p_payload_start), so that the decoders can find the beginning
385          * of their data right out of the box. */
386         p_data = p_pes->p_first;
387         i_payload_size = p_data->p_payload_end
388                                  - p_data->p_payload_start;
389         while( i_pes_header_size > i_payload_size )
390         {
391             /* These packets are entirely filled by the PES header. */
392             i_pes_header_size -= i_payload_size;
393             p_data->p_payload_start = p_data->p_payload_end;
394             /* Go to the next data packet. */
395             if( (p_data = p_data->p_next) == NULL )
396             {
397                 intf_ErrMsg( "PES header bigger than payload" );
398                 p_input->p_plugin->pf_delete_pes( p_input->p_method_data,
399                                                   p_pes );
400                 p_pes = NULL;
401                 return;
402             }
403             i_payload_size = p_data->p_payload_end
404                                  - p_data->p_payload_start;
405         }
406         /* This last packet is partly header, partly payload. */
407         if( i_payload_size < i_pes_header_size )
408         {
409             intf_ErrMsg( "PES header bigger than payload" );
410             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
411             p_pes = NULL;
412             return;
413         }
414         p_data->p_payload_start += i_pes_header_size;
415
416         /* Now we can eventually put the PES packet in the decoder's
417          * PES fifo */
418         if( p_es->p_decoder_fifo != NULL )
419         {
420             input_DecodePES( p_es->p_decoder_fifo, p_pes );
421         }
422         else
423         {
424             intf_ErrMsg("No fifo to receive PES %p (who wrote this damn code ?)",
425                         p_pes);
426             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
427         }
428         p_pes = NULL;
429     }
430 #undef p_pes
431 }
432
433 /*****************************************************************************
434  * input_GatherPES:
435  *****************************************************************************
436  * Gather a PES packet.
437  *****************************************************************************/
438 void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
439                       es_descriptor_t * p_es,
440                       boolean_t b_unit_start, boolean_t b_packet_lost )
441 {
442 #define p_pes (p_es->p_pes)
443
444     //intf_DbgMsg("PES-demultiplexing %p (%p)", p_ts_packet, p_pes);
445
446     /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
447      * often an escape sequence in decoders, so that should make them wait
448      * for the next start code). */
449     if( b_packet_lost || p_es->b_discontinuity )
450     {
451         input_NullPacket( p_input, p_es );
452     }
453
454     if( b_unit_start && p_pes != NULL )
455     {
456         /* If the data packet contains the begining of a new PES packet, and
457          * if we were reassembling a PES packet, then the PES should be
458          * complete now, so parse its header and give it to the decoders. */
459         input_ParsePES( p_input, p_es );
460     }
461
462     if( !b_unit_start && p_pes == NULL )
463     {
464         /* Random access... */
465         p_input->p_plugin->pf_delete_packet( p_input->p_method_data, p_data );
466     }
467     else
468     {
469         if( b_unit_start )
470         {
471             /* If we are at the beginning of a new PES packet, we must fetch
472              * a new PES buffer to begin with the reassembly of this PES
473              * packet. This is also here that we can synchronize with the
474              * stream if we lost packets or if the decoder has just
475              * started. */
476             if( (p_pes = p_input->p_plugin->pf_new_pes( p_input->p_method_data ) ) == NULL )
477             {
478                 intf_ErrMsg("Out of memory");
479                 p_input->b_error = 1;
480                 return;
481             }
482             //intf_DbgMsg("New PES packet %p (first data: %p)", p_pes, p_data);
483             p_pes->p_first = p_data;
484
485             /* If the PES header fits in the first data packet, we can
486              * already set p_gather->i_pes_real_size. */
487             if( p_data->p_payload_end - p_data->p_payload_start
488                     >= PES_HEADER_SIZE )
489             {
490                 p_es->i_pes_real_size =
491                                 U16_AT(p_data->p_payload_start + 4) + 6;
492             }
493             else
494             {
495                 p_es->i_pes_real_size = 0;
496             }
497         }
498         else
499         {
500             /* Update the relations between the data packets */
501             p_es->p_last->p_next = p_data;
502         }
503
504         p_es->p_last = p_data;
505
506         /* Size of the payload carried in the data packet */
507         p_pes->i_pes_size += (p_data->p_payload_end
508                                  - p_data->p_payload_start);
509     
510         /* We can check if the packet is finished */
511         if( p_pes->i_pes_size == p_es->i_pes_real_size )
512         {
513             /* The packet is finished, parse it */
514             input_ParsePES( p_input, p_es );
515         }
516     }
517 #undef p_pes
518 }
519
520
521 /*
522  * Pace control
523  */
524
525 /*
526  *   DISCUSSION : SYNCHRONIZATION METHOD
527  *
528  *   In some cases we can impose the pace of reading (when reading from a
529  *   file or a pipe), and for the synchronization we simply sleep() until
530  *   it is time to deliver the packet to the decoders. When reading from
531  *   the network, we must be read at the same pace as the server writes,
532  *   otherwise the kernel's buffer will trash packets. The risk is now to
533  *   overflow the input buffers in case the server goes too fast, that is
534  *   why we do these calculations :
535  *
536  *   We compute an average for the pcr because we want to eliminate the
537  *   network jitter and keep the low frequency variations. The average is
538  *   in fact a low pass filter and the jitter is a high frequency signal
539  *   that is why it is eliminated by the filter/average.
540  *
541  *   The low frequency variations enable us to synchronize the client clock
542  *   with the server clock because they represent the time variation between
543  *   the 2 clocks. Those variations (ie the filtered pcr) are used to compute
544  *   the presentation dates for the audio and video frames. With those dates
545  *   we can decode (or trash) the MPEG2 stream at "exactly" the same rate
546  *   as it is sent by the server and so we keep the synchronization between
547  *   the server and the client.
548  *
549  *   It is a very important matter if you want to avoid underflow or overflow
550  *   in all the FIFOs, but it may be not enough.
551  */
552
553 /*****************************************************************************
554  * Constants
555  *****************************************************************************/
556
557 /* Maximum number of samples used to compute the dynamic average value,
558  * it is also the maximum of c_average_count in pgrm_ts_data_t.
559  * We use the following formula :
560  * new_average = (old_average * c_average + new_sample_value) / (c_average +1) */
561 #define CR_MAX_AVERAGE_COUNTER 40
562
563 /* Maximum gap allowed between two CRs. */
564 #define CR_MAX_GAP 1000000
565
566 /*****************************************************************************
567  * CRReInit : Reinitialize the clock reference
568  *****************************************************************************/
569 static void CRReInit( pgrm_descriptor_t * p_pgrm )
570 {
571     p_pgrm->delta_cr        = 0;
572     p_pgrm->last_cr         = 0;
573     p_pgrm->c_average_count = 0;
574 }
575
576 /* FIXME: find a better name */
577 /*****************************************************************************
578  * CRDecode : Decode a clock reference
579  *****************************************************************************/
580 static void CRDecode( input_thread_t * p_input, pgrm_descriptor_t * p_pgrm,
581                       mtime_t cr_time )
582 {
583     if( p_pgrm->i_synchro_state != SYNCHRO_OK )
584     {
585         switch( p_pgrm->i_synchro_state )
586         {
587         case SYNCHRO_START:
588             p_pgrm->delta_absolute = mdate() - cr_time;
589             p_pgrm->i_synchro_state = SYNCHRO_OK;
590             break;
591
592         case SYNCHRO_NOT_STARTED:
593             p_pgrm->i_synchro_state = SYNCHRO_START;
594             break;
595
596         default:
597             break;
598         }
599     }
600     else
601     {
602         if( p_pgrm->b_discontinuity ||
603             ( p_pgrm->last_cr != 0 &&
604                   (    (p_pgrm->last_cr - cr_time) > CR_MAX_GAP
605                     || (p_pgrm->last_cr - cr_time) < - CR_MAX_GAP ) ) )
606         {
607             int i_es;
608
609             /* Stream discontinuity. */
610             intf_WarnMsg( 3, "CR re-initialiazed" );
611             CRReInit( p_pgrm );
612             p_pgrm->i_synchro_state = SYNCHRO_REINIT;
613             p_pgrm->b_discontinuity = 0;
614
615             /* Warn all the elementary streams */
616             for( i_es = 0; i_es < p_pgrm->i_es_number; i_es++ )
617             {
618                 p_pgrm->pp_es[i_es]->b_discontinuity = 1;
619             }
620         }
621         p_pgrm->last_cr = cr_time;
622
623         if( p_input->stream.b_pace_control )
624         {
625             /* Wait a while before delivering the packets to the decoder. */
626             mwait( cr_time + p_pgrm->delta_absolute );
627         }
628         else
629         {
630             mtime_t                 sys_time, delta_cr;
631
632             sys_time = mdate();
633             delta_cr = sys_time - cr_time;
634
635             if( p_pgrm->c_average_count == CR_MAX_AVERAGE_COUNTER )
636             {
637                 p_pgrm->delta_cr = ( delta_cr + (p_pgrm->delta_cr
638                                               * (CR_MAX_AVERAGE_COUNTER - 1)) )
639                                      / CR_MAX_AVERAGE_COUNTER;
640             }
641             else
642             {
643                 p_pgrm->delta_cr = ( delta_cr + (p_pgrm->delta_cr
644                                               * p_pgrm->c_average_count) )
645                                      / ( p_pgrm->c_average_count + 1 );
646                 p_pgrm->c_average_count++;
647             }
648         }
649     }
650 }
651
652
653 /*
654  * PS Demultiplexing
655  */
656
657 /*****************************************************************************
658  * GetID: Get the ID of a stream
659  *****************************************************************************/
660 static u16 GetID( data_packet_t * p_data )
661 {
662     u16         i_id;
663
664     i_id = p_data->p_buffer[3];                                 /* stream_id */
665     if( i_id == 0xBD )
666     {
667         /* stream_private_id */
668         i_id |= p_data->p_buffer[ 9 + p_data->p_buffer[8] ] << 8;
669     }
670     return( i_id );
671 }
672
673 /*****************************************************************************
674  * DecodePSM: Decode the Program Stream Map information
675  *****************************************************************************/
676 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
677 {
678     stream_ps_data_t *  p_demux =
679                  (stream_ps_data_t *)p_input->stream.p_demux_data;
680     byte_t *            p_byte;
681     byte_t *            p_end;
682     int                 i;
683     int                 i_new_es_number = 0;
684
685     intf_Msg("input info: Your stream contains Program Stream Map information");
686     intf_Msg("input info: Please send a mail to <massiot@via.ecp.fr>");
687
688     if( p_data->p_payload_start + 10 > p_data->p_payload_end )
689     {
690         intf_ErrMsg( "PSM too short : packet corrupt" );
691         return;
692     }
693
694     if( p_demux->b_has_PSM
695         && p_demux->i_PSM_version == (p_data->p_buffer[6] & 0x1F) )
696     {
697         /* Already got that one. */
698         return;
699     }
700
701     intf_DbgMsg( "Building PSM" );
702     p_demux->b_has_PSM = 1;
703     p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;
704
705     /* Go to elementary_stream_map_length, jumping over
706      * program_stream_info. */
707     p_byte = p_data->p_payload_start + 10
708               + U16_AT(&p_data->p_payload_start[8]);
709     if( p_byte > p_data->p_payload_end )
710     {
711         intf_ErrMsg( "PSM too short : packet corrupt" );
712         return;
713     }
714     /* This is the full size of the elementary_stream_map.
715      * 2 == elementary_stream_map_length
716      * Please note that CRC_32 is not included in the length. */
717     p_end = p_byte + 2 + U16_AT(p_byte);
718     p_byte += 2;
719     if( p_end > p_data->p_payload_end )
720     {
721         intf_ErrMsg( "PSM too short : packet corrupt" );
722         return;
723     }
724
725     vlc_mutex_lock( &p_input->stream.stream_lock );
726
727     /* 4 == minimum useful size of a section */
728     while( p_byte + 4 <= p_end )
729     {
730         es_descriptor_t *   p_es = NULL;
731         u8                  i_stream_id = p_byte[1];
732         /* FIXME: there will be a problem with private streams... (same
733          * stream_id) */
734
735         /* Look for the ES in the ES table */
736         for( i = i_new_es_number;
737              i < p_input->stream.pp_programs[0]->i_es_number;
738              i++ )
739         {
740             if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
741                     == i_stream_id )
742             {
743                 p_es = p_input->stream.pp_programs[0]->pp_es[i];
744                 if( p_es->i_type != p_byte[0] )
745                 {
746                     input_DelES( p_input, p_es );
747                     p_es = NULL;
748                 }
749                 else
750                 {
751                     /* Move the ES to the beginning. */
752                     p_input->stream.pp_programs[0]->pp_es[i]
753                         = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
754                     p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
755                         = p_es;
756                     i_new_es_number++;
757                 }
758                 break;
759             }
760         }
761
762         /* The goal is to have all the ES we have just read in the
763          * beginning of the pp_es table, and all the others at the end,
764          * so that we can close them more easily at the end. */
765         if( p_es == NULL )
766         {
767             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
768                                 i_stream_id, 0 );
769             p_es->i_type = p_byte[0];
770
771             /* input_AddES has inserted the new element at the end. */
772             p_input->stream.pp_programs[0]->pp_es[
773                 p_input->stream.pp_programs[0]->i_es_number ]
774                 = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
775             p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
776             i_new_es_number++;
777         }
778         p_byte += 4 + U16_AT(&p_byte[2]);
779     }
780
781     /* Un-select the streams that are no longer parts of the program. */
782     for( i = i_new_es_number;
783          i < p_input->stream.pp_programs[0]->i_es_number;
784          i++ )
785     {
786         /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
787          * list will be emptied starting from the end */
788         input_DelES( p_input,
789                      p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
790     }
791
792 #ifdef STATS
793     intf_Msg( "input info: The stream map after the PSM is now :" );
794     input_DumpStream( p_input );
795 #endif
796
797     vlc_mutex_unlock( &p_input->stream.stream_lock );
798 }
799
800 /*****************************************************************************
801  * input_ParsePS: read the PS header
802  *****************************************************************************/
803 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
804                                  data_packet_t * p_data )
805 {
806     u32                 i_code;
807     es_descriptor_t *   p_es = NULL;
808
809     i_code = U32_AT( p_data->p_buffer );
810     if( i_code > 0x1BC ) /* ES start code */
811     {
812         u16                 i_id;
813         int                 i_dummy;
814
815         /* This is a PES packet. Find out if we want it or not. */
816         i_id = GetID( p_data );
817
818         vlc_mutex_lock( &p_input->stream.stream_lock );
819         if( p_input->stream.pp_programs[0]->b_is_ok )
820         {
821             /* Look only at the selected ES. */
822             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
823                  i_dummy++ )
824             {
825                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
826                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
827                 {
828                     p_es = p_input->stream.pp_selected_es[i_dummy];
829                     break;
830                 }
831             }
832         }
833         else
834         {
835             stream_ps_data_t * p_demux =
836               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
837
838             /* Search all ES ; if not found -> AddES */
839             p_es = input_FindES( p_input, i_id );
840
841             if( p_es == NULL && !p_demux->b_has_PSM )
842             {
843                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
844                                     i_id, 0 );
845                 if( p_es != NULL )
846                 {
847                     p_es->i_stream_id = p_data->p_buffer[3];
848
849                     /* Set stream type and auto-spawn. */
850                     if( (i_id & 0xF0) == 0xE0 )
851                     {
852                         /* MPEG video */
853                         p_es->i_type = MPEG2_VIDEO_ES;
854 #ifdef AUTO_SPAWN
855                         if( !p_input->stream.b_seekable )
856                             input_SelectES( p_input, p_es );
857 #endif
858                     }
859                     else if( (i_id & 0xE0) == 0xC0 )
860                     {
861                         /* MPEG audio */
862                         p_es->i_type = MPEG2_AUDIO_ES;
863 #ifdef AUTO_SPAWN
864                         if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
865                                 == REQUESTED_MPEG
866                           && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
867                                 == (p_es->i_id & 0x1F) )
868                         {
869                             if( !p_input->stream.b_seekable )
870                                 input_SelectES( p_input, p_es );
871                         }
872 #endif
873                     }
874                     else if( (i_id & 0xF0FF) == 0x80BD )
875                     {
876                         /* AC3 audio (0x80->0x8F) */
877                         p_es->i_type = AC3_AUDIO_ES;
878 #ifdef AUTO_SPAWN
879                         if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
880                                 == REQUESTED_AC3
881                          && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
882                                 == ((p_es->i_id & 0xF00) >> 8) )
883                         {
884                             if( !p_input->stream.b_seekable )
885                                 input_SelectES( p_input, p_es );
886                         }
887 #endif
888                     }
889                     else if( (i_id & 0xE0FF) == 0x20BD )
890                     {
891                         /* Subtitles video (0x20->0x3F) */
892                         p_es->i_type = DVD_SPU_ES;
893 #ifdef AUTO_SPAWN
894                         if( main_GetIntVariable( INPUT_DVD_SUBTITLE_VAR, -1 )
895                                 == ((p_es->i_id & 0x1F00) >> 8) )
896                         {
897                             if( !p_input->stream.b_seekable )
898                                 input_SelectES( p_input, p_es );
899                         }
900 #endif
901                     }
902                     else if( (i_id & 0xF0FF) == 0xA0BD )
903                     {
904                         /* LPCM audio (0xA0->0xAF) */
905                         p_es->i_type = LPCM_AUDIO_ES;
906                         /* FIXME : write the decoder */
907                     }
908                     else
909                     {
910                         p_es->i_type = UNKNOWN_ES;
911                     }
912                 }
913             }
914         } /* stream.b_is_ok */
915         vlc_mutex_unlock( &p_input->stream.stream_lock );
916     } /* i_code > 0xBC */
917
918     return( p_es );
919 }
920
921 /*****************************************************************************
922  * input_DemuxPS: first step of demultiplexing: the PS header
923  *****************************************************************************/
924 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
925 {
926     u32                 i_code;
927     boolean_t           b_trash = 0;
928     es_descriptor_t *   p_es = NULL;
929
930     i_code = U32_AT( p_data->p_buffer );
931     if( i_code <= 0x1BC )
932     {
933         switch( i_code )
934         {
935         case 0x1BA: /* PACK_START_CODE */
936             {
937                 /* Convert the SCR in microseconds. */
938                 mtime_t         scr_time;
939
940                 if( (p_data->p_buffer[4] & 0xC0) == 0x40 )
941                 {
942                     /* MPEG-2 */
943                     scr_time =
944                       (( ((mtime_t)(p_data->p_buffer[4] & 0x38) << 27) |
945                          ((mtime_t)(U32_AT(p_data->p_buffer + 4) & 0x03FFF800)
946                                         << 4) |
947                          ((mtime_t)(U32_AT(p_data->p_buffer + 6) & 0x03FFF800)
948                                         >> 11)
949                       ) * 300) / 27;
950                 }
951                 else
952                 {
953                     /* MPEG-1 SCR is like PTS */
954                     scr_time =
955                       (( ((mtime_t)(p_data->p_buffer[4] & 0x0E) << 29) |
956                          (((mtime_t)U16_AT(p_data->p_buffer + 5) << 14)
957                            - (1 << 14)) |
958                          ((mtime_t)U16_AT(p_data->p_buffer + 7) >> 1)
959                       ) * 300) / 27;
960                 }
961                 /* Call the pace control. */
962                 //intf_Msg("+%lld", scr_time);
963                 CRDecode( p_input, p_input->stream.pp_programs[0],
964                           scr_time );
965                 b_trash = 1;
966             }
967             break;
968
969         case 0x1BB: /* SYSTEM_START_CODE */
970             b_trash = 1;                              /* Nothing interesting */
971             break;
972
973         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
974             DecodePSM( p_input, p_data );
975             b_trash = 1;
976             break;
977     
978         case 0x1B9: /* PROGRAM_END_CODE */
979             b_trash = 1;
980             break;
981    
982         default:
983             /* This should not happen */
984             b_trash = 1;
985             intf_WarnMsg( 1, "Unwanted packet received with start code %x",
986                           i_code );
987         }
988     }
989     else
990     {
991         p_es = input_ParsePS( p_input, p_data );
992
993         if( p_es != NULL && p_es->p_decoder_fifo != NULL )
994         {
995 #ifdef STATS
996             p_es->c_packets++;
997 #endif
998             input_GatherPES( p_input, p_data, p_es, 1, 0 );
999         }
1000         else
1001         {
1002             b_trash = 1;
1003         }
1004     }
1005
1006     /* Trash the packet if it has no payload or if it isn't selected */
1007     if( b_trash )
1008     {
1009         p_input->p_plugin->pf_delete_packet( p_input, p_data );
1010 #ifdef STATS
1011         p_input->c_packets_trashed++;
1012 #endif
1013     }
1014 }
1015
1016
1017 /*
1018  * TS Demultiplexing
1019  */
1020
1021 /*****************************************************************************
1022  * input_DemuxTS: first step of demultiplexing: the TS header
1023  *****************************************************************************/
1024 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
1025 {
1026     int                 i_pid, i_dummy;
1027     boolean_t           b_adaptation;         /* Adaptation field is present */
1028     boolean_t           b_payload;                 /* Packet carries payload */
1029     boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
1030     boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
1031     boolean_t           b_lost = 0;             /* Was there a packet loss ? */
1032     es_descriptor_t *   p_es = NULL;
1033     es_ts_data_t *      p_es_demux = NULL;
1034     pgrm_ts_data_t *    p_pgrm_demux = NULL;
1035
1036 #define p (p_data->p_buffer)
1037
1038     //intf_DbgMsg("input debug: TS-demultiplexing packet %p, pid %d",
1039     //            p_ts_packet, U16_AT(&p[1]) & 0x1fff);
1040
1041     /* Extract flags values from TS common header. */
1042     i_pid = U16_AT(&p[1]) & 0x1fff;
1043     b_unit_start = (p[1] & 0x40);
1044     b_adaptation = (p[3] & 0x20);
1045     b_payload = (p[3] & 0x10);
1046
1047     /* Find out the elementary stream. */
1048     vlc_mutex_lock( &p_input->stream.stream_lock );
1049     p_es = input_FindES( p_input, i_pid );
1050     vlc_mutex_unlock( &p_input->stream.stream_lock );
1051
1052     if( p_es == NULL || p_es->p_decoder_fifo == NULL )
1053     {
1054         /* Not selected. Just read the adaptation field for a PCR. */
1055         b_trash = 1;
1056     }
1057
1058     if( (p_es->p_decoder_fifo != NULL) || (p_pgrm_demux->i_pcr_pid == i_pid) )
1059     {
1060 #ifdef STATS
1061         p_es->c_packets++;
1062 #endif
1063
1064         /* Extract adaptation field information if any */
1065         if( !b_adaptation )
1066         {
1067             /* We don't have any adaptation_field, so payload starts
1068              * immediately after the 4 byte TS header */
1069             p_data->p_payload_start += 4;
1070         }
1071         else
1072         {
1073             /* p[4] is adaptation_field_length minus one */
1074             p_data->p_payload_start += 5 + p[4];
1075     
1076             /* The adaptation field can be limited to the
1077              * adaptation_field_length byte, so that there is nothing to do:
1078              * skip this possibility */
1079             if( p[4] )
1080             {
1081                 /* If the packet has both adaptation_field and payload,
1082                  * adaptation_field cannot be more than 182 bytes long; if
1083                  * there is only an adaptation_field, it must fill the next
1084                  * 183 bytes. */
1085                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1086                 {
1087                     intf_WarnMsg( 2,
1088                         "invalid TS adaptation field (%p)",
1089                         p_data );
1090                     p_data->b_discard_payload = 1;
1091 #ifdef STATS
1092                     p_es->c_invalid_packets++;
1093 #endif
1094                 }
1095     
1096                 /* Now we are sure that the byte containing flags is present:
1097                  * read it */
1098                 else
1099                 {
1100                     /* discontinuity_indicator */
1101                     if( p[5] & 0x80 )
1102                     {
1103                         intf_WarnMsg( 2,
1104                             "discontinuity_indicator"
1105                             " encountered by TS demux (position read: %d,"
1106                             " saved: %d)",
1107                             p[5] & 0x80, p_es_demux->i_continuity_counter );
1108     
1109                         /* If the PID carries the PCR, there will be a system
1110                          * time-based discontinuity. We let the PCR decoder
1111                          * handle that. */
1112                         p_es->p_pgrm->b_discontinuity = 1;
1113     
1114                         /* There also may be a continuity_counter
1115                          * discontinuity: resynchronise our counter with
1116                          * the one of the stream. */
1117                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
1118                     }
1119     
1120                     /* If this is a PCR_PID, and this TS packet contains a
1121                      * PCR, we pass it along to the PCR decoder. */
1122                     if( (p_pgrm_demux->i_pcr_pid == i_pid) && (p[5] & 0x10) )
1123                     {
1124                         /* There should be a PCR field in the packet, check
1125                          * if the adaptation field is long enough to carry
1126                          * it. */
1127                         if( p[4] >= 7 )
1128                         {
1129                             /* Convert the PCR in microseconds.
1130                              * WARNING: do not remove the casts in the
1131                              * following calculation ! */
1132                             mtime_t     pcr_time;
1133                             pcr_time =
1134                                     ( (( (mtime_t)U32_AT((u32*)&p[6]) << 1 )
1135                                       | ( p[10] >> 7 )) * 300 ) / 27;
1136                             /* Call the pace control. */
1137                             CRDecode( p_input, p_es->p_pgrm, pcr_time );
1138                         }
1139                     } /* PCR ? */
1140                 } /* valid TS adaptation field ? */
1141             } /* length > 0 */
1142         } /* has adaptation field */
1143     
1144         /* Check the continuity of the stream. */
1145         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1146         if( i_dummy == 1 )
1147         {
1148             /* Everything is ok, just increase our counter */
1149             p_es_demux->i_continuity_counter++;
1150         }
1151         else
1152         {
1153             if( !b_payload && i_dummy == 0 )
1154             {
1155                 /* This is a packet without payload, this is allowed by the
1156                  * draft. As there is nothing interesting in this packet
1157                  * (except PCR that have already been handled), we can trash
1158                  * the packet. */
1159                 intf_WarnMsg( 1,
1160                               "Packet without payload received by TS demux" );
1161                 b_trash = 1;
1162             }
1163             else if( i_dummy <= 0 )
1164             {
1165                 /* FIXME: this can never happen, can it ? --Meuuh */
1166                 /* Duplicate packet: mark it as being to be trashed. */
1167                 intf_WarnMsg( 1, "Duplicate packet received by TS demux" );
1168                 b_trash = 1;
1169             }
1170             else if( p_es_demux->i_continuity_counter == 0xFF )
1171             {
1172                 /* This means that the packet is the first one we receive for
1173                  * this ES since the continuity counter ranges between 0 and
1174                  * 0x0F excepts when it has been initialized by the input:
1175                  * init the counter to the correct value. */
1176                 intf_DbgMsg( "First packet for PID %d received by TS demux",
1177                              p_es->i_id );
1178                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1179             }
1180             else
1181             {
1182                 /* This can indicate that we missed a packet or that the
1183                  * continuity_counter wrapped and we received a dup packet:
1184                  * as we don't know, do as if we missed a packet to be sure
1185                  * to recover from this situation */
1186                 intf_WarnMsg( 2,
1187                            "Packet lost by TS demux: current %d, packet %d",
1188                            p_es_demux->i_continuity_counter & 0x0f,
1189                            p[3] & 0x0f );
1190                 b_lost = 1;
1191                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1192             } /* not continuous */
1193         } /* continuity */
1194     } /* if selected or PCR */
1195
1196     /* Trash the packet if it has no payload or if it isn't selected */
1197     if( b_trash )
1198     {
1199         p_input->p_plugin->pf_delete_packet( p_input, p_data );
1200 #ifdef STATS
1201         p_input->c_packets_trashed++;
1202 #endif
1203     }
1204     else
1205     {
1206         if( p_es_demux->b_psi )
1207         {
1208             /* The payload contains PSI tables */
1209 #if 0
1210             input_DemuxPSI( p_input, p_data, p_es,
1211                             b_unit_start, b_lost );
1212 #endif
1213         }
1214         else
1215         {
1216             /* The payload carries a PES stream */
1217             if( b_unit_start )
1218             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
1219         }
1220     }
1221
1222 #undef p
1223 }