ALL : In order to make ac3 working in avi file, I've deplaced some code
[vlc.git] / 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.97 2002/05/27 16:01:42 fenrir 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  * PES Packet management
44  */
45
46 /*****************************************************************************
47  * MoveChunk
48  *****************************************************************************
49  * Small utility function used to parse discontinuous headers safely. Copies
50  * i_buf_len bytes of data to a buffer and returns the size copied.
51  * It also solves some alignment problems on non-IA-32, non-PPC processors.
52  * This is a variation on the theme of input_ext-dec.h:GetChunk().
53  *****************************************************************************/
54 static inline size_t MoveChunk( byte_t * p_dest, data_packet_t ** pp_data_src,
55                                 byte_t ** pp_src, size_t i_buf_len )
56 {
57     ptrdiff_t           i_available;
58
59     if( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
60             >= i_buf_len )
61     {
62         if( p_dest != NULL )
63             memcpy( p_dest, *pp_src, i_buf_len );
64         *pp_src += i_buf_len;
65         return( i_buf_len );
66     }
67     else
68     {
69         size_t          i_init_len = i_buf_len;
70
71         do
72         {
73             if( p_dest != NULL )
74                 memcpy( p_dest, *pp_src, i_available );
75             *pp_data_src = (*pp_data_src)->p_next;
76             i_buf_len -= i_available;
77             p_dest += i_available;
78             if( *pp_data_src == NULL )
79             {
80                 *pp_src = NULL;
81                 return( i_init_len - i_buf_len );
82             }
83             *pp_src = (*pp_data_src)->p_payload_start;
84         }
85         while( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
86                 <= i_buf_len );
87
88         if( i_buf_len )
89         {
90             if( p_dest != NULL )
91                 memcpy( p_dest, *pp_src, i_buf_len );
92             *pp_src += i_buf_len;
93         }
94         return( i_init_len );
95     }
96 }
97
98 /*****************************************************************************
99  * input_ParsePES
100  *****************************************************************************
101  * Parse a finished PES packet and analyze its header.
102  *****************************************************************************/
103 #define PES_HEADER_SIZE     7
104 void input_ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
105 {
106     data_packet_t * p_data;
107     byte_t *        p_byte;
108     byte_t          p_header[PES_HEADER_SIZE];
109     int             i_done;
110
111 #define p_pes (p_es->p_pes)
112
113     /* Parse the header. The header has a variable length, but in order
114      * to improve the algorithm, we will read the 14 bytes we may be
115      * interested in */
116     p_data = p_pes->p_first;
117     p_byte = p_data->p_payload_start;
118     i_done = 0;
119
120     if( MoveChunk( p_header, &p_data, &p_byte, PES_HEADER_SIZE )
121             != PES_HEADER_SIZE )
122     {
123         intf_WarnMsg( 1, "input: PES packet too short to have a header" );
124         input_DeletePES( p_input->p_method_data, p_pes );
125         p_pes = NULL;
126         return;
127     }
128
129     /* Get the PES size if defined */
130     p_es->i_pes_real_size = U16_AT(p_header + 4);
131     if( p_es->i_pes_real_size )
132     {
133         p_es->i_pes_real_size += 6;
134     }
135
136     /* First read the 6 header bytes common to all PES packets:
137      * use them to test the PES validity */
138     if( (p_header[0] || p_header[1] || (p_header[2] != 1)) )
139     {
140         /* packet_start_code_prefix != 0x000001 */
141         intf_ErrMsg( "input error: data loss, "
142                      "PES packet doesn't start with 0x000001" );
143         input_DeletePES( p_input->p_method_data, p_pes );
144         p_pes = NULL;
145     }
146     else
147     {
148         int i_pes_header_size, i_payload_size;
149
150         if ( p_es->i_pes_real_size &&
151              (p_es->i_pes_real_size != p_pes->i_pes_size) )
152         {
153             /* PES_packet_length is set and != total received payload */
154             /* Warn the decoder that the data may be corrupt. */
155             intf_WarnMsg( 1, "input: packet corrupted, "
156                              "PES sizes do not match" );
157         }
158
159         switch( p_es->i_stream_id )
160         {
161         case 0xBC:  /* Program stream map */
162         case 0xBE:  /* Padding */
163         case 0xBF:  /* Private stream 2 */
164         case 0xB0:  /* ECM */
165         case 0xB1:  /* EMM */
166         case 0xFF:  /* Program stream directory */
167         case 0xF2:  /* DSMCC stream */
168         case 0xF8:  /* ITU-T H.222.1 type E stream */
169             /* The payload begins immediately after the 6 bytes header, so
170              * we have finished with the parsing */
171             i_pes_header_size = 6;
172             break;
173
174         default:
175             if( (p_header[6] & 0xC0) == 0x80 )
176             {
177                 /* MPEG-2 : the PES header contains at least 3 more bytes. */
178                 size_t      i_max_len;
179                 boolean_t   b_has_pts, b_has_dts;
180                 byte_t      p_full_header[12];
181
182                 p_pes->b_data_alignment = p_header[6] & 0x04;
183
184                 i_max_len = MoveChunk( p_full_header, &p_data, &p_byte, 12 );
185                 if( i_max_len < 2 )
186                 {
187                     intf_WarnMsg( 1,
188                             "PES packet too short to have a MPEG-2 header" );
189                     input_DeletePES( p_input->p_method_data,
190                                             p_pes );
191                     p_pes = NULL;
192                     return;
193                 }
194
195                 b_has_pts = p_full_header[0] & 0x80;
196                 b_has_dts = p_full_header[0] & 0x40;
197                 i_pes_header_size = p_full_header[1] + 9;
198
199                 /* Now parse the optional header extensions */
200                 if( b_has_pts )
201                 {
202                     if( i_max_len < 7 )
203                     {
204                         intf_WarnMsg( 1,
205                             "PES packet too short to have a MPEG-2 header" );
206                         input_DeletePES( p_input->p_method_data,
207                                                 p_pes );
208                         p_pes = NULL;
209                         return;
210                     }
211                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
212                     ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
213                       ((mtime_t)(p_full_header[3]) << 22) |
214                       ((mtime_t)(p_full_header[4] & 0xFE) << 14) |
215                       ((mtime_t)p_full_header[5] << 7) |
216                       ((mtime_t)p_full_header[6] >> 1) ) );
217
218                     if( b_has_dts )
219                     {
220                         if( i_max_len < 12 )
221                         {
222                             intf_WarnMsg( 1,
223                               "PES packet too short to have a MPEG-2 header" );
224                             input_DeletePES( p_input->p_method_data,
225                                                     p_pes );
226                             p_pes = NULL;
227                             return;
228                         }
229                         p_pes->i_dts = input_ClockGetTS( p_input, p_es->p_pgrm,
230                         ( ((mtime_t)(p_full_header[7] & 0x0E) << 29) |
231                           (((mtime_t)U16_AT(p_full_header + 8) << 14)
232                                 - (1 << 14)) |
233                           ((mtime_t)U16_AT(p_full_header + 10) >> 1) ) );
234                     }
235                 }
236             }
237             else
238             {
239                 /* Probably MPEG-1 */
240                 boolean_t       b_has_pts, b_has_dts;
241
242                 i_pes_header_size = 6;
243                 p_data = p_pes->p_first;
244                 p_byte = p_data->p_payload_start;
245                 /* Cannot fail because the previous one succeeded. */
246                 MoveChunk( NULL, &p_data, &p_byte, 6 );
247
248                 while( *p_byte == 0xFF && i_pes_header_size < 23 )
249                 {
250                     i_pes_header_size++;
251                     if( MoveChunk( NULL, &p_data, &p_byte, 1 ) != 1 )
252                     {
253                         intf_WarnMsg( 1,
254                             "PES packet too short to have a MPEG-1 header" );
255                         input_DeletePES( p_input->p_method_data, p_pes );
256                         p_pes = NULL;
257                         return;
258                     }
259                 }
260                 if( i_pes_header_size == 23 )
261                 {
262                     intf_ErrMsg( "input error: too much MPEG-1 stuffing" );
263                     input_DeletePES( p_input->p_method_data, p_pes );
264                     p_pes = NULL;
265                     return;
266                 }
267
268                 if( (*p_byte & 0xC0) == 0x40 )
269                 {
270                     /* Don't ask why... --Meuuh */
271                     /* Erm... why ? --Sam */
272                     /* Well... According to the recommendation, it is for
273                      * STD_buffer_scale and STD_buffer_size. --Meuuh */
274                     i_pes_header_size += 2;
275                     if( MoveChunk( NULL, &p_data, &p_byte, 2 ) != 2 )
276                     {
277                         intf_WarnMsg( 1, "input: PES packet too short "
278                                          "to have a MPEG-1 header" );
279                         input_DeletePES( p_input->p_method_data, p_pes );
280                         p_pes = NULL;
281                         return;
282                     }
283                 }
284
285                 i_pes_header_size++;
286
287                 b_has_pts = *p_byte & 0x20;
288                 b_has_dts = *p_byte & 0x10;
289
290                 if( b_has_pts )
291                 {
292                     byte_t      p_ts[5];
293
294                     i_pes_header_size += 4;
295                     if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
296                     {
297                         intf_WarnMsg( 1, "input: PES packet too short "
298                                          "to have a MPEG-1 header" );
299                         input_DeletePES( p_input->p_method_data, p_pes );
300                         p_pes = NULL;
301                         return;
302                     }
303
304                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
305                        ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
306                          (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
307                          ((mtime_t)p_ts[3] << 7) |
308                          ((mtime_t)p_ts[4] >> 1) ) );
309
310                     if( b_has_dts )
311                     {
312                         i_pes_header_size += 5;
313                         if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
314                         {
315                             intf_WarnMsg( 1, "input: PES packet too short "
316                                              "to have a MPEG-1 header" );
317                             input_DeletePES( p_input->p_method_data,
318                                                     p_pes );
319                             p_pes = NULL;
320                             return;
321                         }
322
323                         p_pes->i_dts = input_ClockGetTS( p_input,
324                                                          p_es->p_pgrm,
325                             ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
326                               (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
327                               ((mtime_t)p_ts[3] << 7) |
328                               ((mtime_t)p_ts[4] >> 1) ) );
329                     }
330                 }
331             }
332
333             break;
334         }
335
336         if( p_es->i_stream_id == 0xbd )
337         {
338             /* With private stream 1, the first byte of the payload
339              * is a stream_private_id, so skip it. */
340             i_pes_header_size++;
341         }
342
343         if( p_es->i_type == AC3_AUDIO_ES )
344         {
345             /* With ac3 audio, we need to skip first 3 bytes */
346             i_pes_header_size += 3;
347         }
348
349         /* Now we've parsed the header, we just have to indicate in some
350          * specific data packets where the PES payload begins (renumber
351          * p_payload_start), so that the decoders can find the beginning
352          * of their data right out of the box. */
353         p_data = p_pes->p_first;
354         i_payload_size = p_data->p_payload_end
355                                  - p_data->p_payload_start;
356         while( i_pes_header_size > i_payload_size )
357         {
358             /* These packets are entirely filled by the PES header. */
359             i_pes_header_size -= i_payload_size;
360             p_data->p_payload_start = p_data->p_payload_end;
361             /* Go to the next data packet. */
362             if( (p_data = p_data->p_next) == NULL )
363             {
364                 intf_ErrMsg( "input error: PES header bigger than payload" );
365                 input_DeletePES( p_input->p_method_data, p_pes );
366                 p_pes = NULL;
367                 return;
368             }
369             i_payload_size = p_data->p_payload_end
370                                  - p_data->p_payload_start;
371         }
372         /* This last packet is partly header, partly payload. */
373         if( i_payload_size < i_pes_header_size )
374         {
375             intf_ErrMsg( "input error: PES header bigger than payload" );
376             input_DeletePES( p_input->p_method_data, p_pes );
377             p_pes = NULL;
378             return;
379         }
380         p_data->p_payload_start += i_pes_header_size;
381
382
383         /* Now we can eventually put the PES packet in the decoder's
384          * PES fifo */
385         if( p_es->p_decoder_fifo != NULL )
386         {
387             input_DecodePES( p_es->p_decoder_fifo, p_pes );
388         }
389         else
390         {
391             intf_ErrMsg( "input error: no fifo to receive PES %p "
392                          "(who wrote this damn code ?)", p_pes );
393             input_DeletePES( p_input->p_method_data, p_pes );
394         }
395         p_pes = NULL;
396     }
397 #undef p_pes
398
399 }
400
401 /*****************************************************************************
402  * input_GatherPES:
403  *****************************************************************************
404  * Gather a PES packet.
405  *****************************************************************************/
406 void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
407                       es_descriptor_t * p_es,
408                       boolean_t b_unit_start, boolean_t b_packet_lost )
409 {
410 #define p_pes (p_es->p_pes)
411
412     /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
413      * often an escape sequence in decoders, so that should make them wait
414      * for the next start code). */
415     if( b_packet_lost )
416     {
417         input_NullPacket( p_input, p_es );
418     }
419
420     if( b_unit_start && p_pes != NULL )
421     {
422         /* If the data packet contains the begining of a new PES packet, and
423          * if we were reassembling a PES packet, then the PES should be
424          * complete now, so parse its header and give it to the decoders. */
425         input_ParsePES( p_input, p_es );
426     }
427
428     if( !b_unit_start && p_pes == NULL )
429     {
430         /* Random access... */
431         input_DeletePacket( p_input->p_method_data, p_data );
432     }
433     else
434     {
435         if( b_unit_start )
436         {
437             /* If we are at the beginning of a new PES packet, we must fetch
438              * a new PES buffer to begin with the reassembly of this PES
439              * packet. This is also here that we can synchronize with the
440              * stream if we lost packets or if the decoder has just
441              * started. */
442             if( (p_pes = input_NewPES( p_input->p_method_data ) ) == NULL )
443             {
444                 intf_ErrMsg( "input error: out of memory" );
445                 p_input->b_error = 1;
446                 return;
447             }
448             p_pes->i_rate = p_input->stream.control.i_rate;
449             p_pes->p_first = p_data;
450             
451             /* If the PES header fits in the first data packet, we can
452              * already set p_gather->i_pes_real_size. */
453             if( p_data->p_payload_end - p_data->p_payload_start
454                     >= PES_HEADER_SIZE )
455             {
456                 p_es->i_pes_real_size = ((u16)p_data->p_payload_start[4] << 8)
457                                          + p_data->p_payload_start[5] + 6;
458             }
459             else
460             { 
461                 p_es->i_pes_real_size = 0;
462             } 
463         }
464         else
465         {
466             /* Update the relations between the data packets */
467             p_pes->p_last->p_next = p_data;
468         }
469
470         p_pes->p_last = p_data;
471         p_pes->i_nb_data++;
472
473         /* Size of the payload carried in the data packet */
474         p_pes->i_pes_size += (p_data->p_payload_end
475                                  - p_data->p_payload_start);
476     
477         /* We can check if the packet is finished */
478         if( p_pes->i_pes_size == p_es->i_pes_real_size )
479         {
480             /* The packet is finished, parse it */
481             input_ParsePES( p_input, p_es );
482         }
483     }
484 #undef p_pes
485 }
486
487
488 /*
489  * PS Demultiplexing
490  */
491
492 /*****************************************************************************
493  * GetID: Get the ID of a stream
494  *****************************************************************************/
495 static u16 GetID( data_packet_t * p_data )
496 {
497     u16         i_id;
498
499     i_id = p_data->p_demux_start[3];                            /* stream_id */
500     if( i_id == 0xBD )
501     {
502         /* FIXME : this is not valid if the header is split in multiple
503          * packets */
504         /* stream_private_id */
505         i_id |= p_data->p_demux_start[ 9 + p_data->p_demux_start[8] ] << 8;
506     }
507     return( i_id );
508 }
509
510 /*****************************************************************************
511  * DecodePSM: Decode the Program Stream Map information
512  *****************************************************************************
513  * FIXME : loads are not aligned in this function
514  *****************************************************************************/
515 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
516 {
517     stream_ps_data_t *  p_demux =
518                  (stream_ps_data_t *)p_input->stream.p_demux_data;
519     byte_t *            p_byte;
520     byte_t *            p_end;
521     int                 i;
522     int                 i_new_es_number = 0;
523
524     if( p_data->p_demux_start + 10 > p_data->p_payload_end )
525     {
526         intf_ErrMsg( "input error: PSM too short : packet corrupt" );
527         return;
528     }
529
530     if( p_demux->b_has_PSM
531         && p_demux->i_PSM_version == (p_data->p_demux_start[6] & 0x1F) )
532     {
533         /* Already got that one. */
534         return;
535     }
536
537     p_demux->b_has_PSM = 1;
538     p_demux->i_PSM_version = p_data->p_demux_start[6] & 0x1F;
539
540     /* Go to elementary_stream_map_length, jumping over
541      * program_stream_info. */
542     p_byte = p_data->p_demux_start + 10
543               + U16_AT(&p_data->p_demux_start[8]);
544     if( p_byte > p_data->p_payload_end )
545     {
546         intf_ErrMsg( "input error: PSM too short, packet corrupt" );
547         return;
548     }
549     /* This is the full size of the elementary_stream_map.
550      * 2 == elementary_stream_map_length
551      * Please note that CRC_32 is not included in the length. */
552     p_end = p_byte + 2 + U16_AT(p_byte);
553     p_byte += 2;
554     if( p_end > p_data->p_payload_end )
555     {
556         intf_ErrMsg( "input error: PSM too short, packet corrupt" );
557         return;
558     }
559
560     vlc_mutex_lock( &p_input->stream.stream_lock );
561
562     /* 4 == minimum useful size of a section */
563     while( p_byte + 4 <= p_end )
564     {
565         es_descriptor_t *   p_es = NULL;
566         u8                  i_stream_id = p_byte[1];
567         /* FIXME: there will be a problem with private streams... (same
568          * stream_id) */
569
570         /* Look for the ES in the ES table */
571         for( i = i_new_es_number;
572              i < p_input->stream.pp_programs[0]->i_es_number;
573              i++ )
574         {
575             if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
576                     == i_stream_id )
577             {
578                 p_es = p_input->stream.pp_programs[0]->pp_es[i];
579                 if( p_es->i_type != p_byte[0] )
580                 {
581                     input_DelES( p_input, p_es );
582                     p_es = NULL;
583                 }
584                 else
585                 {
586                     /* Move the ES to the beginning. */
587                     p_input->stream.pp_programs[0]->pp_es[i]
588                         = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
589                     p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
590                         = p_es;
591                     i_new_es_number++;
592                 }
593                 break;
594             }
595         }
596
597         /* The goal is to have all the ES we have just read in the
598          * beginning of the pp_es table, and all the others at the end,
599          * so that we can close them more easily at the end. */
600         if( p_es == NULL )
601         {
602             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
603                                 i_stream_id, 0 );
604             p_es->i_type = p_byte[0];
605             p_es->b_audio = ( p_es->i_type == MPEG1_AUDIO_ES
606                               || p_es->i_type == MPEG2_AUDIO_ES
607                               || p_es->i_type == AC3_AUDIO_ES
608                               || p_es->i_type == LPCM_AUDIO_ES
609                             );
610
611             /* input_AddES has inserted the new element at the end. */
612             p_input->stream.pp_programs[0]->pp_es[
613                 p_input->stream.pp_programs[0]->i_es_number ]
614                 = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
615             p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
616             i_new_es_number++;
617         }
618         p_byte += 4 + U16_AT(&p_byte[2]);
619     }
620
621     /* Un-select the streams that are no longer parts of the program. */
622     while( i_new_es_number < p_input->stream.pp_programs[0]->i_es_number )
623     {
624         /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
625          * list will be emptied starting from the end */
626         input_DelES( p_input,
627                      p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
628     }
629
630     if( p_main->b_stats )
631     {
632         intf_StatMsg( "input info: The stream map after the PSM is now :" );
633         input_DumpStream( p_input );
634     }
635
636     vlc_mutex_unlock( &p_input->stream.stream_lock );
637 }
638
639 /*****************************************************************************
640  * input_ReadPS: store a PS packet into a data_buffer_t
641  *****************************************************************************/
642 #define PEEK( SIZE )                                                        \
643     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
644     if( i_error == -1 )                                                     \
645     {                                                                       \
646         return( -1 );                                                       \
647     }                                                                       \
648     else if( i_error < SIZE )                                               \
649     {                                                                       \
650         /* EOF */                                                           \
651         return( 0 );                                                        \
652     }
653
654 ssize_t input_ReadPS( input_thread_t * p_input, data_packet_t ** pp_data )
655 {
656     byte_t *            p_peek;
657     size_t              i_packet_size;
658     ssize_t             i_error, i_read;
659
660     /* Read what we believe to be a packet header. */
661     PEEK( 4 );
662
663     if( p_peek[0] || p_peek[1] || p_peek[2] != 1 || p_peek[3] < 0xB9 )
664     {
665         if( p_peek[0] || p_peek[1] || p_peek[2] )
666         {
667             /* It is common for MPEG-1 streams to pad with zeros
668              * (although it is forbidden by the recommendation), so
669              * don't bother everybody in this case. */
670             intf_WarnMsg( 3, "input warning: garbage (0x%.2x%.2x%.2x%.2x)",
671                  p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
672         }
673
674         /* This is not the startcode of a packet. Read the stream
675          * until we find one. */
676         while( p_peek[0] || p_peek[1] || p_peek[2] != 1 || p_peek[3] < 0xB9 )
677         {
678             p_input->p_current_data++;
679             PEEK( 4 );
680             if( p_input->b_die ) return( -1 );
681         }
682         /* Packet found. */
683     }
684
685     /* 0x1B9 == SYSTEM_END_CODE, it is only 4 bytes long. */
686     if( p_peek[3] != 0xB9 )
687     {
688         /* The packet is at least 6 bytes long. */
689         PEEK( 6 );
690
691         if( p_peek[3] != 0xBA )
692         {
693             /* That's the case for all packets, except pack header. */
694             i_packet_size = (p_peek[4] << 8) | p_peek[5];
695         }
696         else
697         {
698             /* Pack header. */
699             if( (p_peek[4] & 0xC0) == 0x40 )
700             {
701                 /* MPEG-2 */
702                 i_packet_size = 8;
703             }
704             else if( (p_peek[4] & 0xF0) == 0x20 )
705             {
706                 /* MPEG-1 */
707                 i_packet_size = 6;
708             }
709             else
710             {
711                 intf_ErrMsg( "Unable to determine stream type" );
712                 return( -1 );
713             }
714         }
715     }
716     else
717     {
718         /* System End Code */
719         i_packet_size = -2;
720     }
721
722     /* Fetch a packet of the appropriate size. */
723     i_read = input_SplitBuffer( p_input, pp_data, i_packet_size + 6 );
724     if( i_read <= 0 )
725     {
726         return( i_read );
727     }
728
729     /* In MPEG-2 pack headers we still have to read stuffing bytes. */
730     if( ((*pp_data)->p_demux_start[3] == 0xBA) && (i_packet_size == 8) )
731     {
732         size_t i_stuffing = ((*pp_data)->p_demux_start[13] & 0x7);
733         /* Force refill of the input buffer - though we don't care
734          * about p_peek. Please note that this is unoptimized. */
735         PEEK( i_stuffing );
736         p_input->p_current_data += i_stuffing;
737     }
738
739     return( 1 );
740 }
741
742 #undef PEEK
743
744 /*****************************************************************************
745  * input_ParsePS: read the PS header
746  *****************************************************************************/
747 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
748                                  data_packet_t * p_data )
749 {
750     u32                 i_code;
751     es_descriptor_t *   p_es = NULL;
752
753     i_code = p_data->p_demux_start[3];
754
755     if( i_code > 0xBC ) /* ES start code */
756     {
757         u16                 i_id;
758         int                 i_dummy;
759
760         /* This is a PES packet. Find out if we want it or not. */
761         i_id = GetID( p_data );
762
763         vlc_mutex_lock( &p_input->stream.stream_lock );
764         if( p_input->stream.pp_programs[0]->b_is_ok )
765         {
766             /* Look only at the selected ES. */
767             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
768                  i_dummy++ )
769             {
770                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
771                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
772                 {
773                     p_es = p_input->stream.pp_selected_es[i_dummy];
774                     break;
775                 }
776             }
777         }
778         else
779         {
780             stream_ps_data_t * p_demux =
781               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
782
783             /* Search all ES ; if not found -> AddES */
784             p_es = input_FindES( p_input, i_id );
785
786             if( p_es == NULL && !p_demux->b_has_PSM )
787             {
788                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
789                                     i_id, 0 );
790                 if( p_es != NULL )
791                 {
792                     p_es->i_stream_id = p_data->p_demux_start[3];
793
794                     /* Set stream type and auto-spawn. */
795                     if( (i_id & 0xF0) == 0xE0 )
796                     {
797                         /* MPEG video */
798                         p_es->i_type = MPEG2_VIDEO_ES;
799                         p_es->i_cat = VIDEO_ES;
800 #ifdef AUTO_SPAWN
801                         if( !p_input->stream.b_seekable )
802                             input_SelectES( p_input, p_es );
803 #endif
804                     }
805                     else if( (i_id & 0xE0) == 0xC0 )
806                     {
807                         /* MPEG audio */
808                         p_es->i_type = MPEG2_AUDIO_ES;
809                         p_es->b_audio = 1;
810                         p_es->i_cat = AUDIO_ES;
811 #ifdef AUTO_SPAWN
812                         if( !p_input->stream.b_seekable )
813                         if( config_GetIntVariable( "audio-channel" )
814                                 == (p_es->i_id & 0x1F) ||
815                             ( config_GetIntVariable( "audio-channel" ) < 0
816                               && !(p_es->i_id & 0x1F) ) )
817                         switch( config_GetIntVariable( "audio-type" ) )
818                         {
819                         case -1:
820                         case REQUESTED_MPEG:
821                             input_SelectES( p_input, p_es );
822                         }
823 #endif
824                     }
825                     else if( (i_id & 0xF0FF) == 0x80BD )
826                     {
827                         /* AC3 audio (0x80->0x8F) */
828                         p_es->i_type = AC3_AUDIO_ES;
829                         p_es->b_audio = 1;
830                         p_es->i_cat = AUDIO_ES;
831 #ifdef AUTO_SPAWN
832                         if( !p_input->stream.b_seekable )
833                         if( config_GetIntVariable( "audio-channel" )
834                                 == ((p_es->i_id & 0xF00) >> 8) ||
835                             ( config_GetIntVariable( "audio-channel" ) < 0
836                               && !((p_es->i_id & 0xF00) >> 8)) )
837                         switch( config_GetIntVariable( "audio-type" ) )
838                         {
839                         case -1:
840                         case REQUESTED_AC3:
841                             input_SelectES( p_input, p_es );
842                         }
843 #endif
844                     }
845                     else if( (i_id & 0xE0FF) == 0x20BD )
846                     {
847                         /* Subtitles video (0x20->0x3F) */
848                         p_es->i_type = DVD_SPU_ES;
849                         p_es->i_cat = SPU_ES;
850 #ifdef AUTO_SPAWN
851                         if( config_GetIntVariable( "spu-channel" )
852                                 == ((p_es->i_id & 0x1F00) >> 8) )
853                         {
854                             if( !p_input->stream.b_seekable )
855                                 input_SelectES( p_input, p_es );
856                         }
857 #endif
858                     }
859                     else if( (i_id & 0xF0FF) == 0xA0BD )
860                     {
861                         /* LPCM audio (0xA0->0xAF) */
862                         p_es->i_type = LPCM_AUDIO_ES;
863                         p_es->b_audio = 1;
864                         p_es->i_cat = AUDIO_ES;
865                     }
866                     else
867                     {
868                         p_es->i_type = UNKNOWN_ES;
869                     }
870                 }
871
872                 /* Tell the interface the stream has changed */
873                 p_input->stream.b_changed = 1;
874             }
875         } /* stream.b_is_ok */
876         vlc_mutex_unlock( &p_input->stream.stream_lock );
877     } /* i_code > 0xBC */
878
879     return( p_es );
880 }
881
882 /*****************************************************************************
883  * input_DemuxPS: first step of demultiplexing: the PS header
884  *****************************************************************************/
885 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
886 {
887     u32                 i_code;
888     boolean_t           b_trash = 0;
889     es_descriptor_t *   p_es = NULL;
890
891     i_code = ((u32)p_data->p_demux_start[0] << 24)
892                 | ((u32)p_data->p_demux_start[1] << 16)
893                 | ((u32)p_data->p_demux_start[2] << 8)
894                 | p_data->p_demux_start[3];
895     if( i_code <= 0x1BC )
896     {
897         switch( i_code )
898         {
899         case 0x1BA: /* PACK_START_CODE */
900             {
901                 /* Read the SCR. */
902                 mtime_t         scr_time;
903                 u32             i_mux_rate;
904
905                 if( (p_data->p_demux_start[4] & 0xC0) == 0x40 )
906                 {
907                     /* MPEG-2 */
908                     byte_t      p_header[14];
909                     byte_t *    p_byte;
910                     p_byte = p_data->p_demux_start;
911
912                     if( MoveChunk( p_header, &p_data, &p_byte, 14 ) != 14 )
913                     {
914                         intf_WarnMsg( 1, "input: packet too short "
915                                          "to have a header" );
916                         b_trash = 1;
917                         break;
918                     }
919                     scr_time =
920                          ((mtime_t)(p_header[4] & 0x38) << 27) |
921                          ((mtime_t)(U32_AT(p_header + 4) & 0x03FFF800)
922                                         << 4) |
923                          ((( ((mtime_t)U16_AT(p_header + 6) << 16)
924                             | (mtime_t)U16_AT(p_header + 8) ) & 0x03FFF800)
925                                         >> 11);
926
927                     /* mux_rate */
928                     i_mux_rate = ((u32)U16_AT(p_header + 10) << 6)
929                                    | (p_header[12] >> 2);
930                     /* FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
931                      * This is the biggest kludge ever !
932                      * I don't know what's wrong with mux_rate calculation
933                      * but this heuristic work well : */
934                     i_mux_rate <<= 1;
935                     i_mux_rate /= 3;
936                 }
937                 else
938                 {
939                     /* MPEG-1 SCR is like PTS. */
940                     byte_t      p_header[12];
941                     byte_t *    p_byte;
942                     p_byte = p_data->p_demux_start;
943
944                     if( MoveChunk( p_header, &p_data, &p_byte, 12 ) != 12 )
945                     {
946                         intf_WarnMsg( 1, "input: packet too short "
947                                          "to have a header" );
948                         b_trash = 1;
949                         break;
950                     }
951                     scr_time =
952                          ((mtime_t)(p_header[4] & 0x0E) << 29) |
953                          (((mtime_t)U32_AT(p_header + 4) & 0xFFFE00) << 6) |
954                          ((mtime_t)p_header[7] << 7) |
955                          ((mtime_t)p_header[8] >> 1);
956
957                     /* mux_rate */
958                     i_mux_rate = (U32_AT(p_header + 8) & 0x7FFFFE) >> 1;
959                 }
960                 /* Call the pace control. */
961                 input_ClockManageRef( p_input,
962                                       p_input->stream.p_selected_program,
963                                       scr_time );
964
965                 if( i_mux_rate != p_input->stream.i_mux_rate
966                      && p_input->stream.i_mux_rate )
967                 {
968                     intf_WarnMsg( 2, "input: mux_rate changed, "
969                                      "expect cosmetic errors" );
970                 }
971                 p_input->stream.i_mux_rate = i_mux_rate;
972
973                 b_trash = 1;
974             }
975             break;
976
977         case 0x1BB: /* SYSTEM_START_CODE */
978             b_trash = 1;                              /* Nothing interesting */
979             break;
980
981         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
982             DecodePSM( p_input, p_data );
983             b_trash = 1;
984             break;
985     
986         case 0x1B9: /* PROGRAM_END_CODE */
987             b_trash = 1;
988             break;
989    
990         default:
991             /* This should not happen */
992             b_trash = 1;
993             intf_WarnMsg( 3, "input: unwanted packet received "
994                              "with start code 0x%.8x", i_code );
995         }
996     }
997     else
998     {
999         p_es = input_ParsePS( p_input, p_data );
1000
1001         vlc_mutex_lock( &p_input->stream.control.control_lock );
1002         if( p_es != NULL && p_es->p_decoder_fifo != NULL
1003              && (!p_es->b_audio || !p_input->stream.control.b_mute) )
1004         {
1005             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1006             p_es->c_packets++;
1007             input_GatherPES( p_input, p_data, p_es, 1, 0 );
1008         }
1009         else
1010         {
1011             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1012             b_trash = 1;
1013         }
1014     }
1015
1016     /* Trash the packet if it has no payload or if it isn't selected */
1017     if( b_trash )
1018     {
1019         input_DeletePacket( p_input->p_method_data, p_data );
1020         p_input->stream.c_packets_trashed++;
1021     }
1022 }
1023
1024  
1025 /*
1026  * TS Demultiplexing
1027  */
1028
1029 /*****************************************************************************
1030  * input_ReadTS: store a TS packet into a data_buffer_t
1031  *****************************************************************************/
1032 #define PEEK( SIZE )                                                        \
1033     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
1034     if( i_error == -1 )                                                     \
1035     {                                                                       \
1036         return( -1 );                                                       \
1037     }                                                                       \
1038     else if( i_error < SIZE )                                               \
1039     {                                                                       \
1040         /* EOF */                                                           \
1041         return( 0 );                                                        \
1042     }
1043
1044 ssize_t input_ReadTS( input_thread_t * p_input, data_packet_t ** pp_data )
1045 {
1046     byte_t *            p_peek;
1047     ssize_t             i_error, i_read;
1048
1049     PEEK( 1 );
1050
1051     if( *p_peek != TS_SYNC_CODE )
1052     {
1053         intf_WarnMsg( 3, "input warning: garbage at input (%x)", *p_peek );
1054
1055         if( p_input->i_mtu )
1056         {
1057             while( *p_peek != TS_SYNC_CODE )
1058             {
1059                 /* Try to resync on next packet. */
1060                 PEEK( TS_PACKET_SIZE );
1061                 p_input->p_current_data += TS_PACKET_SIZE;
1062                 PEEK( 1 );
1063             }
1064         }
1065         else
1066         {
1067             /* Move forward until we find 0x47 (and hope it's the good
1068              * one... FIXME) */
1069             while( *p_peek != TS_SYNC_CODE )
1070             {
1071                 p_input->p_current_data++;
1072                 PEEK( 1 );
1073             }
1074         }
1075     }
1076
1077     i_read = input_SplitBuffer( p_input, pp_data, TS_PACKET_SIZE );
1078     if( i_read <= 0 )
1079     {
1080         return( i_read );
1081     }
1082
1083     return( 1 );
1084 }
1085
1086 /*****************************************************************************
1087  * input_DemuxTS: first step of demultiplexing: the TS header
1088  *****************************************************************************/
1089 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data,
1090                         psi_callback_t pf_psi_callback )
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     boolean_t           b_pcr = 0;                   /* Does it have a PCR ? */
1101     es_descriptor_t *   p_es = NULL;
1102     es_ts_data_t *      p_es_demux = NULL;
1103     pgrm_ts_data_t *    p_pgrm_demux = NULL;
1104
1105 #define p (p_data->p_demux_start)
1106     /* Extract flags values from TS common header. */
1107     i_pid = ((p[1] & 0x1F) << 8) | p[2];
1108     b_unit_start = (p[1] & 0x40);
1109     b_adaptation = (p[3] & 0x20);
1110     b_payload = (p[3] & 0x10);
1111
1112     /* Find out the elementary stream. */
1113     vlc_mutex_lock( &p_input->stream.stream_lock );
1114     
1115     for( i_dummy = 0; i_dummy < p_input->stream.i_pgrm_number; i_dummy ++ )
1116     {
1117         if( (( pgrm_ts_data_t * ) p_input->stream.pp_programs[i_dummy]->
1118                     p_demux_data)->i_pcr_pid == i_pid )
1119         {
1120             b_pcr = 1;
1121             break;
1122         }
1123     }
1124             
1125     p_es= input_FindES( p_input, i_pid );
1126     
1127     if( (p_es != NULL) && (p_es->p_demux_data != NULL) )
1128     {
1129         p_es_demux = (es_ts_data_t *)p_es->p_demux_data;
1130         
1131         if( p_es_demux->b_psi )
1132         {
1133             b_psi = 1;
1134         }
1135         else
1136         {
1137             p_pgrm_demux = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data; 
1138         }
1139     }
1140
1141     vlc_mutex_lock( &p_input->stream.control.control_lock );
1142     if( ( p_es == NULL ) || (p_es->b_audio && p_input->stream.control.b_mute) )
1143     {
1144         /* Not selected. Just read the adaptation field for a PCR. */
1145         b_trash = 1;
1146     }
1147     else if( p_es->p_decoder_fifo == NULL && !b_psi )
1148     {
1149         b_trash = 1; 
1150     }
1151
1152     vlc_mutex_unlock( &p_input->stream.control.control_lock );
1153     vlc_mutex_unlock( &p_input->stream.stream_lock );
1154
1155
1156     /* Don't change the order of the tests : if b_psi then p_pgrm_demux 
1157      * may still be null. Who said it was ugly ?
1158      * I have written worse. --Meuuh */
1159     if( ( p_es  ) && 
1160         ((p_es->p_decoder_fifo != NULL) || b_psi || b_pcr ) )
1161     {
1162         p_es->c_packets++;
1163
1164         /* Extract adaptation field information if any */
1165
1166         if( !b_adaptation )
1167         {
1168             /* We don't have any adaptation_field, so payload starts
1169              * immediately after the 4 byte TS header */
1170             p_data->p_payload_start += 4;
1171         }
1172         else
1173         {
1174             /* p[4] is adaptation_field_length minus one */
1175             p_data->p_payload_start += 5 + p[4];
1176     
1177             /* The adaptation field can be limited to the
1178              * adaptation_field_length byte, so that there is nothing to do:
1179              * skip this possibility */
1180             if( p[4] )
1181             {
1182                 /* If the packet has both adaptation_field and payload,
1183                  * adaptation_field cannot be more than 182 bytes long; if
1184                  * there is only an adaptation_field, it must fill the next
1185                  * 183 bytes. */
1186                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1187                 {
1188                     intf_WarnMsg( 2,
1189                         "input: invalid TS adaptation field (%p)",
1190                         p_data );
1191                     p_data->b_discard_payload = 1;
1192                     p_es->c_invalid_packets++;
1193                 }
1194     
1195                 /* Now we are sure that the byte containing flags is present:
1196                  * read it */
1197                 else
1198                 {
1199                     /* discontinuity_indicator */
1200                     if( p[5] & 0x80 )
1201                     {
1202                         intf_WarnMsg( 2,
1203                             "input: discontinuity_indicator"
1204                             " encountered by TS demux (position read: %d,"
1205                             " saved: %d)",
1206                             p[5] & 0x80, p_es_demux->i_continuity_counter );
1207     
1208                         /* If the PID carries the PCR, there will be a system
1209                          * time-based discontinuity. We let the PCR decoder
1210                          * handle that. */
1211                         p_es->p_pgrm->i_synchro_state = SYNCHRO_REINIT;
1212     
1213                         /* There also may be a continuity_counter
1214                          * discontinuity: resynchronize our counter with
1215                          * the one of the stream. */
1216                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
1217                     }
1218     
1219                 } /* valid TS adaptation field ? */
1220             } /* length > 0 */
1221         } /* has adaptation field */
1222         /* Check the continuity of the stream. */
1223         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1224         if( i_dummy == 1 )
1225         {
1226             /* Everything is ok, just increase our counter */
1227             (p_es_demux->i_continuity_counter)++;
1228         }
1229         else
1230         {
1231             if( !b_payload && i_dummy == 0 )
1232             {
1233                 /* This is a packet without payload, this is allowed by the
1234                  * draft. As there is nothing interesting in this packet
1235                  * (except PCR that have already been handled), we can trash
1236                  * the packet. */
1237                 intf_WarnMsg( 3, "input: packet without payload received "
1238                                  "by TS demux" );
1239                 b_trash = 1;
1240             }
1241             else if( i_dummy <= 0 )
1242             {
1243                 /* Duplicate packet: mark it as being to be trashed. */
1244                 intf_WarnMsg( 3, "input: duplicate packet received "
1245                                  "by TS demux" );
1246                 b_trash = 1;
1247             }
1248             else if( p_es_demux->i_continuity_counter == 0xFF )
1249             {
1250                 /* This means that the packet is the first one we receive for
1251                  * this ES since the continuity counter ranges between 0 and
1252                  * 0x0F excepts when it has been initialized by the input:
1253                  * init the counter to the correct value. */
1254                 intf_WarnMsg( 3, "input: first packet for PID %d received "
1255                              "by TS demux", p_es->i_id );
1256                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1257             }
1258             else
1259             {
1260                 /* This can indicate that we missed a packet or that the
1261                  * continuity_counter wrapped and we received a dup packet:
1262                  * as we don't know, do as if we missed a packet to be sure
1263                  * to recover from this situation */
1264                 intf_WarnMsg( 2, "input: packet lost by TS demux: "
1265                                  "current %d, packet %d",
1266                               p_es_demux->i_continuity_counter & 0x0f,
1267                               p[3] & 0x0f );
1268                 b_lost = 1;
1269                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1270             } /* not continuous */
1271         } /* continuity */
1272     } /* if selected or PCR */
1273     
1274     /* Handle PCR */
1275     if( b_pcr && b_adaptation && (p[5] & 0x10) && p[4]>=7 )
1276     {
1277         /* Read the PCR. */
1278         mtime_t     pcr_time;
1279         pcr_time = ( (mtime_t)p[6] << 25 ) |
1280                    ( (mtime_t)p[7] << 17 ) |
1281                    ( (mtime_t)p[8] << 9 ) |
1282                    ( (mtime_t)p[9] << 1 ) |
1283                    ( (mtime_t)p[10] >> 7 );
1284         /* Call the pace control. */
1285         for( i_dummy = 0; i_dummy < p_input->stream.i_pgrm_number; 
1286                                 i_dummy ++ )
1287         {
1288             if( ( ( pgrm_ts_data_t * ) p_input->stream.pp_programs[i_dummy]->
1289                         p_demux_data )->i_pcr_pid == i_pid )
1290             {
1291                 input_ClockManageRef( p_input,
1292                     p_input->stream.pp_programs[i_dummy], pcr_time );
1293             }
1294         }
1295
1296     }
1297     
1298     /* Trash the packet if it has no payload or if it isn't selected */
1299     if( b_trash )
1300     {
1301         input_DeletePacket( p_input->p_method_data, p_data );
1302         p_input->stream.c_packets_trashed++;
1303     }
1304     else
1305     {
1306         if( b_psi )
1307         {
1308             /* The payload contains PSI tables */
1309             (* pf_psi_callback) ( p_input, p_data, p_es, b_unit_start );
1310         }
1311         else
1312         {
1313             /* The payload carries a PES stream */
1314             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost ); 
1315         }
1316
1317     }
1318
1319 #undef p
1320
1321 }