mpeg_system.c 56.1 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * mpeg_system.c: TS, PS and PES management
 *****************************************************************************
 * Copyright (C) 1998, 1999, 2000 VideoLAN
Henri Fallon's avatar
 
Henri Fallon committed
5
 * $Id: mpeg_system.c,v 1.53 2001/05/02 13:30:30 henri Exp $
6
 *
7 8 9 10
 * Authors: Christophe Massiot <massiot@via.ecp.fr>
 *          Michel Lespinasse <walken@via.ecp.fr>
 *          Benot Steiner <benny@via.ecp.fr>
 *          Samuel Hocevar <sam@via.ecp.fr>
Henri Fallon's avatar
 
Henri Fallon committed
11
 *          Henri Fallon <henri@via.ecp.fr>
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * 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>
Sam Hocevar's avatar
 
Sam Hocevar committed
34
#include <string.h>                                    /* memcpy(), memset() */
Sam Hocevar's avatar
 
Sam Hocevar committed
35
#include <sys/types.h>                                              /* off_t */
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

#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"

51 52
#include "main.h"                           /* AC3/MPEG channel, SPU channel */

53 54 55 56
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/

Henri Fallon's avatar
 
Henri Fallon committed
57 58
static void input_DecodePAT( input_thread_t *, es_descriptor_t *);
static void input_DecodePMT( input_thread_t *, es_descriptor_t *);
59 60 61 62 63

/*
 * PES Packet management
 */

64 65 66 67 68
/*****************************************************************************
 * 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.
69
 * It also solves some alignment problems on non-IA-32, non-PPC processors.
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 111 112 113 114 115 116 117
 * 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 );
    }
}

118 119 120 121 122
/*****************************************************************************
 * input_ParsePES
 *****************************************************************************
 * Parse a finished PES packet and analyze its header.
 *****************************************************************************/
123
#define PES_HEADER_SIZE     7
124 125
void input_ParsePES( input_thread_t * p_input, es_descriptor_t * p_es )
{
126 127
    data_packet_t * p_data;
    byte_t *        p_byte;
128
    byte_t          p_header[PES_HEADER_SIZE];
129
    int             i_done;
130 131 132

#define p_pes (p_es->p_pes)

Sam Hocevar's avatar
 
Sam Hocevar committed
133
    //intf_DbgMsg("End of PES packet %p", p_pes);
134 135 136 137

    /* 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 */
138 139
    p_data = p_pes->p_first;
    p_byte = p_data->p_payload_start;
140 141
    i_done = 0;

142 143
    if( MoveChunk( p_header, &p_data, &p_byte, PES_HEADER_SIZE )
            != PES_HEADER_SIZE )
144 145
    {
        intf_WarnMsg( 3, "PES packet too short to have a header" );
Sam Hocevar's avatar
 
Sam Hocevar committed
146
        p_input->pf_delete_pes( p_input->p_method_data, p_pes );
147 148 149 150 151
        p_pes = NULL;
        return;
    }

    /* Get the PES size if defined */
152 153 154
    p_es->i_pes_real_size = U16_AT(p_header + 4);
    if( p_es->i_pes_real_size )
        p_es->i_pes_real_size += 6;
155 156 157 158 159 160 161

    /* 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" );
Sam Hocevar's avatar
 
Sam Hocevar committed
162
        p_input->pf_delete_pes( p_input->p_method_data, p_pes );
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        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" );
        }

        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:
193 194 195
            if( (p_header[6] & 0xC0) == 0x80 )
            {
                /* MPEG-2 : the PES header contains at least 3 more bytes. */
196
                size_t      i_max_len;
197 198
                boolean_t   b_has_pts, b_has_dts;
                byte_t      p_full_header[12];
199

200 201
                p_pes->b_data_alignment = p_header[6] & 0x04;

202
                i_max_len = MoveChunk( p_full_header, &p_data, &p_byte, 12 );
203 204 205 206
                if( i_max_len < 2 )
                {
                    intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-2 header" );
Sam Hocevar's avatar
 
Sam Hocevar committed
207 208
                    p_input->pf_delete_pes( p_input->p_method_data,
                                            p_pes );
209 210 211 212
                    p_pes = NULL;
                    return;
                }

213 214 215
                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;
216 217

                /* Now parse the optional header extensions */
218
                if( b_has_pts )
219
                {
220 221 222 223
                    if( i_max_len < 7 )
                    {
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-2 header" );
Sam Hocevar's avatar
 
Sam Hocevar committed
224 225
                        p_input->pf_delete_pes( p_input->p_method_data,
                                                p_pes );
226 227 228
                        p_pes = NULL;
                        return;
                    }
229
                    p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
230
                    ( ((mtime_t)(p_full_header[2] & 0x0E) << 29) |
231 232
                      ((mtime_t)(p_full_header[3]) << 22) |
                      ((mtime_t)(p_full_header[4] & 0xFE) << 14) |
233 234
                      ((mtime_t)p_full_header[5] << 7) |
                      ((mtime_t)p_full_header[6] >> 1) ) );
235 236 237 238 239 240 241

                    if( b_has_dts )
                    {
                        if( i_max_len < 12 )
                        {
                            intf_WarnMsg( 3,
                              "PES packet too short to have a MPEG-2 header" );
Sam Hocevar's avatar
 
Sam Hocevar committed
242 243
                            p_input->pf_delete_pes( p_input->p_method_data,
                                                    p_pes );
244 245 246
                            p_pes = NULL;
                            return;
                        }
247
                        p_pes->i_dts = input_ClockGetTS( p_input, p_es->p_pgrm,
248
                        ( ((mtime_t)(p_full_header[7] & 0x0E) << 29) |
249
                          (((mtime_t)U16_AT(p_full_header + 8) << 14)
250
                                - (1 << 14)) |
251
                          ((mtime_t)U16_AT(p_full_header + 10) >> 1) ) );
252
                    }
253 254 255 256 257
                }
            }
            else
            {
                /* Probably MPEG-1 */
258 259
                boolean_t       b_has_pts, b_has_dts;

260 261
                i_pes_header_size = 6;
                p_data = p_pes->p_first;
262 263 264 265
                p_byte = p_data->p_payload_start;
                /* Cannot fail because the previous one succeeded. */
                MoveChunk( NULL, &p_data, &p_byte, 6 );

266
                while( *p_byte == 0xFF && i_pes_header_size < 23 )
267 268
                {
                    i_pes_header_size++;
269
                    if( MoveChunk( NULL, &p_data, &p_byte, 1 ) != 1 )
270
                    {
271 272
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-1 header" );
Sam Hocevar's avatar
 
Sam Hocevar committed
273
                        p_input->pf_delete_pes( p_input->p_method_data, p_pes );
274 275
                        p_pes = NULL;
                        return;
276 277
                    }
                }
278
                if( i_pes_header_size == 23 )
279 280
                {
                    intf_ErrMsg( "Too much MPEG-1 stuffing" );
Sam Hocevar's avatar
 
Sam Hocevar committed
281
                    p_input->pf_delete_pes( p_input->p_method_data, p_pes );
282 283 284 285 286 287 288
                    p_pes = NULL;
                    return;
                }

                if( (*p_byte & 0xC0) == 0x40 )
                {
                    /* Don't ask why... --Meuuh */
Sam Hocevar's avatar
 
Sam Hocevar committed
289
                    /* Erm... why ? --Sam */
290 291
                    /* Well... According to the recommendation, it is for
                     * STD_buffer_scale and STD_buffer_size. --Meuuh */
292
                    i_pes_header_size += 2;
293
                    if( MoveChunk( NULL, &p_data, &p_byte, 2 ) != 2 )
294
                    {
295 296
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-1 header" );
Sam Hocevar's avatar
 
Sam Hocevar committed
297
                        p_input->pf_delete_pes( p_input->p_method_data, p_pes );
298 299
                        p_pes = NULL;
                        return;
300 301 302 303 304
                    }
                }

                i_pes_header_size++;

305 306 307 308
                b_has_pts = *p_byte & 0x20;
                b_has_dts = *p_byte & 0x10;

                if( b_has_pts )
309
                {
310
                    byte_t      p_ts[5];
311 312

                    i_pes_header_size += 4;
313
                    if( MoveChunk( p_ts, &p_data, &p_byte, 5 ) != 5 )
314
                    {
315 316
                        intf_WarnMsg( 3,
                            "PES packet too short to have a MPEG-1 header" );
Sam Hocevar's avatar
 
Sam Hocevar committed
317
                        p_input->pf_delete_pes( p_input->p_method_data, p_pes );
318 319
                        p_pes = NULL;
                        return;
320
                    }
321

322
                    p_pes->i_pts = input_ClockGetTS( p_input, p_es->p_pgrm,
323 324 325 326
                       ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
                         (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
                         ((mtime_t)p_ts[3] << 7) |
                         ((mtime_t)p_ts[4] >> 1) ) );
327 328 329 330 331 332 333 334

                    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" );
Sam Hocevar's avatar
 
Sam Hocevar committed
335 336
                            p_input->pf_delete_pes( p_input->p_method_data,
                                                    p_pes );
337 338 339 340
                            p_pes = NULL;
                            return;
                        }

341 342
                        p_pes->i_dts = input_ClockGetTS( p_input,
                                                         p_es->p_pgrm,
343
                            ( ((mtime_t)(p_ts[0] & 0x0E) << 29) |
344 345 346
                              (((mtime_t)U32_AT(p_ts) & 0xFFFE00) << 6) |
                              ((mtime_t)p_ts[3] << 7) |
                              ((mtime_t)p_ts[4] >> 1) ) );
347
                    }
