ts.c 134 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

Laurent Aimar's avatar
Laurent Aimar committed
36
#include <ctype.h>
37
#include <assert.h>
38

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

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

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

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

71
72
73
74
75
76
77
78
79
/* 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
80
#include <time.h>
81
82
#undef TS_DEBUG

83
84
85
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
gbazin's avatar
   
gbazin committed
86
87
static int  Open  ( vlc_object_t * );
static void Close ( vlc_object_t * );
88

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

#define PID_TEXT N_("Set id of ES to PID")
103
104
105
106
#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>\"}\'.")
107
108
109

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

#define MTUOUT_TEXT N_("MTU for out mode")
113
#define MTUOUT_LONGTEXT N_("MTU for out mode.")
114
115

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

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
118
119
120
121
#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).")

122
#define SILENT_TEXT N_("Silent mode")
123
#define SILENT_LONGTEXT N_("Do not complain on encrypted PES.")
124

125
#define CAPMT_SYSID_TEXT N_("CAPMT System ID")
126
#define CAPMT_SYSID_LONGTEXT N_("Only forward descriptors from this SysID to the CAM.")
127

128
129
130
131
132
133
#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")
134
#define TSDUMP_LONGTEXT N_("Specify a filename where to dump the TS in.")
135
136
137
138
139
140
141
142
143
144
145

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

146
147
148
149
150
151
152
153
154
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 )
    add_bool( "ts-es-id-pid", 1, NULL, PID_TEXT, PID_LONGTEXT, true )
    add_string( "ts-out", NULL, NULL, TSOUT_TEXT, TSOUT_LONGTEXT, true )
155
    add_integer( "ts-out-mtu", 1400, NULL, MTUOUT_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
156
                 MTUOUT_LONGTEXT, true )
157
158
159
160
    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 )
    add_bool( "ts-silent", 0, NULL, SILENT_TEXT, SILENT_LONGTEXT, true )
161

162
163
    add_file( "ts-dump-file", NULL, NULL, TSDUMP_TEXT, TSDUMP_LONGTEXT, false )
    add_bool( "ts-dump-append", 0, NULL, APPEND_TEXT, APPEND_LONGTEXT, false )
164
    add_integer( "ts-dump-size", 16384, NULL, DUMPSIZE_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
165
                 DUMPSIZE_LONGTEXT, true )
166

167
168
169
170
    set_capability( "demux", 10 )
    set_callbacks( Open, Close )
    add_shortcut( "ts" )
vlc_module_end ()
171
172
173
174

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
175
176
177
178
static const char *const ppsz_teletext_type[] = {
 "",
 N_("Teletext"),
 N_("Teletext subtitles"),
179
180
181
 N_("Teletext: additional information"),
 N_("Teletext: program schedule"),
 N_("Teletext subtitles: hearing impaired")
182
};
183
184
185
186
187

typedef struct
{
    uint8_t                 i_objectTypeIndication;
    uint8_t                 i_streamType;
188
    bool                    b_upStream;
189
190
191
192
193
194
195
196
197
198
199
    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
{
200
201
202
203
204
205
206
207
    bool                    b_useAccessUnitStartFlag;
    bool                    b_useAccessUnitEndFlag;
    bool                    b_useRandomAccessPointFlag;
    bool                    b_useRandomAccessUnitsOnlyFlag;
    bool                    b_usePaddingFlag;
    bool                    b_useTimeStampsFlags;
    bool                    b_useIdleFlag;
    bool                    b_durationFlag;
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
    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
{
229
    bool                    b_ok;
230
231
    uint16_t                i_es_id;

232
233
    bool                    b_streamDependenceFlag;
    bool                    b_OCRStreamFlag;
234
235
236
237
238
239
240
241
242
    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;
243

244
245
246
247
} es_mpeg4_descriptor_t;

typedef struct
{
248
    uint8_t                 i_iod_label, i_iod_label_scope;
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265

    /* 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
{
266
267
    dvbpsi_handle   handle;

268
269
270
    int             i_version;
    int             i_number;
    int             i_pid_pcr;
271
    int             i_pid_pmt;
272
273
    /* IOD stuff (mpeg4) */
    iod_descriptor_t *iod;
