Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ 470bce2b

History | View | Annotate | Download (44.2 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
#include "libavutil/crc.h"
23
#include "avformat.h"
24
#include "mpegts.h"
25
#include "internal.h"
26

    
27
//#define DEBUG_SI
28
//#define DEBUG_SEEK
29

    
30
/* 1.0 second at 24Mbit/s */
31
#define MAX_SCAN_PACKETS 32000
32

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

    
38
typedef struct PESContext PESContext;
39

    
40
static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
41
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
42

    
43
enum MpegTSFilterType {
44
    MPEGTS_PES,
45
    MPEGTS_SECTION,
46
};
47

    
48
typedef struct MpegTSFilter MpegTSFilter;
49

    
50
typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start);
51

    
52
typedef struct MpegTSPESFilter {
53
    PESCallback *pes_cb;
54
    void *opaque;
55
} MpegTSPESFilter;
56

    
57
typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
58

    
59
typedef void SetServiceCallback(void *opaque, int ret);
60

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

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

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

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

    
94
    int pos47;
95

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

    
99
    /** compute exact PCR for each transport stream packet   */
100
    int mpeg2ts_compute_pcr;
101

    
102
    int64_t cur_pcr;    /**< used to estimate the exact PCR  */
103
    int pcr_incr;       /**< used to estimate the exact PCR  */
104

    
105
    /* data needed to handle file based ts */
106
    /** stop parsing loop                                    */
107
    int stop_parse;
108
    /** packet containing Audio/Video data                   */
109
    AVPacket *pkt;
110

    
111
    /******************************************/
112
    /* private mpegts data */
113
    /* scan context */
114
    /** structure to keep track of Program->pids mapping     */
115
    unsigned int nb_prg;
116
    struct Program *prg;
117

    
118

    
119
    /** filters for various streams specified by PMT + for the PAT and PMT */
120
    MpegTSFilter *pids[NB_PID_MAX];
121
};
122

    
123
/* TS stream handling */
124

    
125
enum MpegTSState {
126
    MPEGTS_HEADER = 0,
127
    MPEGTS_PESHEADER_FILL,
128
    MPEGTS_PAYLOAD,
129
    MPEGTS_SKIP,
130
};
131

    
132
/* enough for PES header + length */
133
#define PES_START_SIZE 9
134
#define MAX_PES_HEADER_SIZE (9 + 255)
135

    
136
struct PESContext {
137
    int pid;
138
    int pcr_pid; /**< if -1 then all packets containing PCR are considered */
139
    int stream_type;
140
    MpegTSContext *ts;
141
    AVFormatContext *stream;
142
    AVStream *st;
143
    enum MpegTSState state;
144
    /* used to get the format */
145
    int data_index;
146
    int total_size;
147
    int pes_header_size;
148
    int64_t pts, dts;
149
    uint8_t header[MAX_PES_HEADER_SIZE];
150
};
151

    
152
extern AVInputFormat mpegts_demuxer;
153

    
154
static void clear_program(MpegTSContext *ts, unsigned int programid)
155
{
156
    int i;
157

    
158
    for(i=0; i<ts->nb_prg; i++)
159
        if(ts->prg[i].id == programid)
160
            ts->prg[i].nb_pids = 0;
161
}
162

    
163
static void clear_programs(MpegTSContext *ts)
164
{
165
    av_freep(&ts->prg);
166
    ts->nb_prg=0;
167
}
168

    
169
static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
170
{
171
    struct Program *p;
172
    void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
173
    if(!tmp)
174
        return;
175
    ts->prg = tmp;
176
    p = &ts->prg[ts->nb_prg];
177
    p->id = programid;
178
    p->nb_pids = 0;
179
    ts->nb_prg++;
180
}
181

    
182
static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
183
{
184
    int i;
185
    struct Program *p = NULL;
186
    for(i=0; i<ts->nb_prg; i++) {
187
        if(ts->prg[i].id == programid) {
188
            p = &ts->prg[i];
189
            break;
190
        }
191
    }
192
    if(!p)
193
        return;
194

    
195
    if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
196
        return;
197
    p->pids[p->nb_pids++] = pid;
198
}
199

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

    
230
    return !used && discarded;
231
}
232

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

    
243
    if (is_start) {
244
        memcpy(tss->section_buf, buf, buf_size);
245
        tss->section_index = buf_size;
246
        tss->section_h_size = -1;
247
        tss->end_of_section_reached = 0;
248
    } else {
249
        if (tss->end_of_section_reached)
250
            return;
251
        len = 4096 - tss->section_index;
252
        if (buf_size < len)
253
            len = buf_size;
254
        memcpy(tss->section_buf + tss->section_index, buf, len);
255
        tss->section_index += len;
256
    }
257

    
258
    /* compute section length if possible */
259
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
260
        len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
261
        if (len > 4096)
262
            return;
263
        tss->section_h_size = len;
264
    }
265

    
266
    if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
267
        tss->end_of_section_reached = 1;
268
        if (!tss->check_crc ||
269
            av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
270
                   tss->section_buf, tss->section_h_size) == 0)
271
            tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
272
    }
273
}
274

    
275
static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
276
                                         SectionCallback *section_cb, void *opaque,
277
                                         int check_crc)
278

    
279
{
280
    MpegTSFilter *filter;
281
    MpegTSSectionFilter *sec;
282

    
283
#ifdef DEBUG_SI
284
    av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
285
#endif
286
    if (pid >= NB_PID_MAX || ts->pids[pid])
287
        return NULL;
288
    filter = av_mallocz(sizeof(MpegTSFilter));
289
    if (!filter)
290
        return NULL;
291
    ts->pids[pid] = filter;
292
    filter->type = MPEGTS_SECTION;
293
    filter->pid = pid;
294
    filter->last_cc = -1;
295
    sec = &filter->u.section_filter;
296
    sec->section_cb = section_cb;
297
    sec->opaque = opaque;
298
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
299
    sec->check_crc = check_crc;
300
    if (!sec->section_buf) {
301
        av_free(filter);
302
        return NULL;
303
    }
304
    return filter;
305
}
306

    
307
static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
308
                                     PESCallback *pes_cb,
