ts.c 137 KB
Newer Older
1
2
3
/*****************************************************************************
 * ts.c: Transport Stream input module for VLC.
 *****************************************************************************
zorglub's avatar
zorglub committed
4
 * Copyright (C) 2004-2005 the VideoLAN team
5
 * $Id$
6
7
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8
 *          Jean-Paul Saman <jpsaman #_at_# m2x.nl>
9
10
11
12
13
14
15
16
17
18
19
20
21
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
dionoea's avatar
dionoea committed
22
 * 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

zorglub's avatar
zorglub committed
38
39
40
#include <vlc_access.h> /* DVB-specific things */
#include <vlc_demux.h>
#include <vlc_meta.h>
41
#include <vlc_epg.h>
42

43
#include <vlc_iso_lang.h>
zorglub's avatar
zorglub committed
44
45
#include <vlc_network.h>
#include <vlc_charset.h>
46

47
48
#include "../mux/mpeg/csa.h"

49
50
51
/* Include dvbpsi headers */
#ifdef HAVE_DVBPSI_DR_H
#   include <dvbpsi/dvbpsi.h>
52
#   include <dvbpsi/demux.h>
53
54
55
#   include <dvbpsi/descriptor.h>
#   include <dvbpsi/pat.h>
#   include <dvbpsi/pmt.h>
56
#   include <dvbpsi/sdt.h>
57
58
59
60
#   include <dvbpsi/dr.h>
#   include <dvbpsi/psi.h>
#else
#   include "dvbpsi.h"
61
#   include "demux.h"
62
63
64
#   include "descriptor.h"
#   include "tables/pat.h"
#   include "tables/pmt.h"
65
#   include "tables/sdt.h"
66
67
68
69
#   include "descriptors/dr.h"
#   include "psi.h"
#endif

70
71
72
73
74
75
76
77
78
/* EIT support */
#ifdef _DVBPSI_DR_4D_H_
#   define TS_USE_DVB_SI 1
#   ifdef HAVE_DVBPSI_DR_H
#       include <dvbpsi/eit.h>
#   else
#       include "tables/eit.h"
#   endif
#endif
79
80

/* TDT support */
81
#ifdef _DVBPSI_DR_58_H_
82
83
84
85
86
87
#   define TS_USE_TDT 1
#   ifdef HAVE_DVBPSI_DR_H
#       include <dvbpsi/tot.h>
#   else
#       include "tables/tot.h"
#   endif
88
89
#else
#   include <time.h>
90
91
#endif

92
93
#undef TS_DEBUG

94
95
96
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
gbazin's avatar
   
gbazin committed
97
98
static int  Open  ( vlc_object_t * );
static void Close ( vlc_object_t * );
99

100
101
102
/* TODO
 * - Rename "extra pmt" to "user pmt"
 * - Update extra pmt description
103
 *      pmt_pid[:pmt_number][=pid_description[,pid_description]]
104
105
106
 *      where pid_description could take 3 forms:
 *          1. pid:pcr (to force the pcr pid)
 *          2. pid:stream_type
107
 *          3. pid:type=fourcc where type=(video|audio|spu)
108
 */
109
110
#define PMT_TEXT N_("Extra PMT")
#define PMT_LONGTEXT N_( \
111
  "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])." )
112
113

#define PID_TEXT N_("Set id of ES to PID")
114
115
116
117
#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>\"}\'.")
118
119
120

#define TSOUT_TEXT N_("Fast udp streaming")
#define TSOUT_LONGTEXT N_( \
121
  "Sends TS to specific ip:port by udp (you must know what you are doing).")
122
123

#define MTUOUT_TEXT N_("MTU for out mode")
124
#define MTUOUT_LONGTEXT N_("MTU for out mode.")
125
126

#define CSA_TEXT N_("CSA ck")
Christophe Mutricy's avatar
Typo    
Christophe Mutricy committed
127
#define CSA_LONGTEXT N_("Control word for the CSA encryption algorithm")
128

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
129
130
131
132
#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).")

133
#define SILENT_TEXT N_("Silent mode")
134
#define SILENT_LONGTEXT N_("Do not complain on encrypted PES.")
135

136
#define CAPMT_SYSID_TEXT N_("CAPMT System ID")
137
#define CAPMT_SYSID_LONGTEXT N_("Only forward descriptors from this SysID to the CAM.")
138

139
140
141
142
143
144
#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. " )

