ts.c 142 KB
Newer Older
1 2 3
/*****************************************************************************
 * ts.c: Transport Stream input module for VLC.
 *****************************************************************************
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
4
 * Copyright (C) 2004-2005 VLC authors and VideoLAN
5
 * $Id$
6 7
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8
 *          Jean-Paul Saman <jpsaman #_at_# m2x.nl>
9
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
10 11 12
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
13 14 15 16
 * (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
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
17 18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
19
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
20 21 22
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 24 25 26 27
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
28

29 30 31 32
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

33
#include <vlc_common.h>
34
#include <vlc_plugin.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
35

36
#include <assert.h>
37

38
#include <vlc_access.h>    /* DVB-specific things */
Clément Stenac's avatar
Clément Stenac committed
39 40
#include <vlc_demux.h>
#include <vlc_meta.h>
41
#include <vlc_epg.h>
42
#include <vlc_charset.h>   /* FromCharset, for EIT */
43

44 45
#include "../mux/mpeg/csa.h"

46
/* Include dvbpsi headers */
47 48 49 50 51 52 53 54
# include <dvbpsi/dvbpsi.h>
# include <dvbpsi/demux.h>
# include <dvbpsi/descriptor.h>
# include <dvbpsi/pat.h>
# include <dvbpsi/pmt.h>
# include <dvbpsi/sdt.h>
# include <dvbpsi/dr.h>
# include <dvbpsi/psi.h>
55

56
/* EIT support */
57
# include <dvbpsi/eit.h>
58 59

/* TDT support */
60
# include <dvbpsi/tot.h>
61

62 63
#include "../mux/mpeg/dvbpsi_compat.h"

64
#undef TS_DEBUG
65
VLC_FORMAT(1, 2) static void ts_debug(const char *format, ...)
66 67 68 69 70 71 72 73 74 75
{
#ifdef TS_DEBUG
    va_list ap;
    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);
#else
    (void)format;
#endif
}
76

77 78 79
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
Gildas Bazin's avatar
 
Gildas Bazin committed
80 81
static int  Open  ( vlc_object_t * );
static void Close ( vlc_object_t * );
82

83 84 85
/* TODO
 * - Rename "extra pmt" to "user pmt"
 * - Update extra pmt description
86
 *      pmt_pid[:pmt_number][=pid_description[,pid_description]]
87 88 89
 *      where pid_description could take 3 forms:
 *          1. pid:pcr (to force the pcr pid)
 *          2. pid:stream_type
90
 *          3. pid:type=fourcc where type=(video|audio|spu)
91
 */
92 93
#define PMT_TEXT N_("Extra PMT")
#define PMT_LONGTEXT N_( \
94
  "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])." )
95 96

#define PID_TEXT N_("Set id of ES to PID")
97 98 99 100
#define PID_LONGTEXT N_("Set the internal ID of each elementary stream" \
                       " handled by VLC to the same value as the PID in" \
                       " the TS stream, instead of 1, 2, 3, etc. Useful to" \
                       " do \'#duplicate{..., select=\"es=<pid>\"}\'.")
101

102 103 104
#define CSA_TEXT N_("CSA Key")
#define CSA_LONGTEXT N_("CSA encryption key. This must be a " \
  "16 char string (8 hexadecimal bytes).")
105

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
106 107 108 109
#define CSA2_TEXT N_("Second CSA Key")
#define CSA2_LONGTEXT N_("The even CSA encryption key. This must be a " \
  "16 char string (8 hexadecimal bytes).")

110

111 112 113 114 115
#define CPKT_TEXT N_("Packet size in bytes to decrypt")
#define CPKT_LONGTEXT N_("Specify the size of the TS packet to decrypt. " \
    "The decryption routines subtract the TS-header from the value before " \
    "decrypting. " )

116 117
#define SPLIT_ES_TEXT N_("Separate sub-streams")
#define SPLIT_ES_LONGTEXT N_( \
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
118
    "Separate teletex/dvbs pages into independent ES. " \
Rémi Denis-Courmont's avatar
Typos  
Rémi Denis-Courmont committed
119
    "It can be useful to turn off this option when using stream output." )
120

121 122 123
#define SEEK_PERCENT_TEXT N_("Seek based on percent not time")
#define SEEK_PERCENT_LONGTEXT N_( \
    "Seek and position based on a percent byte position, not a PCR generated " \
124
    "time position. If seeking doesn't work property, turn on this option." )
125

126 127
#define PCR_TEXT N_("Trust in-stream PCR")
#define PCR_LONGTEXT N_("Use the stream PCR as a reference.")
128

129 130 131 132 133 134
vlc_module_begin ()
    set_description( N_("MPEG Transport Stream demuxer") )
    set_shortname ( "MPEG-TS" )
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_DEMUX )

135
    add_string( "ts-extra-pmt", NULL, PMT_TEXT, PMT_LONGTEXT, true )
136 137
    add_bool( "ts-trust-pcr", true, PCR_TEXT, PCR_LONGTEXT, true )
        change_safe()
138
    add_bool( "ts-es-id-pid", true, PID_TEXT, PID_LONGTEXT, true )
139
        change_safe()
Rafaël Carré's avatar
Rafaël Carré committed
140 141
    add_obsolete_string( "ts-out" ) /* since 2.2.0 */
    add_obsolete_integer( "ts-out-mtu" ) /* since 2.2.0 */
142
    add_string( "ts-csa-ck", NULL, CSA_TEXT, CSA_LONGTEXT, true )
143
        change_safe()
144
    add_string( "ts-csa2-ck", NULL, CSA2_TEXT, CSA2_LONGTEXT, true )
145
        change_safe()
146
    add_integer( "ts-csa-pkt", 188, CPKT_TEXT, CPKT_LONGTEXT, true )
147 148
        change_safe()

149
    add_bool( "ts-split-es", true, SPLIT_ES_TEXT, SPLIT_ES_LONGTEXT, false )
150
    add_bool( "ts-seek-percent", false, SEEK_PERCENT_TEXT, SEEK_PERCENT_LONGTEXT, true )
151

152 153
    add_obsolete_bool( "ts-silent" );

154 155 156 157
    set_capability( "demux", 10 )
    set_callbacks( Open, Close )
    add_shortcut( "ts" )
vlc_module_end ()
158 159 160 161

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
162 163 164 165
static const char *const ppsz_teletext_type[] = {
 "",
 N_("Teletext"),
 N_("Teletext subtitles"),
166 167 168
 N_("Teletext: additional information"),
 N_("Teletext: program schedule"),
 N_("Teletext subtitles: hearing impaired")
169
};
170 171 172 173 174 175

typedef struct
{
    uint8_t                 i_objectTypeIndication;
    uint8_t                 i_streamType;

176 177
    int                     i_extra;
    uint8_t                 *p_extra;
178 179 180 181 182

} decoder_config_descriptor_t;

typedef struct
{
183
    bool                    b_ok;
184 185 186 187 188
    uint16_t                i_es_id;

    char                    *psz_url;

    decoder_config_descriptor_t    dec_descr;
189

190 191
} es_mpeg4_descriptor_t;

192
#define ES_DESCRIPTOR_COUNT 255
193 194 195 196 197
typedef struct
{
    /* IOD */
    char                    *psz_url;

198
    es_mpeg4_descriptor_t   es_descr[ES_DESCRIPTOR_COUNT];
199 200 201 202 203

} iod_descriptor_t;

typedef struct
{
204
    dvbpsi_handle   handle;
205 206 207
    int             i_version;
    int             i_number;
    int             i_pid_pcr;
208
    int             i_pid_pmt;
209
    mtime_t         i_pcr_value;
210 211
    /* IOD stuff (mpeg4) */
    iod_descriptor_t *iod;
212

213 214
} ts_prg_psi_t;

215 216 217 218
typedef struct
{
    /* for special PAT/SDT case */
    dvbpsi_handle   handle; /* PAT/SDT/EIT */
219
    int             i_pat_version;
220
    int             i_sdt_version;
221 222 223 224

    /* For PMT */
    int             i_prg;
    ts_prg_psi_t    **prg;
225

226 227
} ts_psi_t;

228 229 230 231 232 233
typedef enum
{
    TS_ES_DATA_PES,
    TS_ES_DATA_TABLE_SECTION
} ts_es_data_type_t;

234 235
typedef enum
{
236 237 238
    TS_PMT_REGISTRATION_NONE = 0,
    TS_PMT_REGISTRATION_HDMV
} ts_pmt_registration_type_t;
239

240 241 242 243
typedef struct
{
    es_format_t  fmt;
    es_out_id_t *id;
244
    ts_es_data_type_t data_type;
245 246 247
    int         i_data_size;
    int         i_data_gathered;
    block_t     *p_data;
248
    block_t     **pp_last;
249 250

    es_mpeg4_descriptor_t *p_mpeg4desc;
251

252 253 254 255 256 257
} ts_es_t;

typedef struct
{
    int         i_pid;

258 259
    bool        b_seen;
    bool        b_valid;
260
    int         i_cc;   /* countinuity counter */
261
    bool        b_scrambled;
262 263 264

    /* PSI owner (ie PMT -> PAT, ES -> PMT */
    ts_psi_t   *p_owner;
265
    int         i_owner_number;
266 267 268 269 270

    /* */
    ts_psi_t    *psi;
    ts_es_t     *es;

271 272 273 274
    /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
    ts_es_t     **extra_es;
    int         i_extra_es;

275 276 277 278
} ts_pid_t;

struct demux_sys_t
{
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
279 280
    vlc_mutex_t     csa_lock;

281 282 283
    /* TS packet size (188, 192, 204) */
    int         i_packet_size;

284 285 286
    /* Additional TS packet header size (BluRay TS packets have 4-byte header before sync byte) */
    int         i_packet_header_size;

287 288 289
    /* how many TS packet we read at once */
    int         i_ts_read;

290 291 292 293 294 295 296 297 298 299
    /* to determine length and time */
    int         i_pid_ref_pcr;
    mtime_t     i_first_pcr;
    mtime_t     i_current_pcr;
    mtime_t     i_last_pcr;
    bool        b_force_seek_per_percent;
    int         i_pcrs_num;
    mtime_t     *p_pcrs;
    int64_t     *p_pos;

300 301 302 303
    /* All pid */
    ts_pid_t    pid[8192];

    /* All PMT */
304
    bool        b_user_pmt;
305 306
    int         i_pmt;
    ts_pid_t    **pmt;
307
    int         i_pmt_es;
308 309

    /* */
310
    bool        b_es_id_pid;
311
    csa_t       *csa;
312
    int         i_csa_pkt_size;
313
    bool        b_split_es;
314

315
    bool        b_trust_pcr;
316

Laurent Aimar's avatar
Laurent Aimar committed
317 318 319 320 321
    /* */
    bool        b_access_control;

    /* */
    bool        b_dvb_meta;
322
    int64_t     i_tdt_delta;
323 324
    int64_t     i_dvb_start;
    int64_t     i_dvb_length;
325
    bool        b_broken_charset; /* True if broken encoding is used in EPG/SDT */
Laurent Aimar's avatar
Laurent Aimar committed
326 327 328

    /* */
    int         i_current_program;
329
    vlc_list_t  programs_list;
330

331 332
    /* */
    bool        b_start_record;
333 334
};

335
static int Demux    ( demux_t *p_demux );
336 337
static int Control( demux_t *p_demux, int i_query, va_list args );

338
static void PIDInit ( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner );
339
static void PIDClean( demux_t *, ts_pid_t *pid );
340
static void PIDFillFormat( es_format_t *fmt, int i_stream_type );
341

342 343
static void PATCallBack( void*, dvbpsi_pat_t * );
static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );
344 345 346 347
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
static void PSINewTableCallBack( dvbpsi_t *handle, uint8_t  i_table_id,
                                 uint16_t i_extension, demux_t * );
#else
348 349
static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
                                 uint8_t  i_table_id, uint16_t i_extension );
350 351
#endif

Laurent Aimar's avatar
Laurent Aimar committed
352
static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
353

354 355 356 357 358
static inline int PIDGet( block_t *p )
{
    return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
}

359
static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
360

361 362 363 364 365
static block_t* ReadTSPacket( demux_t *p_demux );
static int Seek( demux_t *p_demux, double f_percent );
static void GetFirstPCR( demux_t *p_demux );
static void GetLastPCR( demux_t *p_demux );
static void CheckPCR( demux_t *p_demux );
366 367
static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );

368
static void              IODFree( iod_descriptor_t * );
369

370
#define TS_USER_PMT_NUMBER (0)
371 372
static int UserPmt( demux_t *p_demux, const char * );

373 374
static int  SetPIDFilter( demux_t *, int i_pid, bool b_selected );
static void SetPrgFilter( demux_t *, int i_prg, bool b_selected );
Laurent Aimar's avatar
Laurent Aimar committed
375

376 377 378 379
#define TS_PACKET_SIZE_188 188
#define TS_PACKET_SIZE_192 192
#define TS_PACKET_SIZE_204 204
#define TS_PACKET_SIZE_MAX 204
380

