Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ 617c4616

History | View | Annotate | Download (46.6 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

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

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

    
39
#define MAX_PES_PAYLOAD 200*1024
40

    
41
typedef struct PESContext PESContext;
42

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

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

    
50
typedef struct MpegTSFilter MpegTSFilter;
51

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

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

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

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

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

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

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

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

    
96
    int pos47;
97

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

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

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

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

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

    
122

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

    
127
/* TS stream handling */
128

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

    
136
/* enough for PES header + length */
137
#define PES_START_SIZE 9
138
#define MAX_PES_HEADER_SIZE (9 + 255)
139

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

    
158
extern AVInputFormat mpegts_demuxer;
159

    
160
static void clear_program(MpegTSContext *ts, unsigned int programid)
161
{
162
    int i;
163

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

    
169
static void clear_programs(MpegTSContext *ts)
170
{
171
    av_freep(&ts->prg);
172
    ts->nb_prg=0;
173
}
174

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

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

    
201
    if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
202
        return;
203
    p->pids[p->nb_pids++] = pid;
204
}
205

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

    
236
    return !used && discarded;
237
}
238

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

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

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

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

    
281
static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
282
                                         SectionCallback *section_cb, void *opaque,
283
                                         int check_crc)
284

    
285
{
286
    MpegTSFilter *filter;
287
    MpegTSSectionFilter *sec;
288

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

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

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

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

    
334
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
335
{
336
    int pid;
337

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

    
351
    av_free(filter);
352
    ts->pids[pid] = NULL;
353
}
354

    
355
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
356
    int stat[packet_size];
357
    int i;
358
    int x=0;
359
    int best_score=0;
360

    
361
    memset(stat, 0, packet_size*sizeof(int));
362

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

    
372
        x++;
373
        if(x == packet_size) x= 0;
374
    }
375

    
376
    return best_score;
377
}
378

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

    
384
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
385
        return -1;
386

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

    
392
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
393
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
394
    else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
395
    else                       return -1;