348 349 350
                }
            }

351 352 353
            break;
        }

Sam Hocevar's avatar
 
Sam Hocevar committed
354
        if( p_es->i_stream_id == 0xbd )
355 356 357 358 359 360
        {
            /* With private stream 1, the first byte of the payload
             * is a stream_private_id, so skip it. */
            i_pes_header_size++;
        }

361 362 363 364
        /* 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. */
365 366 367
        p_data = p_pes->p_first;
        i_payload_size = p_data->p_payload_end
                                 - p_data->p_payload_start;
368 369 370 371
        while( i_pes_header_size > i_payload_size )
        {
            /* These packets are entirely filled by the PES header. */
            i_pes_header_size -= i_payload_size;
372
            p_data->p_payload_start = p_data->p_payload_end;
373
            /* Go to the next data packet. */
374
            if( (p_data = p_data->p_next) == NULL )
375 376
            {
                intf_ErrMsg( "PES header bigger than payload" );
Sam Hocevar's avatar
 
Sam Hocevar committed
377
                p_input->pf_delete_pes( p_input->p_method_data, p_pes );
378 379 380
                p_pes = NULL;
                return;
            }
381 382
            i_payload_size = p_data->p_payload_end
                                 - p_data->p_payload_start;
383 384 385 386 387
        }
        /* This last packet is partly header, partly payload. */
        if( i_payload_size < i_pes_header_size )
        {
            intf_ErrMsg( "PES header bigger than payload" );
Sam Hocevar's avatar
 
Sam Hocevar committed
388
            p_input->pf_delete_pes( p_input->p_method_data, p_pes );
389 390 391
            p_pes = NULL;
            return;
        }
392
        p_data->p_payload_start += i_pes_header_size;
393 394 395

        /* Now we can eventually put the PES packet in the decoder's
         * PES fifo */
396 397 398 399 400 401 402 403
        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);
Sam Hocevar's avatar
 
Sam Hocevar committed
404
            p_input->pf_delete_pes( p_input->p_method_data, p_pes );
405 406
        }
        p_pes = NULL;
407 408
    }
#undef p_pes
409

410 411 412 413 414 415 416
}

/*****************************************************************************
 * input_GatherPES:
 *****************************************************************************
 * Gather a PES packet.
 *****************************************************************************/
