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