396
}
397

    
398
typedef struct SectionHeader {
399
    uint8_t tid;
400
    uint16_t id;
401
    uint8_t version;
402
    uint8_t sec_num;
403
    uint8_t last_sec_num;
404
} SectionHeader;
405

    
406
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
407
{
408
    const uint8_t *p;
409
    int c;
410

    
411
    p = *pp;
412
    if (p >= p_end)
413
        return -1;
414
    c = *p++;
415
    *pp = p;
416
    return c;
417
}
418

    
419
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
420
{
421
    const uint8_t *p;
422
    int c;
423

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

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

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

    
456
static int parse_section_header(SectionHeader *h,
457
                                const uint8_t **pp, const uint8_t *p_end)
458
{
459
    int val;
460

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

    
485
typedef struct {
486
    uint32_t stream_type;
487
    enum CodecType codec_type;
488
    enum CodecID codec_id;
489
} StreamType;
490

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

    
504
static const StreamType HDMV_types[] = {
505
    { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
506
    { 0x82, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
507
    { 0 },
508
};
509

    
510
/* ATSC ? */
511
static const StreamType MISC_types[] = {
512
    { 0x81, CODEC_TYPE_AUDIO,   CODEC_ID_AC3 },
513
    { 0x8a, CODEC_TYPE_AUDIO,   CODEC_ID_DTS },
514
    { 0 },
515
};
516

    
517
static const StreamType REGD_types[] = {
518
    { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
519
    { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO,   CODEC_ID_AC3 },
520
    { 0 },
521
};
522

    
523
/* descriptor present */
524
static const StreamType DESC_types[] = {
525
    { 0x6a, CODEC_TYPE_AUDIO,             CODEC_ID_AC3 }, /* AC-3 descriptor */
526
    { 0x7a, CODEC_TYPE_AUDIO,            CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
527
    { 0x7b, CODEC_TYPE_AUDIO,             CODEC_ID_DTS },
528
    { 0x59, CODEC_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
529
};
530

    
531
static void mpegts_find_stream_type(AVStream *st,
532
                                    uint32_t stream_type, const StreamType *types)
533
{
534
    for (; types->stream_type; types++) {
535
        if (stream_type == types->stream_type) {
536
            st->codec->codec_type = types->codec_type;
537
            st->codec->codec_id   = types->codec_id;
538
            return;
539
        }
540
    }
541
}
542

    
543
static AVStream *new_pes_av_stream(PESContext *pes, uint32_t prog_reg_desc, uint32_t code)
544
{
545
    AVStream *st = av_new_stream(pes->stream, pes->pid);
546

    
547
    if (!st)
548
        return NULL;
549

    
550
    av_set_pts_info(st, 33, 1, 90000);
551
    st->priv_data = pes;
552
    st->codec->codec_type = CODEC_TYPE_DATA;
553
    st->codec->codec_id   = CODEC_ID_PROBE;
554
    st->need_parsing = AVSTREAM_PARSE_FULL;
555
    pes->st = st;
556

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

    
560
    st->codec->codec_tag = pes->stream_type;
561

    
562
    mpegts_find_stream_type(st, pes->stream_type, ISO_types);
563
    if (prog_reg_desc == AV_RL32("HDMV") &&
564
        st->codec->codec_id == CODEC_ID_PROBE)
565
        mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
566
    if (st->codec->codec_id == CODEC_ID_PROBE)
567
        mpegts_find_stream_type(st, pes->stream_type, MISC_types);
568

    
569
    /* stream was not present in PMT, guess based on PES start code */
570
    if (st->codec->codec_id == CODEC_ID_PROBE) {
571
        if (code >= 0x1c0 && code <= 0x1df) {
572
            st->codec->codec_type = CODEC_TYPE_AUDIO;
573
            st->codec->codec_id = CODEC_ID_MP2;
574
        } else if (code == 0x1bd) {
575
            st->codec->codec_type = CODEC_TYPE_AUDIO;
576
            st->codec->codec_id = CODEC_ID_AC3;
577
        }
578
    }
579

    
580
    return st;
581
}
582

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

    
596
#ifdef DEBUG
597
    dprintf(ts->stream, "PMT: len %i\n", section_len);
598
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
599
#endif
600

    
601
    p_end = section + section_len - 4;
602
    p = section;
603
    if (parse_section_header(h, &p, p_end) < 0)
604
        return;
605

    
606
    dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
607
           h->id, h->sec_num, h->last_sec_num);
608

    
609
    if (h->tid != PMT_TID)
610
        return;
611

    
612
    clear_program(ts, h->id);
613
    pcr_pid = get16(&p, p_end) & 0x1fff;
614
    if (pcr_pid < 0)
615
        return;
616
    add_pid_to_pmt(ts, h->id, pcr_pid);
617

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

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

    
649
        /* now create ffmpeg stream */
650
        if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
651
            pes = ts->pids[pid]->u.pes_filter.opaque;
652
            st = pes->st;
653
        } else {
654
            if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
655
            pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
656
            if (pes)
657
                st = new_pes_av_stream(pes, prog_reg_desc, 0);
658
        }
659

    
660
        if (!st)
661
            return;
662

    
663
        add_pid_to_pmt(ts, h->id, pid);
664

    
665
        av_program_add_stream_index(ts->stream, h->id, st->index);
666

    
667
        desc_list_len = get16(&p, p_end) & 0xfff;
668
        if (desc_list_len < 0)
669
            break;
670
        desc_list_end = p + desc_list_len;
671
        if (desc_list_end > p_end)
672
            break;
673
        for(;;) {
674
            desc_tag = get8(&p, desc_list_end);
675
            if (desc_tag < 0)
676
                break;
677
            desc_len = get8(&p, desc_list_end);
678
            if (desc_len < 0)
679
                break;
680
            desc_end = p + desc_len;
681
            if (desc_end > desc_list_end)
682
                break;
683

    
684
            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
685
                   desc_tag, desc_len);
686

    
687
            if (st->codec->codec_id == CODEC_ID_PROBE &&
688
                stream_type == STREAM_TYPE_PRIVATE_DATA)
689
                mpegts_find_stream_type(st, desc_tag, DESC_types);
690

    
691
            switch(desc_tag) {
692
            case 0x59: /* subtitling descriptor */
693
                language[0] = get8(&p, desc_end);
694
                language[1] = get8(&p, desc_end);
695
                language[2] = get8(&p, desc_end);
696
                language[3] = 0;
697
                get8(&p, desc_end);
698
                comp_page = get16(&p, desc_end);
699
                anc_page = get16(&p, desc_end);
700
                st->codec->sub_id = (anc_page << 16) | comp_page;
701
                av_metadata_set(&st->metadata, "language", language);
702
                break;
703
            case 0x0a: /* ISO 639 language 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
                av_metadata_set(&st->metadata, "language", language);
709
                break;
710
            case 0x05: /* registration descriptor */
711
                st->codec->codec_tag = bytestream_get_le32(&p);
712
                dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
713
                if (st->codec->codec_id == CODEC_ID_PROBE &&
714
                    stream_type == STREAM_TYPE_PRIVATE_DATA)
715
                    mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
716
                break;
717
            default:
718
                break;
719
            }
720
            p = desc_end;
721
        }
722
        p = desc_list_end;
723
    }
724
    /* all parameters are there */
725
    ts->stop_parse++;
726
    mpegts_close_filter(ts, filter);
727
}
728

    
729
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
730
{
731
    MpegTSContext *ts = filter->u.section_filter.opaque;
732
    SectionHeader h1, *h = &h1;
733
    const uint8_t *p, *p_end;
734
    int sid, pmt_pid;
735

    
736
#ifdef DEBUG
737
    dprintf(ts->stream, "PAT:\n");
738
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
739
#endif
740
    p_end = section + section_len - 4;
741
    p = section;
742
    if (parse_section_header(h, &p, p_end) < 0)
743
        return;
744
    if (h->tid != PAT_TID)
745
        return;
746

    
747
    clear_programs(ts);
748
    for(;;) {
749
        sid = get16(&p, p_end);
750
        if (sid < 0)
751
            break;
752
        pmt_pid = get16(&p, p_end) & 0x1fff;
753
        if (pmt_pid < 0)
754
            break;
755

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

    
758
        if (sid == 0x0000) {
759
            /* NIT info */
760
        } else {
761
            av_new_program(ts->stream, sid);
762
            ts->stop_parse--;
763
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
764
            add_pat_entry(ts, sid);
765
            add_pid_to_pmt(ts, sid, 0); //add pat pid to program
766
            add_pid_to_pmt(ts, sid, pmt_pid);
767
        }
768
    }
769
    /* not found */
770
    ts->stop_parse++;
771

    
772
    mpegts_close_filter(ts, filter);
773
}
774

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

    
783
#ifdef DEBUG
784
    dprintf(ts->stream, "SDT:\n");
785
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
786
#endif
787

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

    
822
            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
823
                   desc_tag, desc_len);
824

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

    
853
static int64_t get_pts(const uint8_t *p)
854
{
855
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
856
    pts |= (AV_RB16(p + 1) >> 1) << 15;
857
    pts |=  AV_RB16(p + 3) >> 1;
858
    return pts;
859
}
860

    
861
static void new_pes_packet(PESContext *pes, AVPacket *pkt)
862
{
863
    av_init_packet(pkt);
864

    
865
    pkt->destruct = av_destruct_packet;
866
    pkt->data = pes->buffer;
867
    pkt->size = pes->data_index;
868
    memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
869

    
870
    pkt->stream_index = pes->st->index;
871
    pkt->pts = pes->pts;
872
    pkt->dts = pes->dts;
873
    /* store position of first TS packet of this PES packet */
874
    pkt->pos = pes->ts_packet_pos;
875

    
876
    /* reset pts values */
877
    pes->pts = AV_NOPTS_VALUE;
878
    pes->dts = AV_NOPTS_VALUE;
879
    pes->buffer = NULL;
880
    pes->data_index = 0;
881
}
882

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

    
893
    if(!ts->pkt)
894
        return 0;
895

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

    
928
                    if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
929
                        (pes->st && pes->st->discard == AVDISCARD_ALL) ||
930
                        code == 0x1be) /* padding_stream */
