mpeg_system.c 45.3 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * mpeg_system.c: TS, PS and PES management
 *****************************************************************************
 * Copyright (C) 1998, 1999, 2000 VideoLAN
5
 * $Id: mpeg_system.c,v 1.21 2000/12/28 17:57:39 massiot Exp $
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 *
 * Authors: 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include "defs.h"

#include <stdlib.h>
#include <netinet/in.h>

#include "config.h"
#include "common.h"
#include "threads.h"
#include "mtime.h"

#include "intf_msg.h"

#include "stream_control.h"
#include "input_ext-intf.h"
#include "input_ext-dec.h"

#include "input.h"
#include "mpeg_system.h"
45
#include "input_dec.h"
46

47 48
#include "main.h"                           /* AC3/MPEG channel, SPU channel */

49 50 51 52 53 54 55 56 57
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/


/*
 * PES Packet management
 */

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
/*****************************************************************************
 * MoveChunk
 *****************************************************************************
 * Small utility function used to parse discontinuous headers safely. Copies
 * i_buf_len bytes of data to a buffer and returns the size copied.
 * This is a variation on the theme of input_ext-dec.h:GetChunk().
 *****************************************************************************/
static __inline__ size_t MoveChunk( byte_t * p_dest,
                                    data_packet_t ** pp_data_src,
                                    byte_t ** pp_src,
                                    size_t i_buf_len )
{
    ptrdiff_t           i_available;

    if( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
            >= i_buf_len )
    {
        if( p_dest != NULL )
            memcpy( p_dest, *pp_src, i_buf_len );
        *pp_src += i_buf_len;
        return( i_buf_len );
    }
    else
    {
        size_t          i_init_len = i_buf_len;

        do
        {
            if( p_dest != NULL )
                memcpy( p_dest, *pp_src, i_available );
            *pp_data_src = (*pp_data_src)->p_next;
            i_buf_len -= i_available;
            p_dest += i_available;
            if( *pp_data_src == NULL )
            {
                *pp_src = NULL;
                return( i_init_len - i_buf_len );
            }
            *pp_src = (*pp_data_src)->p_payload_start;
        }
        while( (i_available = (*pp_data_src)->p_payload_end - *pp_src)
                <= i_buf_len );

        if( i_buf_len )
        {
            if( p_dest != NULL )
                memcpy( p_dest, *pp_src, i_buf_len );
            *pp_src += i_buf_len;
        }
        return( i_init_len );
    }
}

111 112 113 114 115
/*****************************************************************************
 * input_ParsePES
 *****************************************************************************
 * Parse a finished PES packet and analyze its header.
 *****************************************************************************/
