]> git.sesse.net Git - vlc/blob - src/input/mpeg_system.c
f6b7040da3d4538c3000cab706fd7b977043cb87
[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.87 2002/03/20 17:44:15 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     /* 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 = ((u16)p_data->p_payload_start[4] << 8)
459                                          + p_data->p_payload_start[5] + 6;
460             }
461             else
462             { 
463                 p_es->i_pes_real_size = 0;
464             } 
465         }
466         else
467         {
468             /* Update the relations between the data packets */
469             p_pes->p_last->p_next = p_data;
470         }
471
472         p_pes->p_last = p_data;
473         p_pes->i_nb_data++;
474
475         /* Size of the payload carried in the data packet */
476         p_pes->i_pes_size += (p_data->p_payload_end
477                                  - p_data->p_payload_start);
478     
479         /* We can check if the packet is finished */
480         if( p_pes->i_pes_size == p_es->i_pes_real_size )
481         {
482             /* The packet is finished, parse it */
483             input_ParsePES( p_input, p_es );
484         }
485     }
486 #undef p_pes
487 }
488
489
490 /*
491  * PS Demultiplexing
492  */
493
494 /*****************************************************************************
495  * GetID: Get the ID of a stream
496  *****************************************************************************/
497 static u16 GetID( data_packet_t * p_data )
498 {
499     u16         i_id;
500
501     i_id = p_data->p_demux_start[3];                            /* stream_id */
502     if( i_id == 0xBD )
503     {
504         /* FIXME : this is not valid if the header is split in multiple
505          * packets */
506         /* stream_private_id */
507         i_id |= p_data->p_demux_start[ 9 + p_data->p_demux_start[8] ] << 8;
508     }
509     return( i_id );
510 }
511
512 /*****************************************************************************
513  * DecodePSM: Decode the Program Stream Map information
514  *****************************************************************************
515  * FIXME : loads are not aligned in this function
516  *****************************************************************************/
517 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
518 {
519     stream_ps_data_t *  p_demux =
520                  (stream_ps_data_t *)p_input->stream.p_demux_data;
521     byte_t *            p_byte;
522     byte_t *            p_end;
523     int                 i;
524     int                 i_new_es_number = 0;
525
526     if( p_data->p_demux_start + 10 > p_data->p_payload_end )
527     {
528         intf_ErrMsg( "input error: PSM too short : packet corrupt" );
529         return;
530     }
531
532     if( p_demux->b_has_PSM
533         && p_demux->i_PSM_version == (p_data->p_demux_start[6] & 0x1F) )
534     {
535         /* Already got that one. */
536         return;
537     }
538
539     p_demux->b_has_PSM = 1;
540     p_demux->i_PSM_version = p_data->p_demux_start[6] & 0x1F;
541
542     /* Go to elementary_stream_map_length, jumping over
543      * program_stream_info. */
544     p_byte = p_data->p_demux_start + 10
545               + U16_AT(&p_data->p_demux_start[8]);
546     if( p_byte > p_data->p_payload_end )
547     {
548         intf_ErrMsg( "input error: PSM too short, packet corrupt" );
549         return;
550     }
551     /* This is the full size of the elementary_stream_map.
552      * 2 == elementary_stream_map_length
553      * Please note that CRC_32 is not included in the length. */
554     p_end = p_byte + 2 + U16_AT(p_byte);
555     p_byte += 2;
556     if( p_end > p_data->p_payload_end )
557     {
558         intf_ErrMsg( "input error: PSM too short, packet corrupt" );
559         return;
560     }
561
562     vlc_mutex_lock( &p_input->stream.stream_lock );
563
564     /* 4 == minimum useful size of a section */
565     while( p_byte + 4 <= p_end )
566     {
567         es_descriptor_t *   p_es = NULL;
568         u8                  i_stream_id = p_byte[1];
569         /* FIXME: there will be a problem with private streams... (same
570          * stream_id) */
571
572         /* Look for the ES in the ES table */
573         for( i = i_new_es_number;
574              i < p_input->stream.pp_programs[0]->i_es_number;
575              i++ )
576         {
577             if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
578                     == i_stream_id )
579             {
580                 p_es = p_input->stream.pp_programs[0]->pp_es[i];
581                 if( p_es->i_type != p_byte[0] )
582                 {
583                     input_DelES( p_input, p_es );
584                     p_es = NULL;
585                 }
586                 else
587                 {
588                     /* Move the ES to the beginning. */
589                     p_input->stream.pp_programs[0]->pp_es[i]
590                         = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
591                     p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
592                         = p_es;
593                     i_new_es_number++;
594                 }
595                 break;
596             }
597         }
598
599         /* The goal is to have all the ES we have just read in the
600          * beginning of the pp_es table, and all the others at the end,
601          * so that we can close them more easily at the end. */
602         if( p_es == NULL )
603         {
604             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
605                                 i_stream_id, 0 );
606             p_es->i_type = p_byte[0];
607             p_es->b_audio = ( p_es->i_type == MPEG1_AUDIO_ES
608                               || p_es->i_type == MPEG2_AUDIO_ES
609                               || p_es->i_type == AC3_AUDIO_ES
610                               || p_es->i_type == LPCM_AUDIO_ES
611                             );
612
613             /* input_AddES has inserted the new element at the end. */
614             p_input->stream.pp_programs[0]->pp_es[
615                 p_input->stream.pp_programs[0]->i_es_number ]
616                 = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
617             p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
618             i_new_es_number++;
619         }
620         p_byte += 4 + U16_AT(&p_byte[2]);
621     }
622
623     /* Un-select the streams that are no longer parts of the program. */
624     while( i_new_es_number < p_input->stream.pp_programs[0]->i_es_number )
625     {
626         /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
627          * list will be emptied starting from the end */
628         input_DelES( p_input,
629                      p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
630     }
631
632     if( p_main->b_stats )
633     {
634         intf_StatMsg( "input info: The stream map after the PSM is now :" );
635         input_DumpStream( p_input );
636     }
637
638     vlc_mutex_unlock( &p_input->stream.stream_lock );
639 }
640
641 /*****************************************************************************
642  * input_ReadPS: store a PS packet into a data_buffer_t
643  *****************************************************************************/
644 #define PEEK( SIZE )                                                        \
645     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
646     if( i_error == -1 )                                                     \
647     {                                                                       \
648         return( -1 );                                                       \
649     }                                                                       \
650     else if( i_error < SIZE )                                               \
651     {                                                                       \
652         /* EOF */                                                           \
653         return( 0 );                                                        \
654     }
655
656 ssize_t input_ReadPS( input_thread_t * p_input, data_packet_t ** pp_data )
657 {
658     byte_t *            p_peek;
659     size_t              i_packet_size;
660     ssize_t             i_error, i_read;
661
662     /* Read what we believe to be a packet header. */
663     PEEK( 4 );
664
665     if( *p_peek || *(p_peek + 1) || *(p_peek + 2) != 1 )
666     {
667         if( *p_peek || *(p_peek + 1) || *(p_peek + 2) )
668         {
669             /* It is common for MPEG-1 streams to pad with zeros
670              * (although it is forbidden by the recommendation), so
671              * don't bother everybody in this case. */
672             intf_WarnMsg( 3, "input warning: garbage (0x%.2x%.2x%.2x%.2x)",
673                  *p_peek, *(p_peek + 1), *(p_peek + 2), *(p_peek + 3) );
674         }
675
676         /* This is not the startcode of a packet. Read the stream
677          * until we find one. */
678         while( *p_peek || *(p_peek + 1) || *(p_peek + 2) != 1 )
679         {
680             p_input->p_current_data++;
681             PEEK( 4 );
682         }
683         /* Packet found. */
684     }
685
686     /* 0x1B9 == SYSTEM_END_CODE, it is only 4 bytes long. */
687     if( p_peek[3] != 0xB9 )
688     {
689         /* The packet is at least 6 bytes long. */
690         PEEK( 6 );
691
692         if( p_peek[3] != 0xBA )
693         {
694             /* That's the case for all packets, except pack header. */
695             i_packet_size = (p_peek[4] << 8) | p_peek[5];
696         }
697         else
698         {
699             /* Pack header. */
700             if( (p_peek[4] & 0xC0) == 0x40 )
701             {
702                 /* MPEG-2 */
703                 i_packet_size = 8;
704             }
705             else if( (p_peek[4] & 0xF0) == 0x20 )
706             {
707                 /* MPEG-1 */
708                 i_packet_size = 6;
709             }
710             else
711             {
712                 intf_ErrMsg( "Unable to determine stream type" );
713                 return( -1 );
714             }
715         }
716     }
717     else
718     {
719         /* System End Code */
720         i_packet_size = -2;
721     }
722
723     /* Fetch a packet of the appropriate size. */
724     i_read = input_SplitBuffer( p_input, pp_data, i_packet_size + 6 );
725     if( i_read <= 0 )
726     {
727         return( i_read );
728     }
729
730     /* In MPEG-2 pack headers we still have to read stuffing bytes. */
731     if( ((*pp_data)->p_demux_start[3] == 0xBA) && (i_packet_size == 8) )
732     {
733         size_t i_stuffing = ((*pp_data)->p_demux_start[13] & 0x7);
734         /* Force refill of the input buffer - though we don't care
735          * about p_peek. Please note that this is unoptimized. */
736         PEEK( i_stuffing );
737         p_input->p_current_data += i_stuffing;
738     }
739
740     return( 1 );
741 }
742
743 #undef PEEK
744
745 /*****************************************************************************
746  * input_ParsePS: read the PS header
747  *****************************************************************************/
748 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
749                                  data_packet_t * p_data )
750 {
751     u32                 i_code;
752     es_descriptor_t *   p_es = NULL;
753
754     i_code = p_data->p_demux_start[3];
755
756     if( i_code > 0xBC ) /* ES start code */
757     {
758         u16                 i_id;
759         int                 i_dummy;
760
761         /* This is a PES packet. Find out if we want it or not. */
762         i_id = GetID( p_data );
763
764         vlc_mutex_lock( &p_input->stream.stream_lock );
765         if( p_input->stream.pp_programs[0]->b_is_ok )
766         {
767             /* Look only at the selected ES. */
768             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
769                  i_dummy++ )
770             {
771                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
772                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
773                 {
774                     p_es = p_input->stream.pp_selected_es[i_dummy];
775                     break;
776                 }
777             }
778         }
779         else
780         {
781             stream_ps_data_t * p_demux =
782               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
783
784             /* Search all ES ; if not found -> AddES */
785             p_es = input_FindES( p_input, i_id );
786
787             if( p_es == NULL && !p_demux->b_has_PSM )
788             {
789                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
790                                     i_id, 0 );
791                 if( p_es != NULL )
792                 {
793                     p_es->i_stream_id = p_data->p_demux_start[3];
794
795                     /* Set stream type and auto-spawn. */
796                     if( (i_id & 0xF0) == 0xE0 )
797                     {
798                         /* MPEG video */
799                         p_es->i_type = MPEG2_VIDEO_ES;
800                         p_es->i_cat = VIDEO_ES;
801 #ifdef AUTO_SPAWN
802                         if( !p_input->stream.b_seekable )
803                             input_SelectES( p_input, p_es );
804 #endif
805                     }
806                     else if( (i_id & 0xE0) == 0xC0 )
807                     {
808                         /* MPEG audio */
809                         p_es->i_type = MPEG2_AUDIO_ES;
810                         p_es->b_audio = 1;
811                         p_es->i_cat = AUDIO_ES;
812 #ifdef AUTO_SPAWN
813                         if( !p_input->stream.b_seekable )
814                         if( config_GetIntVariable( "input_channel" )
815                                 == (p_es->i_id & 0x1F) ||
816                             ( config_GetIntVariable( "input_channel" ) < 0
817                               && !(p_es->i_id & 0x1F) ) )
818                         switch( config_GetIntVariable( "input_audio" ) )
819                         {
820                         case -1:
821                         case REQUESTED_MPEG:
822                             input_SelectES( p_input, p_es );
823                         }
824 #endif
825                     }
826                     else if( (i_id & 0xF0FF) == 0x80BD )
827                     {
828                         /* AC3 audio (0x80->0x8F) */
829                         p_es->i_type = AC3_AUDIO_ES;
830                         p_es->b_audio = 1;
831                         p_es->i_cat = AUDIO_ES;
832 #ifdef AUTO_SPAWN
833                         if( !p_input->stream.b_seekable )
834                         if( config_GetIntVariable( "input_channel" )
835                                 == ((p_es->i_id & 0xF00) >> 8) ||
836                             ( config_GetIntVariable( "input_channel" ) < 0
837                               && !((p_es->i_id & 0xF00) >> 8)) )
838                         switch( config_GetIntVariable( "input_audio" ) )
839                         {
840                         case -1:
841                         case REQUESTED_AC3:
842                             input_SelectES( p_input, p_es );
843                         }
844 #endif
845                     }
846                     else if( (i_id & 0xE0FF) == 0x20BD )
847                     {
848                         /* Subtitles video (0x20->0x3F) */
849                         p_es->i_type = DVD_SPU_ES;
850                         p_es->i_cat = SPU_ES;
851 #ifdef AUTO_SPAWN
852                         if( config_GetIntVariable( "input_subtitle" )
853                                 == ((p_es->i_id & 0x1F00) >> 8) )
854                         {
855                             if( !p_input->stream.b_seekable )
856                                 input_SelectES( p_input, p_es );
857                         }
858 #endif
859                     }
860                     else if( (i_id & 0xF0FF) == 0xA0BD )
861                     {
862                         /* LPCM audio (0xA0->0xAF) */
863                         p_es->i_type = LPCM_AUDIO_ES;
864                         p_es->b_audio = 1;
865                         p_es->i_cat = AUDIO_ES;
866                     }
867                     else
868                     {
869                         p_es->i_type = UNKNOWN_ES;
870                     }
871                 }
872
873                 /* Tell the interface the stream has changed */
874                 p_input->stream.b_changed = 1;
875             }
876         } /* stream.b_is_ok */
877         vlc_mutex_unlock( &p_input->stream.stream_lock );
878     } /* i_code > 0xBC */
879
880     return( p_es );
881 }
882
883 /*****************************************************************************
884  * input_DemuxPS: first step of demultiplexing: the PS header
885  *****************************************************************************/
886 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
887 {
888     u32                 i_code;
889     boolean_t           b_trash = 0;
890     es_descriptor_t *   p_es = NULL;
891
892     i_code = ((u32)p_data->p_demux_start[0] << 24)
893                 | ((u32)p_data->p_demux_start[1] << 16)
894                 | ((u32)p_data->p_demux_start[2] << 8)
895                 | p_data->p_demux_start[3];
896     if( i_code <= 0x1BC )
897     {
898         switch( i_code )
899         {
900         case 0x1BA: /* PACK_START_CODE */
901             {
902                 /* Read the SCR. */
903                 mtime_t         scr_time;
904                 u32             i_mux_rate;
905
906                 if( (p_data->p_demux_start[4] & 0xC0) == 0x40 )
907                 {
908                     /* MPEG-2 */
909                     byte_t      p_header[14];
910                     byte_t *    p_byte;
911                     p_byte = p_data->p_demux_start;
912
913                     if( MoveChunk( p_header, &p_data, &p_byte, 14 ) != 14 )
914                     {
915                         intf_WarnMsg( 1, "input: packet too short "
916                                          "to have a header" );
917                         b_trash = 1;
918                         break;
919                     }
920                     scr_time =
921                          ((mtime_t)(p_header[4] & 0x38) << 27) |
922                          ((mtime_t)(U32_AT(p_header + 4) & 0x03FFF800)
923                                         << 4) |
924                          ((( ((mtime_t)U16_AT(p_header + 6) << 16)
925                             | (mtime_t)U16_AT(p_header + 8) ) & 0x03FFF800)
926                                         >> 11);
927
928                     /* mux_rate */
929                     i_mux_rate = ((u32)U16_AT(p_header + 10) << 6)
930                                    | (p_header[12] >> 2);
931                     /* FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
932                      * This is the biggest kludge ever !
933                      * I don't know what's wrong with mux_rate calculation
934                      * but this heuristic work well : */
935                     i_mux_rate <<= 1;
936                     i_mux_rate /= 3;
937                 }
938                 else
939                 {
940                     /* MPEG-1 SCR is like PTS. */
941                     byte_t      p_header[12];
942                     byte_t *    p_byte;
943                     p_byte = p_data->p_demux_start;
944
945                     if( MoveChunk( p_header, &p_data, &p_byte, 12 ) != 12 )
946                     {
947                         intf_WarnMsg( 1, "input: packet too short "
948                                          "to have a header" );
949                         b_trash = 1;
950                         break;
951                     }
952                     scr_time =
953                          ((mtime_t)(p_header[4] & 0x0E) << 29) |
954                          (((mtime_t)U32_AT(p_header + 4) & 0xFFFE00) << 6) |
955                          ((mtime_t)p_header[7] << 7) |
956                          ((mtime_t)p_header[8] >> 1);
957
958                     /* mux_rate */
959                     i_mux_rate = (U32_AT(p_header + 8) & 0x7FFFFE) >> 1;
960                 }
961                 /* Call the pace control. */
962                 input_ClockManageRef( p_input,
963                                       p_input->stream.p_selected_program,
964                                       scr_time );
965
966                 if( i_mux_rate != p_input->stream.i_mux_rate
967                      && p_input->stream.i_mux_rate )
968                 {
969                     intf_WarnMsg( 2, "input: mux_rate changed, "
970                                      "expect cosmetic errors" );
971                 }
972                 p_input->stream.i_mux_rate = i_mux_rate;
973
974                 b_trash = 1;
975             }
976             break;
977
978         case 0x1BB: /* SYSTEM_START_CODE */
979             b_trash = 1;                              /* Nothing interesting */
980             break;
981
982         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
983             DecodePSM( p_input, p_data );
984             b_trash = 1;
985             break;
986     
987         case 0x1B9: /* PROGRAM_END_CODE */
988             b_trash = 1;
989             break;
990    
991         default:
992             /* This should not happen */
993             b_trash = 1;
994             intf_WarnMsg( 3, "input: unwanted packet received "
995                              "with start code 0x%.8x", i_code );
996         }
997     }
998     else
999     {
1000         p_es = input_ParsePS( p_input, p_data );
1001
1002         vlc_mutex_lock( &p_input->stream.control.control_lock );
1003         if( p_es != NULL && p_es->p_decoder_fifo != NULL
1004              && (!p_es->b_audio || !p_input->stream.control.b_mute) )
1005         {
1006             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1007             p_es->c_packets++;
1008             input_GatherPES( p_input, p_data, p_es, 1, 0 );
1009         }
1010         else
1011         {
1012             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1013             b_trash = 1;
1014         }
1015     }
1016
1017     /* Trash the packet if it has no payload or if it isn't selected */
1018     if( b_trash )
1019     {
1020         input_DeletePacket( p_input->p_method_data, p_data );
1021         p_input->stream.c_packets_trashed++;
1022     }
1023 }
1024
1025  
1026 /*
1027  * TS Demultiplexing
1028  */
1029
1030 /*****************************************************************************
1031  * input_ReadTS: store a TS packet into a data_buffer_t
1032  *****************************************************************************/
1033 #define PEEK( SIZE )                                                        \
1034     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
1035     if( i_error == -1 )                                                     \
1036     {                                                                       \
1037         return( -1 );                                                       \
1038     }                                                                       \
1039     else if( i_error < SIZE )                                               \
1040     {                                                                       \
1041         /* EOF */                                                           \
1042         return( 0 );                                                        \
1043     }
1044
1045 ssize_t input_ReadTS( input_thread_t * p_input, data_packet_t ** pp_data )
1046 {
1047     byte_t *            p_peek;
1048     ssize_t             i_error, i_read;
1049
1050     PEEK( 1 );
1051
1052     if( *p_peek != TS_SYNC_CODE )
1053     {
1054         intf_WarnMsg( 3, "input warning: garbage at input (%x)", *p_peek );
1055
1056         if( p_input->i_mtu )
1057         {
1058             while( *p_peek != TS_SYNC_CODE )
1059             {
1060                 /* Try to resync on next packet. */
1061                 PEEK( TS_PACKET_SIZE );
1062                 p_input->p_current_data += TS_PACKET_SIZE;
1063                 PEEK( 1 );
1064             }
1065         }
1066         else
1067         {
1068             /* Move forward until we find 0x47 (and hope it's the good
1069              * one... FIXME) */
1070             while( *p_peek != TS_SYNC_CODE )
1071             {
1072                 p_input->p_current_data++;
1073                 PEEK( 1 );
1074             }
1075         }
1076     }
1077
1078     i_read = input_SplitBuffer( p_input, pp_data, TS_PACKET_SIZE );
1079     if( i_read <= 0 )
1080     {
1081         return( i_read );
1082     }
1083
1084     return( 1 );
1085 }
1086
1087 /*****************************************************************************
1088  * input_DemuxTS: first step of demultiplexing: the TS header
1089  *****************************************************************************/
1090 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
1091 {
1092     u16                 i_pid;
1093     int                 i_dummy;
1094     boolean_t           b_adaptation;         /* Adaptation field is present */
1095     boolean_t           b_payload;                 /* Packet carries payload */
1096     boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
1097     boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
1098     boolean_t           b_lost = 0;             /* Was there a packet loss ? */
1099     boolean_t           b_psi = 0;                        /* Is this a PSI ? */
1100     es_descriptor_t *   p_es = NULL;
1101     es_ts_data_t *      p_es_demux = NULL;
1102     pgrm_ts_data_t *    p_pgrm_demux = NULL;
1103
1104 #define p (p_data->p_demux_start)
1105     /* Extract flags values from TS common header. */
1106     i_pid = ((p[1] & 0x1F) << 8) | p[2];
1107     b_unit_start = (p[1] & 0x40);
1108     b_adaptation = (p[3] & 0x20);
1109     b_payload = (p[3] & 0x10);
1110
1111     /* Find out the elementary stream. */
1112     vlc_mutex_lock( &p_input->stream.stream_lock );
1113         
1114     p_es= input_FindES( p_input, i_pid );
1115     
1116     if( (p_es != NULL) && (p_es->p_demux_data != NULL) )
1117     {
1118         p_es_demux = (es_ts_data_t *)p_es->p_demux_data;
1119         
1120         if( p_es_demux->b_psi )
1121         {
1122             b_psi = 1;
1123         }
1124         else
1125         {
1126             p_pgrm_demux = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data; 
1127         }
1128     }
1129
1130     vlc_mutex_lock( &p_input->stream.control.control_lock );
1131     if( ( p_es == NULL ) || (p_es->b_audio && p_input->stream.control.b_mute) )
1132     {
1133         /* Not selected. Just read the adaptation field for a PCR. */
1134         b_trash = 1;
1135     }
1136     else if( p_es->p_decoder_fifo == NULL && !b_psi )
1137     {
1138         b_trash = 1; 
1139     }
1140
1141     vlc_mutex_unlock( &p_input->stream.control.control_lock );
1142     vlc_mutex_unlock( &p_input->stream.stream_lock );
1143
1144
1145     /* Don't change the order of the tests : if b_psi then p_pgrm_demux 
1146      * may still be null. Who said it was ugly ?
1147      * I have written worse. --Meuuh */
1148     if( ( p_es != NULL ) && 
1149         ((p_es->p_decoder_fifo != NULL) || b_psi 
1150                                    || (p_pgrm_demux->i_pcr_pid == i_pid) ) )
1151     {
1152         p_es->c_packets++;
1153
1154         /* Extract adaptation field information if any */
1155
1156         if( !b_adaptation )
1157         {
1158             /* We don't have any adaptation_field, so payload starts
1159              * immediately after the 4 byte TS header */
1160             p_data->p_payload_start += 4;
1161         }
1162         else
1163         {
1164             /* p[4] is adaptation_field_length minus one */
1165             p_data->p_payload_start += 5 + p[4];
1166     
1167             /* The adaptation field can be limited to the
1168              * adaptation_field_length byte, so that there is nothing to do:
1169              * skip this possibility */
1170             if( p[4] )
1171             {
1172                 /* If the packet has both adaptation_field and payload,
1173                  * adaptation_field cannot be more than 182 bytes long; if
1174                  * there is only an adaptation_field, it must fill the next
1175                  * 183 bytes. */
1176                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1177                 {
1178                     intf_WarnMsg( 2,
1179                         "input: invalid TS adaptation field (%p)",
1180                         p_data );
1181                     p_data->b_discard_payload = 1;
1182                     p_es->c_invalid_packets++;
1183                 }
1184     
1185                 /* Now we are sure that the byte containing flags is present:
1186                  * read it */
1187                 else
1188                 {
1189                     /* discontinuity_indicator */
1190                     if( p[5] & 0x80 )
1191                     {
1192                         intf_WarnMsg( 2,
1193                             "input: discontinuity_indicator"
1194                             " encountered by TS demux (position read: %d,"
1195                             " saved: %d)",
1196                             p[5] & 0x80, p_es_demux->i_continuity_counter );
1197     
1198                         /* If the PID carries the PCR, there will be a system
1199                          * time-based discontinuity. We let the PCR decoder
1200                          * handle that. */
1201                         p_es->p_pgrm->i_synchro_state = SYNCHRO_REINIT;
1202     
1203                         /* There also may be a continuity_counter
1204                          * discontinuity: resynchronize our counter with
1205                          * the one of the stream. */
1206                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
1207                     }
1208     
1209                     /* If this is a PCR_PID, and this TS packet contains a
1210                      * PCR, we pass it along to the PCR decoder. */
1211
1212                     if( !b_psi && (p_pgrm_demux->i_pcr_pid == i_pid)
1213                         && (p[5] & 0x10) )
1214                     {
1215                         /* There should be a PCR field in the packet, check
1216                          * if the adaptation field is long enough to carry
1217                          * it. */
1218                         if( p[4] >= 7 )
1219                         {
1220                             /* Read the PCR. */
1221                             mtime_t     pcr_time;
1222                             pcr_time = ( (mtime_t)p[6] << 25 ) |
1223                                        ( (mtime_t)p[7] << 17 ) |
1224                                        ( (mtime_t)p[8] << 9 ) |
1225                                        ( (mtime_t)p[9] << 1 ) |
1226                                        ( (mtime_t)p[10] >> 7 );
1227                             /* Call the pace control. */
1228                             input_ClockManageRef( p_input, p_es->p_pgrm,
1229                                                   pcr_time );
1230                         }
1231                     } /* PCR ? */
1232                 } /* valid TS adaptation field ? */
1233             } /* length > 0 */
1234         } /* has adaptation field */
1235         /* Check the continuity of the stream. */
1236         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1237         if( i_dummy == 1 )
1238         {
1239             /* Everything is ok, just increase our counter */
1240             (p_es_demux->i_continuity_counter)++;
1241         }
1242         else
1243         {
1244             if( !b_payload && i_dummy == 0 )
1245             {
1246                 /* This is a packet without payload, this is allowed by the
1247                  * draft. As there is nothing interesting in this packet
1248                  * (except PCR that have already been handled), we can trash
1249                  * the packet. */
1250                 intf_WarnMsg( 3, "input: packet without payload received "
1251                                  "by TS demux" );
1252                 b_trash = 1;
1253             }
1254             else if( i_dummy <= 0 )
1255             {
1256                 /* Duplicate packet: mark it as being to be trashed. */
1257                 intf_WarnMsg( 3, "input: duplicate packet received "
1258                                  "by TS demux" );
1259                 b_trash = 1;
1260             }
1261             else if( p_es_demux->i_continuity_counter == 0xFF )
1262             {
1263                 /* This means that the packet is the first one we receive for
1264                  * this ES since the continuity counter ranges between 0 and
1265                  * 0x0F excepts when it has been initialized by the input:
1266                  * init the counter to the correct value. */
1267                 intf_WarnMsg( 3, "input: first packet for PID %d received "
1268                              "by TS demux", p_es->i_id );
1269                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1270             }
1271             else
1272             {
1273                 /* This can indicate that we missed a packet or that the
1274                  * continuity_counter wrapped and we received a dup packet:
1275                  * as we don't know, do as if we missed a packet to be sure
1276                  * to recover from this situation */
1277                 intf_WarnMsg( 2, "input: packet lost by TS demux: "
1278                                  "current %d, packet %d",
1279                               p_es_demux->i_continuity_counter & 0x0f,
1280                               p[3] & 0x0f );
1281                 b_lost = 1;
1282                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1283             } /* not continuous */
1284         } /* continuity */
1285     } /* if selected or PCR */
1286     
1287     /* Trash the packet if it has no payload or if it isn't selected */
1288     if( b_trash )
1289     {
1290         input_DeletePacket( p_input->p_method_data, p_data );
1291         p_input->stream.c_packets_trashed++;
1292     }
1293     else
1294     {
1295         if( b_psi )
1296         {
1297             /* The payload contains PSI tables */
1298             input_DemuxPSI( p_input, p_data, p_es,
1299                             b_unit_start, b_lost );
1300
1301         }
1302         else
1303         {
1304             /* The payload carries a PES stream */
1305             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost ); 
1306         }
1307
1308     }
1309
1310 #undef p
1311
1312 }
1313
1314 /*
1315  * PSI demultiplexing and decoding
1316  */
1317
1318 /*****************************************************************************
1319  * DemuxPSI : makes up complete PSI data
1320  *****************************************************************************/
1321 void input_DemuxPSI( input_thread_t * p_input, data_packet_t * p_data, 
1322         es_descriptor_t * p_es, boolean_t b_unit_start, boolean_t b_lost )
1323 {
1324     es_ts_data_t  * p_demux_data;
1325     
1326     p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
1327
1328 #define p_psi (p_demux_data->p_psi_section)
1329 #define p (p_data->p_payload_start)
1330
1331     if( b_unit_start )
1332     {
1333         /* unit_start set to 1 -> presence of a pointer field
1334          * (see ISO/IEC 13818 (2.4.4.2) which should be set to 0x00 */
1335         if( (u8)p[0] != 0x00 )
1336         {
1337             intf_WarnMsg( 2, "input: non zero pointer field found, "
1338                              "trying to continue" );
1339             p+=(u8)p[0];
1340         }
1341         else
1342         {
1343             p++;
1344         }
1345
1346         /* This is the begining of a new section */
1347
1348         if( ((u8)(p[1]) & 0xc0) != 0x80 ) 
1349         {
1350             intf_WarnMsg( 2, "input: invalid PSI packet" );
1351             p_psi->b_trash = 1;
1352         }
1353         else 
1354         {
1355             p_psi->i_section_length = ((p[1] & 0xF) << 8) | p[2];
1356             p_psi->b_section_complete = 0;
1357             p_psi->i_read_in_section = 0;
1358             p_psi->i_section_number = (u8)p[6];
1359
1360             if( p_psi->b_is_complete || p_psi->i_section_number == 0 )
1361             {
1362                 /* This is a new PSI packet */
1363                 p_psi->b_is_complete = 0;
1364                 p_psi->b_trash = 0;
1365                 p_psi->i_version_number = ( p[5] >> 1 ) & 0x1f;
1366                 p_psi->i_last_section_number = (u8)p[7];
1367
1368                 /* We'll write at the begining of the buffer */
1369                 p_psi->p_current = p_psi->buffer;
1370             }
1371             else
1372             {
1373                 if( p_psi->b_section_complete )
1374                 {
1375                     /* New Section of an already started PSI */
1376                     p_psi->b_section_complete = 0;
1377                     
1378                     if( p_psi->i_version_number != (( p[5] >> 1 ) & 0x1f) )
1379                     {
1380                         intf_WarnMsg( 2, "input: PSI version differs "
1381                                          "inside same PAT" );
1382                         p_psi->b_trash = 1;
1383                     }
1384                     if( p_psi->i_section_number + 1 != (u8)p[6] )
1385                     {
1386                         intf_WarnMsg( 2, "input: PSI Section discontinuity, "
1387                                          "packet lost ?" );
1388                         p_psi->b_trash = 1;
1389                     }
1390                     else
1391                         p_psi->i_section_number++;
1392                 }
1393                 else
1394                 {
1395                     intf_WarnMsg( 2, "input: got unexpected new PSI section" );
1396                     p_psi->b_trash = 1;
1397                 }
1398             }
1399         }
1400     } /* b_unit_start */
1401     
1402     if( !p_psi->b_trash )
1403     {
1404         /* read */
1405         if( (p_data->p_payload_end - p) >=
1406             ( p_psi->i_section_length - p_psi->i_read_in_section ) )
1407         {
1408             /* The end of the section is in this TS packet */
1409             memcpy( p_psi->p_current, p, 
1410             (p_psi->i_section_length - p_psi->i_read_in_section) );
1411     
1412             p_psi->b_section_complete = 1;
1413             p_psi->p_current += 
1414                 (p_psi->i_section_length - p_psi->i_read_in_section);
1415                         
1416             if( p_psi->i_section_number == p_psi->i_last_section_number )
1417             {
1418                 /* This was the last section of PSI */
1419                 p_psi->b_is_complete = 1;
1420
1421                 switch( p_demux_data->i_psi_type)
1422                 {
1423                 case PSI_IS_PAT:
1424                     input_DecodePAT( p_input, p_es );
1425                     break;
1426                 case PSI_IS_PMT:
1427                     input_DecodePMT( p_input, p_es );
1428                     break;
1429                 default:
1430                     intf_WarnMsg(2, "Received unknown PSI in DemuxPSI");
1431                 }
1432             }
1433         }
1434         else
1435         {
1436             memcpy( p_psi->buffer, p, p_data->p_payload_end - p );
1437             p_psi->i_read_in_section += p_data->p_payload_end - p;
1438
1439             p_psi->p_current += p_data->p_payload_end - p;
1440         }
1441     }
1442
1443 #undef p_psi    
1444 #undef p
1445    
1446     input_DeletePacket( p_input->p_method_data, p_data );
1447     
1448     return ;
1449 }
1450
1451 /*****************************************************************************
1452  * DecodePAT : Decodes Programm association table and deal with it
1453  *****************************************************************************/
1454 static void input_DecodePAT( input_thread_t * p_input, es_descriptor_t * p_es )
1455 {
1456     stream_ts_data_t  * p_stream_data;
1457     es_ts_data_t      * p_demux_data;
1458
1459     pgrm_descriptor_t * p_pgrm;
1460     es_descriptor_t   * p_current_es;
1461     byte_t            * p_current_data;           
1462
1463     int                 i_section_length, i_program_id, i_pmt_pid;
1464     int                 i_loop, i_current_section;
1465
1466     boolean_t           b_changed = 0;
1467
1468     p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
1469     p_stream_data = (stream_ts_data_t *)p_input->stream.p_demux_data;
1470     
1471 #define p_psi (p_demux_data->p_psi_section)
1472
1473     /* Not so fast, Mike ! If the PAT version has changed, we first check
1474      * that its content has really changed before doing anything */
1475     if( p_stream_data->i_pat_version != p_psi->i_version_number )
1476     {
1477         int i_programs = p_input->stream.i_pgrm_number;
1478
1479         p_current_data = p_psi->buffer;
1480
1481         do
1482         {
1483             i_section_length = ((u32)(p_current_data[1] & 0xF) << 8) |
1484                                  p_current_data[2];
1485             i_current_section = (u8)p_current_data[6];
1486     
1487             for( i_loop = 0;
1488                  ( i_loop < (i_section_length - 9) / 4 ) && !b_changed;
1489                  i_loop++ )
1490             {
1491                 i_program_id = ( (u32)*(p_current_data + i_loop * 4 + 8) << 8 )
1492                                  | *(p_current_data + i_loop * 4 + 9);
1493                 i_pmt_pid = ( ((u32)*(p_current_data + i_loop * 4 + 10) & 0x1F)
1494                                     << 8 )
1495                                | *(p_current_data + i_loop * 4 + 11);
1496
1497                 if( i_program_id )
1498                 {
1499                     if( (p_pgrm = input_FindProgram( p_input, i_program_id ))
1500                         && (p_current_es = input_FindES( p_input, i_pmt_pid ))
1501                         && p_current_es->p_pgrm == p_pgrm
1502                         && p_current_es->i_id == i_pmt_pid
1503                         && ((es_ts_data_t *)p_current_es->p_demux_data)->b_psi
1504                         && ((es_ts_data_t *)p_current_es->p_demux_data)
1505                             ->i_psi_type == PSI_IS_PMT )
1506                     {
1507                         i_programs--;
1508                     }
1509                     else
1510                     {
1511                         b_changed = 1;
1512                     }
1513                 }
1514             }
1515             
1516             p_current_data += 3 + i_section_length;
1517
1518         } while( ( i_current_section < p_psi->i_last_section_number )
1519                   && !b_changed );
1520
1521         /* If we didn't find the expected amount of programs, the PAT has
1522          * changed. Otherwise, it only changed if b_changed is already != 0 */
1523         b_changed = b_changed || i_programs;
1524     }
1525
1526     if( b_changed )
1527     {
1528         /* PAT has changed. We are going to delete all programs and 
1529          * create new ones. We chose not to only change what was needed
1530          * as a PAT change may mean the stream is radically changing and
1531          * this is a secure method to avoid crashes */
1532         es_ts_data_t      * p_es_demux;
1533         pgrm_ts_data_t    * p_pgrm_demux;
1534         
1535         p_current_data = p_psi->buffer;
1536
1537         /* Delete all programs */
1538         while( p_input->stream.i_pgrm_number )
1539         {
1540             input_DelProgram( p_input, p_input->stream.pp_programs[0] );
1541         }
1542         
1543         do
1544         {
1545             i_section_length = ((u32)(p_current_data[1] & 0xF) << 8) |
1546                                  p_current_data[2];
1547             i_current_section = (u8)p_current_data[6];
1548     
1549             for( i_loop = 0; i_loop < (i_section_length - 9) / 4 ; i_loop++ )
1550             {
1551                 i_program_id = ( (u32)*(p_current_data + i_loop * 4 + 8) << 8 )
1552                                  | *(p_current_data + i_loop * 4 + 9);
1553                 i_pmt_pid = ( ((u32)*(p_current_data + i_loop * 4 + 10) & 0x1F)
1554                                     << 8 )
1555                                | *(p_current_data + i_loop * 4 + 11);
1556     
1557                 /* If program = 0, we're having info about NIT not PMT */
1558                 if( i_program_id )
1559                 {
1560                     /* Add this program */
1561                     p_pgrm = input_AddProgram( p_input, i_program_id, 
1562                                                sizeof( pgrm_ts_data_t ) );
1563                    
1564                     /* whatis the PID of the PMT of this program */
1565                     p_pgrm_demux = (pgrm_ts_data_t *)p_pgrm->p_demux_data;
1566                     p_pgrm_demux->i_pmt_version = PMT_UNINITIALIZED;
1567     
1568                     /* Add the PMT ES to this program */
1569                     p_current_es = input_AddES( p_input, p_pgrm,(u16)i_pmt_pid,
1570                                         sizeof( es_ts_data_t) );
1571                     p_es_demux = (es_ts_data_t *)p_current_es->p_demux_data;
1572                     p_es_demux->b_psi = 1;
1573                     p_es_demux->i_psi_type = PSI_IS_PMT;
1574                     
1575                     p_es_demux->p_psi_section = 
1576                                             malloc( sizeof( psi_section_t ) );
1577                     p_es_demux->p_psi_section->b_is_complete = 0;
1578                 }
1579             }
1580             
1581             p_current_data += 3 + i_section_length;
1582
1583         } while( i_current_section < p_psi->i_last_section_number );
1584
1585         /* Go to the beginning of the next section */
1586         p_stream_data->i_pat_version = p_psi->i_version_number;
1587
1588     }
1589 #undef p_psi    
1590
1591     /* FIXME This has nothing to do here */
1592     if( !p_input->stream.p_selected_program )
1593     {
1594         input_SetProgram( p_input, p_input->stream.pp_programs[0] );
1595     }
1596 }
1597
1598 /*****************************************************************************
1599  * DecodePMT : decode a given Program Stream Map
1600  * ***************************************************************************
1601  * When the PMT changes, it may mean a deep change in the stream, and it is
1602  * careful to delete the ES and add them again. If the PMT doesn't change,
1603  * there no need to do anything.
1604  *****************************************************************************/
1605 static void input_DecodePMT( input_thread_t * p_input, es_descriptor_t * p_es )
1606 {
1607
1608     pgrm_ts_data_t            * p_pgrm_data;
1609     es_ts_data_t              * p_demux_data;
1610
1611     p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
1612     p_pgrm_data = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data;
1613     
1614 #define p_psi (p_demux_data->p_psi_section)
1615
1616     if( p_psi->i_version_number != p_pgrm_data->i_pmt_version ) 
1617     {
1618         es_descriptor_t   * p_new_es;  
1619         es_ts_data_t      * p_es_demux;
1620         byte_t            * p_current_data, * p_current_section;
1621         int                 i_section_length,i_current_section;
1622         int                 i_prog_info_length, i_loop;
1623         int                 i_es_info_length, i_pid, i_stream_type;
1624         int                 i_audio_es, i_spu_es;
1625         int                 i_required_audio_es, i_required_spu_es;
1626         
1627         p_current_section = p_psi->buffer;
1628         p_current_data = p_psi->buffer;
1629
1630         p_pgrm_data->i_pcr_pid = ( ((u32)*(p_current_section + 8) & 0x1F) << 8 ) |
1631                                     *(p_current_section + 9);
1632
1633         i_audio_es = 0;
1634         i_spu_es = 0;
1635
1636         /* Lock stream information */
1637         vlc_mutex_lock( &p_input->stream.stream_lock );
1638
1639         /* Get the number of the required audio stream */
1640         if( p_main->b_audio )
1641         {
1642             /* Default is the first one */
1643             i_required_audio_es = config_GetIntVariable( "input_channel" );
1644             if( i_required_audio_es < 0 )
1645             {
1646                 i_required_audio_es = 1;
1647             }
1648         }
1649         else
1650         {
1651             i_required_audio_es = 0;
1652         }
1653
1654         /* Same thing for subtitles */
1655         if( p_main->b_video )
1656         {
1657             /* for spu, default is none */
1658             i_required_spu_es = config_GetIntVariable( "input_subtitle" );
1659             if( i_required_spu_es < 0 )
1660             {
1661                 i_required_spu_es = 0;
1662             }
1663         }
1664         else
1665         {
1666             i_required_spu_es = 0;
1667         }
1668         
1669         /* Delete all ES in this program  except the PSI. We start from the
1670          * end because i_es_number gets decremented after each deletion. */
1671         for( i_loop = p_es->p_pgrm->i_es_number ; i_loop ; )
1672         {
1673             i_loop--;
1674             p_es_demux = (es_ts_data_t *)
1675                          p_es->p_pgrm->pp_es[i_loop]->p_demux_data;
1676             if ( ! p_es_demux->b_psi )
1677             {
1678                 input_DelES( p_input, p_es->p_pgrm->pp_es[i_loop] );
1679             }
1680         }
1681
1682         /* Then add what we received in this PMT */
1683         do
1684         {
1685             i_section_length = ( ((u32)*(p_current_data + 1) & 0xF) << 8 ) |
1686                                   *(p_current_data + 2);
1687             i_current_section = (u8)p_current_data[6];
1688             i_prog_info_length = ( ((u32)*(p_current_data + 10) & 0xF) << 8 ) |
1689                                     *(p_current_data + 11);
1690
1691             /* For the moment we ignore program descriptors */
1692             p_current_data += 12 + i_prog_info_length;
1693     
1694             /* The end of the section, before the CRC is at 
1695              * p_current_section + i_section_length -1 */
1696             while( p_current_data < p_current_section + i_section_length -1 )
1697             {
1698                 i_stream_type = (int)p_current_data[0];
1699                 i_pid = ( ((u32)*(p_current_data + 1) & 0x1F) << 8 ) |
1700                            *(p_current_data + 2);
1701                 i_es_info_length = ( ((u32)*(p_current_data + 3) & 0xF) << 8 ) |
1702                                       *(p_current_data + 4);
1703                 
1704                 /* Add this ES to the program */
1705                 p_new_es = input_AddES( p_input, p_es->p_pgrm, 
1706                                         (u16)i_pid, sizeof( es_ts_data_t ) );
1707
1708                 /* Tell the decoders what kind of stream it is */
1709                 p_new_es->i_type = i_stream_type;
1710
1711                 /* Tell the interface what kind of stream it is and select 
1712                  * the required ones */
1713                 if ( p_input->stream.p_selected_program == p_new_es->p_pgrm )
1714                 {
1715                     switch( i_stream_type )
1716                     {
1717                         case MPEG1_VIDEO_ES:
1718                         case MPEG2_VIDEO_ES:
1719                             p_new_es->i_cat = VIDEO_ES;
1720                             input_SelectES( p_input, p_new_es );
1721                             break;
1722                         case MPEG1_AUDIO_ES:
1723                         case MPEG2_AUDIO_ES:
1724                             p_new_es->i_cat = AUDIO_ES;
1725                             i_audio_es += 1;
1726                             if( i_audio_es == i_required_audio_es )
1727                                 input_SelectES( p_input, p_new_es );
1728                             break;
1729                         case LPCM_AUDIO_ES :
1730                         case AC3_AUDIO_ES :
1731                             p_new_es->i_stream_id = 0xBD;
1732                             p_new_es->i_cat = AUDIO_ES;
1733                             i_audio_es += 1;
1734                             if( i_audio_es == i_required_audio_es )
1735                                 input_SelectES( p_input, p_new_es );
1736                             break;
1737                         /* Not sure this one is fully specification-compliant */
1738                         case DVD_SPU_ES :
1739                             p_new_es->i_stream_id = 0xBD;
1740                             p_new_es->i_cat = SPU_ES;
1741                             i_spu_es += 1;
1742                             if( i_spu_es == i_required_spu_es )
1743                                 input_SelectES( p_input, p_new_es );
1744                             break;
1745                         default :
1746                             p_new_es->i_cat = UNKNOWN_ES;
1747                             break;
1748                     }
1749                 }
1750                 
1751                 p_current_data += 5 + i_es_info_length;
1752             }
1753
1754             /* Go to the beginning of the next section*/
1755             p_current_data += 3 + i_section_length;
1756            
1757             p_current_section++;
1758             
1759         } while( i_current_section < p_psi->i_last_section_number );
1760
1761         if( i_required_audio_es > i_audio_es )
1762         {
1763             intf_WarnMsg( 2, "input: non-existing audio ES required" );
1764         }
1765         
1766         if( i_required_spu_es > i_spu_es )
1767         {
1768             intf_WarnMsg( 2, "input: non-existing subtitles ES required" );
1769         }
1770         
1771         p_pgrm_data->i_pmt_version = p_psi->i_version_number;
1772
1773         /* inform interface that stream has changed */
1774         p_input->stream.b_changed = 1;
1775         /*  Remove lock */
1776         vlc_mutex_unlock( &p_input->stream.stream_lock );
1777     }
1778     
1779 #undef p_psi
1780 }
1781