]> git.sesse.net Git - vlc/blob - src/input/mpeg_system.c
* New decoder spawning API input_dec.c ;
[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.14 2000/12/21 19:24:27 massiot 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 /* FIXME : deprecated code ! */
671 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
672 {
673     stream_ps_data_t *  p_demux =
674                  (stream_ps_data_t *)p_input->stream.p_demux_data;
675
676     intf_Msg("input info: Your stream contains Program Stream Map information");
677     intf_Msg("input info: Please send a mail to <massiot@via.ecp.fr>");
678
679 #if 0
680     if( !p_demux->b_is_PSM_complete )
681     {
682         byte_t *    p_byte;
683         byte_t *    p_end;
684
685         intf_DbgMsg( "Building PSM" );
686         if( p_data->p_payload_start + 10 > p_data->p_payload_end )
687         {
688             intf_ErrMsg( "PSM too short : packet corrupt" );
689             return;
690         }
691         /* Go to elementary_stream_map_length, jumping over
692          * program_stream_info. */
693         p_byte = p_data->p_payload_start + 10
694                   + U16_AT(&p_data->p_payload_start[8]);
695         if( p_byte > p_data->p_payload_end )
696         {
697             intf_ErrMsg( "PSM too short : packet corrupt" );
698             return;
699         }
700         /* This is the full size of the elementary_stream_map.
701          * 2 == elementary_stream_map_length
702          * 4 == CRC_32 */
703         p_end = p_byte + 2 + U16_AT(p_byte) - 4;
704         p_byte += 2;
705         if( p_end > p_data->p_payload_end )
706         {
707             intf_ErrMsg( "PSM too short : packet corrupt" );
708             return;
709         }
710
711         vlc_mutex_lock( &p_input->stream.stream_lock );
712
713         /* 4 == minimum useful size of a section */
714         while( p_byte + 4 <= p_end )
715         {
716             es_descriptor_t *   p_es;
717
718             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
719                                 p_byte[1], 0 );
720             p_es->i_type = p_byte[0];
721             p_byte += 4 + U16_AT(&p_byte[2]);
722         }
723
724         vlc_mutex_unlock( &p_input->stream.stream_lock );
725         p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;
726         p_demux->b_is_PSM_complete = 1;
727     }
728     else if( p_demux->i_PSM_version != (p_data->p_buffer[6] & 0x1F) )
729     {
730         /* FIXME */
731         intf_ErrMsg( "PSM changed, this is not supported yet !" );
732         p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;
733     }
734 #endif
735 }
736
737 /*****************************************************************************
738  * input_ParsePS: read the PS header
739  *****************************************************************************/
740 es_descriptor_t * input_ParsePS( input_thread_t * p_input,
741                                  data_packet_t * p_data )
742 {
743     u32                 i_code;
744     es_descriptor_t *   p_es = NULL;
745
746     i_code = U32_AT( p_data->p_buffer );
747     if( i_code > 0x1BC ) /* ES start code */
748     {
749         u16                 i_id;
750         int                 i_dummy;
751
752         /* This is a PES packet. Find out if we want it or not. */
753         i_id = GetID( p_data );
754
755         vlc_mutex_lock( &p_input->stream.stream_lock );
756         if( p_input->stream.pp_programs[0]->b_is_ok )
757         {
758             /* Look only at the selected ES. */
759             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
760                  i_dummy++ )
761             {
762                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
763                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
764                 {
765                     p_es = p_input->stream.pp_selected_es[i_dummy];
766                     break;
767                 }
768             }
769         }
770         else
771         {
772             /* Search all ES ; if not found -> AddES */
773             p_es = input_FindES( p_input, i_id );
774
775             if( p_es == NULL )
776             {
777                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
778                                     i_id, 0 );
779                 if( p_es != NULL )
780                 {
781                     p_es->i_stream_id = p_data->p_buffer[3];
782
783                     /* Set stream type and auto-spawn. */
784                     if( (i_id & 0xF0) == 0xE0 )
785                     {
786                         /* MPEG video */
787                         p_es->i_type = MPEG2_VIDEO_ES;
788 #ifdef AUTO_SPAWN
789                         input_SelectES( p_input, p_es );
790 #endif
791                     }
792                     else if( (i_id & 0xE0) == 0xC0 )
793                     {
794                         /* MPEG audio */
795                         p_es->i_type = MPEG2_AUDIO_ES;
796 #ifdef AUTO_SPAWN
797                         if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
798                                 == REQUESTED_MPEG
799                           && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
800                                 == (p_es->i_stream_id & 0x1F) )
801                         {
802                             input_SelectES( p_input, p_es );
803                         }
804 #endif
805                     }
806                     else if( (i_id & 0xF0FF) == 0x80BD )
807                     {
808                         /* AC3 audio (0x80->0x8F) */
809                         p_es->i_type = AC3_AUDIO_ES;
810 #ifdef AUTO_SPAWN
811                         if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
812                                 == REQUESTED_AC3
813                          && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
814                                 == ((p_es->i_stream_id & 0xF00) >> 8) )
815                         {
816                             input_SelectES( p_input, p_es );
817                         }
818 #endif
819                     }
820                     else if( (i_id & 0xE0FF) == 0x20BD )
821                     {
822                         /* Subtitles video (0x20->0x3F) */
823                         p_es->i_type = DVD_SPU_ES;
824 #ifdef AUTO_SPAWN
825                         if( main_GetIntVariable( INPUT_DVD_SUBTITLE_VAR, 0 )
826                                 == ((p_es->i_stream_id & 0x1F00) >> 8) )
827                         {
828                             input_SelectES( p_input, p_es );
829                         }
830 #endif
831                     }
832                     else if( (i_id & 0xF0FF) == 0xA0BD )
833                     {
834                         /* LPCM audio (0xA0->0xAF) */
835                         p_es->i_type = LPCM_AUDIO_ES;
836                         /* FIXME : write the decoder */
837                     }
838                     else
839                     {
840                         p_es->i_type = UNKNOWN_ES;
841                     }
842                 }
843             }
844         } /* stream.b_is_ok */
845         vlc_mutex_unlock( &p_input->stream.stream_lock );
846     } /* i_code > 0xBC */
847
848     return( p_es );
849 }
850
851 /*****************************************************************************
852  * input_DemuxPS: first step of demultiplexing: the PS header
853  *****************************************************************************/
854 void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
855 {
856     u32                 i_code;
857     boolean_t           b_trash = 0;
858     es_descriptor_t *   p_es = NULL;
859
860     i_code = U32_AT( p_data->p_buffer );
861     if( i_code <= 0x1BC )
862     {
863         switch( i_code )
864         {
865         case 0x1BA: /* PACK_START_CODE */
866             {
867                 /* Convert the SCR in microseconds. */
868                 mtime_t         scr_time;
869
870                 if( (p_data->p_buffer[4] & 0xC0) == 0x40 )
871                 {
872                     /* MPEG-2 */
873                     scr_time =
874                       (( ((mtime_t)(p_data->p_buffer[4] & 0x38) << 27) |
875                          ((mtime_t)(U32_AT(p_data->p_buffer + 4) & 0x03FFF800)
876                                         << 4) |
877                          ((mtime_t)(U32_AT(p_data->p_buffer + 6) & 0x03FFF800)
878                                         >> 11)
879                       ) * 300) / 27;
880                 }
881                 else
882                 {
883                     /* MPEG-1 SCR is like PTS */
884                     scr_time =
885                       (( ((mtime_t)(p_data->p_buffer[4] & 0x0E) << 29) |
886                          (((mtime_t)U16_AT(p_data->p_buffer + 5) << 14)
887                            - (1 << 14)) |
888                          ((mtime_t)U16_AT(p_data->p_buffer + 7) >> 1)
889                       ) * 300) / 27;
890                 }
891                 /* Call the pace control. */
892                 //intf_Msg("+%lld\n", scr_time);
893                 CRDecode( p_input, p_input->stream.pp_programs[0],
894                           scr_time );
895                 b_trash = 1;
896             }
897             break;
898
899         case 0x1BB: /* SYSTEM_START_CODE */
900             b_trash = 1;                              /* Nothing interesting */
901             break;
902
903         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
904             DecodePSM( p_input, p_data );
905             b_trash = 1;
906             break;
907     
908         case 0x1B9: /* PROGRAM_END_CODE */
909             b_trash = 1;
910             break;
911    
912         default:
913             /* This should not happen */
914             b_trash = 1;
915             intf_WarnMsg( 1, "Unwanted packet received with start code %x",
916                           i_code );
917         }
918     }
919     else
920     {
921         p_es = input_ParsePS( p_input, p_data );
922
923         if( p_es != NULL && p_es->p_decoder_fifo != NULL )
924         {
925 #ifdef STATS
926             p_es->c_packets++;
927 #endif
928             input_GatherPES( p_input, p_data, p_es, 1, 0 );
929         }
930         else
931         {
932             b_trash = 1;
933         }
934     }
935
936     /* Trash the packet if it has no payload or if it isn't selected */
937     if( b_trash )
938     {
939         p_input->p_plugin->pf_delete_packet( p_input, p_data );
940 #ifdef STATS
941         p_input->c_packets_trashed++;
942 #endif
943     }
944 }
945
946
947 /*
948  * TS Demultiplexing
949  */
950
951 /*****************************************************************************
952  * input_DemuxTS: first step of demultiplexing: the TS header
953  *****************************************************************************/
954 void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
955 {
956     int                 i_pid, i_dummy;
957     boolean_t           b_adaptation;         /* Adaptation field is present */
958     boolean_t           b_payload;                 /* Packet carries payload */
959     boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
960     boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
961     boolean_t           b_lost = 0;             /* Was there a packet loss ? */
962     es_descriptor_t *   p_es = NULL;
963     es_ts_data_t *      p_es_demux = NULL;
964     pgrm_ts_data_t *    p_pgrm_demux = NULL;
965
966 #define p (p_data->p_buffer)
967
968     //intf_DbgMsg("input debug: TS-demultiplexing packet %p, pid %d\n",
969     //            p_ts_packet, U16_AT(&p[1]) & 0x1fff);
970
971     /* Extract flags values from TS common header. */
972     i_pid = U16_AT(&p[1]) & 0x1fff;
973     b_unit_start = (p[1] & 0x40);
974     b_adaptation = (p[3] & 0x20);
975     b_payload = (p[3] & 0x10);
976
977     /* Find out the elementary stream. */
978     vlc_mutex_lock( &p_input->stream.stream_lock );
979     p_es = input_FindES( p_input, i_pid );
980     vlc_mutex_unlock( &p_input->stream.stream_lock );
981
982     if( p_es == NULL || p_es->p_decoder_fifo == NULL )
983     {
984         /* Not selected. Just read the adaptation field for a PCR. */
985         b_trash = 1;
986     }
987
988     if( (p_es->p_decoder_fifo != NULL) || (p_pgrm_demux->i_pcr_pid == i_pid) )
989     {
990 #ifdef STATS
991         p_es->c_packets++;
992 #endif
993
994         /* Extract adaptation field information if any */
995         if( !b_adaptation )
996         {
997             /* We don't have any adaptation_field, so payload starts
998              * immediately after the 4 byte TS header */
999             p_data->p_payload_start += 4;
1000         }
1001         else
1002         {
1003             /* p[4] is adaptation_field_length minus one */
1004             p_data->p_payload_start += 5 + p[4];
1005     
1006             /* The adaptation field can be limited to the
1007              * adaptation_field_length byte, so that there is nothing to do:
1008              * skip this possibility */
1009             if( p[4] )
1010             {
1011                 /* If the packet has both adaptation_field and payload,
1012                  * adaptation_field cannot be more than 182 bytes long; if
1013                  * there is only an adaptation_field, it must fill the next
1014                  * 183 bytes. */
1015                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1016                 {
1017                     intf_WarnMsg( 2,
1018                         "invalid TS adaptation field (%p)",
1019                         p_data );
1020                     p_data->b_discard_payload = 1;
1021 #ifdef STATS
1022                     p_es->c_invalid_packets++;
1023 #endif
1024                 }
1025     
1026                 /* Now we are sure that the byte containing flags is present:
1027                  * read it */
1028                 else
1029                 {
1030                     /* discontinuity_indicator */
1031                     if( p[5] & 0x80 )
1032                     {
1033                         intf_WarnMsg( 2,
1034                             "discontinuity_indicator"                       \
1035                             " encountered by TS demux (position read: %d,"  \
1036                             " saved: %d)",
1037                             p[5] & 0x80, p_es_demux->i_continuity_counter );
1038     
1039                         /* If the PID carries the PCR, there will be a system
1040                          * time-based discontinuity. We let the PCR decoder
1041                          * handle that. */
1042                         p_es->p_pgrm->b_discontinuity = 1;
1043     
1044                         /* There also may be a continuity_counter
1045                          * discontinuity: resynchronise our counter with
1046                          * the one of the stream. */
1047                         p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
1048                     }
1049     
1050                     /* If this is a PCR_PID, and this TS packet contains a
1051                      * PCR, we pass it along to the PCR decoder. */
1052                     if( (p_pgrm_demux->i_pcr_pid == i_pid) && (p[5] & 0x10) )
1053                     {
1054                         /* There should be a PCR field in the packet, check
1055                          * if the adaptation field is long enough to carry
1056                          * it. */
1057                         if( p[4] >= 7 )
1058                         {
1059                             /* Convert the PCR in microseconds.
1060                              * WARNING: do not remove the casts in the
1061                              * following calculation ! */
1062                             mtime_t     pcr_time;
1063                             pcr_time =
1064                                     ( (( (mtime_t)U32_AT((u32*)&p[6]) << 1 )
1065                                       | ( p[10] >> 7 )) * 300 ) / 27;
1066                             /* Call the pace control. */
1067                             CRDecode( p_input, p_es->p_pgrm, pcr_time );
1068                         }
1069                     } /* PCR ? */
1070                 } /* valid TS adaptation field ? */
1071             } /* length > 0 */
1072         } /* has adaptation field */
1073     
1074         /* Check the continuity of the stream. */
1075         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1076         if( i_dummy == 1 )
1077         {
1078             /* Everything is ok, just increase our counter */
1079             p_es_demux->i_continuity_counter++;
1080         }
1081         else
1082         {
1083             if( !b_payload && i_dummy == 0 )
1084             {
1085                 /* This is a packet without payload, this is allowed by the draft.
1086                  * As there is nothing interesting in this packet (except PCR that
1087                  * have already been handled), we can trash the packet. */
1088                 intf_WarnMsg( 1,
1089                               "Packet without payload received by TS demux" );
1090                 b_trash = 1;
1091             }
1092             else if( i_dummy <= 0 )
1093             {
1094                 /* FIXME: this can never happen, can it ? --Meuuh */
1095                 /* Duplicate packet: mark it as being to be trashed. */
1096                 intf_WarnMsg( 1, "Duplicate packet received by TS demux" );
1097                 b_trash = 1;
1098             }
1099             else if( p_es_demux->i_continuity_counter == 0xFF )
1100             {
1101                 /* This means that the packet is the first one we receive for this
1102                  * ES since the continuity counter ranges between 0 and 0x0F
1103                  * excepts when it has been initialized by the input: Init the
1104                  * counter to the correct value. */
1105                 intf_DbgMsg( "First packet for PID %d received by TS demux",
1106                              p_es->i_id );
1107                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1108             }
1109             else
1110             {
1111                 /* This can indicate that we missed a packet or that the
1112                  * continuity_counter wrapped and we received a dup packet: as we
1113                  * don't know, do as if we missed a packet to be sure to recover
1114                  * from this situation */
1115                 intf_WarnMsg( 2,
1116                            "Packet lost by TS demux: current %d, packet %d\n",
1117                            p_es_demux->i_continuity_counter & 0x0f,
1118                            p[3] & 0x0f );
1119                 b_lost = 1;
1120                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1121             } /* not continuous */
1122         } /* continuity */
1123     } /* if selected or PCR */
1124
1125     /* Trash the packet if it has no payload or if it isn't selected */
1126     if( b_trash )
1127     {
1128         p_input->p_plugin->pf_delete_packet( p_input, p_data );
1129 #ifdef STATS
1130         p_input->c_packets_trashed++;
1131 #endif
1132     }
1133     else
1134     {
1135         if( p_es_demux->b_psi )
1136         {
1137             /* The payload contains PSI tables */
1138 #if 0
1139             input_DemuxPSI( p_input, p_data, p_es,
1140                             b_unit_start, b_lost );
1141 #endif
1142         }
1143         else
1144         {
1145             /* The payload carries a PES stream */
1146             if( b_unit_start )
1147             input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
1148         }
1149     }
1150
1151 #undef p
1152 }