Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ dcd913d9

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

    
28
//#define DEBUG_SI
29
//#define DEBUG_SEEK
30

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

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

    
39
typedef struct PESContext PESContext;
40

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

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

    
49
typedef struct MpegTSFilter MpegTSFilter;
50

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

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

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

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

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

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

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

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

    
95
    int pos47;
96

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

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

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

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

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

    
119

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

    
124
/* TS stream handling */
125

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

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

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

    
153
extern AVInputFormat mpegts_demuxer;
154

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

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

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

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

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

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

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

    
231
    return !used && discarded;
232
}
233

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

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

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

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

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

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

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

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

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

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

    
334
    pid = filter->pid;
335
    if (filter->type == MPEGTS_SECTION)
336
        av_freep(&filter->u.section_filter.section_buf);
337
    else if (filter->type == MPEGTS_PES) {
338
        /* referenced private data will be freed later in
339
         * av_close_input_stream */
340
        if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
341
            av_freep(&filter->u.pes_filter.opaque);
342
        }
343
    }
344

    
345
    av_free(filter);
346
    ts->pids[pid] = NULL;
347
}
348

    
349
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
350
    int stat[packet_size];
351
    int i;
352
    int x=0;
353
    int best_score=0;
354

    
355
    memset(stat, 0, packet_size*sizeof(int));
356

    
357
    for(x=i=0; i<size-3; i++){
358
        if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
359
            stat[x]++;
360
            if(stat[x] > best_score){
361
                best_score= stat[x];
362
                if(index) *index= x;
363
            }
364
        }
365

    
366
        x++;
367
        if(x == packet_size) x= 0;
368
    }
369

    
370
    return best_score;
371
}
372

    
373
/* autodetect fec presence. Must have at least 1024 bytes  */
374
static int get_packet_size(const uint8_t *buf, int size)
375
{
376
    int score, fec_score, dvhs_score;
377

    
378
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
379
        return -1;
380

    
381
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
382
    dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
383
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
384
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
385

    
386
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
387
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
388
    else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
389
    else                       return -1;
390
}
391

    
392
typedef struct SectionHeader {
393
    uint8_t tid;
394
    uint16_t id;
395
    uint8_t version;
396
    uint8_t sec_num;
397
    uint8_t last_sec_num;
398
} SectionHeader;
399

    
400
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
401
{
402
    const uint8_t *p;
403
    int c;
404

    
405
    p = *pp;
406
    if (p >= p_end)
407
        return -1;
408
    c = *p++;
409
    *pp = p;
410
    return c;
411
}
412

    
413
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
414
{
415
    const uint8_t *p;
416
    int c;
417

    
418
    p = *pp;
419
    if ((p + 1) >= p_end)
420
        return -1;
421
    c = AV_RB16(p);
422
    p += 2;
423
    *pp = p;
424
    return c;
425
}
426

    
427
/* read and allocate a DVB string preceeded by its length */
428
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
429
{
430
    int len;
431
    const uint8_t *p;
432
    char *str;
433

    
434
    p = *pp;
435
    len = get8(&p, p_end);
436
    if (len < 0)
437
        return NULL;
438
    if ((p + len) > p_end)
439
        return NULL;
440
    str = av_malloc(len + 1);
441
    if (!str)
442
        return NULL;
443
    memcpy(str, p, len);
444
    str[len] = '\0';
445
    p += len;
446
    *pp = p;
447
    return str;
448
}
449

    
450
static int parse_section_header(SectionHeader *h,
451
                                const uint8_t **pp, const uint8_t *p_end)
452
{
453
    int val;
454

    
455
    val = get8(pp, p_end);
456
    if (val < 0)
457
        return -1;
458
    h->tid = val;
459
    *pp += 2;
460
    val = get16(pp, p_end);
461
    if (val < 0)
462
        return -1;
463
    h->id = val;
464
    val = get8(pp, p_end);
465
    if (val < 0)
466
        return -1;
467
    h->version = (val >> 1) & 0x1f;
468
    val = get8(pp, p_end);
469
    if (val < 0)
470
        return -1;
471
    h->sec_num = val;
472
    val = get8(pp, p_end);
473
    if (val < 0)
474
        return -1;
475
    h->last_sec_num = val;
476
    return 0;
477
}
478

    
479

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

    
494
#ifdef DEBUG_SI
495
    av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