#define TSDUMP_TEXT N_("Filename of dump")
145
#define TSDUMP_LONGTEXT N_("Specify a filename where to dump the TS in.")
146
147
148
149
150
151
152
153
154
155
156

#define APPEND_TEXT N_("Append")
#define APPEND_LONGTEXT N_( \
    "If the file exists and this option is selected, the existing file " \
    "will not be overwritten." )

#define DUMPSIZE_TEXT N_("Dump buffer size")
#define DUMPSIZE_LONGTEXT N_( \
    "Tweak the buffer size for reading and writing an integer number of packets." \
    "Specify the size of the buffer here and not the number of packets." )

157
158
159
160
161
#define SPLIT_ES_TEXT N_("Separate sub-streams")
#define SPLIT_ES_LONGTEXT N_( \
    "Separate teletex/dvbs pages into independant ES. " \
    "It can be usefull to turn off this option when using stream output." )

162
163
164
165
166
167
168
vlc_module_begin ()
    set_description( N_("MPEG Transport Stream demuxer") )
    set_shortname ( "MPEG-TS" )
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_DEMUX )

    add_string( "ts-extra-pmt", NULL, NULL, PMT_TEXT, PMT_LONGTEXT, true )
ivoire's avatar
ivoire committed
169
    add_bool( "ts-es-id-pid", true, NULL, PID_TEXT, PID_LONGTEXT, true )
170
    add_string( "ts-out", NULL, NULL, TSOUT_TEXT, TSOUT_LONGTEXT, true )
171
    add_integer( "ts-out-mtu", 1400, NULL, MTUOUT_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
172
                 MTUOUT_LONGTEXT, true )
173
174
175
    add_string( "ts-csa-ck", NULL, NULL, CSA_TEXT, CSA_LONGTEXT, true )
    add_string( "ts-csa2-ck", NULL, NULL, CSA_TEXT, CSA_LONGTEXT, true )
    add_integer( "ts-csa-pkt", 188, NULL, CPKT_TEXT, CPKT_LONGTEXT, true )
ivoire's avatar
ivoire committed
176
    add_bool( "ts-silent", false, NULL, SILENT_TEXT, SILENT_LONGTEXT, true )
177

178
    add_file( "ts-dump-file", NULL, NULL, TSDUMP_TEXT, TSDUMP_LONGTEXT, false )
ivoire's avatar
ivoire committed
179
    add_bool( "ts-dump-append", false, NULL, APPEND_TEXT, APPEND_LONGTEXT, false )
180
    add_integer( "ts-dump-size", 16384, NULL, DUMPSIZE_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
181
                 DUMPSIZE_LONGTEXT, true )
182
    add_bool( "ts-split-es", true, NULL, SPLIT_ES_TEXT, SPLIT_ES_LONGTEXT, false )
183

184
185
186
187
    set_capability( "demux", 10 )
    set_callbacks( Open, Close )
    add_shortcut( "ts" )
vlc_module_end ()
188
189
190
191

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
192
193
194
195
static const char *const ppsz_teletext_type[] = {
 "",
 N_("Teletext"),
 N_("Teletext subtitles"),
196
197
198
 N_("Teletext: additional information"),
 N_("Teletext: program schedule"),
 N_("Teletext subtitles: hearing impaired")
199
};
200
201
202
203
204

typedef struct
{
    uint8_t                 i_objectTypeIndication;
    uint8_t                 i_streamType;
205
    bool                    b_upStream;
206
207
208
209
210
211
212
213
214
215
216
    uint32_t                i_bufferSizeDB;
    uint32_t                i_maxBitrate;
    uint32_t                i_avgBitrate;

    int                     i_decoder_specific_info_len;
    uint8_t                 *p_decoder_specific_info;

} decoder_config_descriptor_t;

typedef struct
{
217
218
219
220
221
222
223
224
    bool                    b_useAccessUnitStartFlag;
    bool                    b_useAccessUnitEndFlag;
    bool                    b_useRandomAccessPointFlag;
    bool                    b_useRandomAccessUnitsOnlyFlag;
    bool                    b_usePaddingFlag;
    bool                    b_useTimeStampsFlags;
    bool                    b_useIdleFlag;
    bool                    b_durationFlag;
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    uint32_t                i_timeStampResolution;
    uint32_t                i_OCRResolution;
    uint8_t                 i_timeStampLength;
    uint8_t                 i_OCRLength;
    uint8_t                 i_AU_Length;
    uint8_t                 i_instantBitrateLength;
    uint8_t                 i_degradationPriorityLength;
    uint8_t                 i_AU_seqNumLength;
    uint8_t                 i_packetSeqNumLength;

    uint32_t                i_timeScale;
    uint16_t                i_accessUnitDuration;
    uint16_t                i_compositionUnitDuration;

    uint64_t                i_startDecodingTimeStamp;
    uint64_t                i_startCompositionTimeStamp;

} sl_config_descriptor_t;

