Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ 5dd3707b

History | View | Annotate | Download (49.7 KB)

1
/*
2
 * MPEG2 transport stream (aka DVB) demuxer
3
 * Copyright (c) 2002-2003 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
//#define DEBUG
23
//#define DEBUG_SEEK
24

    
25
#include "libavutil/crc.h"
26
#include "libavutil/intreadwrite.h"
27
#include "libavcodec/bytestream.h"
28
#include "avformat.h"
29
#include "mpegts.h"
30
#include "internal.h"
31
#include "seek.h"
32

    
33
/* 1.0 second at 24Mbit/s */
34
#define MAX_SCAN_PACKETS 32000
35

    
36
/* maximum size in which we look for synchronisation if
37
   synchronisation is lost */
38
#define MAX_RESYNC_SIZE 4096
39

    
40
#define MAX_PES_PAYLOAD 200*1024
41

    
42
typedef struct PESContext PESContext;
43

    
44
static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
45

    
46
enum MpegTSFilterType {
47
    MPEGTS_PES,
48
    MPEGTS_SECTION,
49
};
50

    
51
typedef struct MpegTSFilter MpegTSFilter;
52

    
53
typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
54

    
55
typedef struct MpegTSPESFilter {
56
    PESCallback *pes_cb;
57
    void *opaque;
58
} MpegTSPESFilter;
59

    
60
typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
61

    
62
typedef void SetServiceCallback(void *opaque, int ret);
63

    
64
typedef struct MpegTSSectionFilter {
65
    int section_index;
66
    int section_h_size;
67
    uint8_t *section_buf;
68
    unsigned int check_crc:1;
69
    unsigned int end_of_section_reached:1;
70
    SectionCallback *section_cb;
71
    void *opaque;
72
} MpegTSSectionFilter;
73

    
74
struct MpegTSFilter {
75
    int pid;
76
    int last_cc; /* last cc code (-1 if first packet) */
77
    enum MpegTSFilterType type;
78
    union {
79
        MpegTSPESFilter pes_filter;
80
        MpegTSSectionFilter section_filter;
81
    } u;
82
};
83

    
84
#define MAX_PIDS_PER_PROGRAM 64
85
struct Program {
86
    unsigned int id; //program id/service id
87
    unsigned int nb_pids;
88
    unsigned int pids[MAX_PIDS_PER_PROGRAM];
89
};
90

    
91
struct MpegTSContext {
92
    /* user data */
93
    AVFormatContext *stream;
94
    /** raw packet size, including FEC if present            */
95
    int raw_packet_size;
96

    
97
    int pos47;
98

    
99
    /** if true, all pids are analyzed to find streams       */
100
    int auto_guess;
101

    
102
    /** compute exact PCR for each transport stream packet   */
103
    int mpeg2ts_compute_pcr;
104

    
105
    int64_t cur_pcr;    /**< used to estimate the exact PCR  */
106
    int pcr_incr;       /**< used to estimate the exact PCR  */
107

    
108
    /* data needed to handle file based ts */
109
    /** stop parsing loop                                    */
110
    int stop_parse;
111
    /** packet containing Audio/Video data                   */
112
    AVPacket *pkt;
113
    /** to detect seek                                       */
114
    int64_t last_pos;
115

    
116
    /******************************************/
117
    /* private mpegts data */
118
    /* scan context */
119
    /** structure to keep track of Program->pids mapping     */
120
    unsigned int nb_prg;
121
    struct Program *prg;
122

    
123

    
124
    /** filters for various streams specified by PMT + for the PAT and PMT */
125
    MpegTSFilter *pids[NB_PID_MAX];
126
};
127

    
128
/* TS stream handling */
129

    
130
enum MpegTSState {
131
    MPEGTS_HEADER = 0,
132
    MPEGTS_PESHEADER,
133
    MPEGTS_PESHEADER_FILL,
134
    MPEGTS_PAYLOAD,
135
    MPEGTS_SKIP,
136
};
137

    
138
/* enough for PES header + length */
139
#define PES_START_SIZE  6
140
#define PES_HEADER_SIZE 9
141
#define MAX_PES_HEADER_SIZE (9 + 255)
142

    
143
struct PESContext {
144
    int pid;
145
    int pcr_pid; /**< if -1 then all packets containing PCR are considered */
146
    int stream_type;
147
    MpegTSContext *ts;
148
    AVFormatContext *stream;
149
    AVStream *st;
150
    enum MpegTSState state;
151
    /* used to get the format */
152
    int data_index;
153
    int total_size;
154
    int pes_header_size;
155
    int64_t pts, dts;
156
    int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
157
    uint8_t header[MAX_PES_HEADER_SIZE];
158
    uint8_t *buffer;
159
};
160

    
161
extern AVInputFormat mpegts_demuxer;
162

    
163
static void clear_program(MpegTSContext *ts, unsigned int programid)
164
{
165
    int i;
166

    
167
    for(i=0; i<ts->nb_prg; i++)
168
        if(ts->prg[i].id == programid)
169
            ts->prg[i].nb_pids = 0;
170
}
171

    
172
static void clear_programs(MpegTSContext *ts)
173
{
174
    av_freep(&ts->prg);
175
    ts->nb_prg=0;
176
}
177

    
178
static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
179
{
180
    struct Program *p;
181
    void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
182
    if(!tmp)
183
        return;
184
    ts->prg = tmp;
185
    p = &ts->prg[ts->nb_prg];
186
    p->id = programid;
187
    p->nb_pids = 0;
188
    ts->nb_prg++;
189
}
190

    
191
static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
192
{
193
    int i;
194
    struct Program *p = NULL;
195
    for(i=0; i<ts->nb_prg; i++) {
196
        if(ts->prg[i].id == programid) {
197
            p = &ts->prg[i];
198
            break;
199
        }
200
    }
201
    if(!p)
202
        return;
203

    
204
    if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
205
        return;
206
    p->pids[p->nb_pids++] = pid;
207
}
208

    
209
/**
210
 * \brief discard_pid() decides if the pid is to be discarded according
211
 *                      to caller's programs selection
212
 * \param ts    : - TS context
213
 * \param pid   : - pid
214
 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
215
 *         0 otherwise
216
 */
217
static int discard_pid(MpegTSContext *ts, unsigned int pid)
218
{
219
    int i, j, k;
220
    int used = 0, discarded = 0;
221
    struct Program *p;
222
    for(i=0; i<ts->nb_prg; i++) {
223
        p = &ts->prg[i];
224
        for(j=0; j<p->nb_pids; j++) {
225
            if(p->pids[j] != pid)
226
                continue;
227
            //is program with id p->id set to be discarded?
228
            for(k=0; k<ts->stream->nb_programs; k++) {
229
                if(ts->stream->programs[k]->id == p->id) {
230
                    if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
231
                        discarded++;
232
                    else
233
                        used++;
234
                }
235
            }
236
        }
237
    }
238

    
239
    return !used && discarded;
240
}
241

    
242
/**
243
 *  Assembles PES packets out of TS packets, and then calls the "section_cb"
244
 *  function when they are complete.
245
 */