496
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
497
#endif
498
    p_end = section + section_len - 4;
499
    p = section;
500
    if (parse_section_header(h, &p, p_end) < 0)
501
        return;
502
#ifdef DEBUG_SI
503
    av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
504
           h->id, h->sec_num, h->last_sec_num);
505
#endif
506
    if (h->tid != PMT_TID)
507
        return;
508

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

    
585
                language[0] = get8(&p, desc_end);
586
                language[1] = get8(&p, desc_end);
587
                language[2] = get8(&p, desc_end);
588
                language[3] = 0;
589
                get8(&p, desc_end);
590
                comp_page = get16(&p, desc_end);
591
                anc_page = get16(&p, desc_end);
592

    
593
                break;
594
            case 0x0a: /* ISO 639 language descriptor */
595
                language[0] = get8(&p, desc_end);
596
                language[1] = get8(&p, desc_end);
597
                language[2] = get8(&p, desc_end);
598
                language[3] = 0;
599
                break;
600
            case REGISTRATION_DESCRIPTOR: /*MPEG-2 Registration descriptor */
601
                {
602
                    uint8_t bytes[4];
603
                    bytes[0] = get8(&p, desc_end);
604
                    bytes[1] = get8(&p, desc_end);
605
                    bytes[2] = get8(&p, desc_end);
606
                    bytes[3] = get8(&p, desc_end);
607
                    if(bytes[0] == 'd' && bytes[1] == 'r' &&
608
                       bytes[2] == 'a' && bytes[3] == 'c')
609
                        has_dirac_descr = 1;
610
                    break;
611
                }
612
            default:
613
                break;
614
            }
615
            p = desc_end;
616
        }
617
        p = desc_list_end;
618

    
619
#ifdef DEBUG_SI
620
        av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
621
               stream_type, pid);
622
#endif
623

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

    
660
        if (st) {
661
            if (language[0] != 0) {
662
                memcpy(st->language, language, 4);
663
            }
664

    
665
            if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
666
                st->codec->sub_id = (anc_page << 16) | comp_page;
667
            }
668
        }
669
    }
670
    /* all parameters are there */
671
    ts->stop_parse++;
672
    mpegts_close_filter(ts, filter);
673
}
674

    
675
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
676
{
677
    MpegTSContext *ts = filter->u.section_filter.opaque;
678
    SectionHeader h1, *h = &h1;
679
    const uint8_t *p, *p_end;
680
    int sid, pmt_pid;
681

    
682
#ifdef DEBUG_SI
683
    av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
684
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
685
#endif
686
    p_end = section + section_len - 4;
687
    p = section;
688
    if (parse_section_header(h, &p, p_end) < 0)
689
        return;
690
    if (h->tid != PAT_TID)
691
        return;
692

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

    
718
    mpegts_close_filter(ts, filter);
719
}
720

    
721
static void mpegts_set_service(MpegTSContext *ts)
722
{
723
    mpegts_open_section_filter(ts, PAT_PID,
724
                                                pat_cb, ts, 1);
725
}
726

    
727
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
728
{
729
    MpegTSContext *ts = filter->u.section_filter.opaque;
730
    SectionHeader h1, *h = &h1;
731
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
732
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
733
    char *name, *provider_name;
734

    
735
#ifdef DEBUG_SI
736
    av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
737
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
738
#endif
739

    
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 != SDT_TID)
745
        return;
746
    onid = get16(&p, p_end);
747
    if (onid < 0)
748
        return;
749
    val = get8(&p, p_end);
750
    if (val < 0)
751
        return;