typedef struct
{
246
    bool                    b_ok;
247
248
    uint16_t                i_es_id;

249
250
    bool                    b_streamDependenceFlag;
    bool                    b_OCRStreamFlag;
251
252
253
254
255
256
257
258
259
    uint8_t                 i_streamPriority;

    char                    *psz_url;

    uint16_t                i_dependOn_es_id;
    uint16_t                i_OCR_es_id;

    decoder_config_descriptor_t    dec_descr;
    sl_config_descriptor_t         sl_descr;
260

261
262
263
264
} es_mpeg4_descriptor_t;

typedef struct
{
265
    uint8_t                 i_iod_label, i_iod_label_scope;
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

    /* IOD */
    uint16_t                i_od_id;
    char                    *psz_url;

    uint8_t                 i_ODProfileLevelIndication;
    uint8_t                 i_sceneProfileLevelIndication;
    uint8_t                 i_audioProfileLevelIndication;
    uint8_t                 i_visualProfileLevelIndication;
    uint8_t                 i_graphicsProfileLevelIndication;

    es_mpeg4_descriptor_t   es_descr[255];

} iod_descriptor_t;

typedef struct
{
283
284
    dvbpsi_handle   handle;

285
286
287
    int             i_version;
    int             i_number;
    int             i_pid_pcr;
288
    int             i_pid_pmt;
289
290
    /* IOD stuff (mpeg4) */
    iod_descriptor_t *iod;
291

292
293
} ts_prg_psi_t;

294
295
296
297
typedef struct
{
    /* for special PAT/SDT case */
    dvbpsi_handle   handle; /* PAT/SDT/EIT */
298
    int             i_pat_version;
299
    int             i_sdt_version;
300
301
302
303

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

305
306
307
308
309
310
} ts_psi_t;

typedef struct
{
    es_format_t  fmt;
    es_out_id_t *id;
311
312
    int         i_pes_size;
    int         i_pes_gathered;
313
    block_t     *p_pes;
314
    block_t     **pp_last;
315
316

    es_mpeg4_descriptor_t *p_mpeg4desc;
317
    int         b_gather;
318

319
320
321
322
323
324
} ts_es_t;

typedef struct
{
    int         i_pid;

325
326
    bool        b_seen;
    bool        b_valid;
327
    int         i_cc;   /* countinuity counter */
328
    bool        b_scrambled;
329
330
331

    /* PSI owner (ie PMT -> PAT, ES -> PMT */
    ts_psi_t   *p_owner;
332
    int         i_owner_number;
333
334
335
336
337

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

338
339
340
341
    /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
    ts_es_t     **extra_es;
    int         i_extra_es;

342
343
344
345
} ts_pid_t;

struct demux_sys_t
{
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
346
347
    vlc_mutex_t     csa_lock;

348
349
350
    /* TS packet size (188, 192, 204) */
    int         i_packet_size;

351
352
353
    /* how many TS packet we read at once */
    int         i_ts_read;

354
355
356
357
    /* All pid */
    ts_pid_t    pid[8192];

    /* All PMT */
358
    bool        b_user_pmt;
359
360
    int         i_pmt;
    ts_pid_t    **pmt;
361
362

    /* */
363
    bool        b_es_id_pid;
364
    csa_t       *csa;
365
    int         i_csa_pkt_size;
366
    bool        b_silent;
367
    bool        b_split_es;
368

369
    bool        b_udp_out;
370
371
    int         fd; /* udp socket */
    uint8_t     *buffer;
372

Laurent Aimar's avatar
Laurent Aimar committed
373
374
375
376
377
    /* */
    bool        b_access_control;

    /* */
    bool        b_dvb_meta;
378
    int64_t     i_tdt_delta;
379
380
    int64_t     i_dvb_start;
    int64_t     i_dvb_length;
Laurent Aimar's avatar
Laurent Aimar committed
381
382
383