931
                        goto skip;
932

    
933
                    /* stream not present in PMT */
934
                    if (!pes->st)
935
                        pes->st = new_pes_av_stream(pes, 0, code);
936
                    if (!pes->st)
937
                        return AVERROR(ENOMEM);
938

    
939
                    pes->total_size = AV_RB16(pes->header + 4);
940
                    /* NOTE: a zero total size means the PES size is
941
                       unbounded */
942
                    if (!pes->total_size)
943
                        pes->total_size = MAX_PES_PAYLOAD;
944

    
945
                    /* allocate pes buffer */
946
                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
947
                    if (!pes->buffer)
948
                        return AVERROR(ENOMEM);
949

    
950
                    if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
951
                        code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
952
                        code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
953
                        code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
954
                        pes->state = MPEGTS_PESHEADER_FILL;
955
                        pes->pes_header_size = pes->header[8] + 9;
956
                    } else {
957
                        pes->state = MPEGTS_PAYLOAD;
958
                        pes->data_index = 0;
959
                    }
960
                } else {
961
                    /* otherwise, it should be a table */
962
                    /* skip packet */
963
                skip:
964
                    pes->state = MPEGTS_SKIP;
965
                    continue;
966
                }
967
            }
968
            break;
969
            /**********************************************/
970
            /* PES packing parsing */
