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