246
static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
247
                               const uint8_t *buf, int buf_size, int is_start)
248
{
249
    MpegTSSectionFilter *tss = &tss1->u.section_filter;
250
    int len;
251

    
252
    if (is_start) {
253
        memcpy(tss->section_buf, buf, buf_size);
254
        tss->section_index = buf_size;
255
        tss->section_h_size = -1;
256
        tss->end_of_section_reached = 0;
257
    } else {
258
        if (tss->end_of_section_reached)
259
            return;
260
        len = 4096 - tss->section_index;
261
        if (buf_size < len)
262
            len = buf_size;
263
        memcpy(tss->section_buf + tss->section_index, buf, len);
264
        tss->section_index += len;
265
    }
266

    
267
    /* compute section length if possible */
268
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
269
        len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
270
        if (len > 4096)
271
            return;
272
        tss->section_h_size = len;
273
    }
274

    
275
    if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
276
        tss->end_of_section_reached = 1;
277
        if (!tss->check_crc ||
278
            av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
279
                   tss->section_buf, tss->section_h_size) == 0)
280
            tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
281
    }
282
}
283

    
284
static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
285
                                         SectionCallback *section_cb, void *opaque,
286
                                         int check_crc)
287

    
288
{
289
    MpegTSFilter *filter;
290
    MpegTSSectionFilter *sec;
291

    
292
    dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
293

    
294
    if (pid >= NB_PID_MAX || ts->pids[pid])
295
        return NULL;
296
    filter = av_mallocz(sizeof(MpegTSFilter));
297
    if (!filter)
298
        return NULL;
299
    ts->pids[pid] = filter;
300
    filter->type = MPEGTS_SECTION;
301
    filter->pid = pid;
302
    filter->last_cc = -1;
303
    sec = &filter->u.section_filter;
304
    sec->section_cb = section_cb;
305
    sec->opaque = opaque;
306
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
307
    sec->check_crc = check_crc;
308
    if (!sec->section_buf) {
309
        av_free(filter);
310
        return NULL;
311
    }
312
    return filter;
313
}
314

    
315
static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
316
                                     PESCallback *pes_cb,
317
                                     void *opaque)
318
{
319
    MpegTSFilter *filter;
320
    MpegTSPESFilter *pes;
321

    
322
    if (pid >= NB_PID_MAX || ts->pids[pid])
323
        return NULL;
324
    filter = av_mallocz(sizeof(MpegTSFilter));
325
    if (!filter)
326
        return NULL;
327
    ts->pids[pid] = filter;
328
    filter->type = MPEGTS_PES;
329
    filter->pid = pid;
330
    filter->last_cc = -1;
331
    pes = &filter->u.pes_filter;
332
    pes->pes_cb = pes_cb;
333
    pes->opaque = opaque;
334
    return filter;
335
}
336

    
337
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
338
{
339
    int pid;
340

    
341
    pid = filter->pid;
342
    if (filter->type == MPEGTS_SECTION)
343
        av_freep(&filter->u.section_filter.section_buf);
344
    else if (filter->type == MPEGTS_PES) {
345
        PESContext *pes = filter->u.pes_filter.opaque;
346
        av_freep(&pes->buffer);
347
        /* referenced private data will be freed later in
348
         * av_close_input_stream */
349
        if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
350
            av_freep(&filter->u.pes_filter.opaque);
351
        }
352
    }
353

    
354
    av_free(filter);
355
    ts->pids[pid] = NULL;
356
}
357

    
358
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
359
    int stat[TS_MAX_PACKET_SIZE];
360
    int i;
361
    int x=0;
362
    int best_score=0;
363

    
364
    memset(stat, 0, packet_size*sizeof(int));
365

    
366
    for(x=i=0; i<size-3; i++){
367
        if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
368
            stat[x]++;
369
            if(stat[x] > best_score){
370
                best_score= stat[x];
371
                if(index) *index= x;
372
            }
373
        }
374

    
375
        x++;
376
        if(x == packet_size) x= 0;
377
    }
378

    
379
    return best_score;
380
}
381

    
382
/* autodetect fec presence. Must have at least 1024 bytes  */
383
static int get_packet_size(const uint8_t *buf, int size)
384
{
385
    int score, fec_score, dvhs_score;
386

    
387
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
388
        return -1;
389

    
390
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
391
    dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
392
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
393
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
394

    
395
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
396
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
397
    else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
398
    else                       return -1;
399
}
400

    
401
typedef struct SectionHeader {
402
    uint8_t tid;
403
    uint16_t id;
404
    uint8_t version;
405
    uint8_t sec_num;
406
    uint8_t last_sec_num;
407
} SectionHeader;
408

    
409
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
410
{
411
    const uint8_t *p;
412
    int c;
413

    
414
    p = *pp;
415
    if (p >= p_end)
416
        return -1;
417
    c = *p++;
418
    *pp = p;
419
    return c;
420
}
421

    
422
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
423
{
424
    const uint8_t *p;
425
    int c;
426

    
427
    p = *pp;
428
    if ((p + 1) >= p_end)
429
        return -1;
430
    c = AV_RB16(p);
431
    p += 2;
432
    *pp = p;
433
    return c;
434
}
435

    
436
/* read and allocate a DVB string preceeded by its length */
437
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
438
{
439
    int len;
440
    const uint8_t *p;
441
    char *str;
442

    
443
    p = *pp;
444
    len = get8(&p, p_end);
445
    if (len < 0)
446
        return NULL;
447
    if ((p + len) > p_end)
448
        return NULL;
449
    str = av_malloc(len + 1);
450
    if (!str)
451
        return NULL;
452
    memcpy(str, p, len);
453
    str[len] = '\0';
454
    p += len;
455
    *pp = p;
456
    return str;
457
}
458

    
459
static int parse_section_header(SectionHeader *h,
460
                                const uint8_t **pp, const uint8_t *p_end)
