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