]> git.sesse.net Git - vlc/blob - modules/demux/mpeg/system.c
69b0b1569571d3414a6e23823b687e0a9c318b2b
[vlc] / modules / demux / mpeg / system.c
1 /*****************************************************************************
2  * system.c: helper module for TS, PS and PES management
3  *****************************************************************************
4  * Copyright (C) 1998-2002 VideoLAN
5  * $Id: system.c,v 1.13 2003/04/01 10:46:35 massiot Exp $
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *          Michel Lespinasse <walken@via.ecp.fr>
9  *          BenoĆ®t Steiner <benny@via.ecp.fr>
10  *          Samuel Hocevar <sam@zoy.org>
11  *          Henri Fallon <henri@via.ecp.fr>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
26  *****************************************************************************/
27
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 #include <stdlib.h>
32 #include <string.h>                                    /* memcpy(), memset() */
33
34 #include <vlc/vlc.h>
35 #include <vlc/input.h>
36
37 #include "system.h"
38
39 /*****************************************************************************
40  * Local prototypes
41  *****************************************************************************/
42 static int Activate ( vlc_object_t * );
43
44 static ssize_t           ReadPS  ( input_thread_t *, data_packet_t ** );
45 static es_descriptor_t * ParsePS ( input_thread_t *, data_packet_t * );
46 static void              DemuxPS ( input_thread_t *, data_packet_t * );
47
48 static ssize_t           ReadTS  ( input_thread_t *, data_packet_t ** );
49 static void              DemuxTS ( input_thread_t *, data_packet_t *,
50                                    psi_callback_t );
51
52 /*****************************************************************************
53  * Module descriptor
54  *****************************************************************************/
55 vlc_module_begin();
56     set_description( _("generic ISO 13818-1 MPEG demultiplexing") );
57     set_capability( "mpeg-system", 100 );
58     set_callbacks( Activate, NULL );
59 vlc_module_end();
60
61 /*****************************************************************************
62  * Activate: initializes helper functions
63  *****************************************************************************/
64 static int Activate ( vlc_object_t *p_this )
65 {
66     static mpeg_demux_t mpeg_demux =
67                     { NULL, ReadPS, ParsePS, DemuxPS, ReadTS, DemuxTS };
68
69     memcpy( p_this->p_private, &mpeg_demux, sizeof( mpeg_demux ) );
70
71     return VLC_SUCCESS;
72 }
73
74 /*
75  * PES Packet management
76  */
77
78 /*****************************************************************************
79  * MoveChunk
80  *****************************************************************************
81  * Small utility function used to parse discontinuous headers safely. Copies
82  * i_buf_len bytes of data to a buffer and returns the size copied.
83  * It also solves some alignment problems on non-IA-32, non-PPC processors.
84  * This is a variation on the theme of input_ext-dec.h:GetChunk().
85  *****************************************************************************/
86 static inline size_t MoveChunk( byte_t * p_dest, data_packet_t ** pp_data_src,
87                                 byte_t ** pp_src, size_t i_buf_len )
88 {
89     size_t i_available;
90
91     i_available = (ptrdiff_t)((*pp_data_src)->p_payload_end - *pp_src);
92     if( i_available >= i_buf_len )
93     {
94         if( p_dest != NULL )
95             memcpy( p_dest, *pp_src, i_buf_len );
96         *pp_src += i_buf_len;
97         return( i_buf_len );
98     }
99     else
100     {
101         size_t i_init_len = i_buf_len;
102
103         do
104         {
105             if( p_dest != NULL )
106                 memcpy( p_dest, *pp_src, i_available );
107             *pp_data_src = (*pp_data_src)->p_next;
108             i_buf_len -= i_available;
109             p_dest += i_available;
110             if( *pp_data_src == NULL )
111             {
112                 *pp_src = NULL;
113                 return( i_init_len - i_buf_len );
114             }
115             *pp_src = (*pp_data_src)->p_payload_start;
116
117             i_available = (ptrdiff_t)((*pp_data_src)->p_payload_end - *pp_src);
118         }
119         while( i_available <= i_buf_len );
120
121         if( i_buf_len )
122         {
123             if( p_dest != NULL )
124                 memcpy( p_dest, *pp_src, i_buf_len );
125             *pp_src += i_buf_len;
126         }
127         return( i_init_len );
128     }
129 }
130
131 /*****************************************************************************
132  * ParsePES
133  *****************************************************************************
134  * Parse a finished PES packet and analyze its header.
135  *****************************************************************************/
136 #define PES_HEADER_SIZE     7
137 static void ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
138 {
139     data_packet_t * p_data;
140     byte_t *        p_byte;
141     byte_t          p_header[PES_HEADER_SIZE];
142     int             i_done;
143
144 #define p_pes (p_es->p_pes)
145
146     /* Parse the header. The header has a variable length, but in order
147      * to improve the algorithm, we will read the 14 bytes we may be
148      * interested in */
149     p_data = p_pes->p_first;
150     p_byte = p_data->p_payload_start;
151     i_done = 0;
152
153     if( MoveChunk( p_header, &p_data, &p_byte, PES_HEADER_SIZE )
154             != PES_HEADER_SIZE )
155     {
156         msg_Warn( p_input, "PES packet too short to have a header" );
157         input_DeletePES( p_input->p_method_data, p_pes );
158         p_pes = NULL;
159         return;
160     }
161
162     /* Get the PES size if defined */
163     p_es->i_pes_real_size = U16_AT(p_header + 4);
164     if( p_es->i_pes_real_size )
165     {
166         p_es->i_pes_real_size += 6;
167     }
168
169     /* First read the 6 header bytes common to all PES packets:
170      * use them to test the PES validity */
171     if( (p_header[0] || p_header[1] || (p_header[2] != 1)) )
172     {
173         /* packet_start_code_prefix != 0x000001 */
174         msg_Err( p_input, "data loss, PES packet does not start with 000001" );
175         input_DeletePES( p_input->p_method_data, p_pes );
176         p_pes = NULL;
177     }
178     else
179     {
180         unsigned int i_pes_header_size, i_payload_size;
181
182         if ( p_es->i_pes_real_size &&
183              (p_es->i_pes_real_size != p_pes->i_pes_size) )
184         {
185             /* PES_packet_length is set and != total received payload */
186             /* Warn the decoder that the data may be corrupt. */
187             msg_Warn( p_input, "packet corrupted, PES sizes do not match" );
188         }
189
190         switch( p_header[3] )
191         {
192         case 0xBC:  /* Program stream map */
193         case 0xBE:  /* Padding */
194         case 0xBF:  /* Private stream 2 */
195         case 0xB0:  /* ECM */
196         case 0xB1:  /* EMM */
197         case 0xFF:  /* Program stream directory */
198         case 0xF2:  /* DSMCC stream */
199         case 0xF8:  /* ITU-T H.222.1 type E stream */
200             /* The payload begins immediately after the 6 bytes header, so
201              * we have finished with the parsing */
202             i_pes_header_size = 6;
203             break;
204
205         default:
206             if( (p_header[6] & 0xC0) == 0x80 )
207             {
208                 /* MPEG-2 : the PES header contains at least 3 more bytes. */
209                 size_t      i_max_len;
210                 vlc_bool_t  b_has_pts, b_has_dts;
211                 byte_t      p_full_header[12];
212
213                 p_pes->b_data_alignment = p_header[6] & 0x04;
214
215                 i_max_len = MoveChunk( p_full_header, &p_data, &p_byte, 12 );
216                 if( i_max_len < 2 )
217                 {
218                     msg_Warn( p_input,
219                               "PES packet too short to have a MPEG-2 header" );
220                     input_DeletePES( p_input->p_method_data,
221                                             p_pes );
222                     p_pes = NULL;
223                     return;
224                 }
225
226                 b_has_pts = p_full_header[0] & 0x80;
227                 b_has_dts = p_full_header[0] & 0x40;
228                 i_pes_header_size = p_full_header[1] + 9;
229
230                 /* Now parse the optional header extensions */
231                 if( b_has_pts )
232                 {
233                     if( i_max_len < 7 )
234                     {
235                         msg_Warn( p_input,
236                              "PES packet too short to have a MPEG-2 header" );
237                         input_DeletePES( p_input->p_method_data,
238                                                 p_pes );
239                         p_pes = NULL;
240                         return;
241                     }
242                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
243                     ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
244                       ((mtime_t)(p_full_header[3]) << 22) |
245                       ((mtime_t)(p_full_header[4] & 0xFE) << 14) |
246                       ((mtime_t)p_full_header[5] << 7) |
247                       ((mtime_t)p_full_header[6] >> 1) ) );
248
249                     if( b_has_dts )
250                     {
251                         if( i_max_len < 12 )
252                         {
253                             msg_Warn( p_input,
254                               "PES packet too short to have a MPEG-2 header" );
255                             input_DeletePES( p_input->p_method_data,
256                                                     p_pes );
257                             p_pes = NULL;
258                             return;
259                         }
260                         p_pes->i_dts = input_ClockGetTS( p_input, p_es->p_pgrm,
261                         ( ((mtime_t)(p_full_header[7] & 0x0E) << 29) |
262                           (((mtime_t)U16_AT(p_full_header + 8) << 14)
263                                 - (1 << 14)) |
264                           ((mtime_t)U16_AT(p_full_header + 10) >> 1) ) );
265                     }
266                 }
267             }
268             else
269             {
270                 /* Probably MPEG-1 */
271                 vlc_bool_t      b_has_pts, b_has_dts;
272
273                 i_pes_header_size = 6;
274                 p_data = p_pes->p_first;
275                 p_byte = p_data->p_payload_start;
276                 /* Cannot fail because the previous one succeeded. */
277                 MoveChunk( NULL, &p_data, &p_byte, 6 );
278
279                 while( *p_byte == 0xFF && i_pes_header_size < 23 )
280                 {
281                     i_pes_header_size++;
282                     if( MoveChunk( NULL, &p_data, &p_byte, 1 ) != 1 )
283                     {
284                         msg_Warn( p_input,
285                             "PES packet too short to have a MPEG-1 header" );
286                         input_DeletePES( p_input->p_method_data, p_pes );
287                         p_pes = NULL;
288                         return;
289                     }
290                 }
291                 if( i_pes_header_size == 23 )
292                 {
293                     msg_Err( p_input, "too much MPEG-1 stuffing" );
294                     input_DeletePES( p_input->p_method_data, p_pes );
295                     p_pes = NULL;
296                     return;
297                 }
298
299                 if( (*p_byte & 0xC0) == 0x40 )
300                 {
301                     /* Don't ask why... --Meuuh */
302                     /* Erm... why ? --Sam */
303                     /* Well... According to the recommendation, it is for
304                      * STD_buffer_scale and STD_buffer_size. --Meuuh */
305                     i_pes_header_size += 2;
306                     if( MoveChunk( NULL, &p_data, &p_byte, 2 ) != 2 )
307                     {
308                         msg_Warn( p_input,
309                             "PES packet too short to have a MPEG-1 header" );
310                         input_DeletePES( p_input->p_method_data, p_pes );
311                         p_pes = NULL;
312                         return;
313                     }
314                 }
315
316                 i_pes_header_size++;
317
318                 b_has_pts = *p_byte & 0x20;
319                 b_has_dts = *p_byte & 0x10;
320
321                 if( b_has_pts )
322                 {
323                     byte_t      p_ts[5];
324
325                     i_pes_header_size += 4;
326                     if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
327                     {
328                         msg_Warn( p_input,
329                             "PES packet too short to have a MPEG-1 header" );
330                         input_DeletePES( p_input->p_method_data, p_pes );
331                         p_pes = NULL;
332                         return;
333                     }
334
335                     p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
336                        ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
337                          (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
338                          ((mtime_t)p_ts[3] << 7) |
339                          ((mtime_t)p_ts[4] >> 1) ) );
340
341                     if( b_has_dts )
342                     {
343                         i_pes_header_size += 5;
344                         if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
345                         {
346                             msg_Warn( p_input,
347                               "PES packet too short to have a MPEG-1 header" );
348                             input_DeletePES( p_input->p_method_data, p_pes );
349                             p_pes = NULL;
350                             return;
351                         }
352
353                         p_pes->i_dts = input_ClockGetTS( p_input,
354                                                          p_es->p_pgrm,
355                             ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
356                               (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
357                               ((mtime_t)p_ts[3] << 7) |
358                               ((mtime_t)p_ts[4] >> 1) ) );
359                     }
360                 }
361             }
362
363             break;
364         }
365
366         /* Welcome to the kludge area ! --Meuuh */
367         if ( p_es->i_fourcc == VLC_FOURCC('a','5','2','b') )
368         {
369             /* With A/52 audio, we need to skip the first 4 bytes */
370             i_pes_header_size += 4;
371         }
372
373         if ( p_es->i_fourcc == VLC_FOURCC('l','p','c','b')
374               || p_es->i_fourcc == VLC_FOURCC('s','p','u','b')
375               || p_es->i_fourcc == VLC_FOURCC('d','t','s','b')
376               || p_es->i_fourcc == VLC_FOURCC('s','d','d','b') )
377         {
378             /* stream_private_id */
379             i_pes_header_size += 1;
380         }
381
382         /* Now we've parsed the header, we just have to indicate in some
383          * specific data packets where the PES payload begins (renumber
384          * p_payload_start), so that the decoders can find the beginning
385          * of their data right out of the box. */
386         p_data = p_pes->p_first;
387         i_payload_size = p_data->p_payload_end
388                                  - p_data->p_payload_start;
389         while( i_pes_header_size > i_payload_size )
390         {
391             /* These packets are entirely filled by the PES header. */
392             i_pes_header_size -= i_payload_size;
393             p_data->p_payload_start = p_data->p_payload_end;
394             /* Go to the next data packet. */
395             if( (p_data = p_data->p_next) == NULL )
396             {
397                 msg_Err( p_input, "PES header bigger than payload" );
398                 input_DeletePES( p_input->p_method_data, p_pes );
399                 p_pes = NULL;
400                 return;
401             }
402             i_payload_size = p_data->p_payload_end
403                                  - p_data->p_payload_start;
404         }
405         /* This last packet is partly header, partly payload. */
406         if( i_payload_size < i_pes_header_size )
407         {
408             msg_Err( p_input, "PES header bigger than payload" );
409             input_DeletePES( p_input->p_method_data, p_pes );
410             p_pes = NULL;
411             return;
412         }
413         p_data->p_payload_start += i_pes_header_size;
414
415
416         /* Now we can eventually put the PES packet in the decoder's
417          * PES fifo */
418         if( p_es->p_decoder_fifo != NULL )
419         {
420             input_DecodePES( p_es->p_decoder_fifo, p_pes );
421         }
422         else
423         {
424             msg_Err( p_input, "no fifo to receive PES %p "
425                               "(who wrote this damn code ?)", p_pes );
426             input_DeletePES( p_input->p_method_data, p_pes );
427         }
428         p_pes = NULL;
429     }
430 #undef p_pes
431
432 }
433
434 /*****************************************************************************
435  * GatherPES:
436  *****************************************************************************
437  * Gather a PES packet.
438  *****************************************************************************/
439 static void GatherPES( input_thread_t * p_input, data_packet_t * p_data,
440                        es_descriptor_t * p_es,
441                        vlc_bool_t b_unit_start, vlc_bool_t b_packet_lost )
442 {
443 #define p_pes (p_es->p_pes)
444
445     /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
446      * often an escape sequence in decoders, so that should make them wait
447      * for the next start code). */
448     if( b_packet_lost )
449     {
450         input_NullPacket( p_input, p_es );
451     }
452
453     if( b_unit_start && p_pes != NULL )
454     {
455         /* If the data packet contains the begining of a new PES packet, and
456          * if we were reassembling a PES packet, then the PES should be
457          * complete now, so parse its header and give it to the decoders. */
458         ParsePES( p_input, p_es );
459     }
460
461     if( !b_unit_start && p_pes == NULL )
462     {
463         /* Random access... */
464         input_DeletePacket( p_input->p_method_data, p_data );
465     }
466     else
467     {
468         if( b_unit_start )
469         {
470             /* If we are at the beginning of a new PES packet, we must fetch
471              * a new PES buffer to begin with the reassembly of this PES
472              * packet. This is also here that we can synchronize with the
473              * stream if we lost packets or if the decoder has just
474              * started. */
475             if( (p_pes = input_NewPES( p_input->p_method_data ) ) == NULL )
476             {
477                 msg_Err( p_input, "out of memory" );
478                 p_input->b_error = 1;
479                 return;
480             }
481             p_pes->i_rate = p_input->stream.control.i_rate;
482             p_pes->p_first = p_data;
483
484             /* If the PES header fits in the first data packet, we can
485              * already set p_gather->i_pes_real_size. */
486             if( p_data->p_payload_end - p_data->p_payload_start
487                     >= PES_HEADER_SIZE )
488             {
489                 p_es->i_pes_real_size = ((u16)p_data->p_payload_start[4] << 8)
490                                          + p_data->p_payload_start[5];
491                 if ( p_es->i_pes_real_size )
492                 {
493                     p_es->i_pes_real_size += 6;
494                 }
495             }
496             else
497             {
498                 p_es->i_pes_real_size = 0;
499             }
500         }
501         else
502         {
503             /* Update the relations between the data packets */
504             p_pes->p_last->p_next = p_data;
505         }
506
507         p_pes->p_last = p_data;
508         p_pes->i_nb_data++;
509
510         /* Size of the payload carried in the data packet */
511         p_pes->i_pes_size += (p_data->p_payload_end
512                                  - p_data->p_payload_start);
513
514         /* We can check if the packet is finished */
515         if( p_es->i_pes_real_size  && p_pes->i_pes_size >= p_es->i_pes_real_size )
516         {
517             if( p_pes->i_pes_size > p_es->i_pes_real_size )
518             {
519                 msg_Warn( p_input,
520                           "Oversized PES packet for PID %d: expected %d, actual %d",
521                           p_es->i_id, p_es->i_pes_real_size, p_pes->i_pes_size );
522             }
523             /* The packet is finished, parse it */
524             ParsePES( p_input, p_es );
525         }
526     }
527 #undef p_pes
528 }
529
530
531 /*
532  * PS Demultiplexing
533  */
534
535 /*****************************************************************************
536  * GetID: Get the ID of a stream
537  *****************************************************************************/
538 static u16 GetID( data_packet_t * p_data )
539 {
540     u16         i_id;
541
542     i_id = p_data->p_demux_start[3];                            /* stream_id */
543     if( i_id == 0xBD )
544     {
545         /* FIXME : this is not valid if the header is split in multiple
546          * packets */
547         /* stream_private_id */
548         i_id |= p_data->p_demux_start[ 9 + p_data->p_demux_start[8] ] << 8;
549     }
550     return( i_id );
551 }
552
553 /*****************************************************************************
554  * DecodePSM: Decode the Program Stream Map information
555  *****************************************************************************
556  * FIXME : loads are not aligned in this function
557  *****************************************************************************/
558 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
559 {
560     stream_ps_data_t *  p_demux =
561                  (stream_ps_data_t *)p_input->stream.p_demux_data;
562     byte_t *            p_byte;
563     byte_t *            p_end;
564     unsigned int        i;
565     unsigned int        i_new_es_number = 0;
566
567     if( p_data->p_demux_start + 10 > p_data->p_payload_end )
568     {
569         msg_Err( p_input, "PSM too short, packet corrupt" );
570         return;
571     }
572
573     if( p_demux->b_has_PSM
574         && p_demux->i_PSM_version == (p_data->p_demux_start[6] & 0x1F) )
575     {
576         /* Already got that one. */
577         return;
578     }
579
580     p_demux->b_has_PSM = 1;
581     p_demux->i_PSM_version = p_data->p_demux_start[6] & 0x1F;
582
583     /* Go to elementary_stream_map_length, jumping over
584      * program_stream_info. */
585     p_byte = p_data->p_demux_start + 10
586               + U16_AT(&p_data->p_demux_start[8]);
587     if( p_byte > p_data->p_payload_end )
588     {
589         msg_Err( p_input, "PSM too short, packet corrupt" );
590         return;
591     }
592     /* This is the full size of the elementary_stream_map.
593      * 2 == elementary_stream_map_length
594      * Please note that CRC_32 is not included in the length. */
595     p_end = p_byte + 2 + U16_AT(p_byte);
596     p_byte += 2;
597     if( p_end > p_data->p_payload_end )
598     {
599         msg_Err( p_input, "PSM too short, packet corrupt" );
600         return;
601     }
602
603     vlc_mutex_lock( &p_input->stream.stream_lock );
604
605     /* 4 == minimum useful size of a section */
606     while( p_byte + 4 <= p_end )
607     {
608         es_descriptor_t *   p_es = NULL;
609         uint8_t             i_stream_id = p_byte[1];
610         /* FIXME: there will be a problem with private streams... (same
611          * stream_id) */
612
613         /* Look for the ES in the ES table */
614         for( i = i_new_es_number;
615              i < p_input->stream.pp_programs[0]->i_es_number;
616              i++ )
617         {
618             if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
619                     == i_stream_id )
620             {
621                 p_es = p_input->stream.pp_programs[0]->pp_es[i];
622                 /* FIXME: do something below */
623 #if 0
624                 if( p_es->i_type != p_byte[0] )
625                 {
626                     input_DelES( p_input, p_es );
627                     p_es = NULL;
628                 }
629                 else
630 #endif
631                 {
632                     /* Move the ES to the beginning. */
633                     p_input->stream.pp_programs[0]->pp_es[i]
634                         = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
635                     p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
636                         = p_es;
637                     i_new_es_number++;
638                 }
639                 break;
640             }
641         }
642
643         /* The goal is to have all the ES we have just read in the
644          * beginning of the pp_es table, and all the others at the end,
645          * so that we can close them more easily at the end. */
646         if( p_es == NULL )
647         {
648             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
649                                 i_stream_id, 0 );
650             switch( p_byte[0] )
651             {
652             case MPEG1_VIDEO_ES:
653             case MPEG2_VIDEO_ES:
654             case MPEG2_MOTO_VIDEO_ES:
655                 p_es->i_fourcc = VLC_FOURCC('m','p','g','v');
656                 p_es->i_cat = VIDEO_ES;
657                 break;
658             case DVD_SPU_ES:
659                 p_es->i_fourcc = VLC_FOURCC('s','p','u','b');
660                 p_es->i_cat = SPU_ES;
661                 break;
662             case MPEG1_AUDIO_ES:
663             case MPEG2_AUDIO_ES:
664                 p_es->i_fourcc = VLC_FOURCC('m','p','g','a');
665                 p_es->i_cat = AUDIO_ES;
666                 break;
667             case A52_AUDIO_ES:
668             case A52DVB_AUDIO_ES:
669                 p_es->i_fourcc = VLC_FOURCC('a','5','2','b');
670                 p_es->i_cat = AUDIO_ES;
671                 break;
672             case LPCM_AUDIO_ES:
673                 p_es->i_fourcc = VLC_FOURCC('l','p','c','b');
674                 p_es->i_cat = AUDIO_ES;
675                 break;
676             default:
677                 p_es->i_fourcc = 0;
678                 break;
679             }
680
681             /* input_AddES has inserted the new element at the end. */
682             p_input->stream.pp_programs[0]->pp_es[
683                 p_input->stream.pp_programs[0]->i_es_number ]
684                 = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
685             p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
686             i_new_es_number++;
687         }
688         p_byte += 4 + U16_AT(&p_byte[2]);
689     }
690
691     /* Un-select the streams that are no longer parts of the program. */
692     while( i_new_es_number < p_input->stream.pp_programs[0]->i_es_number )
693     {
694         /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
695          * list will be emptied starting from the end */
696         input_DelES( p_input,
697                      p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
698     }
699
700     msg_Dbg( p_input, "the stream map after the PSM is now:" );
701     input_DumpStream( p_input );
702
703     vlc_mutex_unlock( &p_input->stream.stream_lock );
704 }
705
706 /*****************************************************************************
707  * ReadPS: store a PS packet into a data_buffer_t
708  *****************************************************************************/
709 #define PEEK( SIZE )                                                        \
710     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
711     if( i_error == -1 )                                                     \
712     {                                                                       \
713         return( -1 );                                                       \
714     }                                                                       \
715     else if( (size_t)i_error < SIZE )                                       \
716     {                                                                       \
717         /* EOF */                                                           \
718         return( 0 );                                                        \
719     }
720
721 static ssize_t ReadPS( input_thread_t * p_input, data_packet_t ** pp_data )
722 {
723     byte_t *            p_peek;
724     size_t              i_packet_size;
725     ssize_t             i_error, i_read;
726
727     /* Read what we believe to be a packet header. */
728     PEEK( 4 );
729
730     if( p_peek[0] || p_peek[1] || p_peek[2] != 1 || p_peek[3] < 0xB9 )
731     {
732         if( p_peek[0] || p_peek[1] || p_peek[2] )
733         {
734             /* It is common for MPEG-1 streams to pad with zeros
735              * (although it is forbidden by the recommendation), so
736              * don't bother everybody in this case. */
737             msg_Warn( p_input, "garbage (0x%.2x%.2x%.2x%.2x)",
738                       p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
739         }
740
741         /* This is not the startcode of a packet. Read the stream
742          * until we find one. */
743         while( p_peek[0] || p_peek[1] || p_peek[2] != 1 || p_peek[3] < 0xB9 )
744         {
745             p_input->p_current_data++;
746             PEEK( 4 );
747             if( p_input->b_die ) return( -1 );
748         }
749         /* Packet found. */
750     }
751
752     /* 0x1B9 == SYSTEM_END_CODE, it is only 4 bytes long. */
753     if( p_peek[3] != 0xB9 )
754     {
755         /* The packet is at least 6 bytes long. */
756         PEEK( 6 );
757
758         if( p_peek[3] != 0xBA )
759         {
760             /* That's the case for all packets, except pack header. */
761             i_packet_size = (p_peek[4] << 8) | p_peek[5];
762         }
763         else
764         {
765             /* Pack header. */
766             if( (p_peek[4] & 0xC0) == 0x40 )
767             {
768                 /* MPEG-2 */
769                 i_packet_size = 8;
770             }
771             else if( (p_peek[4] & 0xF0) == 0x20 )
772             {
773                 /* MPEG-1 */
774                 i_packet_size = 6;
775             }
776             else
777             {
778                 msg_Err( p_input, "unable to determine stream type" );
779                 return( -1 );
780             }
781         }
782     }
783     else
784     {
785         /* System End Code */
786         i_packet_size = -2;
787     }
788
789     /* Fetch a packet of the appropriate size. */
790     i_read = input_SplitBuffer( p_input, pp_data, i_packet_size + 6 );
791     if( i_read <= 0 )
792     {
793         return( i_read );
794     }
795
796     /* In MPEG-2 pack headers we still have to read stuffing bytes. */
797     if( ((*pp_data)->p_demux_start[3] == 0xBA) && (i_packet_size == 8) )
798     {
799         size_t i_stuffing = ((*pp_data)->p_demux_start[13] & 0x7);
800         /* Force refill of the input buffer - though we don't care
801          * about p_peek. Please note that this is unoptimized. */
802         PEEK( i_stuffing );
803         p_input->p_current_data += i_stuffing;
804     }
805
806     return( 1 );
807 }
808
809 #undef PEEK
810
811 /*****************************************************************************
812  * ParsePS: read the PS header
813  *****************************************************************************/
814 static es_descriptor_t * ParsePS( input_thread_t * p_input,
815                                   data_packet_t * p_data )
816 {
817     uint32_t            i_code;
818     es_descriptor_t *   p_es = NULL;
819
820     i_code = p_data->p_demux_start[3];
821
822     if( i_code > 0xBC ) /* ES start code */
823     {
824         uint16_t            i_id;
825         unsigned int        i_dummy;
826
827         /* This is a PES packet. Find out if we want it or not. */
828         i_id = GetID( p_data );
829
830         vlc_mutex_lock( &p_input->stream.stream_lock );
831         if( p_input->stream.pp_programs[0]->b_is_ok )
832         {
833             /* Look only at the selected ES. */
834             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
835                  i_dummy++ )
836             {
837                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
838                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
839                 {
840                     p_es = p_input->stream.pp_selected_es[i_dummy];
841                     break;
842                 }
843             }
844         }
845         else
846         {
847             stream_ps_data_t * p_demux =
848               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
849
850             /* Search all ES ; if not found -> AddES */
851             p_es = input_FindES( p_input, i_id );
852
853             if( p_es == NULL && !p_demux->b_has_PSM )
854             {
855                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
856                                     i_id, 0 );
857                 if( p_es != NULL )
858                 {
859                     p_es->i_stream_id = p_data->p_demux_start[3];
860
861                     /* Set stream type and auto-spawn. */
862                     if( (i_id & 0xF0) == 0xE0 )
863                     {
864                         /* MPEG video */
865                         p_es->i_fourcc = VLC_FOURCC('m','p','g','v');
866                         p_es->i_cat = VIDEO_ES;
867 #ifdef AUTO_SPAWN
868                         if( !p_input->stream.b_seekable )
869                             input_SelectES( p_input, p_es );
870 #endif
871                     }
872                     else if( (i_id & 0xE0) == 0xC0 )
873                     {
874                         /* MPEG audio */
875                         p_es->i_fourcc = VLC_FOURCC('m','p','g','a');
876                         p_es->i_cat = AUDIO_ES;
877 #ifdef AUTO_SPAWN
878                         if( !p_input->stream.b_seekable )
879                         if( config_GetInt( p_input, "audio-channel" )
880                                 == (p_es->i_id & 0x1F) ||
881                             ( config_GetInt( p_input, "audio-channel" ) < 0
882                               && !(p_es->i_id & 0x1F) ) )
883                         switch( config_GetInt( p_input, "audio-type" ) )
884                         {
885                         case -1:
886                         case REQUESTED_MPEG:
887                             input_SelectES( p_input, p_es );
888                         }
889 #endif
890                     }
891                     else if( (i_id & 0xF8FF) == 0x88BD )
892                     {
893                         p_es->i_fourcc = VLC_FOURCC('d','t','s','b');
894                         p_es->i_cat = AUDIO_ES;
895 #ifdef AUTO_SPAWN
896                         if( !p_input->stream.b_seekable )
897                         if( config_GetInt( p_input, "audio-channel" )
898                                 == ((p_es->i_id & 0x700) >> 8) ||
899                             ( config_GetInt( p_input, "audio-channel" ) < 0
900                               && !((p_es->i_id & 0x700) >> 8)) )
901                         switch( config_GetInt( p_input, "audio-type" ) )
902                         {
903                         case -1:
904                         case REQUESTED_DTS:
905                             input_SelectES( p_input, p_es );
906                         }
907 #endif
908                     }
909                     else if( (i_id & 0xF0FF) == 0x80BD )
910                     {
911                         /* A52 audio (0x80->0x8F) */
912                         p_es->i_fourcc = VLC_FOURCC('a','5','2','b');
913                         p_es->i_cat = AUDIO_ES;
914 #ifdef AUTO_SPAWN
915                         if( !p_input->stream.b_seekable )
916                         if( config_GetInt( p_input, "audio-channel" )
917                                 == ((p_es->i_id & 0xF00) >> 8) ||
918                             ( config_GetInt( p_input, "audio-channel" ) < 0
919                               && !((p_es->i_id & 0xF00) >> 8)) )
920                         switch( config_GetInt( p_input, "audio-type" ) )
921                         {
922                         case -1:
923                         case REQUESTED_A52:
924                             input_SelectES( p_input, p_es );
925                         }
926 #endif
927                     }
928                     else if( (i_id & 0xE0FF) == 0x20BD )
929                     {
930                         /* Subtitles video (0x20->0x3F) */
931                         p_es->i_fourcc = VLC_FOURCC('s','p','u','b');
932                         p_es->i_cat = SPU_ES;
933 #ifdef AUTO_SPAWN
934                         if( config_GetInt( p_input, "spu-channel" )
935                                 == ((p_es->i_id & 0x1F00) >> 8) )
936                         {
937                             if( !p_input->stream.b_seekable )
938                                 input_SelectES( p_input, p_es );
939                         }
940 #endif
941                     }
942                     else if( (i_id & 0xF0FF) == 0xA0BD )
943                     {
944                         /* LPCM audio (0xA0->0xAF) */
945                         p_es->i_fourcc = VLC_FOURCC('l','p','c','b');
946                         p_es->i_cat = AUDIO_ES;
947                     }
948                     else
949                     {
950                         p_es->i_fourcc = 0;
951                     }
952                 }
953
954                 /* Tell the interface the stream has changed */
955                 p_input->stream.b_changed = 1;
956             }
957         } /* stream.b_is_ok */
958         vlc_mutex_unlock( &p_input->stream.stream_lock );
959     } /* i_code > 0xBC */
960
961     return( p_es );
962 }
963
964 /*****************************************************************************
965  * DemuxPS: first step of demultiplexing: the PS header
966  *****************************************************************************/
967 static void DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
968 {
969     u32                 i_code;
970     vlc_bool_t          b_trash = 0;
971     es_descriptor_t *   p_es = NULL;
972
973     i_code = ((u32)p_data->p_demux_start[0] << 24)
974                 | ((u32)p_data->p_demux_start[1] << 16)
975                 | ((u32)p_data->p_demux_start[2] << 8)
976                 | p_data->p_demux_start[3];
977     if( i_code <= 0x1BC )
978     {
979         switch( i_code )
980         {
981         case 0x1BA: /* PACK_START_CODE */
982             {
983                 /* Read the SCR. */
984                 mtime_t         scr_time;
985                 u32             i_mux_rate;
986
987                 if( (p_data->p_demux_start[4] & 0xC0) == 0x40 )
988                 {
989                     /* MPEG-2 */
990                     byte_t      p_header[14];
991                     byte_t *    p_byte;
992                     p_byte = p_data->p_demux_start;
993
994                     if( MoveChunk( p_header, &p_data, &p_byte, 14 ) != 14 )
995                     {
996                         msg_Warn( p_input,
997                                   "packet too short to have a header" );
998                         b_trash = 1;
999                         break;
1000                     }
1001                     scr_time =
1002                          ((mtime_t)(p_header[4] & 0x38) << 27) |
1003                          ((mtime_t)(U32_AT(p_header + 4) & 0x03FFF800)
1004                                         << 4) |
1005                          ((( ((mtime_t)U16_AT(p_header + 6) << 16)
1006                             | (mtime_t)U16_AT(p_header + 8) ) & 0x03FFF800)
1007                                         >> 11);
1008
1009                     /* mux_rate */
1010                     i_mux_rate = ((u32)U16_AT(p_header + 10) << 6)
1011                                    | (p_header[12] >> 2);
1012                     /* FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1013                      * This is the biggest kludge ever !
1014                      * I don't know what's wrong with mux_rate calculation
1015                      * but this heuristic works well : */
1016                     i_mux_rate <<= 1;
1017                     i_mux_rate /= 3;
1018                 }
1019                 else
1020                 {
1021                     /* MPEG-1 SCR is like PTS. */
1022                     byte_t      p_header[12];
1023                     byte_t *    p_byte;
1024                     p_byte = p_data->p_demux_start;
1025
1026                     if( MoveChunk( p_header, &p_data, &p_byte, 12 ) != 12 )
1027                     {
1028                         msg_Warn( p_input,
1029                                   "packet too short to have a header" );
1030                         b_trash = 1;
1031                         break;
1032                     }
1033                     scr_time =
1034                          ((mtime_t)(p_header[4] & 0x0E) << 29) |
1035                          (((mtime_t)U32_AT(p_header + 4) & 0xFFFE00) << 6) |
1036                          ((mtime_t)p_header[7] << 7) |
1037                          ((mtime_t)p_header[8] >> 1);
1038
1039                     /* mux_rate */
1040                     i_mux_rate = (U32_AT(p_header + 8) & 0x7FFFFE) >> 1;
1041                 }
1042                 /* Call the pace control. */
1043                 input_ClockManageRef( p_input,
1044                                       p_input->stream.p_selected_program,
1045                                       scr_time );
1046
1047                 if( i_mux_rate != p_input->stream.i_mux_rate
1048                      && p_input->stream.i_mux_rate )
1049                 {
1050                     msg_Warn( p_input,
1051                               "mux_rate changed, expect cosmetic errors" );
1052                 }
1053                 p_input->stream.i_mux_rate = i_mux_rate;
1054
1055                 b_trash = 1;
1056             }
1057             break;
1058
1059         case 0x1BB: /* SYSTEM_START_CODE */
1060             b_trash = 1;                              /* Nothing interesting */
1061             break;
1062
1063         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
1064             DecodePSM( p_input, p_data );
1065             b_trash = 1;
1066             break;
1067
1068         case 0x1B9: /* PROGRAM_END_CODE */
1069             b_trash = 1;
1070             break;
1071
1072         default:
1073             /* This should not happen */
1074             b_trash = 1;
1075             msg_Warn( p_input, "unwanted packet received "
1076                                "with startcode 0x%.8x", i_code );
1077         }
1078     }
1079     else
1080     {
1081         p_es = ParsePS( p_input, p_data );
1082
1083         vlc_mutex_lock( &p_input->stream.control.control_lock );
1084         if( p_es != NULL && p_es->p_decoder_fifo != NULL
1085              && (p_es->i_cat != AUDIO_ES || !p_input->stream.control.b_mute) )
1086         {
1087             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1088             p_es->c_packets++;
1089             GatherPES( p_input, p_data, p_es, 1, 0 );
1090         }
1091         else
1092         {
1093             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1094             b_trash = 1;
1095         }
1096     }
1097
1098     /* Trash the packet if it has no payload or if it isn't selected */
1099     if( b_trash )
1100     {
1101         input_DeletePacket( p_input->p_method_data, p_data );
1102         p_input->stream.c_packets_trashed++;
1103     }
1104 }
1105
1106
1107 /*
1108  * TS Demultiplexing
1109  */
1110
1111 /*****************************************************************************
1112  * ReadTS: store a TS packet into a data_buffer_t
1113  *****************************************************************************/
1114 #define PEEK( SIZE )                                                        \
1115     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
1116     if( i_error == -1 )                                                     \
1117     {                                                                       \
1118         return( -1 );                                                       \
1119     }                                                                       \
1120     else if( i_error < SIZE )                                               \
1121     {                                                                       \
1122         /* EOF */                                                           \
1123         return( 0 );                                                        \
1124     }
1125
1126 static ssize_t ReadTS( input_thread_t * p_input, data_packet_t ** pp_data )
1127 {
1128     byte_t *            p_peek;
1129     ssize_t             i_error, i_read;
1130
1131     PEEK( 1 );
1132
1133     if( *p_peek != TS_SYNC_CODE )
1134     {
1135         msg_Warn( p_input, "garbage at input (%x)", *p_peek );
1136
1137         if( p_input->i_mtu )
1138         {
1139             while( *p_peek != TS_SYNC_CODE )
1140             {
1141                 /* Try to resync on next packet. */
1142                 PEEK( TS_PACKET_SIZE );
1143                 p_input->p_current_data += TS_PACKET_SIZE;
1144                 PEEK( 1 );
1145             }
1146         }
1147         else
1148         {
1149             /* Move forward until we find 0x47 (and hope it's the good
1150              * one... FIXME) */
1151             while( *p_peek != TS_SYNC_CODE )
1152             {
1153                 p_input->p_current_data++;
1154                 PEEK( 1 );
1155             }
1156         }
1157     }
1158
1159     i_read = input_SplitBuffer( p_input, pp_data, TS_PACKET_SIZE );
1160     if( i_read <= 0 )
1161     {
1162         return( i_read );
1163     }
1164
1165     return( 1 );
1166 }
1167
1168 /*****************************************************************************
1169  * DemuxTS: first step of demultiplexing: the TS header
1170  *****************************************************************************/
1171 static void DemuxTS( input_thread_t * p_input, data_packet_t * p_data,
1172                      psi_callback_t pf_psi_callback )
1173 {
1174     uint16_t            i_pid;
1175     unsigned int        i_dummy;
1176     vlc_bool_t          b_adaptation;         /* Adaptation field is present */
1177     vlc_bool_t          b_payload;                 /* Packet carries payload */
1178     vlc_bool_t          b_unit_start;  /* A PSI or a PES start in the packet */
1179     vlc_bool_t          b_trash = 0;             /* Is the packet unuseful ? */
1180     vlc_bool_t          b_lost = 0;             /* Was there a packet loss ? */
1181     vlc_bool_t          b_psi = 0;                        /* Is this a PSI ? */
1182     vlc_bool_t          b_pcr = 0;                   /* Does it have a PCR ? */
1183     es_descriptor_t *   p_es = NULL;
1184     es_ts_data_t *      p_es_demux = NULL;
1185     pgrm_ts_data_t *    p_pgrm_demux = NULL;
1186     stream_ts_data_t *  p_stream_demux =
1187                           (stream_ts_data_t *)p_input->stream.p_demux_data;
1188
1189 #define p (p_data->p_demux_start)
1190     /* Extract flags values from TS common header. */
1191     i_pid = ((p[1] & 0x1F) << 8) | p[2];
1192     b_unit_start = (p[1] & 0x40);
1193     b_adaptation = (p[3] & 0x20);
1194     b_payload = (p[3] & 0x10);
1195
1196     /* Was there a transport error ? */
1197     if ( p[1] & 0x80 )
1198     {
1199         msg_Warn( p_input, "transport_error_indicator set for PID %d counter %x", i_pid, p[3] & 0x0f );
1200     }
1201
1202     /* Find out the elementary stream. */
1203     vlc_mutex_lock( &p_input->stream.stream_lock );
1204
1205     for( i_dummy = 0; i_dummy < p_input->stream.i_pgrm_number; i_dummy ++ )
1206     {
1207         if( (( pgrm_ts_data_t * ) p_input->stream.pp_programs[i_dummy]->
1208                     p_demux_data)->i_pcr_pid == i_pid )
1209         {
1210             b_pcr = 1;
1211             break;
1212         }
1213     }
1214
1215     p_es = input_FindES( p_input, i_pid );
1216
1217     if( (p_es != NULL) && (p_es->p_demux_data != NULL) )
1218     {
1219         p_es_demux = (es_ts_data_t *)p_es->p_demux_data;
1220
1221         if( p_es_demux->b_psi )
1222         {
1223             b_psi = 1;
1224         }
1225         else
1226         {
1227             p_pgrm_demux = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data;
1228         }
1229     }
1230
1231     vlc_mutex_lock( &p_input->stream.control.control_lock );
1232     if( ( p_es == NULL ) || (p_es->i_cat == AUDIO_ES
1233                               && p_input->stream.control.b_mute) )
1234     {
1235         /* Not selected. Just read the adaptation field for a PCR. */
1236         b_trash = 1;
1237     }
1238     else if( p_es->p_decoder_fifo == NULL && !b_psi )
1239     {
1240         b_trash = 1;
1241     }
1242
1243     vlc_mutex_unlock( &p_input->stream.control.control_lock );
1244     vlc_mutex_unlock( &p_input->stream.stream_lock );
1245
1246
1247     /* Don't change the order of the tests : if b_psi then p_pgrm_demux
1248      * may still be null. Who said it was ugly ?
1249      * I have written worse. --Meuuh */
1250     if( ( p_es ) &&
1251         ((p_es->p_decoder_fifo != NULL) || b_psi || b_pcr ) )
1252     {
1253         p_es->c_packets++;
1254
1255         /* Extract adaptation field information if any */
1256
1257         if( !b_adaptation )
1258         {
1259             /* We don't have any adaptation_field, so payload starts
1260              * immediately after the 4 byte TS header */
1261             p_data->p_payload_start += 4;
1262         }
1263         else
1264         {
1265             /* p[4] is adaptation_field_length minus one */
1266             p_data->p_payload_start += 5 + p[4];
1267
1268             /* The adaptation field can be limited to the
1269              * adaptation_field_length byte, so that there is nothing to do:
1270              * skip this possibility */
1271             if( p[4] )
1272             {
1273                 /* If the packet has both adaptation_field and payload,
1274                  * adaptation_field cannot be more than 182 bytes long; if
1275                  * there is only an adaptation_field, it must fill the next
1276                  * 183 bytes. */
1277                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1278                 {
1279                     msg_Warn( p_input, "invalid TS adaptation field for PID %d (%2x)",
1280                               i_pid, p[4] );
1281                     p_data->b_discard_payload = 1;
1282                     p_es->c_invalid_packets++;
1283
1284                     /* The length was invalid so we shouldn't have added it to
1285                      * p_payload_start above.  Ensure p_payload_start has a
1286                      * valid value by setting it equal to p_payload_end.  This
1287                      * also stops any data being processed from the packet.
1288                      */
1289                     p_data->p_payload_start = p_data->p_payload_end;
1290                 }
1291
1292                 /* Now we are sure that the byte containing flags is present:
1293                  * read it */
1294                 else
1295                 {
1296                     /* discontinuity_indicator */
1297                     if( p[5] & 0x80 )
1298                     {
1299                         msg_Warn( p_input,
1300                             "discontinuity_indicator encountered by TS demux "
1301                             "(PID %d: current %d, packet %d)",
1302                             i_pid,
1303                             ( p_es_demux->i_continuity_counter ) & 0x0f,
1304                             p[3] & 0x0f );
1305
1306                         /* If the PID carries the PCR, there will be a system
1307                          * time-based discontinuity. We let the PCR decoder
1308                          * handle that. */
1309                         p_es->p_pgrm->i_synchro_state = SYNCHRO_REINIT;
1310
1311                         /* Don't resynchronise the counter here - it will
1312                          * be checked later and b_lost will then be set if
1313                          * necessary.
1314                          */
1315                     }
1316
1317                 } /* valid TS adaptation field ? */
1318             } /* length > 0 */
1319         } /* has adaptation field */
1320         /* Check the continuity of the stream. */
1321         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1322         if( b_payload &&
1323                 ( i_dummy == 1 || (b_psi && p_stream_demux->b_buggy_psi ) ) )
1324         {
1325             /* Everything is ok, just increase our counter */
1326             (p_es_demux->i_continuity_counter)++;
1327         }
1328         else
1329         {
1330             if( !b_payload && i_dummy == 0 )
1331             {
1332                 /* This is a packet without payload, this is allowed by the
1333                  * draft. As there is nothing interesting in this packet
1334                  * (except PCR that have already been handled), we can trash
1335                  * the packet. */
1336                 b_trash = 1;
1337             }
1338             else if( !b_payload )
1339             {
1340                 /* If there is no payload, the counter should be unchanged */
1341                 msg_Warn( p_input, "packet rxd for PID %d with no payload but "
1342                         "wrong counter: current %d, packet %d", i_pid,
1343                         p_es_demux->i_continuity_counter & 0x0f, p[3] & 0x0f );
1344             }
1345             else if( i_dummy <= 0 )
1346             {
1347                 /* Duplicate packet: mark it as being to be trashed. */
1348                 msg_Warn( p_input,
1349                           "duplicate packet received for PID %d (counter %d)",
1350                           p_es->i_id, p[3] & 0x0f );
1351                 b_trash = 1;
1352             }
1353             else if( p_es_demux->i_continuity_counter == 0xFF )
1354             {
1355                 /* This means that the packet is the first one we receive for
1356                  * this ES since the continuity counter ranges between 0 and
1357                  * 0x0F excepts when it has been initialized by the input:
1358                  * init the counter to the correct value. */
1359                 msg_Warn( p_input, "first packet for PID %d received "
1360                                    "by TS demux", p_es->i_id );
1361                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1362             }
1363             else
1364             {
1365                 /* This can indicate that we missed a packet or that the
1366                  * continuity_counter wrapped and we received a dup packet:
1367                  * as we don't know, do as if we missed a packet to be sure
1368                  * to recover from this situation */
1369                 msg_Warn( p_input,
1370                           "packet lost by TS demux for PID %d: current %d, packet %d",
1371                           i_pid,
1372                           p_es_demux->i_continuity_counter & 0x0f,
1373                           p[3] & 0x0f );
1374                 b_lost = 1;
1375                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1376             } /* not continuous */
1377         } /* continuity */
1378     } /* if selected or PCR */
1379
1380     /* Handle PCR */
1381     if( b_pcr && b_adaptation && (p[5] & 0x10) && p[4]>=7 )
1382     {
1383         /* Read the PCR. */
1384         mtime_t     pcr_time;
1385         pcr_time = ( (mtime_t)p[6] << 25 ) |
1386                    ( (mtime_t)p[7] << 17 ) |
1387                    ( (mtime_t)p[8] << 9 ) |
1388                    ( (mtime_t)p[9] << 1 ) |
1389                    ( (mtime_t)p[10] >> 7 );
1390         /* Call the pace control. */
1391         for( i_dummy = 0; i_dummy < p_input->stream.i_pgrm_number;
1392                                 i_dummy ++ )
1393         {
1394             if( ( ( pgrm_ts_data_t * ) p_input->stream.pp_programs[i_dummy]->
1395                         p_demux_data )->i_pcr_pid == i_pid )
1396             {
1397                 input_ClockManageRef( p_input,
1398                     p_input->stream.pp_programs[i_dummy], pcr_time );
1399             }
1400         }
1401
1402     }
1403
1404     /* Trash the packet if it has no payload or if it isn't selected */
1405     if( b_trash )
1406     {
1407         input_DeletePacket( p_input->p_method_data, p_data );
1408         p_input->stream.c_packets_trashed++;
1409     }
1410     else
1411     {
1412         if( b_psi )
1413         {
1414             /* The payload contains PSI tables */
1415             (* pf_psi_callback) ( p_input, p_data, p_es, b_unit_start );
1416         }
1417         else
1418         {
1419             /* The payload carries a PES stream */
1420             GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
1421         }
1422
1423     }
1424
1425 #undef p
1426
1427 }
1428