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