752
    for(;;) {
753
        sid = get16(&p, p_end);
754
        if (sid < 0)
755
            break;
756
        val = get8(&p, p_end);
757
        if (val < 0)
758
            break;
759
        desc_list_len = get16(&p, p_end) & 0xfff;
760
        if (desc_list_len < 0)
761
            break;
762
        desc_list_end = p + desc_list_len;
763
        if (desc_list_end > p_end)
764
            break;
765
        for(;;) {
766
            desc_tag = get8(&p, desc_list_end);
767
            if (desc_tag < 0)
768
                break;
769
            desc_len = get8(&p, desc_list_end);
770
            desc_end = p + desc_len;
771
            if (desc_end > desc_list_end)
772
                break;
773
#ifdef DEBUG_SI
774
            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
775
                   desc_tag, desc_len);
776
#endif
777
            switch(desc_tag) {
778
            case 0x48:
779
                service_type = get8(&p, p_end);
780
                if (service_type < 0)
781
                    break;
782
                provider_name = getstr8(&p, p_end);
783
                if (!provider_name)
784
                    break;
785
                name = getstr8(&p, p_end);
786
                if (name) {
787
                    AVProgram *program = av_new_program(ts->stream, sid);
788
                    if(program)
789
                        av_set_program_name(program, provider_name, name);
790
                }
791
                av_free(name);
792
                av_free(provider_name);
793
                break;
794
            default:
795
                break;
796
            }
797
            p = desc_end;
798
        }
799
        p = desc_list_end;
800
    }
801
}
802

    
803
/* scan services in a transport stream by looking at the SDT */
804
static void mpegts_scan_sdt(MpegTSContext *ts)
805
{
806
    mpegts_open_section_filter(ts, SDT_PID,
807
                                                sdt_cb, ts, 1);
808
}
809

    
810
static int64_t get_pts(const uint8_t *p)
811
{
812
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
813
    pts |= (AV_RB16(p + 1) >> 1) << 15;
814
    pts |=  AV_RB16(p + 3) >> 1;
815
    return pts;
816
}
817

    
818
/* return non zero if a packet could be constructed */
819
static void mpegts_push_data(MpegTSFilter *filter,
820
                             const uint8_t *buf, int buf_size, int is_start)