274

275
276
} ts_prg_psi_t;

277
278
279
280
typedef struct
{
    /* for special PAT/SDT case */
    dvbpsi_handle   handle; /* PAT/SDT/EIT */
281
    int             i_pat_version;
282
    int             i_sdt_version;
283
284
285
286

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

288
289
290
291
292
293
} ts_psi_t;

typedef struct
{
    es_format_t  fmt;
    es_out_id_t *id;
294
295
    int         i_pes_size;
    int         i_pes_gathered;
296
    block_t     *p_pes;
297
    block_t     **pp_last;
298
299

    es_mpeg4_descriptor_t *p_mpeg4desc;
300
    int         b_gather;
301

302
303
304
305
306
307
} ts_es_t;

typedef struct
{
    int         i_pid;

308
309
    bool        b_seen;
    bool        b_valid;
310
    int         i_cc;   /* countinuity counter */
311
    bool        b_scrambled;
312
313
314

    /* PSI owner (ie PMT -> PAT, ES -> PMT */
    ts_psi_t   *p_owner;
315
    int         i_owner_number;
316
317
318
319
320

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

321
322
323
324
    /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
    ts_es_t     **extra_es;
    int         i_extra_es;

325
326
327
328
} ts_pid_t;

struct demux_sys_t
{
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
329
330
    vlc_mutex_t     csa_lock;

331
332
333
    /* TS packet size (188, 192, 204) */
    int         i_packet_size;

334
335
336
    /* how many TS packet we read at once */
    int         i_ts_read;

337
338
339
340
    /* All pid */
    ts_pid_t    pid[8192];

    /* All PMT */
341
    bool        b_user_pmt;
342
343
    int         i_pmt;
    ts_pid_t    **pmt;
344
345

    /* */
346
    bool        b_es_id_pid;
347
    csa_t       *csa;
348
    int         i_csa_pkt_size;
349
    bool        b_silent;
350

351
    bool        b_udp_out;
352
353
    int         fd; /* udp socket */
    uint8_t     *buffer;
354

Laurent Aimar's avatar
Laurent Aimar committed
355
356
357
358
359
    /* */
    bool        b_access_control;

    /* */
    bool        b_dvb_meta;
360
361
    int64_t     i_dvb_start;
    int64_t     i_dvb_length;
Laurent Aimar's avatar
Laurent Aimar committed
362
363
364

    /* */
    int         i_current_program;
365
    vlc_list_t  *p_programs_list;
366

367
368
369
370
    /* TS dump */
    char        *psz_file;  /* file to dump data in */
    FILE        *p_file;    /* filehandle */
    uint64_t    i_write;    /* bytes written */
371
    bool        b_file_out; /* dump mode enabled */
372

373
374
    /* */
    bool        b_start_record;
375
376
};

377
378
static int Demux    ( demux_t *p_demux );
static int DemuxFile( demux_t *p_demux );
379
380
static int Control( demux_t *p_demux, int i_query, va_list args );

381
static void PIDInit ( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner );
382
383
384
static void PIDClean( es_out_t *out, ts_pid_t *pid );
static int  PIDFillFormat( ts_pid_t *pid, int i_stream_type );

385
386
static void PATCallBack( demux_t *, dvbpsi_pat_t * );
static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt );
387
#ifdef TS_USE_DVB_SI
388
389
static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
                                 uint8_t  i_table_id, uint16_t i_extension );
390
#endif
Laurent Aimar's avatar
Laurent Aimar committed
391
static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
392

393
394
395
396
397
static inline int PIDGet( block_t *p )
{
    return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
}

