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