309
                                     void *opaque)
310
{
311
    MpegTSFilter *filter;
312
    MpegTSPESFilter *pes;
313

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

    
329
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
330
{
331
    int pid;
332

    
333
    pid = filter->pid;
334
    if (filter->type == MPEGTS_SECTION)
335
        av_freep(&filter->u.section_filter.section_buf);
336

    
337
    av_free(filter);
338
    ts->pids[pid] = NULL;
339
}
340

    
341
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
342
    int stat[packet_size];
343
    int i;
344
    int x=0;
345
    int best_score=0;
346

    
347
    memset(stat, 0, packet_size*sizeof(int));
348

    
349
    for(x=i=0; i<size-3; i++){
350
        if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
351
            stat[x]++;
352
            if(stat[x] > best_score){
353
                best_score= stat[x];
354
                if(index) *index= x;
355
            }
356
        }
357

    
358
        x++;
359
        if(x == packet_size) x= 0;
360
    }
361

    
362
    return best_score;
363
}
364

    
365
/* autodetect fec presence. Must have at least 1024 bytes  */
366
static int get_packet_size(const uint8_t *buf, int size)
367
{
368
    int score, fec_score, dvhs_score;
369

    
370
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
371
        return -1;
372

    
373
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
374
    dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
375
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
376
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
377

    
378
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
379
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
380
    else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
381
    else                       return -1;
382
}
383

    
384
typedef struct SectionHeader {
385
    uint8_t tid;
386
    uint16_t id;
387
    uint8_t version;
388
    uint8_t sec_num;
389
    uint8_t last_sec_num;
390
} SectionHeader;
391

    
392
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
393
{
394
    const uint8_t *p;
395
    int c;
396

    
397
    p = *pp;
398
    if (p >= p_end)
399
        return -1;
400
    c = *p++;
401
    *pp = p;
402
    return c;
403
}
404

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

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

    
419
/* read and allocate a DVB string preceeded by its length */
420
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
421
{
422
    int len;
423
    const uint8_t *p;
424
    char *str;
425

    
426
    p = *pp;
427
    len = get8(&p, p_end);
428
    if (len < 0)
429
        return NULL;
430
    if ((p + len) > p_end)
431
        return NULL;
432
    str = av_malloc(len + 1);
433
    if (!str)
434
        return NULL;
435
    memcpy(str, p, len);
436
    str[len] = '\0';
437
    p += len;
438
    *pp = p;
439
    return str;
440
}
441

    
442
static int parse_section_header(SectionHeader *h,
443
                                const uint8_t **pp, const uint8_t *p_end)
444
{
445
    int val;
446

    
447
    val = get8(pp, p_end);
448
    if (val < 0)
449
        return -1;
450
    h->tid = val;
451
    *pp += 2;
452
    val = get16(pp, p_end);
453
    if (val < 0)
454
        return -1;
455
    h->id = val;
456
    val = get8(pp, p_end);
457
    if (val < 0)
458
        return -1;
459
    h->version = (val >> 1) & 0x1f;
460
    val = get8(pp, p_end);
461
    if (val < 0)
462
        return -1;
463
    h->sec_num = val;
464
    val = get8(pp, p_end);
465
    if (val < 0)
466
        return -1;
467
    h->last_sec_num = val;
468
    return 0;
469
}
470

    
471

    
472
static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
473
{
474
    MpegTSContext *ts = filter->u.section_filter.opaque;
475
    SectionHeader h1, *h = &h1;
476
    PESContext *pes;
477
    AVStream *st;
478
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
479
    int program_info_length, pcr_pid, pid, stream_type;
480
    int desc_list_len, desc_len, desc_tag;
481
    int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
482
    char language[4] = {0}; /* initialize to kill warnings */
483
    int has_hdmv_descr = 0;
484
    int has_dirac_descr = 0;
485

    
486
#ifdef DEBUG_SI
487
    av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
488
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
489
#endif
490
    p_end = section + section_len - 4;
491
    p = section;
492
    if (parse_section_header(h, &p, p_end) < 0)
493
        return;
494
#ifdef DEBUG_SI
495
    av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
496
           h->id, h->sec_num, h->last_sec_num);
497
#endif
498
    if (h->tid != PMT_TID)
499
        return;
500

    
501
    clear_program(ts, h->id);
502
    pcr_pid = get16(&p, p_end) & 0x1fff;
503
    if (pcr_pid < 0)
504
        return;
505
    add_pid_to_pmt(ts, h->id, pcr_pid);
506
#ifdef DEBUG_SI
507
    av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
508
#endif
509
    program_info_length = get16(&p, p_end) & 0xfff;
510
    if (program_info_length < 0)
511
        return;
512
    while(program_info_length >= 2) {
513
        uint8_t tag, len;
514
        tag = get8(&p, p_end);
515
        len = get8(&p, p_end);
516
        if(len > program_info_length - 2)
517
            //something else is broken, exit the program_descriptors_loop
518
            break;
519
        program_info_length -= len + 2;
520
        if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
521
            uint8_t bytes[4];
522
            bytes[0] = get8(&p, p_end);
523
            bytes[1] = get8(&p, p_end);
524
            bytes[2] = get8(&p, p_end);
525
            bytes[3] = get8(&p, p_end);
526
            len -= 4;
527
            if(bytes[0] == 'H' && bytes[1] == 'D' &&
528
               bytes[2] == 'M' && bytes[3] == 'V')
529
                has_hdmv_descr = 1;
530
        }