461
{
462
    int val;
463

    
464
    val = get8(pp, p_end);
465
    if (val < 0)
466
        return -1;
467
    h->tid = val;
468
    *pp += 2;
469
    val = get16(pp, p_end);
470
    if (val < 0)
471
        return -1;
472
    h->id = val;
473
    val = get8(pp, p_end);
474
    if (val < 0)
475
        return -1;
476
    h->version = (val >> 1) & 0x1f;
477
    val = get8(pp, p_end);
478
    if (val < 0)
479
        return -1;
480
    h->sec_num = val;
481
    val = get8(pp, p_end);
482
    if (val < 0)
483
        return -1;
484
    h->last_sec_num = val;
485
    return 0;
486
}
487

    
488
typedef struct {
489
    uint32_t stream_type;
490
    enum CodecType codec_type;
491
    enum CodecID codec_id;
492
} StreamType;
493

    
494
static const StreamType ISO_types[] = {
495
    { 0x01, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
496
    { 0x02, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
497
    { 0x03, CODEC_TYPE_AUDIO,        CODEC_ID_MP3 },
498
    { 0x04, CODEC_TYPE_AUDIO,        CODEC_ID_MP3 },
499
    { 0x0f, CODEC_TYPE_AUDIO,        CODEC_ID_AAC },
500
    { 0x10, CODEC_TYPE_VIDEO,      CODEC_ID_MPEG4 },
501
    { 0x1b, CODEC_TYPE_VIDEO,       CODEC_ID_H264 },
502
    { 0xd1, CODEC_TYPE_VIDEO,      CODEC_ID_DIRAC },
503
    { 0xea, CODEC_TYPE_VIDEO,        CODEC_ID_VC1 },
504
    { 0 },
505
};
506

    
507
static const StreamType HDMV_types[] = {
508
    { 0x80, CODEC_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
509
    { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
510
    { 0x82, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
511
    { 0x90, CODEC_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
512
    { 0 },
513
};
514

    
515
/* ATSC ? */
516
static const StreamType MISC_types[] = {
517
    { 0x81, CODEC_TYPE_AUDIO,   CODEC_ID_AC3 },
518
    { 0x8a, CODEC_TYPE_AUDIO,   CODEC_ID_DTS },
519
    { 0 },
520
};
521

    
522
static const StreamType REGD_types[] = {
523
    { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
524
    { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO,   CODEC_ID_AC3 },
525
    { 0 },
526
};
527

    
528
/* descriptor present */
529
static const StreamType DESC_types[] = {
530
    { 0x6a, CODEC_TYPE_AUDIO,             CODEC_ID_AC3 }, /* AC-3 descriptor */
531
    { 0x7a, CODEC_TYPE_AUDIO,            CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
532
    { 0x7b, CODEC_TYPE_AUDIO,             CODEC_ID_DTS },
533
    { 0x59, CODEC_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
534
    { 0 },
535
};
536

    
537
static void mpegts_find_stream_type(AVStream *st,
538
                                    uint32_t stream_type, const StreamType *types)
539
{
540
    for (; types->stream_type; types++) {
541
        if (stream_type == types->stream_type) {
542
            st->codec->codec_type = types->codec_type;
543
            st->codec->codec_id   = types->codec_id;
544
            return;
545
        }
546
    }
547
}
548

    
549
static AVStream *new_pes_av_stream(PESContext *pes, uint32_t prog_reg_desc, uint32_t code)
550
{
551
    AVStream *st = av_new_stream(pes->stream, pes->pid);
552

    
553
    if (!st)
554
        return NULL;
555

    
556
    av_set_pts_info(st, 33, 1, 90000);
557
    st->priv_data = pes;
558
    st->codec->codec_type = CODEC_TYPE_DATA;
559
    st->codec->codec_id   = CODEC_ID_NONE;
560
    st->need_parsing = AVSTREAM_PARSE_FULL;
561
    pes->st = st;
562

    
563
    dprintf(pes->stream, "stream_type=%x pid=%x prog_reg_desc=%.4s\n",
564
            pes->stream_type, pes->pid, (char*)&prog_reg_desc);
565

    
566
    st->codec->codec_tag = pes->stream_type;
567

    
568
    mpegts_find_stream_type(st, pes->stream_type, ISO_types);
569
    if (prog_reg_desc == AV_RL32("HDMV") &&
570
        st->codec->codec_id == CODEC_ID_NONE)
571
        mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
572
    if (st->codec->codec_id == CODEC_ID_NONE)
573
        mpegts_find_stream_type(st, pes->stream_type, MISC_types);
574

    
575
    /* stream was not present in PMT, guess based on PES start code */
576
    if (st->codec->codec_id == CODEC_ID_NONE) {
577
        if (code >= 0x1c0 && code <= 0x1df) {
578
            st->codec->codec_type = CODEC_TYPE_AUDIO;
579
            st->codec->codec_id = CODEC_ID_MP2;
580
        } else if (code == 0x1bd) {
581
            st->codec->codec_type = CODEC_TYPE_AUDIO;
582
            st->codec->codec_id = CODEC_ID_AC3;
583
        }
584
    }
585

    
586
    return st;
587
}
588

    
589
static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
590
{
591
    MpegTSContext *ts = filter->u.section_filter.opaque;
592
    SectionHeader h1, *h = &h1;
593
    PESContext *pes;
594
    AVStream *st;
595
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
596
    int program_info_length, pcr_pid, pid, stream_type;
597
    int desc_list_len, desc_len, desc_tag;
598
    int comp_page, anc_page;
599
    char language[4];
600
    uint32_t prog_reg_desc = 0; /* registration descriptor */
601

    
602
#ifdef DEBUG
603
    dprintf(ts->stream, "PMT: len %i\n", section_len);
604
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
605
#endif
606

    
607
    p_end = section + section_len - 4;
608
    p = section;
609
    if (parse_section_header(h, &p, p_end) < 0)
610
        return;
611

    
612
    dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
613
           h->id, h->sec_num, h->last_sec_num);
614

    
615
    if (h->tid != PMT_TID)
616
        return;
617

    
618
    clear_program(ts, h->id);
619
    pcr_pid = get16(&p, p_end) & 0x1fff;
620
    if (pcr_pid < 0)
621
        return;
622
    add_pid_to_pmt(ts, h->id, pcr_pid);
623

    
624
    dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
625

    
626
    program_info_length = get16(&p, p_end) & 0xfff;
627
    if (program_info_length < 0)
628
        return;
629
    while(program_info_length >= 2) {
630
        uint8_t tag, len;
631
        tag = get8(&p, p_end);
632
        len = get8(&p, p_end);
633
        if(len > program_info_length - 2)
634
            //something else is broken, exit the program_descriptors_loop
635
            break;
636
        program_info_length -= len + 2;
637
        if(tag == 0x05 && len >= 4) { // registration descriptor
638
            prog_reg_desc = bytestream_get_le32(&p);
639
            len -= 4;
640
        }
641
        p += len;
642
    }
643
    p += program_info_length;
644
    if (p >= p_end)
645
        return;
646

    
647
    // stop parsing after pmt, we found header
648
    if (!ts->stream->nb_streams)
649
        ts->stop_parse = 1;
650

    
651
    for(;;) {
652
        st = 0;
653
        stream_type = get8(&p, p_end);
654
        if (stream_type < 0)
655
            break;
656
        pid = get16(&p, p_end) & 0x1fff;
657
        if (pid < 0)
658
            break;
659

    
660
        /* now create ffmpeg stream */
661
        if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
662
            pes = ts->pids[pid]->u.pes_filter.opaque;
663
            st = pes->st;
664
        } else {
665
            if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
666
            pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
667
            if (pes)
668
                st = new_pes_av_stream(pes, prog_reg_desc, 0);
669
        }
670

    
671
        if (!st)
672
            return;
673

    
674
        add_pid_to_pmt(ts, h->id, pid);
675

    
676
        av_program_add_stream_index(ts->stream, h->id, st->index);
677

    
678
        desc_list_len = get16(&p, p_end) & 0xfff;
679
        if (desc_list_len < 0)
680
            break;
681
        desc_list_end = p + desc_list_len;
682
        if (desc_list_end > p_end)
683
            break;
684
        for(;;) {
685
            desc_tag = get8(&p, desc_list_end);
686
            if (desc_tag < 0)
687
                break;
688
            desc_len = get8(&p, desc_list_end);
689
            if (desc_len < 0)
690
                break;
691
            desc_end = p + desc_len;
692
            if (desc_end > desc_list_end)
693
                break;
694

    
695
            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
696
                   desc_tag, desc_len);
697

    
698
            if (st->codec->codec_id == CODEC_ID_NONE &&
699
                stream_type == STREAM_TYPE_PRIVATE_DATA)
700
                mpegts_find_stream_type(st, desc_tag, DESC_types);
701

    
702
            switch(desc_tag) {
703
            case 0x59: /* subtitling descriptor */
704
                language[0] = get8(&p, desc_end);
705
                language[1] = get8(&p, desc_end);
706
                language[2] = get8(&p, desc_end);
707
                language[3] = 0;
708
                get8(&p, desc_end);
709
                comp_page = get16(&p, desc_end);
710
                anc_page = get16(&p, desc_end);
711
                st->codec->sub_id = (anc_page << 16) | comp_page;
712
                av_metadata_set(&st->metadata, "language", language);
713
                break;
714
            case 0x0a: /* ISO 639 language descriptor */
715
                language[0] = get8(&p, desc_end);
716
                language[1] = get8(&p, desc_end);
717
                language[2] = get8(&p, desc_end);
718
                language[3] = 0;
719
                av_metadata_set(&st->metadata, "language", language);
720
                break;
721
            case 0x05: /* registration descriptor */
722
                st->codec->codec_tag = bytestream_get_le32(&p);
723
                dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
724
                if (st->codec->codec_id == CODEC_ID_NONE &&
725
                    stream_type == STREAM_TYPE_PRIVATE_DATA)
726
                    mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
727
                break;
728
            default:
729
                break;
730
            }
731
            p = desc_end;
732
        }
733
        p = desc_list_end;
734
    }
735
    /* all parameters are there */
736
    mpegts_close_filter(ts, filter);
737
}
738

    
739
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
740
{
741
    MpegTSContext *ts = filter->u.section_filter.opaque;
742
    SectionHeader h1, *h = &h1;
743
    const uint8_t *p, *p_end;
744
    int sid, pmt_pid;
745

    
746
#ifdef DEBUG
747
    dprintf(ts->stream, "PAT:\n");
748
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
749
#endif
750
    p_end = section + section_len - 4;
751
    p = section;
752
    if (parse_section_header(h, &p, p_end) < 0)
753
        return;
754
    if (h->tid != PAT_TID)
755
        return;
756

    
757
    clear_programs(ts);
758
    for(;;) {
759
        sid = get16(&p, p_end);
760
        if (sid < 0)
761
            break;
762
        pmt_pid = get16(&p, p_end) & 0x1fff;
763
        if (pmt_pid < 0)
764
            break;
765

    
766
        dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
767

    
768
        if (sid == 0x0000) {
769
            /* NIT info */
770
        } else {
771
            av_new_program(ts->stream, sid);
772
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
773
            add_pat_entry(ts, sid);
774
            add_pid_to_pmt(ts, sid, 0); //add pat pid to program
775
            add_pid_to_pmt(ts, sid, pmt_pid);
776
        }
777
    }
778
}
779

    
780
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
781
{
782
    MpegTSContext *ts = filter->u.section_filter.opaque;
783
    SectionHeader h1, *h = &h1;
784
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
785
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
786
    char *name, *provider_name;
787

    
788
#ifdef DEBUG
789
    dprintf(ts->stream, "SDT:\n");
790
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
791
#endif
792

    
793
    p_end = section + section_len - 4;
794
    p = section;
795
    if (parse_section_header(h, &p, p_end) < 0)
796
        return;
797
    if (h->tid != SDT_TID)
798
        return;
799
    onid = get16(&p, p_end);
800
    if (onid < 0)
801
        return;
802
    val = get8(&p, p_end);
803
    if (val < 0)
804
        return;
805
    for(;;) {
806
        sid = get16(&p, p_end);
807
        if (sid < 0)
808
            break;
809
        val = get8(&p, p_end);
810
        if (val < 0)
811
            break;
812
        desc_list_len = get16(&p, p_end) & 0xfff;
813
        if (desc_list_len < 0)
814
            break;
815
        desc_list_end = p + desc_list_len;
816
        if (desc_list_end > p_end)
817
            break;
818
        for(;;) {
819
            desc_tag = get8(&p, desc_list_end);
820
            if (desc_tag < 0)
821
                break;
822
            desc_len = get8(&p, desc_list_end);
823
            desc_end = p + desc_len;
824
            if (desc_end > desc_list_end)
825
                break;
826

    
827
            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
828
                   desc_tag, desc_len);
829

    
830
            switch(desc_tag) {
831
            case 0x48:
832
                service_type = get8(&p, p_end);
833
                if (service_type < 0)
834
                    break;
835
                provider_name = getstr8(&p, p_end);
836
                if (!provider_name)
837
                    break;
838
                name = getstr8(&p, p_end);
839
                if (name) {
840
                    AVProgram *program = av_new_program(ts->stream, sid);
841
                    if(program) {
842
                        av_metadata_set(&program->metadata, "name", name);
843
                        av_metadata_set(&program->metadata, "provider_name", provider_name);
844
                    }
845
                }
846
                av_free(name);
847
                av_free(provider_name);
848
                break;
849
            default:
850
                break;
851
            }
852
            p = desc_end;
853
        }
854
        p = desc_list_end;
855
    }
856
}
857

    
858
static int64_t get_pts(const uint8_t *p)
859
{
860
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
861
    pts |= (AV_RB16(p + 1) >> 1) << 15;
862
    pts |=  AV_RB16(p + 3) >> 1;
863
    return pts;
864
}
865

    
866
static void new_pes_packet(PESContext *pes, AVPacket *pkt)
867
{
868
    av_init_packet(pkt);
869

    
870
    pkt->destruct = av_destruct_packet;
871
    pkt->data = pes->buffer;
872
    pkt->size = pes->data_index;
873
    memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
874

    
875
    pkt->stream_index = pes->st->index;
876
    pkt->pts = pes->pts;
877
    pkt->dts = pes->dts;
878
    /* store position of first TS packet of this PES packet */
879
    pkt->pos = pes->ts_packet_pos;
880

    
881
    /* reset pts values */
882
    pes->pts = AV_NOPTS_VALUE;
883
    pes->dts = AV_NOPTS_VALUE;
884
    pes->buffer = NULL;
885
    pes->data_index = 0;
886
}
887

    
888
/* return non zero if a packet could be constructed */
889
static int mpegts_push_data(MpegTSFilter *filter,
890
                            const uint8_t *buf, int buf_size, int is_start,
891
                            int64_t pos)
892
{
893
    PESContext *pes = filter->u.pes_filter.opaque;
894
    MpegTSContext *ts = pes->ts;
895
    const uint8_t *p;
896
    int len, code;
897

    
898
    if(!ts->pkt)
899
        return 0;
900

    
901
    if (is_start) {
902
        if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
903
            new_pes_packet(pes, ts->pkt);
904
            ts->stop_parse = 1;
905
        }
906
        pes->state = MPEGTS_HEADER;
907
        pes->data_index = 0;
908
        pes->ts_packet_pos = pos;
909
    }
910
    p = buf;
911
    while (buf_size > 0) {
912
        switch(pes->state) {
913
        case MPEGTS_HEADER:
914
            len = PES_START_SIZE - pes->data_index;
915
            if (len > buf_size)
916
                len = buf_size;
917
            memcpy(pes->header + pes->data_index, p, len);
918
            pes->data_index += len;
919
            p += len;
920
            buf_size -= len;
921
            if (pes->data_index == PES_START_SIZE) {
922
                /* we got all the PES or section header. We can now
923
                   decide */
924
#if 0
925
                av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
926
#endif
927
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
928
                    pes->header[2] == 0x01) {
929
                    /* it must be an mpeg2 PES stream */
930
                    code = pes->header[3] | 0x100;
931
                    dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
932

    
933
                    if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
934
                        (pes->st && pes->st->discard == AVDISCARD_ALL) ||
935
                        code == 0x1be) /* padding_stream */
936
                        goto skip;
937

    
938
                    /* stream not present in PMT */
939
                    if (!pes->st)
940
                        pes->st = new_pes_av_stream(pes, 0, code);
941
                    if (!pes->st)
942
                        return AVERROR(ENOMEM);
943

    
944
                    pes->total_size = AV_RB16(pes->header + 4);
945
                    /* NOTE: a zero total size means the PES size is
946
                       unbounded */
947
                    if (!pes->total_size)
948
                        pes->total_size = MAX_PES_PAYLOAD;
949

    
950
                    /* allocate pes buffer */
951
                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
952
                    if (!pes->buffer)
953
                        return AVERROR(ENOMEM);
954

    
955
                    if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
956
                        code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
957
                        code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
958
                        code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
959
                        pes->state = MPEGTS_PESHEADER;
960
                        if (pes->st->codec->codec_id == CODEC_ID_NONE) {
961
                            dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
962
                                    pes->pid, pes->stream_type);
963
                            pes->st->codec->codec_id = CODEC_ID_PROBE;
964
                        }
965
                    } else {
966
                        pes->state = MPEGTS_PAYLOAD;
967
                        pes->data_index = 0;
968
                    }
969
                } else {
970
                    /* otherwise, it should be a table */
971
                    /* skip packet */
972
                skip:
973
                    pes->state = MPEGTS_SKIP;
974
                    continue;
975
                }
976
            }
977
            break;
978
            /**********************************************/
979
            /* PES packing parsing */
980
        case MPEGTS_PESHEADER:
981
            len = PES_HEADER_SIZE - pes->data_index;
982
            if (len < 0)
983
                return -1;
984
            if (len > buf_size)
985
                len = buf_size;
986
            memcpy(pes->header + pes->data_index, p, len);
987
            pes->data_index += len;
988
            p += len;
989
            buf_size -= len;
990
            if (pes->data_index == PES_HEADER_SIZE) {
991
                pes->pes_header_size = pes->header[8] + 9;
992
                pes->state = MPEGTS_PESHEADER_FILL;
993
            }
994
            break;
995
        case MPEGTS_PESHEADER_FILL:
996
            len = pes->pes_header_size - pes->data_index;
997
            if (len < 0)
998
                return -1;
999
            if (len > buf_size)
1000
                len = buf_size;
1001
            memcpy(pes->header + pes->data_index, p, len);
1002
            pes->data_index += len;
1003
            p += len;
1004
            buf_size -= len;
1005
            if (pes->data_index == pes->pes_header_size) {
1006
                const uint8_t *r;
1007
                unsigned int flags;
1008

    
1009
                flags = pes->header[7];
1010
                r = pes->header + 9;
1011
                pes->pts = AV_NOPTS_VALUE;
1012
                pes->dts = AV_NOPTS_VALUE;
1013
                if ((flags & 0xc0) == 0x80) {
1014
                    pes->dts = pes->pts = get_pts(r);
1015
                    r += 5;
1016
                } else if ((flags & 0xc0) == 0xc0) {
1017
                    pes->pts = get_pts(r);
1018
                    r += 5;
1019
                    pes->dts = get_pts(r);
1020
                    r += 5;
1021
                }
1022

    
1023
                /* we got the full header. We parse it and get the payload */
1024
                pes->state = MPEGTS_PAYLOAD;
1025
                pes->data_index = 0;
1026
            }
1027
            break;
1028
        case MPEGTS_PAYLOAD:
1029
            if (buf_size > 0) {
1030
                if (pes->data_index+buf_size > pes->total_size) {
1031
                    new_pes_packet(pes, ts->pkt);
1032
                    pes->total_size = MAX_PES_PAYLOAD;
1033
                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
1034
                    if (!pes->buffer)
1035
                        return AVERROR(ENOMEM);
1036
                    ts->stop_parse = 1;
1037
                }
1038
                memcpy(pes->buffer+pes->data_index, p, buf_size);
1039
                pes->data_index += buf_size;
1040
            }
1041
            buf_size = 0;
1042
            break;
1043
        case MPEGTS_SKIP:
1044
            buf_size = 0;
1045
            break;
1046
        }
1047
    }
1048

    
1049
    return 0;
1050
}
1051

    
1052
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1053
{
1054
    MpegTSFilter *tss;
1055
    PESContext *pes;
1056

    
1057
    /* if no pid found, then add a pid context */
1058
    pes = av_mallocz(sizeof(PESContext));
1059
    if (!pes)
1060
        return 0;
1061
    pes->ts = ts;
1062
    pes->stream = ts->stream;
1063
    pes->pid = pid;
1064
    pes->pcr_pid = pcr_pid;
1065
    pes->stream_type = stream_type;
1066
    pes->state = MPEGTS_SKIP;
1067
    pes->pts = AV_NOPTS_VALUE;
1068
    pes->dts = AV_NOPTS_VALUE;
1069
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1070
    if (!tss) {
1071
        av_free(pes);
1072
        return 0;
1073
    }
1074
    return pes;
1075
}
1076

    
1077
/* handle one TS packet */
1078
static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1079
{
1080
    AVFormatContext *s = ts->stream;
1081
    MpegTSFilter *tss;
1082
    int len, pid, cc, cc_ok, afc, is_start;
1083
    const uint8_t *p, *p_end;
1084
    int64_t pos;
1085

    
1086
    pid = AV_RB16(packet + 1) & 0x1fff;
1087
    if(pid && discard_pid(ts, pid))
1088
        return 0;
1089
    is_start = packet[1] & 0x40;
1090
    tss = ts->pids[pid];
1091
    if (ts->auto_guess && tss == NULL && is_start) {
1092
        add_pes_stream(ts, pid, -1, 0);
1093
        tss = ts->pids[pid];
1094
    }
1095
    if (!tss)
1096
        return 0;
1097

    
1098
    /* continuity check (currently not used) */
1099
    cc = (packet[3] & 0xf);
1100
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1101
    tss->last_cc = cc;
1102

    
1103
    /* skip adaptation field */
1104
    afc = (packet[3] >> 4) & 3;
1105
    p = packet + 4;
1106
    if (afc == 0) /* reserved value */
1107
        return 0;
1108
    if (afc == 2) /* adaptation field only */
1109
        return 0;
1110
    if (afc == 3) {
1111
        /* skip adapation field */
1112
        p += p[0] + 1;
1113
    }
1114
    /* if past the end of packet, ignore */
1115
    p_end = packet + TS_PACKET_SIZE;
1116
    if (p >= p_end)
1117
        return 0;
1118

    
1119
    pos = url_ftell(ts->stream->pb);
1120
    ts->pos47= pos % ts->raw_packet_size;
1121

    
1122
    if (tss->type == MPEGTS_SECTION) {
1123
        if (is_start) {
1124
            /* pointer field present */
1125
            len = *p++;
1126
            if (p + len > p_end)
1127
                return 0;
1128
            if (len && cc_ok) {
1129
                /* write remaining section bytes */
1130
                write_section_data(s, tss,
1131
                                   p, len, 0);
1132
                /* check whether filter has been closed */
1133
                if (!ts->pids[pid])
1134
                    return 0;
1135
            }
1136
            p += len;
1137
            if (p < p_end) {
1138
                write_section_data(s, tss,
1139
                                   p, p_end - p, 1);
1140
            }
1141
        } else {
1142
            if (cc_ok) {
1143
                write_section_data(s, tss,
1144
                                   p, p_end - p, 0);
1145
            }
1146
        }
1147
    } else {
1148
        int ret;
1149
        // Note: The position here points actually behind the current packet.
1150
        if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1151
                                            pos - ts->raw_packet_size)) < 0)