971
        case MPEGTS_PESHEADER_FILL:
972
            len = pes->pes_header_size - pes->data_index;
973
            if (len < 0)
974
                return -1;
975
            if (len > buf_size)
976
                len = buf_size;
977
            memcpy(pes->header + pes->data_index, p, len);
978
            pes->data_index += len;
979
            p += len;
980
            buf_size -= len;
981
            if (pes->data_index == pes->pes_header_size) {
982
                const uint8_t *r;
983
                unsigned int flags;
984

    
985
                flags = pes->header[7];
986
                r = pes->header + 9;
987
                pes->pts = AV_NOPTS_VALUE;
988
                pes->dts = AV_NOPTS_VALUE;
989
                if ((flags & 0xc0) == 0x80) {
990
                    pes->dts = pes->pts = get_pts(r);
991
                    r += 5;
992
                } else if ((flags & 0xc0) == 0xc0) {
993
                    pes->pts = get_pts(r);
994
                    r += 5;
995
                    pes->dts = get_pts(r);
996
                    r += 5;
997
                }
998

    
999
                /* we got the full header. We parse it and get the payload */
1000
                pes->state = MPEGTS_PAYLOAD;
1001
                pes->data_index = 0;
1002
            }
1003
            break;
1004
        case MPEGTS_PAYLOAD:
1005
            if (buf_size > 0) {
1006
                if (pes->data_index+buf_size > pes->total_size) {
1007
                    new_pes_packet(pes, ts->pkt);
1008
                    pes->total_size = MAX_PES_PAYLOAD;
1009
                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
1010
                    if (!pes->buffer)
1011
                        return AVERROR(ENOMEM);
1012
                    ts->stop_parse = 1;
1013
                }
1014
                memcpy(pes->buffer+pes->data_index, p, buf_size);
1015
                pes->data_index += buf_size;
1016
            }
1017
            buf_size = 0;
1018
            break;
1019
        case MPEGTS_SKIP:
1020
            buf_size = 0;
1021
            break;
1022
        }
1023
    }
1024

    
1025
    return 0;