398
static bool GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
399

400
401
static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );

402
static iod_descriptor_t *IODNew( int , uint8_t * );
403
static void              IODFree( iod_descriptor_t * );
404

405
#define TS_USER_PMT_NUMBER (0)
406
407
static int UserPmt( demux_t *p_demux, const char * );

408
409
410
411
#define TS_PACKET_SIZE_188 188
#define TS_PACKET_SIZE_192 192
#define TS_PACKET_SIZE_204 204
#define TS_PACKET_SIZE_MAX 204
412
#define TS_TOPFIELD_HEADER 1320
413
414
415
416
417
418
419
420
421

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

422
    const uint8_t *p_peek;
423
424
    int          i_sync, i_peek, i;
    int          i_packet_size;
425

426
    ts_pid_t    *pat;
zorglub's avatar
zorglub committed
427
    const char  *psz_mode;
428
429
    bool         b_append;
    bool         b_topfield = false;
430

431
    if( stream_Peek( p_demux->s, &p_peek, TS_PACKET_SIZE_MAX ) <
432
        TS_PACKET_SIZE_MAX ) return VLC_EGENERIC;
433

434
    if( memcmp( p_peek, "TFrc", 4 ) == 0 )
435
    {
436
        b_topfield = true;
437
438
439
        msg_Dbg( p_demux, "this is a topfield file" );
    }

440
441
    /* Search first sync byte */
    for( i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
442
443
444
    {
        if( p_peek[i_sync] == 0x47 ) break;
    }
445
    if( i_sync >= TS_PACKET_SIZE_MAX && !b_topfield )
446
    {
447
448
        if( !p_demux->b_force )
            return VLC_EGENERIC;
449
450
        msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
    }
451

452
453
454
455
456
457
458
459
460
461
    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
462

463
    if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
464
    {
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
        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;
    }
486
    else if( p_demux->b_force )
487
488
489
    {
        i_packet_size = TS_PACKET_SIZE_188;
    }
490
491
492
493
    else if( b_topfield )
    {
        i_packet_size = TS_PACKET_SIZE_188;
#if 0
494
        /* I used the TF5000PVR 2004 Firmware .doc header documentation,
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
         * 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)
525
        // 4 bytes reserved
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
        // 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
    }
557
558
559
560
    else
    {
        msg_Warn( p_demux, "TS module discarded (lost sync)" );
        return VLC_EGENERIC;
561
    }
562

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

    /* Fill dump mode fields */
    p_sys->i_write = 0;
hartman's avatar
hartman committed
572
    p_sys->buffer = NULL;
573
    p_sys->p_file = NULL;
574
    p_sys->b_file_out = false;
575
576
577
    p_sys->psz_file = var_CreateGetString( p_demux, "ts-dump-file" );
    if( *p_sys->psz_file != '\0' )
    {
578
        p_sys->b_file_out = true;
579

580
        b_append = var_CreateGetBool( p_demux, "ts-dump-append" );
581
582
583
584
585
586
587
588
589
590
        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;
        }
591
        else if( ( p_sys->p_file = utf8_fopen( p_sys->psz_file, psz_mode ) ) == NULL )
592
593
        {
            msg_Err( p_demux, "cannot create `%s' for writing", p_sys->psz_file );
594
            p_sys->b_file_out = false;
595
596
597
598
599
        }

        if( p_sys->b_file_out )
        {
            /* Determine how many packets to read. */
600
601
            int bufsize = var_CreateGetInteger( p_demux, "ts-dump-size" );
            p_sys->i_ts_read = (int) (bufsize / p_sys->i_packet_size);
602
603
604
605
606
607
608
609
610
611
612
            if( p_sys->i_ts_read <= 0 )
            {
                p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
            }
            p_sys->buffer = malloc( p_sys->i_packet_size * p_sys->i_ts_read );
            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 );
        }
    }

