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