    /* */
    int         i_current_program;
384
    vlc_list_t  *p_programs_list;
385

386
387
388
389
    /* TS dump */
    char        *psz_file;  /* file to dump data in */
    FILE        *p_file;    /* filehandle */
    uint64_t    i_write;    /* bytes written */
390
    bool        b_file_out; /* dump mode enabled */
391

392
393
    /* */
    bool        b_start_record;
394
395
};

396
397
static int i_broken_epg;

398
399
static int Demux    ( demux_t *p_demux );
static int DemuxFile( demux_t *p_demux );
400
401
static int Control( demux_t *p_demux, int i_query, va_list args );

402
static void PIDInit ( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner );
403
404
405
static void PIDClean( es_out_t *out, ts_pid_t *pid );
static int  PIDFillFormat( ts_pid_t *pid, int i_stream_type );

406
407
static void PATCallBack( demux_t *, dvbpsi_pat_t * );
static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt );
408
#ifdef TS_USE_DVB_SI
409
410
static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
                                 uint8_t  i_table_id, uint16_t i_extension );
411
#endif
Laurent Aimar's avatar
Laurent Aimar committed
412
static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
413

414
415
416
417
418
static inline int PIDGet( block_t *p )
{
    return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
}

419
static bool GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
420

421
422
static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );

423
static iod_descriptor_t *IODNew( int , uint8_t * );
424
static void              IODFree( iod_descriptor_t * );
425

426
#define TS_USER_PMT_NUMBER (0)
427
428
static int UserPmt( demux_t *p_demux, const char * );

429
430
431
432
#define TS_PACKET_SIZE_188 188
#define TS_PACKET_SIZE_192 192
#define TS_PACKET_SIZE_204 204
#define TS_PACKET_SIZE_MAX 204
433
#define TS_TOPFIELD_HEADER 1320
434
435
436
437
438
439
440
441
442