613
    /* Fill p_demux field */
614
615
616
617
    if( p_sys->b_file_out )
        p_demux->pf_demux = DemuxFile;
    else
        p_demux->pf_demux = Demux;
618
619
620
    p_demux->pf_control = Control;

    /* Init p_sys field */
Laurent Aimar's avatar
Laurent Aimar committed
621
622
623
    p_sys->b_dvb_meta = true;
    p_sys->b_access_control = true;
    p_sys->i_current_program = 0;
624
    p_sys->i_dvb_start = 0;
625
626
    p_sys->i_dvb_length = 0;

627
628
629
630
631
    for( i = 0; i < 8192; i++ )
    {
        ts_pid_t *pid = &p_sys->pid[i];

        pid->i_pid      = i;
632
633
        pid->b_seen     = false;
        pid->b_valid    = false;
634
    }
635
    /* PID 8191 is padding */
636
    p_sys->pid[8191].b_seen = true;
637
    p_sys->i_packet_size = i_packet_size;
638
    p_sys->b_udp_out = false;
hartman's avatar
hartman committed
639
    p_sys->fd = -1;
640
    p_sys->i_ts_read = 50;
641
    p_sys->csa = NULL;
642
    p_sys->b_start_record = false;
643
644
645

    /* Init PAT handler */
    pat = &p_sys->pid[0];
646
    PIDInit( pat, true, NULL );
647
648
    pat->psi->handle = dvbpsi_AttachPAT( (dvbpsi_pat_callback)PATCallBack,
                                         p_demux );
649
#ifdef TS_USE_DVB_SI
Laurent Aimar's avatar
Laurent Aimar committed
650
    if( p_sys->b_dvb_meta )
651
652
653
654
    {
        ts_pid_t *sdt = &p_sys->pid[0x11];
        ts_pid_t *eit = &p_sys->pid[0x12];

655
        PIDInit( sdt, true, NULL );
656
657
658
        sdt->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
659
        PIDInit( eit, true, NULL );
660
661
662
        eit->psi->handle =
            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
                                p_demux );
Laurent Aimar's avatar
Laurent Aimar committed
663
        if( p_sys->b_access_control )
664
        {
665
            if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
666
                                ACCESS_SET_PRIVATE_ID_STATE, 0x11, true ) ||
667
                stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
668
                                ACCESS_SET_PRIVATE_ID_STATE, 0x12, true ) )
Laurent Aimar's avatar
Laurent Aimar committed
669
                p_sys->b_access_control = false;
670
671
672
        }
    }
#endif
673
674

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

677
    /* Read config */
678
    p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
679

680
681
    char* psz_string = var_CreateGetString( p_demux, "ts-out" );
    if( psz_string && *psz_string && !p_sys->b_file_out )
682
    {
683
        char *psz = strchr( psz_string, ':' );
684
685
        int   i_port = 0;

686
        p_sys->b_udp_out = true;
687
688
689
690
691
692
693

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

696
        p_sys->fd = net_ConnectUDP( VLC_OBJECT(p_demux), psz_string, i_port, -1 );
697
698
699
        if( p_sys->fd < 0 )
        {
            msg_Err( p_demux, "failed to open udp socket, send disabled" );
700
            p_sys->b_udp_out = false;
701
702
703
        }
        else
        {
704
705
            int i_mtu = var_CreateGetInteger( p_demux, "ts-out-mtu" );
            p_sys->i_ts_read = i_mtu / p_sys->i_packet_size;
706
707
            if( p_sys->i_ts_read <= 0 )
            {
708
                p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
709
            }
710
            p_sys->buffer = malloc( p_sys->i_packet_size * p_sys->i_ts_read );
711
712
        }
    }
713
    free( psz_string );
714

715
    /* We handle description of an extra PMT */
716
    psz_string = var_CreateGetString( p_demux, "ts-extra-pmt" );
717
    p_sys->b_user_pmt = false;