417
void input_GatherPES( input_thread_t * p_input, data_packet_t * p_data,
418 419 420 421 422
                      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
423
    //intf_DbgMsg("PES-demultiplexing %p (%p)", p_ts_packet, p_pes);
424

Sam Hocevar's avatar
 
Sam Hocevar committed
425
    /* If we lost data, insert a NULL data packet (philosophy : 0 is quite
426 427
     * often an escape sequence in decoders, so that should make them wait
     * for the next start code). */
428
    if( b_packet_lost )
429
    {
430
        input_NullPacket( p_input, p_es );
431 432 433 434
    }

    if( b_unit_start && p_pes != NULL )
    {
435
        /* If the data packet contains the begining of a new PES packet, and
436 437 438 439 440 441 442 443
         * 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... */
Sam Hocevar's avatar
 
Sam Hocevar committed
444
        p_input->pf_delete_packet( p_input->p_method_data, p_data );
445 446 447 448 449 450 451 452 453 454
    }
    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. */
Sam Hocevar's avatar
 
Sam Hocevar committed
455
            if( (p_pes = p_input->pf_new_pes( p_input->p_method_data ) ) == NULL )
456 457 458 459 460
            {
                intf_ErrMsg("Out of memory");
                p_input->b_error = 1;
                return;
            }
461
            p_pes->i_rate = p_input->stream.control.i_rate;
462
            p_pes->p_first = p_data;
Henri Fallon's avatar
 
Henri Fallon committed
463
            
464 465 466 467 468 469 470
            /* 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;
Henri Fallon's avatar
 
Henri Fallon committed
471
                
472 473
            }
            else
Henri Fallon's avatar
 
Henri Fallon committed
474
            { 
475
                p_es->i_pes_real_size = 0;
Henri Fallon's avatar
 
Henri Fallon committed
476
            } 
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        }
        else
        {
            /* Update the relations between the data packets */
            p_es->p_last->p_next = p_data;
        }

        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
}


/*
 * PS Demultiplexing
 */

505 506 507 508 509 510 511
/*****************************************************************************
 * GetID: Get the ID of a stream
 *****************************************************************************/
static u16 GetID( data_packet_t * p_data )
{
    u16         i_id;

512
    i_id = p_data->p_payload_start[3];                                 /* stream_id */
513 514
    if( i_id == 0xBD )
    {
515 516
        /* FIXME : this is not valid if the header is split in multiple
         * packets */
517
        /* stream_private_id */
518
        i_id |= p_data->p_payload_start[ 9 + p_data->p_payload_start[8] ] << 8;
519 520 521 522
    }
    return( i_id );
}

523 524
/*****************************************************************************
 * DecodePSM: Decode the Program Stream Map information
525 526
 *****************************************************************************
 * FIXME : loads are not aligned in this function
527 528 529 530 531
 *****************************************************************************/
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;
532 533 534 535
    byte_t *            p_byte;
    byte_t *            p_end;
    int                 i;
    int                 i_new_es_number = 0;
536

537
    if( p_data->p_payload_start + 10 > p_data->p_payload_end )
538
    {
539 540 541
        intf_ErrMsg( "PSM too short : packet corrupt" );
        return;
    }
542

543
    if( p_demux->b_has_PSM
544
        && p_demux->i_PSM_version == (p_data->p_payload_start[6] & 0x1F) )
545 546 547 548
    {
        /* Already got that one. */
        return;
    }
549

550
    intf_DbgMsg( "Building PSM" );
551
    p_demux->b_has_PSM = 1;
552
    p_demux->i_PSM_version = p_data->p_payload_start[6] & 0x1F;
553 554 555 556 557 558 559 560 561 562 563 564

    /* 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
565 566
     * Please note that CRC_32 is not included in the length. */
    p_end = p_byte + 2 + U16_AT(p_byte);
567 568 569 570 571 572
    p_byte += 2;
    if( p_end > p_data->p_payload_end )
    {
        intf_ErrMsg( "PSM too short : packet corrupt" );
        return;
    }
573

574 575 576 577 578 579 580 581 582 583 584 585 586 587
    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++ )
588
        {
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
            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;
605
                    i_new_es_number++;
606 607 608 609
                }
                break;
            }
        }
610

611 612 613 614 615
        /* 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 )
        {
616
            p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
617
                                i_stream_id, 0 );
618
            p_es->i_type = p_byte[0];
619 620 621 622 623
            p_es->b_audio = ( p_es->i_type == MPEG1_AUDIO_ES
                              || p_es->i_type == MPEG2_AUDIO_ES
                              || p_es->i_type == AC3_AUDIO_ES
                              || p_es->i_type == LPCM_AUDIO_ES
                            );
624

625 626 627 628 629
            /* 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;
630
            i_new_es_number++;
631 632
        }
        p_byte += 4 + U16_AT(&p_byte[2]);
633
    }
634 635 636 637 638

    /* 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++ )
639
    {
Sam Hocevar's avatar
 
Sam Hocevar committed
640 641
        /* We remove pp_es[i_new_es_member] and not pp_es[i] because the
         * list will be emptied starting from the end */
642 643
        input_DelES( p_input,
                     p_input->stream.pp_programs[0]->pp_es[i_new_es_number] );
644
    }
645 646 647 648 649 650

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

651
    vlc_mutex_unlock( &p_input->stream.stream_lock );
652 653
}

654 655 656 657 658 659 660 661 662
/*****************************************************************************
 * 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;

663
    i_code = p_data->p_payload_start[3];
Cyril Deguet's avatar
 
Cyril Deguet committed
664

665
    if( i_code > 0xBC ) /* ES start code */