1026
}
1027

    
1028
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1029
{
1030
    MpegTSFilter *tss;
1031
    PESContext *pes;
1032

    
1033
    /* if no pid found, then add a pid context */
1034
    pes = av_mallocz(sizeof(PESContext));
1035
    if (!pes)
1036
        return 0;
1037
    pes->ts = ts;
1038
    pes->stream = ts->stream;
1039
    pes->pid = pid;
1040
    pes->pcr_pid = pcr_pid;
1041
    pes->stream_type = stream_type;
1042
    pes->state = MPEGTS_SKIP;
1043
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1044
    if (!tss) {
1045
        av_free(pes);
1046
        return 0;
1047
    }
1048
    return pes;
1049
}
1050

    
1051
/* handle one TS packet */
1052
static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1053
{
1054
    AVFormatContext *s = ts->stream;
1055
    MpegTSFilter *tss;
1056
    int len, pid, cc, cc_ok, afc, is_start;
1057
    const uint8_t *p, *p_end;
1058
    int64_t pos;
1059

    
1060
    pid = AV_RB16(packet + 1) & 0x1fff;
1061
    if(pid && discard_pid(ts, pid))
1062
        return 0;
1063
    is_start = packet[1] & 0x40;
1064
    tss = ts->pids[pid];
1065
    if (ts->auto_guess && tss == NULL && is_start) {
1066
        add_pes_stream(ts, pid, -1, 0);
1067
        tss = ts->pids[pid];
1068
    }
1069
    if (!tss)
1070
        return 0;
1071

    
1072
    /* continuity check (currently not used) */
1073
    cc = (packet[3] & 0xf);
1074
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1075
    tss->last_cc = cc;
1076

    
1077
    /* skip adaptation field */
1078
    afc = (packet[3] >> 4) & 3;
1079
    p = packet + 4;
1080
    if (afc == 0) /* reserved value */
1081
        return 0;
1082
    if (afc == 2) /* adaptation field only */
1083
        return 0;
1084
    if (afc == 3) {
1085
        /* skip adapation field */
1086
        p += p[0] + 1;
1087
    }
1088
    /* if past the end of packet, ignore */
1089
    p_end = packet + TS_PACKET_SIZE;
1090
    if (p >= p_end)
1091
        return 0;
1092

    
1093
    pos = url_ftell(ts->stream->pb);
1094
    ts->pos47= pos % ts->raw_packet_size;
1095

    
1096
    if (tss->type == MPEGTS_SECTION) {
1097
        if (is_start) {
1098
            /* pointer field present */
1099
            len = *p++;
1100
            if (p + len > p_end)
1101
                return 0;
1102
            if (len && cc_ok) {
1103
                /* write remaining section bytes */
1104
                write_section_data(s, tss,
1105
                                   p, len, 0);
1106
                /* check whether filter has been closed */
1107
                if (!ts->pids[pid])
1108
                    return 0;
1109
            }
1110
            p += len;
1111
            if (p < p_end) {
1112
                write_section_data(s, tss,
1113
                                   p, p_end - p, 1);
1114
            }
1115
        } else {
1116
            if (cc_ok) {
1117
                write_section_data(s, tss,
1118
                                   p, p_end - p, 0);
1119
            }
1120
        }
1121
    } else {
1122
        int ret;
1123
        // Note: The position here points actually behind the current packet.
1124
        if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1125
                                            pos - ts->raw_packet_size)) < 0)
1126
            return ret;
1127
    }
1128

    
1129
    return 0;
1130
}
1131

    
1132
/* XXX: try to find a better synchro over several packets (use
1133
   get_packet_size() ?) */
1134
static int mpegts_resync(ByteIOContext *pb)
1135
{
1136
    int c, i;
1137

    
1138
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1139
        c = url_fgetc(pb);
1140
        if (c < 0)
1141
            return -1;
1142
        if (c == 0x47) {
1143
            url_fseek(pb, -1, SEEK_CUR);
1144
            return 0;
1145
        }
1146
    }
1147
    /* no sync found */
1148
    return -1;