531
        p += len;
532
    }
533
    p += program_info_length;
534
    if (p >= p_end)
535
        return;
536
    for(;;) {
537
        language[0] = 0;
538
        st = 0;
539
        stream_type = get8(&p, p_end);
540
        if (stream_type < 0)
541
            break;
542
        pid = get16(&p, p_end) & 0x1fff;
543
        if (pid < 0)
544
            break;
545
        desc_list_len = get16(&p, p_end) & 0xfff;
546
        if (desc_list_len < 0)
547
            break;
548
        desc_list_end = p + desc_list_len;
549
        if (desc_list_end > p_end)
550
            break;
551
        for(;;) {
552
            desc_tag = get8(&p, desc_list_end);
553
            if (desc_tag < 0)
554
                break;
555
            if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
556
                if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
557
                    /*assume DVB AC-3 Audio*/
558
                    stream_type = STREAM_TYPE_AUDIO_AC3;
559
                } else if(desc_tag == 0x7B) {
560
                    /* DVB DTS audio */
561
                    stream_type = STREAM_TYPE_AUDIO_DTS;
562
                }
563
            }
564
            desc_len = get8(&p, desc_list_end);
565
            desc_end = p + desc_len;
566
            if (desc_end > desc_list_end)
567
                break;
568
#ifdef DEBUG_SI
569
            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
570
                   desc_tag, desc_len);
571
#endif
572
            switch(desc_tag) {
573
            case DVB_SUBT_DESCID:
574
                if (stream_type == STREAM_TYPE_PRIVATE_DATA)
575
                    stream_type = STREAM_TYPE_SUBTITLE_DVB;
576

    
577
                language[0] = get8(&p, desc_end);
578
                language[1] = get8(&p, desc_end);
579
                language[2] = get8(&p, desc_end);
580
                language[3] = 0;
581
                get8(&p, desc_end);
582
                comp_page = get16(&p, desc_end);
583
                anc_page = get16(&p, desc_end);
584

    
585
                break;
586
            case 0x0a: /* ISO 639 language descriptor */
587
                language[0] = get8(&p, desc_end);
588
                language[1] = get8(&p, desc_end);
589
                language[2] = get8(&p, desc_end);
590
                language[3] = 0;
591
                break;
592
            case REGISTRATION_DESCRIPTOR: /*MPEG-2 Registration descriptor */
593
                {
594
                    uint8_t bytes[4];
595
                    bytes[0] = get8(&p, desc_end);
596
                    bytes[1] = get8(&p, desc_end);
597
                    bytes[2] = get8(&p, desc_end);
598
                    bytes[3] = get8(&p, desc_end);
599
                    if(bytes[0] == 'd' && bytes[1] == 'r' &&
600
                       bytes[2] == 'a' && bytes[3] == 'c')
601
                        has_dirac_descr = 1;
602
                    break;
603
                }
604
            default:
605
                break;
606
            }
607
            p = desc_end;
608
        }
609
        p = desc_list_end;
610

    
611
#ifdef DEBUG_SI
612
        av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
613
               stream_type, pid);
614
#endif
615

    
616
        /* now create ffmpeg stream */
617
        switch(stream_type) {
618
        case STREAM_TYPE_AUDIO_MPEG1:
619
        case STREAM_TYPE_AUDIO_MPEG2:
620
        case STREAM_TYPE_VIDEO_MPEG1:
621
        case STREAM_TYPE_VIDEO_MPEG2:
622
        case STREAM_TYPE_VIDEO_MPEG4:
623
        case STREAM_TYPE_VIDEO_H264:
624
        case STREAM_TYPE_VIDEO_VC1:
625
        case STREAM_TYPE_VIDEO_DIRAC:
626
        case STREAM_TYPE_AUDIO_AAC:
627
        case STREAM_TYPE_AUDIO_AC3:
628
        case STREAM_TYPE_AUDIO_DTS:
629
        case STREAM_TYPE_AUDIO_HDMV_DTS:
630
        case STREAM_TYPE_SUBTITLE_DVB:
631
            if((stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
632
            || (stream_type == STREAM_TYPE_VIDEO_DIRAC    && !has_dirac_descr))
633
                break;
634
            if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
635
                pes= ts->pids[pid]->u.pes_filter.opaque;
636
                st= pes->st;
637
            }else{
638
                if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
639
                pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
640
                if (pes)
641
                    st = new_pes_av_stream(pes, 0);
642
            }
643
            add_pid_to_pmt(ts, h->id, pid);
644
            if(st)
645
                av_program_add_stream_index(ts->stream, h->id, st->index);
646
            break;
647
        default:
648
            /* we ignore the other streams */
649
            break;
650
        }
651

    
652
        if (st) {
653
            if (language[0] != 0) {
654
                memcpy(st->language, language, 4);
655
            }
656

    
657
            if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
658
                st->codec->sub_id = (anc_page << 16) | comp_page;
659
            }
660
        }
661
    }
662
    /* all parameters are there */
663
    ts->stop_parse++;
664
    mpegts_close_filter(ts, filter);
