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