116
#define PES_HEADER_SIZE     7
117 118
void input_ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
{
119 120
    data_packet_t * p_data;
    byte_t *        p_byte;
121
    byte_t          p_header[PES_HEADER_SIZE];
122
    int             i_done;
123 124 125

#define p_pes (p_es->p_pes)

Sam Hocevar's avatar
 
Sam Hocevar committed
126
    //intf_DbgMsg("End of PES packet %p", p_pes);
127 128 129 130

    /* Parse the header. The header has a variable length, but in order
     * to improve the algorithm, we will read the 14 bytes we may be
     * interested in */
131 132
    p_data = p_pes->p_first;
    p_byte = p_data->p_payload_start;
133 134
    i_done = 0;

135 136
    if( MoveChunk( p_header, &p_data, &p_byte, PES_HEADER_SIZE )
            != PES_HEADER_SIZE )
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    {
        intf_WarnMsg( 3, "PES packet too short to have a header" );
        p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
        p_pes = NULL;
        return;
    }

    /* Get the PES size if defined */
    p_es->i_pes_real_size = U16_AT(p_header + 4) + 6;

    /* First read the 6 header bytes common to all PES packets:
     * use them to test the PES validity */
    if( (p_header[0] || p_header[1] || (p_header[2] != 1)) )
    {
        /* packet_start_code_prefix != 0x000001 */
        intf_ErrMsg( "PES packet doesn't start with 0x000001 : data loss" );
        p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
        p_pes = NULL;
    }
    else
    {
        int i_pes_header_size, i_payload_size;

        if ( p_es->i_pes_real_size &&
             (p_es->i_pes_real_size != p_pes->i_pes_size) )
        {
            /* PES_packet_length is set and != total received payload */
            /* Warn the decoder that the data may be corrupt. */
            intf_WarnMsg( 3, "PES sizes do not match : packet corrupted" );
            p_pes->b_messed_up = 1;
        }

        switch( p_es->i_stream_id )
        {
        case 0xBC:  /* Program stream map */
        case 0xBE:  /* Padding */
        case 0xBF:  /* Private stream 2 */
        case 0xB0:  /* ECM */
        case 0xB1:  /* EMM */
        case 0xFF:  /* Program stream directory */
        case 0xF2:  /* DSMCC stream */
        case 0xF8:  /* ITU-T H.222.1 type E stream */
            /* The payload begins immediately after the 6 bytes header, so
             * we have finished with the parsing */
            i_pes_header_size = 6;
            break;

        default:
185 186 187
            if( (p_header[6] & 0xC0) == 0x80 )
            {
                /* MPEG-2 : the PES header contains at least 3 more bytes. */
188
                size_t      i_max_len;
189 190
                boolean_t   b_has_pts, b_has_dts;
                byte_t      p_full_header[12];
191

192 193
                p_pes->b_data_alignment = p_header[6] & 0x04;

194
                i_max_len = MoveChunk( p_full_header, &p_data, &p_byte, 12 );
195 196 197 198 199 200 201 202 203 204
                if( i_max_len < 2 )
                {
                    intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-2 header" );
                    p_input->p_plugin->pf_delete_pes( p_input->p_method_data,
                                                      p_pes );
                    p_pes = NULL;
                    return;
                }

205 206 207
                b_has_pts = p_full_header[0] & 0x80;
                b_has_dts = p_full_header[0] & 0x40;
                i_pes_header_size = p_full_header[1] + 9;
208 209

                /* Now parse the optional header extensions */
210
                if( b_has_pts )
211
                {
212 213 214 215 216 217 218 219 220 221
                    if( i_max_len < 7 )
                    {
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-2 header" );
                        p_input->p_plugin->pf_delete_pes(
                                                      p_input->p_method_data,
                                                      p_pes );
                        p_pes = NULL;
                        return;
                    }
222
                    p_pes->i_pts =
223 224 225
                    ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
                      (((mtime_t)U16_AT(p_full_header + 3) << 14) - (1 << 14)) |
                      ((mtime_t)U16_AT(p_full_header + 5) >> 1) ) * 300;
226
                    p_pes->i_pts /= 27;
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

                    if( b_has_dts )
                    {
                        if( i_max_len < 12 )
                        {
                            intf_WarnMsg( 3,
                              "PES packet too short to have a MPEG-2 header" );
                            p_input->p_plugin->pf_delete_pes(
                                    p_input->p_method_data,
                                    p_pes );
                            p_pes = NULL;
                            return;
                        }
                        p_pes->i_dts =
                        ( ((mtime_t)(p_full_header[7] & 0x0E) << 29) |
                          (((mtime_t)U16_AT(p_full_header + 10) << 14)
                                - (1 << 14)) |
                          ((mtime_t)U16_AT(p_full_header + 12) >> 1) ) * 300;
                        p_pes->i_dts /= 27;
                    }
247 248 249 250 251
                }
            }
            else
            {
                /* Probably MPEG-1 */
252 253
                boolean_t       b_has_pts, b_has_dts;

254 255
                i_pes_header_size = 6;
                p_data = p_pes->p_first;
256 257 258 259
                p_byte = p_data->p_payload_start;
                /* Cannot fail because the previous one succeeded. */
                MoveChunk( NULL, &p_data, &p_byte, 6 );

260 261 262
                while( *p_byte == 0xFF && i_pes_header_size < 22 )
                {
                    i_pes_header_size++;
263
                    if( MoveChunk( NULL, &p_data, &p_byte, 1 ) != 1 )
264
                    {
265 266 267 268 269
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-1 header" );
                        p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
                        p_pes = NULL;
                        return;
270 271 272 273 274 275 276 277 278 279 280 281 282
                    }
                }
                if( i_pes_header_size == 22 )
                {
                    intf_ErrMsg( "Too much MPEG-1 stuffing" );
                    p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
                    p_pes = NULL;
                    return;
                }

                if( (*p_byte & 0xC0) == 0x40 )
                {
                    /* Don't ask why... --Meuuh */
Sam Hocevar's avatar
 
Sam Hocevar committed
283
                    /* Erm... why ? --Sam */
284 285
                    /* Well... According to the recommendation, it is for
                     * 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 290 291 292 293
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-1 header" );
                        p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
                        p_pes = NULL;
                        return;
294 295 296 297 298
                    }
                }

                i_pes_header_size++;

299 300 301 302
                b_has_pts = *p_byte & 0x20;
                b_has_dts = *p_byte & 0x10;

                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 310 311 312 313 314
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-1 header" );
                        p_input->p_plugin->pf_delete_pes(
                                            p_input->p_method_data, p_pes );
                        p_pes = NULL;
                        return;
315
                    }
316

317
                    p_pes->i_pts =
318 319 320
                      ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
                        (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
                        ((mtime_t)U16_AT(p_ts + 3) >> 1) ) * 300;
321
                    p_pes->i_pts /= 27;
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

                    if( b_has_dts )
                    {
                        i_pes_header_size += 5;
                        if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
                        {
                            intf_WarnMsg( 3,
                              "PES packet too short to have a MPEG-1 header" );
                            p_input->p_plugin->pf_delete_pes(
                                    p_input->p_method_data, p_pes );
                            p_pes = NULL;
                            return;
                        }

                        p_pes->i_dts =
                            ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
                              (((mtime_t)U16_AT(p_ts + 1) << 14) - (1 << 14)) |
                              ((mtime_t)U16_AT(p_ts + 3) >> 1) ) * 300;
                        p_pes->i_dts /= 27;
                    }
342 343 344 345
                }
            }

            /* PTS management */
346
            if( p_pes->i_pts )
347
            {
Sam Hocevar's avatar
 
Sam Hocevar committed
348
                //intf_Msg("%lld", p_pes->i_pts);
349 350 351 352
                switch( p_es->p_pgrm->i_synchro_state )
                {
                case SYNCHRO_NOT_STARTED:
                case SYNCHRO_START:
353
                    p_pes->i_pts = p_pes->i_dts = 0;
354 355 356
                    break;

                case SYNCHRO_REINIT: /* We skip a PES | Why ?? --Meuuh */
357
                    p_pes->i_pts = p_pes->i_dts = 0;
358 359 360 361 362
                    p_es->p_pgrm->i_synchro_state = SYNCHRO_START;
                    break;

                case SYNCHRO_OK:
                    p_pes->i_pts += p_es->p_pgrm->delta_cr
363 364
                                         + p_es->p_pgrm->delta_absolute
                                         + DEFAULT_PTS_DELAY;
365 366 367
                    p_pes->i_dts += p_es->p_pgrm->delta_cr
                                         + p_es->p_pgrm->delta_absolute
                                         + DEFAULT_PTS_DELAY;
368 369 370 371 372 373
                    break;
                }
            }
            break;
        }

Sam Hocevar's avatar
 
Sam Hocevar committed
374
        if( p_es->i_stream_id == 0xbd )
375 376 377 378 379 380
        {
            /* With private stream 1, the first byte of the payload
             * is a stream_private_id, so skip it. */
            i_pes_header_size++;
        }

381 382 383 384
        /* Now we've parsed the header, we just have to indicate in some
         * specific data packets where the PES payload begins (renumber
         * p_payload_start), so that the decoders can find the beginning
         * of their data right out of the box. */
385 386 387
        p_data = p_pes->p_first;
        i_payload_size = p_data->p_payload_end
                                 - p_data->p_payload_start;
388 389 390 391
        while( i_pes_header_size > i_payload_size )
        {
            /* These packets are entirely filled by the PES header. */
            i_pes_header_size -= i_payload_size;
392
            p_data->p_payload_start = p_data->p_payload_end;
393
            /* Go to the next data packet. */
394
            if( (p_data = p_data->p_next) == NULL )
395 396 397 398 399 400 401
            {
                intf_ErrMsg( "PES header bigger than payload" );
                p_input->p_plugin->pf_delete_pes( p_input->p_method_data,
                                                  p_pes );
                p_pes = NULL;
                return;
            }
402 403
            i_payload_size = p_data->p_payload_end
                                 - p_data->p_payload_start;
404 405 406 407 408 409 410 411 412
        }
        /* This last packet is partly header, partly payload. */
        if( i_payload_size < i_pes_header_size )
        {
            intf_ErrMsg( "PES header bigger than payload" );
            p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
            p_pes = NULL;
            return;
        }
413
        p_data->p_payload_start += i_pes_header_size;
414 415 416

        /* Now we can eventually put the PES packet in the decoder's
         * PES fifo */
417 418 419 420 421 422 423 424 425 426 427
        if( p_es->p_decoder_fifo != NULL )
        {
            input_DecodePES( p_es->p_decoder_fifo, p_pes );
        }
        else
        {
            intf_ErrMsg("No fifo to receive PES %p (who wrote this damn code ?)",
                        p_pes);
            p_input->p_plugin->pf_delete_pes( p_input->p_method_data, p_pes );
        }
        p_pes = NULL;
428 429 430 431 432 433 434 435 436
    }
#undef p_pes
}

/*****************************************************************************
 * input_GatherPES:
 *****************************************************************************
 * Gather a PES packet.
 *****************************************************************************/
437
void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
438 439 440 441 442
                      es_descriptor_t * p_es,
                      boolean_t b_unit_start, boolean_t b_packet_lost )
{
#define p_pes (p_es->p_pes)

Sam Hocevar's avatar
 
Sam Hocevar committed
443
    //intf_DbgMsg("PES-demultiplexing %p (%p)", p_ts_packet, p_pes);
444

Sam Hocevar's avatar
 
Sam Hocevar committed
445
    /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
446 447
     * often an escape sequence in decoders, so that should make them wait
     * for the next start code). */