1152
            return ret;
1153
    }
1154

    
1155
    return 0;
1156
}
1157

    
1158
/* XXX: try to find a better synchro over several packets (use
1159
   get_packet_size() ?) */
1160
static int mpegts_resync(ByteIOContext *pb)
1161
{
1162
    int c, i;
1163

    
1164
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1165
        c = url_fgetc(pb);
1166
        if (c < 0)
1167
            return -1;
1168
        if (c == 0x47) {
1169
            url_fseek(pb, -1, SEEK_CUR);
1170
            return 0;
1171
        }
1172
    }
1173
    /* no sync found */
1174
    return -1;
1175
}
1176

    
1177
/* return -1 if error or EOF. Return 0 if OK. */
1178
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1179
{
1180
    int skip, len;
1181

    
1182
    for(;;) {
1183
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1184
        if (len != TS_PACKET_SIZE)
1185
            return AVERROR(EIO);
1186
        /* check paquet sync byte */
1187
        if (buf[0] != 0x47) {
1188
            /* find a new packet start */
1189
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1190
            if (mpegts_resync(pb) < 0)
1191
                return AVERROR_INVALIDDATA;
1192
            else
1193
                continue;
1194
        } else {
1195
            skip = raw_packet_size - TS_PACKET_SIZE;
1196
            if (skip > 0)
1197
                url_fskip(pb, skip);
1198
            break;
1199
        }
1200
    }
1201
    return 0;
1202
}
1203

    
1204
static int handle_packets(MpegTSContext *ts, int nb_packets)
1205
{
1206
    AVFormatContext *s = ts->stream;
1207
    ByteIOContext *pb = s->pb;
1208
    uint8_t packet[TS_PACKET_SIZE];
1209
    int packet_num, ret;
1210

    
1211
    ts->stop_parse = 0;
1212
    packet_num = 0;
1213
    for(;;) {
1214
        if (ts->stop_parse>0)
1215
            break;
1216
        packet_num++;
1217
        if (nb_packets != 0 && packet_num >= nb_packets)
1218
            break;
1219
        ret = read_packet(pb, packet, ts->raw_packet_size);
1220
        if (ret != 0)
1221
            return ret;
1222
        ret = handle_packet(ts, packet);
1223
        if (ret != 0)
1224
            return ret;
1225
    }
1226
    return 0;
1227
}
1228

    
1229
static int mpegts_probe(AVProbeData *p)
1230
{
1231
#if 1
1232
    const int size= p->buf_size;
1233
    int score, fec_score, dvhs_score;
1234
    int check_count= size / TS_FEC_PACKET_SIZE;
1235
#define CHECK_COUNT 10
1236

    
1237
    if (check_count < CHECK_COUNT)
1238
        return -1;
1239

    
1240
    score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
1241
    dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1242
    fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1243
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1244

    
1245
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1246
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1247
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1248
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1249
    else                                    return -1;
1250
#else
1251
    /* only use the extension for safer guess */
1252
    if (match_ext(p->filename, "ts"))
1253
        return AVPROBE_SCORE_MAX;
1254
    else
1255
        return 0;
1256
#endif
1257
}
1258

    
1259
/* return the 90kHz PCR and the extension for the 27MHz PCR. return
1260
   (-1) if not available */