/*****************************************************************************
 * Open
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
    demux_t     *p_demux = (demux_t*)p_this;
    demux_sys_t *p_sys;

443
    const uint8_t *p_peek;
444
445
    int          i_sync, i_peek, i;
    int          i_packet_size;
446

447
    ts_pid_t    *pat;
zorglub's avatar
zorglub committed
448
    const char  *psz_mode;
449
450
    bool         b_append;
    bool         b_topfield = false;
451

452
    if( stream_Peek( p_demux->s, &p_peek, TS_PACKET_SIZE_MAX ) <
453
        TS_PACKET_SIZE_MAX ) return VLC_EGENERIC;
454

455
    if( memcmp( p_peek, "TFrc", 4 ) == 0 )
456
    {
457
        b_topfield = true;
458
459
460
        msg_Dbg( p_demux, "this is a topfield file" );
    }

461
462
    /* Search first sync byte */
    for( i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
463
464
465
    {
        if( p_peek[i_sync] == 0x47 ) break;
    }
466
    if( i_sync >= TS_PACKET_SIZE_MAX && !b_topfield )
467
    {
468
469
        if( !p_demux->b_force )
            return VLC_EGENERIC;
470
471
        msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
    }
472

473
474
475
476
477
478
479
480
481
482
    if( b_topfield )
    {
        /* Read the entire Topfield header */
        i_peek = TS_TOPFIELD_HEADER;
    }
    else
    {
        /* Check next 3 sync bytes */
        i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
    }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
483

484
    if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
485
    {
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        msg_Err( p_demux, "cannot peek" );
        return VLC_EGENERIC;
    }
    if( p_peek[i_sync + 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 )
    {
        i_packet_size = TS_PACKET_SIZE_188;
    }
    else if( p_peek[i_sync + 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 )
    {
        i_packet_size = TS_PACKET_SIZE_192;
    }
    else if( p_peek[i_sync + 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 )
    {
        i_packet_size = TS_PACKET_SIZE_204;
    }
507
    else if( p_demux->b_force )
508
509
510
    {
        i_packet_size = TS_PACKET_SIZE_188;
    }
511
512
513
514
    else if( b_topfield )
    {
        i_packet_size = TS_PACKET_SIZE_188;
#if 0
515
        /* I used the TF5000PVR 2004 Firmware .doc header documentation,
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
         * 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;
        char *psz_name = malloc(25);
        char *psz_event_name;
        char *psz_event_text = malloc(130);
        char *psz_ext_text = malloc(1025);

        // 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)
546
        // 4 bytes reserved
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
        // 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);
        psz_event_name = malloc( i_name+1 );
        // 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
    }
578
579
580
581
    else
    {
        msg_Warn( p_demux, "TS module discarded (lost sync)" );
        return VLC_EGENERIC;
582
    }
583

584
    p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
585
586
    if( !p_sys )
        return VLC_ENOMEM;
587
    memset( p_sys, 0, sizeof( demux_sys_t ) );
588
    p_sys->i_packet_size = i_packet_size;
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
589
    vlc_mutex_init( &p_sys->csa_lock );
590
591
592

    /* Fill dump mode fields */
    p_sys->i_write = 0;
hartman's avatar
hartman committed
593
    p_sys->buffer = NULL;
594
    p_sys->p_file = NULL;
595
    p_sys->b_file_out = false;
596
597
598
    p_sys->psz_file = var_CreateGetString( p_demux, "ts-dump-file" );
    if( *p_sys->psz_file != '\0' )
    {
599
        p_sys->b_file_out = true;
600

601
        b_append = var_CreateGetBool( p_demux, "ts-dump-append" );
602
603
604
605
606
607
608
609
610
611
        if ( b_append )
            psz_mode = "ab";
        else
            psz_mode = "wb";

        if( !strcmp( p_sys->psz_file, "-" ) )
        {
            msg_Info( p_demux, "dumping raw stream to standard output" );
            p_sys->p_file = stdout;
        }
612
        else if( ( p_sys->p_file = utf8_fopen( p_sys->psz_file, psz_mode ) ) == NULL )
613
614
        {
            msg_Err( p_demux, "cannot create `%s' for writing", p_sys->psz_file );
615
            p_sys->b_file_out = false;
616
617
618
619
620
        }

        if( p_sys->b_file_out )
        {
            /* Determine how many packets to read. */
621
622
            int bufsize = var_CreateGetInteger( p_demux, "ts-dump-size" );
            p_sys->i_ts_read = (int) (bufsize / p_sys->i_packet_size);
623
624
625
626
            if( p_sys->i_ts_read <= 0 )
            {
                p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
            }
627
            p_sys->buffer = xmalloc( p_sys->i_packet_size * p_sys->i_ts_read );
628
629
630
631
632
633
            msg_Info( p_demux, "%s raw stream to file `%s' reading packets %d",
                      b_append ? "appending" : "dumping", p_sys->psz_file,
                      p_sys->i_ts_read );
        }
    }

634
    /* Fill p_demux field */
635
636
637
638
    if( p_sys->b_file_out )
        p_demux->pf_demux = DemuxFile;
    else
        p_demux->pf_demux = Demux;
639
640
641
    p_demux->pf_control = Control;

    /* Init p_sys field */
Laurent Aimar's avatar
Laurent Aimar committed
642
643
644
    p_sys->b_dvb_meta = true;
    p_sys->b_access_control = true;
    p_sys->i_current_program = 0;
645
    p_sys->i_tdt_delta = 0;
646
    p_sys->i_dvb_start = 0;
647
648
    p_sys->i_dvb_length = 0;

649
650
651
652
653
    for( i = 0; i < 8192; i++ )
    {
        ts_pid_t *pid = &p_sys->pid[i];

        pid->i_pid      = i;
654
655
        pid->b_seen     = false;
        pid->b_valid    = false;
656
    }
657
    /* PID 8191 is padding */
658
    p_sys->pid[8191].b_seen = true;
659
    p_sys->i_packet_size = i_packet_size;
660
    p_sys->b_udp_out = false;
hartman's avatar
hartman committed
661
    p_sys->fd = -1;
662
    p_sys->i_ts_read = 50;
663
    p_sys->csa = NULL;
664
    p_sys->b_start_record = false;
665
666
667

    /* Init PAT handler */
    pat = &p_sys->pid[0];
668
    PIDInit( pat, true, NULL );
669
670
    pat->psi->handle = dvbpsi_AttachPAT( (dvbpsi_pat_callback)PATCallBack,
                                         p_demux );
671
#ifdef TS_USE_DVB_SI
Laurent Aimar's avatar
Laurent Aimar committed
672
    if( p_sys->b_dvb_meta )
673
674
675
676
    {
        ts_pid_t *sdt = &p_sys->pid[0x11];
        ts_pid_t *eit = &p_sys->pid[0x12];

677
        PIDInit( sdt, true, NULL );
678
679
680
        sdt->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
681
        PIDInit( eit, true, NULL );
682
683
684
        eit->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
685
#ifdef TS_USE_TDT
686
        ts_pid_t *tdt = &p_sys->pid[0x14];
687
688
689
690
691
        PIDInit( tdt, true, NULL );
        tdt->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
#endif
Laurent Aimar's avatar
Laurent Aimar committed
692
        if( p_sys->b_access_control )
693
        {
694
            if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
695
                                ACCESS_SET_PRIVATE_ID_STATE, 0x11, true ) ||
696
697
698
699
#ifdef TS_USE_TDT
                stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
                                ACCESS_SET_PRIVATE_ID_STATE, 0x14, true ) ||
#endif
700
                stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
701
                                ACCESS_SET_PRIVATE_ID_STATE, 0x12, true ) )
Laurent Aimar's avatar
Laurent Aimar committed
702
                p_sys->b_access_control = false;
703
704
705
        }
    }
#endif
706
707

    /* Init PMT array */
hartman's avatar
hartman committed
708
    TAB_INIT( p_sys->i_pmt, p_sys->pmt );
709

710
    /* Read config */
711
    p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
712

713
714
    char* psz_string = var_CreateGetString( p_demux, "ts-out" );
    if( psz_string && *psz_string && !p_sys->b_file_out )
715
    {
716
        char *psz = strchr( psz_string, ':' );
717
718
        int   i_port = 0;

719
        p_sys->b_udp_out = true;
720
721
722
723
724
725
726

        if( psz )
        {
            *psz++ = '\0';
            i_port = atoi( psz );
        }
        if( i_port <= 0 ) i_port  = 1234;
727
        msg_Dbg( p_demux, "resend ts to '%s:%d'", psz_string, i_port );
728

729
        p_sys->fd = net_ConnectUDP( VLC_OBJECT(p_demux), psz_string, i_port, -1 );
730
731
732
        if( p_sys->fd < 0 )
        {
            msg_Err( p_demux, "failed to open udp socket, send disabled" );
733
            p_sys->b_udp_out = false;
734
735
736
        }
        else
        {
737
738
            int i_mtu = var_CreateGetInteger( p_demux, "ts-out-mtu" );
            p_sys->i_ts_read = i_mtu / p_sys->i_packet_size;
739
740
            if( p_sys->i_ts_read <= 0 )
            {
741
                p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
742
            }
743
            p_sys->buffer = malloc( p_sys->i_packet_size * p_sys->i_ts_read );
744
745
        }
    }
746
    free( psz_string );
747

748
    /* We handle description of an extra PMT */
749
    psz_string = var_CreateGetString( p_demux, "ts-extra-pmt" );
750
    p_sys->b_user_pmt = false;
751
752
753
    if( psz_string && *psz_string )
        UserPmt( p_demux, psz_string );
    free( psz_string );
754

755
756
    psz_string = var_CreateGetStringCommand( p_demux, "ts-csa-ck" );
    if( psz_string && *psz_string )
757
    {
758
        int i_res;
759
        char* psz_csa2;
760
761
762

        p_sys->csa = csa_New();

763
764
765
        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
766
        {
767
            if( csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_csa2, false ) != VLC_SUCCESS )
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
768
            {
769
                csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
770
771
772
773
            }
        }
        else if ( i_res == VLC_SUCCESS )
        {
774
            csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
775
776
        }
        else
777
        {
778
            csa_Delete( p_sys->csa );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
779
            p_sys->csa = NULL;
780
        }
781
782

        if( p_sys->csa )
783
        {
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
784
785
786
            var_AddCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, (void *)1 );
            var_AddCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );

787
788
            int i_pkt = var_CreateGetInteger( p_demux, "ts-csa-pkt" );
            if( i_pkt < 4 || i_pkt > 188 )
789
            {
790
                msg_Err( p_demux, "wrong packet size %d specified.", i_pkt );
791
792
                msg_Warn( p_demux, "using default packet size of 188 bytes" );
                p_sys->i_csa_pkt_size = 188;
793
            }
794
795
            else
                p_sys->i_csa_pkt_size = i_pkt;
796
            msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
797
        }
798
        free( psz_csa2 );
799
    }
800
    free( psz_string );
801

802
    p_sys->b_silent = var_CreateGetBool( p_demux, "ts-silent" );
803
    p_sys->b_split_es = var_InheritBool( p_demux, "ts-split-es" );
804

805
806
807
808
809
810
811
812
813
814
815
816
    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:" );
817
    for( int i = 0; i < 8192; i++ )
818
819
820
821
822
823
824
    {
        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
825
826
827
828
829
830
831
832
            case 0: /* PAT */
                dvbpsi_DetachPAT( pid->psi->handle );
                free( pid->psi );
                break;
            case 1: /* CAT */
                free( pid->psi );
                break;
            default:
833
                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
834
                {
835
                    /* SDT or EIT or TDT */
Laurent Aimar's avatar
Laurent Aimar committed
836
                    dvbpsi_DetachDemux( pid->psi->handle );
837
                    free( pid->psi );
Laurent Aimar's avatar
Laurent Aimar committed
838
839
840
841
842
843
                }
                else
                {
                    PIDClean( p_demux->out, pid );
                }
                break;
844
845
846
847
            }
        }
        else if( pid->b_valid && pid->es )
        {
848
            PIDClean( p_demux->out, pid );
849
        }