448
    if( b_packet_lost || p_es->b_discontinuity )
449 450
    {
        data_packet_t *             p_pad_data;
451 452 453

        if( (p_pad_data = p_input->p_plugin->pf_new_packet(
                                            p_input->p_method_data,
454 455
                                            PADDING_PACKET_SIZE )) == NULL )
        {
Sam Hocevar's avatar
 
Sam Hocevar committed
456
            intf_ErrMsg("Out of memory");
457 458 459 460 461
            p_input->b_error = 1;
            return;
        }
        memset( p_data->p_buffer, 0, PADDING_PACKET_SIZE );
        p_pad_data->b_discard_payload = 1;
462 463 464 465 466 467 468 469 470 471 472

        if( p_pes != NULL )
        {
            p_pes->b_messed_up = p_pes->b_discontinuity = 1;
            input_GatherPES( p_input, p_pad_data, p_es, 0, 0 );
        }
        else
        {
            if( (p_pes = p_input->p_plugin->pf_new_pes(
                                            p_input->p_method_data )) == NULL )
            {
Sam Hocevar's avatar
 
Sam Hocevar committed
473
                intf_ErrMsg("Out of memory");
474 475 476 477 478 479
                p_input->b_error = 1;
                return;
            }

            p_pes->p_first = p_pad_data;
            p_pes->b_messed_up = p_pes->b_discontinuity = 1;
480
            input_DecodePES( p_es->p_decoder_fifo, p_pes );
481 482 483
        }

        p_es->b_discontinuity = 0;
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
    }

    if( b_unit_start && p_pes != NULL )
    {
        /* If the TS packet contains the begining of a new PES packet, and
         * if we were reassembling a PES packet, then the PES should be
         * complete now, so parse its header and give it to the decoders. */
        input_ParsePES( p_input, p_es );
    }

    if( !b_unit_start && p_pes == NULL )
    {
        /* Random access... */
        p_input->p_plugin->pf_delete_packet( p_input->p_method_data, p_data );
    }
    else
    {
        if( b_unit_start )
        {
            /* If we are at the beginning of a new PES packet, we must fetch
             * a new PES buffer to begin with the reassembly of this PES
             * packet. This is also here that we can synchronize with the
             * stream if we lost packets or if the decoder has just
             * started. */
508
            if( (p_pes = p_input->p_plugin->pf_new_pes( p_input->p_method_data ) ) == NULL )
509 510 511 512 513
            {
                intf_ErrMsg("Out of memory");
                p_input->b_error = 1;
                return;
            }
Sam Hocevar's avatar
 
Sam Hocevar committed
514
            //intf_DbgMsg("New PES packet %p (first data: %p)", p_pes, p_data);
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
            p_pes->p_first = p_data;

            /* If the PES header fits in the first data packet, we can
             * already set p_gather->i_pes_real_size. */
            if( p_data->p_payload_end - p_data->p_payload_start
                    >= PES_HEADER_SIZE )
            {
                p_es->i_pes_real_size =
                                U16_AT(p_data->p_payload_start + 4) + 6;
            }
            else
            {
                p_es->i_pes_real_size = 0;
            }
        }
        else
        {
            /* Update the relations between the data packets */
            p_es->p_last->p_next = p_data;
        }

        p_data->p_next = NULL;
        p_es->p_last = p_data;

        /* Size of the payload carried in the data packet */
        p_pes->i_pes_size += (p_data->p_payload_end
                                 - p_data->p_payload_start);
    
        /* We can check if the packet is finished */
        if( p_pes->i_pes_size == p_es->i_pes_real_size )
        {
            /* The packet is finished, parse it */
            input_ParsePES( p_input, p_es );
        }
    }