666 667 668 669 670 671 672 673 674 675 676
    {
        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. */
677
            for( i_dummy = 0; i_dummy < p_input->stream.i_selected_es_number;
678
                 i_dummy++ )
679
            {
680 681
                if( p_input->stream.pp_selected_es[i_dummy] != NULL
                    && p_input->stream.pp_selected_es[i_dummy]->i_id == i_id )
682
                {
683
                    p_es = p_input->stream.pp_selected_es[i_dummy];
684 685 686 687 688 689
                    break;
                }
            }
        }
        else
        {
690 691 692
            stream_ps_data_t * p_demux =
              (stream_ps_data_t *)p_input->stream.pp_programs[0]->p_demux_data;

693
            /* Search all ES ; if not found -> AddES */
694
            p_es = input_FindES( p_input, i_id );
695

696
            if( p_es == NULL && !p_demux->b_has_PSM )
697 698 699 700 701
            {
                p_es = input_AddES( p_input, p_input->stream.pp_programs[0],
                                    i_id, 0 );
                if( p_es != NULL )
                {
702
                    p_es->i_stream_id = p_data->p_payload_start[3];
703 704 705 706 707 708

                    /* Set stream type and auto-spawn. */
                    if( (i_id & 0xF0) == 0xE0 )
                    {
                        /* MPEG video */
                        p_es->i_type = MPEG2_VIDEO_ES;
709
                        p_es->i_cat = VIDEO_ES;
710
#ifdef AUTO_SPAWN
711 712
                        if( !p_input->stream.b_seekable )
                            input_SelectES( p_input, p_es );
713 714 715 716 717 718
#endif
                    }
                    else if( (i_id & 0xE0) == 0xC0 )
                    {
                        /* MPEG audio */
                        p_es->i_type = MPEG2_AUDIO_ES;
719
                        p_es->b_audio = 1;
720
                        p_es->i_cat = AUDIO_ES;
721
#ifdef AUTO_SPAWN
722
                        if( !p_input->stream.b_seekable )
Sam Hocevar's avatar
 
Sam Hocevar committed
723
                        if( main_GetIntVariable( INPUT_CHANNEL_VAR, 0 )
724
                                == (p_es->i_id & 0x1F) )
Sam Hocevar's avatar
 
Sam Hocevar committed
725
                        switch( main_GetIntVariable( INPUT_AUDIO_VAR, 0 ) )
726
                        {
727
                        case 0:
Sam Hocevar's avatar
 
Sam Hocevar committed
728
                            main_PutIntVariable( INPUT_CHANNEL_VAR,
729 730 731
                                                 REQUESTED_MPEG );
                        case REQUESTED_MPEG:
                            input_SelectES( p_input, p_es );
732
                        }
733 734 735 736
#endif
                    }
                    else if( (i_id & 0xF0FF) == 0x80BD )
                    {
737
                        /* AC3 audio (0x80->0x8F) */
738
                        p_es->i_type = AC3_AUDIO_ES;
739
                        p_es->b_audio = 1;
740
                        p_es->i_cat = AUDIO_ES;
741
#ifdef AUTO_SPAWN
742
                        if( !p_input->stream.b_seekable )
Sam Hocevar's avatar
 
Sam Hocevar committed
743
                        if( main_GetIntVariable( INPUT_CHANNEL_VAR, 0 )
744
                                == ((p_es->i_id & 0xF00) >> 8) )
Sam Hocevar's avatar
 
Sam Hocevar committed
745
                        switch( main_GetIntVariable( INPUT_AUDIO_VAR, 0 ) )
746
                        {
747
                        case 0:
Sam Hocevar's avatar
 
Sam Hocevar committed
748
                            main_PutIntVariable( INPUT_CHANNEL_VAR,
749 750 751
                                                 REQUESTED_AC3 );
                        case REQUESTED_AC3:
                            input_SelectES( p_input, p_es );
752
                        }
753 754
#endif
                    }
755
                    else if( (i_id & 0xE0FF) == 0x20BD )
756
                    {
757
                        /* Subtitles video (0x20->0x3F) */
758
                        p_es->i_type = DVD_SPU_ES;
759
                        p_es->i_cat = SPU_ES;
760
#ifdef AUTO_SPAWN
Sam Hocevar's avatar
 
Sam Hocevar committed
761
                        if( main_GetIntVariable( INPUT_SUBTITLE_VAR, -1 )
762
                                == ((p_es->i_id & 0x1F00) >> 8) )
763
                        {
764 765
                            if( !p_input->stream.b_seekable )
                                input_SelectES( p_input, p_es );
766
                        }
767 768
#endif
                    }
769 770 771 772
                    else if( (i_id & 0xF0FF) == 0xA0BD )
                    {
                        /* LPCM audio (0xA0->0xAF) */
                        p_es->i_type = LPCM_AUDIO_ES;
773
                        p_es->b_audio = 1;
774
                        p_es->i_cat = AUDIO_ES;
775 776
                        /* FIXME : write the decoder */
                    }
777 778 779 780 781 782 783 784 785 786 787 788 789
                    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 );
}

790 791 792 793 794 795 796 797 798
/*****************************************************************************
 * 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;

799
    i_code = U32_AT( p_data->p_payload_start );
800
    if( i_code <= 0x1BC )
801 802 803 804 805
    {
        switch( i_code )
        {
        case 0x1BA: /* PACK_START_CODE */
            {
806
                /* Read the SCR. */
807
                mtime_t         scr_time;
Christophe Massiot's avatar
Christophe Massiot committed
808
                u32             i_mux_rate;
809

810
                if( (p_data->p_payload_start[4] & 0xC0) == 0x40 )
811 812
                {
                    /* MPEG-2 */
813 814 815 816 817 818 819 820 821 822
                    byte_t      p_header[14];
                    byte_t *    p_byte;
                    p_byte = p_data->p_payload_start;

                    if( MoveChunk( p_header, &p_data, &p_byte, 14 ) != 14 )
                    {
                        intf_WarnMsg( 3, "Packet too short to have a header" );
                        b_trash = 1;
                        break;
                    }
823
                    scr_time =
824 825
                         ((mtime_t)(p_header[4] & 0x38) << 27) |
                         ((mtime_t)(U32_AT(p_header + 4) & 0x03FFF800)
826
                                        << 4) |
827 828
                         ((( ((mtime_t)U16_AT(p_header + 6) << 16)
                            | (mtime_t)U16_AT(p_header + 8) ) & 0x03FFF800)
829
                                        >> 11);
Christophe Massiot's avatar
Christophe Massiot committed
830 831

                    /* mux_rate */
832 833
                    i_mux_rate = ((u32)U16_AT(p_header + 10) << 6)
                                   | (p_header[12] >> 2);
834 835 836
                }
                else
                {
837
                    /* MPEG-1 SCR is like PTS. */
838 839 840 841 842 843 844 845 846 847
                    byte_t      p_header[12];
                    byte_t *    p_byte;
                    p_byte = p_data->p_payload_start;

                    if( MoveChunk( p_header, &p_data, &p_byte, 12 ) != 12 )
                    {
                        intf_WarnMsg( 3, "Packet too short to have a header" );
                        b_trash = 1;
                        break;
                    }
848
                    scr_time =
849 850 851 852
                         ((mtime_t)(p_header[4] & 0x0E) << 29) |
                         (((mtime_t)U32_AT(p_header + 4) & 0xFFFE00) << 6) |
                         ((mtime_t)p_header[7] << 7) |
                         ((mtime_t)p_header[8] >> 1);
Christophe Massiot's avatar
Christophe Massiot committed
853 854

                    /* mux_rate */
855
                    i_mux_rate = (U32_AT(p_header + 8) & 0x7FFFFE) >> 1;
856
                }
857
                /* Call the pace control. */
858 859
                input_ClockManageRef( p_input, p_input->stream.pp_programs[0],
                                      scr_time );
Christophe Massiot's avatar
Christophe Massiot committed
860 861 862 863 864 865 866 867 868

                if( i_mux_rate != p_input->stream.i_mux_rate
                     && p_input->stream.i_mux_rate )
                {
                    intf_WarnMsg(2,
                                 "Mux_rate changed - expect cosmetic errors");
                }
                p_input->stream.i_mux_rate = i_mux_rate;

869
                b_trash = 1;
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
            }
            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;
Sam Hocevar's avatar
 
Sam Hocevar committed
889
            intf_WarnMsg( 1, "Unwanted packet received with start code 0x%.8x",
890 891 892 893 894
                          i_code );
        }
    }
    else
    {
895
        p_es = input_ParsePS( p_input, p_data );
896

897 898 899
        vlc_mutex_lock( &p_input->stream.control.control_lock );
        if( p_es != NULL && p_es->p_decoder_fifo != NULL
             && (!p_es->b_audio || !p_input->stream.control.b_mute) )
900
        {
901
            vlc_mutex_unlock( &p_input->stream.control.control_lock );
902 903 904 905 906
#ifdef STATS
            p_es->c_packets++;
#endif
            input_GatherPES( p_input, p_data, p_es, 1, 0 );
        }
907 908
        else
        {
909
            vlc_mutex_unlock( &p_input->stream.control.control_lock );
910 911
            b_trash = 1;
        }
912 913 914 915 916
    }

    /* Trash the packet if it has no payload or if it isn't selected */
    if( b_trash )
    {
Sam Hocevar's avatar
 
Sam Hocevar committed
917
        p_input->pf_delete_packet( p_input->p_method_data, p_data );
918 919 920 921 922 923
#ifdef STATS
        p_input->c_packets_trashed++;
#endif
    }
}