850

851
852
        if( pid->b_seen )
        {
853
            msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
854
        }
855

Laurent Aimar's avatar
Laurent Aimar committed
856
        if( p_sys->b_access_control && pid->i_pid > 0 )
857
858
        {
            /* too much */
Jean-Paul Saman's avatar
Jean-Paul Saman committed
859
860
            stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
                            ACCESS_SET_PRIVATE_ID_STATE, pid->i_pid,
861
                            false );
862
        }
863
864
    }

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
865
    vlc_mutex_lock( &p_sys->csa_lock );
866
867
    if( p_sys->csa )
    {
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
868
869
        var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
        var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
870
871
        csa_Delete( p_sys->csa );
    }
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
872
    vlc_mutex_unlock( &p_sys->csa_lock );
873

hartman's avatar
hartman committed
874
    TAB_CLEAN( p_sys->i_pmt, p_sys->pmt );
875

Laurent Aimar's avatar
Laurent Aimar committed
876
    if( p_sys->p_programs_list )
877
878
879
    {
        vlc_value_t val;
        val.p_list = p_sys->p_programs_list;
880
        var_FreeList( &val, NULL );
881
882
    }

883
884
885
    /* If in dump mode, then close the file */
    if( p_sys->b_file_out )
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
886
        msg_Info( p_demux ,"closing %s (%"PRId64" Kbytes dumped)",
Jean-Paul Saman's avatar
Jean-Paul Saman committed
887
                  p_sys->psz_file, p_sys->i_write / 1024 );
888
889
890
891
892
893

        if( p_sys->p_file != stdout )
        {
            fclose( p_sys->p_file );
        }
    }
hartman's avatar
hartman committed
894
895
896
897
898
    /* When streaming, close the port */
    if( p_sys->fd > -1 )
    {
        net_Close( p_sys->fd );
    }
899

hartman's avatar
hartman committed
900
    free( p_sys->buffer );
901
902
    free( p_sys->psz_file );

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
903
    vlc_mutex_destroy( &p_sys->csa_lock );
904
905
906
    free( p_sys );
}

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
/*****************************************************************************
 * 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;
}

929
930
931
932
/*****************************************************************************
 * DemuxFile:
 *****************************************************************************/