1261
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1262
                     const uint8_t *packet)
1263
{
1264
    int afc, len, flags;
1265
    const uint8_t *p;
1266
    unsigned int v;
1267

    
1268
    afc = (packet[3] >> 4) & 3;
1269
    if (afc <= 1)
1270
        return -1;
1271
    p = packet + 4;
1272
    len = p[0];
1273
    p++;
1274
    if (len == 0)
1275
        return -1;
1276
    flags = *p++;
1277
    len--;
1278
    if (!(flags & 0x10))
1279
        return -1;
1280
    if (len < 6)
1281
        return -1;
1282
    v = AV_RB32(p);
1283
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1284
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1285
    return 0;
1286
}
1287

    
1288
static int mpegts_read_header(AVFormatContext *s,
1289
                              AVFormatParameters *ap)
1290
{
1291
    MpegTSContext *ts = s->priv_data;
1292
    ByteIOContext *pb = s->pb;
1293
    uint8_t buf[5*1024];
1294
    int len;
1295
    int64_t pos;
1296

    
1297
    if (ap) {
1298
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1299
        if(ap->mpeg2ts_raw){
1300
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1301
            return -1;
1302
        }
1303
    }
1304

    
1305
    /* read the first 1024 bytes to get packet size */
1306
    pos = url_ftell(pb);
1307
    len = get_buffer(pb, buf, sizeof(buf));
1308
    if (len != sizeof(buf))
1309
        goto fail;
1310
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1311
    if (ts->raw_packet_size <= 0)
1312
        goto fail;
1313
    ts->stream = s;
1314
    ts->auto_guess = 0;
1315

    
1316
    if (s->iformat == &mpegts_demuxer) {
1317
        /* normal demux */
1318

    
1319
        /* first do a scaning to get all the services */
1320
        url_fseek(pb, pos, SEEK_SET);
1321

    
1322
        mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1323

    
1324
        mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1325

    
1326
        handle_packets(ts, s->probesize);
1327
        /* if could not find service, enable auto_guess */
1328

    
1329
        ts->auto_guess = 1;
1330

    
1331
        dprintf(ts->stream, "tuning done\n");
1332

    
1333
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1334
    } else {
1335
        AVStream *st;
1336
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1337
        int64_t pcrs[2], pcr_h;
1338
        int packet_count[2];
1339
        uint8_t packet[TS_PACKET_SIZE];
1340

    
1341
        /* only read packets */
1342

    
1343
        st = av_new_stream(s, 0);
1344
        if (!st)
1345
            goto fail;
1346
        av_set_pts_info(st, 60, 1, 27000000);
1347
        st->codec->codec_type = CODEC_TYPE_DATA;
1348
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1349

    
1350
        /* we iterate until we find two PCRs to estimate the bitrate */
1351
        pcr_pid = -1;
1352
        nb_pcrs = 0;
1353
        nb_packets = 0;
1354
        for(;;) {
1355
            ret = read_packet(s->pb, packet, ts->raw_packet_size);
1356
            if (ret < 0)
1357
                return -1;
1358
            pid = AV_RB16(packet + 1) & 0x1fff;
1359
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1360
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1361
                pcr_pid = pid;
1362
                packet_count[nb_pcrs] = nb_packets;
1363
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1364
                nb_pcrs++;
1365
                if (nb_pcrs >= 2)
1366
                    break;
1367
            }
1368
            nb_packets++;
1369
        }
1370

    
1371
        /* NOTE1: the bitrate is computed without the FEC */
1372
        /* NOTE2: it is only the bitrate of the start of the stream */
1373
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1374
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1375
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1376
        st->codec->bit_rate = s->bit_rate;
1377
        st->start_time = ts->cur_pcr;
1378
#if 0
1379
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1380
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1381
#endif
1382
    }
