]> git.sesse.net Git - vlc/blob - src/input/mpeg_system.c
. fixed "-a [ mpeg | ac3 | lpcm | off ]" option
[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.12 2000/12/20 20:09:19 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 #include <netinet/in.h>
31
32 #include "config.h"
33 #include "common.h"
34 #include "threads.h"
35 #include "mtime.h"
36
37 #include "intf_msg.h"
38
39 #include "stream_control.h"
40 #include "input_ext-intf.h"
41 #include "input_ext-dec.h"
42
43 #include "input.h"
44 #include "mpeg_system.h"
45
46 #include "main.h"                           /* AC3/MPEG channel, SPU channel */
47
48 /*****************************************************************************
49  * Local prototypes
50  *****************************************************************************/
51
52
53 /*
54  * PES Packet management
55  */
56
57 /*****************************************************************************
58  * input_DecodePES
59  *****************************************************************************
60  * Put a PES in the decoder's fifo.
61  *****************************************************************************/
62 void input_DecodePES( input_thread_t * p_input, es_descriptor_t * p_es )
63 {
64 #define p_pes (p_es->p_pes)
65
66     if( p_es->p_decoder_fifo != NULL )
67     {
68         vlc_mutex_lock( &p_es->p_decoder_fifo->data_lock );
69
70 #if 0
71         if( p_input->stream.b_pace_control )
72         {
73             /* FIXME : normally we shouldn't need this... */
74             while( DECODER_FIFO_ISFULL( *p_es->p_decoder_fifo ) )
75             {
76                 vlc_mutex_unlock( &p_es->p_decoder_fifo->data_lock );
77                 msleep( 20000 );
78                 vlc_mutex_lock( &p_es->p_decoder_fifo->data_lock );
79             }
80         }
81 #endif
82
83         if( !DECODER_FIFO_ISFULL( *p_es->p_decoder_fifo ) )
84         {
85             //intf_DbgMsg("Putting %p into fifo %p/%d\n",
86             //            p_pes, p_fifo, p_fifo->i_end);
87             p_es->p_decoder_fifo->buffer[p_es->p_decoder_fifo->i_end] = p_pes;
88             DECODER_FIFO_INCEND( *p_es->p_decoder_fifo );
89
90             /* Warn the decoder that it's got work to do. */
91             vlc_cond_signal( &p_es->p_decoder_fifo->data_wait );
92         }
93         else
94         {
95             /* The FIFO is full !!! This should not happen. */
96             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
97             intf_ErrMsg( "PES trashed - fifo full ! (%d, %d)",
98                        p_es->i_id, p_es->i_type);
99         }
100         vlc_mutex_unlock( &p_es->p_decoder_fifo->data_lock );
101     }
102     else
103     {
104         intf_ErrMsg("No fifo to receive PES %p (who wrote this damn code ?)",
105                     p_pes);
106         p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
107     }
108     p_pes = NULL;
109
110 #undef p_pes
111 }
112
113 /*****************************************************************************
114  * input_ParsePES
115  *****************************************************************************
116  * Parse a finished PES packet and analyze its header.
117  *****************************************************************************/
118 #define PES_HEADER_SIZE     14
119 void input_ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
120 {
121     data_packet_t * p_header_data;
122     byte_t          p_header[PES_HEADER_SIZE];
123     int             i_done, i_todo;
124
125 #define p_pes (p_es->p_pes)
126
127     //intf_DbgMsg("End of PES packet %p\n", 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_header_data = p_pes->p_first;
133     i_done = 0;
134
135     for( ; ; )
136     {
137         i_todo = p_header_data->p_payload_end
138                      - p_header_data->p_payload_start;
139         if( i_todo > PES_HEADER_SIZE - i_done )
140             i_todo = PES_HEADER_SIZE - i_done;
141
142         memcpy( p_header + i_done, p_header_data->p_payload_start,
143                 i_todo );
144         i_done += i_todo;
145
146         if( i_done < PES_HEADER_SIZE && p_header_data->p_next != NULL )
147         {
148             p_header_data = p_header_data->p_next;
149         }
150         else
151         {
152             break;
153         }
154     }
155
156     if( i_done != PES_HEADER_SIZE )
157     {
158         intf_WarnMsg( 3, "PES packet too short to have a header" );
159         p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
160         p_pes = NULL;
161         return;
162     }
163
164     /* Get the PES size if defined */
165     p_es->i_pes_real_size = U16_AT(p_header + 4) + 6;
166
167     /* First read the 6 header bytes common to all PES packets:
168      * use them to test the PES validity */
169     if( (p_header[0] || p_header[1] || (p_header[2] != 1)) )
170     {
171         /* packet_start_code_prefix != 0x000001 */
172         intf_ErrMsg( "PES packet doesn't start with 0x000001 : data loss" );
173         p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
174         p_pes = NULL;
175     }
176     else
177     {
178         int i_pes_header_size, i_payload_size;
179
180         if ( p_es->i_pes_real_size &&
181              (p_es->i_pes_real_size != p_pes->i_pes_size) )
182         {
183             /* PES_packet_length is set and != total received payload */
184             /* Warn the decoder that the data may be corrupt. */
185             intf_WarnMsg( 3, "PES sizes do not match : packet corrupted" );
186             p_pes->b_messed_up = 1;
187         }
188
189         switch( p_es->i_stream_id )
190         {
191         case 0xBC:  /* Program stream map */
192         case 0xBE:  /* Padding */
193         case 0xBF:  /* Private stream 2 */
194         case 0xB0:  /* ECM */
195         case 0xB1:  /* EMM */
196         case 0xFF:  /* Program stream directory */
197         case 0xF2:  /* DSMCC stream */
198         case 0xF8:  /* ITU-T H.222.1 type E stream */
199             /* The payload begins immediately after the 6 bytes header, so
200              * we have finished with the parsing */
201             i_pes_header_size = 6;
202             break;
203
204         default:
205             if( (p_header[6] & 0xC0) == 0x80 )
206             {
207                 /* MPEG-2 : the PES header contains at least 3 more bytes. */
208                 p_pes->b_data_alignment = p_header[6] & 0x04;
209                 p_pes->b_has_pts = p_header[7] & 0x80;
210                 i_pes_header_size = p_header[8] + 9;
211
212                 /* Now parse the optional header extensions (in the limit of
213                  * the 14 bytes). */
214                 if( p_pes->b_has_pts )
215                 {
216                     p_pes->i_pts =
217                       ( ((mtime_t)(p_header[9] & 0x0E) << 29) |
218                         (((mtime_t)U16_AT(p_header + 10) << 14) - (1 << 14)) |
219                         ((mtime_t)U16_AT(p_header + 12) >> 1) ) * 300;
220                     p_pes->i_pts /= 27;
221                 }
222             }
223             else
224             {
225                 /* Probably MPEG-1 */
226                 byte_t *        p_byte;
227                 data_packet_t * p_data;
228
229                 i_pes_header_size = 6;
230                 p_data = p_pes->p_first;
231                 p_byte = p_data->p_buffer + 6;
232                 while( *p_byte == 0xFF && i_pes_header_size < 22 )
233                 {
234                     i_pes_header_size++;
235                     p_byte++;
236                     if( p_byte >= p_data->p_payload_end )
237                     {
238                         p_data = p_data->p_next;
239                         if( p_data == NULL )
240                         {
241                             intf_ErrMsg( "MPEG-1 packet too short for header" );
242                             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
243                             p_pes = NULL;
244                             return;
245                         }
246                         p_byte = p_data->p_payload_start;
247                     }
248                 }
249                 if( i_pes_header_size == 22 )
250                 {
251                     intf_ErrMsg( "Too much MPEG-1 stuffing" );
252                     p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
253                     p_pes = NULL;
254                     return;
255                 }
256
257                 if( (*p_byte & 0xC0) == 0x40 )
258                 {
259                     /* Don't ask why... --Meuuh */
260                     p_byte += 2;
261                     i_pes_header_size += 2;
262                     if( p_byte >= p_data->p_payload_end )
263                     {
264                         int i_plus = p_byte - p_data->p_payload_end;
265                         p_data = p_data->p_next;
266                         if( p_data == NULL )
267                         {
268                             intf_ErrMsg( "MPEG-1 packet too short for header" );
269                             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
270                             p_pes = NULL;
271                             return;
272                         }
273                         p_byte = p_data->p_payload_start + i_plus;
274                     }
275                 }
276
277                 i_pes_header_size++;
278                 p_pes->b_has_pts = *p_byte & 0x20;
279
280                 if( *p_byte & 0x10 )
281                 {
282                     /* DTS */
283                     i_pes_header_size += 5;
284                 }
285                 if( *p_byte & 0x20 )
286                 {
287                     /* PTS */
288                     byte_t      p_pts[5];
289                     int         i;
290
291                     i_pes_header_size += 4;
292                     p_pts[0] = *p_byte;
293                     for( i = 1; i < 5; i++ )
294                     {
295                         p_byte++;
296                         if( p_byte >= p_data->p_payload_end )
297                         {
298                             p_data = p_data->p_next;
299                             if( p_data == NULL )
300                             {
301                                 intf_ErrMsg( "MPEG-1 packet too short for header" );
302                                 p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
303                                 p_pes = NULL;
304                                 return;
305                             }
306                             p_byte = p_data->p_payload_start;
307                         }
308
309                         p_pts[i] = *p_byte;
310                     }
311                     p_pes->i_pts =
312                       ( ((mtime_t)(p_pts[0] & 0x0E) << 29) |
313                         (((mtime_t)U16_AT(p_pts + 1) << 14) - (1 << 14)) |
314                         ((mtime_t)U16_AT(p_pts + 3) >> 1) ) * 300;
315                     p_pes->i_pts /= 27;
316                 }
317             }
318
319             /* PTS management */
320             if( p_pes->b_has_pts )
321             {
322                 //intf_Msg("%lld\n", p_pes->i_pts);
323                 switch( p_es->p_pgrm->i_synchro_state )
324                 {
325                 case SYNCHRO_NOT_STARTED:
326                 case SYNCHRO_START:
327                     p_pes->b_has_pts = 0;
328                     break;
329
330                 case SYNCHRO_REINIT: /* We skip a PES | Why ?? --Meuuh */
331                     p_pes->b_has_pts = 0;
332                     p_es->p_pgrm->i_synchro_state = SYNCHRO_START;
333                     break;
334
335                 case SYNCHRO_OK:
336                     p_pes->i_pts += p_es->p_pgrm->delta_cr
337                                          + p_es->p_pgrm->delta_absolute
338                                          + DEFAULT_PTS_DELAY;
339                     break;
340                 }
341             }
342             break;
343         }
344
345         if( p_es->i_stream_id == 0xBC )
346         {
347             /* With private stream 1, the first byte of the payload
348              * is a stream_private_id, so skip it. */
349             i_pes_header_size++;
350         }
351
352         /* Now we've parsed the header, we just have to indicate in some
353          * specific data packets where the PES payload begins (renumber
354          * p_payload_start), so that the decoders can find the beginning
355          * of their data right out of the box. */
356         p_header_data = p_pes->p_first;
357         i_payload_size = p_header_data->p_payload_end
358                                  - p_header_data->p_payload_start;
359         while( i_pes_header_size > i_payload_size )
360         {
361             /* These packets are entirely filled by the PES header. */
362             i_pes_header_size -= i_payload_size;
363             p_header_data->p_payload_start = p_header_data->p_payload_end;
364             /* Go to the next data packet. */
365             if( (p_header_data = p_header_data->p_next) == NULL )
366             {
367                 intf_ErrMsg( "PES header bigger than payload" );
368                 p_input->p_plugin->pf_delete_pes( p_input->p_method_data,
369                                                   p_pes );
370                 p_pes = NULL;
371                 return;
372             }
373             i_payload_size = p_header_data->p_payload_end
374                                  - p_header_data->p_payload_start;
375         }
376         /* This last packet is partly header, partly payload. */
377         if( i_payload_size < i_pes_header_size )
378         {
379             intf_ErrMsg( "PES header bigger than payload" );
380             p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
381             p_pes = NULL;
382             return;
383         }
384         p_header_data->p_payload_start += i_pes_header_size;
385
386         /* Now we can eventually put the PES packet in the decoder's
387          * PES fifo */
388         input_DecodePES( p_input, p_es );
389     }
390 #undef p_pes
391 }
392
393 /*****************************************************************************
394  * input_GatherPES:
395  *****************************************************************************
396  * Gather a PES packet.
397  *****************************************************************************/
398 void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
399                       es_descriptor_t * p_es,
400                       boolean_t b_unit_start, boolean_t b_packet_lost )
401 {
402 #define p_pes (p_es->p_pes)
403
404     //intf_DbgMsg("PES-demultiplexing %p (%p)\n", p_ts_packet, p_pes);
405
406     /* If we lost data, insert an NULL data packet (philosophy : 0 is quite
407      * often an escape sequence in decoders, so that should make them wait
408      * for the next start code). */
409     if( b_packet_lost || p_es->b_discontinuity )
410     {
411         data_packet_t *             p_pad_data;
412
413         if( (p_pad_data = p_input->p_plugin->pf_new_packet(
414                                             p_input->p_method_data,
415                                             PADDING_PACKET_SIZE )) == NULL )
416         {
417             intf_ErrMsg("Out of memory\n");
418             p_input->b_error = 1;
419             return;
420         }
421         memset( p_data->p_buffer, 0, PADDING_PACKET_SIZE );
422         p_pad_data->b_discard_payload = 1;
423
424         if( p_pes != NULL )
425         {
426             p_pes->b_messed_up = p_pes->b_discontinuity = 1;
427             input_GatherPES( p_input, p_pad_data, p_es, 0, 0 );
428         }
429         else
430         {
431             if( (p_pes = p_input->p_plugin->pf_new_pes(
432                                             p_input->p_method_data )) == NULL )
433             {
434                 intf_ErrMsg("Out of memory\n");
435                 p_input->b_error = 1;
436                 return;
437             }
438
439             p_pes->p_first = p_pad_data;
440             p_pes->b_messed_up = p_pes->b_discontinuity = 1;
441             input_DecodePES( p_input, p_es );
442         }
443
444         p_es->b_discontinuity = 0;
445     }
446
447     if( b_unit_start && p_pes != NULL )
448     {
449         /* If the TS packet contains the begining of a new PES packet, and
450          * if we were reassembling a PES packet, then the PES should be
451          * complete now, so parse its header and give it to the decoders. */
452         input_ParsePES( p_input, p_es );
453     }
454
455     if( !b_unit_start && p_pes == NULL )
456     {
457         /* Random access... */
458         p_input->p_plugin->pf_delete_packet( p_input->p_method_data, p_data );
459     }
460     else
461     {
462         if( b_unit_start )
463         {
464             /* If we are at the beginning of a new PES packet, we must fetch
465              * a new PES buffer to begin with the reassembly of this PES
466              * packet. This is also here that we can synchronize with the
467              * stream if we lost packets or if the decoder has just
468              * started. */
469             if( (p_pes = p_input->p_plugin->pf_new_pes( p_input->p_method_data ) ) == NULL )
470             {
471                 intf_ErrMsg("Out of memory");
472                 p_input->b_error = 1;
473                 return;
474             }
475             //intf_DbgMsg("New PES packet %p (first data: %p)\n", p_pes, p_data);
476             p_pes->p_first = p_data;
477
478             /* If the PES header fits in the first data packet, we can
479              * already set p_gather->i_pes_real_size. */
480             if( p_data->p_payload_end - p_data->p_payload_start
481                     >= PES_HEADER_SIZE )
482             {
483                 p_es->i_pes_real_size =
484                                 U16_AT(p_data->p_payload_start + 4) + 6;
485             }
486             else
487             {
488                 p_es->i_pes_real_size = 0;
489             }
490         }
491         else
492         {
493             /* Update the relations between the data packets */
494             p_es->p_last->p_next = p_data;
495         }
496
497         p_data->p_next = NULL;
498         p_es->p_last = p_data;
499
500         /* Size of the payload carried in the data packet */
501         p_pes->i_pes_size += (p_data->p_payload_end
502                                  - p_data->p_payload_start);
503     
504         /* We can check if the packet is finished */
505         if( p_pes->i_pes_size == p_es->i_pes_real_size )
506         {
507             /* The packet is finished, parse it */
508             input_ParsePES( p_input, p_es );
509         }
510     }
511 #undef p_pes
512 }
513
514
515 /*
516  * Pace control
517  */
518
519 /*
520  *   DISCUSSION : SYNCHRONIZATION METHOD
521  *
522  *   In some cases we can impose the pace of reading (when reading from a
523  *   file or a pipe), and for the synchronization we simply sleep() until
524  *   it is time to deliver the packet to the decoders. When reading from
525  *   the network, we must be read at the same pace as the server writes,
526  *   otherwise the kernel's buffer will trash packets. The risk is now to
527  *   overflow the input buffers in case the server goes too fast, that is
528  *   why we do these calculations :
529  *
530  *   We compute an average for the pcr because we want to eliminate the
531  *   network jitter and keep the low frequency variations. The average is
532  *   in fact a low pass filter and the jitter is a high frequency signal
533  *   that is why it is eliminated by the filter/average.
534  *
535  *   The low frequency variations enable us to synchronize the client clock
536  *   with the server clock because they represent the time variation between
537  *   the 2 clocks. Those variations (ie the filtered pcr) are used to compute
538  *   the presentation dates for the audio and video frames. With those dates
539  *   we can decode (or trash) the MPEG2 stream at "exactly" the same rate
540  *   as it is sent by the server and so we keep the synchronization between
541  *   the server and the client.
542  *
543  *   It is a very important matter if you want to avoid underflow or overflow
544  *   in all the FIFOs, but it may be not enough.
545  */
546
547 /*****************************************************************************
548  * Constants
549  *****************************************************************************/
550
551 /* Maximum number of samples used to compute the dynamic average value,
552  * it is also the maximum of c_average_count in pgrm_ts_data_t.
553  * We use the following formula :
554  * new_average = (old_average * c_average + new_sample_value) / (c_average +1) */
555 #define CR_MAX_AVERAGE_COUNTER 40
556
557 /* Maximum gap allowed between two CRs. */
558 #define CR_MAX_GAP 1000000
559
560 /*****************************************************************************
561  * CRReInit : Reinitialize the clock reference
562  *****************************************************************************/
563 static void CRReInit( pgrm_descriptor_t * p_pgrm )
564 {
565     p_pgrm->delta_cr        = 0;
566     p_pgrm->last_cr         = 0;
567     p_pgrm->c_average_count = 0;
568 }
569
570 /* FIXME: find a better name */
571 /*****************************************************************************
572  * CRDecode : Decode a clock reference
573  *****************************************************************************/
574 static void CRDecode( input_thread_t * p_input, pgrm_descriptor_t * p_pgrm,
575                       mtime_t cr_time )
576 {
577     if( p_pgrm->i_synchro_state != SYNCHRO_OK )
578     {
579         switch( p_pgrm->i_synchro_state )
580         {
581         case SYNCHRO_START:
582             p_pgrm->delta_absolute = mdate() - cr_time;
583             p_pgrm->i_synchro_state = SYNCHRO_OK;
584             break;
585
586         case SYNCHRO_NOT_STARTED:
587             p_pgrm->i_synchro_state = SYNCHRO_START;
588             break;
589
590         default:
591             break;
592         }
593     }
594     else
595     {
596         if( p_pgrm->b_discontinuity ||
597             ( p_pgrm->last_cr != 0 &&
598                   (    (p_pgrm->last_cr - cr_time) > CR_MAX_GAP
599                     || (p_pgrm->last_cr - cr_time) < - CR_MAX_GAP ) ) )
600         {
601             int i_es;
602
603             /* Stream discontinuity. */
604             intf_WarnMsg( 3, "CR re-initialiazed" );
605             CRReInit( p_pgrm );
606             p_pgrm->i_synchro_state = SYNCHRO_REINIT;
607             p_pgrm->b_discontinuity = 0;
608
609             /* Warn all the elementary streams */
610             for( i_es = 0; i_es < p_pgrm->i_es_number; i_es++ )
611             {
612                 p_pgrm->pp_es[i_es]->b_discontinuity = 1;
613             }
614         }
615         p_pgrm->last_cr = cr_time;
616
617         if( p_input->stream.b_pace_control )
618         {
619             /* Wait a while before delivering the packets to the decoder. */
620             mwait( cr_time + p_pgrm->delta_absolute );
621         }
622         else
623         {
624             mtime_t                 sys_time, delta_cr;
625
626             sys_time = mdate();
627             delta_cr = sys_time - cr_time;
628
629             if( p_pgrm->c_average_count == CR_MAX_AVERAGE_COUNTER )
630             {
631                 p_pgrm->delta_cr = ( delta_cr + (p_pgrm->delta_cr
632                                               * (CR_MAX_AVERAGE_COUNTER - 1)) )
633                                      / CR_MAX_AVERAGE_COUNTER;
634             }
635             else
636             {
637                 p_pgrm->delta_cr = ( delta_cr + (p_pgrm->delta_cr
638                                               * p_pgrm->c_average_count) )
639                                      / ( p_pgrm->c_average_count + 1 );
640                 p_pgrm->c_average_count++;
641             }
642         }
643     }
644 }
645
646
647 /*
648  * PS Demultiplexing
649  */
650
651 /*****************************************************************************
652  * GetID: Get the ID of a stream
653  *****************************************************************************/
654 static u16 GetID( data_packet_t * p_data )
655 {
656     u16         i_id;
657
658     i_id = p_data->p_buffer[3];                                 /* stream_id */
659     if( i_id == 0xBD )
660     {
661         /* stream_private_id */
662         i_id |= p_data->p_buffer[ 9 + p_data->p_buffer[8] ] << 8;
663     }
664     return( i_id );
665 }
666
667 /*****************************************************************************
668  * DecodePSM: Decode the Program Stream Map information
669  *****************************************************************************/
670 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
671 {
672     stream_ps_data_t *  p_demux =
673                  (stream_ps_data_t *)p_input->stream.p_demux_data;
674
675     if( !p_demux->b_is_PSM_complete )
676     {
677         byte_t *    p_byte;
678         byte_t *    p_end;
679         int         i_es = 0;
680
681         intf_DbgMsg( "Building PSM" );
682         if( p_data->p_payload_start + 10 > p_data->p_payload_end )
683         {
684             intf_ErrMsg( "PSM too short : packet corrupt" );
685             return;
686         }
687         /* Go to elementary_stream_map_length, jumping over
688          * program_stream_info. */
689         p_byte = p_data->p_payload_start + 10
690                   + U16_AT(&p_data->p_payload_start[8]);
691         if( p_byte > p_data->p_payload_end )
692         {
693             intf_ErrMsg( "PSM too short : packet corrupt" );
694             return;
695         }
696         /* This is the full size of the elementary_stream_map.
697          * 2 == elementary_stream_map_length
698          * 4 == CRC_32 */
699         p_end = p_byte + 2 + U16_AT(p_byte) - 4;
700         p_byte += 2;
701         if( p_end > p_data->p_payload_end )
702         {
703             intf_ErrMsg( "PSM too short : packet corrupt" );
704             return;
705         }
706
707         vlc_mutex_lock( &p_input->stream.stream_lock );
708
709         /* 4 == minimum useful size of a section */
710         while( p_byte + 4 <= p_end )
711         {
712             p_input->p_es[i_es].i_id
713                 = p_input->p_es[i_es].i_stream_id
714                 = p_byte[1];
715             p_input->p_es[i_es].i_type = p_byte[0];
716             p_input->p_es[i_es].p_pgrm = p_input->stream.pp_programs[0];
717             p_input->p_es[i_es].p_pes = NULL;
718             p_byte += 4 + U16_AT(&p_byte[2]);
719
720 #ifdef AUTO_SPAWN
721             switch( p_input->p_es[i_es].i_type )
722             {
723                 case MPEG1_AUDIO_ES:
724                 case MPEG2_AUDIO_ES:
725                     /* Spawn audio thread. */
726                     intf_DbgMsg( "Starting an MPEG-audio decoder" );
727                     break;
728
729                 case MPEG1_VIDEO_ES:
730                 case MPEG2_VIDEO_ES:
731                     /* Spawn video thread. */
732                     intf_DbgMsg( "Starting an MPEG-video decoder" );
733                     break;
734             }
735 #endif
736
737             i_es++;
738         }
739
740         vlc_mutex_unlock( &p_input->stream.stream_lock );
741         p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;
742         p_demux->b_is_PSM_complete = 1;
743     }
744     else if( p_demux->i_PSM_version != (p_data->p_buffer[6] & 0x1F) )
745     {
746         /* FIXME */
747         intf_ErrMsg( "PSM changed, this is not supported yet !" );
748         p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;
749     }
750 }
751
752 /*****************************************************************************
753  * input_ParsePS: read the PS header
754  *****************************************************************************/
755 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
756                                  data_packet_t * p_data )
757 {
758     u32                 i_code;
759     es_descriptor_t *   p_es = NULL;
760
761     i_code = U32_AT( p_data->p_buffer );
762     if( i_code > 0x1BC ) /* ES start code */
763     {
764         u16                 i_id;
765         int                 i_dummy;
766
767         /* This is a PES packet. Find out if we want it or not. */
768         i_id = GetID( p_data );
769
770         vlc_mutex_lock( &p_input->stream.stream_lock );
771         if( p_input->stream.pp_programs[0]->b_is_ok )
772         {
773             /* Look only at the selected ES. */
774             for( i_dummy = 0; i_dummy < INPUT_MAX_SELECTED_ES; i_dummy++ )
775             {
776                 if( p_input->pp_selected_es[i_dummy] != NULL
777                     && p_input->pp_selected_es[i_dummy]->i_id == i_id )
778                 {
779                     p_es = p_input->pp_selected_es[i_dummy];
780                     break;
781                 }
782             }
783         }
784         else
785         {
786             /* Search all ES ; if not found -> AddES */
787             for( i_dummy = 0; i_dummy < INPUT_MAX_ES; i_dummy++ )
788             {
789                 if( p_input->p_es[i_dummy].i_id != EMPTY_ID 
790                     && p_input->p_es[i_dummy].i_id == i_id )
791                 {
792                     p_es = &p_input->p_es[i_dummy];
793                     break;
794                 }
795             }
796
797             if( p_es == NULL )
798             {
799                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
800                                     i_id, 0 );
801                 if( p_es != NULL )
802                 {
803                     p_es->i_stream_id = p_data->p_buffer[3];
804
805                     /* Set stream type and auto-spawn. */
806                     if( (i_id & 0xF0) == 0xE0 )
807                     {
808                         /* MPEG video */
809                         p_es->i_type = MPEG2_VIDEO_ES;
810 #ifdef AUTO_SPAWN
811                         input_SelectES( p_input, p_es );
812 #endif
813                     }
814                     else if( (i_id & 0xE0) == 0xC0 )
815                     {
816                         /* MPEG audio */
817                         p_es->i_type = MPEG2_AUDIO_ES;
818 #ifdef AUTO_SPAWN
819                         if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
820                                 == REQUESTED_MPEG
821                           && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
822                                 == (p_es->i_stream_id & 0x1F) )
823                         {
824                             input_SelectES( p_input, p_es );
825                         }
826 #endif
827                     }
828                     else if( (i_id & 0xF0FF) == 0x80BD )
829                     {
830                         /* AC3 audio (0x80->0x8F) */
831                         p_es->i_type = AC3_AUDIO_ES;
832 #ifdef AUTO_SPAWN
833                         if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
834                                 == REQUESTED_AC3
835                          && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
836                                 == ((p_es->i_stream_id & 0xF00) >> 8) )
837                         {
838                             input_SelectES( p_input, p_es );
839                         }
840 #endif
841                     }
842                     else if( (i_id & 0xE0FF) == 0x20BD )
843                     {
844                         /* Subtitles video (0x20->0x3F) */
845                         p_es->i_type = DVD_SPU_ES;
846 #ifdef AUTO_SPAWN
847                         if( main_GetIntVariable( INPUT_DVD_SUBTITLE_VAR, 0 )
848                                 == ((p_es->i_stream_id & 0x1F00) >> 8) )
849                         {
850                             input_SelectES( p_input, p_es );
851                         }
852 #endif
853                     }
854                     else if( (i_id & 0xF0FF) == 0xA0BD )
855                     {
856                         /* LPCM audio (0xA0->0xAF) */
857                         p_es->i_type = LPCM_AUDIO_ES;
858                         /* FIXME : write the decoder */
859                     }
860                     else
861                     {
862                         p_es->i_type = UNKNOWN_ES;
863                     }
864                 }
865             }
866         } /* stream.b_is_ok */
867         vlc_mutex_unlock( &p_input->stream.stream_lock );
868     } /* i_code > 0xBC */
869
870     return( p_es );
871 }
872
873 /*****************************************************************************
874  * input_DemuxPS: first step of demultiplexing: the PS header
875  *****************************************************************************/
876 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
877 {
878     u32                 i_code;
879     boolean_t           b_trash = 0;
880     es_descriptor_t *   p_es = NULL;
881
882     i_code = U32_AT( p_data->p_buffer );
883     if( i_code <= 0x1BC )
884     {
885         switch( i_code )
886         {
887         case 0x1BA: /* PACK_START_CODE */
888             {
889                 /* Convert the SCR in microseconds. */
890                 mtime_t         scr_time;
891
892                 if( (p_data->p_buffer[4] & 0xC0) == 0x40 )
893                 {
894                     /* MPEG-2 */
895                     scr_time =
896                       (( ((mtime_t)(p_data->p_buffer[4] & 0x38) << 27) |
897                          ((mtime_t)(U32_AT(p_data->p_buffer + 4) & 0x03FFF800)
898                                         << 4) |
899                          ((mtime_t)(U32_AT(p_data->p_buffer + 6) & 0x03FFF800)
900                                         >> 11)
901                       ) * 300) / 27;
902                 }
903                 else
904                 {
905                     /* MPEG-1 SCR is like PTS */
906                     scr_time =
907                       (( ((mtime_t)(p_data->p_buffer[4] & 0x0E) << 29) |
908                          (((mtime_t)U16_AT(p_data->p_buffer + 5) << 14)
909                            - (1 << 14)) |
910                          ((mtime_t)U16_AT(p_data->p_buffer + 7) >> 1)
911                       ) * 300) / 27;
912                 }
913                 /* Call the pace control. */
914                 //intf_Msg("+%lld\n", scr_time);
915                 CRDecode( p_input, p_input->stream.pp_programs[0],
916                           scr_time );
917                 b_trash = 1;
918             }
919             break;
920
921         case 0x1BB: /* SYSTEM_START_CODE */
922             b_trash = 1;                              /* Nothing interesting */
923             break;
924
925         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
926             intf_ErrMsg("meuuuuh\n");
927             DecodePSM( p_input, p_data );
928             b_trash = 1;
929             break;
930     
931         case 0x1B9: /* PROGRAM_END_CODE */
932             b_trash = 1;
933             break;
934    
935         default:
936             /* This should not happen */
937             b_trash = 1;
938             intf_WarnMsg( 1, "Unwanted packet received with start code %x",
939                           i_code );
940         }
941     }
942     else
943     {
944         p_es = input_ParsePS( p_input, p_data );
945
946         if( p_es != NULL && p_es->p_decoder_fifo != NULL && !b_trash )
947         {
948 #ifdef STATS
949             p_es->c_packets++;
950 #endif
951             input_GatherPES( p_input, p_data, p_es, 1, 0 );
952         }
953     }
954
955     /* Trash the packet if it has no payload or if it isn't selected */
956     if( b_trash )
957     {
958         p_input->p_plugin->pf_delete_packet( p_input, p_data );
959 #ifdef STATS
960         p_input->c_packets_trashed++;
961 #endif
962     }
963 }
964
965
966 /*
967  * TS Demultiplexing
968  */
969
970 /*****************************************************************************
971  * input_DemuxTS: first step of demultiplexing: the TS header
972  *****************************************************************************/
973 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
974 {
975     int                 i_pid, i_dummy;
976     boolean_t           b_adaptation;         /* Adaptation field is present */
977     boolean_t           b_payload;                 /* Packet carries payload */
978     boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
979     boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
980     boolean_t           b_lost = 0;             /* Was there a packet loss ? */
981     es_descriptor_t *   p_es = NULL;
982     es_ts_data_t *      p_es_demux = NULL;
983     pgrm_ts_data_t *    p_pgrm_demux = NULL;
984
985 #define p (p_data->p_buffer)
986
987     //intf_DbgMsg("input debug: TS-demultiplexing packet %p, pid %d\n",
988     //            p_ts_packet, U16_AT(&p[1]) & 0x1fff);
989
990     /* Extract flags values from TS common header. */
991     i_pid = U16_AT(&p[1]) & 0x1fff;
992     b_unit_start = (p[1] & 0x40);
993     b_adaptation = (p[3] & 0x20);
994     b_payload = (p[3] & 0x10);
995
996     /* Find out the elementary stream. */
997     vlc_mutex_lock( &p_input->stream.stream_lock );
998     for( i_dummy = 0; i_dummy < INPUT_MAX_ES; i_dummy++ )
999     {
1000         if( p_input->p_es[i_dummy].i_id != EMPTY_ID )
1001         {
1002             if( p_input->p_es[i_dummy].i_id == i_pid )
1003             {
1004                 p_es = &p_input->p_es[i_dummy];
1005                 p_es_demux = (es_ts_data_t *)p_es->p_demux_data;
1006                 p_pgrm_demux = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data;
1007                 break;
1008             }
1009         }
1010     }
1011     vlc_mutex_unlock( &p_input->stream.stream_lock );
1012
1013 #ifdef STATS
1014     p_es->c_packets++;
1015 #endif
1016
1017     if( p_es->p_decoder_fifo == NULL )
1018     {
1019         /* Not selected. Just read the adaptation field for a PCR. */
1020         b_trash = 1;
1021     }
1022
1023     if( (p_es->p_decoder_fifo != NULL) || (p_pgrm_demux->i_pcr_pid == i_pid) )
1024     {
1025         /* Extract adaptation field information if any */
1026         if( !b_adaptation )
1027         {
1028             /* We don't have any adaptation_field, so payload starts
1029              * immediately after the 4 byte TS header */
1030             p_data->p_payload_start += 4;
1031         }
1032         else
1033         {
1034             /* p[4] is adaptation_field_length minus one */
1035             p_data->p_payload_start += 5 + p[4];
1036     
1037             /* The adaptation field can be limited to the
1038              * adaptation_field_length byte, so that there is nothing to do:
1039              * skip this possibility */
1040             if( p[4] )
1041             {
1042                 /* If the packet has both adaptation_field and payload,
1043                  * adaptation_field cannot be more than 182 bytes long; if
1044                  * there is only an adaptation_field, it must fill the next
1045                  * 183 bytes. */
1046                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1047                 {
1048                     intf_WarnMsg( 2,
1049                         "invalid TS adaptation field (%p)",
1050                         p_data );
1051                     p_data->b_discard_payload = 1;
1052 #ifdef STATS
1053                     p_es->c_invalid_packets++;
1054 #endif
1055                 }
1056     
1057                 /* Now we are sure that the byte containing flags is present:
1058                  * read it */
1059                 else
1060                 {
1061                     /* discontinuity_indicator */
1062                     if( p[5] & 0x80 )
1063                     {
1064                         intf_WarnMsg( 2,
1065                             "discontinuity_indicator"                       \
1066                             " encountered by TS demux (position read: %d,"  \
1067                             " saved: %d)",
1068                             p[5] & 0x80, p_es_demux->i_continuity_counter );
1069     
1070                         /* If the PID carries the PCR, there will be a system
1071                          * time-based discontinuity. We let the PCR decoder
1072                          * handle that. */
1073                         p_es->p_pgrm->b_discontinuity = 1;
1074     
1075                         /* There also may be a continuity_counter
1076                          * discontinuity: resynchronise our counter with
1077                          * the one of the stream. */
1078                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
1079                     }
1080     
1081                     /* If this is a PCR_PID, and this TS packet contains a
1082                      * PCR, we pass it along to the PCR decoder. */
1083                     if( (p_pgrm_demux->i_pcr_pid == i_pid) && (p[5] & 0x10) )
1084                     {
1085                         /* There should be a PCR field in the packet, check
1086                          * if the adaptation field is long enough to carry
1087                          * it. */
1088                         if( p[4] >= 7 )
1089                         {
1090                             /* Convert the PCR in microseconds.
1091                              * WARNING: do not remove the casts in the
1092                              * following calculation ! */
1093                             mtime_t     pcr_time;
1094                             pcr_time =
1095                                     ( (( (mtime_t)U32_AT((u32*)&p[6]) << 1 )
1096                                       | ( p[10] >> 7 )) * 300 ) / 27;
1097                             /* Call the pace control. */
1098                             CRDecode( p_input, p_es->p_pgrm, pcr_time );
1099                         }
1100                     } /* PCR ? */
1101                 } /* valid TS adaptation field ? */
1102             } /* length > 0 */
1103         } /* has adaptation field */
1104     
1105         /* Check the continuity of the stream. */
1106         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1107         if( i_dummy == 1 )
1108         {
1109             /* Everything is ok, just increase our counter */
1110             p_es_demux->i_continuity_counter++;
1111         }
1112         else
1113         {
1114             if( !b_payload && i_dummy == 0 )
1115             {
1116                 /* This is a packet without payload, this is allowed by the draft.
1117                  * As there is nothing interesting in this packet (except PCR that
1118                  * have already been handled), we can trash the packet. */
1119                 intf_WarnMsg( 1,
1120                               "Packet without payload received by TS demux" );
1121                 b_trash = 1;
1122             }
1123             else if( i_dummy <= 0 )
1124             {
1125                 /* FIXME: this can never happen, can it ? --Meuuh */
1126                 /* Duplicate packet: mark it as being to be trashed. */
1127                 intf_WarnMsg( 1, "Duplicate packet received by TS demux" );
1128                 b_trash = 1;
1129             }
1130             else if( p_es_demux->i_continuity_counter == 0xFF )
1131             {
1132                 /* This means that the packet is the first one we receive for this
1133                  * ES since the continuity counter ranges between 0 and 0x0F
1134                  * excepts when it has been initialized by the input: Init the
1135                  * counter to the correct value. */
1136                 intf_DbgMsg( "First packet for PID %d received by TS demux",
1137                              p_es->i_id );
1138                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1139             }
1140             else
1141             {
1142                 /* This can indicate that we missed a packet or that the
1143                  * continuity_counter wrapped and we received a dup packet: as we
1144                  * don't know, do as if we missed a packet to be sure to recover
1145                  * from this situation */
1146                 intf_WarnMsg( 2,
1147                            "Packet lost by TS demux: current %d, packet %d\n",
1148                            p_es_demux->i_continuity_counter & 0x0f,
1149                            p[3] & 0x0f );
1150                 b_lost = 1;
1151                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1152             } /* not continuous */
1153         } /* continuity */
1154     } /* if selected or PCR */
1155
1156     /* Trash the packet if it has no payload or if it isn't selected */
1157     if( b_trash )
1158     {
1159         p_input->p_plugin->pf_delete_packet( p_input, p_data );
1160 #ifdef STATS
1161         p_input->c_packets_trashed++;
1162 #endif
1163     }
1164     else
1165     {
1166         if( p_es_demux->b_psi )
1167         {
1168             /* The payload contains PSI tables */
1169 #if 0
1170             input_DemuxPSI( p_input, p_data, p_es,
1171                             b_unit_start, b_lost );
1172 #endif
1173         }
1174         else
1175         {
1176             /* The payload carries a PES stream */
1177             if( b_unit_start )
1178             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
1179         }
1180     }
1181
1182 #undef p
1183 }