static int DemuxFile( demux_t *p_demux )
933
{
934
    demux_sys_t *p_sys = p_demux->p_sys;
Laurent Aimar's avatar
Laurent Aimar committed
935
936
937
    const int i_bufsize = p_sys->i_packet_size * p_sys->i_ts_read;
    uint8_t   *p_buffer = p_sys->buffer; /* Put first on sync byte */
    const int i_data = stream_Read( p_demux->s, p_sys->buffer, i_bufsize );
938

Laurent Aimar's avatar
Laurent Aimar committed
939
    if( i_data <= 0 && i_data < p_sys->i_packet_size )
940
    {
941
        msg_Dbg( p_demux, "error reading malformed packets" );
942
943
944
945
        return i_data;
    }

    /* Test continuity counter */
Laurent Aimar's avatar
Laurent Aimar committed
946
    for( int i_pos = 0; i_pos < i_data;  )
947
948
949
950
    {
        if( p_sys->buffer[i_pos] != 0x47 )
        {
            msg_Warn( p_demux, "lost sync" );
951
            while( vlc_object_alive (p_demux) && (i_pos < i_data) )
952
953
954
955
956
            {
                i_pos++;
                if( p_sys->buffer[i_pos] == 0x47 )
                    break;
            }
957
            if( vlc_object_alive (p_demux) )
958
959
                msg_Warn( p_demux, "sync found" );
        }
960

961
962
963
964
965
966
        /* continuous when (one of this):
         * diff == 1
         * diff == 0 and payload == 0
         * diff == 0 and duplicate packet (playload != 0) <- should we
         *   test the content ?
         */
Laurent Aimar's avatar
Laurent Aimar committed
967
968
969
        const int i_cc  = p_buffer[i_pos+3]&0x0f;
        const bool b_payload = p_buffer[i_pos+3]&0x10;
        const bool b_adaptation = p_buffer[i_pos+3]&0x20;
970

971
        /* Get the PID */
Laurent Aimar's avatar
Laurent Aimar committed
972
        ts_pid_t *p_pid = &p_sys->pid[ ((p_buffer[i_pos+1]&0x1f)<<8)|p_buffer[i_pos+2] ];
973

974
        /* Detect discontinuity indicator in adaptation field */
975
        if( b_adaptation && p_buffer[i_pos + 4] > 0 )
976
977
978
979
980
981
        {
            if( p_buffer[i_pos+5]&0x80 )
                msg_Warn( p_demux, "discontinuity indicator (pid=%d) ", p_pid->i_pid );
            if( p_buffer[i_pos+5]&0x40 )
                msg_Warn( p_demux, "random access indicator (pid=%d) ", p_pid->i_pid );
        }
982

Laurent Aimar's avatar
Laurent Aimar committed
983
        const int i_diff = ( i_cc - p_pid->i_cc )&0x0f;
984
985
        if( b_payload && i_diff == 1 )
        {
986
            p_pid->i_cc = ( p_pid->i_cc + 1 ) & 0xf;
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        }
        else
        {
            if( p_pid->i_cc == 0xff )
            {
                msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
                        p_pid->i_pid, i_cc );
                p_pid->i_cc = i_cc;
            }
            else if( i_diff != 0 )
            {
                /* FIXME what to do when discontinuity_indicator is set ? */
                msg_Warn( p_demux, "transport error detected 0x%x instead of 0x%x",
                          i_cc, ( p_pid->i_cc + 1 )&0x0f );
1001

1002
1003
1004
1005
1006
                p_pid->i_cc = i_cc;
                /* Mark transport error in the TS packet. */
                p_buffer[i_pos+1] |= 0x80;
            }
        }
1007

1008
1009
        /* Test if user wants to decrypt it first */
        if( p_sys->csa )
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
1010
1011
        {
            vlc_mutex_lock( &p_sys->csa_lock );
1012
            csa_Decrypt( p_demux->p_sys->csa, &p_buffer[i_pos], p_demux->p_sys->i_csa_pkt_size );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
1013
1014
            vlc_mutex_unlock( &p_sys->csa_lock );
        }
1015

1016
1017
1018
1019
        i_pos += p_sys->i_packet_size;
    }

    /* Then write */
Laurent Aimar's avatar
Laurent Aimar committed
1020
1021
    const int i_write = fwrite( p_sys->buffer, 1, i_data, p_sys->p_file );
    if( i_write < 0 )
1022
1023
1024
1025
1026
    {
        msg_Err( p_demux, "failed to write data" );
        return -1;
    }

Laurent Aimar's avatar
Laurent Aimar committed
1027
    p_sys->i_write += i_write;
1028
1029
1030
    return 1;
}

1031
1032
1033
1034
1035
1036
1037
1038
/*****************************************************************************
 * Demux:
 *****************************************************************************/
static int Demux( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;

    /* We read at most 100 TS packet or until a frame is completed */
Laurent Aimar's avatar
Laurent Aimar committed
1039
    for( int i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
1040
    {
1041
        bool         b_frame = false;
1042
1043
1044
        block_t     *p_pkt;

        /* Get a new TS packet */
1045
        if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
1046
1047
1048
1049
        {
            msg_Dbg( p_demux, "eof ?" );
            return 0;
        }
1050
1051

        /* Check sync byte and re-sync if needed */
1052
1053
1054
1055
1056
        if( p_pkt->p_buffer[0] != 0x47 )
        {
            msg_Warn( p_demux, "lost synchro" );
            block_Release( p_pkt );

1057
            while( vlc_object_alive (p_demux) )
1058
            {
1059
                const uint8_t *p_peek;
1060
                int i_peek, i_skip = 0;
1061

1062
1063
1064
                i_peek = stream_Peek( p_demux->s, &p_peek,
                                      p_sys->i_packet_size * 10 );
                if( i_peek < p_sys->i_packet_size + 1 )
1065
1066
1067
1068
1069
                {
                    msg_Dbg( p_demux, "eof ?" );
                    return 0;
                }

gbazin's avatar