821
{
822
    PESContext *pes = filter->u.pes_filter.opaque;
823
    MpegTSContext *ts = pes->ts;
824
    const uint8_t *p;
825
    int len, code;
826

    
827
    if(!ts->pkt)
828
        return;
829

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

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

    
941
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
942
{
943
    AVStream *st;
944
    enum CodecID codec_id;
945
    enum CodecType codec_type;
946

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

    
1016

    
1017
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1018
{
1019
    MpegTSFilter *tss;
1020
    PESContext *pes;
1021

    
1022
    /* if no pid found, then add a pid context */
1023
    pes = av_mallocz(sizeof(PESContext));
1024
    if (!pes)
1025
        return 0;
1026
    pes->ts = ts;
1027
    pes->stream = ts->stream;
1028
    pes->pid = pid;
1029
    pes->pcr_pid = pcr_pid;
1030
    pes->stream_type = stream_type;
1031
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1032
    if (!tss) {
1033
        av_free(pes);
1034
        return 0;
1035
    }
1036
    return pes;
1037
}
1038

    
1039
/* handle one TS packet */
1040
static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1041
{
1042
    AVFormatContext *s = ts->stream;
1043
    MpegTSFilter *tss;
1044
    int len, pid, cc, cc_ok, afc, is_start;
1045
    const uint8_t *p, *p_end;
1046

    
1047
    pid = AV_RB16(packet + 1) & 0x1fff;
1048
    if(pid && discard_pid(ts, pid))
1049
        return;
1050
    is_start = packet[1] & 0x40;
1051
    tss = ts->pids[pid];
1052
    if (ts->auto_guess && tss == NULL && is_start) {
1053
        add_pes_stream(ts, pid, -1, 0);
1054
        tss = ts->pids[pid];
1055
    }
1056
    if (!tss)
1057
        return;
1058

    
1059
    /* continuity check (currently not used) */
1060
    cc = (packet[3] & 0xf);
1061
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1062
    tss->last_cc = cc;
1063

    
1064
    /* skip adaptation field */
1065
    afc = (packet[3] >> 4) & 3;
1066
    p = packet + 4;
1067
    if (afc == 0) /* reserved value */
1068
        return;
1069
    if (afc == 2) /* adaptation field only */
1070
        return;
1071
    if (afc == 3) {
1072
        /* skip adapation field */
1073
        p += p[0] + 1;
1074
    }
1075
    /* if past the end of packet, ignore */
1076
    p_end = packet + TS_PACKET_SIZE;
1077
    if (p >= p_end)
1078
        return;
1079

    
1080
    ts->pos47= url_ftell(ts->stream->pb) % ts->raw_packet_size;
1081

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

    
1113
/* XXX: try to find a better synchro over several packets (use
1114
   get_packet_size() ?) */
1115
static int mpegts_resync(ByteIOContext *pb)
1116
{
1117
    int c, i;
1118

    
1119
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1120
        c = url_fgetc(pb);
1121
        if (c < 0)
1122
            return -1;
1123
        if (c == 0x47) {
1124
            url_fseek(pb, -1, SEEK_CUR);
1125
            return 0;
1126
        }
1127
    }
1128
    /* no sync found */
1129
    return -1;
1130
}
1131

    
1132
/* return -1 if error or EOF. Return 0 if OK. */
1133
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1134
{
1135
    int skip, len;
1136

    
1137
    for(;;) {
1138
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1139
        if (len != TS_PACKET_SIZE)
1140
            return AVERROR(EIO);
1141
        /* check paquet sync byte */
1142
        if (buf[0] != 0x47) {
1143
            /* find a new packet start */
1144
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1145
            if (mpegts_resync(pb) < 0)
1146
                return AVERROR_INVALIDDATA;
1147
            else
1148
                continue;
1149
        } else {
1150
            skip = raw_packet_size - TS_PACKET_SIZE;
1151
            if (skip > 0)
1152
                url_fskip(pb, skip);
1153
            break;
1154
        }
1155
    }
1156
    return 0;
1157
}
1158

    
1159
static int handle_packets(MpegTSContext *ts, int nb_packets)
1160
{
1161
    AVFormatContext *s = ts->stream;
1162
    ByteIOContext *pb = s->pb;
1163
    uint8_t packet[TS_PACKET_SIZE];
1164
    int packet_num, ret;
1165

    
1166
    ts->stop_parse = 0;
1167
    packet_num = 0;
1168
    for(;;) {
1169
        if (ts->stop_parse>0)
1170
            break;
1171
        packet_num++;
1172
        if (nb_packets != 0 && packet_num >= nb_packets)
1173
            break;
1174
        ret = read_packet(pb, packet, ts->raw_packet_size);
1175
        if (ret != 0)
1176
            return ret;
1177
        handle_packet(ts, packet);
1178
    }
1179
    return 0;
1180
}
1181

    
1182
static int mpegts_probe(AVProbeData *p)
1183
{
1184
#if 1
1185
    const int size= p->buf_size;
1186
    int score, fec_score, dvhs_score;
1187
    int check_count= size / TS_FEC_PACKET_SIZE;
1188
#define CHECK_COUNT 10
1189

    
1190
    if (check_count < CHECK_COUNT)
1191
        return -1;
1192

    
1193
    score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
1194
    dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1195
    fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1196
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1197

    
1198
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1199
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1200
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1201
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1202
    else                                    return -1;
1203
#else
1204
    /* only use the extension for safer guess */
1205
    if (match_ext(p->filename, "ts"))
1206
        return AVPROBE_SCORE_MAX;
1207
    else
1208
        return 0;
1209
#endif
1210
}
1211

    
1212
/* return the 90kHz PCR and the extension for the 27MHz PCR. return
1213
   (-1) if not available */
1214
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1215
                     const uint8_t *packet)
1216
{
1217
    int afc, len, flags;
1218
    const uint8_t *p;
1219
    unsigned int v;
1220

    
1221
    afc = (packet[3] >> 4) & 3;
1222
    if (afc <= 1)
1223
        return -1;
1224
    p = packet + 4;
1225
    len = p[0];
1226
    p++;
1227
    if (len == 0)
1228
        return -1;
1229
    flags = *p++;
1230
    len--;
1231
    if (!(flags & 0x10))
1232
        return -1;
1233
    if (len < 6)
1234
        return -1;
1235
    v = AV_RB32(p);
1236
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1237
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1238
    return 0;
1239
}
1240

    
1241
static int mpegts_read_header(AVFormatContext *s,
1242
                              AVFormatParameters *ap)
1243
{
1244
    MpegTSContext *ts = s->priv_data;
1245
    ByteIOContext *pb = s->pb;
1246
    uint8_t buf[5*1024];
1247
    int len;
1248
    int64_t pos;
1249

    
1250
    if (ap) {
1251
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1252
        if(ap->mpeg2ts_raw){
1253
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1254
            return -1;
1255
        }
1256
    }
1257

    
1258
    /* read the first 1024 bytes to get packet size */
1259
    pos = url_ftell(pb);
1260
    len = get_buffer(pb, buf, sizeof(buf));
1261
    if (len != sizeof(buf))
1262
        goto fail;
1263
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1264
    if (ts->raw_packet_size <= 0)
1265
        goto fail;
1266
    ts->stream = s;
1267
    ts->auto_guess = 0;
1268

    
1269
    if (s->iformat == &mpegts_demuxer) {
1270
        /* normal demux */
1271

    
1272
        /* first do a scaning to get all the services */
1273
        url_fseek(pb, pos, SEEK_SET);
1274
        mpegts_scan_sdt(ts);
1275

    
1276
        mpegts_set_service(ts);
1277

    
1278
        handle_packets(ts, s->probesize);
1279
        /* if could not find service, enable auto_guess */
1280

    
1281
        ts->auto_guess = 1;
1282

    
1283
#ifdef DEBUG_SI
1284
        av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1285
#endif
1286
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1287
    } else {
1288
        AVStream *st;
1289
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1290
        int64_t pcrs[2], pcr_h;
1291
        int packet_count[2];
1292
        uint8_t packet[TS_PACKET_SIZE];
1293

    
1294
        /* only read packets */
1295

    
1296
        st = av_new_stream(s, 0);
1297
        if (!st)
1298
            goto fail;
1299
        av_set_pts_info(st, 60, 1, 27000000);
1300
        st->codec->codec_type = CODEC_TYPE_DATA;
1301
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1302

    
1303
        /* we iterate until we find two PCRs to estimate the bitrate */
1304
        pcr_pid = -1;
1305
        nb_pcrs = 0;
1306
        nb_packets = 0;
1307
        for(;;) {
1308
            ret = read_packet(s->pb, packet, ts->raw_packet_size);
1309
            if (ret < 0)
1310
                return -1;
1311
            pid = AV_RB16(packet + 1) & 0x1fff;
1312
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1313
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1314
                pcr_pid = pid;
1315
                packet_count[nb_pcrs] = nb_packets;
1316
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1317
                nb_pcrs++;
1318
                if (nb_pcrs >= 2)
1319
                    break;
1320
            }
1321
            nb_packets++;
1322
        }
1323

    
1324
        /* NOTE1: the bitrate is computed without the FEC */
1325
        /* NOTE2: it is only the bitrate of the start of the stream */
1326
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1327
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1328
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1329
        st->codec->bit_rate = s->bit_rate;
1330
        st->start_time = ts->cur_pcr;
1331
#if 0
1332
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1333
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1334
#endif
1335
    }
1336

    
1337
    url_fseek(pb, pos, SEEK_SET);
1338
    return 0;
1339
 fail:
1340
    return -1;
1341
}
1342

    
1343
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1344

    
1345
static int mpegts_raw_read_packet(AVFormatContext *s,
1346
                                  AVPacket *pkt)