665
}
666

    
667
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
668
{
669
    MpegTSContext *ts = filter->u.section_filter.opaque;
670
    SectionHeader h1, *h = &h1;
671
    const uint8_t *p, *p_end;
672
    int sid, pmt_pid;
673

    
674
#ifdef DEBUG_SI
675
    av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
676
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
677
#endif
678
    p_end = section + section_len - 4;
679
    p = section;
680
    if (parse_section_header(h, &p, p_end) < 0)
681
        return;
682
    if (h->tid != PAT_TID)
683
        return;
684

    
685
    clear_programs(ts);
686
    for(;;) {
687
        sid = get16(&p, p_end);
688
        if (sid < 0)
689
            break;
690
        pmt_pid = get16(&p, p_end) & 0x1fff;
691
        if (pmt_pid < 0)
692
            break;
693
#ifdef DEBUG_SI
694
        av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
695
#endif
696
        if (sid == 0x0000) {
697
            /* NIT info */
698
        } else {
699
            av_new_program(ts->stream, sid);
700
            ts->stop_parse--;
701
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
702
            add_pat_entry(ts, sid);
703
            add_pid_to_pmt(ts, sid, 0); //add pat pid to program
704
            add_pid_to_pmt(ts, sid, pmt_pid);
705
        }
706
    }
707
    /* not found */
708
    ts->stop_parse++;
709

    
710
    mpegts_close_filter(ts, filter);
711
}
712

    
713
static void mpegts_set_service(MpegTSContext *ts)
714
{
715
    mpegts_open_section_filter(ts, PAT_PID,
716
                                                pat_cb, ts, 1);
717
}
718

    
719
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
720
{
721
    MpegTSContext *ts = filter->u.section_filter.opaque;
722
    SectionHeader h1, *h = &h1;
723
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
724
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
725
    char *name, *provider_name;
726

    
727
#ifdef DEBUG_SI
728
    av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
729
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
730
#endif
731

    
732
    p_end = section + section_len - 4;
733
    p = section;
734
    if (parse_section_header(h, &p, p_end) < 0)
735
        return;
736
    if (h->tid != SDT_TID)
737
        return;
738
    onid = get16(&p, p_end);
739
    if (onid < 0)
740
        return;
741
    val = get8(&p, p_end);
742
    if (val < 0)
743
        return;
744
    for(;;) {
745
        sid = get16(&p, p_end);
746
        if (sid < 0)
747
            break;
748
        val = get8(&p, p_end);
749
        if (val < 0)
750
            break;
751
        desc_list_len = get16(&p, p_end) & 0xfff;
752
        if (desc_list_len < 0)
753
            break;
754
        desc_list_end = p + desc_list_len;
755
        if (desc_list_end > p_end)
756
            break;
757
        for(;;) {
758
            desc_tag = get8(&p, desc_list_end);
759
            if (desc_tag < 0)
760
                break;
761
            desc_len = get8(&p, desc_list_end);
762
            desc_end = p + desc_len;
763
            if (desc_end > desc_list_end)
764
                break;
765
#ifdef DEBUG_SI
766
            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
767
                   desc_tag, desc_len);
768
#endif
769
            switch(desc_tag) {
770
            case 0x48:
771
                service_type = get8(&p, p_end);
772
                if (service_type < 0)
773
                    break;
774
                provider_name = getstr8(&p, p_end);
775
                if (!provider_name)
776
                    break;
777
                name = getstr8(&p, p_end);
778
                if (name) {
779
                    AVProgram *program = av_new_program(ts->stream, sid);
780
                    if(program)
781
                        av_set_program_name(program, provider_name, name);
782
                }
783
                av_free(name);
784
                av_free(provider_name);
785
                break;
786
            default:
787
                break;
788
            }
789
            p = desc_end;
790
        }
791
        p = desc_list_end;
792
    }
793
}
794

    
795
/* scan services in a transport stream by looking at the SDT */
796
static void mpegts_scan_sdt(MpegTSContext *ts)
797
{
798
    mpegts_open_section_filter(ts, SDT_PID,
799
                                                sdt_cb, ts, 1);
800
}
801

    
802
static int64_t get_pts(const uint8_t *p)
803
{
804
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
805
    pts |= (AV_RB16(p + 1) >> 1) << 15;
806
    pts |=  AV_RB16(p + 3) >> 1;
807
    return pts;
808
}
809

    
810
/* return non zero if a packet could be constructed */
811
static void mpegts_push_data(MpegTSFilter *filter,
812
                             const uint8_t *buf, int buf_size, int is_start)