1383

    
1384
    url_fseek(pb, pos, SEEK_SET);
1385
    return 0;
1386
 fail:
1387
    return -1;
1388
}
1389

    
1390
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1391

    
1392
static int mpegts_raw_read_packet(AVFormatContext *s,
1393
                                  AVPacket *pkt)
1394
{
1395
    MpegTSContext *ts = s->priv_data;
1396
    int ret, i;
1397
    int64_t pcr_h, next_pcr_h, pos;
1398
    int pcr_l, next_pcr_l;
1399
    uint8_t pcr_buf[12];
1400

    
1401
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1402
        return AVERROR(ENOMEM);
1403
    pkt->pos= url_ftell(s->pb);
1404
    ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1405
    if (ret < 0) {
1406
        av_free_packet(pkt);
1407
        return ret;
1408
    }
1409
    if (ts->mpeg2ts_compute_pcr) {
1410
        /* compute exact PCR for each packet */
1411
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1412
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1413
            pos = url_ftell(s->pb);
1414
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1415
                url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1416
                get_buffer(s->pb, pcr_buf, 12);
1417
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1418
                    /* XXX: not precise enough */
1419
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1420
                        (i + 1);
1421
                    break;
1422
                }
1423
            }
1424
            url_fseek(s->pb, pos, SEEK_SET);
