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