813
{
814
    PESContext *pes = filter->u.pes_filter.opaque;
815
    MpegTSContext *ts = pes->ts;
816
    const uint8_t *p;
817
    int len, code;
818

    
819
    if(!ts->pkt)
820
        return;
821

    
822
    if (is_start) {
823
        pes->state = MPEGTS_HEADER;
824
        pes->data_index = 0;
825
    }
826
    p = buf;
827
    while (buf_size > 0) {
828
        switch(pes->state) {
829
        case MPEGTS_HEADER:
830
            len = PES_START_SIZE - pes->data_index;
831
            if (len > buf_size)
832
                len = buf_size;
833
            memcpy(pes->header + pes->data_index, p, len);
834
            pes->data_index += len;
835
            p += len;
836
            buf_size -= len;
837
            if (pes->data_index == PES_START_SIZE) {
838
                /* we got all the PES or section header. We can now
839
                   decide */
840
#if 0
841
                av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
842
#endif
843
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
844
                    pes->header[2] == 0x01) {
845
                    /* it must be an mpeg2 PES stream */
846
                    code = pes->header[3] | 0x100;
847
                    if (!((code >= 0x1c0 && code <= 0x1df) ||
848
                          (code >= 0x1e0 && code <= 0x1ef) ||
849
                          (code == 0x1bd) || (code == 0x1fd)))
850
                        goto skip;
851
                    if (!pes->st) {
852
                        /* allocate stream */
853
                        new_pes_av_stream(pes, code);
854
                    }
855
                    pes->state = MPEGTS_PESHEADER_FILL;
856
                    pes->total_size = AV_RB16(pes->header + 4);
857
                    /* NOTE: a zero total size means the PES size is
858
                       unbounded */
859
                    if (pes->total_size)
860
                        pes->total_size += 6;
861
                    pes->pes_header_size = pes->header[8] + 9;
862
                } else {
863
                    /* otherwise, it should be a table */
864
                    /* skip packet */
865
                skip:
866
                    pes->state = MPEGTS_SKIP;
867
                    continue;
868
                }
869
            }
870
            break;
871
            /**********************************************/
872
            /* PES packing parsing */
873
        case MPEGTS_PESHEADER_FILL:
874
            len = pes->pes_header_size - pes->data_index;
875
            if (len > buf_size)
876
                len = buf_size;
877
            memcpy(pes->header + pes->data_index, p, len);
878
            pes->data_index += len;
879
            p += len;
880
            buf_size -= len;
881
            if (pes->data_index == pes->pes_header_size) {
882
                const uint8_t *r;
883
                unsigned int flags;
884

    
885
                flags = pes->header[7];
886
                r = pes->header + 9;
887
                pes->pts = AV_NOPTS_VALUE;
888
                pes->dts = AV_NOPTS_VALUE;
889
                if ((flags & 0xc0) == 0x80) {
890
                    pes->pts = get_pts(r);
891
                    r += 5;
892
                } else if ((flags & 0xc0) == 0xc0) {
893
                    pes->pts = get_pts(r);
894
                    r += 5;
895
                    pes->dts = get_pts(r);
896
                    r += 5;
897
                }
898
                /* we got the full header. We parse it and get the payload */
899
                pes->state = MPEGTS_PAYLOAD;
900
            }
901
            break;
902
        case MPEGTS_PAYLOAD:
903
            if (pes->total_size) {
904
                len = pes->total_size - pes->data_index;
905
                if (len > buf_size)
906
                    len = buf_size;
907
            } else {
908
                len = buf_size;
909
            }
910
            if (len > 0) {
911
                AVPacket *pkt = ts->pkt;
912
                if (pes->st && av_new_packet(pkt, len) == 0) {
913
                    memcpy(pkt->data, p, len);
914
                    pkt->stream_index = pes->st->index;
915
                    pkt->pts = pes->pts;
916
                    pkt->dts = pes->dts;
917
                    /* reset pts values */
918
                    pes->pts = AV_NOPTS_VALUE;
919
                    pes->dts = AV_NOPTS_VALUE;
920
                    ts->stop_parse = 1;
921
                    return;
922
                }
923
            }
924
            buf_size = 0;
925
            break;
926
        case MPEGTS_SKIP:
927
            buf_size = 0;
928
            break;
929
        }
930
    }