#undef p_pes
}


/*
 * Pace control
 */

/*
 *   DISCUSSION : SYNCHRONIZATION METHOD
 *
 *   In some cases we can impose the pace of reading (when reading from a
 *   file or a pipe), and for the synchronization we simply sleep() until
 *   it is time to deliver the packet to the decoders. When reading from
 *   the network, we must be read at the same pace as the server writes,
 *   otherwise the kernel's buffer will trash packets. The risk is now to
 *   overflow the input buffers in case the server goes too fast, that is
 *   why we do these calculations :
 *
 *   We compute an average for the pcr because we want to eliminate the
 *   network jitter and keep the low frequency variations. The average is
 *   in fact a low pass filter and the jitter is a high frequency signal
 *   that is why it is eliminated by the filter/average.
 *
 *   The low frequency variations enable us to synchronize the client clock
 *   with the server clock because they represent the time variation between
 *   the 2 clocks. Those variations (ie the filtered pcr) are used to compute
 *   the presentation dates for the audio and video frames. With those dates
 *   we can decode (or trash) the MPEG2 stream at "exactly" the same rate
 *   as it is sent by the server and so we keep the synchronization between
 *   the server and the client.
 *
 *   It is a very important matter if you want to avoid underflow or overflow
 *   in all the FIFOs, but it may be not enough.
 */

/*****************************************************************************
 * Constants
 *****************************************************************************/

/* Maximum number of samples used to compute the dynamic average value,
 * it is also the maximum of c_average_count in pgrm_ts_data_t.
 * We use the following formula :
 * new_average = (old_average * c_average + new_sample_value) / (c_average +1) */
#define CR_MAX_AVERAGE_COUNTER 40

/* Maximum gap allowed between two CRs. */
#define CR_MAX_GAP 1000000

/*****************************************************************************
 * CRReInit : Reinitialize the clock reference
 *****************************************************************************/
static void CRReInit( pgrm_descriptor_t * p_pgrm )
{
    p_pgrm->delta_cr        = 0;
    p_pgrm->last_cr         = 0;
    p_pgrm->c_average_count = 0;
}

/* FIXME: find a better name */
/*****************************************************************************
 * CRDecode : Decode a clock reference
 *****************************************************************************/
613
static void CRDecode( input_thread_t * p_input, pgrm_descriptor_t * p_pgrm,
614 615
                      mtime_t cr_time )
{
616 617 618 619 620 621 622 623 624
    if( p_pgrm->i_synchro_state != SYNCHRO_OK )
    {
        switch( p_pgrm->i_synchro_state )
        {
        case SYNCHRO_START:
            p_pgrm->delta_absolute = mdate() - cr_time;
            p_pgrm->i_synchro_state = SYNCHRO_OK;
            break;

625 626 627 628
        case SYNCHRO_NOT_STARTED:
            p_pgrm->i_synchro_state = SYNCHRO_START;
            break;

629 630 631 632
        default:
            break;
        }
    }
633 634
    else
    {
635
        if( p_pgrm->b_discontinuity ||
636 637 638 639
            ( p_pgrm->last_cr != 0 &&
                  (    (p_pgrm->last_cr - cr_time) > CR_MAX_GAP
                    || (p_pgrm->last_cr - cr_time) < - CR_MAX_GAP ) ) )
        {
640 641
            int i_es;

642
            /* Stream discontinuity. */
643 644 645
            intf_WarnMsg( 3, "CR re-initialiazed" );
            CRReInit( p_pgrm );
            p_pgrm->i_synchro_state = SYNCHRO_REINIT;
646
            p_pgrm->b_discontinuity = 0;
647 648 649 650 651 652

            /* Warn all the elementary streams */
            for( i_es = 0; i_es < p_pgrm->i_es_number; i_es++ )
            {
                p_pgrm->pp_es[i_es]->b_discontinuity = 1;
            }
653 654 655
        }
        p_pgrm->last_cr = cr_time;

656
        if( p_input->stream.b_pace_control )
657
        {
658 659
            /* Wait a while before delivering the packets to the decoder. */
            mwait( cr_time + p_pgrm->delta_absolute );
660 661 662
        }
        else
        {
663
            mtime_t                 sys_time, delta_cr;
664

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
            sys_time = mdate();
            delta_cr = sys_time - cr_time;

            if( p_pgrm->c_average_count == CR_MAX_AVERAGE_COUNTER )
            {
                p_pgrm->delta_cr = ( delta_cr + (p_pgrm->delta_cr
                                              * (CR_MAX_AVERAGE_COUNTER - 1)) )
                                     / CR_MAX_AVERAGE_COUNTER;
            }
            else
            {
                p_pgrm->delta_cr = ( delta_cr + (p_pgrm->delta_cr
                                              * p_pgrm->c_average_count) )
                                     / ( p_pgrm->c_average_count + 1 );
                p_pgrm->c_average_count++;
            }
681 682 683 684 685 686 687 688 689
        }
    }
}