718
719
720
    if( psz_string && *psz_string )
        UserPmt( p_demux, psz_string );
    free( psz_string );
721

722
723
    psz_string = var_CreateGetStringCommand( p_demux, "ts-csa-ck" );
    if( psz_string && *psz_string )
724
    {
725
        int i_res;
726
        char* psz_csa2;
727
728
729

        p_sys->csa = csa_New();

730
731
732
        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
733
        {
734
            if( csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_csa2, false ) != VLC_SUCCESS )
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
735
            {
736
                csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
737
738
739
740
            }
        }
        else if ( i_res == VLC_SUCCESS )
        {
741
            csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
742
743
        }
        else
744
        {
745
            csa_Delete( p_sys->csa );
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
746
            p_sys->csa = NULL;
747
        }
748
749

        if( p_sys->csa )
750
        {
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
751
752
753
            var_AddCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, (void *)1 );
            var_AddCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );

754
755
            int i_pkt = var_CreateGetInteger( p_demux, "ts-csa-pkt" );
            if( i_pkt < 4 || i_pkt > 188 )
756
            {
757
                msg_Err( p_demux, "wrong packet size %d specified.", i_pkt );
758
759
                msg_Warn( p_demux, "using default packet size of 188 bytes" );
                p_sys->i_csa_pkt_size = 188;
760
            }
761
762
            else
                p_sys->i_csa_pkt_size = i_pkt;
763
            msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
764
        }
765
        free( psz_csa2 );
766
    }
767
    free( psz_string );
768

769
    p_sys->b_silent = var_CreateGetBool( p_demux, "ts-silent" );
770

771
772
773
774
775
776
777
778
779
780
781
782
    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:" );
783
    for( int i = 0; i < 8192; i++ )
784
785
786
787
788
789
790
    {
        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
791
792
793
794
795
796
797
798
799
800
801
802
            case 0: /* PAT */
                dvbpsi_DetachPAT( pid->psi->handle );
                free( pid->psi );
                break;
            case 1: /* CAT */
                free( pid->psi );
                break;
            default:
                if( p_sys->b_dvb_meta && ( pid->i_pid == 0x11 || pid->i_pid == 0x12 ) )
                {
                    /* SDT or EIT */
                    dvbpsi_DetachDemux( pid->psi->handle );
803
                    free( pid->psi );
Laurent Aimar's avatar
Laurent Aimar committed
804
805
806
807
808
809
                }
                else
                {
                    PIDClean( p_demux->out, pid );
                }
                break;
810
811
812
813
            }
        }
        else if( pid->b_valid && pid->es )
        {
814
            PIDClean( p_demux->out, pid );
815
        }
816

817
818
        if( pid->b_seen )
        {
819
            msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
820
        }
821

Laurent Aimar's avatar
Laurent Aimar committed
822
        if( p_sys->b_access_control && pid->i_pid > 0 )
823
824
        {
            /* too much */
Jean-Paul Saman's avatar
Jean-Paul Saman committed
825
826
            stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
                            ACCESS_SET_PRIVATE_ID_STATE, pid->i_pid,
827
                            false );
828
        }
829
830
    }

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
831
    vlc_mutex_lock( &p_sys->csa_lock );
832
833
    if( p_sys->csa )
    {
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
834
835
        var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
        var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
836
837
        csa_Delete( p_sys->csa );
    }
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
838
    vlc_mutex_unlock( &p_sys->csa_lock );
839

hartman's avatar
hartman committed
840
    TAB_CLEAN( p_sys->i_pmt, p_sys->pmt );
841

Laurent Aimar's avatar
Laurent Aimar committed
842
    if( p_sys->p_programs_list )
843
844
845
    {
        vlc_value_t val;
        val.p_list = p_sys->p_programs_list;
846
        var_FreeList( &val, NULL );
847
848
    }

