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