]> git.sesse.net Git - vlc/blob - src/input/mpeg_system.c
-New method using netlist to read packets on DVD device by sectors of
[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.31 2001/02/08 01:34:42 stef 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->p_plugin->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->p_plugin->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->p_plugin->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->p_plugin->pf_delete_pes(
215                                                       p_input->p_method_data,
216                                                       p_pes );
217                         p_pes = NULL;
218                         return;
219                     }
220                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
221                     ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
222                       (((mtime_t)U16_AT(p_full_header + 3) << 14) - (1 << 14)) |
223                       ((mtime_t)U16_AT(p_full_header + 5) >> 1) ) );
224
225                     if( b_has_dts )
226                     {
227                         if( i_max_len < 12 )
228                         {
229                             intf_WarnMsg( 3,
230                               "PES packet too short to have a MPEG-2 header" );
231                             p_input->p_plugin->pf_delete_pes(
232                                     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->p_plugin->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->p_plugin->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->p_plugin->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->p_plugin->pf_delete_pes(
308                                             p_input->p_method_data, p_pes );
309                         p_pes = NULL;
310                         return;
311                     }
312
313                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
314                       ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
315                         (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
316                         ((mtime_t)U16_AT(p_ts + 3) >> 1) ) );
317
318                     if( b_has_dts )
319                     {
320                         i_pes_header_size += 5;
321                         if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
322                         {
323                             intf_WarnMsg( 3,
324                               "PES packet too short to have a MPEG-1 header" );
325                             p_input->p_plugin->pf_delete_pes(
326                                     p_input->p_method_data, p_pes );
327                             p_pes = NULL;
328                             return;
329                         }
330
331                         p_pes->i_dts = input_ClockGetTS( p_input,
332                                                          p_es->p_pgrm,
333                             ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
334                               (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
335                               ((mtime_t)U16_AT(p_ts + 3) >> 1) ) );
336                     }
337                 }
338             }
339
340             break;
341         }
342
343         if( p_es->i_stream_id == 0xbd )
344         {
345             /* With private stream 1, the first byte of the payload
346              * is a stream_private_id, so skip it. */
347             i_pes_header_size++;
348         }
349
350         /* Now we've parsed the header, we just have to indicate in some
351          * specific data packets where the PES payload begins (renumber
352          * p_payload_start), so that the decoders can find the beginning
353          * of their data right out of the box. */
354         p_data = p_pes->p_first;
355         i_payload_size = p_data->p_payload_end
356                                  - p_data->p_payload_start;
357         while( i_pes_header_size > i_payload_size )
358         {
359             /* These packets are entirely filled by the PES header. */
360             i_pes_header_size -= i_payload_size;
361             p_data->p_payload_start = p_data->p_payload_end;
362             /* Go to the next data packet. */
363             if( (p_data = p_data->p_next) == NULL )
364             {
365                 intf_ErrMsg( "PES header bigger than payload" );
366                 p_input->p_plugin->pf_delete_pes( p_input->p_method_data,
367                                                   p_pes );
368                 p_pes = NULL;
369                 return;
370             }
371             i_payload_size = p_data->p_payload_end
372                                  - p_data->p_payload_start;
373         }
374         /* This last packet is partly header, partly payload. */
375         if( i_payload_size < i_pes_header_size )
376         {
377             intf_ErrMsg( "PES header bigger than payload" );
378             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
379             p_pes = NULL;
380             return;
381         }
382         p_data->p_payload_start += i_pes_header_size;
383
384         /* Now we can eventually put the PES packet in the decoder's
385          * PES fifo */
386         if( p_es->p_decoder_fifo != NULL )
387         {
388             input_DecodePES( p_es->p_decoder_fifo, p_pes );
389         }
390         else
391         {
392             intf_ErrMsg("No fifo to receive PES %p (who wrote this damn code ?)",
393                         p_pes);
394             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
395         }
396         p_pes = NULL;
397     }
398 #undef p_pes
399
400 }
401
402 /*****************************************************************************
403  * input_GatherPES:
404  *****************************************************************************
405  * Gather a PES packet.
406  *****************************************************************************/
407 void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
408                       es_descriptor_t * p_es,
409                       boolean_t b_unit_start, boolean_t b_packet_lost )
410 {
411 #define p_pes (p_es->p_pes)
412
413     //intf_DbgMsg("PES-demultiplexing %p (%p)", p_ts_packet, p_pes);
414
415     /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
416      * often an escape sequence in decoders, so that should make them wait
417      * for the next start code). */
418     if( b_packet_lost || p_es->b_discontinuity )
419     {
420         input_NullPacket( p_input, p_es );
421     }
422
423     if( b_unit_start && p_pes != NULL )
424     {
425         /* If the data packet contains the begining of a new PES packet, and
426          * if we were reassembling a PES packet, then the PES should be
427          * complete now, so parse its header and give it to the decoders. */
428         input_ParsePES( p_input, p_es );
429     }
430
431     if( !b_unit_start && p_pes == NULL )
432     {
433         /* Random access... */
434         p_input->p_plugin->pf_delete_packet( p_input->p_method_data, p_data );
435     }
436     else
437     {
438         if( b_unit_start )
439         {
440             /* If we are at the beginning of a new PES packet, we must fetch
441              * a new PES buffer to begin with the reassembly of this PES
442              * packet. This is also here that we can synchronize with the
443              * stream if we lost packets or if the decoder has just
444              * started. */
445             if( (p_pes = p_input->p_plugin->pf_new_pes( p_input->p_method_data ) ) == NULL )
446             {
447                 intf_ErrMsg("Out of memory");
448                 p_input->b_error = 1;
449                 return;
450             }
451             p_pes->i_rate = p_input->stream.control.i_rate;
452             p_pes->p_first = p_data;
453
454             /* If the PES header fits in the first data packet, we can
455              * already set p_gather->i_pes_real_size. */
456             if( p_data->p_payload_end - p_data->p_payload_start
457                     >= PES_HEADER_SIZE )
458             {
459                 p_es->i_pes_real_size =
460                                 U16_AT(p_data->p_payload_start + 4) + 6;
461             }
462             else
463             {
464                 p_es->i_pes_real_size = 0;
465             }
466         }
467         else
468         {
469             /* Update the relations between the data packets */
470             p_es->p_last->p_next = p_data;
471         }
472
473         p_es->p_last = p_data;
474
475         /* Size of the payload carried in the data packet */
476         p_pes->i_pes_size += (p_data->p_payload_end
477                                  - p_data->p_payload_start);
478     
479         /* We can check if the packet is finished */
480         if( p_pes->i_pes_size == p_es->i_pes_real_size )
481         {
482             /* The packet is finished, parse it */
483             input_ParsePES( p_input, p_es );
484         }
485     }
486 #undef p_pes
487 }
488
489
490 /*
491  * PS Demultiplexing
492  */
493
494 /*****************************************************************************
495  * GetID: Get the ID of a stream
496  *****************************************************************************/
497 static u16 GetID( data_packet_t * p_data )
498 {
499     u16         i_id;
500
501     i_id = p_data->p_buffer[3];                                 /* stream_id */
502     if( i_id == 0xBD )
503     {
504         /* stream_private_id */
505         i_id |= p_data->p_buffer[ 9 + p_data->p_buffer[8] ] << 8;
506     }
507     return( i_id );
508 }
509
510 /*****************************************************************************
511  * DecodePSM: Decode the Program Stream Map information
512  *****************************************************************************/
513 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
514 {
515     stream_ps_data_t *  p_demux =
516                  (stream_ps_data_t *)p_input->stream.p_demux_data;
517     byte_t *            p_byte;
518     byte_t *            p_end;
519     int                 i;
520     int                 i_new_es_number = 0;
521
522     intf_Msg("input info: Your stream contains Program Stream Map information");
523     intf_Msg("input info: Please send a mail to <massiot@via.ecp.fr>");
524
525     if( p_data->p_payload_start + 10 > p_data->p_payload_end )
526     {
527         intf_ErrMsg( "PSM too short : packet corrupt" );
528         return;
529     }
530
531     if( p_demux->b_has_PSM
532         && p_demux->i_PSM_version == (p_data->p_buffer[6] & 0x1F) )
533     {
534         /* Already got that one. */
535         return;
536     }
537
538     intf_DbgMsg( "Building PSM" );
539     p_demux->b_has_PSM = 1;
540     p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;
541
542     /* Go to elementary_stream_map_length, jumping over
543      * program_stream_info. */
544     p_byte = p_data->p_payload_start + 10
545               + U16_AT(&p_data->p_payload_start[8]);
546     if( p_byte > p_data->p_payload_end )
547     {
548         intf_ErrMsg( "PSM too short : packet corrupt" );
549         return;
550     }
551     /* This is the full size of the elementary_stream_map.
552      * 2 == elementary_stream_map_length
553      * Please note that CRC_32 is not included in the length. */
554     p_end = p_byte + 2 + U16_AT(p_byte);
555     p_byte += 2;
556     if( p_end > p_data->p_payload_end )
557     {
558         intf_ErrMsg( "PSM too short : packet corrupt" );
559         return;
560     }
561
562     vlc_mutex_lock( &p_input->stream.stream_lock );
563
564     /* 4 == minimum useful size of a section */
565     while( p_byte + 4 <= p_end )
566     {
567         es_descriptor_t *   p_es = NULL;
568         u8                  i_stream_id = p_byte[1];
569         /* FIXME: there will be a problem with private streams... (same
570          * stream_id) */
571
572         /* Look for the ES in the ES table */
573         for( i = i_new_es_number;
574              i < p_input->stream.pp_programs[0]->i_es_number;
575              i++ )
576         {
577             if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
578                     == i_stream_id )
579             {
580                 p_es = p_input->stream.pp_programs[0]->pp_es[i];
581                 if( p_es->i_type != p_byte[0] )
582                 {
583                     input_DelES( p_input, p_es );
584                     p_es = NULL;
585                 }
586                 else
587                 {
588                     /* Move the ES to the beginning. */
589                     p_input->stream.pp_programs[0]->pp_es[i]
590                         = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
591                     p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
592                         = p_es;
593                     i_new_es_number++;
594                 }
595                 break;
596             }
597         }
598
599         /* The goal is to have all the ES we have just read in the
600          * beginning of the pp_es table, and all the others at the end,
601          * so that we can close them more easily at the end. */
602         if( p_es == NULL )
603         {
604             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
605                                 i_stream_id, 0 );
606             p_es->i_type = p_byte[0];
607             p_es->b_audio = ( p_es->i_type == MPEG1_AUDIO_ES
608                               || p_es->i_type == MPEG2_AUDIO_ES
609                               || p_es->i_type == AC3_AUDIO_ES
610                               || p_es->i_type == LPCM_AUDIO_ES
611                             );
612
613             /* input_AddES has inserted the new element at the end. */
614             p_input->stream.pp_programs[0]->pp_es[
615                 p_input->stream.pp_programs[0]->i_es_number ]
616                 = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
617             p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
618             i_new_es_number++;
619         }
620         p_byte += 4 + U16_AT(&p_byte[2]);
621     }
622
623     /* Un-select the streams that are no longer parts of the program. */
624     for( i = i_new_es_number;
625          i < p_input->stream.pp_programs[0]->i_es_number;
626          i++ )
627     {
628         /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
629          * list will be emptied starting from the end */
630         input_DelES( p_input,
631                      p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
632     }
633
634 #ifdef STATS
635     intf_Msg( "input info: The stream map after the PSM is now :" );
636     input_DumpStream( p_input );
637 #endif
638
639     vlc_mutex_unlock( &p_input->stream.stream_lock );
640 }
641
642 /*****************************************************************************
643  * input_ParsePS: read the PS header
644  *****************************************************************************/
645 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
646                                  data_packet_t * p_data )
647 {
648     u32                 i_code;
649     es_descriptor_t *   p_es = NULL;
650
651     i_code = U32_AT( p_data->p_buffer );
652     if( i_code > 0x1BC ) /* ES start code */
653     {
654         u16                 i_id;
655         int                 i_dummy;
656
657         /* This is a PES packet. Find out if we want it or not. */
658         i_id = GetID( p_data );
659
660         vlc_mutex_lock( &p_input->stream.stream_lock );
661         if( p_input->stream.pp_programs[0]->b_is_ok )
662         {
663             /* Look only at the selected ES. */
664             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
665                  i_dummy++ )
666             {
667                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
668                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
669                 {
670                     p_es = p_input->stream.pp_selected_es[i_dummy];
671                     break;
672                 }
673             }
674         }
675         else
676         {
677             stream_ps_data_t * p_demux =
678               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
679
680             /* Search all ES ; if not found -> AddES */
681             p_es = input_FindES( p_input, i_id );
682
683             if( p_es == NULL && !p_demux->b_has_PSM )
684             {
685                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
686                                     i_id, 0 );
687                 if( p_es != NULL )
688                 {
689                     p_es->i_stream_id = p_data->p_buffer[3];
690
691                     /* Set stream type and auto-spawn. */
692                     if( (i_id & 0xF0) == 0xE0 )
693                     {
694                         /* MPEG video */
695                         p_es->i_type = MPEG2_VIDEO_ES;
696 #ifdef AUTO_SPAWN
697                         if( !p_input->stream.b_seekable )
698                             input_SelectES( p_input, p_es );
699 #endif
700                     }
701                     else if( (i_id & 0xE0) == 0xC0 )
702                     {
703                         /* MPEG audio */
704                         p_es->i_type = MPEG2_AUDIO_ES;
705                         p_es->b_audio = 1;
706 #ifdef AUTO_SPAWN
707                         if( !p_input->stream.b_seekable )
708                         if( main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
709                                 == (p_es->i_id & 0x1F) )
710                         switch( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 ) )
711                         {
712                         case 0:
713                             main_PutIntVariable( INPUT_DVD_CHANNEL_VAR,
714                                                  REQUESTED_MPEG );
715                         case REQUESTED_MPEG:
716                             input_SelectES( p_input, p_es );
717                         }
718 #endif
719                     }
720                     else if( (i_id & 0xF0FF) == 0x80BD )
721                     {
722                         /* AC3 audio (0x80->0x8F) */
723                         p_es->i_type = AC3_AUDIO_ES;
724                         p_es->b_audio = 1;
725 #ifdef AUTO_SPAWN
726                         if( !p_input->stream.b_seekable )
727                         if( main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
728                                 == ((p_es->i_id & 0xF00) >> 8) )
729                         switch( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 ) )
730                         {
731                         case 0:
732                             main_PutIntVariable( INPUT_DVD_CHANNEL_VAR,
733                                                  REQUESTED_AC3 );
734                         case REQUESTED_AC3:
735                             input_SelectES( p_input, p_es );
736                         }
737 #endif
738                     }
739                     else if( (i_id & 0xE0FF) == 0x20BD )
740                     {
741                         /* Subtitles video (0x20->0x3F) */
742                         p_es->i_type = DVD_SPU_ES;
743 #ifdef AUTO_SPAWN
744                         if( main_GetIntVariable( INPUT_DVD_SUBTITLE_VAR, -1 )
745                                 == ((p_es->i_id & 0x1F00) >> 8) )
746                         {
747                             if( !p_input->stream.b_seekable )
748                                 input_SelectES( p_input, p_es );
749                         }
750 #endif
751                     }
752                     else if( (i_id & 0xF0FF) == 0xA0BD )
753                     {
754                         /* LPCM audio (0xA0->0xAF) */
755                         p_es->i_type = LPCM_AUDIO_ES;
756                         p_es->b_audio = 1;
757                         /* FIXME : write the decoder */
758                     }
759                     else
760                     {
761                         p_es->i_type = UNKNOWN_ES;
762                     }
763                 }
764             }
765         } /* stream.b_is_ok */
766         vlc_mutex_unlock( &p_input->stream.stream_lock );
767     } /* i_code > 0xBC */
768
769     return( p_es );
770 }
771
772 /*****************************************************************************
773  * input_DemuxPS: first step of demultiplexing: the PS header
774  *****************************************************************************/
775 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
776 {
777     u32                 i_code;
778     boolean_t           b_trash = 0;
779     es_descriptor_t *   p_es = NULL;
780
781     i_code = U32_AT( p_data->p_buffer );
782     if( i_code <= 0x1BC )
783     {
784         switch( i_code )
785         {
786         case 0x1BA: /* PACK_START_CODE */
787             {
788                 /* Read the SCR. */
789                 mtime_t         scr_time;
790
791                 if( (p_data->p_buffer[4] & 0xC0) == 0x40 )
792                 {
793                     /* MPEG-2 */
794                     scr_time =
795                          ((mtime_t)(p_data->p_buffer[4] & 0x38) << 27) |
796                          ((mtime_t)(U32_AT(p_data->p_buffer + 4) & 0x03FFF800)
797                                         << 4) |
798                          ((mtime_t)(U32_AT(p_data->p_buffer + 6) & 0x03FFF800)
799                                         >> 11);
800                 }
801                 else
802                 {
803                     /* MPEG-1 SCR is like PTS. */
804                     scr_time =
805                          ((mtime_t)(p_data->p_buffer[4] & 0x0E) << 29) |
806                          (((mtime_t)U16_AT(p_data->p_buffer + 5) << 14)
807                            - (1 << 14)) |
808                          ((mtime_t)U16_AT(p_data->p_buffer + 7) >> 1);
809                 }
810                 /* Call the pace control. */
811                 //intf_Msg("+%lld", scr_time);
812                 input_ClockManageRef( p_input, p_input->stream.pp_programs[0],
813                                       scr_time );
814                 b_trash = 1;
815             }
816             break;
817
818         case 0x1BB: /* SYSTEM_START_CODE */
819             b_trash = 1;                              /* Nothing interesting */
820             break;
821
822         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
823             DecodePSM( p_input, p_data );
824             b_trash = 1;
825             break;
826     
827         case 0x1B9: /* PROGRAM_END_CODE */
828             b_trash = 1;
829             break;
830    
831         default:
832             /* This should not happen */
833             b_trash = 1;
834             intf_WarnMsg( 1, "Unwanted packet received with start code %x",
835                           i_code );
836         }
837     }
838     else
839     {
840         p_es = input_ParsePS( p_input, p_data );
841
842         vlc_mutex_lock( &p_input->stream.control.control_lock );
843         if( p_es != NULL && p_es->p_decoder_fifo != NULL
844              && (!p_es->b_audio || !p_input->stream.control.b_mute) )
845         {
846             vlc_mutex_unlock( &p_input->stream.control.control_lock );
847 #ifdef STATS
848             p_es->c_packets++;
849 #endif
850             input_GatherPES( p_input, p_data, p_es, 1, 0 );
851         }
852         else
853         {
854             vlc_mutex_unlock( &p_input->stream.control.control_lock );
855             b_trash = 1;
856         }
857     }
858
859     /* Trash the packet if it has no payload or if it isn't selected */
860     if( b_trash )
861     {
862         p_input->p_plugin->pf_delete_packet( p_input->p_method_data, p_data );
863 #ifdef STATS
864         p_input->c_packets_trashed++;
865 #endif
866     }
867 }
868
869
870 /*
871  * TS Demultiplexing
872  */
873
874 /*****************************************************************************
875  * input_DemuxTS: first step of demultiplexing: the TS header
876  *****************************************************************************/
877 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
878 {
879     int                 i_pid, i_dummy;
880     boolean_t           b_adaptation;         /* Adaptation field is present */
881     boolean_t           b_payload;                 /* Packet carries payload */
882     boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
883     boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
884     boolean_t           b_lost = 0;             /* Was there a packet loss ? */
885     es_descriptor_t *   p_es = NULL;
886     es_ts_data_t *      p_es_demux = NULL;
887     pgrm_ts_data_t *    p_pgrm_demux = NULL;
888
889 #define p (p_data->p_buffer)
890
891     //intf_DbgMsg("input debug: TS-demultiplexing packet %p, pid %d",
892     //            p_ts_packet, U16_AT(&p[1]) & 0x1fff);
893
894     /* Extract flags values from TS common header. */
895     i_pid = U16_AT(&p[1]) & 0x1fff;
896     b_unit_start = (p[1] & 0x40);
897     b_adaptation = (p[3] & 0x20);
898     b_payload = (p[3] & 0x10);
899
900     /* Find out the elementary stream. */
901     vlc_mutex_lock( &p_input->stream.stream_lock );
902     p_es = input_FindES( p_input, i_pid );
903
904     vlc_mutex_lock( &p_input->stream.control.control_lock );
905     if( p_es == NULL || p_es->p_decoder_fifo == NULL
906          || (p_es->b_audio && p_input->stream.control.b_mute) )
907     {
908         /* Not selected. Just read the adaptation field for a PCR. */
909         b_trash = 1;
910     }
911     vlc_mutex_unlock( &p_input->stream.control.control_lock );
912     vlc_mutex_unlock( &p_input->stream.stream_lock );
913
914     if( (p_es->p_decoder_fifo != NULL) || (p_pgrm_demux->i_pcr_pid == i_pid) )
915     {
916 #ifdef STATS
917         p_es->c_packets++;
918 #endif
919
920         /* Extract adaptation field information if any */
921         if( !b_adaptation )
922         {
923             /* We don't have any adaptation_field, so payload starts
924              * immediately after the 4 byte TS header */
925             p_data->p_payload_start += 4;
926         }
927         else
928         {
929             /* p[4] is adaptation_field_length minus one */
930             p_data->p_payload_start += 5 + p[4];
931     
932             /* The adaptation field can be limited to the
933              * adaptation_field_length byte, so that there is nothing to do:
934              * skip this possibility */
935             if( p[4] )
936             {
937                 /* If the packet has both adaptation_field and payload,
938                  * adaptation_field cannot be more than 182 bytes long; if
939                  * there is only an adaptation_field, it must fill the next
940                  * 183 bytes. */
941                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
942                 {
943                     intf_WarnMsg( 2,
944                         "invalid TS adaptation field (%p)",
945                         p_data );
946                     p_data->b_discard_payload = 1;
947 #ifdef STATS
948                     p_es->c_invalid_packets++;
949 #endif
950                 }
951     
952                 /* Now we are sure that the byte containing flags is present:
953                  * read it */
954                 else
955                 {
956                     /* discontinuity_indicator */
957                     if( p[5] & 0x80 )
958                     {
959                         intf_WarnMsg( 2,
960                             "discontinuity_indicator"
961                             " encountered by TS demux (position read: %d,"
962                             " saved: %d)",
963                             p[5] & 0x80, p_es_demux->i_continuity_counter );
964     
965                         /* If the PID carries the PCR, there will be a system
966                          * time-based discontinuity. We let the PCR decoder
967                          * handle that. */
968                         p_es->p_pgrm->b_discontinuity = 1;
969     
970                         /* There also may be a continuity_counter
971                          * discontinuity: resynchronise our counter with
972                          * the one of the stream. */
973                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
974                     }
975     
976                     /* If this is a PCR_PID, and this TS packet contains a
977                      * PCR, we pass it along to the PCR decoder. */
978                     if( (p_pgrm_demux->i_pcr_pid == i_pid) && (p[5] & 0x10) )
979                     {
980                         /* There should be a PCR field in the packet, check
981                          * if the adaptation field is long enough to carry
982                          * it. */
983                         if( p[4] >= 7 )
984                         {
985                             /* Read the PCR. */
986                             mtime_t     pcr_time;
987                             pcr_time =
988                                     ( (mtime_t)U32_AT((u32*)&p[6]) << 1 )
989                                       | ( p[10] >> 7 );
990                             /* Call the pace control. */
991                             input_ClockManageRef( p_input, p_es->p_pgrm,
992                                                   pcr_time );
993                         }
994                     } /* PCR ? */
995                 } /* valid TS adaptation field ? */
996             } /* length > 0 */
997         } /* has adaptation field */
998     
999         /* Check the continuity of the stream. */
1000         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1001         if( i_dummy == 1 )
1002         {
1003             /* Everything is ok, just increase our counter */
1004             p_es_demux->i_continuity_counter++;
1005         }
1006         else
1007         {
1008             if( !b_payload && i_dummy == 0 )
1009             {
1010                 /* This is a packet without payload, this is allowed by the
1011                  * draft. As there is nothing interesting in this packet
1012                  * (except PCR that have already been handled), we can trash
1013                  * the packet. */
1014                 intf_WarnMsg( 1,
1015                               "Packet without payload received by TS demux" );
1016                 b_trash = 1;
1017             }
1018             else if( i_dummy <= 0 )
1019             {
1020                 /* FIXME: this can never happen, can it ? --Meuuh */
1021                 /* Duplicate packet: mark it as being to be trashed. */
1022                 intf_WarnMsg( 1, "Duplicate packet received by TS demux" );
1023                 b_trash = 1;
1024             }
1025             else if( p_es_demux->i_continuity_counter == 0xFF )
1026             {
1027                 /* This means that the packet is the first one we receive for
1028                  * this ES since the continuity counter ranges between 0 and
1029                  * 0x0F excepts when it has been initialized by the input:
1030                  * init the counter to the correct value. */
1031                 intf_DbgMsg( "First packet for PID %d received by TS demux",
1032                              p_es->i_id );
1033                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1034             }
1035             else
1036             {
1037                 /* This can indicate that we missed a packet or that the
1038                  * continuity_counter wrapped and we received a dup packet:
1039                  * as we don't know, do as if we missed a packet to be sure
1040                  * to recover from this situation */
1041                 intf_WarnMsg( 2,
1042                            "Packet lost by TS demux: current %d, packet %d",
1043                            p_es_demux->i_continuity_counter & 0x0f,
1044                            p[3] & 0x0f );
1045                 b_lost = 1;
1046                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1047             } /* not continuous */
1048         } /* continuity */
1049     } /* if selected or PCR */
1050
1051     /* Trash the packet if it has no payload or if it isn't selected */
1052     if( b_trash )
1053     {
1054         p_input->p_plugin->pf_delete_packet( p_input, p_data );
1055 #ifdef STATS
1056         p_input->c_packets_trashed++;
1057 #endif
1058     }
1059     else
1060     {
1061         if( p_es_demux->b_psi )
1062         {
1063             /* The payload contains PSI tables */
1064 #if 0
1065             /* FIXME ! write the PSI decoder :p */
1066             input_DemuxPSI( p_input, p_data, p_es,
1067                             b_unit_start, b_lost );
1068 #endif
1069         }
1070         else
1071         {
1072             /* The payload carries a PES stream */
1073             if( b_unit_start )
1074             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
1075         }
1076     }
1077
1078 #undef p
1079 }