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