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