1425
            /* no next PCR found: we use previous increment */
1426
            ts->cur_pcr = pcr_h * 300 + pcr_l;
1427
        }
1428
        pkt->pts = ts->cur_pcr;
1429
        pkt->duration = ts->pcr_incr;
1430
        ts->cur_pcr += ts->pcr_incr;
1431
    }
1432
    pkt->stream_index = 0;
1433
    return 0;
1434
}
1435

    
1436
static int mpegts_read_packet(AVFormatContext *s,
1437
                              AVPacket *pkt)
1438
{
1439
    MpegTSContext *ts = s->priv_data;
1440
    int ret, i;
1441

    
1442
    if (url_ftell(s->pb) != ts->last_pos) {
1443
        /* seek detected, flush pes buffer */
1444
        for (i = 0; i < NB_PID_MAX; i++) {
1445
            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1446
                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1447
                av_freep(&pes->buffer);
1448
                pes->data_index = 0;
1449
                pes->state = MPEGTS_SKIP; /* skip until pes header */
1450
            }
1451
        }
1452
    }
1453

    
1454
    ts->pkt = pkt;
1455
    ret = handle_packets(ts, 0);
1456
    if (ret < 0) {
1457
        /* flush pes data left */
1458
        for (i = 0; i < NB_PID_MAX; i++) {
1459
            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1460
                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1461
                if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1462
                    new_pes_packet(pes, pkt);
1463
                    ret = 0;
1464
                    break;
1465
                }
1466
            }
1467
        }
1468
    }