849
850
851
    /* 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
852
        msg_Info( p_demux ,"closing %s (%"PRId64" Kbytes dumped)",
Jean-Paul Saman's avatar
Jean-Paul Saman committed
853
                  p_sys->psz_file, p_sys->i_write / 1024 );
854
855
856
857
858
859

        if( p_sys->p_file != stdout )
        {
            fclose( p_sys->p_file );
        }
    }
hartman's avatar
hartman committed
860
861
862
863
864
    /* When streaming, close the port */
    if( p_sys->fd > -1 )
    {
        net_Close( p_sys->fd );
    }
865

hartman's avatar
hartman committed
866
    free( p_sys->buffer );
867
868
    free( p_sys->psz_file );

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

Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
/*****************************************************************************
 * 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;
}

895
896
897
898
/*****************************************************************************
 * DemuxFile:
 *****************************************************************************/
static int DemuxFile( demux_t *p_demux )
899
{
900
    demux_sys_t *p_sys = p_demux->p_sys;
Laurent Aimar's avatar
Laurent Aimar committed
901
902
903
    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 );
904

Laurent Aimar's avatar
Laurent Aimar committed
905
    if( i_data <= 0 && i_data < p_sys->i_packet_size )
906
    {
907
        msg_Dbg( p_demux, "error reading malformed packets" );
908
909
910
911
        return i_data;
    }

    /* Test continuity counter */
Laurent Aimar's avatar
Laurent Aimar committed
912
    for( int i_pos = 0; i_pos < i_data;  )
913
914
915
916
    {
        if( p_sys->buffer[i_pos] != 0x47 )
        {
            msg_Warn( p_demux, "lost sync" );
917
            while( vlc_object_alive (p_demux) && (i_pos < i_data) )
918
919
920
921
922
            {
                i_pos++;
                if( p_sys->buffer[i_pos] == 0x47 )
                    break;
            }
923
            if( vlc_object_alive (p_demux) )
924
925
                msg_Warn( p_demux, "sync found" );
        }
926

927
928
929
930
931
932
        /* 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
933
934
935
        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;
936

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

940
        /* Detect discontinuity indicator in adaptation field */
941
        if( b_adaptation && p_buffer[i_pos + 4] > 0 )
942
943
944
945
946
947
        {
            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 );
        }
948

Laurent Aimar's avatar
Laurent Aimar committed
949
        const int i_diff = ( i_cc - p_pid->i_cc )&0x0f;
950
951
        if( b_payload && i_diff == 1 )
        {
952
            p_pid->i_cc = ( p_pid->i_cc + 1 ) & 0xf;
953
954
955
956
957
958
959
960
961
962
963
964
965
966
        }
        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 );
967

968
969
970
971
972
                p_pid->i_cc = i_cc;
                /* Mark transport error in the TS packet. */
                p_buffer[i_pos+1] |= 0x80;
            }
        }
973

974
975
        /* Test if user wants to decrypt it first */
        if( p_sys->csa )
Kaloyan Kovachev's avatar
Kaloyan Kovachev committed
976
977
        {
            vlc_mutex_lock( &p_sys->csa_lock );
978
            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
979
980
            vlc_mutex_unlock( &p_sys->csa_lock );
        }
981

982
983
984
985
        i_pos += p_sys->i_packet_size;
    }

    /* Then write */
Laurent Aimar's avatar
Laurent Aimar committed
986
987
    const int i_write = fwrite( p_sys->buffer, 1, i_data, p_sys->p_file );
    if( i_write < 0 )
988
989
990
991
992
    {
        msg_Err( p_demux, "failed to write data" );
        return -1;
    }

Laurent Aimar's avatar
Laurent Aimar committed
993
    p_sys->i_write += i_write;
994
995
996
    return 1;
}

997
998
999
1000
/*****************************************************************************
 * Demux:
 *****************************************************************************/
static int Demux( demux_t *p_demux )