381
static int DetectPacketSize( demux_t *p_demux, int *pi_header_size )
382
{
383
    const uint8_t *p_peek;
Laurent Aimar's avatar
Laurent Aimar committed
384 385 386
    if( stream_Peek( p_demux->s,
                     &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
        return -1;
387

388 389
    *pi_header_size = 0;

390
    if( memcmp( p_peek, "TFrc", 4 ) == 0 )
391 392
    {
#if 0
393
        /* I used the TF5000PVR 2004 Firmware .doc header documentation,
394 395 396
         * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
         * but after the filename the offsets seem to be incorrect.  - DJ */
        int i_duration, i_name;
397
        char *psz_name = xmalloc(25);
398
        char *psz_event_name;
399 400
        char *psz_event_text = xmalloc(130);
        char *psz_ext_text = xmalloc(1025);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

        // 2 bytes version Uimsbf (4,5)
        // 2 bytes reserved (6,7)
        // 2 bytes duration in minutes Uimsbf (8,9(
        i_duration = (int) (p_peek[8] << 8) | p_peek[9];
        msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
        // 2 bytes service number in channel list (10, 11)
        // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
        // 4 bytes of reserved + tuner info (14,15,16,17)
        // 2 bytes of Service ID  Bslbf (18,19)
        // 2 bytes of PMT PID  Uimsbf (20,21)
        // 2 bytes of PCR PID  Uimsbf (22,23)
        // 2 bytes of Video PID  Uimsbf (24,25)
        // 2 bytes of Audio PID  Uimsbf (26,27)
        // 24 bytes filename Bslbf
        memcpy( psz_name, &p_peek[28], 24 );
        psz_name[24] = '\0';
        msg_Dbg( p_demux, "recordingname=%s", psz_name );
        // 1 byte of sat index Uimsbf  (52)
        // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
        // 4 bytes of freq. Uimsbf (56,57,58,59)
        // 2 bytes of symbol rate Uimsbf (60,61)
        // 2 bytes of TS stream ID Uimsbf (62,63)
424
        // 4 bytes reserved
425 426 427 428 429 430 431 432 433 434
        // 2 bytes reserved
        // 2 bytes duration Uimsbf (70,71)
        //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
        //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
        // 4 bytes EventID Uimsbf (72-75)
        // 8 bytes of Start and End time info (76-83)
        // 1 byte reserved (84)
        // 1 byte event name length Uimsbf (89)
        i_name = (int)(p_peek[89]&~0x81);
        msg_Dbg( p_demux, "event name length = %d", i_name);
435
        psz_event_name = xmalloc( i_name+1 );
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
        // 1 byte parental rating (90)
        // 129 bytes of event text
        memcpy( psz_event_name, &p_peek[91], i_name );
        psz_event_name[i_name] = '\0';
        memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
        psz_event_text[129-i_name] = '\0';
        msg_Dbg( p_demux, "event name=%s", psz_event_name );
        msg_Dbg( p_demux, "event text=%s", psz_event_text );
        // 12 bytes reserved (220)
        // 6 bytes reserved
        // 2 bytes Event Text Length Uimsbf
        // 4 bytes EventID Uimsbf
        // FIXME We just have 613 bytes. not enough for this entire text
        // 1024 bytes Extended Event Text Bslbf
        memcpy( psz_ext_text, p_peek+372, 1024 );
        psz_ext_text[1024] = '\0';
        msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
        // 52 bytes reserved Bslbf
#endif
Laurent Aimar's avatar
Laurent Aimar committed
455 456
        msg_Dbg( p_demux, "this is a topfield file" );
        return TS_PACKET_SIZE_188;
457
    }
Laurent Aimar's avatar
Laurent Aimar committed
458 459

    for( int i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
460
    {
Laurent Aimar's avatar
Laurent Aimar committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        if( p_peek[i_sync] != 0x47 )
            continue;

        /* Check next 3 sync bytes */
        int i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
        if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
        {
            msg_Err( p_demux, "cannot peek" );
            return -1;
        }
        if( p_peek[i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
            p_peek[i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
            p_peek[i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
        {
            return TS_PACKET_SIZE_188;
        }
        else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
                 p_peek[i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
                 p_peek[i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
        {
481 482 483 484
            if( i_sync == 4 )
            {
                *pi_header_size = 4; /* BluRay TS packets have 4-byte header */
            }
Laurent Aimar's avatar
Laurent Aimar committed
485 486 487 488 489 490 491 492
            return TS_PACKET_SIZE_192;
        }
        else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
                 p_peek[i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
                 p_peek[i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
        {
            return TS_PACKET_SIZE_204;
        }
493
    }
494

Laurent Aimar's avatar
Laurent Aimar committed
495 496 497 498 499
    if( p_demux->b_force )
    {
        msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
        return TS_PACKET_SIZE_188;
    }
500
    msg_Dbg( p_demux, "TS module discarded (lost sync)" );
Laurent Aimar's avatar
Laurent Aimar committed
501 502 503
    return -1;
}

504 505 506 507 508 509 510 511 512 513 514 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
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
static void vlc_dvbpsi_reset( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    ts_pid_t *pat = &p_sys->pid[0];
    ts_pid_t *sdt = &p_sys->pid[0x11];
    ts_pid_t *eit = &p_sys->pid[0x12];
    ts_pid_t *tdt = &p_sys->pid[0x14];

    if( pat->psi->handle )
    {
        if( dvbpsi_decoder_present( pat->psi->handle ) )
            dvbpsi_pat_detach( pat->psi->handle );
        dvbpsi_delete( pat->psi->handle );
        pat->psi->handle = NULL;
    }

    if( sdt->psi->handle )
    {
        if( dvbpsi_decoder_present( sdt->psi->handle ) )
            dvbpsi_DetachDemux( sdt->psi->handle );
        dvbpsi_delete( sdt->psi->handle );
        sdt->psi->handle = NULL;
    }

    if( eit->psi->handle )
    {
        if( dvbpsi_decoder_present( eit->psi->handle ) )
            dvbpsi_DetachDemux( eit->psi->handle );
        dvbpsi_delete( eit->psi->handle );
        eit->psi->handle = NULL;
    }

    if( tdt->psi->handle )
    {
        if( dvbpsi_decoder_present( tdt->psi->handle ) )
            dvbpsi_DetachDemux( tdt->psi->handle );
        dvbpsi_delete( tdt->psi->handle );
        tdt->psi->handle = NULL;
    }
}
#endif

Laurent Aimar's avatar
Laurent Aimar committed
548 549 550 551 552 553 554 555
/*****************************************************************************
 * Open
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys;

556
    int          i_packet_size, i_packet_header_size = 0;
Laurent Aimar's avatar
Laurent Aimar committed
557 558 559 560

    ts_pid_t    *pat;

    /* Search first sync byte */
561
    i_packet_size = DetectPacketSize( p_demux, &i_packet_header_size );
Laurent Aimar's avatar
Laurent Aimar committed
562 563 564
    if( i_packet_size < 0 )
        return VLC_EGENERIC;

565
    p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
566 567
    if( !p_sys )
        return VLC_ENOMEM;
568
    memset( p_sys, 0, sizeof( demux_sys_t ) );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
569
    vlc_mutex_init( &p_sys->csa_lock );
570

571
    p_demux->pf_demux = Demux;
572 573 574
    p_demux->pf_control = Control;

    /* Init p_sys field */
Laurent Aimar's avatar
Laurent Aimar committed
575 576 577
    p_sys->b_dvb_meta = true;
    p_sys->b_access_control = true;
    p_sys->i_current_program = 0;
578 579
    p_sys->programs_list.i_count = 0;
    p_sys->programs_list.p_values = NULL;
580
    p_sys->i_tdt_delta = 0;
581
    p_sys->i_dvb_start = 0;
582 583
    p_sys->i_dvb_length = 0;

584 585
    p_sys->b_broken_charset = false;

Laurent Aimar's avatar
Laurent Aimar committed
586
    for( int i = 0; i < 8192; i++ )
587 588 589
    {
        ts_pid_t *pid = &p_sys->pid[i];
        pid->i_pid      = i;
590 591
        pid->b_seen     = false;
        pid->b_valid    = false;
592
    }
593
    /* PID 8191 is padding */
594
    p_sys->pid[8191].b_seen = true;
595
    p_sys->i_packet_size = i_packet_size;
596
    p_sys->i_packet_header_size = i_packet_header_size;
597
    p_sys->i_ts_read = 50;
598
    p_sys->csa = NULL;
599
    p_sys->b_start_record = false;
600

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
# define VLC_DVBPSI_DEMUX_TABLE_INIT(table,obj) \
    do { \
        (table)->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG ); \
        if( ! (table)->psi->handle ) \
        { \
            vlc_mutex_destroy( &p_sys->csa_lock ); \
            free( p_sys ); \
            return VLC_ENOMEM; \
        } \
        (table)->psi->handle->p_sys = (void *) VLC_OBJECT(obj); \
        if( !dvbpsi_AttachDemux( (table)->psi->handle, (dvbpsi_demux_new_cb_t)PSINewTableCallBack, (obj) ) ) \
        { \
            vlc_dvbpsi_reset( obj ); \
            vlc_mutex_destroy( &p_sys->csa_lock ); \
            free( p_sys ); \
            return VLC_EGENERIC; \
        } \
    } while (0);
#endif

622 623
    /* Init PAT handler */
    pat = &p_sys->pid[0];
624
    PIDInit( pat, true, NULL );
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
    pat->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
    if( !pat->psi->handle )
    {
        vlc_mutex_destroy( &p_sys->csa_lock );
        free( p_sys );
        return VLC_ENOMEM;
    }
    pat->psi->handle->p_sys = (void *) p_demux;
    if( !dvbpsi_pat_attach( pat->psi->handle, PATCallBack, p_demux ) )
    {
        vlc_dvbpsi_reset( p_demux );
        vlc_mutex_destroy( &p_sys->csa_lock );
        free( p_sys );
        return VLC_EGENERIC;
    }
#else
642
    pat->psi->handle = dvbpsi_AttachPAT( PATCallBack, p_demux );
643
#endif
Laurent Aimar's avatar
Laurent Aimar committed
644
    if( p_sys->b_dvb_meta )
645 646 647 648
    {
        ts_pid_t *sdt = &p_sys->pid[0x11];
        ts_pid_t *eit = &p_sys->pid[0x12];

649
        PIDInit( sdt, true, NULL );
650 651 652
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
        VLC_DVBPSI_DEMUX_TABLE_INIT( sdt, p_demux )
#else
653 654 655
        sdt->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
656
#endif
657
        PIDInit( eit, true, NULL );
658 659 660
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
        VLC_DVBPSI_DEMUX_TABLE_INIT( eit, p_demux )
#else
661 662 663
        eit->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
664
#endif
665
        ts_pid_t *tdt = &p_sys->pid[0x14];
666
        PIDInit( tdt, true, NULL );
667 668 669
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
        VLC_DVBPSI_DEMUX_TABLE_INIT( tdt, p_demux )
#else
670 671 672
        tdt->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
673 674
#endif

Laurent Aimar's avatar
Laurent Aimar committed
675
        if( p_sys->b_access_control )
676
        {
Laurent Aimar's avatar
Laurent Aimar committed
677 678 679
            if( SetPIDFilter( p_demux, 0x11, true ) ||
                SetPIDFilter( p_demux, 0x14, true ) ||
                SetPIDFilter( p_demux, 0x12, true ) )
Laurent Aimar's avatar
Laurent Aimar committed
680
                p_sys->b_access_control = false;
681 682
        }
    }
683

684 685 686 687
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
# undef VLC_DVBPSI_DEMUX_TABLE_INIT
#endif

688
    /* Init PMT array */
689
    TAB_INIT( p_sys->i_pmt, p_sys->pmt );
690
    p_sys->i_pmt_es = 0;
691

692
    /* Read config */
693
    p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
694

695 696
    p_sys->b_trust_pcr = var_CreateGetBool( p_demux, "ts-trust-pcr" );

697
    /* We handle description of an extra PMT */
Rafaël Carré's avatar
Rafaël Carré committed
698
    char* psz_string = var_CreateGetString( p_demux, "ts-extra-pmt" );
699
    p_sys->b_user_pmt = false;
700 701 702
    if( psz_string && *psz_string )
        UserPmt( p_demux, psz_string );
    free( psz_string );
703

704 705
    psz_string = var_CreateGetStringCommand( p_demux, "ts-csa-ck" );
    if( psz_string && *psz_string )
706
    {
707
        int i_res;
708
        char* psz_csa2;
709 710 711

        p_sys->csa = csa_New();

712 713 714
        psz_csa2 = var_CreateGetStringCommand( p_demux, "ts-csa2-ck" );
        i_res = csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, true );
        if( i_res == VLC_SUCCESS && psz_csa2 && *psz_csa2 )
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
715
        {
716
            if( csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_csa2, false ) != VLC_SUCCESS )
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
717
            {
718
                csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
719 720 721 722
            }
        }
        else if ( i_res == VLC_SUCCESS )
        {
723
            csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
724 725
        }
        else
726
        {
727
            csa_Delete( p_sys->csa );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
728
            p_sys->csa = NULL;
729
        }
730 731

        if( p_sys->csa )
732
        {
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
733 734 735
            var_AddCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, (void *)1 );
            var_AddCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );

736 737
            int i_pkt = var_CreateGetInteger( p_demux, "ts-csa-pkt" );
            if( i_pkt < 4 || i_pkt > 188 )
738
            {
739
                msg_Err( p_demux, "wrong packet size %d specified.", i_pkt );
740 741
                msg_Warn( p_demux, "using default packet size of 188 bytes" );
                p_sys->i_csa_pkt_size = 188;
742
            }
743 744
            else
                p_sys->i_csa_pkt_size = i_pkt;
745
            msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
746
        }
747
        free( psz_csa2 );
748
    }
749
    free( psz_string );
750

751
    p_sys->b_split_es = var_InheritBool( p_demux, "ts-split-es" );
752

753 754 755 756 757 758 759 760 761
    p_sys->i_pid_ref_pcr = -1;
    p_sys->i_first_pcr = -1;
    p_sys->i_current_pcr = -1;
    p_sys->i_last_pcr = -1;
    p_sys->b_force_seek_per_percent = var_InheritBool( p_demux, "ts-seek-percent" );
    p_sys->i_pcrs_num = 10;
    p_sys->p_pcrs = (mtime_t *)calloc( p_sys->i_pcrs_num, sizeof( mtime_t ) );
    p_sys->p_pos = (int64_t *)calloc( p_sys->i_pcrs_num, sizeof( int64_t ) );

762 763 764 765 766 767
    if( !p_sys->p_pcrs || !p_sys->p_pos )
    {
        Close( p_this );
        return VLC_ENOMEM;
    }

768
    bool can_seek = false;
769
    stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &can_seek );
770 771 772 773 774 775 776 777
    if( can_seek  )
    {
        GetFirstPCR( p_demux );
        CheckPCR( p_demux );
        GetLastPCR( p_demux );
    }
    if( p_sys->i_first_pcr < 0 || p_sys->i_last_pcr < 0 )
    {
778
        msg_Dbg( p_demux, "Force Seek Per Percent: PCR's not found,");
779 780 781
        p_sys->b_force_seek_per_percent = true;
    }

782
    while( p_sys->i_pmt_es <= 0 && vlc_object_alive( p_demux ) )
783
    {
784
        if( Demux( p_demux ) != 1 )
785 786
            break;
    }
787 788 789 790 791 792 793 794 795 796 797 798
    return VLC_SUCCESS;
}

/*****************************************************************************
 * Close
 *****************************************************************************/
static void Close( vlc_object_t *p_this )
{
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys = p_demux->p_sys;

    msg_Dbg( p_demux, "pid list:" );
799
    for( int i = 0; i < 8192; i++ )
800 801 802 803 804 805 806
    {
        ts_pid_t *pid = &p_sys->pid[i];

        if( pid->b_valid && pid->psi )
        {
            switch( pid->i_pid )
            {
Laurent Aimar's avatar
Laurent Aimar committed
807
            case 0: /* PAT */
808 809 810 811 812 813
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
                if( dvbpsi_decoder_present( pid->psi->handle ) )
                    dvbpsi_pat_detach( pid->psi->handle );
                dvbpsi_delete( pid->psi->handle );
                pid->psi->handle = NULL;
#else
Laurent Aimar's avatar
Laurent Aimar committed
814
                dvbpsi_DetachPAT( pid->psi->handle );
815
#endif
Laurent Aimar's avatar
Laurent Aimar committed
816 817 818 819 820 821
                free( pid->psi );
                break;
            case 1: /* CAT */
                free( pid->psi );
                break;
            default:
822
                if( p_sys->b_dvb_meta && ( pid->i_pid == 0x11 || pid->i_pid == 0x12 || pid->i_pid == 0x14 ) )
Laurent Aimar's avatar
Laurent Aimar committed
823
                {
824
                    /* SDT or EIT or TDT */
Laurent Aimar's avatar
Laurent Aimar committed
825
                    dvbpsi_DetachDemux( pid->psi->handle );
826 827 828 829
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
                    dvbpsi_delete( pid->psi->handle );
                    pid->psi->handle = NULL;
#endif
830
                    free( pid->psi );
Laurent Aimar's avatar
Laurent Aimar committed
831 832 833
                }
                else
                {
834
                    PIDClean( p_demux, pid );
Laurent Aimar's avatar
Laurent Aimar committed
835 836
                }
                break;
837 838 839 840
            }
        }
        else if( pid->b_valid && pid->es )
        {
841
            PIDClean( p_demux, pid );
842
        }
843

844 845
        if( pid->b_seen )
        {
846
            msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
847
        }
848

Laurent Aimar's avatar
Laurent Aimar committed
849 850 851
        /* too much */
        if( pid->i_pid > 0 )
            SetPIDFilter( p_demux, pid->i_pid, false );
852 853
    }

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
854
    vlc_mutex_lock( &p_sys->csa_lock );
855 856
    if( p_sys->csa )
    {
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
857 858
        var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
        var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
859 860
        csa_Delete( p_sys->csa );
    }
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
861
    vlc_mutex_unlock( &p_sys->csa_lock );
862

863
    TAB_CLEAN( p_sys->i_pmt, p_sys->pmt );
864

865
    free( p_sys->programs_list.p_values );
866

867 868 869
    free( p_sys->p_pcrs );
    free( p_sys->p_pos );

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
870
    vlc_mutex_destroy( &p_sys->csa_lock );
871 872 873
    free( p_sys );
}

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
/*****************************************************************************
 * ChangeKeyCallback: called when changing the odd encryption key on the fly.
 *****************************************************************************/
static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
                           vlc_value_t oldval, vlc_value_t newval,
                           void *p_data )
{
    VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys = p_demux->p_sys;
    int         i_tmp = (intptr_t)p_data;

    vlc_mutex_lock( &p_sys->csa_lock );
    if ( i_tmp )
        i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, true );
    else
        i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, false );

    vlc_mutex_unlock( &p_sys->csa_lock );
    return i_tmp;
}

896 897 898 899 900 901
/*****************************************************************************
 * Demux:
 *****************************************************************************/
static int Demux( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;
902
    bool b_wait_es = p_sys->i_pmt_es <= 0;
903 904

    /* We read at most 100 TS packet or until a frame is completed */
Laurent Aimar's avatar
Laurent Aimar committed
905
    for( int i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
906
    {
907
        bool         b_frame = false;
908
        block_t     *p_pkt;
909
        if( !(p_pkt = ReadTSPacket( p_demux )) )
910 911 912
        {
            return 0;
        }
913

914 915 916 917 918 919 920
        if( p_sys->b_start_record )
        {
            /* Enable recording once synchronized */
            stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, true, "ts" );
            p_sys->b_start_record = false;
        }

921
        /* Parse the TS packet */
Laurent Aimar's avatar
Laurent Aimar committed
922
        ts_pid_t *p_pid = &p_sys->pid[PIDGet( p_pkt )];
923 924 925 926 927

        if( p_pid->b_valid )
        {
            if( p_pid->psi )
            {
928
                if( p_pid->i_pid == 0 || ( p_sys->b_dvb_meta && ( p_pid->i_pid == 0x11 || p_pid->i_pid == 0x12 || p_pid->i_pid == 0x14 ) ) )
929 930 931 932 933
                {
                    dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
                }
                else
                {
Laurent Aimar's avatar
Laurent Aimar committed
934
                    for( int i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
935
                    {
936 937
                        dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
                                           p_pkt->p_buffer );
938 939
                    }
                }
940 941
                block_Release( p_pkt );
            }
942 943
            else
            {
Rafaël Carré's avatar
Rafaël Carré committed
944
                b_frame = GatherData( p_demux, p_pid, p_pkt );
945
            }
946 947 948 949 950
        }
        else
        {
            if( !p_pid->b_seen )
            {
951
                msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
952
            }
953 954
            /* We have to handle PCR if present */
            PCRHandle( p_demux, p_pid, p_pkt );
955 956
            block_Release( p_pkt );
        }
957
        p_pid->b_seen = true;
958

959
        if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) )
960 961 962
            break;
    }

963
    demux_UpdateTitleFromStream( p_demux );
964 965 966 967 968 969
    return 1;
}

/*****************************************************************************
 * Control:
 *****************************************************************************/
970 971 972 973 974 975 976 977
static int DVBEventInformation( demux_t *p_demux, int64_t *pi_time, int64_t *pi_length )
{
    demux_sys_t *p_sys = p_demux->p_sys;
    if( pi_length )
        *pi_length = 0;
    if( pi_time )
        *pi_time = 0;

978
    if( p_sys->i_dvb_length > 0 )
979
    {
980 981
        const int64_t t = mdate() + p_sys->i_tdt_delta;

982 983 984
        if( p_sys->i_dvb_start <= t && t < p_sys->i_dvb_start + p_sys->i_dvb_length )
        {
            if( pi_length )
985
                *pi_length = p_sys->i_dvb_length;
986
            if( pi_time )
987
                *pi_time   = t - p_sys->i_dvb_start;
988 989 990 991 992 993
            return VLC_SUCCESS;
        }
    }
    return VLC_EGENERIC;
}