931
}
932

    
933
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
934
{
935
    AVStream *st;
936
    enum CodecID codec_id;
937
    enum CodecType codec_type;
938

    
939
    switch(pes->stream_type){
940
    case STREAM_TYPE_AUDIO_MPEG1:
941
    case STREAM_TYPE_AUDIO_MPEG2:
942
        codec_type = CODEC_TYPE_AUDIO;
943
        codec_id = CODEC_ID_MP3;
944
        break;
945
    case STREAM_TYPE_VIDEO_MPEG1:
946
    case STREAM_TYPE_VIDEO_MPEG2:
947
        codec_type = CODEC_TYPE_VIDEO;
948
        codec_id = CODEC_ID_MPEG2VIDEO;
949
        break;
950
    case STREAM_TYPE_VIDEO_MPEG4:
951
        codec_type = CODEC_TYPE_VIDEO;
952
        codec_id = CODEC_ID_MPEG4;
953
        break;
954
    case STREAM_TYPE_VIDEO_H264:
955
        codec_type = CODEC_TYPE_VIDEO;
956
        codec_id = CODEC_ID_H264;
957
        break;
958
    case STREAM_TYPE_VIDEO_VC1:
959
        codec_type = CODEC_TYPE_VIDEO;
960
        codec_id = CODEC_ID_VC1;
961
        break;
962
    case STREAM_TYPE_VIDEO_DIRAC:
963
        codec_type = CODEC_TYPE_VIDEO;
964
        codec_id = CODEC_ID_DIRAC;
965
        break;
966
    case STREAM_TYPE_AUDIO_AAC:
967
        codec_type = CODEC_TYPE_AUDIO;
968
        codec_id = CODEC_ID_AAC;
969
        break;
970
    case STREAM_TYPE_AUDIO_AC3:
971
        codec_type = CODEC_TYPE_AUDIO;
972
        codec_id = CODEC_ID_AC3;
973
        break;
974
    case STREAM_TYPE_AUDIO_DTS:
975
    case STREAM_TYPE_AUDIO_HDMV_DTS:
976
        codec_type = CODEC_TYPE_AUDIO;
977
        codec_id = CODEC_ID_DTS;
978
        break;
979
    case STREAM_TYPE_SUBTITLE_DVB:
980
        codec_type = CODEC_TYPE_SUBTITLE;
981
        codec_id = CODEC_ID_DVB_SUBTITLE;
982
        break;
983
    default:
984
        if (code >= 0x1c0 && code <= 0x1df) {
985
            codec_type = CODEC_TYPE_AUDIO;
986
            codec_id = CODEC_ID_MP2;
987
        } else if (code == 0x1bd) {
988
            codec_type = CODEC_TYPE_AUDIO;
989
            codec_id = CODEC_ID_AC3;
990
        } else {
991
            codec_type = CODEC_TYPE_VIDEO;
992
            codec_id = CODEC_ID_PROBE;
993
        }
994
        break;
995
    }
996
    st = av_new_stream(pes->stream, pes->pid);
997
    if (st) {
998
        av_set_pts_info(st, 33, 1, 90000);
999
        st->priv_data = pes;
1000
        st->codec->codec_type = codec_type;
1001
        st->codec->codec_id = codec_id;
1002
        st->need_parsing = AVSTREAM_PARSE_FULL;
1003
        pes->st = st;
1004
    }
1005
    return st;
1006
}
1007

    
1008

    
1009
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1010
{
1011
    MpegTSFilter *tss;
1012
    PESContext *pes;
1013

    
1014
    /* if no pid found, then add a pid context */
1015
    pes = av_mallocz(sizeof(PESContext));
1016
    if (!pes)
1017
        return 0;
1018
    pes->ts = ts;
1019
    pes->stream = ts->stream;
1020
    pes->pid = pid;
1021
    pes->pcr_pid = pcr_pid;
1022
    pes->stream_type = stream_type;
1023
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1024
    if (!tss) {
1025
        av_free(pes);
1026
        return 0;
1027
    }
1028
    return pes;
1029
}
1030

    
1031
/* handle one TS packet */
1032
static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1033
{
1034
    AVFormatContext *s = ts->stream;
1035
    MpegTSFilter *tss;
1036
    int len, pid, cc, cc_ok, afc, is_start;
1037
    const uint8_t *p, *p_end;
1038

    
1039
    pid = AV_RB16(packet + 1) & 0x1fff;
1040
    if(pid && discard_pid(ts, pid))
1041
        return;
1042
    is_start = packet[1] & 0x40;
1043
    tss = ts->pids[pid];
1044
    if (ts->auto_guess && tss == NULL && is_start) {
1045
        add_pes_stream(ts, pid, -1, 0);
1046
        tss = ts->pids[pid];
1047
    }
1048
    if (!tss)
1049
        return;
1050

    
1051
    /* continuity check (currently not used) */
1052
    cc = (packet[3] & 0xf);
1053
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1054
    tss->last_cc = cc;
1055

    
1056
    /* skip adaptation field */
1057
    afc = (packet[3] >> 4) & 3;
1058
    p = packet + 4;
1059
    if (afc == 0) /* reserved value */
1060
        return;
1061
    if (afc == 2) /* adaptation field only */
1062
        return;
1063
    if (afc == 3) {
1064
        /* skip adapation field */
1065
        p += p[0] + 1;
1066
    }
1067
    /* if past the end of packet, ignore */
1068
    p_end = packet + TS_PACKET_SIZE;
1069
    if (p >= p_end)
1070
        return;
1071

    
1072
    ts->pos47= url_ftell(ts->stream->pb) % ts->raw_packet_size;
1073

    
1074
    if (tss->type == MPEGTS_SECTION) {
1075
        if (is_start) {
1076
            /* pointer field present */
1077
            len = *p++;
1078
            if (p + len > p_end)
1079
                return;
1080
            if (len && cc_ok) {
1081
                /* write remaining section bytes */
1082
                write_section_data(s, tss,
1083
                                   p, len, 0);
1084
                /* check whether filter has been closed */
1085
                if (!ts->pids[pid])
1086
                    return;
1087
            }
1088
            p += len;
1089
            if (p < p_end) {
1090
                write_section_data(s, tss,
1091
                                   p, p_end - p, 1);
1092
            }
1093
        } else {
1094
            if (cc_ok) {
1095
                write_section_data(s, tss,
1096
                                   p, p_end - p, 0);
1097
            }
1098
        }
1099
    } else {
1100
        tss->u.pes_filter.pes_cb(tss,
1101
                                 p, p_end - p, is_start);
1102
    }
1103
}
1104

    
1105
/* XXX: try to find a better synchro over several packets (use
1106
   get_packet_size() ?) */
1107
static int mpegts_resync(ByteIOContext *pb)
1108
{
1109
    int c, i;
1110

    
1111
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1112
        c = url_fgetc(pb);
1113
        if (c < 0)
1114
            return -1;
1115
        if (c == 0x47) {
1116
            url_fseek(pb, -1, SEEK_CUR);
1117
            return 0;
1118
        }
1119
    }
1120
    /* no sync found */
1121
    return -1;