/*
 * PS Demultiplexing
 */

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
/*****************************************************************************
 * GetID: Get the ID of a stream
 *****************************************************************************/
static u16 GetID( data_packet_t * p_data )
{
    u16         i_id;

    i_id = p_data->p_buffer[3];                                 /* stream_id */
    if( i_id == 0xBD )
    {
        /* stream_private_id */
        i_id |= p_data->p_buffer[ 9 + p_data->p_buffer[8] ] << 8;
    }
    return( i_id );
}

706 707 708 709 710 711 712
/*****************************************************************************
 * DecodePSM: Decode the Program Stream Map information
 *****************************************************************************/
static void DecodePSM( input_thread_t * p_input, data_packet_t * p_data )
{
    stream_ps_data_t *  p_demux =
                 (stream_ps_data_t *)p_input->stream.p_demux_data;
713 714 715 716
    byte_t *            p_byte;
    byte_t *            p_end;
    int                 i;
    int                 i_new_es_number = 0;
717

718 719 720
    intf_Msg("input info: Your stream contains Program Stream Map information");
    intf_Msg("input info: Please send a mail to <massiot@via.ecp.fr>");

721
    if( p_data->p_payload_start + 10 > p_data->p_payload_end )
722
    {
723 724 725
        intf_ErrMsg( "PSM too short : packet corrupt" );
        return;
    }
726

727 728
    if( p_demux->b_has_PSM
        && p_demux->i_PSM_version == (p_data->p_buffer[6] & 0x1F) )
729 730 731 732
    {
        /* Already got that one. */
        return;
    }
733

734
    intf_DbgMsg( "Building PSM" );
735
    p_demux->b_has_PSM = 1;
736 737 738 739 740 741 742 743 744 745 746 747 748
    p_demux->i_PSM_version = p_data->p_buffer[6] & 0x1F;

    /* Go to elementary_stream_map_length, jumping over
     * program_stream_info. */
    p_byte = p_data->p_payload_start + 10
              + U16_AT(&p_data->p_payload_start[8]);
    if( p_byte > p_data->p_payload_end )
    {
        intf_ErrMsg( "PSM too short : packet corrupt" );
        return;
    }
    /* This is the full size of the elementary_stream_map.
     * 2 == elementary_stream_map_length
749 750
     * Please note that CRC_32 is not included in the length. */
    p_end = p_byte + 2 + U16_AT(p_byte);
751 752 753 754 755 756
    p_byte += 2;
    if( p_end > p_data->p_payload_end )
    {
        intf_ErrMsg( "PSM too short : packet corrupt" );
        return;
    }
757

758 759 760 761 762 763 764 765 766 767 768 769 770 771
    vlc_mutex_lock( &p_input->stream.stream_lock );

    /* 4 == minimum useful size of a section */
    while( p_byte + 4 <= p_end )
    {
        es_descriptor_t *   p_es = NULL;
        u8                  i_stream_id = p_byte[1];
        /* FIXME: there will be a problem with private streams... (same
         * stream_id) */

        /* Look for the ES in the ES table */
        for( i = i_new_es_number;
             i < p_input->stream.pp_programs[0]->i_es_number;
             i++ )
772
        {
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
            if( p_input->stream.pp_programs[0]->pp_es[i]->i_stream_id
                    == i_stream_id )
            {
                p_es = p_input->stream.pp_programs[0]->pp_es[i];
                if( p_es->i_type != p_byte[0] )
                {
                    input_DelES( p_input, p_es );
                    p_es = NULL;
                }
                else
                {
                    /* Move the ES to the beginning. */
                    p_input->stream.pp_programs[0]->pp_es[i]
                        = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
                    p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ]
                        = p_es;
789
                    i_new_es_number++;
790 791 792 793
                }
                break;
            }
        }
794

795 796 797 798 799
        /* The goal is to have all the ES we have just read in the
         * beginning of the pp_es table, and all the others at the end,
         * so that we can close them more easily at the end. */
        if( p_es == NULL )
        {
800
            p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
801
                                i_stream_id, 0 );
802
            p_es->i_type = p_byte[0];
803

804 805 806 807 808
            /* input_AddES has inserted the new element at the end. */
            p_input->stream.pp_programs[0]->pp_es[
                p_input->stream.pp_programs[0]->i_es_number ]
                = p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ];
            p_input->stream.pp_programs[0]->pp_es[ i_new_es_number ] = p_es;