994 995
static int Control( demux_t *p_demux, int i_query, va_list args )
{
996
    demux_sys_t *p_sys = p_demux->p_sys;
997
    double f, *pf;
998
    bool b_bool, *pb_bool;
999
    int64_t i64;
1000
    int64_t *pi64;
1001
    int i_int;
1002 1003 1004

    switch( i_query )
    {
Laurent Aimar's avatar
Laurent Aimar committed
1005 1006
    case DEMUX_GET_POSITION:
        pf = (double*) va_arg( args, double* );
1007 1008 1009 1010 1011

        if( p_sys->b_force_seek_per_percent ||
            (p_sys->b_dvb_meta && p_sys->b_access_control) ||
            p_sys->i_current_pcr - p_sys->i_first_pcr < 0 ||
            p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
Laurent Aimar's avatar
Laurent Aimar committed
1012 1013 1014 1015
        {
            int64_t i_time, i_length;
            if( !DVBEventInformation( p_demux, &i_time, &i_length ) && i_length > 0 )
                *pf = (double)i_time/(double)i_length;
1016
            else if( (i64 = stream_Size( p_demux->s) ) > 0 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1017 1018 1019 1020 1021
            {
                int64_t offset = stream_Tell( p_demux->s );

                *pf = (double)offset / (double)i64;
            }
1022
            else
Laurent Aimar's avatar
Laurent Aimar committed
1023 1024
                *pf = 0.0;
        }
1025 1026 1027 1028
        else
        {
            *pf = (double)(p_sys->i_current_pcr - p_sys->i_first_pcr) / (double)(p_sys->i_last_pcr - p_sys->i_first_pcr);
        }
Laurent Aimar's avatar
Laurent Aimar committed
1029
        return VLC_SUCCESS;
1030

Laurent Aimar's avatar
Laurent Aimar committed
1031 1032
    case DEMUX_SET_POSITION:
        f = (double) va_arg( args, double );
1033

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        if( p_sys->b_force_seek_per_percent ||
            (p_sys->b_dvb_meta && p_sys->b_access_control) ||
            p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
        {
            i64 = stream_Size( p_demux->s );
            if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
                return VLC_EGENERIC;
        }
        else
        {
            if( Seek( p_demux, f ) )
            {
                p_sys->b_force_seek_per_percent = true;
                return VLC_EGENERIC;
            }
        }
Laurent Aimar's avatar
Laurent Aimar committed
1050
        return VLC_SUCCESS;
1051

Laurent Aimar's avatar
Laurent Aimar committed
1052 1053
    case DEMUX_GET_TIME:
        pi64 = (int64_t*)va_arg( args, int64_t * );
1054
        if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
1055
            p_sys->b_force_seek_per_percent ||
1056
            p_sys->i_current_pcr - p_sys->i_first_pcr < 0 )
Laurent Aimar's avatar
Laurent Aimar committed
1057
        {
1058 1059 1060 1061 1062 1063 1064 1065
            if( DVBEventInformation( p_demux, pi64, NULL ) )
            {
                *pi64 = 0;
            }
        }
        else
        {
            *pi64 = (p_sys->i_current_pcr - p_sys->i_first_pcr) * 100 / 9;
Laurent Aimar's avatar
Laurent Aimar committed
1066 1067
        }
        return VLC_SUCCESS;
1068

Laurent Aimar's avatar
Laurent Aimar committed
1069 1070
    case DEMUX_GET_LENGTH:
        pi64 = (int64_t*)va_arg( args, int64_t * );
1071
        if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
1072
            p_sys->b_force_seek_per_percent ||
1073
            p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
Laurent Aimar's avatar
Laurent Aimar committed
1074
        {
1075 1076 1077 1078 1079 1080 1081 1082
            if( DVBEventInformation( p_demux, NULL, pi64 ) )
            {
                *pi64 = 0;
            }
        }
        else
        {
            *pi64 = (p_sys->i_last_pcr - p_sys->i_first_pcr) * 100 / 9;
Laurent Aimar's avatar
Laurent Aimar committed
1083 1084 1085 1086 1087 1088
        }
        return VLC_SUCCESS;

    case DEMUX_SET_GROUP:
    {
        vlc_list_t *p_list;
1089

Laurent Aimar's avatar
Laurent Aimar committed
1090 1091 1092
        i_int = (int)va_arg( args, int );
        p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
        msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
1093

1094 1095 1096 1097
        if( i_int == 0 && p_sys->i_current_program > 0 )
            i_int = p_sys->i_current_program;

        if( p_sys->i_current_program > 0 )
Laurent Aimar's avatar
Laurent Aimar committed
1098
        {
1099
            if( p_sys->i_current_program != i_int )
1100
                SetPrgFilter( p_demux, p_sys->i_current_program, false );
1101 1102 1103 1104 1105 1106
        }
        else if( p_sys->i_current_program < 0 )
        {
            for( int i = 0; i < p_sys->programs_list.i_count; i++ )
                SetPrgFilter( p_demux, p_sys->programs_list.p_values[i].i_int, false );
        }
1107

1108 1109 1110 1111
        if( i_int > 0 )
        {
            p_sys->i_current_program = i_int;
            SetPrgFilter( p_demux, p_sys->i_current_program, true );
1112
        }
1113
        else if( i_int < 0 )
Laurent Aimar's avatar
Laurent Aimar committed
1114 1115
        {
            p_sys->i_current_program = -1;
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
            p_sys->programs_list.i_count = 0;
            if( p_list )
            {
                vlc_list_t *p_dst = &p_sys->programs_list;
                free( p_dst->p_values );

                p_dst->p_values = calloc( p_list->i_count,
                                          sizeof(*p_dst->p_values) );
                if( p_dst->p_values )
                {
                    p_dst->i_count = p_list->i_count;
                    for( int i = 0; i < p_list->i_count; i++ )
1128
                    {
1129
                        p_dst->p_values[i] = p_list->p_values[i];
1130 1131
                        SetPrgFilter( p_demux, p_dst->p_values[i].i_int, true );
                    }
1132 1133
                }
            }
Laurent Aimar's avatar
Laurent Aimar committed
1134 1135 1136
        }
        return VLC_SUCCESS;
    }
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    case DEMUX_GET_TITLE_INFO:
    {
        struct input_title_t ***v = va_arg( args, struct input_title_t*** );
        int *c = va_arg( args, int * );

        *va_arg( args, int* ) = 0; /* Title offset */
        *va_arg( args, int* ) = 0; /* Chapter offset */
        return stream_Control( p_demux->s, STREAM_GET_TITLE_INFO, v, c );
    }

    case DEMUX_SET_TITLE:
1149
        return stream_vaControl( p_demux->s, STREAM_SET_TITLE, args );
1150 1151

    case DEMUX_SET_SEEKPOINT:
1152
        return stream_vaControl( p_demux->s, STREAM_SET_SEEKPOINT, args );
1153

1154
    case DEMUX_GET_META:
1155
        return stream_vaControl( p_demux->s, STREAM_GET_META, args );
1156

Laurent Aimar's avatar
Laurent Aimar committed
1157 1158 1159 1160
    case DEMUX_CAN_RECORD:
        pb_bool = (bool*)va_arg( args, bool * );
        *pb_bool = true;
        return VLC_SUCCESS;
1161

Laurent Aimar's avatar
Laurent Aimar committed
1162 1163
    case DEMUX_SET_RECORD_STATE:
        b_bool = (bool)va_arg( args, int );
1164

Laurent Aimar's avatar
Laurent Aimar committed
1165 1166 1167 1168
        if( !b_bool )
            stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, false );
        p_sys->b_start_record = b_bool;
        return VLC_SUCCESS;
1169

1170
    case DEMUX_GET_SIGNAL:
1171
        return stream_vaControl( p_demux->s, STREAM_GET_SIGNAL, args );
1172

Laurent Aimar's avatar
Laurent Aimar committed
1173 1174
    default:
        return VLC_EGENERIC;
1175 1176 1177
    }
}

1178 1179 1180 1181 1182 1183 1184 1185 1186
/*****************************************************************************
 *
 *****************************************************************************/
static int UserPmt( demux_t *p_demux, const char *psz_fmt )
{
    demux_sys_t *p_sys = p_demux->p_sys;
    char *psz_dup = strdup( psz_fmt );
    char *psz = psz_dup;
    int  i_pid;
1187
    int  i_number;
1188
    ts_prg_psi_t *prg = NULL;
1189 1190 1191 1192

    if( !psz_dup )
        return VLC_ENOMEM;

1193
    /* Parse PID */
1194 1195 1196 1197
    i_pid = strtol( psz, &psz, 0 );
    if( i_pid < 2 || i_pid >= 8192 )
        goto error;

1198 1199 1200 1201 1202 1203
    /* Parse optional program number */
    i_number = 0;
    if( *psz == ':' )
        i_number = strtol( &psz[1], &psz, 0 );

    /* */
1204 1205
    ts_pid_t *pmt = &p_sys->pid[i_pid];

1206
    msg_Dbg( p_demux, "user pmt specified (pid=%d,number=%d)", i_pid, i_number );
1207 1208 1209
    PIDInit( pmt, true, NULL );

    /* Dummy PMT */
1210
    prg = calloc( 1, sizeof( ts_prg_psi_t ) );
1211 1212 1213 1214 1215
    if( !prg )
        goto error;

    prg->i_pid_pcr  = -1;
    prg->i_pid_pmt  = -1;
1216 1217
    prg->i_version  = -1;
    prg->i_number   = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
    prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
    if( !prg->handle )
        goto error;
    prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
    if( !dvbpsi_pmt_attach( prg->handle,
                            ((i_number != TS_USER_PMT_NUMBER ? i_number : 1)),
                            PMTCallBack, p_demux ) )
    {
        dvbpsi_delete( prg->handle );
        prg->handle = NULL;
        goto error;
    }
#else
1232
    prg->handle     = dvbpsi_AttachPMT(
1233
        ((i_number != TS_USER_PMT_NUMBER) ? i_number : 1),
1234
        PMTCallBack, p_demux );
1235
#endif
1236 1237
    TAB_APPEND( pmt->psi->i_prg, pmt->psi->prg, prg );

1238 1239 1240
    psz = strchr( psz, '=' );
    if( psz )
        psz++;
1241 1242 1243
    while( psz && *psz )
    {
        char *psz_next = strchr( psz, ',' );
1244
        int i_pid;
1245 1246 1247 1248 1249

        if( psz_next )
            *psz_next++ = '\0';

        i_pid = strtol( psz, &psz, 0 );
1250 1251 1252 1253 1254
        if( *psz != ':' || i_pid < 2 || i_pid >= 8192 )
            goto next;

        char *psz_opt = &psz[1];
        if( !strcmp( psz_opt, "pcr" ) )
1255
        {
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
            prg->i_pid_pcr = i_pid;
        }
        else if( !p_sys->pid[i_pid].b_valid )
        {
            ts_pid_t *pid = &p_sys->pid[i_pid];

            char *psz_arg = strchr( psz_opt, '=' );
            if( psz_arg )
                *psz_arg++ = '\0';

            PIDInit( pid, false, pmt->psi);
            if( prg->i_pid_pcr <= 0 )
                prg->i_pid_pcr = i_pid;

            if( psz_arg && strlen( psz_arg ) == 4 )
1271
            {
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
                const vlc_fourcc_t i_codec = VLC_FOURCC( psz_arg[0], psz_arg[1],
                                                         psz_arg[2], psz_arg[3] );
                int i_cat = UNKNOWN_ES;
                es_format_t *fmt = &pid->es->fmt;

                if( !strcmp( psz_opt, "video" ) )
                    i_cat = VIDEO_ES;
                else if( !strcmp( psz_opt, "audio" ) )
                    i_cat = AUDIO_ES;
                else if( !strcmp( psz_opt, "spu" ) )
                    i_cat = SPU_ES;

                es_format_Init( fmt, i_cat, i_codec );
                fmt->b_packetized = false;
            }
            else
            {
                const int i_stream_type = strtol( psz_opt, NULL, 0 );
1290
                PIDFillFormat( &pid->es->fmt, i_stream_type );
1291 1292 1293 1294
            }
            pid->es->fmt.i_group = i_number;
            if( p_sys->b_es_id_pid )
                pid->es->fmt.i_id = i_pid;
1295

1296 1297 1298 1299 1300 1301
            if( pid->es->fmt.i_cat != UNKNOWN_ES )
            {
                msg_Dbg( p_demux, "  * es pid=%d fcc=%4.4s", i_pid,
                         (char*)&pid->es->fmt.i_codec );
                pid->es->id = es_out_Add( p_demux->out,
                                          &pid->es->fmt );
1302
                p_sys->i_pmt_es++;
1303 1304
            }
        }
1305 1306

    next:
1307 1308 1309
        psz = psz_next;
    }

1310 1311
    p_sys->b_user_pmt = true;
    TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
1312 1313 1314 1315
    free( psz_dup );
    return VLC_SUCCESS;

error:
1316
    free( prg );
1317 1318 1319 1320
    free( psz_dup );
    return VLC_EGENERIC;
}

Laurent Aimar's avatar
Laurent Aimar committed
1321 1322 1323 1324 1325 1326 1327
static int SetPIDFilter( demux_t *p_demux, int i_pid, bool b_selected )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    if( !p_sys->b_access_control )
        return VLC_EGENERIC;

1328 1329
    return stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_STATE,
                           i_pid, b_selected );
Laurent Aimar's avatar
Laurent Aimar committed
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 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
static void SetPrgFilter( demux_t *p_demux, int i_prg_id, bool b_selected )
{
    demux_sys_t *p_sys = p_demux->p_sys;
    ts_prg_psi_t *p_prg = NULL;
    int i_pmt_pid = -1;

    /* Search pmt to be unselected */
    for( int i = 0; i < p_sys->i_pmt; i++ )
    {
        ts_pid_t *pmt = p_sys->pmt[i];

        for( int i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
        {
            if( pmt->psi->prg[i_prg]->i_number == i_prg_id )
            {
                i_pmt_pid = p_sys->pmt[i]->i_pid;
                p_prg = p_sys->pmt[i]->psi->prg[i_prg];
                break;
            }
        }
        if( i_pmt_pid > 0 )
            break;
    }
    if( i_pmt_pid <= 0 )
        return;
    assert( p_prg );

    SetPIDFilter( p_demux, i_pmt_pid, b_selected );
    if( p_prg->i_pid_pcr > 0 )
        SetPIDFilter( p_demux, p_prg->i_pid_pcr, b_selected );

    /* All ES */
    for( int i = 2; i < 8192; i++ )
    {
        ts_pid_t *pid = &p_sys->pid[i];

        if( !pid->b_valid || pid->psi )
            continue;

        for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
        {
            if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
            {
                /* We only remove/select es that aren't defined by extra pmt */
                SetPIDFilter( p_demux, i, b_selected );
                break;
            }
        }
    }
}

1383
static void PIDInit( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner )
1384
{
1385
    bool b_old_valid = pid->b_valid;
1386

1387
    pid->b_valid    = true;
1388
    pid->i_cc       = 0xff;
1389
    pid->b_scrambled = false;
1390
    pid->p_owner    = p_owner;
1391
    pid->i_owner_number = 0;
1392

1393
    TAB_INIT( pid->i_extra_es, pid->extra_es );
1394

1395 1396 1397 1398
    if( b_psi )
    {
        pid->es  = NULL;

1399 1400
        if( !b_old_valid )
        {
1401
            pid->psi = xmalloc( sizeof( ts_psi_t ) );
Laurent Aimar's avatar
Laurent Aimar committed
1402 1403
            pid->psi->handle = NULL;
            TAB_INIT( pid->psi->i_prg, pid->psi->prg );
1404
        }
Laurent Aimar's avatar
Laurent Aimar committed
1405 1406
        assert( pid->psi );

1407
        pid->psi->i_pat_version  = -1;
1408
        pid->psi->i_sdt_version  = -1;
1409 1410 1411
        if( p_owner )
        {
            ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
            if( !prg )
                return;
            /* PMT */
            prg->i_version  = -1;
            prg->i_number   = -1;
            prg->i_pid_pcr  = -1;
            prg->i_pid_pmt  = -1;
            prg->i_pcr_value= -1;
            prg->iod        = NULL;
            prg->handle     = NULL;

            TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
1424
        }
1425 1426 1427 1428
    }
    else
    {
        pid->psi = NULL;
1429 1430 1431 1432 1433
        pid->es  = calloc( 1, sizeof( ts_es_t ) );
        if( !pid->es )
            return;

        es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
1434
        pid->es->data_type = TS_ES_DATA_PES;
1435
        pid->es->pp_last = &pid->es->p_data;
1436 1437 1438
    }
}

1439
static void PIDClean( demux_t *p_demux, ts_pid_t *pid )
1440
{
1441 1442 1443
    demux_sys_t *p_sys = p_demux->p_sys;
    es_out_t *out = p_demux->out;

1444 1445
    if( pid->psi )
    {
Laurent Aimar's avatar
Laurent Aimar committed
1446
        if( pid->psi->handle )
1447 1448 1449 1450 1451 1452 1453
        {
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
            if( dvbpsi_decoder_present( pid->psi->handle ) )
                dvbpsi_pmt_detach( pid->psi->handle );
            dvbpsi_delete( pid->psi->handle );
            pid->psi->handle = NULL;
#else
Laurent Aimar's avatar
Laurent Aimar committed
1454
            dvbpsi_DetachPMT( pid->psi->handle );
1455 1456
#endif
        }
Laurent Aimar's avatar
Laurent Aimar committed
1457
        for( int i = 0; i < pid->psi->i_prg; i++ )
1458
        {
1459 1460 1461
            if( pid->psi->prg[i]->iod )
                IODFree( pid->psi->prg[i]->iod );
            if( pid->psi->prg[i]->handle )
1462 1463 1464 1465 1466 1467
            {
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
                if( dvbpsi_decoder_present( pid->psi->prg[i]->handle ) )
                    dvbpsi_pmt_detach( pid->psi->prg[i]->handle );
                dvbpsi_delete( pid->psi->prg[i]->handle );
#else
1468
                dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
1469 1470
#endif
            }
1471 1472
            free( pid->psi->prg[i] );
        }
1473
        free( pid->psi->prg );
1474 1475 1476 1477 1478
        free( pid->psi );
    }
    else
    {
        if( pid->es->id )
1479
        {
1480
            es_out_Del( out, pid->es->id );
1481 1482
            p_sys->i_pmt_es--;
        }
1483

1484 1485
        if( pid->es->p_data )
            block_ChainRelease( pid->es->p_data );
1486 1487 1488

        es_format_Clean( &pid->es->fmt );

1489
        free( pid->es );
1490

Laurent Aimar's avatar
Laurent Aimar committed
1491
        for( int i = 0; i < pid->i_extra_es; i++ )
1492 1493
        {
            if( pid->extra_es[i]->id )
1494
            {
1495
                es_out_Del( out, pid->extra_es[i]->id );
1496 1497
                p_sys->i_pmt_es--;
            }
1498

1499 1500
            if( pid->extra_es[i]->p_data )
                block_ChainRelease( pid->extra_es[i]->p_data );
1501 1502 1503 1504 1505

            es_format_Clean( &pid->extra_es[i]->fmt );

            free( pid->extra_es[i] );
        }
Laurent Aimar's avatar
Laurent Aimar committed
1506 1507
        if( pid->i_extra_es )
            free( pid->extra_es );
1508
    }
1509

1510
    pid->b_valid = false;
1511 1512
}

1513 1514 1515
/****************************************************************************
 * gathering stuff
 ****************************************************************************/
1516
static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
1517
{
1518
    demux_sys_t *p_sys = p_demux->p_sys;
1519
    uint8_t header[34];
1520 1521
    unsigned i_pes_size = 0;
    unsigned i_skip = 0;
1522 1523
    mtime_t i_dts = -1;
    mtime_t i_pts = -1;
1524
    mtime_t i_length = 0;
1525 1526

    /* FIXME find real max size */
Pierre d'Herbemont's avatar
Pierre d'Herbemont committed
1527
    /* const int i_max = */ block_ChainExtract( p_pes, header, 34 );
1528

1529 1530
    if( header[0] != 0 || header[1] != 0 || header[2] != 1 )
    {
1531 1532
        msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
                    header[0], header[1],header[2],header[3], pid->i_pid );
1533 1534 1535 1536 1537 1538 1539
        block_ChainRelease( p_pes );
        return;
    }

    /* TODO check size */
    switch( header[3] )
    {
Laurent Aimar's avatar
Laurent Aimar committed
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
    case 0xBC:  /* Program stream map */
    case 0xBE:  /* Padding */
    case 0xBF:  /* Private stream 2 */
    case 0xF0:  /* ECM */
    case 0xF1:  /* EMM */
    case 0xFF:  /* Program stream directory */
    case 0xF2:  /* DSMCC stream */
    case 0xF8:  /* ITU-T H.222.1 type E stream */
        i_skip = 6;
        break;
    default:
        if( ( header[6]&0xC0 ) == 0x80 )
        {
            /* mpeg2 PES */
            i_skip = header[8] + 9;

            if( header[7]&0x80 )    /* has pts */
1557
            {
Laurent Aimar's avatar
Laurent Aimar committed
1558 1559 1560 1561 1562
                i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
                         (mtime_t)(header[10] << 22)|
                        ((mtime_t)(header[11]&0xfe) << 14)|
                         (mtime_t)(header[12] << 7)|
                         (mtime_t)(header[13] >> 1);
1563

Laurent Aimar's avatar
Laurent Aimar committed
1564
                if( header[7]&0x40 )    /* has dts */
1565
                {
Laurent Aimar's avatar
Laurent Aimar committed
1566 1567 1568 1569 1570
                     i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
                             (mtime_t)(header[15] << 22)|
                            ((mtime_t)(header[16]&0xfe) << 14)|
                             (mtime_t)(header[17] << 7)|
                             (mtime_t)(header[18] >> 1);
1571 1572
                }
            }
Laurent Aimar's avatar
Laurent Aimar committed
1573 1574 1575 1576 1577
        }
        else
        {
            i_skip = 6;
            while( i_skip < 23 && header[i_skip] == 0xff )
1578
            {
Laurent Aimar's avatar
Laurent Aimar committed
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
                i_skip++;
            }
            if( i_skip == 23 )
            {
                msg_Err( p_demux, "too much MPEG-1 stuffing" );
                block_ChainRelease( p_pes );
                return;
            }
            if( ( header[i_skip] & 0xC0 ) == 0x40 )
            {
                i_skip += 2;
            }
1591

Laurent Aimar's avatar
Laurent Aimar committed
1592 1593 1594 1595 1596 1597 1598
            if(  header[i_skip]&0x20 )
            {
                 i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
                          (mtime_t)(header[i_skip+1] << 22)|
                         ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
                          (mtime_t)(header[i_skip+3] << 7)|
                          (mtime_t)(header[i_skip+4] >> 1);
1599

Laurent Aimar's avatar
Laurent Aimar committed
1600 1601 1602 1603 1604 1605 1606 1607
                if( header[i_skip]&0x10 )    /* has dts */
                {
                     i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
                              (mtime_t)(header[i_skip+6] << 22)|
                             ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
                              (mtime_t)(header[i_skip+8] << 7)|
                              (mtime_t)(header[i_skip+9] >> 1);
                     i_skip += 10;
1608 1609 1610
                }
                else
                {
Laurent Aimar's avatar
Laurent Aimar committed
1611
                    i_skip += 5;
1612 1613
                }
            }
Laurent Aimar's avatar
Laurent Aimar committed
1614 1615 1616 1617 1618 1619
            else
            {
                i_skip += 1;
            }
        }
        break;
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
    }

    if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
        pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
    {
        i_skip += 4;
    }
    else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
             pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
             pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
    {
        i_skip += 1;
    }
1633
    else if( pid->es->fmt.i_codec == VLC_CODEC_SUBT &&
1634
             pid->es->p_mpeg4desc )
1635 1636 1637
    {
        decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;

1638 1639 1640
        if( dcd->i_extra > 2 &&
            dcd->p_extra[0] == 0x10 &&
            ( dcd->p_extra[1]&0x10 ) )
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
        {
            /* display length */
            if( p_pes->i_buffer + 2 <= i_skip )
                i_length = GetWBE( &p_pes->p_buffer[i_skip] );

            i_skip += 2;
        }
        if( p_pes->i_buffer + 2 <= i_skip )
            i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
        /* */
        i_skip += 2;
    }
1653

1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
    /* skip header */
    while( p_pes && i_skip > 0 )
    {
        if( p_pes->i_buffer <= i_skip )
        {
            block_t *p_next = p_pes->p_next;

            i_skip -= p_pes->i_buffer;
            block_Release( p_pes );
            p_pes = p_next;
        }
        else
        {
            p_pes->i_buffer -= i_skip;
            p_pes->p_buffer += i_skip;
            break;
        }
    }
1672

1673 1674 1675 1676
    /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
    if( i_pts >= 0 && i_dts < 0 )
        i_dts = i_pts;

1677 1678
    if( p_pes )
    {
1679 1680
        block_t *p_block;

1681
        if( i_dts >= 0 )
1682 1683
            p_pes->i_dts = VLC_TS_0 + i_dts * 100 / 9;

1684
        if( i_pts >= 0 )
1685 1686
            p_pes->i_pts = VLC_TS_0 + i_pts * 100 / 9;

1687
        p_pes->i_length = i_length * 100 / 9;
1688

1689
        p_block = block_ChainGather( p_pes );
1690
        if( pid->es->fmt.i_codec == VLC_CODEC_SUBT )
1691
        {
1692 1693 1694 1695 1696 1697
            if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
            {
                p_block->i_buffer = i_pes_size;
            }
            /* Append a \0 */
            p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
1698 1699
            if( !p_block )
                abort();
1700
            p_block->p_buffer[p_block->i_buffer -1] = '\0';
1701
        }
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
        else if( pid->es->fmt.i_codec == VLC_CODEC_TELETEXT )
        {
            if( p_block->i_pts <= VLC_TS_INVALID )
            {
                /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
                 * In this case use the last PCR + 40ms */
                for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
                {
                    if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
                    {
                        mtime_t i_pcr = pid->p_owner->prg[i]->i_pcr_value;
                        if( i_pcr > VLC_TS_INVALID )
                            p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
                        break;
                    }
                }
            }
        }
1720

1721
        for( int i = 0; i < pid->i_extra_es; i++ )
1722 1723 1724 1725 1726
        {
            es_out_Send( p_demux->out, pid->extra_es[i]->id,
                         block_Duplicate( p_block ) );
        }

1727 1728 1729
        if (!p_sys->b_trust_pcr)
            es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
                    pid->i_owner_number, p_block->i_pts);
1730

1731
        es_out_Send( p_demux->out, pid->es->id, p_block );
1732 1733 1734 1735 1736
    }
    else
    {
        msg_Warn( p_demux, "empty pes" );
    }
