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