Henri Fallon's avatar
 
Henri Fallon committed
924
 
925 926 927 928 929 930 931 932 933
/*
 * TS Demultiplexing
 */

/*****************************************************************************
 * input_DemuxTS: first step of demultiplexing: the TS header
 *****************************************************************************/
void input_DemuxTS( input_thread_t * p_input, data_packet_t * p_data )
{
Henri Fallon's avatar
 
Henri Fallon committed
934 935
    u16                 i_pid;
    int                 i_dummy;
936 937 938 939 940
    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 ? */
Henri Fallon's avatar
 
Henri Fallon committed
941
    boolean_t           b_psi = 0;                        /* Is this a PSI ? */
942 943 944 945
    es_descriptor_t *   p_es = NULL;
    es_ts_data_t *      p_es_demux = NULL;
    pgrm_ts_data_t *    p_pgrm_demux = NULL;

Henri Fallon's avatar
 
Henri Fallon committed
946
    #define p (p_data->p_buffer)
947 948 949 950 951 952 953 954
    /* 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 );
Henri Fallon's avatar
 
Henri Fallon committed
955 956
        
    p_es= input_FindES( p_input, i_pid );
Henri Fallon's avatar
 
Henri Fallon committed
957
    
Henri Fallon's avatar
 
Henri Fallon committed
958 959 960 961 962 963
    if( (p_es != NULL) && (p_es->p_demux_data != NULL) )
    {
        p_es_demux = (es_ts_data_t *)p_es->p_demux_data;
        
        if( p_es_demux->b_psi )
            b_psi = 1;
Henri Fallon's avatar
 
Henri Fallon committed
964 965
        else
            p_pgrm_demux = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data; 
Henri Fallon's avatar
 
Henri Fallon committed
966 967
    }

968
    vlc_mutex_lock( &p_input->stream.control.control_lock );
Henri Fallon's avatar
 
Henri Fallon committed
969
    if( ( p_es == NULL ) || (p_es->b_audio && p_input->stream.control.b_mute) )
970 971 972 973
    {
        /* Not selected. Just read the adaptation field for a PCR. */
        b_trash = 1;
    }
Henri Fallon's avatar
 
Henri Fallon committed
974 975 976
    else if( p_es->p_decoder_fifo == NULL  && !b_psi )
      b_trash =1; 

977 978
    vlc_mutex_unlock( &p_input->stream.control.control_lock );
    vlc_mutex_unlock( &p_input->stream.stream_lock );
979

Henri Fallon's avatar
 
Henri Fallon committed
980

Henri Fallon's avatar
 
Henri Fallon committed
981 982
    /* Don't change the order of the tests : if b_psi then p_pgrm_demux 
     * may still be null. Who said it was ugly ? */
Henri Fallon's avatar
 
Henri Fallon committed
983 984 985
    if( ( p_es != NULL ) && 
        ((p_es->p_decoder_fifo != NULL) || b_psi 
                                   || (p_pgrm_demux->i_pcr_pid == i_pid) ) )