Gildas Bazin's avatar
 
Gildas Bazin committed
1737
}
1738

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
{
    block_t *p_content = block_ChainGather( p_data );
    mtime_t i_date = -1;
    for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
    {
        if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
        {
            i_date = pid->p_owner->prg[i]->i_pcr_value;
            if( i_date >= 0 )
                break;
        }
    }
    if( i_date >= 0 )
    {
        if( pid->es->fmt.i_codec == VLC_CODEC_SCTE_27 )
        {
            /* We need to extract the truncated pts stored inside the payload */
            if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
            {
                int i_index = 0;
1760
                size_t i_offset = 4;
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
                if( p_content->p_buffer[3] & 0x40 )
                {
                    i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
                              p_content->p_buffer[8];
                    i_offset = 9;
                }
                if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
                {
                    bool is_immediate = p_content->p_buffer[i_offset + 3] & 0x40;
                    if( !is_immediate )
                    {
                        mtime_t i_display_in = GetDWBE( &p_content->p_buffer[i_offset + 4] );
                        if( i_display_in < i_date )
                            i_date = i_display_in + (1ll << 32);
                        else
                            i_date = i_display_in;
                    }

                }
            }
        }
        p_content->i_dts =
        p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
    }
    es_out_Send( p_demux->out, pid->es->id, p_content );
}
static void ParseData( demux_t *p_demux, ts_pid_t *pid )
{
    block_t *p_data = pid->es->p_data;

    /* remove the pes from pid */
    pid->es->p_data = NULL;
    pid->es->i_data_size = 0;
    pid->es->i_data_gathered = 0;
    pid->es->pp_last = &pid->es->p_data;

    if( pid->es->data_type == TS_ES_DATA_PES )
    {
        ParsePES( p_demux, pid, p_data );
    }
    else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
    {
        ParseTableSection( p_demux, pid, p_data );
    }
    else
    {
        block_ChainRelease( p_data );
    }
}

1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
static block_t* ReadTSPacket( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    block_t     *p_pkt;

    /* Get a new TS packet */
    if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
    {
        msg_Dbg( p_demux, "eof ?" );
        return NULL;
    }

1824 1825 1826 1827 1828 1829 1830
    /* Skip header (BluRay streams).
     * re-sync logic would do this (by adjusting packet start), but this would result in losing first and last ts packets.
     * First packet is usually PAT, and losing it means losing whole first GOP. This is fatal with still-image based menus.
     */
    p_pkt->p_buffer += p_sys->i_packet_header_size;
    p_pkt->i_buffer -= p_sys->i_packet_header_size;

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
    /* Check sync byte and re-sync if needed */
    if( p_pkt->p_buffer[0] != 0x47 )
    {
        msg_Warn( p_demux, "lost synchro" );
        block_Release( p_pkt );
        while( vlc_object_alive (p_demux) )
        {
            const uint8_t *p_peek;
            int i_peek, i_skip = 0;

            i_peek = stream_Peek( p_demux->s, &p_peek,
                    p_sys->i_packet_size * 10 );
            if( i_peek < p_sys->i_packet_size + 1 )
            {
                msg_Dbg( p_demux, "eof ?" );
                return NULL;
            }

            while( i_skip < i_peek - p_sys->i_packet_size )
            {
1851 1852
                if( p_peek[i_skip + p_sys->i_packet_header_size] == 0x47 &&
                        p_peek[i_skip + p_sys->i_packet_header_size + p_sys->i_packet_size] == 0x47 )
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
                {
                    break;
                }
                i_skip++;
            }
            msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
            stream_Read( p_demux->s, NULL, i_skip );

            if( i_skip < i_peek - p_sys->i_packet_size )
            {
                break;
            }
        }
        if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
        {
            msg_Dbg( p_demux, "eof ?" );
            return NULL;
        }
    }
    return p_pkt;
}

static mtime_t AdjustPCRWrapAround( demux_t *p_demux, mtime_t i_pcr )
1876 1877
{
    demux_sys_t   *p_sys = p_demux->p_sys;
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
    /*
     * PCR is 33bit. If PCR reaches to 0x1FFFFFFFF (26:30:43.717), ressets from 0.
     * So, need to add 0x1FFFFFFFF, for calculating duration or current position.
     */
    mtime_t i_adjust = 0;
    int64_t i_pos = stream_Tell( p_demux->s );
    int i;
    for( i = 1; i < p_sys->i_pcrs_num && p_sys->p_pos[i] <= i_pos; ++i )
    {
        if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
            i_adjust += 0x1FFFFFFFF;
    }
    if( p_sys->p_pcrs[i-1] > i_pcr )
        i_adjust += 0x1FFFFFFFF;
1892

1893 1894 1895 1896 1897 1898 1899 1900
    return i_pcr + i_adjust;
}

static mtime_t GetPCR( block_t *p_pkt )
{
    const uint8_t *p = p_pkt->p_buffer;

    mtime_t i_pcr = -1;
1901

1902 1903 1904 1905
    if( ( p[3]&0x20 ) && /* adaptation */
        ( p[5]&0x10 ) &&
        ( p[4] >= 7 ) )
    {
Laurent Aimar's avatar
Laurent Aimar committed
1906
        /* PCR is 33 bits */
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
        i_pcr = ( (mtime_t)p[6] << 25 ) |
                ( (mtime_t)p[7] << 17 ) |
                ( (mtime_t)p[8] << 9 ) |
                ( (mtime_t)p[9] << 1 ) |
                ( (mtime_t)p[10] >> 7 );
    }
    return i_pcr;
}

static int SeekToPCR( demux_t *p_demux, int64_t i_pos )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    mtime_t i_pcr = -1;
1921
    const int64_t i_initial_pos = stream_Tell( p_demux->s );
1922 1923 1924 1925

    if( i_pos < 0 )
        return VLC_EGENERIC;

1926 1927 1928
    int64_t i_last_pos = stream_Size( p_demux->s ) - p_sys->i_packet_size;
    if( i_pos > i_last_pos )
        i_pos = i_last_pos;
1929 1930 1931 1932 1933 1934

    if( stream_Seek( p_demux->s, i_pos ) )
        return VLC_EGENERIC;

    while( vlc_object_alive( p_demux ) )
    {
1935 1936
        block_t *p_pkt;

1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
        if( !( p_pkt = ReadTSPacket( p_demux ) ) )
        {
            break;
        }
        if( PIDGet( p_pkt ) == p_sys->i_pid_ref_pcr )
        {
            i_pcr = GetPCR( p_pkt );
        }
        block_Release( p_pkt );
        if( i_pcr >= 0 )
            break;
        if( stream_Tell( p_demux->s ) >= i_last_pos )
            break;
    }
    if( i_pcr < 0 )
    {
        stream_Seek( p_demux->s, i_initial_pos );
1954
        assert( i_initial_pos == stream_Tell( p_demux->s ) );
1955 1956
        return VLC_EGENERIC;
    }
1957 1958 1959

    p_sys->i_current_pcr = i_pcr;
    return VLC_SUCCESS;
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
}

static int Seek( demux_t *p_demux, double f_percent )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    int64_t i_initial_pos = stream_Tell( p_demux->s );
    mtime_t i_initial_pcr = p_sys->i_current_pcr;

    /*
     * Find the time position by using binary search algorithm.
     */
    mtime_t i_target_pcr = (p_sys->i_last_pcr - p_sys->i_first_pcr) * f_percent + p_sys->i_first_pcr;

    int64_t i_head_pos = 0;
1975
    int64_t i_tail_pos;
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    {
        mtime_t i_adjust = 0;
        int i;
        for( i = 1; i < p_sys->i_pcrs_num; ++i )
        {
            if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
                i_adjust += 0x1FFFFFFFF;
            if( p_sys->p_pcrs[i] + i_adjust > i_target_pcr )
                break;
        }
        i_head_pos = p_sys->p_pos[i-1];
        i_tail_pos = ( i < p_sys->i_pcrs_num ) ?  p_sys->p_pos[i] : stream_Size( p_demux->s );
    }
Rafaël Carré's avatar
Rafaël Carré committed
1989
    msg_Dbg( p_demux, "Seek():i_head_pos:%"PRId64", i_tail_pos:%"PRId64, i_head_pos, i_tail_pos);
1990 1991 1992 1993 1994

    bool b_found = false;
    int i_cnt = 0;
    while( i_head_pos <= i_tail_pos )
    {
1995
        /* Round i_pos to a multiple of p_sys->i_packet_size */
1996
        int64_t i_pos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
1997 1998
        int64_t i_div = i_pos % p_sys->i_packet_size;
        i_pos -= i_div;
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
        if( SeekToPCR( p_demux, i_pos ) )
            break;
        p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
        int64_t i_diff_msec = (p_sys->i_current_pcr - i_target_pcr) * 100 / 9 / 1000;
        if( i_diff_msec > 500 )
        {
            i_tail_pos = i_pos - p_sys->i_packet_size;
        }
        else if( i_diff_msec < -500 )
        {
            i_head_pos = i_pos + p_sys->i_packet_size;
        }
        else
        {
            // diff time <= 500msec
            b_found = true;
            break;
        }
        ++i_cnt;
    }
    if( !b_found )
    {
        msg_Dbg( p_demux, "Seek():cannot find a time position. i_cnt:%d", i_cnt );
        stream_Seek( p_demux->s, i_initial_pos );
        p_sys->i_current_pcr = i_initial_pcr;
        return VLC_EGENERIC;
    }
    else
    {
        msg_Dbg( p_demux, "Seek():can find a time position. i_cnt:%d", i_cnt );
        return VLC_SUCCESS;
    }
}

static void GetFirstPCR( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    int64_t i_initial_pos = stream_Tell( p_demux->s );

    if( stream_Seek( p_demux->s, 0 ) )
        return;

    while( vlc_object_alive (p_demux) )
    {
        block_t     *p_pkt;
2045

2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
        if( !( p_pkt = ReadTSPacket( p_demux ) ) )
        {
            break;
        }
        mtime_t i_pcr = GetPCR( p_pkt );
        if( i_pcr >= 0 )
        {
            p_sys->i_pid_ref_pcr = PIDGet( p_pkt );
            p_sys->i_first_pcr = i_pcr;
            p_sys->i_current_pcr = i_pcr;
        }
        block_Release( p_pkt );
        if( p_sys->i_first_pcr >= 0 )
            break;
    }
    stream_Seek( p_demux->s, i_initial_pos );
}

static void GetLastPCR( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;

2068
    const int64_t i_initial_pos = stream_Tell( p_demux->s );
2069 2070
    mtime_t i_initial_pcr = p_sys->i_current_pcr;

2071 2072 2073
    int64_t i_stream_size = stream_Size( p_demux->s );
    int64_t i_last_pos = i_stream_size - p_sys->i_packet_size;
    /* Round i_pos to a multiple of p_sys->i_packet_size */
2074
    int64_t i_pos = i_last_pos - p_sys->i_packet_size * 4500; /* FIXME if the value is not reasonable, please change it. */
2075 2076 2077 2078 2079 2080
    int64_t i_div = i_pos % p_sys->i_packet_size;
    i_pos -= i_div;

    if( i_pos <= i_initial_pos && i_pos >= i_stream_size )
        i_pos = i_initial_pos + p_sys->i_packet_size;
    if( i_pos < 0 && i_pos >= i_stream_size )
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
        return;

    while( vlc_object_alive( p_demux ) )
    {
        if( SeekToPCR( p_demux, i_pos ) )
            break;
        p_sys->i_last_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
        if( ( i_pos = stream_Tell( p_demux->s ) ) >= i_last_pos )
            break;
    }
    if( p_sys->i_last_pcr >= 0 )
    {
        int64_t i_size = stream_Size( p_demux->s );
        mtime_t i_duration_msec = ( p_sys->i_last_pcr - p_sys->i_first_pcr ) * 100 / 9 / 1000;
        int64_t i_rate = ( i_size < 0 || i_duration_msec <= 0 ) ? 0 : i_size * 1000 * 8 / i_duration_msec;
        const int64_t TS_SUPPOSED_MAXRATE = 55 * 1000 * 1000; //FIXME I think it's enough.
        const int64_t TS_SUPPOSED_MINRATE = 0.5 * 1000 * 1000; //FIXME
        if( i_rate < TS_SUPPOSED_MINRATE || i_rate > TS_SUPPOSED_MAXRATE )
        {
2100
            msg_Dbg( p_demux, "calculated bitrate (%"PRId64"bit/s) is too low or too high. min bitrate (%"PRId64"bit/s) max bitrate (%"PRId64"bit/s)",
2101 2102 2103 2104 2105
                     i_rate, TS_SUPPOSED_MINRATE, TS_SUPPOSED_MAXRATE );
            p_sys->i_last_pcr = -1;
        }
    }
    stream_Seek( p_demux->s, i_initial_pos );
2106
    assert( i_initial_pos == stream_Tell( p_demux->s ) );
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
    p_sys->i_current_pcr = i_initial_pcr;
}

static void CheckPCR( demux_t *p_demux )
{
    demux_sys_t   *p_sys = p_demux->p_sys;

    int64_t i_initial_pos = stream_Tell( p_demux->s );
    mtime_t i_initial_pcr = p_sys->i_current_pcr;

    int64_t i_size = stream_Size( p_demux->s );

    int i = 0;
    p_sys->p_pcrs[0] = p_sys->i_first_pcr;
    p_sys->p_pos[0] = i_initial_pos;

    for( i = 1; i < p_sys->i_pcrs_num && vlc_object_alive( p_demux ); ++i )
    {
2125
        /* Round i_pos to a multiple of p_sys->i_packet_size */
2126
        int64_t i_pos = i_size / p_sys->i_pcrs_num * i;
2127 2128
        int64_t i_div = i_pos % p_sys->i_packet_size;
        i_pos -= i_div;
2129 2130 2131 2132 2133 2134
        if( SeekToPCR( p_demux, i_pos ) )
            break;
        p_sys->p_pcrs[i] = p_sys->i_current_pcr;
        p_sys->p_pos[i] = stream_Tell( p_demux->s );
        if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
        {
2135
            msg_Dbg( p_demux, "PCR Wrap Around found between %d%% and %d%% (pcr:%"PRId64"(0x%09"PRIx64") pcr:%"PRId64"(0x%09"PRIx64"))",
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
                    (int)((i-1)*100/p_sys->i_pcrs_num), (int)(i*100/p_sys->i_pcrs_num), p_sys->p_pcrs[i-1], p_sys->p_pcrs[i-1], p_sys->p_pcrs[i], p_sys->p_pcrs[i] );
        }
    }
    if( i < p_sys->i_pcrs_num )
    {
        msg_Dbg( p_demux, "Force Seek Per Percent: Seeking failed at %d%%.", (int)(i*100/p_sys->i_pcrs_num) );
        p_sys->b_force_seek_per_percent = true;
    }

    stream_Seek( p_demux->s, i_initial_pos );
    p_sys->i_current_pcr = i_initial_pcr;
}

static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
{
    demux_sys_t   *p_sys = p_demux->p_sys;

    if( p_sys->i_pmt_es <= 0 )
        return;

    mtime_t i_pcr = GetPCR( p_bk );
2157 2158
    if( i_pcr < 0 )
        return;
2159

2160 2161 2162 2163
    if( p_sys->i_pid_ref_pcr == pid->i_pid )
        p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, i_pcr );

    /* Search program and set the PCR */
2164 2165 2166 2167 2168
    int i_group = -1;
    for( int i = 0; i < p_sys->i_pmt && i_group < 0 ; i++ )
    {
        bool b_pmt_has_es = false;

2169
        for( int i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
2170
        {
2171
            if( pid->i_pid == p_sys->pmt[i]->psi->prg[i_prg]->i_pid_pcr )
2172
            {
2173
                /* We've found our target group */
2174
                p_sys->pmt[i]->psi->prg[i_prg]->i_pcr_value = i_pcr;
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184
                i_group = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
                for( int j = 0; j < 8192; j++ )
                {
                    const ts_pid_t *pid = &p_sys->pid[j];
                    if( pid->b_valid && pid->p_owner == p_sys->pmt[i]->psi && pid->es )
                    {
                        b_pmt_has_es = true;
                        break;
                    }
                }
2185
            }
2186 2187 2188 2189 2190 2191
        }

        if ( p_sys->b_trust_pcr && i_group > 0 && b_pmt_has_es )
            es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
              i_group, VLC_TS_0 + i_pcr * 100 / 9 );
    }
2192 2193
}

2194
static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2195
{
2196
    const uint8_t *p = p_bk->p_buffer;
2197
    const bool b_unit_start = p[1]&0x40;
2198
    const bool b_scrambled  = p[3]&0x80;
2199 2200
    const bool b_adaptation = p[3]&0x20;
    const bool b_payload    = p[3]&0x10;
Laurent Aimar's avatar
Laurent Aimar committed
2201 2202
    const int  i_cc         = p[3]&0x0f; /* continuity counter */
    bool       b_discontinuity = false;  /* discontinuity */
2203

2204 2205
    /* transport_scrambling_control is ignored */
    int         i_skip = 0;
Laurent Aimar's avatar
Laurent Aimar committed
2206
    bool        i_ret  = false;
2207

2208
#if 0
2209
    msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
2210 2211
             "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
             b_payload, i_cc );
2212 2213
#endif

2214 2215 2216 2217
    /* For now, ignore additional error correction
     * TODO: handle Reed-Solomon 204,188 error correction */
    p_bk->i_buffer = TS_PACKET_SIZE_188;

2218 2219
    if( p[1]&0x80 )
    {
2220
        msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
2221
                 pid->i_pid );
2222 2223
        if( pid->es->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
            pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
2224 2225
    }

2226 2227
    if( p_demux->p_sys->csa )
    {
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
2228
        vlc_mutex_lock( &p_demux->p_sys->csa_lock );
2229
        csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
2230
        vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
2231 2232
    }

2233 2234
    if( !b_adaptation )
    {
2235 2236
        /* We don't have any adaptation_field, so payload starts
         * immediately after the 4 byte TS header */
2237 2238 2239 2240
        i_skip = 4;
    }
    else
    {
2241
        /* p[4] is adaptation_field_length minus one */
2242 2243 2244
        i_skip = 5 + p[4];
        if( p[4] > 0 )
        {
2245
            /* discontinuity indicator found in stream */
2246
            b_discontinuity = (p[5]&0x80) ? true : false;
2247
            if( b_discontinuity && pid->es->p_data )
2248
            {
2249 2250
                msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
                            pid->i_pid );
2251
                /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
2252
            }
2253
#if 0
2254 2255
            if( p[5]&0x40 )
                msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
2256
#endif
2257 2258
        }
    }
2259

2260
    /* Test continuity counter */
2261 2262 2263
    /* continuous when (one of this):
        * diff == 1
        * diff == 0 and payload == 0
2264 2265
        * diff == 0 and duplicate packet (playload != 0) <- should we
        *   test the content ?
2266
     */
Laurent Aimar's avatar
Laurent Aimar committed
2267
    const int i_diff = ( i_cc - pid->i_cc )&0x0f;
2268 2269
    if( b_payload && i_diff == 1 )
    {
2270
        pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
2271 2272 2273 2274 2275
    }
    else
    {
        if( pid->i_cc == 0xff )
        {
2276
            msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
2277
                      pid->i_pid, i_cc );
2278 2279
            pid->i_cc = i_cc;
        }
2280
        else if( i_diff != 0 && !b_discontinuity )
2281
        {
2282 2283
            msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
                      i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
2284 2285

            pid->i_cc = i_cc;
2286
            if( pid->es->p_data && pid->es->fmt.i_cat != VIDEO_ES )
2287
            {
2288
                /* Small video artifacts are usually better than
2289
                 * dropping full frames */
2290
                pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
2291 2292 2293 2294
            }
        }
    }

2295
    PCRHandle( p_demux, pid, p_bk );
2296

Rafaël Carré's avatar
Rafaël Carré committed
2297
    if( i_skip >= 188 || pid->es->id == NULL )
2298 2299
    {
        block_Release( p_bk );
2300
        return i_ret;
2301
    }
2302

2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
    /* */
    if( !pid->b_scrambled != !b_scrambled )
    {
        msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
                  pid->i_pid, pid->b_scrambled, b_scrambled );

        pid->b_scrambled = b_scrambled;

        for( int i = 0; i < pid->i_extra_es; i++ )
        {
            es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
                            pid->extra_es[i]->id, b_scrambled );
        }
        es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
                        pid->es->id, b_scrambled );
    }

