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