986
    {
987 988 989 990
#ifdef STATS
        p_es->c_packets++;
#endif

991
        /* Extract adaptation field information if any */
Henri Fallon's avatar
 
Henri Fallon committed
992

993 994 995 996 997 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 1023 1024 1025 1026 1027 1028 1029 1030 1031
        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
1032 1033
                            "discontinuity_indicator"
                            " encountered by TS demux (position read: %d,"
1034 1035 1036 1037 1038 1039
                            " 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. */
1040
                        p_es->p_pgrm->i_synchro_state = SYNCHRO_REINIT;
1041 1042 1043 1044 1045 1046 1047 1048 1049
    
                        /* 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. */
Henri Fallon's avatar
 
Henri Fallon committed
1050

Henri Fallon's avatar
 
Henri Fallon committed
1051
                    if( !b_psi && (p_pgrm_demux->i_pcr_pid == i_pid) && (p[5] & 0x10) )
1052 1053 1054 1055 1056 1057
                    {
                        /* There should be a PCR field in the packet, check
                         * if the adaptation field is long enough to carry
                         * it. */
                        if( p[4] >= 7 )
                        {
1058
                            /* Read the PCR. */
1059 1060
                            mtime_t     pcr_time;
                            pcr_time =
1061 1062
                                    ( (mtime_t)U32_AT((u32*)&p[6]) << 1 )
                                      | ( p[10] >> 7 );
1063
                            /* Call the pace control. */
1064 1065
                            input_ClockManageRef( p_input, p_es->p_pgrm,
                                                  pcr_time );
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                        }
                    } /* 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 */
Henri Fallon's avatar
 
Henri Fallon committed
1076
            (p_es_demux->i_continuity_counter)++;
1077 1078 1079 1080 1081
        }
        else
        {
            if( !b_payload && i_dummy == 0 )
            {
Sam Hocevar's avatar
 
Sam Hocevar committed
1082 1083 1084 1085
                /* 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. */
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
                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
1099 1100 1101 1102
                /* 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. */
1103 1104 1105 1106 1107 1108 1109
                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
1110 1111 1112
                 * 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 */
1113
                intf_WarnMsg( 2,
Sam Hocevar's avatar
 
Sam Hocevar committed
1114
                           "Packet lost by TS demux: current %d, packet %d",
1115 1116 1117 1118 1119 1120 1121
                           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 */
Henri Fallon's avatar
 
Henri Fallon committed
1122
    
1123 1124 1125
    /* Trash the packet if it has no payload or if it isn't selected */
    if( b_trash )
    {
Henri Fallon's avatar
 
Henri Fallon committed
1126
        p_input->pf_delete_packet( p_input->p_method_data, p_data );
1127 1128 1129 1130 1131 1132
#ifdef STATS
        p_input->c_packets_trashed++;
#endif
    }
    else
    {
Henri Fallon's avatar
 
Henri Fallon committed
1133
        if( b_psi )
1134 1135 1136 1137
        {
            /* The payload contains PSI tables */
            input_DemuxPSI( p_input, p_data, p_es,
                            b_unit_start, b_lost );
Henri Fallon's avatar
 
Henri Fallon committed
1138

1139 1140 1141 1142
        }
        else
        {
            /* The payload carries a PES stream */
Henri Fallon's avatar
 
Henri Fallon committed
1143
            input_GatherPES( p_input, p_data, p_es, b_unit_start, b_lost ); 
1144
        }
Henri Fallon's avatar
 
Henri Fallon committed
1145

1146 1147 1148
    }

#undef p
Henri Fallon's avatar
 
Henri Fallon committed
1149

1150
}
Henri Fallon's avatar
 
Henri Fallon committed
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174

/*
 * PSI demultiplexing and decoding
 */

/*****************************************************************************
 * DemuxPSI : makes up complete PSI data
 *****************************************************************************/
void input_DemuxPSI( input_thread_t * p_input, data_packet_t * p_data, 
        es_descriptor_t * p_es, boolean_t b_unit_start, boolean_t b_lost )
{
    es_ts_data_t  * p_demux_data;
    
    p_demux_data = (es_ts_data_t *)p_es->p_demux_data;

#define p_psi (p_demux_data->p_psi_section)
#define p (p_data->p_payload_start)

    if( b_unit_start )
    {
        /* unit_start set to 1 -> presence of a pointer field
         * (see ISO/IEC 13818 (2.4.4.2) which should be set to 0x00 */
        if( (u8)p[0] != 0x00 )
        {
Henri Fallon's avatar
 
Henri Fallon committed
1175 1176
            intf_WarnMsg( 2, 
                          "Non zero pointer field found. Trying to continue" );
Henri Fallon's avatar
 
Henri Fallon committed
1177 1178 1179 1180 1181 1182 1183 1184 1185
            p+=(u8)p[0];
        }
        else
            p++;

        /* This is the begining of a new section */

        if( ((u8)(p[1]) & 0xc0) != 0x80 ) 
        {
Henri Fallon's avatar
 
Henri Fallon committed
1186
            intf_WarnMsg( 2, "Invalid PSI packet" );
Henri Fallon's avatar
 
Henri Fallon committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 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 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
            p_psi->b_trash = 1;
        }
        else 
        {
            p_psi->i_section_length = U16_AT(p+1) & 0x0fff;
            p_psi->b_section_complete = 0;
            p_psi->i_read_in_section = 0;
            p_psi->i_section_number = (u8)p[6];

            if( p_psi->b_is_complete || p_psi->i_section_number == 0 )
            {
                /* This is a new PSI packet */
                p_psi->b_is_complete = 0;
                p_psi->b_trash = 0;
                p_psi->i_version_number = ( p[5] >> 1 ) & 0x1f;
                p_psi->i_last_section_number = (u8)p[7];

                /* We'll write at the begining of the buffer */
                p_psi->p_current = p_psi->buffer;
            }
            else
            {
                if( p_psi->b_section_complete )
                {
                    /* New Section of an already started PSI */
                    p_psi->b_section_complete = 0;
                    
                    if( p_psi->i_version_number != (( p[5] >> 1 ) & 0x1f) )
                    {
                        intf_WarnMsg( 2,"PSI version differs inside same PAT" );
                        p_psi->b_trash = 1;
                    }
                    if( p_psi->i_section_number + 1 != (u8)p[6] )
                    {
                        intf_WarnMsg( 2, 
                                "PSI Section discontinuity. Packet lost ?");
                        p_psi->b_trash = 1;
                    }
                    else
                        p_psi->i_section_number++;
                }
                else
                {
                    intf_WarnMsg( 2, "Received unexpected new PSI section" );
                    p_psi->b_trash = 1;
                }
            }
        }
    } /* b_unit_start */
    
    if( !p_psi->b_trash )
    {
        /* read */
        if( (p_data->p_payload_end - p) >=
            ( p_psi->i_section_length - p_psi->i_read_in_section ) )
        {
            /* The end of the section is in this TS packet */
            memcpy( p_psi->p_current, p, 
            (p_psi->i_section_length - p_psi->i_read_in_section) );
    
            p_psi->b_section_complete = 1;
            p_psi->p_current += 
                (p_psi->i_section_length - p_psi->i_read_in_section);
                        
            if( p_psi->i_section_number == p_psi->i_last_section_number )
            {
                /* This was the last section of PSI */
                p_psi->b_is_complete = 1;
            }
        }
        else
        {
            memcpy( p_psi->buffer, p, p_data->p_payload_end - p );
            p_psi->i_read_in_section+= p_data->p_payload_end - p;

            p_psi->p_current += p_data->p_payload_end - p;
        }
    }

    if ( p_psi->b_is_complete )
    {
        switch( p_demux_data->i_psi_type)
        {
            case PSI_IS_PAT:
                input_DecodePAT( p_input, p_es );
                break;
            case PSI_IS_PMT:
                input_DecodePMT( p_input, p_es );
                break;
            default:
Henri Fallon's avatar
 
Henri Fallon committed
1277
                intf_WarnMsg(2, "Received unknown PSI in demuxPSI");
Henri Fallon's avatar
 
Henri Fallon committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        }
    }
#undef p_psi    
#undef p
    
    return ;
}

/*****************************************************************************
 * DecodePAT : Decodes Programm association table and deal with it
 *****************************************************************************/
static void input_DecodePAT( input_thread_t * p_input, es_descriptor_t * p_es )
{
    
    stream_ts_data_t  * p_stream_data;
    es_ts_data_t      * p_demux_data;

    p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
    p_stream_data = (stream_ts_data_t *)p_input->stream.p_demux_data;
    
#define p_psi (p_demux_data->p_psi_section)

    if( p_stream_data->i_pat_version != p_psi->i_version_number )
    {
        /* PAT has changed. We are going to delete all programms and 
         * create new ones. We chose not to only change what was needed
         * as a PAT change may mean the stream is radically changing and
Henri Fallon's avatar
 
Henri Fallon committed
1305
         * this is a secure method to avoid krashes */
Henri Fallon's avatar
 
Henri Fallon committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
        pgrm_descriptor_t * p_pgrm;
        es_descriptor_t   * p_current_es;
        es_ts_data_t      * p_es_demux;
        pgrm_ts_data_t    * p_pgrm_demux;
        byte_t            * p_current_data;           
        
        int                 i_section_length,i_program_id,i_pmt_pid;
        int                 i_loop, i_current_section;
        
        p_current_data = p_psi->buffer;


        for( i_loop = 0; i_loop < p_input->stream.i_pgrm_number; i_loop++ )
        {
            input_DelProgram( p_input, p_input->stream.pp_programs[i_loop] );
        }
        
        do
        {
            i_section_length = U16_AT(p_current_data+1) & 0x0fff;
            i_current_section = (u8)p_current_data[6];
    
            for( i_loop = 0; i_loop < (i_section_length-9)/4 ; i_loop++ )
            {
                i_program_id = U16_AT(p_current_data + i_loop*4 + 8);
                i_pmt_pid = U16_AT( p_current_data + i_loop*4 + 10) & 0x1fff;
    
                /* If program = 0, we're having info about NIT not PMT */
                if( i_program_id )
                {
                    /* Add this program */
                    p_pgrm = input_AddProgram( p_input, i_program_id, 
                                               sizeof( pgrm_ts_data_t ) );
                   
                    /* whatis the PID of the PMT of this program */
                    p_pgrm_demux = (pgrm_ts_data_t *)p_pgrm->p_demux_data;
                    p_pgrm_demux->i_pmt_version = PMT_UNINITIALIZED;
    
                    /* Add the PMT ES to this program */
                    p_current_es = input_AddES( p_input, p_pgrm,(u16)i_pmt_pid,
                                        sizeof( es_ts_data_t) );
                    p_es_demux = (es_ts_data_t *)p_current_es->p_demux_data;
                    p_es_demux->b_psi = 1;
                    p_es_demux->i_psi_type = PSI_IS_PMT;
                    
                    p_es_demux->p_psi_section = 
                                            malloc( sizeof( psi_section_t ) );
                    p_es_demux->p_psi_section->b_is_complete = 0;
                }
            }
            
            p_current_data+=3+i_section_length;
            
        } while( i_current_section < p_psi->i_last_section_number );
        
        /* Go to the beginning of the next section*/
        p_stream_data->i_pat_version = p_psi->i_version_number;

    }
#undef p_psi    

}

/*****************************************************************************
 * DecodePMT : decode a given Program Stream Map
 * ***************************************************************************
 * When the PMT changes, it may mean a deep change in the stream, and it is
Henri Fallon's avatar
 
Henri Fallon committed
1373
 * careful to delete the ES and add them again. If the PMT doesn't change,
Henri Fallon's avatar
 
Henri Fallon committed
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
 * there no need to do anything.
 *****************************************************************************/
static void input_DecodePMT( input_thread_t * p_input, es_descriptor_t * p_es )
{

    pgrm_ts_data_t            * p_pgrm_data;
    es_ts_data_t              * p_demux_data;

    p_demux_data = (es_ts_data_t *)p_es->p_demux_data;
    p_pgrm_data = (pgrm_ts_data_t *)p_es->p_pgrm->p_demux_data;
    
#define p_psi (p_demux_data->p_psi_section)

    if( p_psi->i_version_number != p_pgrm_data->i_pmt_version ) 
    {
        es_descriptor_t   * p_new_es;  
        es_ts_data_t      * p_es_demux;
        byte_t            * p_current_data, * p_current_section;
        int                 i_section_length,i_current_section;
        int                 i_prog_info_length, i_loop;
        int                 i_es_info_length, i_pid, i_stream_type;
Henri Fallon's avatar
 
Henri Fallon committed
1395 1396
        int                 i_audio_es, i_spu_es;
        int                 i_required_audio_es, i_required_spu_es;
Henri Fallon's avatar
 
Henri Fallon committed
1397 1398 1399 1400 1401
        
        p_current_section = p_psi->buffer;
        p_current_data = p_psi->buffer;
        
        p_pgrm_data->i_pcr_pid = U16_AT(p_current_section + 8) & 0x1fff;
Henri Fallon's avatar
 
Henri Fallon committed
1402
        
Henri Fallon's avatar
 
Henri Fallon committed
1403 1404 1405
        i_audio_es = 0;
        i_spu_es = 0;
        
Henri Fallon's avatar
 
Henri Fallon committed
1406 1407
        /* Lock stream information */
        vlc_mutex_lock( &p_input->stream.stream_lock );
Henri Fallon's avatar
 
Henri Fallon committed
1408

Henri Fallon's avatar
 
Henri Fallon committed
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
        /* Get the number of the required audio stream */
        if( p_main->b_audio )
        {
            /* Default is the first one */
            i_required_audio_es = main_GetIntVariable( INPUT_CHANNEL_VAR, 1 );
            if( i_required_audio_es < 0 )
            {
                main_PutIntVariable( INPUT_CHANNEL_VAR, 1 );
                i_required_audio_es = 1;
            }
        }
        else
        {
            i_required_audio_es = 0;
        }

        /* Same thing for subtitles */
        if( p_main->b_video )
        {
            /* for spu, default is none */
            i_required_spu_es = main_GetIntVariable( INPUT_SUBTITLE_VAR, 0 );
            if( i_required_spu_es < 0 )
            {
                main_PutIntVariable( INPUT_SUBTITLE_VAR, 0 );
                i_required_spu_es = 0;
            }
        }
        else
        {
            i_required_spu_es = 0;
        }
        
Henri Fallon's avatar
 
Henri Fallon committed
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
        /* Delete all ES in this program  except the PSI */
        for( i_loop=0; i_loop < p_es->p_pgrm->i_es_number; i_loop++ )
        {
            p_es_demux = (es_ts_data_t *)
                         p_es->p_pgrm->pp_es[i_loop]->p_demux_data;
            if ( ! p_es_demux->b_psi )
            input_DelES( p_input, p_es->p_pgrm->pp_es[i_loop] );
        }

        /* Then add what we received in this PMT */
        do
        {
            
            i_section_length = U16_AT(p_current_data+1) & 0x0fff;
            i_current_section = (u8)p_current_data[6];
            i_prog_info_length = U16_AT(p_current_data+10) & 0x0fff;

            /* For the moment we ignore program descriptors */
            p_current_data += 12+i_prog_info_length;
    
            /* The end of the section, before the CRC is at 
             * p_current_section + i_section_length -1 */
            while( p_current_data < p_current_section + i_section_length -1 )
            {
                i_stream_type = (int)p_current_data[0];
                i_pid = U16_AT( p_current_data + 1 ) & 0x1fff;
                i_es_info_length = U16_AT( p_current_data + 3 ) & 0x0fff;
                
                /* Add this ES to the program */
                p_new_es = input_AddES( p_input, p_es->p_pgrm, 
                                        (u16)i_pid, sizeof( es_ts_data_t ) );
Henri Fallon's avatar
 
Henri Fallon committed
1472 1473

                /* Tell the decoders what kind of stream it is */
Henri Fallon's avatar
 
Henri Fallon committed
1474
                p_new_es->i_type = i_stream_type;
Henri Fallon's avatar
 
Henri Fallon committed
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492

                /* Tell the interface what kind of stream it is and select 
                 * the required ones */
                switch( i_stream_type )
                {
                    case MPEG1_VIDEO_ES:
                    case MPEG2_VIDEO_ES:
                        p_new_es->i_cat = VIDEO_ES;
                        input_SelectES( p_input, p_new_es );
                        break;
                    case MPEG1_AUDIO_ES:
                    case MPEG2_AUDIO_ES:
                    case LPCM_AUDIO_ES :
                        p_new_es->i_cat = AUDIO_ES;
                        i_audio_es += 1;
                        if( i_audio_es == i_required_audio_es )
                            input_SelectES( p_input, p_new_es );
                        break;
Henri Fallon's avatar
 
Henri Fallon committed
1493 1494 1495 1496 1497 1498 1499
                    case AC3_AUDIO_ES :
                        p_new_es->i_stream_id = 0xBD;
                        p_new_es->i_cat = AUDIO_ES;
                        i_audio_es += 1;
                        if( i_audio_es == i_required_audio_es )
                            input_SelectES( p_input, p_new_es );
                        break;
Henri Fallon's avatar
 
Henri Fallon committed
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
                    /* Not sure this one is fully norm-compliant */
                    case DVD_SPU_ES :
                        p_new_es->i_cat = SPU_ES;
                        i_spu_es += 1;
                        if( i_spu_es == i_required_spu_es )
                            input_SelectES( p_input, p_new_es );
                        break;
                    default :
                        p_new_es->i_cat = UNKNOWN_ES;
                        break;
                }
Henri Fallon's avatar
 
Henri Fallon committed
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
                
                p_current_data += 5 + i_es_info_length;
            }

            /* Go to the beginning of the next section*/
            p_current_data += 3+i_section_length;
           
            p_current_section+=1;
            
        } while( i_current_section < p_psi->i_last_section_number );

Henri Fallon's avatar
 
Henri Fallon committed
1522 1523 1524 1525 1526 1527
        if( i_required_audio_es > i_audio_es )
            intf_WarnMsg( 2, "TS input: Non-existing audio es required." );
        
        if( i_required_spu_es > i_spu_es )
            intf_WarnMsg( 2, "TS input: Non-existing subtitles es required." );
        
Henri Fallon's avatar
 
Henri Fallon committed
1528 1529
        p_pgrm_data->i_pmt_version = p_psi->i_version_number;

1530 1531
        /* inform interface that stream has changed */
        p_input->stream.b_changed = 1;
Henri Fallon's avatar
 
Henri Fallon committed
1532 1533 1534
    }
    
#undef p_psi
Henri Fallon's avatar
 
Henri Fallon committed
1535 1536 1537

    /*  Remove lock */
    vlc_mutex_unlock( &p_input->stream.stream_lock );
Henri Fallon's avatar
 
Henri Fallon committed
1538
}