809
            i_new_es_number++;
810 811
        }
        p_byte += 4 + U16_AT(&p_byte[2]);
812
    }
813 814 815 816 817

    /* Un-select the streams that are no longer parts of the program. */
    for( i = i_new_es_number;
         i < p_input->stream.pp_programs[0]->i_es_number;
         i++ )
818
    {
819 820 821
        input_DelES( p_input,
                     p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
        /* Yes, I wrote *i_new_es_number* */
822
    }
823 824 825 826 827 828

#ifdef STATS
    intf_Msg( "input info: The stream map after the PSM is now :" );
    input_DumpStream( p_input );
#endif

829
    vlc_mutex_unlock( &p_input->stream.stream_lock );
830 831
}

832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
/*****************************************************************************
 * input_ParsePS: read the PS header
 *****************************************************************************/
es_descriptor_t * input_ParsePS( input_thread_t * p_input,
                                 data_packet_t * p_data )
{
    u32                 i_code;
    es_descriptor_t *   p_es = NULL;

    i_code = U32_AT( p_data->p_buffer );
    if( i_code > 0x1BC ) /* ES start code */
    {
        u16                 i_id;
        int                 i_dummy;

        /* This is a PES packet. Find out if we want it or not. */
        i_id = GetID( p_data );

        vlc_mutex_lock( &p_input->stream.stream_lock );
        if( p_input->stream.pp_programs[0]->b_is_ok )
        {
            /* Look only at the selected ES. */
854
            for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
855
                 i_dummy++ )
856
            {
857 858
                if( p_input->stream.pp_selected_es[i_dummy] != NULL
                    && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
859
                {
860
                    p_es = p_input->stream.pp_selected_es[i_dummy];
861 862 863 864 865 866
                    break;
                }
            }
        }
        else
        {
867 868 869
            stream_ps_data_t * p_demux =
              (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;

870
            /* Search all ES ; if not found -> AddES */
871
            p_es = input_FindES( p_input, i_id );
872

873
            if( p_es == NULL && !p_demux->b_has_PSM )
874 875 876 877 878 879 880 881 882 883 884 885 886
            {
                p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
                                    i_id, 0 );
                if( p_es != NULL )
                {
                    p_es->i_stream_id = p_data->p_buffer[3];

                    /* Set stream type and auto-spawn. */
                    if( (i_id & 0xF0) == 0xE0 )
                    {
                        /* MPEG video */
                        p_es->i_type = MPEG2_VIDEO_ES;
#ifdef AUTO_SPAWN
887 888
                        if( !p_input->stream.b_seekable )
                            input_SelectES( p_input, p_es );
889 890 891 892 893 894 895
#endif
                    }
                    else if( (i_id & 0xE0) == 0xC0 )
                    {
                        /* MPEG audio */
                        p_es->i_type = MPEG2_AUDIO_ES;
#ifdef AUTO_SPAWN
896 897
                        if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
                                == REQUESTED_MPEG
898
                          && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
899
                                == (p_es->i_id & 0x1F) )
900
                        {
901 902
                            if( !p_input->stream.b_seekable )
                                input_SelectES( p_input, p_es );
903
                        }
904 905 906 907
#endif
                    }
                    else if( (i_id & 0xF0FF) == 0x80BD )
                    {
908
                        /* AC3 audio (0x80->0x8F) */
909 910
                        p_es->i_type = AC3_AUDIO_ES;
#ifdef AUTO_SPAWN
911 912
                        if( main_GetIntVariable( INPUT_DVD_AUDIO_VAR, 0 )
                                == REQUESTED_AC3
913
                         && main_GetIntVariable( INPUT_DVD_CHANNEL_VAR, 0 )
914
                                == ((p_es->i_id & 0xF00) >> 8) )
915
                        {
916 917
                            if( !p_input->stream.b_seekable )
                                input_SelectES( p_input, p_es );
918
                        }
919 920
#endif
                    }
921
                    else if( (i_id & 0xE0FF) == 0x20BD )
922
                    {
923
                        /* Subtitles video (0x20->0x3F) */
924 925
                        p_es->i_type = DVD_SPU_ES;
#ifdef AUTO_SPAWN
926
                        if( main_GetIntVariable( INPUT_DVD_SUBTITLE_VAR, 0 )
927
                                == ((p_es->i_id & 0x1F00) >> 8) )
928
                        {
929 930
                            if( !p_input->stream.b_seekable )
                                input_SelectES( p_input, p_es );
931
                        }
932 933
#endif
                    }
934 935 936 937 938 939
                    else if( (i_id & 0xF0FF) == 0xA0BD )
                    {
                        /* LPCM audio (0xA0->0xAF) */
                        p_es->i_type = LPCM_AUDIO_ES;
                        /* FIXME : write the decoder */
                    }
940 941 942 943 944 945 946 947 948 949 950 951 952
                    else
                    {
                        p_es->i_type = UNKNOWN_ES;
                    }
                }
            }
        } /* stream.b_is_ok */
        vlc_mutex_unlock( &p_input->stream.stream_lock );
    } /* i_code > 0xBC */

    return( p_es );
}

953 954 955 956 957 958 959 960 961 962
/*****************************************************************************
 * input_DemuxPS: first step of demultiplexing: the PS header
 *****************************************************************************/