1469

    
1470
    ts->last_pos = url_ftell(s->pb);
1471

    
1472
    return ret;
1473
}
1474

    
1475
static int mpegts_read_close(AVFormatContext *s)
1476
{
1477
    MpegTSContext *ts = s->priv_data;
1478
    int i;
1479

    
1480
    clear_programs(ts);
1481

    
1482
    for(i=0;i<NB_PID_MAX;i++)
1483
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1484

    
1485
    return 0;
1486
}
1487

    
1488
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1489
                              int64_t *ppos, int64_t pos_limit)
1490
{
1491
    MpegTSContext *ts = s->priv_data;
1492
    int64_t pos, timestamp;
1493
    uint8_t buf[TS_PACKET_SIZE];
1494
    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1495
    const int find_next= 1;
1496
    pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1497
    if (find_next) {
1498
        for(;;) {
1499
            url_fseek(s->pb, pos, SEEK_SET);
1500
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1501
                return AV_NOPTS_VALUE;
1502
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1503
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1504
                break;
1505
            }
1506
            pos += ts->raw_packet_size;
1507
        }
1508
    } else {
1509
        for(;;) {
1510
            pos -= ts->raw_packet_size;
1511
            if (pos < 0)
1512
                return AV_NOPTS_VALUE;
1513
            url_fseek(s->pb, pos, SEEK_SET);
1514
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1515
                return AV_NOPTS_VALUE;
1516
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1517
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1518
                break;
1519
            }
1520
        }
1521
    }
1522
    *ppos = pos;
1523

    
1524
    return timestamp;
1525
}
1526

    
1527
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags);
1528

    
1529
static int read_seek2(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t target_ts, int64_t max_ts, int flags)
1530
{
1531
    int64_t pos;
1532

    
1533
    int64_t ts_ret, ts_adj;
1534
    int stream_index_gen_search;
1535
    AVStream *st;
1536
    AVParserState *backup;
1537

    
1538
    backup = ff_store_parser_state(s);
1539

    
1540
    // detect direction of seeking for search purposes
1541
    flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ? AVSEEK_FLAG_BACKWARD : 0;
1542

    
1543
    if (flags & AVSEEK_FLAG_BYTE) {
1544
        /* use position directly, we will search starting from it */
1545
        pos = target_ts;
1546
    } else {
1547
        /* search for some position with good timestamp match */
1548
        if(stream_index < 0){
1549
            stream_index_gen_search = av_find_default_stream_index(s);
1550
            if (stream_index_gen_search < 0) {
1551
                ff_restore_parser_state(s, backup);
1552
                return -1;
1553
            }
1554

    
1555
            st = s->streams[stream_index_gen_search];
1556
            /* timestamp for default must be expressed in AV_TIME_BASE units */
1557
            ts_adj = av_rescale(target_ts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1558
        } else {
1559
            ts_adj = target_ts;
1560
            stream_index_gen_search = stream_index;
1561
        }
1562
        pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1563
                            0, INT64_MAX, -1,
1564
                            AV_NOPTS_VALUE,
1565
                            AV_NOPTS_VALUE,
1566
                            flags, &ts_ret, mpegts_get_pcr);
1567
        if (pos < 0) {
1568
            ff_restore_parser_state(s, backup);
1569
            return -1;
1570
        }
1571
    }
1572

    
1573
    /* search for actual matching keyframe/starting position for all streams */
1574
    if (ff_gen_syncpoint_search(s, stream_index, pos, min_ts, target_ts, max_ts, flags) < 0) {
1575
        ff_restore_parser_state(s, backup);
1576
        return -1;
1577
    }
1578

    
1579
    ff_free_parser_state(s, backup);
1580
    return 0;
1581
}
1582

    
1583
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1584
{
1585
    int ret;
1586
    if (flags & AVSEEK_FLAG_BACKWARD) {
1587
        ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1588
        if (ret < 0) {
1589
            // for compatibility reasons, seek to best-fitting timestamp
1590
            ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags & ~AVSEEK_FLAG_BACKWARD);
1591
        }
1592
    } else {
1593
        ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1594
        if (ret < 0) {
1595
            // for compatibility reasons, seek to best-fitting timestamp
1596
            ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1597
        }
1598
    }
1599
    return ret;
1600
}
1601

    
1602
/**************************************************************/
1603
/* parsing functions - called from other demuxers such as RTP */
1604

    
1605
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1606
{
1607
    MpegTSContext *ts;
1608

    
1609
    ts = av_mallocz(sizeof(MpegTSContext));
1610
    if (!ts)
1611
        return NULL;
1612
    /* no stream case, currently used by RTP */
1613
    ts->raw_packet_size = TS_PACKET_SIZE;
1614
    ts->stream = s;
1615
    ts->auto_guess = 1;
1616
    return ts;
1617
}
1618

    
1619
/* return the consumed length if a packet was output, or -1 if no
1620
   packet is output */
1621
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1622
                        const uint8_t *buf, int len)
1623
{
1624
    int len1;
1625

    
1626
    len1 = len;
1627
    ts->pkt = pkt;
1628
    ts->stop_parse = 0;
1629
    for(;;) {
1630
        if (ts->stop_parse>0)
1631
            break;
1632
        if (len < TS_PACKET_SIZE)
1633
            return -1;
1634
        if (buf[0] != 0x47) {
1635
            buf++;
1636
            len--;
1637
        } else {
1638
            handle_packet(ts, buf);
1639
            buf += TS_PACKET_SIZE;
1640
            len -= TS_PACKET_SIZE;
1641
        }
1642
    }
1643
    return len1 - len;
1644
}
1645

    
1646
void mpegts_parse_close(MpegTSContext *ts)
1647
{
1648
    int i;
1649

    
1650
    for(i=0;i<NB_PID_MAX;i++)
1651
        av_free(ts->pids[i]);
1652
    av_free(ts);
1653
}
1654

    
1655
AVInputFormat mpegts_demuxer = {
1656
    "mpegts",
1657
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1658
    sizeof(MpegTSContext),
1659
    mpegts_probe,
1660
    mpegts_read_header,
1661
    mpegts_read_packet,
1662
    mpegts_read_close,
1663
    read_seek,
1664
    mpegts_get_pcr,
1665
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1666
    .read_seek2 = read_seek2,
1667
};
1668

    
1669
AVInputFormat mpegtsraw_demuxer = {
1670
    "mpegtsraw",
1671
    NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1672
    sizeof(MpegTSContext),
1673
    NULL,
1674
    mpegts_read_header,
1675
    mpegts_raw_read_packet,
1676
    mpegts_read_close,
1677
    read_seek,
1678
    mpegts_get_pcr,
1679
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1680
    .read_seek2 = read_seek2,
1681
};