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