]> git.sesse.net Git - vlc/blob - src/input/mpeg_system.c
* Fixed my old stupid bug that disabled sound after having played the
[vlc] / src / input / mpeg_system.c
1 /*****************************************************************************
2  * mpeg_system.c: TS, PS and PES management
3  *****************************************************************************
4  * Copyright (C) 1998, 1999, 2000 VideoLAN
5  * $Id: mpeg_system.c,v 1.35 2001/02/12 07:52:40 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  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  * 
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include "defs.h"
31
32 #include <stdlib.h>
33
34 #include "config.h"
35 #include "common.h"
36 #include "threads.h"
37 #include "mtime.h"
38
39 #include "intf_msg.h"
40
41 #include "stream_control.h"
42 #include "input_ext-intf.h"
43 #include "input_ext-dec.h"
44
45 #include "input.h"
46 #include "mpeg_system.h"
47
48 #include "main.h"                           /* AC3/MPEG channel, SPU channel */
49
50 /*****************************************************************************
51  * Local prototypes
52  *****************************************************************************/
53
54
55 /*
56  * PES Packet management
57  */
58
59 /*****************************************************************************
60  * MoveChunk
61  *****************************************************************************
62  * Small utility function used to parse discontinuous headers safely. Copies
63  * i_buf_len bytes of data to a buffer and returns the size copied.
64  * This is a variation on the theme of input_ext-dec.h:GetChunk().
65  *****************************************************************************/
66 static __inline__ size_t MoveChunk( byte_t * p_dest,
67                                     data_packet_t ** pp_data_src,
68                                     byte_t ** pp_src,
69                                     size_t i_buf_len )
70 {
71     ptrdiff_t           i_available;
72
73     if( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
74             >= i_buf_len )
75     {
76         if( p_dest != NULL )
77             memcpy( p_dest, *pp_src, i_buf_len );
78         *pp_src += i_buf_len;
79         return( i_buf_len );
80     }
81     else
82     {
83         size_t          i_init_len = i_buf_len;
84
85         do
86         {
87             if( p_dest != NULL )
88                 memcpy( p_dest, *pp_src, i_available );
89             *pp_data_src = (*pp_data_src)->p_next;
90             i_buf_len -= i_available;
91             p_dest += i_available;
92             if( *pp_data_src == NULL )
93             {
94                 *pp_src = NULL;
95                 return( i_init_len - i_buf_len );
96             }
97             *pp_src = (*pp_data_src)->p_payload_start;
98         }
99         while( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
100                 <= i_buf_len );
101
102         if( i_buf_len )
103         {
104             if( p_dest != NULL )
105                 memcpy( p_dest, *pp_src, i_buf_len );
106             *pp_src += i_buf_len;
107         }
108         return( i_init_len );
109     }
110 }
111
112 /*****************************************************************************
113  * input_ParsePES
114  *****************************************************************************
115  * Parse a finished PES packet and analyze its header.
116  *****************************************************************************/
117 #define PES_HEADER_SIZE     7
118 void input_ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
119 {
120     data_packet_t * p_data;
121     byte_t *        p_byte;
122     byte_t          p_header[PES_HEADER_SIZE];
123     int             i_done;
124
125 #define p_pes (p_es->p_pes)
126
127     //intf_DbgMsg("End of PES packet %p", p_pes);
128
129     /* Parse the header. The header has a variable length, but in order
130      * to improve the algorithm, we will read the 14 bytes we may be
131      * interested in */
132     p_data = p_pes->p_first;
133     p_byte = p_data->p_payload_start;
134     i_done = 0;
135
136     if( MoveChunk( p_header, &p_data, &p_byte, PES_HEADER_SIZE )
137             != PES_HEADER_SIZE )
138     {
139         intf_WarnMsg( 3, "PES packet too short to have a header" );
140         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
141         p_pes = NULL;
142         return;
143     }
144
145     /* Get the PES size if defined */
146     p_es->i_pes_real_size = U16_AT(p_header + 4) + 6;
147
148     /* First read the 6 header bytes common to all PES packets:
149      * use them to test the PES validity */
150     if( (p_header[0] || p_header[1] || (p_header[2] != 1)) )
151     {
152         /* packet_start_code_prefix != 0x000001 */
153         intf_ErrMsg( "PES packet doesn't start with 0x000001 : data loss" );
154         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
155         p_pes = NULL;
156     }
157     else
158     {
159         int i_pes_header_size, i_payload_size;
160
161         if ( p_es->i_pes_real_size &&
162              (p_es->i_pes_real_size != p_pes->i_pes_size) )
163         {
164             /* PES_packet_length is set and != total received payload */
165             /* Warn the decoder that the data may be corrupt. */
166             intf_WarnMsg( 3, "PES sizes do not match : packet corrupted" );
167         }
168
169         switch( p_es->i_stream_id )
170         {
171         case 0xBC:  /* Program stream map */
172         case 0xBE:  /* Padding */
173         case 0xBF:  /* Private stream 2 */
174         case 0xB0:  /* ECM */
175         case 0xB1:  /* EMM */
176         case 0xFF:  /* Program stream directory */
177         case 0xF2:  /* DSMCC stream */
178         case 0xF8:  /* ITU-T H.222.1 type E stream */
179             /* The payload begins immediately after the 6 bytes header, so
180              * we have finished with the parsing */
181             i_pes_header_size = 6;
182             break;
183
184         default:
185             if( (p_header[6] & 0xC0) == 0x80 )
186             {
187                 /* MPEG-2 : the PES header contains at least 3 more bytes. */
188                 size_t      i_max_len;
189                 boolean_t   b_has_pts, b_has_dts;
190                 byte_t      p_full_header[12];
191
192                 p_pes->b_data_alignment = p_header[6] & 0x04;
193
194                 i_max_len = MoveChunk( p_full_header, &p_data, &p_byte, 12 );
195                 if( i_max_len < 2 )
196                 {
197                     intf_WarnMsg( 3,
198                             "PES packet too short to have a MPEG-2 header" );
199                     p_input->pf_delete_pes( p_input->p_method_data,
200                                             p_pes );
201                     p_pes = NULL;
202                     return;
203                 }
204
205                 b_has_pts = p_full_header[0] & 0x80;
206                 b_has_dts = p_full_header[0] & 0x40;
207                 i_pes_header_size = p_full_header[1] + 9;
208
209                 /* Now parse the optional header extensions */
210                 if( b_has_pts )
211                 {
212                     if( i_max_len < 7 )
213                     {
214                         intf_WarnMsg( 3,
215                             "PES packet too short to have a MPEG-2 header" );
216                         p_input->pf_delete_pes( p_input->p_method_data,
217                                                 p_pes );
218                         p_pes = NULL;
219                         return;
220                     }
221                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
222                     ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
223                       (((mtime_t)U16_AT(p_full_header + 3) << 14) - (1 << 14)) |
224                       ((mtime_t)U16_AT(p_full_header + 5) >> 1) ) );
225
226                     if( b_has_dts )
227                     {
228                         if( i_max_len < 12 )
229                         {
230                             intf_WarnMsg( 3,
231                               "PES packet too short to have a MPEG-2 header" );
232                             p_input->pf_delete_pes( p_input->p_method_data,
233                                                     p_pes );
234                             p_pes = NULL;
235                             return;
236                         }
237                         p_pes->i_dts = input_ClockGetTS( p_input, p_es->p_pgrm,
238                         ( ((mtime_t)(p_full_header[7] & 0x0E) << 29) |
239                           (((mtime_t)U16_AT(p_full_header + 8) << 14)
240                                 - (1 << 14)) |
241                           ((mtime_t)U16_AT(p_full_header + 10) >> 1) ) );
242                     }
243                 }
244             }
245             else
246             {
247                 /* Probably MPEG-1 */
248                 boolean_t       b_has_pts, b_has_dts;
249
250                 i_pes_header_size = 6;
251                 p_data = p_pes->p_first;
252                 p_byte = p_data->p_payload_start;
253                 /* Cannot fail because the previous one succeeded. */
254                 MoveChunk( NULL, &p_data, &p_byte, 6 );
255
256                 while( *p_byte == 0xFF && i_pes_header_size < 22 )
257                 {
258                     i_pes_header_size++;
259                     if( MoveChunk( NULL, &p_data, &p_byte, 1 ) != 1 )
260                     {
261                         intf_WarnMsg( 3,
262                             "PES packet too short to have a MPEG-1 header" );
263                         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
264                         p_pes = NULL;
265                         return;
266                     }
267                 }
268                 if( i_pes_header_size == 22 )
269                 {
270                     intf_ErrMsg( "Too much MPEG-1 stuffing" );
271                     p_input->pf_delete_pes( p_input->p_method_data, p_pes );
272                     p_pes = NULL;
273                     return;
274                 }
275
276                 if( (*p_byte & 0xC0) == 0x40 )
277                 {
278                     /* Don't ask why... --Meuuh */
279                     /* Erm... why ? --Sam */
280                     /* Well... According to the recommendation, it is for
281                      * STD_buffer_scale and STD_buffer_size. --Meuuh */
282                     i_pes_header_size += 2;
283                     if( MoveChunk( NULL, &p_data, &p_byte, 2 ) != 2 )
284                     {
285                         intf_WarnMsg( 3,
286                             "PES packet too short to have a MPEG-1 header" );
287                         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
288                         p_pes = NULL;
289                         return;
290                     }
291                 }
292
293                 i_pes_header_size++;
294
295                 b_has_pts = *p_byte & 0x20;
296                 b_has_dts = *p_byte & 0x10;
297
298                 if( b_has_pts )
299                 {
300                     byte_t      p_ts[5];
301
302                     i_pes_header_size += 4;
303                     if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
304                     {
305                         intf_WarnMsg( 3,
306                             "PES packet too short to have a MPEG-1 header" );
307                         p_input->pf_delete_pes( p_input->p_method_data, p_pes );
308                         p_pes = NULL;
309                         return;
310                     }
311
312                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
313                       ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
314                         (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
315                         ((mtime_t)U16_AT(p_ts + 3) >> 1) ) );
316
317                     if( b_has_dts )
318                     {
319                         i_pes_header_size += 5;
320                         if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
321                         {
322                             intf_WarnMsg( 3,
323                               "PES packet too short to have a MPEG-1 header" );
324                             p_input->pf_delete_pes( p_input->p_method_data,
325                                                     p_pes );
326                             p_pes = NULL;
327                             return;
328                         }
329
330                         p_pes->i_dts = input_ClockGetTS( p_input,
331                                                          p_es->p_pgrm,
332                             ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
333                               (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
334                               ((mtime_t)U16_AT(p_ts + 3) >> 1) ) );
335                     }
336                 }
337             }
338
339             break;
340         }
341
342         if( p_es->i_stream_id == 0xbd )
343         {
344             /* With private stream 1, the first byte of the payload
345              * is a stream_private_id, so skip it. */
346             i_pes_header_size++;
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( "PES header bigger than payload" );
365                 p_input->pf_delete_pes( 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( "PES header bigger than payload" );
376             p_input->pf_delete_pes( 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         /* Now we can eventually put the PES packet in the decoder's
383          * PES fifo */
384         if( p_es->p_decoder_fifo != NULL )
385         {
386             input_DecodePES( p_es->p_decoder_fifo, p_pes );
387         }
388         else
389         {
390             intf_ErrMsg("No fifo to receive PES %p (who wrote this damn code ?)",
391                         p_pes);
392             p_input->pf_delete_pes( p_input->p_method_data, p_pes );
393         }
394         p_pes = NULL;
395     }
396 #undef p_pes
397
398 }
399
400 /*****************************************************************************
401  * input_GatherPES:
402  *****************************************************************************
403  * Gather a PES packet.
404  *****************************************************************************/
405 void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
406                       es_descriptor_t * p_es,
407                       boolean_t b_unit_start, boolean_t b_packet_lost )
408 {
409 #define p_pes (p_es->p_pes)
410
411     //intf_DbgMsg("PES-demultiplexing %p (%p)", p_ts_packet, p_pes);
412
413     /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
414      * often an escape sequence in decoders, so that should make them wait
415      * for the next start code). */
416     if( b_packet_lost )
417     {
418         input_NullPacket( p_input, p_es );
419     }
420
421     if( b_unit_start && p_pes != NULL )
422     {
423         /* If the data packet contains the begining of a new PES packet, and
424          * if we were reassembling a PES packet, then the PES should be
425          * complete now, so parse its header and give it to the decoders. */
426         input_ParsePES( p_input, p_es );
427     }
428
429     if( !b_unit_start && p_pes == NULL )
430     {
431         /* Random access... */
432         p_input->pf_delete_packet( p_input->p_method_data, p_data );
433     }
434     else
435     {
436         if( b_unit_start )
437         {
438             /* If we are at the beginning of a new PES packet, we must fetch
439              * a new PES buffer to begin with the reassembly of this PES
440              * packet. This is also here that we can synchronize with the
441              * stream if we lost packets or if the decoder has just
442              * started. */
443             if( (p_pes = p_input->pf_new_pes( p_input->p_method_data ) ) == NULL )
444             {
445                 intf_ErrMsg("Out of memory");
446                 p_input->b_error = 1;
447                 return;
448             }
449             p_pes->i_rate = p_input->stream.control.i_rate;
450             p_pes->p_first = p_data;
451
452             /* If the PES header fits in the first data packet, we can
453              * already set p_gather->i_pes_real_size. */
454             if( p_data->p_payload_end - p_data->p_payload_start
455                     >= PES_HEADER_SIZE )
456             {
457                 p_es->i_pes_real_size =
458                                 U16_AT(p_data->p_payload_start + 4) + 6;
459             }
460             else
461             {
462                 p_es->i_pes_real_size = 0;
463             }
464         }
465         else
466         {
467             /* Update the relations between the data packets */
468             p_es->p_last->p_next = p_data;
469         }
470
471         p_es->p_last = p_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_buffer[3];                                 /* stream_id */
500     if( i_id == 0xBD )
501     {
502         /* stream_private_id */
503         i_id |= p_data->p_buffer[ 9 + p_data->p_buffer[8] ] << 8;
504     }
505     return( i_id );
506 }
507
508 /*****************************************************************************
509  * DecodePSM: Decode the Program Stream Map information
510  *****************************************************************************/
511 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
512 {
513     stream_ps_data_t *  p_demux =
514                  (stream_ps_data_t *)p_input->stream.p_demux_data;
515     byte_t *            p_byte;
516     byte_t *            p_end;
517     int                 i;
518     int                 i_new_es_number = 0;
519
520     intf_Msg("input info: Your stream contains Program Stream Map information");
521     intf_Msg("input info: Please send a mail to <massiot@via.ecp.fr>");
522
523     if( p_data->p_payload_start + 10 > p_data->p_payload_end )
524     {
525         intf_ErrMsg( "PSM too short : packet corrupt" );
526         return;
527     }
528
529     if( p_demux->b_has_PSM
530         && p_demux->i_PSM_version == (p_data->p_buffer[6] & 0x1F) )
531     {
532         /* Already got that one. */
533         return;
534     }
535
536     intf_DbgMsg( "Building PSM" );
537     p_demux->b_has_PSM = 1;
538     p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;
539
540     /* Go to elementary_stream_map_length, jumping over
541      * program_stream_info. */
542     p_byte = p_data->p_payload_start + 10
543               + U16_AT(&p_data->p_payload_start[8]);
544     if( p_byte > p_data->p_payload_end )
545     {
546         intf_ErrMsg( "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( "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     for( i = i_new_es_number;
623          i < p_input->stream.pp_programs[0]->i_es_number;
624          i++ )
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 #ifdef STATS
633     intf_Msg( "input info: The stream map after the PSM is now :" );
634     input_DumpStream( p_input );
635 #endif
636
637     vlc_mutex_unlock( &p_input->stream.stream_lock );
638 }
639
640 /*****************************************************************************
641  * input_ParsePS: read the PS header
642  *****************************************************************************/
643 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
644                                  data_packet_t * p_data )
645 {
646     u32                 i_code;
647     es_descriptor_t *   p_es = NULL;
648
649     i_code = U32_AT( p_data->p_buffer );
650     if( i_code > 0x1BC ) /* ES start code */
651     {
652         u16                 i_id;
653         int                 i_dummy;
654
655         /* This is a PES packet. Find out if we want it or not. */
656         i_id = GetID( p_data );
657
658         vlc_mutex_lock( &p_input->stream.stream_lock );
659         if( p_input->stream.pp_programs[0]->b_is_ok )
660         {
661             /* Look only at the selected ES. */
662             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
663                  i_dummy++ )
664             {
665                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
666                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
667                 {
668                     p_es = p_input->stream.pp_selected_es[i_dummy];
669                     break;
670                 }
671             }
672         }
673         else
674         {
675             stream_ps_data_t * p_demux =
676               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
677
678             /* Search all ES ; if not found -> AddES */
679             p_es = input_FindES( p_input, i_id );
680
681             if( p_es == NULL && !p_demux->b_has_PSM )
682             {
683                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
684                                     i_id, 0 );
685                 if( p_es != NULL )
686                 {
687                     p_es->i_stream_id = p_data->p_buffer[3];
688
689                     /* Set stream type and auto-spawn. */
690                     if( (i_id & 0xF0) == 0xE0 )
691                     {
692                         /* MPEG video */
693                         p_es->i_type = MPEG2_VIDEO_ES;
694 #ifdef AUTO_SPAWN
695                         if( !p_input->stream.b_seekable )
696                             input_SelectES( p_input, p_es );
697 #endif
698                     }
699                     else if( (i_id & 0xE0) == 0xC0 )
700                     {
701                         /* MPEG audio */
702                         p_es->i_type = MPEG2_AUDIO_ES;
703                         p_es->b_audio = 1;
704 #ifdef AUTO_SPAWN
705                         if( !p_input->stream.b_seekable )
706                         if( main_GetIntVariable( INPUT_CHANNEL_VAR, 0 )
707                                 == (p_es->i_id & 0x1F) )
708                         switch( main_GetIntVariable( INPUT_AUDIO_VAR, 0 ) )
709                         {
710                         case 0:
711                             main_PutIntVariable( INPUT_CHANNEL_VAR,
712                                                  REQUESTED_MPEG );
713                         case REQUESTED_MPEG:
714                             input_SelectES( p_input, p_es );
715                         }
716 #endif
717                     }
718                     else if( (i_id & 0xF0FF) == 0x80BD )
719                     {
720                         /* AC3 audio (0x80->0x8F) */
721                         p_es->i_type = AC3_AUDIO_ES;
722                         p_es->b_audio = 1;
723 #ifdef AUTO_SPAWN
724                         if( !p_input->stream.b_seekable )
725                         if( main_GetIntVariable( INPUT_CHANNEL_VAR, 0 )
726                                 == ((p_es->i_id & 0xF00) >> 8) )
727                         switch( main_GetIntVariable( INPUT_AUDIO_VAR, 0 ) )
728                         {
729                         case 0:
730                             main_PutIntVariable( INPUT_CHANNEL_VAR,
731                                                  REQUESTED_AC3 );
732                         case REQUESTED_AC3:
733                             input_SelectES( p_input, p_es );
734                         }
735 #endif
736                     }
737                     else if( (i_id & 0xE0FF) == 0x20BD )
738                     {
739                         /* Subtitles video (0x20->0x3F) */
740                         p_es->i_type = DVD_SPU_ES;
741 #ifdef AUTO_SPAWN
742                         if( main_GetIntVariable( INPUT_SUBTITLE_VAR, -1 )
743                                 == ((p_es->i_id & 0x1F00) >> 8) )
744                         {
745                             if( !p_input->stream.b_seekable )
746                                 input_SelectES( p_input, p_es );
747                         }
748 #endif
749                     }
750                     else if( (i_id & 0xF0FF) == 0xA0BD )
751                     {
752                         /* LPCM audio (0xA0->0xAF) */
753                         p_es->i_type = LPCM_AUDIO_ES;
754                         p_es->b_audio = 1;
755                         /* FIXME : write the decoder */
756                     }
757                     else
758                     {
759                         p_es->i_type = UNKNOWN_ES;
760                     }
761                 }
762             }
763         } /* stream.b_is_ok */
764         vlc_mutex_unlock( &p_input->stream.stream_lock );
765     } /* i_code > 0xBC */
766
767     return( p_es );
768 }
769
770 /*****************************************************************************
771  * input_DemuxPS: first step of demultiplexing: the PS header
772  *****************************************************************************/
773 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
774 {
775     u32                 i_code;
776     boolean_t           b_trash = 0;
777     es_descriptor_t *   p_es = NULL;
778
779     i_code = U32_AT( p_data->p_buffer );
780     if( i_code <= 0x1BC )
781     {
782         switch( i_code )
783         {
784         case 0x1BA: /* PACK_START_CODE */
785             {
786                 /* Read the SCR. */
787                 mtime_t         scr_time;
788
789                 if( (p_data->p_buffer[4] & 0xC0) == 0x40 )
790                 {
791                     /* MPEG-2 */
792                     scr_time =
793                          ((mtime_t)(p_data->p_buffer[4] & 0x38) << 27) |
794                          ((mtime_t)(U32_AT(p_data->p_buffer + 4) & 0x03FFF800)
795                                         << 4) |
796                          ((mtime_t)(U32_AT(p_data->p_buffer + 6) & 0x03FFF800)
797                                         >> 11);
798                 }
799                 else
800                 {
801                     /* MPEG-1 SCR is like PTS. */
802                     scr_time =
803                          ((mtime_t)(p_data->p_buffer[4] & 0x0E) << 29) |
804                          (((mtime_t)U16_AT(p_data->p_buffer + 5) << 14)
805                            - (1 << 14)) |
806                          ((mtime_t)U16_AT(p_data->p_buffer + 7) >> 1);
807                 }
808                 /* Call the pace control. */
809                 //intf_Msg("+%lld", scr_time);
810                 input_ClockManageRef( p_input, p_input->stream.pp_programs[0],
811                                       scr_time );
812                 b_trash = 1;
813             }
814             break;
815
816         case 0x1BB: /* SYSTEM_START_CODE */
817             b_trash = 1;                              /* Nothing interesting */
818             break;
819
820         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
821             DecodePSM( p_input, p_data );
822             b_trash = 1;
823             break;
824     
825         case 0x1B9: /* PROGRAM_END_CODE */
826             b_trash = 1;
827             break;
828    
829         default:
830             /* This should not happen */
831             b_trash = 1;
832             intf_WarnMsg( 1, "Unwanted packet received with start code %x",
833                           i_code );
834         }
835     }
836     else
837     {
838         p_es = input_ParsePS( p_input, p_data );
839
840         vlc_mutex_lock( &p_input->stream.control.control_lock );
841         if( p_es != NULL && p_es->p_decoder_fifo != NULL
842              && (!p_es->b_audio || !p_input->stream.control.b_mute) )
843         {
844             vlc_mutex_unlock( &p_input->stream.control.control_lock );
845 #ifdef STATS
846             p_es->c_packets++;
847 #endif
848             input_GatherPES( p_input, p_data, p_es, 1, 0 );
849         }
850         else
851         {
852             vlc_mutex_unlock( &p_input->stream.control.control_lock );
853             b_trash = 1;
854         }
855     }
856
857     /* Trash the packet if it has no payload or if it isn't selected */
858     if( b_trash )
859     {
860         p_input->pf_delete_packet( p_input->p_method_data, p_data );
861 #ifdef STATS
862         p_input->c_packets_trashed++;
863 #endif
864     }
865 }
866
867
868 /*
869  * TS Demultiplexing
870  */
871
872 /*****************************************************************************
873  * input_DemuxTS: first step of demultiplexing: the TS header
874  *****************************************************************************/
875 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
876 {
877     int                 i_pid, i_dummy;
878     boolean_t           b_adaptation;         /* Adaptation field is present */
879     boolean_t           b_payload;                 /* Packet carries payload */
880     boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
881     boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
882     boolean_t           b_lost = 0;             /* Was there a packet loss ? */
883     es_descriptor_t *   p_es = NULL;
884     es_ts_data_t *      p_es_demux = NULL;
885     pgrm_ts_data_t *    p_pgrm_demux = NULL;
886
887 #define p (p_data->p_buffer)
888
889     //intf_DbgMsg("input debug: TS-demultiplexing packet %p, pid %d",
890     //            p_ts_packet, U16_AT(&p[1]) & 0x1fff);
891
892     /* Extract flags values from TS common header. */
893     i_pid = U16_AT(&p[1]) & 0x1fff;
894     b_unit_start = (p[1] & 0x40);
895     b_adaptation = (p[3] & 0x20);
896     b_payload = (p[3] & 0x10);
897
898     /* Find out the elementary stream. */
899     vlc_mutex_lock( &p_input->stream.stream_lock );
900     p_es = input_FindES( p_input, i_pid );
901
902     vlc_mutex_lock( &p_input->stream.control.control_lock );
903     if( p_es == NULL || p_es->p_decoder_fifo == NULL
904          || (p_es->b_audio && p_input->stream.control.b_mute) )
905     {
906         /* Not selected. Just read the adaptation field for a PCR. */
907         b_trash = 1;
908     }
909     vlc_mutex_unlock( &p_input->stream.control.control_lock );
910     vlc_mutex_unlock( &p_input->stream.stream_lock );
911
912     if( (p_es->p_decoder_fifo != NULL) || (p_pgrm_demux->i_pcr_pid == i_pid) )
913     {
914 #ifdef STATS
915         p_es->c_packets++;
916 #endif
917
918         /* Extract adaptation field information if any */
919         if( !b_adaptation )
920         {
921             /* We don't have any adaptation_field, so payload starts
922              * immediately after the 4 byte TS header */
923             p_data->p_payload_start += 4;
924         }
925         else
926         {
927             /* p[4] is adaptation_field_length minus one */
928             p_data->p_payload_start += 5 + p[4];
929     
930             /* The adaptation field can be limited to the
931              * adaptation_field_length byte, so that there is nothing to do:
932              * skip this possibility */
933             if( p[4] )
934             {
935                 /* If the packet has both adaptation_field and payload,
936                  * adaptation_field cannot be more than 182 bytes long; if
937                  * there is only an adaptation_field, it must fill the next
938                  * 183 bytes. */
939                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
940                 {
941                     intf_WarnMsg( 2,
942                         "invalid TS adaptation field (%p)",
943                         p_data );
944                     p_data->b_discard_payload = 1;
945 #ifdef STATS
946                     p_es->c_invalid_packets++;
947 #endif
948                 }
949     
950                 /* Now we are sure that the byte containing flags is present:
951                  * read it */
952                 else
953                 {
954                     /* discontinuity_indicator */
955                     if( p[5] & 0x80 )
956                     {
957                         intf_WarnMsg( 2,
958                             "discontinuity_indicator"
959                             " encountered by TS demux (position read: %d,"
960                             " saved: %d)",
961                             p[5] & 0x80, p_es_demux->i_continuity_counter );
962     
963                         /* If the PID carries the PCR, there will be a system
964                          * time-based discontinuity. We let the PCR decoder
965                          * handle that. */
966                         p_es->p_pgrm->i_synchro_state = SYNCHRO_REINIT;
967     
968                         /* There also may be a continuity_counter
969                          * discontinuity: resynchronise our counter with
970                          * the one of the stream. */
971                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
972                     }
973     
974                     /* If this is a PCR_PID, and this TS packet contains a
975                      * PCR, we pass it along to the PCR decoder. */
976                     if( (p_pgrm_demux->i_pcr_pid == i_pid) && (p[5] & 0x10) )
977                     {
978                         /* There should be a PCR field in the packet, check
979                          * if the adaptation field is long enough to carry
980                          * it. */
981                         if( p[4] >= 7 )
982                         {
983                             /* Read the PCR. */
984                             mtime_t     pcr_time;
985                             pcr_time =
986                                     ( (mtime_t)U32_AT((u32*)&p[6]) << 1 )
987                                       | ( p[10] >> 7 );
988                             /* Call the pace control. */
989                             input_ClockManageRef( p_input, p_es->p_pgrm,
990                                                   pcr_time );
991                         }
992                     } /* PCR ? */
993                 } /* valid TS adaptation field ? */
994             } /* length > 0 */
995         } /* has adaptation field */
996     
997         /* Check the continuity of the stream. */
998         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
999         if( i_dummy == 1 )
1000         {
1001             /* Everything is ok, just increase our counter */
1002             p_es_demux->i_continuity_counter++;
1003         }
1004         else
1005         {
1006             if( !b_payload && i_dummy == 0 )
1007             {
1008                 /* This is a packet without payload, this is allowed by the
1009                  * draft. As there is nothing interesting in this packet
1010                  * (except PCR that have already been handled), we can trash
1011                  * the packet. */
1012                 intf_WarnMsg( 1,
1013                               "Packet without payload received by TS demux" );
1014                 b_trash = 1;
1015             }
1016             else if( i_dummy <= 0 )
1017             {
1018                 /* FIXME: this can never happen, can it ? --Meuuh */
1019                 /* Duplicate packet: mark it as being to be trashed. */
1020                 intf_WarnMsg( 1, "Duplicate packet received by TS demux" );
1021                 b_trash = 1;
1022             }
1023             else if( p_es_demux->i_continuity_counter == 0xFF )
1024             {
1025                 /* This means that the packet is the first one we receive for
1026                  * this ES since the continuity counter ranges between 0 and
1027                  * 0x0F excepts when it has been initialized by the input:
1028                  * init the counter to the correct value. */
1029                 intf_DbgMsg( "First packet for PID %d received by TS demux",
1030                              p_es->i_id );
1031                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1032             }
1033             else
1034             {
1035                 /* This can indicate that we missed a packet or that the
1036                  * continuity_counter wrapped and we received a dup packet:
1037                  * as we don't know, do as if we missed a packet to be sure
1038                  * to recover from this situation */
1039                 intf_WarnMsg( 2,
1040                            "Packet lost by TS demux: current %d, packet %d",
1041                            p_es_demux->i_continuity_counter & 0x0f,
1042                            p[3] & 0x0f );
1043                 b_lost = 1;
1044                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1045             } /* not continuous */
1046         } /* continuity */
1047     } /* if selected or PCR */
1048
1049     /* Trash the packet if it has no payload or if it isn't selected */
1050     if( b_trash )
1051     {
1052         p_input->pf_delete_packet( p_input, p_data );
1053 #ifdef STATS
1054         p_input->c_packets_trashed++;
1055 #endif
1056     }
1057     else
1058     {
1059         if( p_es_demux->b_psi )
1060         {
1061             /* The payload contains PSI tables */
1062 #if 0
1063             /* FIXME ! write the PSI decoder :p */
1064             input_DemuxPSI( p_input, p_data, p_es,
1065                             b_unit_start, b_lost );
1066 #endif
1067         }
1068         else
1069         {
1070             /* The payload carries a PES stream */
1071             if( b_unit_start )
1072             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
1073         }
1074     }
1075
1076 #undef p
1077 }