1347
{
1348
    MpegTSContext *ts = s->priv_data;
1349
    int ret, i;
1350
    int64_t pcr_h, next_pcr_h, pos;
1351
    int pcr_l, next_pcr_l;
1352
    uint8_t pcr_buf[12];
1353

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

    
1389
static int mpegts_read_packet(AVFormatContext *s,
1390
                              AVPacket *pkt)
1391
{
1392
    MpegTSContext *ts = s->priv_data;
1393

    
1394
    ts->pkt = pkt;
1395
    return handle_packets(ts, 0);
1396
}
1397

    
1398
static int mpegts_read_close(AVFormatContext *s)
1399
{
1400
    MpegTSContext *ts = s->priv_data;
1401
    int i;
1402

    
1403
    clear_programs(ts);
1404

    
1405
    for(i=0;i<NB_PID_MAX;i++)
1406
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1407

    
1408
    return 0;
1409
}
1410

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

    
1447
    return timestamp;
1448
}
1449

    
1450
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1451
    MpegTSContext *ts = s->priv_data;
1452
    uint8_t buf[TS_PACKET_SIZE];
1453
    int64_t pos;
1454

    
1455
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1456
        return -1;
1457

    
1458
    pos= url_ftell(s->pb);
1459

    
1460
    for(;;) {
1461
        url_fseek(s->pb, pos, SEEK_SET);
1462
        if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1463
            return -1;
1464
//        pid = AV_RB16(buf + 1) & 0x1fff;
1465
        if(buf[1] & 0x40) break;
1466
        pos += ts->raw_packet_size;
1467
    }
