]> git.sesse.net Git - vlc/blob - src/input/mpeg_system.c
* ./BUGS: added a list of known bugs. Please add your findings!
[vlc] / src / input / mpeg_system.c
1 /*****************************************************************************
2  * mpeg_system.c: TS, PS and PES management
3  *****************************************************************************
4  * Copyright (C) 1998-2001 VideoLAN
5  * $Id: mpeg_system.c,v 1.78 2002/01/04 14:01:34 sam Exp $
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *          Michel Lespinasse <walken@via.ecp.fr>
9  *          BenoĆ®t Steiner <benny@via.ecp.fr>
10  *          Samuel Hocevar <sam@via.ecp.fr>
11  *          Henri Fallon <henri@via.ecp.fr>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  * 
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
26  *****************************************************************************/
27
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 #include <stdlib.h>
32 #include <string.h>                                    /* memcpy(), memset() */
33 #include <sys/types.h>                                              /* off_t */
34
35 #include <videolan/vlc.h>
36
37 #include "stream_control.h"
38 #include "input_ext-intf.h"
39 #include "input_ext-dec.h"
40 #include "input_ext-plugins.h"
41
42 /*****************************************************************************
43  * Local prototypes
44  *****************************************************************************/
45
46 static void input_DecodePAT( input_thread_t *, es_descriptor_t *);
47 static void input_DecodePMT( input_thread_t *, es_descriptor_t *);
48
49 /*
50  * PES Packet management
51  */
52
53 /*****************************************************************************
54  * MoveChunk
55  *****************************************************************************
56  * Small utility function used to parse discontinuous headers safely. Copies
57  * i_buf_len bytes of data to a buffer and returns the size copied.
58  * It also solves some alignment problems on non-IA-32, non-PPC processors.
59  * This is a variation on the theme of input_ext-dec.h:GetChunk().
60  *****************************************************************************/
61 static __inline__ size_t MoveChunk( byte_t * p_dest,
62                                     data_packet_t ** pp_data_src,
63                                     byte_t ** pp_src,
64                                     size_t i_buf_len )
65 {
66     ptrdiff_t           i_available;
67
68     if( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
69             >= i_buf_len )
70     {
71         if( p_dest != NULL )
72             memcpy( p_dest, *pp_src, i_buf_len );
73         *pp_src += i_buf_len;
74         return( i_buf_len );
75     }
76     else
77     {
78         size_t          i_init_len = i_buf_len;
79
80         do
81         {
82             if( p_dest != NULL )
83                 memcpy( p_dest, *pp_src, i_available );
84             *pp_data_src = (*pp_data_src)->p_next;
85             i_buf_len -= i_available;
86             p_dest += i_available;
87             if( *pp_data_src == NULL )
88             {
89                 *pp_src = NULL;
90                 return( i_init_len - i_buf_len );
91             }
92             *pp_src = (*pp_data_src)->p_payload_start;
93         }
94         while( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
95                 <= i_buf_len );
96
97         if( i_buf_len )
98         {
99             if( p_dest != NULL )
100                 memcpy( p_dest, *pp_src, i_buf_len );
101             *pp_src += i_buf_len;
102         }
103         return( i_init_len );
104     }
105 }
106
107 /*****************************************************************************
108  * input_ParsePES
109  *****************************************************************************
110  * Parse a finished PES packet and analyze its header.
111  *****************************************************************************/
112 #define PES_HEADER_SIZE     7
113 void input_ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
114 {
115     data_packet_t * p_data;
116     byte_t *        p_byte;
117     byte_t          p_header[PES_HEADER_SIZE];
118     int             i_done;
119
120 #define p_pes (p_es->p_pes)
121
122     //intf_DbgMsg("End of PES packet %p", p_pes);
123
124     /* Parse the header. The header has a variable length, but in order
125      * to improve the algorithm, we will read the 14 bytes we may be
126      * interested in */
127     p_data = p_pes->p_first;
128     p_byte = p_data->p_payload_start;
129     i_done = 0;
130
131     if( MoveChunk( p_header, &p_data, &p_byte, PES_HEADER_SIZE )
132             != PES_HEADER_SIZE )
133     {
134         intf_WarnMsg( 1, "input: PES packet too short to have a header" );
135         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
136         p_pes = NULL;
137         return;
138     }
139
140     /* Get the PES size if defined */
141     p_es->i_pes_real_size = U16_AT(p_header + 4);
142     if( p_es->i_pes_real_size )
143     {
144         p_es->i_pes_real_size += 6;
145     }
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( "input error: data loss, "
153                      "PES packet doesn't start with 0x000001" );
154         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
155         p_pes = NULL;
156     }
157     else
158     {
159         int i_pes_header_size, i_payload_size;
160
161         if ( p_es->i_pes_real_size &&
162              (p_es->i_pes_real_size != p_pes->i_pes_size) )
163         {
164             /* PES_packet_length is set and != total received payload */
165             /* Warn the decoder that the data may be corrupt. */
166             intf_WarnMsg( 1, "input: packet corrupted, "
167                              "PES sizes do not match" );
168         }
169
170         switch( p_es->i_stream_id )
171         {
172         case 0xBC:  /* Program stream map */
173         case 0xBE:  /* Padding */
174         case 0xBF:  /* Private stream 2 */
175         case 0xB0:  /* ECM */
176         case 0xB1:  /* EMM */
177         case 0xFF:  /* Program stream directory */
178         case 0xF2:  /* DSMCC stream */
179         case 0xF8:  /* ITU-T H.222.1 type E stream */
180             /* The payload begins immediately after the 6 bytes header, so
181              * we have finished with the parsing */
182             i_pes_header_size = 6;
183             break;
184
185         default:
186             if( (p_header[6] & 0xC0) == 0x80 )
187             {
188                 /* MPEG-2 : the PES header contains at least 3 more bytes. */
189                 size_t      i_max_len;
190                 boolean_t   b_has_pts, b_has_dts;
191                 byte_t      p_full_header[12];
192
193                 p_pes->b_data_alignment = p_header[6] & 0x04;
194
195                 i_max_len = MoveChunk( p_full_header, &p_data, &p_byte, 12 );
196                 if( i_max_len < 2 )
197                 {
198                     intf_WarnMsg( 1,
199                             "PES packet too short to have a MPEG-2 header" );
200                     p_input->pf_delete_pes( p_input->p_method_data,
201                                             p_pes );
202                     p_pes = NULL;
203                     return;
204                 }
205
206                 b_has_pts = p_full_header[0] & 0x80;
207                 b_has_dts = p_full_header[0] & 0x40;
208                 i_pes_header_size = p_full_header[1] + 9;
209
210                 /* Now parse the optional header extensions */
211                 if( b_has_pts )
212                 {
213                     if( i_max_len < 7 )
214                     {
215                         intf_WarnMsg( 1,
216                             "PES packet too short to have a MPEG-2 header" );
217                         p_input->pf_delete_pes( p_input->p_method_data,
218                                                 p_pes );
219                         p_pes = NULL;
220                         return;
221                     }
222                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
223                     ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
224                       ((mtime_t)(p_full_header[3]) << 22) |
225                       ((mtime_t)(p_full_header[4] & 0xFE) << 14) |
226                       ((mtime_t)p_full_header[5] << 7) |
227                       ((mtime_t)p_full_header[6] >> 1) ) );
228
229                     if( b_has_dts )
230                     {
231                         if( i_max_len < 12 )
232                         {
233                             intf_WarnMsg( 1,
234                               "PES packet too short to have a MPEG-2 header" );
235                             p_input->pf_delete_pes( p_input->p_method_data,
236                                                     p_pes );
237                             p_pes = NULL;
238                             return;
239                         }
240                         p_pes->i_dts = input_ClockGetTS( p_input, p_es->p_pgrm,
241                         ( ((mtime_t)(p_full_header[7] & 0x0E) << 29) |
242                           (((mtime_t)U16_AT(p_full_header + 8) << 14)
243                                 - (1 << 14)) |
244                           ((mtime_t)U16_AT(p_full_header + 10) >> 1) ) );
245                     }
246                 }
247             }
248             else
249             {
250                 /* Probably MPEG-1 */
251                 boolean_t       b_has_pts, b_has_dts;
252
253                 i_pes_header_size = 6;
254                 p_data = p_pes->p_first;
255                 p_byte = p_data->p_payload_start;
256                 /* Cannot fail because the previous one succeeded. */
257                 MoveChunk( NULL, &p_data, &p_byte, 6 );
258
259                 while( *p_byte == 0xFF && i_pes_header_size < 23 )
260                 {
261                     i_pes_header_size++;
262                     if( MoveChunk( NULL, &p_data, &p_byte, 1 ) != 1 )
263                     {
264                         intf_WarnMsg( 1,
265                             "PES packet too short to have a MPEG-1 header" );
266                         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
267                         p_pes = NULL;
268                         return;
269                     }
270                 }
271                 if( i_pes_header_size == 23 )
272                 {
273                     intf_ErrMsg( "input error: too much MPEG-1 stuffing" );
274                     p_input->pf_delete_pes( p_input->p_method_data, p_pes );
275                     p_pes = NULL;
276                     return;
277                 }
278
279                 if( (*p_byte & 0xC0) == 0x40 )
280                 {
281                     /* Don't ask why... --Meuuh */
282                     /* Erm... why ? --Sam */
283                     /* Well... According to the recommendation, it is for
284                      * STD_buffer_scale and STD_buffer_size. --Meuuh */
285                     i_pes_header_size += 2;
286                     if( MoveChunk( NULL, &p_data, &p_byte, 2 ) != 2 )
287                     {
288                         intf_WarnMsg( 1, "input: PES packet too short "
289                                          "to have a MPEG-1 header" );
290                         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
291                         p_pes = NULL;
292                         return;
293                     }
294                 }
295
296                 i_pes_header_size++;
297
298                 b_has_pts = *p_byte & 0x20;
299                 b_has_dts = *p_byte & 0x10;
300
301                 if( b_has_pts )
302                 {
303                     byte_t      p_ts[5];
304
305                     i_pes_header_size += 4;
306                     if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
307                     {
308                         intf_WarnMsg( 1, "input: PES packet too short "
309                                          "to have a MPEG-1 header" );
310                         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
311                         p_pes = NULL;
312                         return;
313                     }
314
315                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
316                        ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
317                          (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
318                          ((mtime_t)p_ts[3] << 7) |
319                          ((mtime_t)p_ts[4] >> 1) ) );
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( 1, "input: PES packet too short "
327                                              "to have a MPEG-1 header" );
328                             p_input->pf_delete_pes( p_input->p_method_data,
329                                                     p_pes );
330                             p_pes = NULL;
331                             return;
332                         }
333
334                         p_pes->i_dts = input_ClockGetTS( p_input,
335                                                          p_es->p_pgrm,
336                             ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
337                               (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
338                               ((mtime_t)p_ts[3] << 7) |
339                               ((mtime_t)p_ts[4] >> 1) ) );
340                     }
341                 }
342             }
343
344             break;
345         }
346
347         if( p_es->i_stream_id == 0xbd )
348         {
349             /* With private stream 1, the first byte of the payload
350              * is a stream_private_id, so skip it. */
351             i_pes_header_size++;
352         }
353
354         /* Now we've parsed the header, we just have to indicate in some
355          * specific data packets where the PES payload begins (renumber
356          * p_payload_start), so that the decoders can find the beginning
357          * of their data right out of the box. */
358         p_data = p_pes->p_first;
359         i_payload_size = p_data->p_payload_end
360                                  - p_data->p_payload_start;
361         while( i_pes_header_size > i_payload_size )
362         {
363             /* These packets are entirely filled by the PES header. */
364             i_pes_header_size -= i_payload_size;
365             p_data->p_payload_start = p_data->p_payload_end;
366             /* Go to the next data packet. */
367             if( (p_data = p_data->p_next) == NULL )
368             {
369                 intf_ErrMsg( "input error: PES header bigger than payload" );
370                 p_input->pf_delete_pes( p_input->p_method_data, p_pes );
371                 p_pes = NULL;
372                 return;
373             }
374             i_payload_size = p_data->p_payload_end
375                                  - p_data->p_payload_start;
376         }
377         /* This last packet is partly header, partly payload. */
378         if( i_payload_size < i_pes_header_size )
379         {
380             intf_ErrMsg( "input error: PES header bigger than payload" );
381             p_input->pf_delete_pes( p_input->p_method_data, p_pes );
382             p_pes = NULL;
383             return;
384         }
385         p_data->p_payload_start += i_pes_header_size;
386
387         /* Now we can eventually put the PES packet in the decoder's
388          * PES fifo */
389         if( p_es->p_decoder_fifo != NULL )
390         {
391             input_DecodePES( p_es->p_decoder_fifo, p_pes );
392         }
393         else
394         {
395             intf_ErrMsg( "input error: no fifo to receive PES %p "
396                          "(who wrote this damn code ?)", p_pes );
397             p_input->pf_delete_pes( p_input->p_method_data, p_pes );
398         }
399         p_pes = NULL;
400     }
401 #undef p_pes
402
403 }
404
405 /*****************************************************************************
406  * input_GatherPES:
407  *****************************************************************************
408  * Gather a PES packet.
409  *****************************************************************************/
410 void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
411                       es_descriptor_t * p_es,
412                       boolean_t b_unit_start, boolean_t b_packet_lost )
413 {
414 #define p_pes (p_es->p_pes)
415
416     //intf_DbgMsg("PES-demultiplexing %p (%p)", p_ts_packet, p_pes);
417
418     /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
419      * often an escape sequence in decoders, so that should make them wait
420      * for the next start code). */
421     if( b_packet_lost )
422     {
423         input_NullPacket( p_input, p_es );
424     }
425
426     if( b_unit_start && p_pes != NULL )
427     {
428         /* If the data packet contains the begining of a new PES packet, and
429          * if we were reassembling a PES packet, then the PES should be
430          * complete now, so parse its header and give it to the decoders. */
431         input_ParsePES( p_input, p_es );
432     }
433
434     if( !b_unit_start && p_pes == NULL )
435     {
436         /* Random access... */
437         p_input->pf_delete_packet( p_input->p_method_data, p_data );
438     }
439     else
440     {
441         if( b_unit_start )
442         {
443             /* If we are at the beginning of a new PES packet, we must fetch
444              * a new PES buffer to begin with the reassembly of this PES
445              * packet. This is also here that we can synchronize with the
446              * stream if we lost packets or if the decoder has just
447              * started. */
448             if( (p_pes = p_input->pf_new_pes( p_input->p_method_data ) ) == NULL )
449             {
450                 intf_ErrMsg( "input error: out of memory" );
451                 p_input->b_error = 1;
452                 return;
453             }
454             p_pes->i_rate = p_input->stream.control.i_rate;
455             p_pes->p_first = p_data;
456             
457             /* If the PES header fits in the first data packet, we can
458              * already set p_gather->i_pes_real_size. */
459             if( p_data->p_payload_end - p_data->p_payload_start
460                     >= PES_HEADER_SIZE )
461             {
462                 p_es->i_pes_real_size =
463                                 U16_AT(p_data->p_payload_start + 4) + 6;
464                 
465             }
466             else
467             { 
468                 p_es->i_pes_real_size = 0;
469             } 
470         }
471         else
472         {
473             /* Update the relations between the data packets */
474             p_pes->p_last->p_next = p_data;
475         }
476
477         p_pes->p_last = p_data;
478         p_pes->i_nb_data++;
479
480         /* Size of the payload carried in the data packet */
481         p_pes->i_pes_size += (p_data->p_payload_end
482                                  - p_data->p_payload_start);
483     
484         /* We can check if the packet is finished */
485         if( p_pes->i_pes_size == p_es->i_pes_real_size )
486         {
487             /* The packet is finished, parse it */
488             input_ParsePES( p_input, p_es );
489         }
490     }
491 #undef p_pes
492 }
493
494
495 /*
496  * PS Demultiplexing
497  */
498
499 /*****************************************************************************
500  * GetID: Get the ID of a stream
501  *****************************************************************************/
502 static u16 GetID( data_packet_t * p_data )
503 {
504     u16         i_id;
505
506     i_id = p_data->p_demux_start[3];                            /* stream_id */
507     if( i_id == 0xBD )
508     {
509         /* FIXME : this is not valid if the header is split in multiple
510          * packets */
511         /* stream_private_id */
512         i_id |= p_data->p_demux_start[ 9 + p_data->p_demux_start[8] ] << 8;
513     }
514     return( i_id );
515 }
516
517 /*****************************************************************************
518  * DecodePSM: Decode the Program Stream Map information
519  *****************************************************************************
520  * FIXME : loads are not aligned in this function
521  *****************************************************************************/
522 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
523 {
524     stream_ps_data_t *  p_demux =
525                  (stream_ps_data_t *)p_input->stream.p_demux_data;
526     byte_t *            p_byte;
527     byte_t *            p_end;
528     int                 i;
529     int                 i_new_es_number = 0;
530
531     if( p_data->p_demux_start + 10 > p_data->p_payload_end )
532     {
533         intf_ErrMsg( "input error: PSM too short : packet corrupt" );
534         return;
535     }
536
537     if( p_demux->b_has_PSM
538         && p_demux->i_PSM_version == (p_data->p_demux_start[6] & 0x1F) )
539     {
540         /* Already got that one. */
541         return;
542     }
543
544     intf_DbgMsg( "input: building PSM" );
545     p_demux->b_has_PSM = 1;
546     p_demux->i_PSM_version = p_data->p_demux_start[6] & 0x1F;
547
548     /* Go to elementary_stream_map_length, jumping over
549      * program_stream_info. */
550     p_byte = p_data->p_demux_start + 10
551               + U16_AT(&p_data->p_demux_start[8]);
552     if( p_byte > p_data->p_payload_end )
553     {
554         intf_ErrMsg( "input error: PSM too short, packet corrupt" );
555         return;
556     }
557     /* This is the full size of the elementary_stream_map.
558      * 2 == elementary_stream_map_length
559      * Please note that CRC_32 is not included in the length. */
560     p_end = p_byte + 2 + U16_AT(p_byte);
561     p_byte += 2;
562     if( p_end > p_data->p_payload_end )
563     {
564         intf_ErrMsg( "input error: PSM too short, packet corrupt" );
565         return;
566     }
567
568     vlc_mutex_lock( &p_input->stream.stream_lock );
569
570     /* 4 == minimum useful size of a section */
571     while( p_byte + 4 <= p_end )
572     {
573         es_descriptor_t *   p_es = NULL;
574         u8                  i_stream_id = p_byte[1];
575         /* FIXME: there will be a problem with private streams... (same
576          * stream_id) */
577
578         /* Look for the ES in the ES table */
579         for( i = i_new_es_number;
580              i < p_input->stream.pp_programs[0]->i_es_number;
581              i++ )
582         {
583             if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
584                     == i_stream_id )
585             {
586                 p_es = p_input->stream.pp_programs[0]->pp_es[i];
587                 if( p_es->i_type != p_byte[0] )
588                 {
589                     input_DelES( p_input, p_es );
590                     p_es = NULL;
591                 }
592                 else
593                 {
594                     /* Move the ES to the beginning. */
595                     p_input->stream.pp_programs[0]->pp_es[i]
596                         = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
597                     p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
598                         = p_es;
599                     i_new_es_number++;
600                 }
601                 break;
602             }
603         }
604
605         /* The goal is to have all the ES we have just read in the
606          * beginning of the pp_es table, and all the others at the end,
607          * so that we can close them more easily at the end. */
608         if( p_es == NULL )
609         {
610             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
611                                 i_stream_id, 0 );
612             p_es->i_type = p_byte[0];
613             p_es->b_audio = ( p_es->i_type == MPEG1_AUDIO_ES
614                               || p_es->i_type == MPEG2_AUDIO_ES
615                               || p_es->i_type == AC3_AUDIO_ES
616                               || p_es->i_type == LPCM_AUDIO_ES
617                             );
618
619             /* input_AddES has inserted the new element at the end. */
620             p_input->stream.pp_programs[0]->pp_es[
621                 p_input->stream.pp_programs[0]->i_es_number ]
622                 = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
623             p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
624             i_new_es_number++;
625         }
626         p_byte += 4 + U16_AT(&p_byte[2]);
627     }
628
629     /* Un-select the streams that are no longer parts of the program. */
630     while( i_new_es_number < p_input->stream.pp_programs[0]->i_es_number )
631     {
632         /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
633          * list will be emptied starting from the end */
634         input_DelES( p_input,
635                      p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
636     }
637
638     if( p_main->b_stats )
639     {
640         intf_StatMsg( "input info: The stream map after the PSM is now :" );
641         input_DumpStream( p_input );
642     }
643
644     vlc_mutex_unlock( &p_input->stream.stream_lock );
645 }
646
647 /*****************************************************************************
648  * input_ParsePS: read the PS header
649  *****************************************************************************/
650 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
651                                  data_packet_t * p_data )
652 {
653     u32                 i_code;
654     es_descriptor_t *   p_es = NULL;
655
656     i_code = p_data->p_demux_start[3];
657
658     if( i_code > 0xBC ) /* ES start code */
659     {
660         u16                 i_id;
661         int                 i_dummy;
662
663         /* This is a PES packet. Find out if we want it or not. */
664         i_id = GetID( p_data );
665
666         vlc_mutex_lock( &p_input->stream.stream_lock );
667         if( p_input->stream.pp_programs[0]->b_is_ok )
668         {
669             /* Look only at the selected ES. */
670             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
671                  i_dummy++ )
672             {
673                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
674                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
675                 {
676                     p_es = p_input->stream.pp_selected_es[i_dummy];
677                     break;
678                 }
679             }
680         }
681         else
682         {
683             stream_ps_data_t * p_demux =
684               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
685
686             /* Search all ES ; if not found -> AddES */
687             p_es = input_FindES( p_input, i_id );
688
689             if( p_es == NULL && !p_demux->b_has_PSM )
690             {
691                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
692                                     i_id, 0 );
693                 if( p_es != NULL )
694                 {
695                     p_es->i_stream_id = p_data->p_demux_start[3];
696
697                     /* Set stream type and auto-spawn. */
698                     if( (i_id & 0xF0) == 0xE0 )
699                     {
700                         /* MPEG video */
701                         p_es->i_type = MPEG2_VIDEO_ES;
702                         p_es->i_cat = VIDEO_ES;
703 #ifdef AUTO_SPAWN
704                         if( !p_input->stream.b_seekable )
705                             input_SelectES( p_input, p_es );
706 #endif
707                     }
708                     else if( (i_id & 0xE0) == 0xC0 )
709                     {
710                         /* MPEG audio */
711                         p_es->i_type = MPEG2_AUDIO_ES;
712                         p_es->b_audio = 1;
713                         p_es->i_cat = AUDIO_ES;
714 #ifdef AUTO_SPAWN
715                         if( !p_input->stream.b_seekable )
716                         if( main_GetIntVariable( INPUT_CHANNEL_VAR, 0 )
717                                 == (p_es->i_id & 0x1F) )
718                         switch( main_GetIntVariable( INPUT_AUDIO_VAR, 0 ) )
719                         {
720                         case 0:
721                             main_PutIntVariable( INPUT_CHANNEL_VAR,
722                                                  REQUESTED_MPEG );
723                         case REQUESTED_MPEG:
724                             input_SelectES( p_input, p_es );
725                         }
726 #endif
727                     }
728                     else if( (i_id & 0xF0FF) == 0x80BD )
729                     {
730                         /* AC3 audio (0x80->0x8F) */
731                         p_es->i_type = AC3_AUDIO_ES;
732                         p_es->b_audio = 1;
733                         p_es->i_cat = AUDIO_ES;
734 #ifdef AUTO_SPAWN
735                         if( !p_input->stream.b_seekable )
736                         if( main_GetIntVariable( INPUT_CHANNEL_VAR, 0 )
737                                 == ((p_es->i_id & 0xF00) >> 8) )
738                         switch( main_GetIntVariable( INPUT_AUDIO_VAR, 0 ) )
739                         {
740                         case 0:
741                             main_PutIntVariable( INPUT_CHANNEL_VAR,
742                                                  REQUESTED_AC3 );
743                         case REQUESTED_AC3:
744                             input_SelectES( p_input, p_es );
745                         }
746 #endif
747                     }
748                     else if( (i_id & 0xE0FF) == 0x20BD )
749                     {
750                         /* Subtitles video (0x20->0x3F) */
751                         p_es->i_type = DVD_SPU_ES;
752                         p_es->i_cat = SPU_ES;
753 #ifdef AUTO_SPAWN
754                         if( main_GetIntVariable( INPUT_SUBTITLE_VAR, -1 )
755                                 == ((p_es->i_id & 0x1F00) >> 8) )
756                         {
757                             if( !p_input->stream.b_seekable )
758                                 input_SelectES( p_input, p_es );
759                         }
760 #endif
761                     }
762                     else if( (i_id & 0xF0FF) == 0xA0BD )
763                     {
764                         /* LPCM audio (0xA0->0xAF) */
765                         p_es->i_type = LPCM_AUDIO_ES;
766                         p_es->b_audio = 1;
767                         p_es->i_cat = AUDIO_ES;
768                     }
769                     else
770                     {
771                         p_es->i_type = UNKNOWN_ES;
772                     }
773                 }
774
775                 /* Tell the interface the stream has changed */
776                 p_input->stream.b_changed = 1;
777             }
778         } /* stream.b_is_ok */
779         vlc_mutex_unlock( &p_input->stream.stream_lock );
780     } /* i_code > 0xBC */
781
782     return( p_es );
783 }
784
785 /*****************************************************************************
786  * input_DemuxPS: first step of demultiplexing: the PS header
787  *****************************************************************************/
788 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
789 {
790     u32                 i_code;
791     boolean_t           b_trash = 0;
792     es_descriptor_t *   p_es = NULL;
793
794     i_code = ((u32)p_data->p_demux_start[0] << 24)
795                 | ((u32)p_data->p_demux_start[1] << 16)
796                 | ((u32)p_data->p_demux_start[2] << 8)
797                 | p_data->p_demux_start[3];
798     if( i_code <= 0x1BC )
799     {
800         switch( i_code )
801         {
802         case 0x1BA: /* PACK_START_CODE */
803             {
804                 /* Read the SCR. */
805                 mtime_t         scr_time;
806                 u32             i_mux_rate;
807
808                 if( (p_data->p_demux_start[4] & 0xC0) == 0x40 )
809                 {
810                     /* MPEG-2 */
811                     byte_t      p_header[14];
812                     byte_t *    p_byte;
813                     p_byte = p_data->p_demux_start;
814
815                     if( MoveChunk( p_header, &p_data, &p_byte, 14 ) != 14 )
816                     {
817                         intf_WarnMsg( 1, "input: packet too short "
818                                          "to have a header" );
819                         b_trash = 1;
820                         break;
821                     }
822                     scr_time =
823                          ((mtime_t)(p_header[4] & 0x38) << 27) |
824                          ((mtime_t)(U32_AT(p_header + 4) & 0x03FFF800)
825                                         << 4) |
826                          ((( ((mtime_t)U16_AT(p_header + 6) << 16)
827                             | (mtime_t)U16_AT(p_header + 8) ) & 0x03FFF800)
828                                         >> 11);
829
830                     /* mux_rate */
831                     i_mux_rate = ((u32)U16_AT(p_header + 10) << 6)
832                                    | (p_header[12] >> 2);
833                     /* FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
834                      * This is the biggest kludge ever !
835                      * I don't know what's wrong with mux_rate calculation
836                      * but this heuristic work well : */
837                     i_mux_rate <<= 1;
838                     i_mux_rate /= 3;
839                 }
840                 else
841                 {
842                     /* MPEG-1 SCR is like PTS. */
843                     byte_t      p_header[12];
844                     byte_t *    p_byte;
845                     p_byte = p_data->p_demux_start;
846
847                     if( MoveChunk( p_header, &p_data, &p_byte, 12 ) != 12 )
848                     {
849                         intf_WarnMsg( 1, "input: packet too short "
850                                          "to have a header" );
851                         b_trash = 1;
852                         break;
853                     }
854                     scr_time =
855                          ((mtime_t)(p_header[4] & 0x0E) << 29) |
856                          (((mtime_t)U32_AT(p_header + 4) & 0xFFFE00) << 6) |
857                          ((mtime_t)p_header[7] << 7) |
858                          ((mtime_t)p_header[8] >> 1);
859
860                     /* mux_rate */
861                     i_mux_rate = (U32_AT(p_header + 8) & 0x7FFFFE) >> 1;
862                 }
863                 /* Call the pace control. */
864                 input_ClockManageRef( p_input, p_input->stream.pp_programs[0],
865                                       scr_time );
866
867                 if( i_mux_rate != p_input->stream.i_mux_rate
868                      && p_input->stream.i_mux_rate )
869                 {
870                     intf_WarnMsg( 2, "input: mux_rate changed, "
871                                      "expect cosmetic errors" );
872                 }
873                 p_input->stream.i_mux_rate = i_mux_rate;
874
875                 b_trash = 1;
876             }
877             break;
878
879         case 0x1BB: /* SYSTEM_START_CODE */
880             b_trash = 1;                              /* Nothing interesting */
881             break;
882
883         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
884             DecodePSM( p_input, p_data );
885             b_trash = 1;
886             break;
887     
888         case 0x1B9: /* PROGRAM_END_CODE */
889             b_trash = 1;
890             break;
891    
892         default:
893             /* This should not happen */
894             b_trash = 1;
895             intf_WarnMsg( 3, "input: unwanted packet received "
896                              "with start code 0x%.8x", i_code );
897         }
898     }
899     else
900     {
901         p_es = input_ParsePS( p_input, p_data );
902
903         vlc_mutex_lock( &p_input->stream.control.control_lock );
904         if( p_es != NULL && p_es->p_decoder_fifo != NULL
905              && (!p_es->b_audio || !p_input->stream.control.b_mute) )
906         {
907             vlc_mutex_unlock( &p_input->stream.control.control_lock );
908             p_es->c_packets++;
909             input_GatherPES( p_input, p_data, p_es, 1, 0 );
910         }
911         else
912         {
913             vlc_mutex_unlock( &p_input->stream.control.control_lock );
914             b_trash = 1;
915         }
916     }
917
918     /* Trash the packet if it has no payload or if it isn't selected */
919     if( b_trash )
920     {
921         p_input->pf_delete_packet( p_input->p_method_data, p_data );
922         p_input->stream.c_packets_trashed++;
923     }
924 }
925
926  
927 /*
928  * TS Demultiplexing
929  */
930
931 /*****************************************************************************
932  * input_DemuxTS: first step of demultiplexing: the TS header
933  *****************************************************************************/
934 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
935 {
936     u16                 i_pid;
937     int                 i_dummy;
938     boolean_t           b_adaptation;         /* Adaptation field is present */
939     boolean_t           b_payload;                 /* Packet carries payload */
940     boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
941     boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
942     boolean_t           b_lost = 0;             /* Was there a packet loss ? */
943     boolean_t           b_psi = 0;                        /* Is this a PSI ? */
944     es_descriptor_t *   p_es = NULL;
945     es_ts_data_t *      p_es_demux = NULL;
946     pgrm_ts_data_t *    p_pgrm_demux = NULL;
947
948 #define p (p_data->p_demux_start)
949     /* Extract flags values from TS common header. */
950     i_pid = ((p[1] & 0x1F) << 8) | p[2];
951     b_unit_start = (p[1] & 0x40);
952     b_adaptation = (p[3] & 0x20);
953     b_payload = (p[3] & 0x10);
954
955     /* Find out the elementary stream. */
956     vlc_mutex_lock( &p_input->stream.stream_lock );
957         
958     p_es= input_FindES( p_input, i_pid );
959     
960     if( (p_es != NULL) && (p_es->p_demux_data != NULL) )
961     {
962         p_es_demux = (es_ts_data_t *)p_es->p_demux_data;
963         
964         if( p_es_demux->b_psi )
965         {
966             b_psi = 1;
967         }
968         else
969         {
970             p_pgrm_demux = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data; 
971         }
972     }
973
974     vlc_mutex_lock( &p_input->stream.control.control_lock );
975     if( ( p_es == NULL ) || (p_es->b_audio && p_input->stream.control.b_mute) )
976     {
977         /* Not selected. Just read the adaptation field for a PCR. */
978         b_trash = 1;
979     }
980     else if( p_es->p_decoder_fifo == NULL && !b_psi )
981     {
982         b_trash = 1; 
983     }
984
985     vlc_mutex_unlock( &p_input->stream.control.control_lock );
986     vlc_mutex_unlock( &p_input->stream.stream_lock );
987
988
989     /* Don't change the order of the tests : if b_psi then p_pgrm_demux 
990      * may still be null. Who said it was ugly ?
991      * I have written worse. --Meuuh */
992     if( ( p_es != NULL ) && 
993         ((p_es->p_decoder_fifo != NULL) || b_psi 
994                                    || (p_pgrm_demux->i_pcr_pid == i_pid) ) )
995     {
996         p_es->c_packets++;
997
998         /* Extract adaptation field information if any */
999
1000         if( !b_adaptation )
1001         {
1002             /* We don't have any adaptation_field, so payload starts
1003              * immediately after the 4 byte TS header */
1004             p_data->p_payload_start += 4;
1005         }
1006         else
1007         {
1008             /* p[4] is adaptation_field_length minus one */
1009             p_data->p_payload_start += 5 + p[4];
1010     
1011             /* The adaptation field can be limited to the
1012              * adaptation_field_length byte, so that there is nothing to do:
1013              * skip this possibility */
1014             if( p[4] )
1015             {
1016                 /* If the packet has both adaptation_field and payload,
1017                  * adaptation_field cannot be more than 182 bytes long; if
1018                  * there is only an adaptation_field, it must fill the next
1019                  * 183 bytes. */
1020                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1021                 {
1022                     intf_WarnMsg( 2,
1023                         "input: invalid TS adaptation field (%p)",
1024                         p_data );
1025                     p_data->b_discard_payload = 1;
1026                     p_es->c_invalid_packets++;
1027                 }
1028     
1029                 /* Now we are sure that the byte containing flags is present:
1030                  * read it */
1031                 else
1032                 {
1033                     /* discontinuity_indicator */
1034                     if( p[5] & 0x80 )
1035                     {
1036                         intf_WarnMsg( 2,
1037                             "input: discontinuity_indicator"
1038                             " encountered by TS demux (position read: %d,"
1039                             " saved: %d)",
1040                             p[5] & 0x80, p_es_demux->i_continuity_counter );
1041     
1042                         /* If the PID carries the PCR, there will be a system
1043                          * time-based discontinuity. We let the PCR decoder
1044                          * handle that. */
1045                         p_es->p_pgrm->i_synchro_state = SYNCHRO_REINIT;
1046     
1047                         /* There also may be a continuity_counter
1048                          * discontinuity: resynchronize our counter with
1049                          * the one of the stream. */
1050                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
1051                     }
1052     
1053                     /* If this is a PCR_PID, and this TS packet contains a
1054                      * PCR, we pass it along to the PCR decoder. */
1055
1056                     if( !b_psi && (p_pgrm_demux->i_pcr_pid == i_pid)
1057                         && (p[5] & 0x10) )
1058                     {
1059                         /* There should be a PCR field in the packet, check
1060                          * if the adaptation field is long enough to carry
1061                          * it. */
1062                         if( p[4] >= 7 )
1063                         {
1064                             /* Read the PCR. */
1065                             mtime_t     pcr_time;
1066                             pcr_time = ( (mtime_t)p[6] << 25 ) |
1067                                        ( (mtime_t)p[7] << 17 ) |
1068                                        ( (mtime_t)p[8] << 9 ) |
1069                                        ( (mtime_t)p[9] << 1 ) |
1070                                        ( (mtime_t)p[10] >> 7 );
1071                             /* Call the pace control. */
1072                             input_ClockManageRef( p_input, p_es->p_pgrm,
1073                                                   pcr_time );
1074                         }
1075                     } /* PCR ? */
1076                 } /* valid TS adaptation field ? */
1077             } /* length > 0 */
1078         } /* has adaptation field */
1079         /* Check the continuity of the stream. */
1080         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1081         if( i_dummy == 1 )
1082         {
1083             /* Everything is ok, just increase our counter */
1084             (p_es_demux->i_continuity_counter)++;
1085         }
1086         else
1087         {
1088             if( !b_payload && i_dummy == 0 )
1089             {
1090                 /* This is a packet without payload, this is allowed by the
1091                  * draft. As there is nothing interesting in this packet
1092                  * (except PCR that have already been handled), we can trash
1093                  * the packet. */
1094                 intf_WarnMsg( 3, "input: packet without payload received "
1095                                  "by TS demux" );
1096                 b_trash = 1;
1097             }
1098             else if( i_dummy <= 0 )
1099             {
1100                 /* Duplicate packet: mark it as being to be trashed. */
1101                 intf_WarnMsg( 3, "input: duplicate packet received "
1102                                  "by TS demux" );
1103                 b_trash = 1;
1104             }
1105             else if( p_es_demux->i_continuity_counter == 0xFF )
1106             {
1107                 /* This means that the packet is the first one we receive for
1108                  * this ES since the continuity counter ranges between 0 and
1109                  * 0x0F excepts when it has been initialized by the input:
1110                  * init the counter to the correct value. */
1111                 intf_WarnMsg( 3, "input: first packet for PID %d received "
1112                              "by TS demux", p_es->i_id );
1113                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1114             }
1115             else
1116             {
1117                 /* This can indicate that we missed a packet or that the
1118                  * continuity_counter wrapped and we received a dup packet:
1119                  * as we don't know, do as if we missed a packet to be sure
1120                  * to recover from this situation */
1121                 intf_WarnMsg( 2, "input: packet lost by TS demux: "
1122                                  "current %d, packet %d",
1123                               p_es_demux->i_continuity_counter & 0x0f,
1124                               p[3] & 0x0f );
1125                 b_lost = 1;
1126                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1127             } /* not continuous */
1128         } /* continuity */
1129     } /* if selected or PCR */
1130     
1131     /* Trash the packet if it has no payload or if it isn't selected */
1132     if( b_trash )
1133     {
1134         p_input->pf_delete_packet( p_input->p_method_data, p_data );
1135         p_input->stream.c_packets_trashed++;
1136     }
1137     else
1138     {
1139         if( b_psi )
1140         {
1141             /* The payload contains PSI tables */
1142             input_DemuxPSI( p_input, p_data, p_es,
1143                             b_unit_start, b_lost );
1144
1145         }
1146         else
1147         {
1148             /* The payload carries a PES stream */
1149             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost ); 
1150         }
1151
1152     }
1153
1154 #undef p
1155
1156 }
1157
1158 /*
1159  * PSI demultiplexing and decoding
1160  */
1161
1162 /*****************************************************************************
1163  * DemuxPSI : makes up complete PSI data
1164  *****************************************************************************/
1165 void input_DemuxPSI( input_thread_t * p_input, data_packet_t * p_data, 
1166         es_descriptor_t * p_es, boolean_t b_unit_start, boolean_t b_lost )
1167 {
1168     es_ts_data_t  * p_demux_data;
1169     
1170     p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
1171
1172 #define p_psi (p_demux_data->p_psi_section)
1173 #define p (p_data->p_payload_start)
1174
1175     if( b_unit_start )
1176     {
1177         /* unit_start set to 1 -> presence of a pointer field
1178          * (see ISO/IEC 13818 (2.4.4.2) which should be set to 0x00 */
1179         if( (u8)p[0] != 0x00 )
1180         {
1181             intf_WarnMsg( 2, "input: non zero pointer field found, "
1182                              "trying to continue" );
1183             p+=(u8)p[0];
1184         }
1185         else
1186         {
1187             p++;
1188         }
1189
1190         /* This is the begining of a new section */
1191
1192         if( ((u8)(p[1]) & 0xc0) != 0x80 ) 
1193         {
1194             intf_WarnMsg( 2, "input: invalid PSI packet" );
1195             p_psi->b_trash = 1;
1196         }
1197         else 
1198         {
1199             p_psi->i_section_length = ((p[1] & 0xF) << 8) | p[2];
1200             p_psi->b_section_complete = 0;
1201             p_psi->i_read_in_section = 0;
1202             p_psi->i_section_number = (u8)p[6];
1203
1204             if( p_psi->b_is_complete || p_psi->i_section_number == 0 )
1205             {
1206                 /* This is a new PSI packet */
1207                 p_psi->b_is_complete = 0;
1208                 p_psi->b_trash = 0;
1209                 p_psi->i_version_number = ( p[5] >> 1 ) & 0x1f;
1210                 p_psi->i_last_section_number = (u8)p[7];
1211
1212                 /* We'll write at the begining of the buffer */
1213                 p_psi->p_current = p_psi->buffer;
1214             }
1215             else
1216             {
1217                 if( p_psi->b_section_complete )
1218                 {
1219                     /* New Section of an already started PSI */
1220                     p_psi->b_section_complete = 0;
1221                     
1222                     if( p_psi->i_version_number != (( p[5] >> 1 ) & 0x1f) )
1223                     {
1224                         intf_WarnMsg( 2, "input: PSI version differs "
1225                                          "inside same PAT" );
1226                         p_psi->b_trash = 1;
1227                     }
1228                     if( p_psi->i_section_number + 1 != (u8)p[6] )
1229                     {
1230                         intf_WarnMsg( 2, "input: PSI Section discontinuity, "
1231                                          "packet lost ?" );
1232                         p_psi->b_trash = 1;
1233                     }
1234                     else
1235                         p_psi->i_section_number++;
1236                 }
1237                 else
1238                 {
1239                     intf_WarnMsg( 2, "input: got unexpected new PSI section" );
1240                     p_psi->b_trash = 1;
1241                 }
1242             }
1243         }
1244     } /* b_unit_start */
1245     
1246     if( !p_psi->b_trash )
1247     {
1248         /* read */
1249         if( (p_data->p_payload_end - p) >=
1250             ( p_psi->i_section_length - p_psi->i_read_in_section ) )
1251         {
1252             /* The end of the section is in this TS packet */
1253             memcpy( p_psi->p_current, p, 
1254             (p_psi->i_section_length - p_psi->i_read_in_section) );
1255     
1256             p_psi->b_section_complete = 1;
1257             p_psi->p_current += 
1258                 (p_psi->i_section_length - p_psi->i_read_in_section);
1259                         
1260             if( p_psi->i_section_number == p_psi->i_last_section_number )
1261             {
1262                 /* This was the last section of PSI */
1263                 p_psi->b_is_complete = 1;
1264
1265                 switch( p_demux_data->i_psi_type)
1266                 {
1267                 case PSI_IS_PAT:
1268                     input_DecodePAT( p_input, p_es );
1269                     break;
1270                 case PSI_IS_PMT:
1271                     input_DecodePMT( p_input, p_es );
1272                     break;
1273                 default:
1274                     intf_WarnMsg(2, "Received unknown PSI in DemuxPSI");
1275                 }
1276             }
1277         }
1278         else
1279         {
1280             memcpy( p_psi->buffer, p, p_data->p_payload_end - p );
1281             p_psi->i_read_in_section += p_data->p_payload_end - p;
1282
1283             p_psi->p_current += p_data->p_payload_end - p;
1284         }
1285     }
1286
1287 #undef p_psi    
1288 #undef p
1289    
1290     p_input->pf_delete_packet( p_input->p_method_data, p_data );
1291     
1292     return ;
1293 }
1294
1295 /*****************************************************************************
1296  * DecodePAT : Decodes Programm association table and deal with it
1297  *****************************************************************************/
1298 static void input_DecodePAT( input_thread_t * p_input, es_descriptor_t * p_es )
1299 {
1300     stream_ts_data_t  * p_stream_data;
1301     es_ts_data_t      * p_demux_data;
1302
1303     pgrm_descriptor_t * p_pgrm;
1304     es_descriptor_t   * p_current_es;
1305     byte_t            * p_current_data;           
1306
1307     int                 i_section_length, i_program_id, i_pmt_pid;
1308     int                 i_loop, i_current_section;
1309
1310     boolean_t           b_changed = 0;
1311
1312     p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
1313     p_stream_data = (stream_ts_data_t *)p_input->stream.p_demux_data;
1314     
1315 #define p_psi (p_demux_data->p_psi_section)
1316
1317     /* Not so fast, Mike ! If the PAT version has changed, we first check
1318      * that its content has really changed before doing anything */
1319     if( p_stream_data->i_pat_version != p_psi->i_version_number )
1320     {
1321         int i_programs = p_input->stream.i_pgrm_number;
1322
1323         p_current_data = p_psi->buffer;
1324
1325         do
1326         {
1327             i_section_length = ((u32)(p_current_data[1] & 0xF) << 8) |
1328                                  p_current_data[2];
1329             i_current_section = (u8)p_current_data[6];
1330     
1331             for( i_loop = 0;
1332                  ( i_loop < (i_section_length - 9) / 4 ) && !b_changed;
1333                  i_loop++ )
1334             {
1335                 i_program_id = ( (u32)*(p_current_data + i_loop * 4 + 8) << 8 )
1336                                  | *(p_current_data + i_loop * 4 + 9);
1337                 i_pmt_pid = ( ((u32)*(p_current_data + i_loop * 4 + 10) & 0x1F)
1338                                     << 8 )
1339                                | *(p_current_data + i_loop * 4 + 11);
1340
1341                 if( i_program_id )
1342                 {
1343                     if( (p_pgrm = input_FindProgram( p_input, i_program_id ))
1344                         && (p_current_es = input_FindES( p_input, i_pmt_pid ))
1345                         && p_current_es->p_pgrm == p_pgrm
1346                         && p_current_es->i_id == i_pmt_pid
1347                         && ((es_ts_data_t *)p_current_es->p_demux_data)->b_psi
1348                         && ((es_ts_data_t *)p_current_es->p_demux_data)
1349                             ->i_psi_type == PSI_IS_PMT )
1350                     {
1351                         i_programs--;
1352                     }
1353                     else
1354                     {
1355                         b_changed = 1;
1356                     }
1357                 }
1358             }
1359             
1360             p_current_data += 3 + i_section_length;
1361
1362         } while( ( i_current_section < p_psi->i_last_section_number )
1363                   && !b_changed );
1364
1365         /* If we didn't find the expected amount of programs, the PAT has
1366          * changed. Otherwise, it only changed if b_changed is already != 0 */
1367         b_changed = b_changed || i_programs;
1368     }
1369
1370     if( b_changed )
1371     {
1372         /* PAT has changed. We are going to delete all programs and 
1373          * create new ones. We chose not to only change what was needed
1374          * as a PAT change may mean the stream is radically changing and
1375          * this is a secure method to avoid crashes */
1376         es_ts_data_t      * p_es_demux;
1377         pgrm_ts_data_t    * p_pgrm_demux;
1378         
1379         p_current_data = p_psi->buffer;
1380
1381         /* Delete all programs */
1382         while( p_input->stream.i_pgrm_number )
1383         {
1384             input_DelProgram( p_input, p_input->stream.pp_programs[0] );
1385         }
1386         
1387         do
1388         {
1389             i_section_length = ((u32)(p_current_data[1] & 0xF) << 8) |
1390                                  p_current_data[2];
1391             i_current_section = (u8)p_current_data[6];
1392     
1393             for( i_loop = 0; i_loop < (i_section_length - 9) / 4 ; i_loop++ )
1394             {
1395                 i_program_id = ( (u32)*(p_current_data + i_loop * 4 + 8) << 8 )
1396                                  | *(p_current_data + i_loop * 4 + 9);
1397                 i_pmt_pid = ( ((u32)*(p_current_data + i_loop * 4 + 10) & 0x1F)
1398                                     << 8 )
1399                                | *(p_current_data + i_loop * 4 + 11);
1400     
1401                 /* If program = 0, we're having info about NIT not PMT */
1402                 if( i_program_id )
1403                 {
1404                     /* Add this program */
1405                     p_pgrm = input_AddProgram( p_input, i_program_id, 
1406                                                sizeof( pgrm_ts_data_t ) );
1407                    
1408                     /* whatis the PID of the PMT of this program */
1409                     p_pgrm_demux = (pgrm_ts_data_t *)p_pgrm->p_demux_data;
1410                     p_pgrm_demux->i_pmt_version = PMT_UNINITIALIZED;
1411     
1412                     /* Add the PMT ES to this program */
1413                     p_current_es = input_AddES( p_input, p_pgrm,(u16)i_pmt_pid,
1414                                         sizeof( es_ts_data_t) );
1415                     p_es_demux = (es_ts_data_t *)p_current_es->p_demux_data;
1416                     p_es_demux->b_psi = 1;
1417                     p_es_demux->i_psi_type = PSI_IS_PMT;
1418                     
1419                     p_es_demux->p_psi_section = 
1420                                             malloc( sizeof( psi_section_t ) );
1421                     p_es_demux->p_psi_section->b_is_complete = 0;
1422                 }
1423             }
1424             
1425             p_current_data += 3 + i_section_length;
1426
1427         } while( i_current_section < p_psi->i_last_section_number );
1428
1429         /* Go to the beginning of the next section */
1430         p_stream_data->i_pat_version = p_psi->i_version_number;
1431
1432     }
1433 #undef p_psi    
1434
1435     /* FIXME This has nothing to do here */
1436     p_input->stream.p_selected_program = p_input->stream.pp_programs[0] ;
1437 }
1438
1439 /*****************************************************************************
1440  * DecodePMT : decode a given Program Stream Map
1441  * ***************************************************************************
1442  * When the PMT changes, it may mean a deep change in the stream, and it is
1443  * careful to delete the ES and add them again. If the PMT doesn't change,
1444  * there no need to do anything.
1445  *****************************************************************************/
1446 static void input_DecodePMT( input_thread_t * p_input, es_descriptor_t * p_es )
1447 {
1448
1449     pgrm_ts_data_t            * p_pgrm_data;
1450     es_ts_data_t              * p_demux_data;
1451
1452     p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
1453     p_pgrm_data = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data;
1454     
1455 #define p_psi (p_demux_data->p_psi_section)
1456
1457     if( p_psi->i_version_number != p_pgrm_data->i_pmt_version ) 
1458     {
1459         es_descriptor_t   * p_new_es;  
1460         es_ts_data_t      * p_es_demux;
1461         byte_t            * p_current_data, * p_current_section;
1462         int                 i_section_length,i_current_section;
1463         int                 i_prog_info_length, i_loop;
1464         int                 i_es_info_length, i_pid, i_stream_type;
1465         int                 i_audio_es, i_spu_es;
1466         int                 i_required_audio_es, i_required_spu_es;
1467         
1468         p_current_section = p_psi->buffer;
1469         p_current_data = p_psi->buffer;
1470
1471         p_pgrm_data->i_pcr_pid = ( ((u32)*(p_current_section + 8) & 0x1F) << 8 ) |
1472                                     *(p_current_section + 9);
1473
1474         i_audio_es = 0;
1475         i_spu_es = 0;
1476
1477         /* Lock stream information */
1478         vlc_mutex_lock( &p_input->stream.stream_lock );
1479
1480         /* Get the number of the required audio stream */
1481         if( p_main->b_audio )
1482         {
1483             /* Default is the first one */
1484             i_required_audio_es = main_GetIntVariable( INPUT_CHANNEL_VAR, 1 );
1485             if( i_required_audio_es < 0 )
1486             {
1487                 main_PutIntVariable( INPUT_CHANNEL_VAR, 1 );
1488                 i_required_audio_es = 1;
1489             }
1490         }
1491         else
1492         {
1493             i_required_audio_es = 0;
1494         }
1495
1496         /* Same thing for subtitles */
1497         if( p_main->b_video )
1498         {
1499             /* for spu, default is none */
1500             i_required_spu_es = main_GetIntVariable( INPUT_SUBTITLE_VAR, 0 );
1501             if( i_required_spu_es < 0 )
1502             {
1503                 main_PutIntVariable( INPUT_SUBTITLE_VAR, 0 );
1504                 i_required_spu_es = 0;
1505             }
1506         }
1507         else
1508         {
1509             i_required_spu_es = 0;
1510         }
1511         
1512         /* Delete all ES in this program  except the PSI. We start from the
1513          * end because i_es_number gets decremented after each deletion. */
1514         for( i_loop = p_es->p_pgrm->i_es_number ; i_loop ; )
1515         {
1516             i_loop--;
1517             p_es_demux = (es_ts_data_t *)
1518                          p_es->p_pgrm->pp_es[i_loop]->p_demux_data;
1519             if ( ! p_es_demux->b_psi )
1520             {
1521                 input_DelES( p_input, p_es->p_pgrm->pp_es[i_loop] );
1522             }
1523         }
1524
1525         /* Then add what we received in this PMT */
1526         do
1527         {
1528             i_section_length = ( ((u32)*(p_current_data + 1) & 0xF) << 8 ) |
1529                                   *(p_current_data + 2);
1530             i_current_section = (u8)p_current_data[6];
1531             i_prog_info_length = ( ((u32)*(p_current_data + 10) & 0xF) << 8 ) |
1532                                     *(p_current_data + 11);
1533
1534             /* For the moment we ignore program descriptors */
1535             p_current_data += 12 + i_prog_info_length;
1536     
1537             /* The end of the section, before the CRC is at 
1538              * p_current_section + i_section_length -1 */
1539             while( p_current_data < p_current_section + i_section_length -1 )
1540             {
1541                 i_stream_type = (int)p_current_data[0];
1542                 i_pid = ( ((u32)*(p_current_data + 1) & 0x1F) << 8 ) |
1543                            *(p_current_data + 2);
1544                 i_es_info_length = ( ((u32)*(p_current_data + 3) & 0xF) << 8 ) |
1545                                       *(p_current_data + 4);
1546                 
1547                 /* Add this ES to the program */
1548                 p_new_es = input_AddES( p_input, p_es->p_pgrm, 
1549                                         (u16)i_pid, sizeof( es_ts_data_t ) );
1550
1551                 /* Tell the decoders what kind of stream it is */
1552                 p_new_es->i_type = i_stream_type;
1553
1554                 /* Tell the interface what kind of stream it is and select 
1555                  * the required ones */
1556                 switch( i_stream_type )
1557                 {
1558                     case MPEG1_VIDEO_ES:
1559                     case MPEG2_VIDEO_ES:
1560                         p_new_es->i_cat = VIDEO_ES;
1561                         input_SelectES( p_input, p_new_es );
1562                         break;
1563                     case MPEG1_AUDIO_ES:
1564                     case MPEG2_AUDIO_ES:
1565                         p_new_es->i_cat = AUDIO_ES;
1566                         i_audio_es += 1;
1567                         if( i_audio_es == i_required_audio_es )
1568                             input_SelectES( p_input, p_new_es );
1569                         break;
1570                     case LPCM_AUDIO_ES :
1571                     case AC3_AUDIO_ES :
1572                         p_new_es->i_stream_id = 0xBD;
1573                         p_new_es->i_cat = AUDIO_ES;
1574                         i_audio_es += 1;
1575                         if( i_audio_es == i_required_audio_es )
1576                             input_SelectES( p_input, p_new_es );
1577                         break;
1578                     /* Not sure this one is fully specification-compliant */
1579                     case DVD_SPU_ES :
1580                         p_new_es->i_stream_id = 0xBD;
1581                         p_new_es->i_cat = SPU_ES;
1582                         i_spu_es += 1;
1583                         if( i_spu_es == i_required_spu_es )
1584                             input_SelectES( p_input, p_new_es );
1585                         break;
1586                     default :
1587                         p_new_es->i_cat = UNKNOWN_ES;
1588                         break;
1589                 }
1590                 
1591                 p_current_data += 5 + i_es_info_length;
1592             }
1593
1594             /* Go to the beginning of the next section*/
1595             p_current_data += 3 + i_section_length;
1596            
1597             p_current_section++;
1598             
1599         } while( i_current_section < p_psi->i_last_section_number );
1600
1601         if( i_required_audio_es > i_audio_es )
1602         {
1603             intf_WarnMsg( 2, "input: non-existing audio ES required" );
1604         }
1605         
1606         if( i_required_spu_es > i_spu_es )
1607         {
1608             intf_WarnMsg( 2, "input: non-existing subtitles ES required" );
1609         }
1610         
1611         p_pgrm_data->i_pmt_version = p_psi->i_version_number;
1612
1613         /* inform interface that stream has changed */
1614         p_input->stream.b_changed = 1;
1615         /*  Remove lock */
1616         vlc_mutex_unlock( &p_input->stream.stream_lock );
1617     }
1618     
1619 #undef p_psi
1620 }
1621