]> git.sesse.net Git - vlc/blob - modules/demux/mpeg/system.c
3cd3154300b9eeaf1604013f3d0a3aa9f976c3b9
[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.17 2003/09/10 11:51:00 fenrir 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_Err( 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_Err( 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         {
368             /* With A/52 audio, we need to skip the first 4 bytes */
369             i_pes_header_size += 4;
370         }
371
372         if ( p_es->i_fourcc == VLC_FOURCC('l','p','c','b')
373               || p_es->i_fourcc == VLC_FOURCC('s','p','u','b')
374               || p_es->i_fourcc == VLC_FOURCC('d','t','s','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_Err( 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_Err( 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_decoder_fifo != NULL )
418         {
419             input_DecodePES( p_es->p_decoder_fifo, p_pes );
420         }
421         else
422         {
423             msg_Err( p_input, "no fifo to receive PES %p "
424                               "(who wrote this damn code ?)", p_pes );
425             input_DeletePES( p_input->p_method_data, p_pes );
426         }
427         p_pes = NULL;
428     }
429 #undef p_pes
430
431 }
432
433 /*****************************************************************************
434  * GatherPES:
435  *****************************************************************************
436  * Gather a PES packet.
437  *****************************************************************************/
438 static void GatherPES( input_thread_t * p_input, data_packet_t * p_data,
439                        es_descriptor_t * p_es,
440                        vlc_bool_t b_unit_start, vlc_bool_t b_packet_lost )
441 {
442 #define p_pes (p_es->p_pes)
443
444     /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
445      * often an escape sequence in decoders, so that should make them wait
446      * for the next start code). */
447     if( b_packet_lost )
448     {
449         input_NullPacket( p_input, p_es );
450     }
451
452     if( b_unit_start && p_pes != NULL )
453     {
454         /* If the data packet contains the begining of a new PES packet, and
455          * if we were reassembling a PES packet, then the PES should be
456          * complete now, so parse its header and give it to the decoders. */
457         ParsePES( p_input, p_es );
458     }
459
460     if( !b_unit_start && p_pes == NULL )
461     {
462         /* Random access... */
463         input_DeletePacket( p_input->p_method_data, p_data );
464     }
465     else
466     {
467         if( b_unit_start )
468         {
469             /* If we are at the beginning of a new PES packet, we must fetch
470              * a new PES buffer to begin with the reassembly of this PES
471              * packet. This is also here that we can synchronize with the
472              * stream if we lost packets or if the decoder has just
473              * started. */
474             if( (p_pes = input_NewPES( p_input->p_method_data ) ) == NULL )
475             {
476                 msg_Err( p_input, "out of memory" );
477                 p_input->b_error = 1;
478                 return;
479             }
480             p_pes->i_rate = p_input->stream.control.i_rate;
481             p_pes->p_first = p_data;
482
483             /* If the PES header fits in the first data packet, we can
484              * already set p_gather->i_pes_real_size. */
485             if( p_data->p_payload_end - p_data->p_payload_start
486                     >= PES_HEADER_SIZE )
487             {
488                 p_es->i_pes_real_size = ((u16)p_data->p_payload_start[4] << 8)
489                                          + p_data->p_payload_start[5];
490                 if ( p_es->i_pes_real_size )
491                 {
492                     p_es->i_pes_real_size += 6;
493                 }
494             }
495             else
496             {
497                 p_es->i_pes_real_size = 0;
498             }
499         }
500         else
501         {
502             /* Update the relations between the data packets */
503             p_pes->p_last->p_next = p_data;
504         }
505
506         p_pes->p_last = p_data;
507         p_pes->i_nb_data++;
508
509         /* Size of the payload carried in the data packet */
510         p_pes->i_pes_size += (p_data->p_payload_end
511                                  - p_data->p_payload_start);
512
513         /* We can check if the packet is finished */
514         if( p_es->i_pes_real_size  && p_pes->i_pes_size >= p_es->i_pes_real_size )
515         {
516             if( p_pes->i_pes_size > p_es->i_pes_real_size )
517             {
518                 msg_Warn( p_input,
519                           "Oversized PES packet for PID %d: expected %d, actual %d",
520                           p_es->i_id, p_es->i_pes_real_size, p_pes->i_pes_size );
521             }
522             /* The packet is finished, parse it */
523             ParsePES( p_input, p_es );
524         }
525     }
526 #undef p_pes
527 }
528
529
530 /*
531  * PS Demultiplexing
532  */
533
534 /*****************************************************************************
535  * GetID: Get the ID of a stream
536  *****************************************************************************/
537 static u16 GetID( data_packet_t * p_data )
538 {
539     u16         i_id;
540
541     i_id = p_data->p_demux_start[3];                            /* stream_id */
542     if( i_id == 0xBD )
543     {
544         /* FIXME : this is not valid if the header is split in multiple
545          * packets */
546         /* stream_private_id */
547         i_id |= p_data->p_demux_start[ 9 + p_data->p_demux_start[8] ] << 8;
548     }
549     return( i_id );
550 }
551
552 /*****************************************************************************
553  * DecodePSM: Decode the Program Stream Map information
554  *****************************************************************************
555  * FIXME : loads are not aligned in this function
556  *****************************************************************************/
557 static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
558 {
559     stream_ps_data_t *  p_demux =
560                  (stream_ps_data_t *)p_input->stream.p_demux_data;
561     byte_t *            p_byte;
562     byte_t *            p_end;
563     unsigned int        i;
564     unsigned int        i_new_es_number = 0;
565
566     if( p_data->p_demux_start + 10 > p_data->p_payload_end )
567     {
568         msg_Err( p_input, "PSM too short, packet corrupt" );
569         return;
570     }
571
572     if( p_demux->b_has_PSM
573         && p_demux->i_PSM_version == (p_data->p_demux_start[6] & 0x1F) )
574     {
575         /* Already got that one. */
576         return;
577     }
578
579     p_demux->b_has_PSM = 1;
580     p_demux->i_PSM_version = p_data->p_demux_start[6] & 0x1F;
581
582     /* Go to elementary_stream_map_length, jumping over
583      * program_stream_info. */
584     p_byte = p_data->p_demux_start + 10
585               + U16_AT(&p_data->p_demux_start[8]);
586     if( p_byte > p_data->p_payload_end )
587     {
588         msg_Err( p_input, "PSM too short, packet corrupt" );
589         return;
590     }
591     /* This is the full size of the elementary_stream_map.
592      * 2 == elementary_stream_map_length
593      * Please note that CRC_32 is not included in the length. */
594     p_end = p_byte + 2 + U16_AT(p_byte);
595     p_byte += 2;
596     if( p_end > p_data->p_payload_end )
597     {
598         msg_Err( p_input, "PSM too short, packet corrupt" );
599         return;
600     }
601
602     vlc_mutex_lock( &p_input->stream.stream_lock );
603
604     /* 4 == minimum useful size of a section */
605     while( p_byte + 4 <= p_end )
606     {
607         es_descriptor_t *   p_es = NULL;
608         uint8_t             i_stream_id = p_byte[1];
609         /* FIXME: there will be a problem with private streams... (same
610          * stream_id) */
611
612         /* Look for the ES in the ES table */
613         for( i = i_new_es_number;
614              i < p_input->stream.pp_programs[0]->i_es_number;
615              i++ )
616         {
617             if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
618                     == i_stream_id )
619             {
620                 p_es = p_input->stream.pp_programs[0]->pp_es[i];
621                 /* FIXME: do something below */
622 #if 0
623                 if( p_es->i_type != p_byte[0] )
624                 {
625                     input_DelES( p_input, p_es );
626                     p_es = NULL;
627                 }
628                 else
629 #endif
630                 {
631                     /* Move the ES to the beginning. */
632                     p_input->stream.pp_programs[0]->pp_es[i]
633                         = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
634                     p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
635                         = p_es;
636                     i_new_es_number++;
637                 }
638                 break;
639             }
640         }
641
642         /* The goal is to have all the ES we have just read in the
643          * beginning of the pp_es table, and all the others at the end,
644          * so that we can close them more easily at the end. */
645         if( p_es == NULL )
646         {
647             int i_fourcc, i_cat;
648
649             switch( p_byte[0] )
650             {
651             case MPEG1_VIDEO_ES:
652             case MPEG2_VIDEO_ES:
653             case MPEG2_MOTO_VIDEO_ES:
654                 i_fourcc = VLC_FOURCC('m','p','g','v');
655                 i_cat = VIDEO_ES;
656                 break;
657             case DVD_SPU_ES:
658                 i_fourcc = VLC_FOURCC('s','p','u','b');
659                 i_cat = SPU_ES;
660                 break;
661             case MPEG1_AUDIO_ES:
662             case MPEG2_AUDIO_ES:
663                 i_fourcc = VLC_FOURCC('m','p','g','a');
664                 i_cat = AUDIO_ES;
665                 break;
666             case A52_AUDIO_ES:
667                 i_fourcc = VLC_FOURCC('a','5','2','b');
668                 i_cat = AUDIO_ES;
669                 break;
670             case LPCM_AUDIO_ES:
671                 i_fourcc = VLC_FOURCC('l','p','c','b');
672                 i_cat = AUDIO_ES;
673                 break;
674             default:
675                 i_cat = UNKNOWN_ES;
676                 i_fourcc = 0;
677                 break;
678             }
679
680             p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
681                                 i_stream_id, i_cat, NULL, 0 );
682             p_es->i_fourcc = i_fourcc;
683
684             /* input_AddES has inserted the new element at the end. */
685             p_input->stream.pp_programs[0]->pp_es[
686                 p_input->stream.pp_programs[0]->i_es_number ]
687                 = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
688             p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
689             i_new_es_number++;
690         }
691         p_byte += 4 + U16_AT(&p_byte[2]);
692     }
693
694     /* Un-select the streams that are no longer parts of the program. */
695     while( i_new_es_number < p_input->stream.pp_programs[0]->i_es_number )
696     {
697         /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
698          * list will be emptied starting from the end */
699         input_DelES( p_input,
700                      p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
701     }
702
703     msg_Dbg( p_input, "the stream map after the PSM is now:" );
704     input_DumpStream( p_input );
705
706     vlc_mutex_unlock( &p_input->stream.stream_lock );
707 }
708
709 /*****************************************************************************
710  * ReadPS: store a PS packet into a data_buffer_t
711  *****************************************************************************/
712 #define PEEK( SIZE )                                                        \
713     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
714     if( i_error == -1 )                                                     \
715     {                                                                       \
716         return( -1 );                                                       \
717     }                                                                       \
718     else if( (size_t)i_error < SIZE )                                       \
719     {                                                                       \
720         /* EOF */                                                           \
721         return( 0 );                                                        \
722     }
723
724 static ssize_t ReadPS( input_thread_t * p_input, data_packet_t ** pp_data )
725 {
726     byte_t *            p_peek;
727     size_t              i_packet_size;
728     ssize_t             i_error, i_read;
729
730     /* Read what we believe to be a packet header. */
731     PEEK( 4 );
732
733     if( p_peek[0] || p_peek[1] || p_peek[2] != 1 || p_peek[3] < 0xB9 )
734     {
735         if( p_peek[0] || p_peek[1] || p_peek[2] )
736         {
737             /* It is common for MPEG-1 streams to pad with zeros
738              * (although it is forbidden by the recommendation), so
739              * don't bother everybody in this case. */
740             msg_Warn( p_input, "garbage (0x%.2x%.2x%.2x%.2x)",
741                       p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
742         }
743
744         /* This is not the startcode of a packet. Read the stream
745          * until we find one. */
746         while( p_peek[0] || p_peek[1] || p_peek[2] != 1 || p_peek[3] < 0xB9 )
747         {
748             p_input->p_current_data++;
749             PEEK( 4 );
750             if( p_input->b_die ) return( -1 );
751         }
752         /* Packet found. */
753     }
754
755     /* 0x1B9 == SYSTEM_END_CODE, it is only 4 bytes long. */
756     if( p_peek[3] != 0xB9 )
757     {
758         /* The packet is at least 6 bytes long. */
759         PEEK( 6 );
760
761         if( p_peek[3] != 0xBA )
762         {
763             /* That's the case for all packets, except pack header. */
764             i_packet_size = (p_peek[4] << 8) | p_peek[5];
765         }
766         else
767         {
768             /* Pack header. */
769             if( (p_peek[4] & 0xC0) == 0x40 )
770             {
771                 /* MPEG-2 */
772                 i_packet_size = 8;
773             }
774             else if( (p_peek[4] & 0xF0) == 0x20 )
775             {
776                 /* MPEG-1 */
777                 i_packet_size = 6;
778             }
779             else
780             {
781                 msg_Err( p_input, "unable to determine stream type" );
782                 p_input->p_current_data++;
783                 return( -1 );
784             }
785         }
786     }
787     else
788     {
789         /* System End Code */
790         i_packet_size = -2;
791     }
792
793     /* Fetch a packet of the appropriate size. */
794     i_read = input_SplitBuffer( p_input, pp_data, i_packet_size + 6 );
795     if( i_read <= 0 )
796     {
797         return( i_read );
798     }
799
800     /* In MPEG-2 pack headers we still have to read stuffing bytes. */
801     if( ((*pp_data)->p_demux_start[3] == 0xBA) && (i_packet_size == 8) )
802     {
803         size_t i_stuffing = ((*pp_data)->p_demux_start[13] & 0x7);
804         /* Force refill of the input buffer - though we don't care
805          * about p_peek. Please note that this is unoptimized. */
806         PEEK( i_stuffing );
807         p_input->p_current_data += i_stuffing;
808     }
809
810     return( 1 );
811 }
812
813 #undef PEEK
814
815 /*****************************************************************************
816  * ParsePS: read the PS header
817  *****************************************************************************/
818 static es_descriptor_t * ParsePS( input_thread_t * p_input,
819                                   data_packet_t * p_data )
820 {
821     uint32_t            i_code;
822     es_descriptor_t *   p_es = NULL;
823
824     i_code = p_data->p_demux_start[3];
825
826     if( i_code > 0xBC ) /* ES start code */
827     {
828         uint16_t            i_id;
829         unsigned int        i_dummy;
830
831         /* This is a PES packet. Find out if we want it or not. */
832         i_id = GetID( p_data );
833
834         vlc_mutex_lock( &p_input->stream.stream_lock );
835         if( p_input->stream.pp_programs[0]->b_is_ok )
836         {
837             /* Look only at the selected ES. */
838             for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
839                  i_dummy++ )
840             {
841                 if( p_input->stream.pp_selected_es[i_dummy] != NULL
842                     && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
843                 {
844                     p_es = p_input->stream.pp_selected_es[i_dummy];
845                     break;
846                 }
847             }
848         }
849         else
850         {
851             vlc_bool_t b_auto_spawn = VLC_FALSE;
852             stream_ps_data_t * p_demux =
853               (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;
854
855             /* Search all ES ; if not found -> AddES */
856             p_es = input_FindES( p_input, i_id );
857
858             if( p_es == NULL && !p_demux->b_has_PSM )
859             {
860                 int i_fourcc, i_cat;
861
862                 /* Set stream type and auto-spawn. */
863                 if( (i_id & 0xF0) == 0xE0 )
864                 {
865                     /* MPEG video */
866                     i_fourcc = VLC_FOURCC('m','p','g','v');
867                     i_cat = VIDEO_ES;
868 #ifdef AUTO_SPAWN
869                     if( !p_input->stream.b_seekable ) b_auto_spawn = VLC_TRUE;
870 #endif
871                 }
872                 else if( (i_id & 0xE0) == 0xC0 )
873                 {
874                     /* MPEG audio */
875                     i_fourcc = VLC_FOURCC('m','p','g','a');
876                     i_cat = AUDIO_ES;
877 #ifdef AUTO_SPAWN
878                     if( !p_input->stream.b_seekable )
879                     if( config_GetInt( p_input, "audio-channel" )
880                             == (i_id & 0x1F) ||
881                         ( config_GetInt( p_input, "audio-channel" ) < 0
882                           && !(i_id & 0x1F) ) )
883                     switch( config_GetInt( p_input, "audio-type" ) )
884                     {
885                     case -1:
886                     case REQUESTED_MPEG:
887                         b_auto_spawn = VLC_TRUE;
888                     }
889 #endif
890                 }
891                 else if( (i_id & 0xF8FF) == 0x88BD )
892                 {
893                     i_fourcc = VLC_FOURCC('d','t','s','b');
894                     i_cat = AUDIO_ES;
895 #ifdef AUTO_SPAWN
896                     if( !p_input->stream.b_seekable )
897                     if( config_GetInt( p_input, "audio-channel" )
898                             == ((i_id & 0x700) >> 8) ||
899                         ( config_GetInt( p_input, "audio-channel" ) < 0
900                           && !((i_id & 0x700) >> 8)) )
901                     switch( config_GetInt( p_input, "audio-type" ) )
902                     {
903                     case -1:
904                     case REQUESTED_DTS:
905                         b_auto_spawn = VLC_TRUE;
906                     }
907 #endif
908                 }
909                 else if( (i_id & 0xF0FF) == 0x80BD )
910                 {
911                     /* A52 audio (0x80->0x8F) */
912                     i_fourcc = VLC_FOURCC('a','5','2','b');
913                     i_cat = AUDIO_ES;
914 #ifdef AUTO_SPAWN
915                     if( !p_input->stream.b_seekable )
916                     if( config_GetInt( p_input, "audio-channel" )
917                             == ((i_id & 0xF00) >> 8) ||
918                         ( config_GetInt( p_input, "audio-channel" ) < 0
919                           && !((i_id & 0xF00) >> 8)) )
920                     switch( config_GetInt( p_input, "audio-type" ) )
921                     {
922                     case -1:
923                     case REQUESTED_A52:
924                         b_auto_spawn = VLC_TRUE;
925                     }
926 #endif
927                 }
928                 else if( (i_id & 0xE0FF) == 0x20BD )
929                 {
930                     /* Subtitles video (0x20->0x3F) */
931                     i_fourcc = VLC_FOURCC('s','p','u','b');
932                     i_cat = SPU_ES;
933 #ifdef AUTO_SPAWN
934                     if( !p_input->stream.b_seekable )
935                     if( config_GetInt( p_input, "spu-channel" )
936                            == ((i_id & 0x1F00) >> 8) )
937                     {
938                         b_auto_spawn = VLC_TRUE;
939                     }
940 #endif
941                 }
942                 else if( (i_id & 0xF0FF) == 0xA0BD )
943                 {
944                     /* LPCM audio (0xA0->0xAF) */
945                     i_fourcc = VLC_FOURCC('l','p','c','b');
946                     i_cat = AUDIO_ES;
947                 }
948                 else
949                 {
950                     i_cat = UNKNOWN_ES;
951                     i_fourcc = 0;
952                 }
953
954                 p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
955                                     i_id, i_cat, NULL, 0 );
956
957                 p_es->i_stream_id = p_data->p_demux_start[3];
958                 p_es->i_fourcc = i_fourcc;
959
960                 if( b_auto_spawn ) input_SelectES( p_input, p_es );
961
962                 /* Tell the interface the stream has changed */
963                 p_input->stream.b_changed = 1;
964             }
965         } /* stream.b_is_ok */
966         vlc_mutex_unlock( &p_input->stream.stream_lock );
967     } /* i_code > 0xBC */
968
969     return( p_es );
970 }
971
972 /*****************************************************************************
973  * DemuxPS: first step of demultiplexing: the PS header
974  *****************************************************************************/
975 static void DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
976 {
977     u32                 i_code;
978     vlc_bool_t          b_trash = 0;
979     es_descriptor_t *   p_es = NULL;
980
981     i_code = ((u32)p_data->p_demux_start[0] << 24)
982                 | ((u32)p_data->p_demux_start[1] << 16)
983                 | ((u32)p_data->p_demux_start[2] << 8)
984                 | p_data->p_demux_start[3];
985     if( i_code <= 0x1BC )
986     {
987         switch( i_code )
988         {
989         case 0x1BA: /* PACK_START_CODE */
990             {
991                 /* Read the SCR. */
992                 mtime_t         scr_time;
993                 u32             i_mux_rate;
994
995                 if( (p_data->p_demux_start[4] & 0xC0) == 0x40 )
996                 {
997                     /* MPEG-2 */
998                     byte_t      p_header[14];
999                     byte_t *    p_byte;
1000                     p_byte = p_data->p_demux_start;
1001
1002                     if( MoveChunk( p_header, &p_data, &p_byte, 14 ) != 14 )
1003                     {
1004                         msg_Warn( p_input,
1005                                   "packet too short to have a header" );
1006                         b_trash = 1;
1007                         break;
1008                     }
1009                     scr_time =
1010                          ((mtime_t)(p_header[4] & 0x38) << 27) |
1011                          ((mtime_t)(U32_AT(p_header + 4) & 0x03FFF800)
1012                                         << 4) |
1013                          ((( ((mtime_t)U16_AT(p_header + 6) << 16)
1014                             | (mtime_t)U16_AT(p_header + 8) ) & 0x03FFF800)
1015                                         >> 11);
1016
1017                     /* mux_rate */
1018                     i_mux_rate = ((u32)U16_AT(p_header + 10) << 6)
1019                                    | (p_header[12] >> 2);
1020                     /* FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
1021                      * This is the biggest kludge ever !
1022                      * I don't know what's wrong with mux_rate calculation
1023                      * but this heuristic works well : */
1024                     i_mux_rate <<= 1;
1025                     i_mux_rate /= 3;
1026                 }
1027                 else
1028                 {
1029                     /* MPEG-1 SCR is like PTS. */
1030                     byte_t      p_header[12];
1031                     byte_t *    p_byte;
1032                     p_byte = p_data->p_demux_start;
1033
1034                     if( MoveChunk( p_header, &p_data, &p_byte, 12 ) != 12 )
1035                     {
1036                         msg_Warn( p_input,
1037                                   "packet too short to have a header" );
1038                         b_trash = 1;
1039                         break;
1040                     }
1041                     scr_time =
1042                          ((mtime_t)(p_header[4] & 0x0E) << 29) |
1043                          (((mtime_t)U32_AT(p_header + 4) & 0xFFFE00) << 6) |
1044                          ((mtime_t)p_header[7] << 7) |
1045                          ((mtime_t)p_header[8] >> 1);
1046
1047                     /* mux_rate */
1048                     i_mux_rate = (U32_AT(p_header + 8) & 0x7FFFFE) >> 1;
1049                 }
1050                 /* Call the pace control. */
1051                 input_ClockManageRef( p_input,
1052                                       p_input->stream.p_selected_program,
1053                                       scr_time );
1054
1055                 if( i_mux_rate != p_input->stream.i_mux_rate
1056                      && p_input->stream.i_mux_rate )
1057                 {
1058                     msg_Warn( p_input,
1059                               "mux_rate changed, expect cosmetic errors" );
1060                 }
1061                 p_input->stream.i_mux_rate = i_mux_rate;
1062
1063                 b_trash = 1;
1064             }
1065             break;
1066
1067         case 0x1BB: /* SYSTEM_START_CODE */
1068             b_trash = 1;                              /* Nothing interesting */
1069             break;
1070
1071         case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
1072             DecodePSM( p_input, p_data );
1073             b_trash = 1;
1074             break;
1075
1076         case 0x1B9: /* PROGRAM_END_CODE */
1077             b_trash = 1;
1078             break;
1079
1080         default:
1081             /* This should not happen */
1082             b_trash = 1;
1083             msg_Warn( p_input, "unwanted packet received "
1084                                "with startcode 0x%.8x", i_code );
1085         }
1086     }
1087     else
1088     {
1089         p_es = ParsePS( p_input, p_data );
1090
1091         vlc_mutex_lock( &p_input->stream.control.control_lock );
1092         if( p_es != NULL && p_es->p_decoder_fifo != NULL
1093              && (p_es->i_cat != AUDIO_ES || !p_input->stream.control.b_mute) )
1094         {
1095             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1096             p_es->c_packets++;
1097             GatherPES( p_input, p_data, p_es, 1, 0 );
1098         }
1099         else
1100         {
1101             vlc_mutex_unlock( &p_input->stream.control.control_lock );
1102             b_trash = 1;
1103         }
1104     }
1105
1106     /* Trash the packet if it has no payload or if it isn't selected */
1107     if( b_trash )
1108     {
1109         input_DeletePacket( p_input->p_method_data, p_data );
1110         p_input->stream.c_packets_trashed++;
1111     }
1112 }
1113
1114
1115 /*
1116  * TS Demultiplexing
1117  */
1118
1119 /*****************************************************************************
1120  * ReadTS: store a TS packet into a data_buffer_t
1121  *****************************************************************************/
1122 #define PEEK( SIZE )                                                        \
1123     i_error = input_Peek( p_input, &p_peek, SIZE );                         \
1124     if( i_error == -1 )                                                     \
1125     {                                                                       \
1126         return( -1 );                                                       \
1127     }                                                                       \
1128     else if( i_error < SIZE )                                               \
1129     {                                                                       \
1130         /* EOF */                                                           \
1131         return( 0 );                                                        \
1132     }
1133
1134 static ssize_t ReadTS( input_thread_t * p_input, data_packet_t ** pp_data )
1135 {
1136     byte_t *            p_peek;
1137     ssize_t             i_error, i_read;
1138
1139     PEEK( 1 );
1140
1141     if( *p_peek != TS_SYNC_CODE )
1142     {
1143         msg_Warn( p_input, "garbage at input (%x)", *p_peek );
1144
1145         if( p_input->i_mtu )
1146         {
1147             while( *p_peek != TS_SYNC_CODE )
1148             {
1149                 /* Try to resync on next packet. */
1150                 PEEK( TS_PACKET_SIZE );
1151                 p_input->p_current_data += TS_PACKET_SIZE;
1152                 PEEK( 1 );
1153             }
1154         }
1155         else
1156         {
1157             /* Move forward until we find 0x47 (and hope it's the good
1158              * one... FIXME) */
1159             while( *p_peek != TS_SYNC_CODE )
1160             {
1161                 p_input->p_current_data++;
1162                 PEEK( 1 );
1163             }
1164         }
1165     }
1166
1167     i_read = input_SplitBuffer( p_input, pp_data, TS_PACKET_SIZE );
1168     if( i_read <= 0 )
1169     {
1170         return( i_read );
1171     }
1172
1173     return( 1 );
1174 }
1175
1176 /*****************************************************************************
1177  * DemuxTS: first step of demultiplexing: the TS header
1178  *****************************************************************************/
1179 static void DemuxTS( input_thread_t * p_input, data_packet_t * p_data,
1180                      psi_callback_t pf_psi_callback )
1181 {
1182     uint16_t            i_pid;
1183     unsigned int        i_dummy;
1184     vlc_bool_t          b_adaptation;         /* Adaptation field is present */
1185     vlc_bool_t          b_payload;                 /* Packet carries payload */
1186     vlc_bool_t          b_unit_start;  /* A PSI or a PES start in the packet */
1187     vlc_bool_t          b_trash = 0;             /* Is the packet unuseful ? */
1188     vlc_bool_t          b_lost = 0;             /* Was there a packet loss ? */
1189     vlc_bool_t          b_psi = 0;                        /* Is this a PSI ? */
1190     vlc_bool_t          b_pcr = 0;                   /* Does it have a PCR ? */
1191     es_descriptor_t *   p_es = NULL;
1192     es_ts_data_t *      p_es_demux = NULL;
1193     pgrm_ts_data_t *    p_pgrm_demux = NULL;
1194     stream_ts_data_t *  p_stream_demux =
1195                           (stream_ts_data_t *)p_input->stream.p_demux_data;
1196
1197 #define p (p_data->p_demux_start)
1198     /* Extract flags values from TS common header. */
1199     i_pid = ((p[1] & 0x1F) << 8) | p[2];
1200     b_unit_start = (p[1] & 0x40);
1201     b_adaptation = (p[3] & 0x20);
1202     b_payload = (p[3] & 0x10);
1203
1204     /* Was there a transport error ? */
1205     if ( p[1] & 0x80 )
1206     {
1207         msg_Warn( p_input, "transport_error_indicator set for PID %d counter %x", i_pid, p[3] & 0x0f );
1208     }
1209
1210     /* Find out the elementary stream. */
1211     vlc_mutex_lock( &p_input->stream.stream_lock );
1212
1213     for( i_dummy = 0; i_dummy < p_input->stream.i_pgrm_number; i_dummy ++ )
1214     {
1215         if( (( pgrm_ts_data_t * ) p_input->stream.pp_programs[i_dummy]->
1216                     p_demux_data)->i_pcr_pid == i_pid )
1217         {
1218             b_pcr = 1;
1219             break;
1220         }
1221     }
1222
1223     p_es = input_FindES( p_input, i_pid );
1224
1225     if( (p_es != NULL) && (p_es->p_demux_data != NULL) )
1226     {
1227         p_es_demux = (es_ts_data_t *)p_es->p_demux_data;
1228
1229         if( p_es_demux->b_psi )
1230         {
1231             b_psi = 1;
1232         }
1233         else
1234         {
1235             p_pgrm_demux = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data;
1236         }
1237     }
1238
1239     vlc_mutex_lock( &p_input->stream.control.control_lock );
1240     if( ( p_es == NULL ) || (p_es->i_cat == AUDIO_ES
1241                               && p_input->stream.control.b_mute) )
1242     {
1243         /* Not selected. Just read the adaptation field for a PCR. */
1244         b_trash = 1;
1245     }
1246     else if( p_es->p_decoder_fifo == NULL && !b_psi )
1247     {
1248         b_trash = 1;
1249     }
1250
1251     vlc_mutex_unlock( &p_input->stream.control.control_lock );
1252     vlc_mutex_unlock( &p_input->stream.stream_lock );
1253
1254
1255     /* Don't change the order of the tests : if b_psi then p_pgrm_demux
1256      * may still be null. Who said it was ugly ?
1257      * I have written worse. --Meuuh */
1258     if( ( p_es ) &&
1259         ((p_es->p_decoder_fifo != NULL) || b_psi || b_pcr ) )
1260     {
1261         p_es->c_packets++;
1262
1263         /* Extract adaptation field information if any */
1264
1265         if( !b_adaptation )
1266         {
1267             /* We don't have any adaptation_field, so payload starts
1268              * immediately after the 4 byte TS header */
1269             p_data->p_payload_start += 4;
1270         }
1271         else
1272         {
1273             /* p[4] is adaptation_field_length minus one */
1274             p_data->p_payload_start += 5 + p[4];
1275
1276             /* The adaptation field can be limited to the
1277              * adaptation_field_length byte, so that there is nothing to do:
1278              * skip this possibility */
1279             if( p[4] )
1280             {
1281                 /* If the packet has both adaptation_field and payload,
1282                  * adaptation_field cannot be more than 182 bytes long; if
1283                  * there is only an adaptation_field, it must fill the next
1284                  * 183 bytes. */
1285                 if( b_payload ? (p[4] > 182) : (p[4] != 183) )
1286                 {
1287                     msg_Warn( p_input, "invalid TS adaptation field for PID %d (%2x)",
1288                               i_pid, p[4] );
1289                     p_data->b_discard_payload = 1;
1290                     p_es->c_invalid_packets++;
1291
1292                     /* The length was invalid so we shouldn't have added it to
1293                      * p_payload_start above.  Ensure p_payload_start has a
1294                      * valid value by setting it equal to p_payload_end.  This
1295                      * also stops any data being processed from the packet.
1296                      */
1297                     p_data->p_payload_start = p_data->p_payload_end;
1298                 }
1299
1300                 /* Now we are sure that the byte containing flags is present:
1301                  * read it */
1302                 else
1303                 {
1304                     /* discontinuity_indicator */
1305                     if( p[5] & 0x80 )
1306                     {
1307                         msg_Warn( p_input,
1308                             "discontinuity_indicator encountered by TS demux "
1309                             "(PID %d: current %d, packet %d)",
1310                             i_pid,
1311                             ( p_es_demux->i_continuity_counter ) & 0x0f,
1312                             p[3] & 0x0f );
1313
1314                         /* If the PID carries the PCR, there will be a system
1315                          * time-based discontinuity. We let the PCR decoder
1316                          * handle that. */
1317                         p_es->p_pgrm->i_synchro_state = SYNCHRO_REINIT;
1318
1319                         /* Don't resynchronise the counter here - it will
1320                          * be checked later and b_lost will then be set if
1321                          * necessary.
1322                          */
1323                     }
1324
1325                 } /* valid TS adaptation field ? */
1326             } /* length > 0 */
1327         } /* has adaptation field */
1328         /* Check the continuity of the stream. */
1329         i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
1330         if( b_payload &&
1331                 ( i_dummy == 1 || (b_psi && p_stream_demux->b_buggy_psi ) ) )
1332         {
1333             /* Everything is ok, just increase our counter */
1334             (p_es_demux->i_continuity_counter)++;
1335         }
1336         else
1337         {
1338             if( !b_payload && i_dummy == 0 )
1339             {
1340                 /* This is a packet without payload, this is allowed by the
1341                  * draft. As there is nothing interesting in this packet
1342                  * (except PCR that have already been handled), we can trash
1343                  * the packet. */
1344                 b_trash = 1;
1345             }
1346             else if( !b_payload )
1347             {
1348                 /* If there is no payload, the counter should be unchanged */
1349                 msg_Warn( p_input, "packet rxd for PID %d with no payload but "
1350                         "wrong counter: current %d, packet %d", i_pid,
1351                         p_es_demux->i_continuity_counter & 0x0f, p[3] & 0x0f );
1352             }
1353             else if( i_dummy <= 0 )
1354             {
1355                 /* Duplicate packet: mark it as being to be trashed. */
1356                 msg_Warn( p_input,
1357                           "duplicate packet received for PID %d (counter %d)",
1358                           p_es->i_id, p[3] & 0x0f );
1359                 b_trash = 1;
1360             }
1361             else if( p_es_demux->i_continuity_counter == 0xFF )
1362             {
1363                 /* This means that the packet is the first one we receive for
1364                  * this ES since the continuity counter ranges between 0 and
1365                  * 0x0F excepts when it has been initialized by the input:
1366                  * init the counter to the correct value. */
1367                 msg_Warn( p_input, "first packet for PID %d received "
1368                                    "by TS demux", p_es->i_id );
1369                 p_es_demux->i_continuity_counter = (p[3] & 0x0f);
1370             }
1371             else
1372             {
1373                 /* This can indicate that we missed a packet or that the
1374                  * continuity_counter wrapped and we received a dup packet:
1375                  * as we don't know, do as if we missed a packet to be sure
1376                  * to recover from this situation */
1377                 msg_Warn( p_input,
1378                           "packet lost by TS demux for PID %d: current %d, packet %d",
1379                           i_pid,
1380                           p_es_demux->i_continuity_counter & 0x0f,
1381                           p[3] & 0x0f );
1382                 b_lost = 1;
1383                 p_es_demux->i_continuity_counter = p[3] & 0x0f;
1384             } /* not continuous */
1385         } /* continuity */
1386     } /* if selected or PCR */
1387
1388     /* Handle PCR */
1389     if( b_pcr && b_adaptation && (p[5] & 0x10) && p[4]>=7 )
1390     {
1391         /* Read the PCR. */
1392         mtime_t     pcr_time;
1393         pcr_time = ( (mtime_t)p[6] << 25 ) |
1394                    ( (mtime_t)p[7] << 17 ) |
1395                    ( (mtime_t)p[8] << 9 ) |
1396                    ( (mtime_t)p[9] << 1 ) |
1397                    ( (mtime_t)p[10] >> 7 );
1398         /* Call the pace control. */
1399         for( i_dummy = 0; i_dummy < p_input->stream.i_pgrm_number;
1400                                 i_dummy ++ )
1401         {
1402             if( ( ( pgrm_ts_data_t * ) p_input->stream.pp_programs[i_dummy]->
1403                         p_demux_data )->i_pcr_pid == i_pid )
1404             {
1405                 input_ClockManageRef( p_input,
1406                     p_input->stream.pp_programs[i_dummy], pcr_time );
1407             }
1408         }
1409
1410     }
1411
1412     /* Trash the packet if it has no payload or if it isn't selected */
1413     if( b_trash )
1414     {
1415         input_DeletePacket( p_input->p_method_data, p_data );
1416         p_input->stream.c_packets_trashed++;
1417     }
1418     else
1419     {
1420         if( b_psi )
1421         {
1422             /* The payload contains PSI tables */
1423             (* pf_psi_callback) ( p_input, p_data, p_es, b_unit_start );
1424         }
1425         else
1426         {
1427             /* The payload carries a PES stream */
1428             GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
1429         }
1430
1431     }
1432
1433 #undef p
1434
1435 }