void input_DemuxPS( input_thread_t * p_input, data_packet_t * p_data )
{
    u32                 i_code;
    boolean_t           b_trash = 0;
    es_descriptor_t *   p_es = NULL;

    i_code = U32_AT( p_data->p_buffer );
963
    if( i_code <= 0x1BC )
964 965 966 967 968 969 970
    {
        switch( i_code )
        {
        case 0x1BA: /* PACK_START_CODE */
            {
                /* Convert the SCR in microseconds. */
                mtime_t         scr_time;
971

972 973 974 975 976
                if( (p_data->p_buffer[4] & 0xC0) == 0x40 )
                {
                    /* MPEG-2 */
                    scr_time =
                      (( ((mtime_t)(p_data->p_buffer[4] & 0x38) << 27) |
977 978 979 980
                         ((mtime_t)(U32_AT(p_data->p_buffer + 4) & 0x03FFF800)
                                        << 4) |
                         ((mtime_t)(U32_AT(p_data->p_buffer + 6) & 0x03FFF800)
                                        >> 11)
981 982 983 984 985 986 987 988 989 990 991 992
                      ) * 300) / 27;
                }
                else
                {
                    /* MPEG-1 SCR is like PTS */
                    scr_time =
                      (( ((mtime_t)(p_data->p_buffer[4] & 0x0E) << 29) |
                         (((mtime_t)U16_AT(p_data->p_buffer + 5) << 14)
                           - (1 << 14)) |
                         ((mtime_t)U16_AT(p_data->p_buffer + 7) >> 1)
                      ) * 300) / 27;
                }
993
                /* Call the pace control. */
Sam Hocevar's avatar
 
Sam Hocevar committed
994
                //intf_Msg("+%lld", scr_time);
995 996
                CRDecode( p_input, p_input->stream.pp_programs[0],
                          scr_time );
997
                b_trash = 1;
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
            }
            break;

        case 0x1BB: /* SYSTEM_START_CODE */
            b_trash = 1;                              /* Nothing interesting */
            break;

        case 0x1BC: /* PROGRAM_STREAM_MAP_CODE */
            DecodePSM( p_input, p_data );
            b_trash = 1;
            break;
    
        case 0x1B9: /* PROGRAM_END_CODE */
            b_trash = 1;
            break;
   
        default:
            /* This should not happen */
            b_trash = 1;
            intf_WarnMsg( 1, "Unwanted packet received with start code %x",
                          i_code );
        }
    }
    else
    {
1023
        p_es = input_ParsePS( p_input, p_data );
1024

1025
        if( p_es != NULL && p_es->p_decoder_fifo != NULL )
1026 1027 1028 1029 1030 1031
        {
#ifdef STATS
            p_es->c_packets++;
#endif
            input_GatherPES( p_input, p_data, p_es, 1, 0 );
        }
1032 1033 1034 1035
        else
        {
            b_trash = 1;
        }
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    }

    /* Trash the packet if it has no payload or if it isn't selected */
    if( b_trash )
    {
        p_input->p_plugin->pf_delete_packet( p_input, p_data );
#ifdef STATS
        p_input->c_packets_trashed++;
#endif
    }
}


/*
 * TS Demultiplexing
 */

/*****************************************************************************
 * input_DemuxTS: first step of demultiplexing: the TS header
 *****************************************************************************/