1149
}
1150

    
1151
/* return -1 if error or EOF. Return 0 if OK. */
1152
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1153
{
1154
    int skip, len;
1155

    
1156
    for(;;) {
1157
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1158
        if (len != TS_PACKET_SIZE)
1159
            return AVERROR(EIO);
1160
        /* check paquet sync byte */
1161
        if (buf[0] != 0x47) {
1162
            /* find a new packet start */
1163
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1164
            if (mpegts_resync(pb) < 0)
1165
                return AVERROR_INVALIDDATA;
1166
            else
1167
                continue;
1168
        } else {
1169
            skip = raw_packet_size - TS_PACKET_SIZE;
1170
            if (skip > 0)
1171
                url_fskip(pb, skip);
1172
            break;
1173
        }
1174
    }
1175
    return 0;
1176
}
1177

    
1178
static int handle_packets(MpegTSContext *ts, int nb_packets)
1179
{
1180
    AVFormatContext *s = ts->stream;
1181
    ByteIOContext *pb = s->pb;
1182
    uint8_t packet[TS_PACKET_SIZE];
1183
    int packet_num, ret;
1184

    
1185
    ts->stop_parse = 0;
1186
    packet_num = 0;
1187
    for(;;) {
1188
        if (ts->stop_parse>0)
1189
            break;
1190
        packet_num++;
1191
        if (nb_packets != 0 && packet_num >= nb_packets)
1192
            break;
1193
        ret = read_packet(pb, packet, ts->raw_packet_size);
1194
        if (ret != 0)
1195
            return ret;
1196
        ret = handle_packet(ts, packet);
1197
        if (ret != 0)
1198
            return ret;
1199
    }
1200
    return 0;
1201
}
1202

    
1203
static int mpegts_probe(AVProbeData *p)
1204
{
1205
#if 1
1206
    const int size= p->buf_size;
1207
    int score, fec_score, dvhs_score;
1208
    int check_count= size / TS_FEC_PACKET_SIZE;
1209
#define CHECK_COUNT 10
1210

    
1211
    if (check_count < CHECK_COUNT)
1212
        return -1;
1213

    
1214
    score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
1215
    dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1216
    fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1217
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1218

    
1219
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1220
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1221
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1222
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1223
    else                                    return -1;
1224
#else
1225
    /* only use the extension for safer guess */
1226
    if (match_ext(p->filename, "ts"))
1227
        return AVPROBE_SCORE_MAX;
1228
    else
1229
        return 0;
1230
#endif
1231
}
1232

    
1233
/* return the 90kHz PCR and the extension for the 27MHz PCR. return
1234
   (-1) if not available */
1235
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1236
                     const uint8_t *packet)
1237
{
1238
    int afc, len, flags;
1239
    const uint8_t *p;
1240
    unsigned int v;
1241

    
1242
    afc = (packet[3] >> 4) & 3;
1243
    if (afc <= 1)
1244
        return -1;
1245
    p = packet + 4;
1246
    len = p[0];
1247
    p++;
1248
    if (len == 0)
1249
        return -1;
1250
    flags = *p++;
1251
    len--;
1252
    if (!(flags & 0x10))
1253
        return -1;
1254
    if (len < 6)
1255
        return -1;
1256
    v = AV_RB32(p);
1257
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1258
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1259
    return 0;
1260
}
1261

    
1262
static int mpegts_read_header(AVFormatContext *s,
1263
                              AVFormatParameters *ap)
1264
{
1265
    MpegTSContext *ts = s->priv_data;
1266
    ByteIOContext *pb = s->pb;
1267
    uint8_t buf[5*1024];
1268
    int len;
1269
    int64_t pos;
1270

    
1271
    if (ap) {
1272
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1273
        if(ap->mpeg2ts_raw){
1274
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1275
            return -1;
1276
        }
1277
    }
1278

    
1279
    /* read the first 1024 bytes to get packet size */
1280
    pos = url_ftell(pb);
1281
    len = get_buffer(pb, buf, sizeof(buf));
1282
    if (len != sizeof(buf))
1283
        goto fail;
1284
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1285
    if (ts->raw_packet_size <= 0)
1286
        goto fail;
1287
    ts->stream = s;
1288
    ts->auto_guess = 0;
1289

    
1290
    if (s->iformat == &mpegts_demuxer) {
1291
        /* normal demux */
1292

    
1293
        /* first do a scaning to get all the services */
1294
        url_fseek(pb, pos, SEEK_SET);
1295

    
1296
        mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1297

    
1298
        mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1299

    
1300
        handle_packets(ts, s->probesize);
1301
        /* if could not find service, enable auto_guess */
1302

    
1303
        ts->auto_guess = 1;
1304

    
1305
        dprintf(ts->stream, "tuning done\n");
1306

    
1307
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1308
    } else {
1309
        AVStream *st;
1310
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1311
        int64_t pcrs[2], pcr_h;
1312
        int packet_count[2];
1313
        uint8_t packet[TS_PACKET_SIZE];
1314

    
1315
        /* only read packets */
1316

    
1317
        st = av_new_stream(s, 0);
1318
        if (!st)
1319
            goto fail;
1320
        av_set_pts_info(st, 60, 1, 27000000);
1321
        st->codec->codec_type = CODEC_TYPE_DATA;
1322
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1323

    
1324
        /* we iterate until we find two PCRs to estimate the bitrate */
1325
        pcr_pid = -1;
1326
        nb_pcrs = 0;
1327
        nb_packets = 0;
1328
        for(;;) {
1329
            ret = read_packet(s->pb, packet, ts->raw_packet_size);
1330
            if (ret < 0)
1331
                return -1;
1332
            pid = AV_RB16(packet + 1) & 0x1fff;
1333
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1334
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1335
                pcr_pid = pid;
1336
                packet_count[nb_pcrs] = nb_packets;
1337
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1338
                nb_pcrs++;
1339
                if (nb_pcrs >= 2)
1340
                    break;
1341
            }
1342
            nb_packets++;
1343
        }
1344

    
1345
        /* NOTE1: the bitrate is computed without the FEC */
1346
        /* NOTE2: it is only the bitrate of the start of the stream */
1347
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1348
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1349
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1350
        st->codec->bit_rate = s->bit_rate;
1351
        st->start_time = ts->cur_pcr;
1352
#if 0
1353
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1354
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1355
#endif
1356
    }