2320 2321 2322
    /* We have to gather it */
    p_bk->p_buffer += i_skip;
    p_bk->i_buffer -= i_skip;
2323

2324 2325
    if( b_unit_start )
    {
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
        if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
        {
            int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
            block_t *p = block_Duplicate( p_bk );
            if( p )
            {
                p->i_buffer = i_pointer_field;
                p->p_buffer++;
                block_ChainLastAppend( &pid->es->pp_last, p );
            }
            p_bk->i_buffer -= 1 + i_pointer_field;
            p_bk->p_buffer += 1 + i_pointer_field;
        }
2339
        if( pid->es->p_data )
2340
        {
2341
            ParseData( p_demux, pid );
2342
            i_ret = true;
2343
        }
2344

2345
        block_ChainLastAppend( &pid->es->pp_last, p_bk );
2346
        if( pid->es->data_type == TS_ES_DATA_PES )
2347
        {
2348
            if( p_bk->i_buffer > 6 )
2349
            {
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
                pid->es->i_data_size = GetWBE( &p_bk->p_buffer[4] );
                if( pid->es->i_data_size > 0 )
                {
                    pid->es->i_data_size += 6;
                }
            }
        }
        else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
        {
            if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
            {
                pid->es->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
2362
            }
2363
        }
2364 2365 2366
        pid->es->i_data_gathered += p_bk->i_buffer;
        if( pid->es->i_data_size > 0 &&
            pid->es->i_data_gathered >= pid->es->i_data_size )
2367
        {
2368
            ParseData( p_demux, pid );
2369
            i_ret = true;
2370 2371 2372 2373
        }
    }
    else
    {
2374
        if( pid->es->p_data == NULL )
2375 2376 2377 2378 2379 2380 2381
        {
            /* msg_Dbg( p_demux, "broken packet" ); */
            block_Release( p_bk );
        }
        else
        {
            block_ChainLastAppend( &pid->es->pp_last, p_bk );
2382
            pid->es->i_data_gathered += p_bk->i_buffer;
2383

2384 2385
            if( pid->es->i_data_size > 0 &&
                pid->es->i_data_gathered >= pid->es->i_data_size )
2386
            {
2387
                ParseData( p_demux, pid );
2388
                i_ret = true;
2389
            }
2390 2391
        }
    }
2392

2393 2394 2395
    return i_ret;
}

2396
static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
2397 2398 2399
{
    switch( i_stream_type )
    {
Laurent Aimar's avatar
Laurent Aimar committed
2400 2401 2402
    case 0x01:  /* MPEG-1 video */
    case 0x02:  /* MPEG-2 video */
    case 0x80:  /* MPEG-2 MOTO video */
2403
        es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
Laurent Aimar's avatar
Laurent Aimar committed
2404 2405 2406
        break;
    case 0x03:  /* MPEG-1 audio */
    case 0x04:  /* MPEG-2 audio */
2407
        es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
Laurent Aimar's avatar
Laurent Aimar committed
2408
        break;
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
2409
    case 0x11:  /* MPEG4 (audio) LATM */
Laurent Aimar's avatar
Laurent Aimar committed
2410
    case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
2411 2412
    case 0x1c:  /* ISO/IEC 14496-3 Audio, without using any additional
                   transport syntax, such as DST, ALS and SLS */
2413
        es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
Laurent Aimar's avatar
Laurent Aimar committed
2414 2415
        break;
    case 0x10:  /* MPEG4 (video) */
2416
        es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
Laurent Aimar's avatar
Laurent Aimar committed
2417 2418
        break;
    case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
2419
        es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
Laurent Aimar's avatar
Laurent Aimar committed
2420
        break;
2421 2422 2423
    case 0x24:  /* HEVC */
        es_format_Init( fmt, VIDEO_ES, VLC_CODEC_HEVC );
        break;
2424 2425 2426
    case 0x42:  /* CAVS (Chinese AVS) */
        es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
        break;
2427

Laurent Aimar's avatar
Laurent Aimar committed
2428
    case 0x81:  /* A52 (audio) */
2429
        es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
Laurent Aimar's avatar
Laurent Aimar committed
2430
        break;
2431 2432
    case 0x82:  /* SCTE-27 (sub) */
        es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
Laurent Aimar's avatar
Laurent Aimar committed
2433 2434
        break;
    case 0x84:  /* SDDS (audio) */
2435
        es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
Laurent Aimar's avatar
Laurent Aimar committed
2436 2437
        break;
    case 0x85:  /* DTS (audio) */
2438
        es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
Laurent Aimar's avatar
Laurent Aimar committed
2439
        break;
2440 2441 2442
    case 0x87: /* E-AC3 */
        es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
        break;
2443

Laurent Aimar's avatar
Laurent Aimar committed
2444 2445 2446 2447 2448 2449
    case 0x91:  /* A52 vls (audio) */
        es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
        break;
    case 0x92:  /* DVD_SPU vls (sub) */
        es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
        break;
2450

Laurent Aimar's avatar
Laurent Aimar committed
2451 2452 2453
    case 0x94:  /* SDDS (audio) */
        es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
        break;
2454

Laurent Aimar's avatar
Laurent Aimar committed
2455 2456 2457
    case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
        es_format_Init( fmt, UNKNOWN_ES, 0 );
        break;
2458

Laurent Aimar's avatar
Laurent Aimar committed
2459 2460 2461 2462 2463 2464
    case 0x06:  /* PES_PRIVATE  (fixed later) */
    case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
    case 0xEA:  /* Privately managed ES (VC-1) (fixed later */
    default:
        es_format_Init( fmt, UNKNOWN_ES, 0 );
        break;
2465 2466
    }

2467
    /* PES packets usually contain truncated frames */
2468
    fmt->b_packetized = false;
2469 2470 2471
}

/*****************************************************************************
2472
 * MP4 specific functions (IOD parser)
2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
 *****************************************************************************/
static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
{
    unsigned int i_b;
    unsigned int i_len = 0;
    do
    {
        i_b = **pp_data;
        (*pp_data)++;
        (*pi_data)--;
        i_len = ( i_len << 7 ) + ( i_b&0x7f );

2485
    } while( i_b&0x80 && *pi_data > 0 );
2486

2487 2488 2489 2490
    if (i_len > *pi_data)
        i_len = *pi_data;

    return i_len;
2491
}
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2492

2493
static int IODGetBytes( int *pi_data, uint8_t **pp_data, size_t bytes )
2494
{
2495 2496
    uint32_t res = 0;
    while( *pi_data > 0 && bytes-- )
2497
    {
2498 2499
        res <<= 8;
        res |= **pp_data;
2500 2501 2502
        (*pp_data)++;
        (*pi_data)--;
    }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2503

2504
    return res;
2505 2506 2507 2508
}

static char* IODGetURL( int *pi_data, uint8_t **pp_data )
{
2509 2510 2511 2512 2513 2514 2515
    int len = IODGetBytes( pi_data, pp_data, 1 );
    if (len > *pi_data)
        len = *pi_data;
    char *url = strndup( (char*)*pp_data, len );
    *pp_data += len;
    *pi_data -= len;
    return url;
2516 2517 2518 2519
}

static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
{
2520
    uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
2521

2522 2523 2524
    iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
    if( !p_iod )
        return NULL;
2525 2526 2527 2528 2529 2530

    if( i_data < 3 )
    {
        return p_iod;
    }

2531 2532 2533
    byte1 = IODGetBytes( &i_data, &p_data, 1 );
    byte2 = IODGetBytes( &i_data, &p_data, 1 );
    byte3 = IODGetBytes( &i_data, &p_data, 1 );
2534
    if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
2535
    {
2536
        i_iod_label = byte1;
2537 2538
        i_iod_tag = byte2;
    }
2539
    else  //correct implementation of the IOD_descriptor
2540
    {
2541
        i_iod_label = byte2;
2542 2543
        i_iod_tag = byte3;
    }
2544

2545
    ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
2546

2547
    if( i_iod_tag != 0x02 )
2548
    {
2549
        ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
2550 2551 2552
        return p_iod;
    }

2553
    IODDescriptorLength( &i_data, &p_data );
2554

2555 2556
    uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
    uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
2557 2558
    i_od_id |= i_flags >> 6;
    ts_debug( "\n* od_id:%d", i_od_id );
2559
    ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
2560
    if ((i_flags >> 5) & 0x01)
2561 2562
    {
        p_iod->psz_url = IODGetURL( &i_data, &p_data );
2563 2564
        ts_debug( "\n* url string:%s", p_iod->psz_url );
        ts_debug( "\n*****************************\n" );
2565 2566 2567 2568 2569 2570 2571
        return p_iod;
    }
    else
    {
        p_iod->psz_url = NULL;
    }

2572 2573 2574 2575 2576 2577
    /* Profile Level Indication */
    IODGetBytes( &i_data, &p_data, 1 ); /* OD */
    IODGetBytes( &i_data, &p_data, 1 ); /* scene */
    IODGetBytes( &i_data, &p_data, 1 ); /* audio */
    IODGetBytes( &i_data, &p_data, 1 ); /* visual */
    IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
2578

2579 2580 2581
    int i_length = 0;
    int i_data_sav = i_data;
    uint8_t *p_data_sav = p_data;
2582
    for (int i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
2583
    {
2584 2585 2586 2587 2588 2589 2590
        es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];

        p_data = p_data_sav + i_length;
        i_data = i_data_sav - i_length;

        int i_tag = IODGetBytes( &i_data, &p_data, 1 );
        i_length = IODDescriptorLength( &i_data, &p_data );
2591

2592 2593
        i_data_sav = i_data;
        p_data_sav = p_data;
2594 2595 2596

        i_data = i_length;

2597
        if ( i_tag != 0x03 )
2598
        {
2599 2600 2601
            ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
            continue;
        }
2602

2603 2604 2605 2606 2607
        es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
        int i_flags = IODGetBytes( &i_data, &p_data, 1 );
        bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
        if( b_streamDependenceFlag )
            IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
2608

2609 2610
        if( (i_flags >> 6) & 0x01 )
            es_descr->psz_url = IODGetURL( &i_data, &p_data );
2611

2612 2613 2614
        bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
        if( b_OCRStreamFlag )
            IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
2615

2616 2617 2618 2619 2620
        if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
        {
            ts_debug( "\n* ERR missing DecoderConfigDescr" );
            continue;
        }
2621
        int i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
2622 2623 2624 2625 2626 2627 2628 2629 2630
        decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
        dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
        i_flags = IODGetBytes( &i_data, &p_data, 1 );
        dec_descr->i_streamType = i_flags >> 2;

        IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
        IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
        IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */

2631
        if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
2632 2633 2634 2635 2636 2637 2638 2639
        {
            dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
            if( dec_descr->i_extra > 0 )
            {
                dec_descr->p_extra = xmalloc( dec_descr->i_extra );
                memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
                p_data += dec_descr->i_extra;
                i_data -= dec_descr->i_extra;
Laurent Aimar's avatar
Laurent Aimar committed
2640
            }
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
        }
        else
        {
            dec_descr->i_extra = 0;
            dec_descr->p_extra = NULL;
        }

        if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
        {
            ts_debug( "\n* ERR missing SLConfigDescr" );
            continue;
        }
        IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
        switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
        {
Laurent Aimar's avatar
Laurent Aimar committed
2656
        default:
2657 2658 2659
            ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
        case 0x01:
            // FIXME
Laurent Aimar's avatar
Laurent Aimar committed
2660
            break;
2661
        }
2662
        es_descr->b_ok = true;
2663
    }
2664

2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
    return p_iod;
}

static void IODFree( iod_descriptor_t *p_iod )
{
    if( p_iod->psz_url )
    {
        free( p_iod->psz_url );
        free( p_iod );
        return;
    }

2677
    for( int i = 0; i < 255; i++ )
2678 2679 2680 2681 2682 2683 2684
    {
#define es_descr p_iod->es_descr[i]
        if( es_descr.b_ok )
        {
            if( es_descr.psz_url )
                free( es_descr.psz_url );
            else
2685
                free( es_descr.dec_descr.p_extra );
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
        }
#undef  es_descr
    }
    free( p_iod );
}

/****************************************************************************
 ****************************************************************************
 ** libdvbpsi callbacks
 ****************************************************************************
 ****************************************************************************/
Laurent Aimar's avatar
Laurent Aimar committed
2697
static bool ProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
2698 2699 2700
{
    demux_sys_t          *p_sys = p_demux->p_sys;

2701
    if( ( p_sys->i_current_program == -1 && p_sys->programs_list.i_count == 0 ) ||
Laurent Aimar's avatar
Laurent Aimar committed
2702 2703 2704
        p_sys->i_current_program == 0 )
        return true;
    if( p_sys->i_current_program == i_pgrm )
2705
        return true;
2706

2707
    if( p_sys->programs_list.i_count != 0 )
2708
    {
2709
        for( int i = 0; i < p_sys->programs_list.i_count; i++ )
2710
        {
2711
            if( i_pgrm == p_sys->programs_list.p_values[i].i_int )
2712
                return true;
2713 2714
        }
    }
2715
    return false;
2716 2717
}

Laurent Aimar's avatar
Laurent Aimar committed
2718
static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
2719 2720 2721
{
    demux_sys_t *p_sys = p_demux->p_sys;

2722
    if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
2723 2724 2725 2726 2727
        return;

    msg_Warn( p_demux, "Switching to non DVB mode" );

    /* This doesn't look like a DVB stream so don't try
2728
     * parsing the SDT/EDT/TDT */
2729

2730
    for( int i = 0x11; i <= 0x14; i++ )
2731
    {
2732
        if( i == 0x13 ) continue;
2733 2734 2735
        ts_pid_t *p_pid = &p_sys->pid[i];
        if( p_pid->psi )
        {
2736 2737 2738 2739 2740 2741

#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
            if( dvbpsi_decoder_present( p_pid->psi->handle ))
                dvbpsi_DetachDemux( p_pid->psi->handle );
            dvbpsi_delete( p_pid->psi->handle );
#else
2742
            dvbpsi_DetachDemux( p_pid->psi->handle );
2743
#endif
2744 2745 2746 2747
            free( p_pid->psi );
            p_pid->psi = NULL;
            p_pid->b_valid = false;
        }
Laurent Aimar's avatar
Laurent Aimar committed
2748
        SetPIDFilter( p_demux, i, false );
2749
    }
Laurent Aimar's avatar
Laurent Aimar committed
2750
    p_sys->b_dvb_meta = false;
2751 2752
}

2753
#include "dvb-text.h"
2754

2755
static char *EITConvertToUTF8( const unsigned char *psz_instring,
2756 2757
                               size_t i_length,
                               bool b_broken )
2758
{
2759 2760 2761 2762 2763 2764 2765
    /* Deal with no longer broken providers (no switch byte
      but sending ISO_8859-1 instead of ISO_6937) without
      removing them from the broken providers table
      (keep the entry for correctly handling recorded TS).
    */
    b_broken = b_broken && i_length && *psz_instring > 0x20;

2766 2767 2768
    if( b_broken )
        return FromCharset( "ISO_8859-1", psz_instring, i_length );
    return vlc_from_EIT( psz_instring, i_length );
2769 2770
}

2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786
static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
{
    demux_sys_t          *p_sys = p_demux->p_sys;
    ts_pid_t             *sdt = &p_sys->pid[0x11];
    dvbpsi_sdt_service_t *p_srv;

    msg_Dbg( p_demux, "SDTCallBack called" );

    if( sdt->psi->i_sdt_version != -1 &&
        ( !p_sdt->b_current_next ||
          p_sdt->i_version == sdt->psi->i_sdt_version ) )
    {
        dvbpsi_DeleteSDT( p_sdt );
        return;
    }

2787 2788
    msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
             "network_id=%d",
2789 2790 2791 2792 2793 2794
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
             p_sdt->i_extension,
#else
             p_sdt->i_ts_id,
#endif
             p_sdt->i_version, p_sdt->b_current_next,
2795
             p_sdt->i_network_id );
2796

2797
    p_sys->b_broken_charset = false;
2798

2799 2800
    for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
    {
2801
        vlc_meta_t          *p_meta;
2802 2803
        dvbpsi_descriptor_t *p_dr;

2804 2805 2806
        const char *psz_type = NULL;
        const char *psz_status = NULL;

2807
        msg_Dbg( p_demux, "  * service id=%d eit schedule=%d present=%d "
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
2808
                 "running=%d free_ca=%d",
2809 2810 2811
                 p_srv->i_service_id, p_srv->b_eit_schedule,
                 p_srv->b_eit_present, p_srv->i_running_status,
                 p_srv->b_free_ca );
2812

2813
        p_meta = vlc_meta_New();
2814 2815 2816 2817
        for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
        {
            if( p_dr->i_tag == 0x48 )
            {
2818
                static const char *ppsz_type[17] = {
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
                    "Reserved",
                    "Digital television service",
                    "Digital radio sound service",
                    "Teletext service",
                    "NVOD reference service",
                    "NVOD time-shifted service",
                    "Mosaic service",
                    "PAL coded signal",
                    "SECAM coded signal",
                    "D/D2-MAC",
                    "FM Radio",
                    "NTSC coded signal",
                    "Data broadcast service",
                    "Reserved for Common Interface Usage",
                    "RCS Map (see EN 301 790 [35])",
                    "RCS FLS (see EN 301 790 [35])",
                    "DVB MHP service"
                };
                dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
2838 2839
                char *str1 = NULL;
                char *str2 = NULL;
2840

2841 2842
                /* Workarounds for broadcasters with broken EPG */

2843 2844
                if( p_sdt->i_network_id == 133 )
                    p_sys->b_broken_charset = true;  /* SKY DE & BetaDigital use ISO8859-1 */
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857

                /* List of providers using ISO8859-1 */
                static const char ppsz_broken_providers[][8] = {
                    "CSAT",     /* CanalSat FR */
                    "GR1",      /* France televisions */
                    "MULTI4",   /* NT1 */
                    "MR5",      /* France 2/M6 HD */
                    ""
                };
                for( int i = 0; *ppsz_broken_providers[i]; i++ )
                {
                    const size_t i_length = strlen(ppsz_broken_providers[i]);
                    if( pD->i_service_provider_name_length == i_length &&
2858
                        !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
2859 2860
                        p_sys->b_broken_charset = true;
                }
2861 2862 2863

                /* FIXME: Digital+ ES also uses ISO8859-1 */

2864
                str1 = EITConvertToUTF8(pD->i_service_provider_name,
2865 2866
                                        pD->i_service_provider_name_length,
                                        p_sys->b_broken_charset );
2867
                str2 = EITConvertToUTF8(pD->i_service_name,
2868 2869
                                        pD->i_service_name_length,
                                        p_sys->b_broken_charset );
2870 2871

                msg_Dbg( p_demux, "    - type=%d provider=%s name=%s",
2872
                         pD->i_service_type, str1, str2 );
2873

Clément Stenac's avatar
Clément Stenac committed
2874
                vlc_meta_SetTitle( p_meta, str2 );
Clément Stenac's avatar
Clément Stenac committed
2875
                vlc_meta_SetPublisher( p_meta, str1 );
2876
                if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
2877
                    psz_type = ppsz_type[pD->i_service_type];
2878 2879
                free( str1 );
                free( str2 );
2880 2881 2882
            }
        }

2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
        if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
        {
            static const char *ppsz_status[5] = {
                "Unknown",
                "Not running",
                "Starts in a few seconds",
                "Pausing",
                "Running"
            };
            psz_status = ppsz_status[p_srv->i_running_status];
        }

        if( psz_type )
            vlc_meta_AddExtra( p_meta, "Type", psz_type );
        if( psz_status )
            vlc_meta_AddExtra( p_meta, "Status", psz_status );
2899 2900 2901 2902 2903 2904 2905 2906 2907

        es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
                        p_srv->i_service_id, p_meta );
        vlc_meta_Delete( p_meta );
    }

    sdt->psi->i_sdt_version = p_sdt->i_version;
    dvbpsi_DeleteSDT( p_sdt );
}
2908 2909 2910

/* i_year: year - 1900  i_month: 0-11  i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
2911
{
2912 2913
    static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
    int64_t i_day;
2914

2915 2916 2917 2918 2919 2920 2921 2922
    if( i_year < 70 ||
        i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
        i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
        return -1;

    /* Count the number of days */
    i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
#define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
2923
    for( int i = 70; i < i_year; i++ )
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
        i_day += LEAP(1900+i);
    if( i_month > 1 )
        i_day += LEAP(1900+i_year);
#undef LEAP
    /**/
    return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
}