1468
    url_fseek(s->pb, pos, SEEK_SET);
1469

    
1470
    return 0;
1471
}
1472

    
1473
/**************************************************************/
1474
/* parsing functions - called from other demuxers such as RTP */
1475

    
1476
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1477
{
1478
    MpegTSContext *ts;
1479

    
1480
    ts = av_mallocz(sizeof(MpegTSContext));
1481
    if (!ts)
1482
        return NULL;
1483
    /* no stream case, currently used by RTP */
1484
    ts->raw_packet_size = TS_PACKET_SIZE;
1485
    ts->stream = s;
1486
    ts->auto_guess = 1;
1487
    return ts;
1488
}
1489

    
1490
/* return the consumed length if a packet was output, or -1 if no
1491
   packet is output */
1492
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1493
                        const uint8_t *buf, int len)
1494
{
1495
    int len1;
1496

    
1497
    len1 = len;
1498
    ts->pkt = pkt;
1499
    ts->stop_parse = 0;
1500
    for(;;) {
1501
        if (ts->stop_parse>0)
1502
            break;
1503
        if (len < TS_PACKET_SIZE)
1504
            return -1;
1505
        if (buf[0] != 0x47) {
1506
            buf++;
1507
            len--;
1508
        } else {
1509
            handle_packet(ts, buf);
1510
            buf += TS_PACKET_SIZE;
1511
            len -= TS_PACKET_SIZE;
1512
        }
1513
    }
1514
    return len1 - len;
1515
}
1516

    
1517
void mpegts_parse_close(MpegTSContext *ts)
1518
{
1519
    int i;
1520

    
1521
    for(i=0;i<NB_PID_MAX;i++)
1522
        av_free(ts->pids[i]);
1523
    av_free(ts);
1524
}
1525

    
1526
AVInputFormat mpegts_demuxer = {
1527
    "mpegts",
1528
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1529
    sizeof(MpegTSContext),
1530
    mpegts_probe,
1531
    mpegts_read_header,
1532
    mpegts_read_packet,
1533
    mpegts_read_close,
1534
    read_seek,
1535
    mpegts_get_pcr,
1536
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1537
};
1538

    
1539
AVInputFormat mpegtsraw_demuxer = {
1540
    "mpegtsraw",
1541
    NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1542
    sizeof(MpegTSContext),
1543
    NULL,
1544
    mpegts_read_header,
1545
    mpegts_raw_read_packet,
1546
    mpegts_read_close,
1547
    read_seek,
1548
    mpegts_get_pcr,
1549
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1550
};