1357

    
1358
    url_fseek(pb, pos, SEEK_SET);
1359
    return 0;
1360
 fail:
1361
    return -1;
1362
}
1363

    
1364
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1365

    
1366
static int mpegts_raw_read_packet(AVFormatContext *s,
1367
                                  AVPacket *pkt)
1368
{
1369
    MpegTSContext *ts = s->priv_data;
1370
    int ret, i;
1371
    int64_t pcr_h, next_pcr_h, pos;
1372
    int pcr_l, next_pcr_l;
1373
    uint8_t pcr_buf[12];
1374

    
1375
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1376
        return AVERROR(ENOMEM);
1377
    pkt->pos= url_ftell(s->pb);
1378
    ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1379
    if (ret < 0) {
1380
        av_free_packet(pkt);
1381
        return ret;
1382
    }
1383
    if (ts->mpeg2ts_compute_pcr) {
1384
        /* compute exact PCR for each packet */
1385
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1386
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1387
            pos = url_ftell(s->pb);
1388
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1389
                url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1390
                get_buffer(s->pb, pcr_buf, 12);
1391
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1392
                    /* XXX: not precise enough */
1393
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1394
                        (i + 1);
1395
                    break;
1396
                }
1397
            }
1398
            url_fseek(s->pb, pos, SEEK_SET);
1399
            /* no next PCR found: we use previous increment */
1400
            ts->cur_pcr = pcr_h * 300 + pcr_l;
1401
        }
1402
        pkt->pts = ts->cur_pcr;
1403
        pkt->duration = ts->pcr_incr;
1404
        ts->cur_pcr += ts->pcr_incr;
1405
    }
1406
    pkt->stream_index = 0;
1407
    return 0;
1408
}
1409

    
1410
static int mpegts_read_packet(AVFormatContext *s,
1411
                              AVPacket *pkt)
1412
{
1413
    MpegTSContext *ts = s->priv_data;
1414
    int ret, i;
1415

    
1416
    if (url_ftell(s->pb) != ts->last_pos) {
1417
        /* seek detected, flush pes buffer */
1418
        for (i = 0; i < NB_PID_MAX; i++) {
1419
            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1420
                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1421
                av_freep(&pes->buffer);
1422
                pes->data_index = 0;
1423
                pes->state = MPEGTS_SKIP; /* skip until pes header */
1424
            }
1425
        }
1426
    }
1427

    
1428
    ts->pkt = pkt;
1429
    ret = handle_packets(ts, 0);
1430
    if (ret < 0) {
1431
        /* flush pes data left */
1432
        for (i = 0; i < NB_PID_MAX; i++) {
1433
            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1434
                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1435
                if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1436
                    new_pes_packet(pes, pkt);
1437
                    ret = 0;
1438
                    break;
1439
                }
1440
            }
1441
        }
1442
    }
1443

    
1444
    ts->last_pos = url_ftell(s->pb);
1445

    
1446
    return ret;
1447
}
1448

    
1449
static int mpegts_read_close(AVFormatContext *s)
1450
{
1451
    MpegTSContext *ts = s->priv_data;
1452
    int i;
1453

    
1454
    clear_programs(ts);
1455

    
1456
    for(i=0;i<NB_PID_MAX;i++)
1457
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1458

    
1459
    return 0;
1460
}
1461

    
1462
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1463
                              int64_t *ppos, int64_t pos_limit)