void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
{
    int                 i_pid, i_dummy;
    boolean_t           b_adaptation;         /* Adaptation field is present */
    boolean_t           b_payload;                 /* Packet carries payload */
    boolean_t           b_unit_start;  /* A PSI or a PES start in the packet */
    boolean_t           b_trash = 0;             /* Is the packet unuseful ? */
    boolean_t           b_lost = 0;             /* Was there a packet loss ? */
    es_descriptor_t *   p_es = NULL;
    es_ts_data_t *      p_es_demux = NULL;
    pgrm_ts_data_t *    p_pgrm_demux = NULL;

#define p (p_data->p_buffer)

Sam Hocevar's avatar
 
Sam Hocevar committed
1070
    //intf_DbgMsg("input debug: TS-demultiplexing packet %p, pid %d",
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    //            p_ts_packet, U16_AT(&p[1]) & 0x1fff);

    /* Extract flags values from TS common header. */
    i_pid = U16_AT(&p[1]) & 0x1fff;
    b_unit_start = (p[1] & 0x40);
    b_adaptation = (p[3] & 0x20);
    b_payload = (p[3] & 0x10);

    /* Find out the elementary stream. */
    vlc_mutex_lock( &p_input->stream.stream_lock );
1081
    p_es = input_FindES( p_input, i_pid );
1082 1083
    vlc_mutex_unlock( &p_input->stream.stream_lock );

1084
    if( p_es == NULL || p_es->p_decoder_fifo == NULL )
1085 1086 1087 1088 1089 1090 1091
    {
        /* Not selected. Just read the adaptation field for a PCR. */
        b_trash = 1;
    }

    if( (p_es->p_decoder_fifo != NULL) || (p_pgrm_demux->i_pcr_pid == i_pid) )
    {
1092 1093 1094 1095
#ifdef STATS
        p_es->c_packets++;
#endif

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
        /* Extract adaptation field information if any */
        if( !b_adaptation )
        {
            /* We don't have any adaptation_field, so payload starts
             * immediately after the 4 byte TS header */
            p_data->p_payload_start += 4;
        }
        else
        {
            /* p[4] is adaptation_field_length minus one */
            p_data->p_payload_start += 5 + p[4];
    
            /* The adaptation field can be limited to the
             * adaptation_field_length byte, so that there is nothing to do:
             * skip this possibility */
            if( p[4] )
            {
                /* If the packet has both adaptation_field and payload,
                 * adaptation_field cannot be more than 182 bytes long; if
                 * there is only an adaptation_field, it must fill the next
                 * 183 bytes. */
                if( b_payload ? (p[4] > 182) : (p[4] != 183) )
                {
                    intf_WarnMsg( 2,
                        "invalid TS adaptation field (%p)",
                        p_data );
                    p_data->b_discard_payload = 1;
#ifdef STATS
                    p_es->c_invalid_packets++;
#endif
                }
    
                /* Now we are sure that the byte containing flags is present:
                 * read it */
                else
                {
                    /* discontinuity_indicator */
                    if( p[5] & 0x80 )
                    {
                        intf_WarnMsg( 2,
Sam Hocevar's avatar
 
Sam Hocevar committed
1136 1137
                            "discontinuity_indicator"
                            " encountered by TS demux (position read: %d,"
1138 1139 1140 1141 1142 1143
                            " saved: %d)",
                            p[5] & 0x80, p_es_demux->i_continuity_counter );
    
                        /* If the PID carries the PCR, there will be a system
                         * time-based discontinuity. We let the PCR decoder
                         * handle that. */
1144
                        p_es->p_pgrm->b_discontinuity = 1;
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    
                        /* There also may be a continuity_counter
                         * discontinuity: resynchronise our counter with
                         * the one of the stream. */
                        p_es_demux->i_continuity_counter = (p[3] & 0x0f) - 1;
                    }
    
                    /* If this is a PCR_PID, and this TS packet contains a
                     * PCR, we pass it along to the PCR decoder. */
                    if( (p_pgrm_demux->i_pcr_pid == i_pid) && (p[5] & 0x10) )
                    {
                        /* There should be a PCR field in the packet, check
                         * if the adaptation field is long enough to carry
                         * it. */
                        if( p[4] >= 7 )
                        {
                            /* Convert the PCR in microseconds.
                             * WARNING: do not remove the casts in the
                             * following calculation ! */
                            mtime_t     pcr_time;
                            pcr_time =
                                    ( (( (mtime_t)U32_AT((u32*)&p[6]) << 1 )
                                      | ( p[10] >> 7 )) * 300 ) / 27;
                            /* Call the pace control. */
1169
                            CRDecode( p_input, p_es->p_pgrm, pcr_time );
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
                        }
                    } /* PCR ? */
                } /* valid TS adaptation field ? */
            } /* length > 0 */
        } /* has adaptation field */
    
        /* Check the continuity of the stream. */
        i_dummy = ((p[3] & 0x0f) - p_es_demux->i_continuity_counter) & 0x0f;
        if( i_dummy == 1 )
        {
            /* Everything is ok, just increase our counter */
            p_es_demux->i_continuity_counter++;
        }
        else
        {
            if( !b_payload && i_dummy == 0 )
            {
Sam Hocevar's avatar
 
Sam Hocevar committed
1187 1188 1189 1190
                /* This is a packet without payload, this is allowed by the
                 * draft. As there is nothing interesting in this packet
                 * (except PCR that have already been handled), we can trash
                 * the packet. */
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
                intf_WarnMsg( 1,
                              "Packet without payload received by TS demux" );
                b_trash = 1;
            }
            else if( i_dummy <= 0 )
            {
                /* FIXME: this can never happen, can it ? --Meuuh */
                /* Duplicate packet: mark it as being to be trashed. */
                intf_WarnMsg( 1, "Duplicate packet received by TS demux" );
                b_trash = 1;
            }
            else if( p_es_demux->i_continuity_counter == 0xFF )
            {
Sam Hocevar's avatar
 
Sam Hocevar committed
1204 1205 1206 1207
                /* This means that the packet is the first one we receive for
                 * this ES since the continuity counter ranges between 0 and
                 * 0x0F excepts when it has been initialized by the input:
                 * init the counter to the correct value. */
1208 1209 1210 1211 1212 1213 1214
                intf_DbgMsg( "First packet for PID %d received by TS demux",
                             p_es->i_id );
                p_es_demux->i_continuity_counter = (p[3] & 0x0f);
            }
            else
            {
                /* This can indicate that we missed a packet or that the
Sam Hocevar's avatar
 
Sam Hocevar committed
1215 1216 1217
                 * continuity_counter wrapped and we received a dup packet:
                 * as we don't know, do as if we missed a packet to be sure
                 * to recover from this situation */
1218
                intf_WarnMsg( 2,
Sam Hocevar's avatar
 
Sam Hocevar committed
1219
                           "Packet lost by TS demux: current %d, packet %d",
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
                           p_es_demux->i_continuity_counter & 0x0f,
                           p[3] & 0x0f );
                b_lost = 1;
                p_es_demux->i_continuity_counter = p[3] & 0x0f;
            } /* not continuous */
        } /* continuity */
    } /* if selected or PCR */

    /* Trash the packet if it has no payload or if it isn't selected */
    if( b_trash )
    {
        p_input->p_plugin->pf_delete_packet( p_input, p_data );
#ifdef STATS
        p_input->c_packets_trashed++;
#endif
    }
    else
    {
        if( p_es_demux->b_psi )
        {
            /* The payload contains PSI tables */
#if 0
            input_DemuxPSI( p_input, p_data, p_es,
                            b_unit_start, b_lost );
#endif
        }
        else
        {
            /* The payload carries a PES stream */
            if( b_unit_start )
            input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost );
        }
    }

#undef p
}