1122
}
1123

    
1124
/* return -1 if error or EOF. Return 0 if OK. */
1125
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1126
{
1127
    int skip, len;
1128

    
1129
    for(;;) {
1130
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1131
        if (len != TS_PACKET_SIZE)
1132
            return AVERROR(EIO);
1133
        /* check paquet sync byte */
1134
        if (buf[0] != 0x47) {
1135
            /* find a new packet start */
1136
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1137
            if (mpegts_resync(pb) < 0)
1138
                return AVERROR_INVALIDDATA;
1139
            else
1140
                continue;
1141
        } else {
1142
            skip = raw_packet_size - TS_PACKET_SIZE;
1143
            if (skip > 0)
1144
                url_fskip(pb, skip);
1145
            break;
1146
        }
1147
    }
1148
    return 0;
1149
}
1150

    
1151
static int handle_packets(MpegTSContext *ts, int nb_packets)
1152
{
1153
    AVFormatContext *s = ts->stream;
1154
    ByteIOContext *pb = s->pb;
1155
    uint8_t packet[TS_PACKET_SIZE];
1156
    int packet_num, ret;
1157

    
1158
    ts->stop_parse = 0;
1159
    packet_num = 0;
1160
    for(;;) {
1161
        if (ts->stop_parse>0)
1162
            break;
1163
        packet_num++;
1164
        if (nb_packets != 0 && packet_num >= nb_packets)
1165
            break;
1166
        ret = read_packet(pb, packet, ts->raw_packet_size);
1167
        if (ret != 0)
1168
            return ret;
1169
        handle_packet(ts, packet);
1170
    }
1171
    return 0;
1172
}
1173

    
1174
static int mpegts_probe(AVProbeData *p)
1175
{
1176
#if 1
1177
    const int size= p->buf_size;
1178
    int score, fec_score, dvhs_score;
1179
#define CHECK_COUNT 10
1180

    
1181
    if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1182
        return -1;
1183

    
1184
    score    = analyze(p->buf, TS_PACKET_SIZE    *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1185
    dvhs_score  = analyze(p->buf, TS_DVHS_PACKET_SIZE    *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1186
    fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1187
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1188

    
1189
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1190
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1191
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1192
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1193
    else                                    return -1;
1194
#else
1195
    /* only use the extension for safer guess */
1196
    if (match_ext(p->filename, "ts"))
1197
        return AVPROBE_SCORE_MAX;
1198
    else
1199
        return 0;
1200
#endif
1201
}
1202

    
1203
/* return the 90kHz PCR and the extension for the 27MHz PCR. return
1204
   (-1) if not available */
1205
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1206
                     const uint8_t *packet)
1207
{
1208
    int afc, len, flags;
1209
    const uint8_t *p;
1210
    unsigned int v;
1211

    
1212
    afc = (packet[3] >> 4) & 3;
1213
    if (afc <= 1)
1214
        return -1;
1215
    p = packet + 4;
1216
    len = p[0];
1217
    p++;
1218
    if (len == 0)
1219
        return -1;
1220
    flags = *p++;
1221
    len--;
1222
    if (!(flags & 0x10))
1223
        return -1;
1224
    if (len < 6)
1225
        return -1;
1226
    v = AV_RB32(p);
1227
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1228
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1229
    return 0;
1230
}
1231

    
1232
static int mpegts_read_header(AVFormatContext *s,
1233
                              AVFormatParameters *ap)
1234
{
1235
    MpegTSContext *ts = s->priv_data;
1236
    ByteIOContext *pb = s->pb;
1237
    uint8_t buf[1024];
1238
    int len;
1239
    int64_t pos;
1240

    
1241
    if (ap) {
1242
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1243
        if(ap->mpeg2ts_raw){
1244
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1245
            return -1;
1246
        }
1247
    }
1248

    
1249
    /* read the first 1024 bytes to get packet size */
1250
    pos = url_ftell(pb);
1251
    len = get_buffer(pb, buf, sizeof(buf));
1252
    if (len != sizeof(buf))
1253
        goto fail;
1254
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1255
    if (ts->raw_packet_size <= 0)
1256
        goto fail;
1257
    ts->stream = s;
1258
    ts->auto_guess = 0;
1259

    
1260
    if (s->iformat == &mpegts_demuxer) {
1261
        /* normal demux */
1262

    
1263
        /* first do a scaning to get all the services */
1264
        url_fseek(pb, pos, SEEK_SET);
1265
        mpegts_scan_sdt(ts);
1266

    
1267
        mpegts_set_service(ts);
1268

    
1269
        handle_packets(ts, s->probesize);
1270
        /* if could not find service, enable auto_guess */
1271

    
1272
        ts->auto_guess = 1;
1273

    
1274
#ifdef DEBUG_SI
1275
        av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1276
#endif
1277
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1278
    } else {
1279
        AVStream *st;
1280
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1281
        int64_t pcrs[2], pcr_h;
1282
        int packet_count[2];
1283
        uint8_t packet[TS_PACKET_SIZE];
1284

    
1285
        /* only read packets */
1286

    
1287
        st = av_new_stream(s, 0);
1288
        if (!st)
1289
            goto fail;
1290
        av_set_pts_info(st, 60, 1, 27000000);
1291
        st->codec->codec_type = CODEC_TYPE_DATA;
1292
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1293

    
1294
        /* we iterate until we find two PCRs to estimate the bitrate */
1295
        pcr_pid = -1;
1296
        nb_pcrs = 0;
1297
        nb_packets = 0;
1298
        for(;;) {
1299
            ret = read_packet(s->pb, packet, ts->raw_packet_size);
1300
            if (ret < 0)
1301
                return -1;
1302
            pid = AV_RB16(packet + 1) & 0x1fff;
1303
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1304
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1305
                pcr_pid = pid;
1306
                packet_count[nb_pcrs] = nb_packets;
1307
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1308
                nb_pcrs++;
1309
                if (nb_pcrs >= 2)
1310
                    break;
1311
            }
1312
            nb_packets++;
1313
        }
1314

    
1315
        /* NOTE1: the bitrate is computed without the FEC */
1316
        /* NOTE2: it is only the bitrate of the start of the stream */
1317
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1318
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1319
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1320
        st->codec->bit_rate = s->bit_rate;
1321
        st->start_time = ts->cur_pcr;
1322
#if 0
1323
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1324
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1325
#endif
1326
    }
1327

    
1328
    url_fseek(pb, pos, SEEK_SET);
1329
    return 0;
1330
 fail:
1331
    return -1;
1332
}
1333

    
1334
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1335

    
1336
static int mpegts_raw_read_packet(AVFormatContext *s,
1337
                                  AVPacket *pkt)
1338
{
1339
    MpegTSContext *ts = s->priv_data;
1340
    int ret, i;
1341
    int64_t pcr_h, next_pcr_h, pos;
1342
    int pcr_l, next_pcr_l;
1343
    uint8_t pcr_buf[12];
1344

    
1345
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1346
        return AVERROR(ENOMEM);
1347
    pkt->pos= url_ftell(s->pb);
1348
    ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1349
    if (ret < 0) {
1350
        av_free_packet(pkt);
1351
        return ret;
1352
    }
1353
    if (ts->mpeg2ts_compute_pcr) {
1354
        /* compute exact PCR for each packet */
1355
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1356
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1357
            pos = url_ftell(s->pb);
1358
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1359
                url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1360
                get_buffer(s->pb, pcr_buf, 12);
1361
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1362
                    /* XXX: not precise enough */
1363
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1364
                        (i + 1);
1365
                    break;
1366
                }
1367
            }