static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
{
    const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
    const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
    const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;

    *p_y = 1900 + yp + c*1;
2939
    *p_m = mp - 1 - c*12;
2940
    *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
}
#define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
static int64_t EITConvertStartTime( uint64_t i_date )
{
    const int i_mjd = i_date >> 24;
    const int i_hour   = CVT_FROM_BCD(i_date >> 16);
    const int i_minute = CVT_FROM_BCD(i_date >>  8);
    const int i_second = CVT_FROM_BCD(i_date      );
    int i_year;
    int i_month;
    int i_day;

    /* if all 40 bits are 1, the start is unknown */
    if( i_date == UINT64_C(0xffffffffff) )
        return -1;
2956

2957 2958
    EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
    return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
2959
}
2960
static int EITConvertDuration( uint32_t i_duration )
2961
{
2962
    return CVT_FROM_BCD(i_duration >> 16) * 3600 +
2963 2964
           CVT_FROM_BCD(i_duration >> 8 ) * 60 +
           CVT_FROM_BCD(i_duration      );
2965
}
2966 2967
#undef CVT_FROM_BCD

2968 2969 2970 2971
static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
{
    demux_sys_t        *p_sys = p_demux->p_sys;

2972 2973
    p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
                         - mdate();
2974 2975 2976
    dvbpsi_DeleteTOT(p_tdt);
}

2977

2978 2979
static void EITCallBack( demux_t *p_demux,
                         dvbpsi_eit_t *p_eit, bool b_current_following )
2980
{
2981
    demux_sys_t        *p_sys = p_demux->p_sys;
2982
    dvbpsi_eit_event_t *p_evt;
2983
    vlc_epg_t *p_epg;
2984 2985

    msg_Dbg( p_demux, "EITCallBack called" );
2986
    if( !p_eit->b_current_next )
2987 2988 2989 2990 2991
    {
        dvbpsi_DeleteEIT( p_eit );
        return;
    }

2992 2993 2994
    msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
             "ts_id=%d network_id=%d segment_last_section_number=%d "
             "last_table_id=%d",
2995 2996 2997 2998 2999 3000
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
             p_eit->i_extension,
#else
             p_eit->i_service_id,
#endif
             p_eit->i_version, p_eit->b_current_next,
3001 3002
             p_eit->i_ts_id, p_eit->i_network_id,
             p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
3003

3004
    p_epg = vlc_epg_New( NULL );
3005 3006 3007
    for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
    {
        dvbpsi_descriptor_t *p_dr;
3008 3009
        char                *psz_name = NULL;
        char                *psz_text = NULL;
3010
        char                *psz_extra = strdup("");
3011 3012
        int64_t i_start;
        int i_duration;
3013
        int i_min_age = 0;
3014 3015 3016 3017 3018

        i_start = EITConvertStartTime( p_evt->i_start_time );
        i_duration = EITConvertDuration( p_evt->i_duration );

        msg_Dbg( p_demux, "  * event id=%d start_time:%d duration=%d "
3019
                          "running=%d free_ca=%d",
3020
                 p_evt->i_event_id, (int)i_start, (int)i_duration,
3021 3022 3023 3024 3025 3026 3027 3028
                 p_evt->i_running_status, p_evt->b_free_ca );

        for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
        {
            if( p_dr->i_tag == 0x4d )
            {
                dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );

3029 3030 3031
                /* Only take first description, as we don't handle language-info
                   for epg atm*/
                if( pE && psz_name == NULL)
3032
                {
3033 3034 3035 3036
                    psz_name = EITConvertToUTF8( pE->i_event_name, pE->i_event_name_length,
                                                 p_sys->b_broken_charset );
                    psz_text = EITConvertToUTF8( pE->i_text, pE->i_text_length,
                                                 p_sys->b_broken_charset );
3037 3038 3039 3040 3041 3042 3043 3044 3045
                    msg_Dbg( p_demux, "    - short event lang=%3.3s '%s' : '%s'",
                             pE->i_iso_639_code, psz_name, psz_text );
                }
            }
            else if( p_dr->i_tag == 0x4e )
            {
                dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
                if( pE )
                {
3046 3047 3048 3049 3050
                    msg_Dbg( p_demux, "    - extended event lang=%3.3s [%d/%d]",
                             pE->i_iso_639_code,
                             pE->i_descriptor_number, pE->i_last_descriptor_number );

                    if( pE->i_text_length > 0 )
3051
                    {
3052 3053
                        char *psz_text = EITConvertToUTF8( pE->i_text, pE->i_text_length,
                                                           p_sys->b_broken_charset );
3054 3055 3056
                        if( psz_text )
                        {
                            msg_Dbg( p_demux, "       - text='%s'", psz_text );
3057

3058
                            psz_extra = xrealloc( psz_extra,
3059
                                   strlen(psz_extra) + strlen(psz_text) + 1 );
3060 3061 3062
                            strcat( psz_extra, psz_text );
                            free( psz_text );
                        }
3063 3064
                    }

Laurent Aimar's avatar
Laurent Aimar committed
3065
                    for( int i = 0; i < pE->i_entry_count; i++ )
3066
                    {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
3067
                        char *psz_dsc = EITConvertToUTF8( pE->i_item_description[i],
3068 3069 3070 3071
                                                          pE->i_item_description_length[i],
                                                          p_sys->b_broken_charset );
                        char *psz_itm = EITConvertToUTF8( pE->i_item[i], pE->i_item_length[i],
                                                          p_sys->b_broken_charset );
3072

3073 3074 3075
                        if( psz_dsc && psz_itm )
                        {
                            msg_Dbg( p_demux, "       - desc='%s' item='%s'", psz_dsc, psz_itm );
3076
#if 0
3077
                            psz_extra = xrealloc( psz_extra,
3078 3079
                                         strlen(psz_extra) + strlen(psz_dsc) +
                                         strlen(psz_itm) + 3 + 1 );
3080 3081 3082 3083 3084
                            strcat( psz_extra, "(" );
                            strcat( psz_extra, psz_dsc );
                            strcat( psz_extra, " " );
                            strcat( psz_extra, psz_itm );
                            strcat( psz_extra, ")" );
3085
#endif
3086
                        }
3087 3088
                        free( psz_dsc );
                        free( psz_itm );
3089
                    }
3090 3091
                }
            }
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103
            else if( p_dr->i_tag == 0x55 )
            {
                dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
                if ( pR )
                {
                    for ( int i = 0; i < pR->i_ratings_number; i++ )
                    {
                        const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
                        if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
                        {
                            if ( p_rating->i_rating + 3 > i_min_age )
                                i_min_age = p_rating->i_rating + 3;
3104
                            msg_Dbg( p_demux, "    - parental control set to %d years",
3105 3106 3107 3108 3109
                                     i_min_age );
                        }
                    }
                }
            }
3110 3111
            else
            {
3112
                msg_Dbg( p_demux, "    - event unknown dr 0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
3113 3114 3115
            }
        }

3116 3117
        /* */
        if( i_start > 0 )
3118
            vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
3119
                              *psz_extra ? psz_extra : NULL, i_min_age );
3120

3121 3122 3123 3124
        /* Update "now playing" field */
        if( p_evt->i_running_status == 0x04 && i_start > 0 )
            vlc_epg_SetCurrent( p_epg, i_start );

3125 3126
        free( psz_name );
        free( psz_text );
3127 3128 3129

        free( psz_extra );
    }
3130
    if( p_epg->i_event > 0 )
3131
    {
3132 3133
        if( b_current_following &&
            (  p_sys->i_current_program == -1 ||
3134 3135 3136 3137 3138 3139 3140
               p_sys->i_current_program ==
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
                    p_eit->i_extension
#else
                    p_eit->i_service_id
#endif
                ) )
3141 3142 3143 3144 3145 3146
        {
            p_sys->i_dvb_length = 0;
            p_sys->i_dvb_start = 0;

            if( p_epg->p_current )
            {
3147 3148
                p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
                p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
3149 3150
            }
        }
3151 3152 3153 3154 3155 3156 3157
        es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
                        p_eit->i_extension,
#else
                        p_eit->i_service_id,
#endif
                        p_epg );
3158
    }
3159
    vlc_epg_Delete( p_epg );
3160

3161 3162
    dvbpsi_DeleteEIT( p_eit );
}
3163 3164 3165 3166 3167 3168 3169 3170
static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
{
    EITCallBack( p_demux, p_eit, true );
}
static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
{
    EITCallBack( p_demux, p_eit, false );
}
3171

3172 3173 3174 3175
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
                                 uint16_t i_extension, demux_t *p_demux )
#else
3176 3177
static void PSINewTableCallBack( demux_t *p_demux, dvbpsi_handle h,
                                 uint8_t  i_table_id, uint16_t i_extension )
3178
#endif
3179
{
3180
    assert( h );
3181 3182 3183 3184
#if 0
    msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
             i_table_id, i_table_id, i_extension, i_extension );
#endif
3185
    if( p_demux->p_sys->pid[0].psi->i_pat_version != -1 && i_table_id == 0x42 )
3186 3187 3188
    {
        msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
                 i_table_id, i_table_id, i_extension, i_extension );
3189 3190 3191 3192
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
        if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
            msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
#else
3193 3194
        dvbpsi_AttachSDT( h, i_table_id, i_extension,
                          (dvbpsi_sdt_callback)SDTCallBack, p_demux );
3195
#endif
3196
    }
3197 3198 3199
    else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
             ( i_table_id == 0x4e || /* Current/Following */
               (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
3200 3201 3202 3203
    {
        msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
                 i_table_id, i_table_id, i_extension, i_extension );

3204 3205 3206
        dvbpsi_eit_callback cb = i_table_id == 0x4e ?
                                    (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
                                    (dvbpsi_eit_callback)EITCallBackSchedule;
3207 3208 3209 3210
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
        if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
            msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
#else
3211
        dvbpsi_AttachEIT( h, i_table_id, i_extension, cb, p_demux );
3212
#endif
3213
    }
3214
    else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
3215
              i_table_id == 0x70 )  /* TDT */
3216 3217 3218
    {
         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
                 i_table_id, i_table_id, i_extension, i_extension );
3219 3220 3221 3222
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
        if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
            msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
#else
3223 3224
         dvbpsi_AttachTOT( h, i_table_id, i_extension,
                           (dvbpsi_tot_callback)TDTCallBack, p_demux);
3225
#endif
3226
    }
3227 3228
}

3229 3230 3231
/*****************************************************************************
 * PMT callback and helpers
 *****************************************************************************/
Laurent Aimar's avatar
Laurent Aimar committed
3232 3233
static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
                                                 int i_tag )
3234 3235
{
    dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
Laurent Aimar's avatar
Laurent Aimar committed
3236
    while( p_dr && ( p_dr->i_tag != i_tag ) )
3237
        p_dr = p_dr->p_next;
Laurent Aimar's avatar
Laurent Aimar committed
3238 3239
    return p_dr;
}
Laurent Aimar's avatar
Laurent Aimar committed
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
static bool PMTEsHasRegistration( demux_t *p_demux,
                                  const dvbpsi_pmt_es_t *p_es,
                                  const char *psz_tag )
{
    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
    if( !p_dr )
        return false;

    if( p_dr->i_length < 4 )
    {
        msg_Warn( p_demux, "invalid Registration Descriptor" );
        return false;
    }

    assert( strlen(psz_tag) == 4 );
    return !memcmp( p_dr->p_data, psz_tag, 4 );
}
Laurent Aimar's avatar
Laurent Aimar committed
3257 3258 3259 3260 3261
static void PMTSetupEsISO14496( demux_t *p_demux, ts_pid_t *pid,
                                const ts_prg_psi_t *prg, const dvbpsi_pmt_es_t *p_es )
{
    es_format_t *p_fmt = &pid->es->fmt;

3262
    /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
Laurent Aimar's avatar
Laurent Aimar committed
3263
    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x1f );
3264 3265 3266

    if( p_dr && p_dr->i_length == 2 )
    {
Laurent Aimar's avatar
Laurent Aimar committed
3267
        const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
3268

3269
        msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
3270 3271 3272

        pid->es->p_mpeg4desc = NULL;

3273
        for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
3274 3275
        {
            iod_descriptor_t *iod = prg->iod;
3276
            if( iod->es_descr[i].i_es_id == i_es_id )
3277
            {
3278 3279 3280 3281
                if ( iod->es_descr[i].b_ok )
                    pid->es->p_mpeg4desc = &iod->es_descr[i];
                else
                    msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
3282 3283 3284 3285
                break;
            }
        }
    }
Laurent Aimar's avatar
Laurent Aimar committed
3286
    if( !pid->es->p_mpeg4desc )
3287
    {
3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
        switch( p_es->i_type )
        {
        /* non fatal, set by packetizer */
        case 0x0f: /* ADTS */
        case 0x11: /* LOAS */
            msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
                      pid->i_pid, p_es->i_type );
            break;
        default:
            msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
                     pid->i_pid, p_es->i_type );
            break;
        }
Laurent Aimar's avatar
Laurent Aimar committed
3301 3302
        return;
    }
3303

Laurent Aimar's avatar
Laurent Aimar committed
3304 3305 3306 3307 3308
    const decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
    if( dcd->i_streamType == 0x04 )    /* VisualStream */
    {
        p_fmt->i_cat = VIDEO_ES;
        switch( dcd->i_objectTypeIndication )
3309
        {
Laurent Aimar's avatar
Laurent Aimar committed
3310 3311
        case 0x0B: /* mpeg4 sub */
            p_fmt->i_cat = SPU_ES;
3312
            p_fmt->i_codec = VLC_CODEC_SUBT;
Laurent Aimar's avatar
Laurent Aimar committed
3313
            break;
3314

Laurent Aimar's avatar
Laurent Aimar committed
3315
        case 0x20: /* mpeg4 */
3316
            p_fmt->i_codec = VLC_CODEC_MP4V;
Laurent Aimar's avatar
Laurent Aimar committed
3317 3318
            break;
        case 0x21: /* h264 */
3319
            p_fmt->i_codec = VLC_CODEC_H264;
Laurent Aimar's avatar
Laurent Aimar committed
3320 3321 3322 3323 3324 3325 3326
            break;
        case 0x60:
        case 0x61:
        case 0x62:
        case 0x63:
        case 0x64:
        case 0x65: /* mpeg2 */
3327
            p_fmt->i_codec = VLC_CODEC_MPGV;
Laurent Aimar's avatar
Laurent Aimar committed
3328 3329
            break;
        case 0x6a: /* mpeg1 */
3330
            p_fmt->i_codec = VLC_CODEC_MPGV;
Laurent Aimar's avatar
Laurent Aimar committed
3331 3332
            break;
        case 0x6c: /* mpeg1 */
3333
            p_fmt->i_codec = VLC_CODEC_JPEG;
Laurent Aimar's avatar
Laurent Aimar committed
3334 3335 3336 3337
            break;
        default:
            p_fmt->i_cat = UNKNOWN_ES;
            break;
3338
        }
Laurent Aimar's avatar
Laurent Aimar committed
3339 3340 3341 3342 3343
    }
    else if( dcd->i_streamType == 0x05 )    /* AudioStream */
    {
        p_fmt->i_cat = AUDIO_ES;
        switch( dcd->i_objectTypeIndication )
3344
        {
Laurent Aimar's avatar
Laurent Aimar committed
3345
        case 0x40: /* mpeg4 */
3346
            p_fmt->i_codec = VLC_CODEC_MP4A;
Laurent Aimar's avatar
Laurent Aimar committed
3347 3348 3349 3350
            break;
        case 0x66:
        case 0x67:
        case 0x68: /* mpeg2 aac */
3351
            p_fmt->i_codec = VLC_CODEC_MP4A;
Laurent Aimar's avatar
Laurent Aimar committed
3352 3353
            break;
        case 0x69: /* mpeg2 */
3354
            p_fmt->i_codec = VLC_CODEC_MPGA;
Laurent Aimar's avatar
Laurent Aimar committed
3355 3356
            break;
        case 0x6b: /* mpeg1 */
3357
            p_fmt->i_codec = VLC_CODEC_MPGA;
Laurent Aimar's avatar
Laurent Aimar committed
3358 3359 3360 3361
            break;
        default:
            p_fmt->i_cat = UNKNOWN_ES;
            break;
3362
        }
Laurent Aimar's avatar
Laurent Aimar committed
3363 3364 3365 3366 3367
    }
    else
    {
        p_fmt->i_cat = UNKNOWN_ES;
    }
3368

Laurent Aimar's avatar
Laurent Aimar committed
3369 3370
    if( p_fmt->i_cat != UNKNOWN_ES )
    {
3371
        p_fmt->i_extra = dcd->i_extra;
Laurent Aimar's avatar
Laurent Aimar committed
3372
        if( p_fmt->i_extra > 0 )
3373
        {
Laurent Aimar's avatar
Laurent Aimar committed
3374 3375
            p_fmt->p_extra = malloc( p_fmt->i_extra );
            if( p_fmt->p_extra )
3376
                memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
Laurent Aimar's avatar
Laurent Aimar committed
3377 3378
            else
                p_fmt->i_extra = 0;
3379 3380 3381 3382
        }
    }
}

3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
typedef struct
{
    int  i_type;
    int  i_magazine;
    int  i_page;
    char p_iso639[3];
} ts_teletext_page_t;

static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
                                const dvbpsi_pmt_es_t *p_es )
3393
{
Laurent Aimar's avatar
Laurent Aimar committed
3394 3395
    es_format_t *p_fmt = &pid->es->fmt;

3396
    ts_teletext_page_t p_page[2 * 64 + 20];
3397
    unsigned i_page = 0;
3398

3399
    /* Gather pages information */
3400
#if defined _DVBPSI_DR_56_H_ && \
3401
    defined DVBPSI_VERSION && DVBPSI_VERSION_INT > DVBPSI_VERSION_WANTED(0,1,5)
3402
    for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
3403
    {
3404 3405 3406
        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, i_tag_idx == 0 ? 0x46 : 0x56 );
        if( !p_dr )
            continue;
3407

3408 3409 3410 3411 3412
        dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
        if( !p_sub )
            continue;

        for( int i = 0; i < p_sub->i_pages_number; i++ )
3413
        {
3414 3415
            const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];

Pierre d'Herbemont's avatar
Pierre d'Herbemont committed
3416
            if( p_src->i_teletext_type >= 0x06 )
3417
                continue;
3418

3419 3420 3421 3422 3423
            assert( i_page < sizeof(p_page)/sizeof(*p_page) );

            ts_teletext_page_t *p_dst = &p_page[i_page++];

            p_dst->i_type = p_src->i_teletext_type;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
3424 3425
            p_dst->i_magazine = p_src->i_teletext_magazine_number
                ? p_src->i_teletext_magazine_number : 8;
3426 3427
            p_dst->i_page = p_src->i_teletext_page_number;
            memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
3428
        }
3429
    }
3430
#endif
3431 3432 3433 3434 3435 3436

    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
    if( p_dr )
    {
        dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
        for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
3437
        {
3438 3439 3440 3441
            dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];

            if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
                continue;
3442

3443
            assert( i_page < sizeof(p_page)/sizeof(*p_page) );
3444

3445 3446 3447
            ts_teletext_page_t *p_dst = &p_page[i_page++];

            switch( p_src->i_subtitling_type )
3448
            {
3449 3450 3451 3452 3453 3454 3455 3456
            case 0x01:
                p_dst->i_type = 0x02;
                break;
            default:
                p_dst->i_type = 0x03;
                break;
            }
            /* FIXME check if it is the right split */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
3457 3458
            p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
                ? (p_src->i_composition_page_id >> 8) : 8;
3459 3460 3461 3462
            p_dst->i_page = p_src->i_composition_page_id & 0xff;
            memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
        }
    }
3463

3464
    /* */
3465
    es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
3466

3467
    if( !p_demux->p_sys->b_split_es || i_page <= 0 )
