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