1368
            url_fseek(s->pb, pos, SEEK_SET);
1369
            /* no next PCR found: we use previous increment */
1370
            ts->cur_pcr = pcr_h * 300 + pcr_l;
1371
        }
1372
        pkt->pts = ts->cur_pcr;
1373
        pkt->duration = ts->pcr_incr;
1374
        ts->cur_pcr += ts->pcr_incr;
1375
    }
1376
    pkt->stream_index = 0;
1377
    return 0;
1378
}
1379

    
1380
static int mpegts_read_packet(AVFormatContext *s,
1381
                              AVPacket *pkt)
1382
{
1383
    MpegTSContext *ts = s->priv_data;
1384

    
1385
    ts->pkt = pkt;
1386
    return handle_packets(ts, 0);
1387
}
1388

    
1389
static int mpegts_read_close(AVFormatContext *s)
1390
{
1391
    MpegTSContext *ts = s->priv_data;
1392
    int i;
1393

    
1394
    clear_programs(ts);
1395

    
1396
    for(i=0;i<NB_PID_MAX;i++)
1397
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1398

    
1399
    return 0;
1400
}
1401

    
1402
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1403
                              int64_t *ppos, int64_t pos_limit)
1404
{
1405
    MpegTSContext *ts = s->priv_data;
1406
    int64_t pos, timestamp;
1407
    uint8_t buf[TS_PACKET_SIZE];
1408
    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1409
    const int find_next= 1;
1410
    pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1411
    if (find_next) {
1412
        for(;;) {
1413
            url_fseek(s->pb, pos, SEEK_SET);
1414
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1415
                return AV_NOPTS_VALUE;
1416
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1417
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1418
                break;
1419
            }
1420
            pos += ts->raw_packet_size;
1421
        }
1422
    } else {
1423
        for(;;) {
1424
            pos -= ts->raw_packet_size;
1425
            if (pos < 0)
1426
                return AV_NOPTS_VALUE;
1427
            url_fseek(s->pb, pos, SEEK_SET);
1428
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1429
                return AV_NOPTS_VALUE;
1430
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1431
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1432
                break;
1433
            }
1434
        }
1435
    }
1436
    *ppos = pos;
1437

    
1438
    return timestamp;
1439
}
1440

    
1441
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1442
    MpegTSContext *ts = s->priv_data;
1443
    uint8_t buf[TS_PACKET_SIZE];
1444
    int64_t pos;
1445

    
1446
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1447
        return -1;
1448

    
1449
    pos= url_ftell(s->pb);
1450

    
1451
    for(;;) {
1452
        url_fseek(s->pb, pos, SEEK_SET);
1453
        if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1454
            return -1;
1455
//        pid = AV_RB16(buf + 1) & 0x1fff;
1456
        if(buf[1] & 0x40) break;
1457
        pos += ts->raw_packet_size;
1458
    }
1459
    url_fseek(s->pb, pos, SEEK_SET);
1460

    
1461
    return 0;
1462
}
1463

    
1464
/**************************************************************/
1465
/* parsing functions - called from other demuxers such as RTP */
1466

    
1467
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1468
{
1469
    MpegTSContext *ts;
1470

    
1471
    ts = av_mallocz(sizeof(MpegTSContext));
1472
    if (!ts)
1473
        return NULL;
1474
    /* no stream case, currently used by RTP */
1475
    ts->raw_packet_size = TS_PACKET_SIZE;
1476
    ts->stream = s;
1477
    ts->auto_guess = 1;
1478
    return ts;
1479
}
1480

    
1481
/* return the consumed length if a packet was output, or -1 if no
1482
   packet is output */
1483
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1484
                        const uint8_t *buf, int len)
1485
{
1486
    int len1;
1487

    
1488
    len1 = len;
1489
    ts->pkt = pkt;
1490
    ts->stop_parse = 0;
1491
    for(;;) {
1492
        if (ts->stop_parse>0)
1493
            break;
1494
        if (len < TS_PACKET_SIZE)
1495
            return -1;
1496
        if (buf[0] != 0x47) {
1497
            buf++;
1498
            len--;
1499
        } else {
1500
            handle_packet(ts, buf);
1501
            buf += TS_PACKET_SIZE;
1502
            len -= TS_PACKET_SIZE;
1503
        }
1504
    }
1505
    return len1 - len;
1506
}
1507

    
1508
void mpegts_parse_close(MpegTSContext *ts)
1509
{
1510
    int i;
1511

    
1512
    for(i=0;i<NB_PID_MAX;i++)
1513
        av_free(ts->pids[i]);
1514
    av_free(ts);
1515
}
1516

    
1517
AVInputFormat mpegts_demuxer = {
1518
    "mpegts",
1519
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1520
    sizeof(MpegTSContext),
1521
    mpegts_probe,
1522
    mpegts_read_header,
1523
    mpegts_read_packet,
1524
    mpegts_read_close,
1525
    read_seek,
1526
    mpegts_get_pcr,
1527
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1528
};
1529

    
1530
AVInputFormat mpegtsraw_demuxer = {
1531
    "mpegtsraw",
1532
    NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1533
    sizeof(MpegTSContext),
1534
    NULL,
1535
    mpegts_read_header,
1536
    mpegts_raw_read_packet,
1537
    mpegts_read_close,
1538
    read_seek,
1539
    mpegts_get_pcr,
1540
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1541
};