3468 3469 3470
    {
        p_fmt->subs.teletext.i_magazine = -1;
        p_fmt->subs.teletext.i_page = 0;
3471
        p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
3472

3473 3474 3475 3476
        dvbpsi_descriptor_t *p_dr;
        p_dr = PMTEsFindDescriptor( p_es, 0x46 );
        if( !p_dr )
            p_dr = PMTEsFindDescriptor( p_es, 0x56 );
3477

3478
        if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
3479
        {
3480
            /* Descriptor pass-through */
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
            p_fmt->p_extra = malloc( p_dr->i_length );
            if( p_fmt->p_extra )
            {
                p_fmt->i_extra = p_dr->i_length;
                memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
            }
        }
    }
    else
    {
3491
        for( unsigned i = 0; i < i_page; i++ )
3492 3493 3494 3495 3496 3497 3498
        {
            ts_es_t *p_es;

            /* */
            if( i == 0 )
            {
                p_es = pid->es;
3499 3500 3501
            }
            else
            {
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512
                p_es = malloc( sizeof(*p_es) );
                if( !p_es )
                    break;

                es_format_Copy( &p_es->fmt, &pid->es->fmt );
                free( p_es->fmt.psz_language );
                free( p_es->fmt.psz_description );
                p_es->fmt.psz_language = NULL;
                p_es->fmt.psz_description = NULL;

                p_es->id      = NULL;
3513 3514 3515 3516
                p_es->p_data  = NULL;
                p_es->i_data_size = 0;
                p_es->i_data_gathered = 0;
                p_es->pp_last = &p_es->p_data;
3517
                p_es->data_type = TS_ES_DATA_PES;
3518 3519 3520
                p_es->p_mpeg4desc = NULL;

                TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
3521
            }
3522 3523 3524

            /* */
            const ts_teletext_page_t *p = &p_page[i];
3525 3526
            p_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
                      ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
3527
            p_es->fmt.psz_language = strndup( p->p_iso639, 3 );
3528
            p_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
3529 3530 3531 3532 3533 3534 3535 3536
            p_es->fmt.subs.teletext.i_magazine = p->i_magazine;
            p_es->fmt.subs.teletext.i_page = p->i_page;

            msg_Dbg( p_demux,
                         "    * ttxt type=%s lan=%s page=%d%02x",
                         p_es->fmt.psz_description,
                         p_es->fmt.psz_language,
                         p->i_magazine, p->i_page );
3537
        }
3538 3539 3540 3541 3542 3543 3544
    }
}
static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pid_t *pid,
                                   const dvbpsi_pmt_es_t *p_es )
{
    es_format_t *p_fmt = &pid->es->fmt;

3545
    es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
3546 3547 3548 3549 3550 3551 3552

    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
    int i_page = 0;
    dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
    for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
    {
        const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
3553 3554
        if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
            ( i_type >= 0x20 && i_type <= 0x24 ) )
3555 3556 3557
            i_page++;
    }

3558
    if( !p_demux->p_sys->b_split_es  || i_page <= 0 )
3559 3560 3561 3562
    {
        p_fmt->subs.dvb.i_id = -1;
        p_fmt->psz_description = strdup( _("DVB subtitles") );

3563
        if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
3564
        {
3565
            /* Descriptor pass-through */
Laurent Aimar's avatar
Laurent Aimar committed
3566 3567
            p_fmt->p_extra = malloc( p_dr->i_length );
            if( p_fmt->p_extra )
3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578
            {
                p_fmt->i_extra = p_dr->i_length;
                memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
            }
        }
    }
    else
    {
        for( int i = 0; i < p_sub->i_subtitles_number; i++ )
        {
            ts_es_t *p_es;
3579

3580 3581
            /* */
            if( i == 0 )
3582
            {
3583 3584 3585 3586 3587 3588 3589
                p_es = pid->es;
            }
            else
            {
                p_es = malloc( sizeof(*p_es) );
                if( !p_es )
                    break;
3590

3591 3592 3593 3594 3595 3596 3597
                es_format_Copy( &p_es->fmt, &pid->es->fmt );
                free( p_es->fmt.psz_language );
                free( p_es->fmt.psz_description );
                p_es->fmt.psz_language = NULL;
                p_es->fmt.psz_description = NULL;

                p_es->id      = NULL;
3598 3599 3600 3601
                p_es->p_data   = NULL;
                p_es->i_data_size = 0;
                p_es->i_data_gathered = 0;
                p_es->pp_last = &p_es->p_data;
3602
                p_es->data_type = TS_ES_DATA_PES;
3603 3604 3605 3606
                p_es->p_mpeg4desc = NULL;

                TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
            }
3607

3608 3609
            /* */
            const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
3610
            p_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
3611 3612 3613 3614 3615 3616
            switch( p->i_subtitling_type )
            {
            case 0x10: /* unspec. */
            case 0x11: /* 4:3 */
            case 0x12: /* 16:9 */
            case 0x13: /* 2.21:1 */
3617
            case 0x14: /* HD monitor */
3618 3619 3620 3621 3622 3623
                p_es->fmt.psz_description = strdup( _("DVB subtitles") );
                break;
            case 0x20: /* Hearing impaired unspec. */
            case 0x21: /* h.i. 4:3 */
            case 0x22: /* h.i. 16:9 */
            case 0x23: /* h.i. 2.21:1 */
3624
            case 0x24: /* h.i. HD monitor */
3625 3626 3627 3628 3629
                p_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
                break;
            default:
                break;
            }
3630

3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
            /* Hack, FIXME */
            p_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
                                      ( p->i_ancillary_page_id   << 16 );
        }
    }
}
static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
                            const dvbpsi_pmt_es_t *p_es )
{
    es_format_t *p_fmt = &pid->es->fmt;
3641
    dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_es, 0x59 );
3642

3643 3644 3645 3646 3647
    if( PMTEsHasRegistration( p_demux, p_es, "AC-3" ) ||
        PMTEsFindDescriptor( p_es, 0x6a ) ||
        PMTEsFindDescriptor( p_es, 0x81 ) )
    {
        p_fmt->i_cat = AUDIO_ES;
3648
        p_fmt->i_codec = VLC_CODEC_A52;
3649 3650 3651 3652 3653
    }
    else if( PMTEsFindDescriptor( p_es, 0x7a ) )
    {
        /* DVB with stream_type 0x06 (ETS EN 300 468) */
        p_fmt->i_cat = AUDIO_ES;
3654
        p_fmt->i_codec = VLC_CODEC_EAC3;
3655 3656 3657 3658 3659 3660 3661 3662
    }
    else if( PMTEsHasRegistration( p_demux, p_es, "DTS1" ) ||
             PMTEsHasRegistration( p_demux, p_es, "DTS2" ) ||
             PMTEsHasRegistration( p_demux, p_es, "DTS3" ) ||
             PMTEsFindDescriptor( p_es, 0x73 ) )
    {
        /*registration descriptor(ETSI TS 101 154 Annex F)*/
        p_fmt->i_cat = AUDIO_ES;
3663
        p_fmt->i_codec = VLC_CODEC_DTS;
3664
    }
3665
    else if( PMTEsHasRegistration( p_demux, p_es, "BSSD" ) && !p_subs_dr )
3666
    {
3667 3668
        /* BSSD is AES3 DATA, but could also be subtitles
         * we need to check for secondary descriptor then s*/
3669 3670
        p_fmt->i_cat = AUDIO_ES;
        p_fmt->b_packetized = true;
3671
        p_fmt->i_codec = VLC_CODEC_302M;
3672
    }
3673 3674 3675 3676 3677
    else if( PMTEsHasRegistration( p_demux, p_es, "HEVC" ) )
    {
        p_fmt->i_cat = VIDEO_ES;
        p_fmt->i_codec = VLC_CODEC_HEVC;
    }
3678 3679 3680 3681
    else
    {
        /* Subtitle/Teletext/VBI fallbacks */
        dvbpsi_subtitling_dr_t *p_sub;
3682
        if( p_subs_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_subs_dr ) ) )
3683 3684 3685 3686 3687
        {
            for( int i = 0; i < p_sub->i_subtitles_number; i++ )
            {
                if( p_fmt->i_cat != UNKNOWN_ES )
                    break;
3688

3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699
                switch( p_sub->p_subtitle[i].i_subtitling_type )
                {
                case 0x01: /* EBU Teletext subtitles */
                case 0x02: /* Associated EBU Teletext */
                case 0x03: /* VBI data */
                    PMTSetupEsTeletext( p_demux, pid, p_es );
                    break;
                case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
                case 0x11: /*                 ...   on 4:3 AR monitor */
                case 0x12: /*                 ...   on 16:9 AR monitor */
                case 0x13: /*                 ...   on 2.21:1 AR monitor */
3700
                case 0x14: /*                 ...   for display on a high definition monitor */
3701 3702 3703 3704
                case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
                case 0x21: /*                 ...   on 4:3 AR monitor */
                case 0x22: /*                 ...   on 16:9 AR monitor */
                case 0x23: /*                 ...   on 2.21:1 AR monitor */
3705
                case 0x24: /*                 ...   for display on a high definition monitor */
3706 3707 3708
                    PMTSetupEsDvbSubtitle( p_demux, pid, p_es );
                    break;
                default:
3709 3710
                    msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
                             p_sub->p_subtitle[i].i_subtitling_type );
3711
                    break;
3712 3713 3714
                }
            }
        }
3715

3716 3717 3718 3719 3720 3721 3722 3723
        if( p_fmt->i_cat == UNKNOWN_ES &&
            ( PMTEsFindDescriptor( p_es, 0x45 ) ||  /* VBI Data descriptor */
              PMTEsFindDescriptor( p_es, 0x46 ) ||  /* VBI Teletext descriptor */
              PMTEsFindDescriptor( p_es, 0x56 ) ) ) /* EBU Teletext descriptor */
        {
            /* Teletext/VBI */
            PMTSetupEsTeletext( p_demux, pid, p_es );
        }
3724
    }
3725

Rémi Denis-Courmont's avatar
Typos  
Rémi Denis-Courmont committed
3726
    /* FIXME is it useful ? */
3727 3728 3729 3730 3731 3732 3733
    if( PMTEsFindDescriptor( p_es, 0x52 ) )
    {
        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
        dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );

        msg_Dbg( p_demux, "    * Stream Component Identifier: %d", p_si->i_component_tag );
    }
3734 3735 3736 3737 3738
}

static void PMTSetupEs0xEA( demux_t *p_demux, ts_pid_t *pid,
                           const dvbpsi_pmt_es_t *p_es )
{
Laurent Aimar's avatar
Laurent Aimar committed
3739
    /* Registration Descriptor */
Laurent Aimar's avatar
Laurent Aimar committed
3740
    if( !PMTEsHasRegistration( p_demux, p_es, "VC-1" ) )
Laurent Aimar's avatar
Laurent Aimar committed
3741
    {
Laurent Aimar's avatar
Laurent Aimar committed
3742
        msg_Err( p_demux, "Registration descriptor not found or invalid" );
Laurent Aimar's avatar
Laurent Aimar committed
3743 3744
        return;
    }
3745

Laurent Aimar's avatar
Laurent Aimar committed
3746
    es_format_t *p_fmt = &pid->es->fmt;
Laurent Aimar's avatar
Laurent Aimar committed
3747

Laurent Aimar's avatar
Laurent Aimar committed
3748 3749
    /* registration descriptor for VC-1 (SMPTE rp227) */
    p_fmt->i_cat = VIDEO_ES;
3750
    p_fmt->i_codec = VLC_CODEC_VC1;
Laurent Aimar's avatar
Laurent Aimar committed
3751

Laurent Aimar's avatar
Laurent Aimar committed
3752 3753 3754 3755
    /* XXX With Simple and Main profile the SEQUENCE
     * header is modified: video width and height are
     * inserted just after the start code as 2 int16_t
     * The packetizer will take care of that. */
3756 3757 3758 3759 3760
}

static void PMTSetupEs0xD1( demux_t *p_demux, ts_pid_t *pid,
                           const dvbpsi_pmt_es_t *p_es )
{
Laurent Aimar's avatar
Laurent Aimar committed
3761
    /* Registration Descriptor */
Laurent Aimar's avatar
Laurent Aimar committed
3762
    if( !PMTEsHasRegistration( p_demux, p_es, "drac" ) )
Laurent Aimar's avatar
Laurent Aimar committed
3763
    {
Laurent Aimar's avatar
Laurent Aimar committed
3764
        msg_Err( p_demux, "Registration descriptor not found or invalid" );
Laurent Aimar's avatar
Laurent Aimar committed
3765 3766
        return;
    }
3767

Laurent Aimar's avatar
Laurent Aimar committed
3768
    es_format_t *p_fmt = &pid->es->fmt;
3769

Laurent Aimar's avatar
Laurent Aimar committed
3770 3771 3772
    /* registration descriptor for Dirac
     * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
    p_fmt->i_cat = VIDEO_ES;
3773
    p_fmt->i_codec = VLC_CODEC_DIRAC;
3774 3775 3776 3777 3778 3779
}

static void PMTSetupEs0xA0( demux_t *p_demux, ts_pid_t *pid,
                           const dvbpsi_pmt_es_t *p_es )
{
    /* MSCODEC sent by vlc */
Laurent Aimar's avatar
Laurent Aimar committed
3780 3781
    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0xa0 );
    if( !p_dr || p_dr->i_length < 10 )
3782
    {
Laurent Aimar's avatar
Laurent Aimar committed
3783 3784 3785
        msg_Warn( p_demux,
                  "private MSCODEC (vlc) without bih private descriptor" );
        return;
3786
    }
Laurent Aimar's avatar
Laurent Aimar committed
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796

    es_format_t *p_fmt = &pid->es->fmt;
    p_fmt->i_cat = VIDEO_ES;
    p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
                                 p_dr->p_data[2], p_dr->p_data[3] );
    p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
    p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
    p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );

    if( p_fmt->i_extra > 0 )
3797
    {
Laurent Aimar's avatar
Laurent Aimar committed
3798 3799 3800 3801 3802 3803
        p_fmt->p_extra = malloc( p_fmt->i_extra );
        if( p_fmt->p_extra )
            memcpy( p_fmt->p_extra, &p_dr->p_data[10],
                    __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
        else
            p_fmt->i_extra = 0;
3804 3805 3806 3807
    }
    /* For such stream we will gather them ourself and don't launch a
     * packetizer.
     * Yes it's ugly but it's the only way to have DIV3 working */
Laurent Aimar's avatar
Laurent Aimar committed
3808
    p_fmt->b_packetized = true;
3809 3810
}

3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pid_t *pid )
{
    /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
     * with audio track pid being 0x1100..0x11FF */
    if ( p_pmt->i_program_number == 0x1 &&
         p_pmt->i_pcr_pid == 0x1000 &&
        ( pid->i_pid >> 8 ) == 0x11 )
    {
        /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
        es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
    }
    else
        es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
}

3826 3827
static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pid_t *pid,
                            const dvbpsi_pmt_es_t *p_es )
3828
{
Laurent Aimar's avatar
Laurent Aimar committed
3829 3830
    es_format_t *p_fmt = &pid->es->fmt;

3831 3832 3833 3834
    /* Blu-Ray mapping */
    switch( p_es->i_type )
    {
    case 0x80:
Laurent Aimar's avatar
Laurent Aimar committed
3835
        p_fmt->i_cat = AUDIO_ES;
3836
        p_fmt->i_codec = VLC_CODEC_BD_LPCM;
3837 3838 3839 3840 3841
        break;
    case 0x82:
    case 0x85: /* DTS-HD High resolution audio */
    case 0x86: /* DTS-HD Master audio */
    case 0xA2: /* Secondary DTS audio */
Laurent Aimar's avatar
Laurent Aimar committed
3842
        p_fmt->i_cat = AUDIO_ES;
3843
        p_fmt->i_codec = VLC_CODEC_DTS;
3844 3845 3846
        break;

    case 0x83: /* TrueHD AC3 */
Laurent Aimar's avatar
Laurent Aimar committed
3847
        p_fmt->i_cat = AUDIO_ES;
3848
        p_fmt->i_codec = VLC_CODEC_TRUEHD;
3849 3850 3851 3852
        break;

    case 0x84: /* E-AC3 */
    case 0xA1: /* Secondary E-AC3 */
Laurent Aimar's avatar
Laurent Aimar committed
3853
        p_fmt->i_cat = AUDIO_ES;
3854
        p_fmt->i_codec = VLC_CODEC_EAC3;
3855 3856
        break;
    case 0x90: /* Presentation graphics */
3857 3858 3859
        p_fmt->i_cat = SPU_ES;
        p_fmt->i_codec = VLC_CODEC_BD_PG;
        break;
3860 3861
    case 0x91: /* Interactive graphics */
    case 0x92: /* Subtitle */
3862
        return false;
3863
    default:
3864 3865 3866
        msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
                  p_es->i_pid, p_es->i_type );
        return false;
3867 3868
        break;
    }
3869
    return true;
3870
}
3871