1464
{
1465
    MpegTSContext *ts = s->priv_data;
1466
    int64_t pos, timestamp;
1467
    uint8_t buf[TS_PACKET_SIZE];
1468
    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1469
    const int find_next= 1;
1470
    pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1471
    if (find_next) {
1472
        for(;;) {
1473
            url_fseek(s->pb, pos, SEEK_SET);
1474
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1475
                return AV_NOPTS_VALUE;
1476
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1477
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1478
                break;
1479
            }
1480
            pos += ts->raw_packet_size;
1481
        }
1482
    } else {
1483
        for(;;) {
1484
            pos -= ts->raw_packet_size;
1485
            if (pos < 0)
1486
                return AV_NOPTS_VALUE;
1487
            url_fseek(s->pb, pos, SEEK_SET);
1488
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1489
                return AV_NOPTS_VALUE;
1490
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1491
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1492
                break;
1493
            }
1494
        }
1495
    }
1496
    *ppos = pos;
1497

    
1498
    return timestamp;
1499
}
1500

    
1501
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1502
    MpegTSContext *ts = s->priv_data;
1503
    uint8_t buf[TS_PACKET_SIZE];
1504
    int64_t pos;
1505

    
1506
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1507
        return -1;
1508

    
1509
    pos= url_ftell(s->pb);
1510

    
1511
    for(;;) {
1512
        url_fseek(s->pb, pos, SEEK_SET);
1513
        if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1514
            return -1;
1515
//        pid = AV_RB16(buf + 1) & 0x1fff;
1516
        if(buf[1] & 0x40) break;
1517
        pos += ts->raw_packet_size;
1518
    }
1519
    url_fseek(s->pb, pos, SEEK_SET);
1520

    
1521
    return 0;
1522
}
1523

    
1524
/**************************************************************/
1525
/* parsing functions - called from other demuxers such as RTP */
1526

    
1527
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1528
{
1529
    MpegTSContext *ts;
1530

    
1531
    ts = av_mallocz(sizeof(MpegTSContext));
1532
    if (!ts)
1533
        return NULL;
1534
    /* no stream case, currently used by RTP */
1535
    ts->raw_packet_size = TS_PACKET_SIZE;
1536
    ts->stream = s;
1537
    ts->auto_guess = 1;
1538
    return ts;
1539
}
1540

    
1541
/* return the consumed length if a packet was output, or -1 if no
1542
   packet is output */
1543
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1544
                        const uint8_t *buf, int len)
1545
{
1546
    int len1;
1547

    
1548
    len1 = len;
1549
    ts->pkt = pkt;
1550
    ts->stop_parse = 0;
1551
    for(;;) {
1552
        if (ts->stop_parse>0)
1553
            break;
1554
        if (len < TS_PACKET_SIZE)
1555
            return -1;
1556
        if (buf[0] != 0x47) {
1557
            buf++;
1558
            len--;
1559
        } else {
1560
            handle_packet(ts, buf);
1561
            buf += TS_PACKET_SIZE;
1562
            len -= TS_PACKET_SIZE;
1563
        }
1564
    }
1565
    return len1 - len;
1566
}
1567

    
1568
void mpegts_parse_close(MpegTSContext *ts)
1569
{
1570
    int i;
1571

    
1572
    for(i=0;i<NB_PID_MAX;i++)
1573
        av_free(ts->pids[i]);
1574
    av_free(ts);
1575
}
1576

    
1577
AVInputFormat mpegts_demuxer = {
1578
    "mpegts",
1579
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1580
    sizeof(MpegTSContext),
1581
    mpegts_probe,
1582
    mpegts_read_header,
1583
    mpegts_read_packet,
1584
    mpegts_read_close,
1585
    read_seek,
1586
    mpegts_get_pcr,
1587
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1588
};
1589

    
1590
AVInputFormat mpegtsraw_demuxer = {
1591
    "mpegtsraw",
1592
    NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1593
    sizeof(MpegTSContext),
1594
    NULL,
1595
    mpegts_read_header,
1596
    mpegts_raw_read_packet,
1597
    mpegts_read_close,
1598
    read_seek,
1599
    mpegts_get_pcr,
1600
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1601
};