3872
static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pid_t *pid,
3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897
                                    const dvbpsi_pmt_es_t *p_es )
{
    static const struct
    {
        char         psz_tag[5];
        int          i_cat;
        vlc_fourcc_t i_codec;
    } p_regs[] = {
        { "AC-3", AUDIO_ES, VLC_CODEC_A52   },
        { "DTS1", AUDIO_ES, VLC_CODEC_DTS   },
        { "DTS2", AUDIO_ES, VLC_CODEC_DTS   },
        { "DTS3", AUDIO_ES, VLC_CODEC_DTS   },
        { "BSSD", AUDIO_ES, VLC_CODEC_302M  },
        { "VC-1", VIDEO_ES, VLC_CODEC_VC1   },
        { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
        { "", UNKNOWN_ES, 0 }
    };
    es_format_t *p_fmt = &pid->es->fmt;

    for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
    {
        if( PMTEsHasRegistration( p_demux, p_es, p_regs[i].psz_tag ) )
        {
            p_fmt->i_cat   = p_regs[i].i_cat;
            p_fmt->i_codec = p_regs[i].i_codec;
3898 3899
            if (p_es->i_type == 0x87)
                p_fmt->i_codec = VLC_CODEC_EAC3;
3900
            return true;
3901 3902
        }
    }
3903
    return false;
3904 3905
}

3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
static char *GetAudioTypeDesc(demux_t *p_demux, int type)
{
    static const char *audio_type[] = {
        NULL,
        N_("clean effects"),
        N_("hearing impaired"),
        N_("visual impaired commentary"),
    };

    if (type < 0 || type > 3)
        msg_Dbg( p_demux, "unknown audio type: %d", type);
    else if (type > 0)
3918
        return strdup(audio_type[type]);
3919 3920 3921

    return NULL;
}
3922
static void PMTParseEsIso639( demux_t *p_demux, ts_pid_t *pid,
Laurent Aimar's avatar
Laurent Aimar committed
3923
                              const dvbpsi_pmt_es_t *p_es )
3924 3925
{
    /* get language descriptor */
Laurent Aimar's avatar
Laurent Aimar committed
3926
    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x0a );
3927

Laurent Aimar's avatar
Laurent Aimar committed
3928 3929 3930 3931 3932
    if( !p_dr )
        return;

    dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
    if( !p_decoded )
3933
    {
Laurent Aimar's avatar
Laurent Aimar committed
3934 3935 3936
        msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
        return;
    }
3937 3938

#if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
Laurent Aimar's avatar
Laurent Aimar committed
3939 3940 3941
    pid->es->fmt.psz_language = malloc( 4 );
    if( pid->es->fmt.psz_language )
    {
3942
        memcpy( pid->es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
Laurent Aimar's avatar
Laurent Aimar committed
3943 3944 3945
        pid->es->fmt.psz_language[3] = 0;
        msg_Dbg( p_demux, "found language: %s", pid->es->fmt.psz_language);
    }
3946 3947 3948
    int type = p_decoded->code[0].i_audio_type;
    pid->es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
    if (type == 0)
3949
        pid->es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
3950

Laurent Aimar's avatar
Laurent Aimar committed
3951 3952 3953 3954 3955 3956 3957 3958 3959
    pid->es->fmt.i_extra_languages = p_decoded->i_code_count-1;
    if( pid->es->fmt.i_extra_languages > 0 )
        pid->es->fmt.p_extra_languages =
            malloc( sizeof(*pid->es->fmt.p_extra_languages) *
                    pid->es->fmt.i_extra_languages );
    if( pid->es->fmt.p_extra_languages )
    {
        for( int i = 0; i < pid->es->fmt.i_extra_languages; i++ )
        {
3960
            pid->es->fmt.p_extra_languages[i].psz_language = malloc(4);
Laurent Aimar's avatar
Laurent Aimar committed
3961
            if( pid->es->fmt.p_extra_languages[i].psz_language )
3962
            {
Laurent Aimar's avatar
Laurent Aimar committed
3963 3964 3965
                memcpy( pid->es->fmt.p_extra_languages[i].psz_language,
                    p_decoded->code[i+1].iso_639_code, 3 );
                pid->es->fmt.p_extra_languages[i].psz_language[3] = '\0';
3966
            }
3967
            int type = p_decoded->code[i].i_audio_type;
3968
            pid->es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
3969 3970
        }
    }
Laurent Aimar's avatar
Laurent Aimar committed
3971 3972 3973 3974 3975 3976 3977 3978 3979
#else
    pid->es->fmt.psz_language = malloc( 4 );
    if( pid->es->fmt.psz_language )
    {
        memcpy( pid->es->fmt.psz_language,
                p_decoded->i_iso_639_code, 3 );
        pid->es->fmt.psz_language[3] = 0;
    }
#endif
3980 3981
}

3982
static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
3983
{
3984 3985
    demux_t      *p_demux = data;
    demux_sys_t  *p_sys = p_demux->p_sys;
3986

3987 3988
    ts_pid_t     *pmt = NULL;
    ts_prg_psi_t *prg;
3989 3990

    msg_Dbg( p_demux, "PMTCallBack called" );
3991

3992
    /* First find this PMT declared in PAT */
3993 3994
    for( int i = 0; !pmt && i < p_sys->i_pmt; i++ )
        for( int i_prg = 0; !pmt && i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
3995
        {
3996
            const int i_pmt_number = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
3997 3998
            if( i_pmt_number != TS_USER_PMT_NUMBER &&
                i_pmt_number == p_pmt->i_program_number )
3999 4000 4001 4002
            {
                pmt = p_sys->pmt[i];
                prg = p_sys->pmt[i]->psi->prg[i_prg];
            }
4003
        }
4004

4005 4006 4007 4008 4009 4010 4011
    if( pmt == NULL )
    {
        msg_Warn( p_demux, "unreferenced program (broken stream)" );
        dvbpsi_DeletePMT(p_pmt);
        return;
    }

4012

4013 4014
    if( prg->i_version != -1 &&
        ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
4015 4016 4017 4018 4019
    {
        dvbpsi_DeletePMT( p_pmt );
        return;
    }

4020 4021
    ts_pid_t **pp_clean = NULL;
    int      i_clean = 0;
4022
    /* Clean this program (remove all es) */
Laurent Aimar's avatar
Laurent Aimar committed
4023
    for( int i = 0; i < 8192; i++ )
4024 4025 4026
    {
        ts_pid_t *pid = &p_sys->pid[i];

4027 4028
        if( pid->b_valid && pid->p_owner == pmt->psi &&
            pid->i_owner_number == prg->i_number && pid->psi == NULL )
4029
        {
4030
            TAB_APPEND( i_clean, pp_clean, pid );
4031 4032
        }
    }
4033
    if( prg->iod )
4034
    {
4035 4036
        IODFree( prg->iod );
        prg->iod = NULL;
4037 4038
    }

4039
    msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
4040
             p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
4041 4042
    prg->i_pid_pcr = p_pmt->i_pcr_pid;
    prg->i_version = p_pmt->i_version;
4043

Laurent Aimar's avatar
Laurent Aimar committed
4044 4045
    ValidateDVBMeta( p_demux, prg->i_pid_pcr );
    if( ProgramIsSelected( p_demux, prg->i_number ) )
4046
        SetPIDFilter( p_demux, prg->i_pid_pcr, true ); /* Set demux filter */
4047

4048 4049
    /* Parse PMT descriptors */
    ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
4050
    dvbpsi_descriptor_t  *p_dr;
4051
    for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
4052
        switch(p_dr->i_tag)
4053
        {
4054
        case 0x1d: /* We have found an IOD descriptor */
4055
            msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
4056
            prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
4057 4058 4059
            break;

        case 0x9:
4060
            msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
4061 4062 4063 4064
                    (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
            break;

        case 0x5: /* Registration Descriptor */
4065
            if( p_dr->i_length != 4 )
4066
            {
4067
                msg_Warn( p_demux, " * PMT invalid Registration Descriptor" );
4068 4069 4070
            }
            else
            {
4071
                msg_Dbg( p_demux, " * PMT descriptor : registration %4.4s", p_dr->p_data );
4072
                if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
4073
                    registration_type = TS_PMT_REGISTRATION_HDMV; /* Blu-Ray */
4074
            }
4075 4076
            break;

4077
        case 0x0f:
4078 4079 4080 4081 4082
            msg_Dbg( p_demux, " * PMT descriptor : Private Data (0x0f)" );
            break;

        case 0xC1:
            msg_Dbg( p_demux, " * PMT descriptor : Digital copy control (0xC1)" );
4083 4084
            break;

4085 4086 4087 4088 4089
        case 0x88: /* EACEM Simulcast HD Logical channels ordering */
            msg_Dbg( p_demux, " * descriptor : EACEM Simulcast HD" );
            /* TODO: apply visibility flags */
            break;

4090
        default:
4091
            msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
4092
        }
4093

4094
    dvbpsi_pmt_es_t      *p_es;
4095 4096
    for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
    {
4097 4098 4099
        ts_pid_t tmp_pid, *old_pid = 0, *pid = &tmp_pid;

        /* Find out if the PID was already declared */
Laurent Aimar's avatar
Laurent Aimar committed
4100
        for( int i = 0; i < i_clean; i++ )
4101 4102 4103 4104 4105 4106 4107
        {
            if( pp_clean[i] == &p_sys->pid[p_es->i_pid] )
            {
                old_pid = pp_clean[i];
                break;
            }
        }
Laurent Aimar's avatar
Laurent Aimar committed
4108
        ValidateDVBMeta( p_demux, p_es->i_pid );
4109

4110
        if( !old_pid && p_sys->pid[p_es->i_pid].b_valid )
4111
        {
4112
            msg_Warn( p_demux, " * PMT error: pid=%d already defined",
4113 4114
                      p_es->i_pid );
            continue;
4115 4116
        }

4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174
        char const * psz_typedesc = "";
        switch(p_es->i_type)
        {
        case 0x00:
            psz_typedesc = "ISO/IEC Reserved";
            break;
        case 0x01:
            psz_typedesc = "ISO/IEC 11172 Video";
            break;
        case 0x02:
            psz_typedesc = "ISO/IEC 13818-2 Video or ISO/IEC 11172-2 constrained parameter video stream";
            break;
        case 0x03:
            psz_typedesc = "ISO/IEC 11172 Audio";
            break;
        case 0x04:
            psz_typedesc = "ISO/IEC 13818-3 Audio";
            break;
        case 0x05:
            psz_typedesc = "ISO/IEC 13818-1 private_sections";
            break;
        case 0x06:
            psz_typedesc = "ISO/IEC 13818-1 PES packets containing private data";
            break;
        case 0x07:
            psz_typedesc = "ISO/IEC 13522 MHEG";
            break;
        case 0x08:
            psz_typedesc = "ISO/IEC 13818-1 Annex A DSM CC";
            break;
        case 0x09:
            psz_typedesc = "ITU-T Rec. H.222.1";
            break;
        case 0x0A:
            psz_typedesc = "ISO/IEC 13818-6 type A";
            break;
        case 0x0B:
            psz_typedesc = "ISO/IEC 13818-6 type B";
            break;
        case 0x0C:
            psz_typedesc = "ISO/IEC 13818-6 type C";
            break;
        case 0x0D:
            psz_typedesc = "ISO/IEC 13818-6 type D";
            break;
        case 0x0E:
            psz_typedesc = "ISO/IEC 13818-1 auxiliary";
            break;
        default:
            if (p_es->i_type >= 0x0F && p_es->i_type <=0x7F)
                psz_typedesc = "ISO/IEC 13818-1 Reserved";
            else
                psz_typedesc = "User Private";
        }

        msg_Dbg( p_demux, "  * pid=%d type=0x%x %s",
                 p_es->i_pid, p_es->i_type, psz_typedesc );

Laurent Aimar's avatar
Laurent Aimar committed
4175 4176 4177
        for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
             p_dr = p_dr->p_next )
        {
4178 4179
            msg_Dbg( p_demux, "    - descriptor tag 0x%x",
                     p_dr->i_tag );
Laurent Aimar's avatar
Laurent Aimar committed
4180 4181
        }

4182
        PIDInit( pid, false, pmt->psi );
4183
        PIDFillFormat( &pid->es->fmt, p_es->i_type );
4184
        pid->i_owner_number = prg->i_number;
4185 4186
        pid->i_pid          = p_es->i_pid;
        pid->b_seen         = p_sys->pid[p_es->i_pid].b_seen;
4187

4188 4189 4190

        bool b_registration_applied = false;
        if ( p_es->i_type >= 0x80 ) /* non standard, extensions */
4191
        {
4192 4193 4194
            if ( registration_type == TS_PMT_REGISTRATION_HDMV )
            {
                if (( b_registration_applied = PMTSetupEsHDMV( p_demux, pid, p_es ) ))
4195
                    msg_Dbg( p_demux, "    + HDMV registration applied to pid %d type 0x%x",
4196 4197 4198 4199 4200
                             p_es->i_pid, p_es->i_type );
            }
            else
            {
                if (( b_registration_applied = PMTSetupEsRegistration( p_demux, pid, p_es ) ))
4201
                    msg_Dbg( p_demux, "    + registration applied to pid %d type 0x%x",
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233
                        p_es->i_pid, p_es->i_type );
            }
        }

        if ( !b_registration_applied )
        {
            switch( p_es->i_type )
            {
            case 0x10:
            case 0x11:
            case 0x12:
            case 0x0f:
                PMTSetupEsISO14496( p_demux, pid, prg, p_es );
                break;
            case 0x06:
                PMTSetupEs0x06( p_demux, pid, p_es );
                break;
            case 0x83:
                /* LPCM (audio) */
                PMTSetupEs0x83( p_pmt, pid );
                break;
            case 0xa0:
                PMTSetupEs0xA0( p_demux, pid, p_es );
                break;
            case 0xd1:
                PMTSetupEs0xD1( p_demux, pid, p_es );
                break;
            case 0xEA:
                PMTSetupEs0xEA( p_demux, pid, p_es );
            default:
                break;
            }
4234
        }
4235

4236 4237
        if( pid->es->fmt.i_cat == AUDIO_ES ||
            ( pid->es->fmt.i_cat == SPU_ES &&
4238 4239
              pid->es->fmt.i_codec != VLC_CODEC_DVBS &&
              pid->es->fmt.i_codec != VLC_CODEC_TELETEXT ) )
4240
        {
4241
            PMTParseEsIso639( p_demux, pid, p_es );
4242 4243
        }

4244 4245 4246 4247 4248 4249 4250 4251 4252 4253
        switch( pid->es->fmt.i_codec )
        {
        case VLC_CODEC_SCTE_27:
            pid->es->data_type = TS_ES_DATA_TABLE_SECTION;
            break;
        default:
            //pid->es->data_type = TS_ES_DATA_PES;
            break;
        }

4254
        pid->es->fmt.i_group = p_pmt->i_program_number;
4255 4256 4257
        for( int i = 0; i < pid->i_extra_es; i++ )
            pid->extra_es[i]->fmt.i_group = p_pmt->i_program_number;

4258 4259
        if( pid->es->fmt.i_cat == UNKNOWN_ES )
        {
4260 4261
            msg_Dbg( p_demux, "   => pid %d content is *unknown*",
                     p_es->i_pid );
4262
        }
Rafaël Carré's avatar
Rafaël Carré committed
4263
        else
4264
        {
4265 4266
            msg_Dbg( p_demux, "   => pid %d has now es fcc=%4.4s",
                     p_es->i_pid, (char*)&pid->es->fmt.i_codec );
4267

4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
            if( p_sys->b_es_id_pid ) pid->es->fmt.i_id = p_es->i_pid;

            /* Check if we can avoid restarting the ES */
            if( old_pid &&
                pid->es->fmt.i_codec == old_pid->es->fmt.i_codec &&
                pid->es->fmt.i_extra == old_pid->es->fmt.i_extra &&
                pid->es->fmt.i_extra == 0 &&
                pid->i_extra_es == old_pid->i_extra_es &&
                ( ( !pid->es->fmt.psz_language &&
                    !old_pid->es->fmt.psz_language ) ||
                  ( pid->es->fmt.psz_language &&
                    old_pid->es->fmt.psz_language &&
                    !strcmp( pid->es->fmt.psz_language,
                             old_pid->es->fmt.psz_language ) ) ) )
4282
            {
4283 4284 4285 4286
                pid->i_cc = old_pid->i_cc;
                ts_es_t *e = pid->es;
                pid->es = old_pid->es;
                old_pid->es = e;
Laurent Aimar's avatar
Laurent Aimar committed
4287
                for( int i = 0; i < pid->i_extra_es; i++ )
4288
                {
4289 4290 4291
                    e = pid->extra_es[i];
                    pid->extra_es[i] = old_pid->extra_es[i];
                    old_pid->extra_es[i] = e;
4292
                }
4293
            }
4294
            else
4295
            {
4296
                pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
Laurent Aimar's avatar
Laurent Aimar committed
4297
                for( int i = 0; i < pid->i_extra_es; i++ )
4298 4299 4300 4301
                {
                    pid->extra_es[i]->id =
                        es_out_Add( p_demux->out, &pid->extra_es[i]->fmt );
                }
4302
                p_sys->i_pmt_es += 1 + pid->i_extra_es;
4303
            }
4304
        }
4305

4306 4307 4308
        /* Add ES to the list */
        if( old_pid )
        {
4309
            PIDClean( p_demux, old_pid );
4310 4311 4312 4313
            TAB_REMOVE( i_clean, pp_clean, old_pid );
        }
        p_sys->pid[p_es->i_pid] = *pid;

Laurent Aimar's avatar
Laurent Aimar committed
4314 4315
        p_dr = PMTEsFindDescriptor( p_es, 0x09 );
        if( p_dr && p_dr->i_length >= 2 )
4316
        {
4317
            msg_Dbg( p_demux, "   * PMT descriptor : CA (0x9) SysID 0x%x",
4318
                     (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
4319 4320
        }

Rafaël Carré's avatar
Rafaël Carré committed
4321
        if( ProgramIsSelected( p_demux, prg->i_number ) && pid->es->id != NULL )
4322
            SetPIDFilter( p_demux, p_es->i_pid, true ); /* Set demux filter */
4323
    }
4324

4325 4326
    /* Set CAM descrambling */
    if( !ProgramIsSelected( p_demux, prg->i_number )
4327 4328
     || stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_CA,
                        p_pmt ) != VLC_SUCCESS )
Christophe Massiot's avatar
Christophe Massiot committed
4329
        dvbpsi_DeletePMT( p_pmt );
4330

Laurent Aimar's avatar
Laurent Aimar committed
4331
    for( int i = 0; i < i_clean; i++ )
4332
    {
Laurent Aimar's avatar
Laurent Aimar committed
4333
        if( ProgramIsSelected( p_demux, prg->i_number ) )
Laurent Aimar's avatar
Laurent Aimar committed
4334
            SetPIDFilter( p_demux, pp_clean[i]->i_pid, false );
4335

4336
        PIDClean( p_demux, pp_clean[i] );
4337
    }
Laurent Aimar's avatar
Laurent Aimar committed
4338 4339
    if( i_clean )
        free( pp_clean );
4340 4341
}

4342
static void PATCallBack( void *data, dvbpsi_pat_t *p_pat )
4343
{
4344
    demux_t              *p_demux = data;
4345 4346 4347 4348 4349 4350
    demux_sys_t          *p_sys = p_demux->p_sys;
    dvbpsi_pat_program_t *p_program;
    ts_pid_t             *pat = &p_sys->pid[0];

    msg_Dbg( p_demux, "PATCallBack called" );

4351 4352 4353 4354
    if( ( pat->psi->i_pat_version != -1 &&
            ( !p_pat->b_current_next ||
              p_pat->i_version == pat->psi->i_pat_version ) ) ||
        p_sys->b_user_pmt )
4355 4356 4357 4358 4359
    {
        dvbpsi_DeletePAT( p_pat );
        return;
    }

4360
    msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
Gildas Bazin's avatar
 
Gildas Bazin committed
4361
             p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
4362 4363

    /* Clean old */
4364
    if( p_sys->i_pmt > 0 )
4365
    {
4366 4367
        int      i_pmt_rm = 0;
        ts_pid_t **pmt_rm = NULL;
4368

4369
        /* Search pmt to be deleted */
Laurent Aimar's avatar
Laurent Aimar committed
4370
        for( int i = 0; i < p_sys->i_pmt; i++ )
4371
        {
4372
            ts_pid_t *pmt = p_sys->pmt[i];
4373
            bool b_keep = false;
4374

4375
            for( p_program = p_pat->p_first_program; !b_keep && p_program;
4376
                 p_program = p_program->p_next )
4377
            {
4378 4379
                if( p_program->i_pid != pmt->i_pid )
                    continue;
4380

4381 4382 4383
                for( int i_prg = 0; !b_keep && i_prg < pmt->psi->i_prg; i_prg++ )
                    if( p_program->i_number == pmt->psi->prg[i_prg]->i_number )
                        b_keep = true;
4384
            }
4385 4386 4387 4388 4389

            if( b_keep )
                continue;

            TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
4390 4391 4392
        }

        /* Delete all ES attached to thoses PMT */
Laurent Aimar's avatar
Laurent Aimar committed
4393
        for( int i = 2; i < 8192; i++ )
4394 4395
        {
            ts_pid_t *pid = &p_sys->pid[i];
4396

Laurent Aimar's avatar
Laurent Aimar committed
4397 4398
            if( !pid->b_valid || pid->psi )
                continue;
4399

Laurent Aimar's avatar
Laurent Aimar committed
4400
            for( int j = 0; j < i_pmt_rm && pid->b_valid; j++ )
4401
            {
Laurent Aimar's avatar
Laurent Aimar committed
4402
                for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
4403
                {
4404
                    /* We only remove es that aren't defined by extra pmt */
Laurent Aimar's avatar
Laurent Aimar committed
4405 4406
                    if( pid->p_owner->prg[i_prg]->i_pid_pmt != pmt_rm[j]->i_pid )
                        continue;
4407

Laurent Aimar's avatar
Laurent Aimar committed
4408 4409
                    if( pid->es->id )
                        SetPIDFilter( p_demux, i, false );
4410

4411
                    PIDClean( p_demux, pid );
4412
                    break;
4413
                }
4414 4415
            }
        }
4416 4417

        /* Delete PMT pid */
Laurent Aimar's avatar
Laurent Aimar committed
4418
        for( int i = 0; i < i_pmt_rm; i++ )
4419
        {
4420 4421
            ts_pid_t *pid = pmt_rm[i];
            SetPIDFilter( p_demux, pid->i_pid, false );
4422

4423
            for( int i_prg = 0; i_prg < pid->psi->i_prg; i_prg++ )
4424
            {
4425
                const int i_number = pid->psi->prg[i_prg]->i_number;
4426
                es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, i_number );
4427 4428
            }

4429 4430
            PIDClean( p_demux, &p_sys->pid[pid->i_pid] );
            TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pid );
4431
        }
4432

4433
        free( pmt_rm );
4434 4435 4436
    }

    /* now create programs */
Gildas Bazin's avatar
 
Gildas Bazin committed
4437 4438
    for( p_program = p_pat->p_first_program; p_program != NULL;
         p_program = p_program->p_next )
4439
    {
4440
        msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
Gildas Bazin's avatar
 
Gildas Bazin committed
4441
                 p_program->i_pid );
4442 4443 4444 4445 4446 4447 4448 4449
        if( p_program->i_number == 0 )
            continue;

        ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];

        ValidateDVBMeta( p_demux, p_program->i_pid );

        if( pmt->b_valid )
4450
        {
4451
            bool b_add = true;
4452 4453 4454
            for( int i_prg = 0; b_add && i_prg < pmt->psi->i_prg; i_prg++ )
                if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
                    b_add = false;
4455

4456 4457 4458 4459 4460 4461 4462
            if( !b_add )
                continue;
        }
        else
        {
            TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
        }
4463

4464 4465
        PIDInit( pmt, true, pat->psi );
        ts_prg_psi_t *prg = pmt->psi->prg[pmt->psi->i_prg-1];
4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479
#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
        prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
        if( !prg->handle )
        {
            dvbpsi_DeletePAT( p_pat );
            return;
        }
        prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
        if( !dvbpsi_pmt_attach( prg->handle, p_program->i_number, PMTCallBack, p_demux ) )
            msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
                     p_program->i_number );
#else
        prg->handle = dvbpsi_AttachPMT( p_program->i_number, PMTCallBack, p_demux );
#endif
4480 4481
        prg->i_number = p_program->i_number;
        prg->i_pid_pmt = p_program->i_pid;
4482

4483 4484 4485 4486 4487
        /* Now select PID at access level */
        if( ProgramIsSelected( p_demux, p_program->i_number ) )
        {
            if( p_sys->i_current_program == 0 )
                p_sys->i_current_program = p_program->i_number;
4488

4489 4490
            if( SetPIDFilter( p_demux, p_program->i_pid, true ) )
                p_sys->b_access_control = false;
4491 4492
        }
    }
4493
    pat->psi->i_pat_version = p_pat->i_version;
4494 4495 4496

    dvbpsi_DeletePAT( p_pat );
}