Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ 81d5ae6d

History | View | Annotate | Download (43.5 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
#include "avformat.h"
22
#include "crc.h"
23
#include "mpegts.h"
24

    
25
//#define DEBUG_SI
26
//#define DEBUG_SEEK
27

    
28
/* 1.0 second at 24Mbit/s */
29
#define MAX_SCAN_PACKETS 32000
30

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

    
36
typedef struct PESContext PESContext;
37

    
38
static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
39
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
40
extern void av_set_program_name(AVProgram *program, char *provider_name, char *name);
41
extern void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx);
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
    int check_crc:1;
66
    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
typedef struct {
83
    unsigned int id; //program id/service id
84
    unsigned int nb_pids;
85
    unsigned int pids[MAX_PIDS_PER_PROGRAM];
86
} Program_t;
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
    Program_t *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
    Program_t *p;
172
    void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(Program_t));
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
    Program_t *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
    Program_t *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
    else if (filter->type == MPEGTS_PES)
337
        av_freep(&filter->u.pes_filter.opaque);
338

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

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

    
349
    memset(stat, 0, packet_size*sizeof(int));
350

    
351
    for(x=i=0; i<size; i++){
352
        if(buf[i] == 0x47){
353
            stat[x]++;
354
            if(stat[x] > best_score){
355
                best_score= stat[x];
356
                if(index) *index= x;
357
            }
358
        }
359

    
360
        x++;
361
        if(x == packet_size) x= 0;
362
    }
363

    
364
    return best_score;
365
}
366

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

    
372
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
373
        return -1;
374

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

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

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

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

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

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

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

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

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

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

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

    
473

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

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

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

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

    
586
                break;
587
            case 0x0a: /* ISO 639 language descriptor */
588
                language[0] = get8(&p, desc_end);
589
                language[1] = get8(&p, desc_end);
590
                language[2] = get8(&p, desc_end);
591
                language[3] = 0;
592
                break;
593
            default:
594
                break;
595
            }
596
            p = desc_end;
597
        }
598
        p = desc_list_end;
599

    
600
#ifdef DEBUG_SI
601
        av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
602
               stream_type, pid);
603
#endif
604

    
605
        /* now create ffmpeg stream */
606
        switch(stream_type) {
607
        case STREAM_TYPE_AUDIO_MPEG1:
608
        case STREAM_TYPE_AUDIO_MPEG2:
609
        case STREAM_TYPE_VIDEO_MPEG1:
610
        case STREAM_TYPE_VIDEO_MPEG2:
611
        case STREAM_TYPE_VIDEO_MPEG4:
612
        case STREAM_TYPE_VIDEO_H264:
613
        case STREAM_TYPE_VIDEO_VC1:
614
        case STREAM_TYPE_AUDIO_AAC:
615
        case STREAM_TYPE_AUDIO_AC3:
616
        case STREAM_TYPE_AUDIO_DTS:
617
        case STREAM_TYPE_AUDIO_HDMV_DTS:
618
        case STREAM_TYPE_SUBTITLE_DVB:
619
            if(stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
620
                break;
621
            if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
622
                pes= ts->pids[pid]->u.pes_filter.opaque;
623
                st= pes->st;
624
            }else{
625
                if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
626
                pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
627
                if (pes)
628
                    st = new_pes_av_stream(pes, 0);
629
            }
630
            add_pid_to_pmt(ts, h->id, pid);
631
            if(st)
632
                av_program_add_stream_index(ts->stream, h->id, st->index);
633
            break;
634
        default:
635
            /* we ignore the other streams */
636
            break;
637
        }
638

    
639
        if (st) {
640
            if (language[0] != 0) {
641
                memcpy(st->language, language, 4);
642
            }
643

    
644
            if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
645
                st->codec->sub_id = (anc_page << 16) | comp_page;
646
            }
647
        }
648
    }
649
    /* all parameters are there */
650
    ts->stop_parse++;
651
    mpegts_close_filter(ts, filter);
652
}
653

    
654
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
655
{
656
    MpegTSContext *ts = filter->u.section_filter.opaque;
657
    SectionHeader h1, *h = &h1;
658
    const uint8_t *p, *p_end;
659
    int sid, pmt_pid;
660

    
661
#ifdef DEBUG_SI
662
    av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
663
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
664
#endif
665
    p_end = section + section_len - 4;
666
    p = section;
667
    if (parse_section_header(h, &p, p_end) < 0)
668
        return;
669
    if (h->tid != PAT_TID)
670
        return;
671

    
672
    clear_programs(ts);
673
    for(;;) {
674
        sid = get16(&p, p_end);
675
        if (sid < 0)
676
            break;
677
        pmt_pid = get16(&p, p_end) & 0x1fff;
678
        if (pmt_pid < 0)
679
            break;
680
#ifdef DEBUG_SI
681
        av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
682
#endif
683
        if (sid == 0x0000) {
684
            /* NIT info */
685
        } else {
686
            av_new_program(ts->stream, sid);
687
            ts->stop_parse--;
688
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
689
            add_pat_entry(ts, sid);
690
            add_pid_to_pmt(ts, sid, 0); //add pat pid to program
691
            add_pid_to_pmt(ts, sid, pmt_pid);
692
        }
693
    }
694
    /* not found */
695
    ts->stop_parse++;
696

    
697
    mpegts_close_filter(ts, filter);
698
}
699

    
700
static void mpegts_set_service(MpegTSContext *ts)
701
{
702
    mpegts_open_section_filter(ts, PAT_PID,
703
                                                pat_cb, ts, 1);
704
}
705

    
706
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
707
{
708
    MpegTSContext *ts = filter->u.section_filter.opaque;
709
    SectionHeader h1, *h = &h1;
710
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
711
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
712
    char *name, *provider_name;
713

    
714
#ifdef DEBUG_SI
715
    av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
716
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
717
#endif
718

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

    
782
/* scan services in a transport stream by looking at the SDT */
783
static void mpegts_scan_sdt(MpegTSContext *ts)
784
{
785
    mpegts_open_section_filter(ts, SDT_PID,
786
                                                sdt_cb, ts, 1);
787
}
788

    
789
static int64_t get_pts(const uint8_t *p)
790
{
791
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
792
    pts |= (AV_RB16(p + 1) >> 1) << 15;
793
    pts |=  AV_RB16(p + 3) >> 1;
794
    return pts;
795
}
796

    
797
/* return non zero if a packet could be constructed */
798
static void mpegts_push_data(MpegTSFilter *filter,
799
                             const uint8_t *buf, int buf_size, int is_start)
800
{
801
    PESContext *pes = filter->u.pes_filter.opaque;
802
    MpegTSContext *ts = pes->ts;
803
    const uint8_t *p;
804
    int len, code;
805

    
806
    if(!ts->pkt)
807
        return;
808

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

    
872
                flags = pes->header[7];
873
                r = pes->header + 9;
874
                pes->pts = AV_NOPTS_VALUE;
875
                pes->dts = AV_NOPTS_VALUE;
876
                if ((flags & 0xc0) == 0x80) {
877
                    pes->pts = get_pts(r);
878
                    r += 5;
879
                } else if ((flags & 0xc0) == 0xc0) {
880
                    pes->pts = get_pts(r);
881
                    r += 5;
882
                    pes->dts = get_pts(r);
883
                    r += 5;
884
                }
885
                /* we got the full header. We parse it and get the payload */
886
                pes->state = MPEGTS_PAYLOAD;
887
            }
888
            break;
889
        case MPEGTS_PAYLOAD:
890
            if (pes->total_size) {
891
                len = pes->total_size - pes->data_index;
892
                if (len > buf_size)
893
                    len = buf_size;
894
            } else {
895
                len = buf_size;
896
            }
897
            if (len > 0) {
898
                AVPacket *pkt = ts->pkt;
899
                if (pes->st && av_new_packet(pkt, len) == 0) {
900
                    memcpy(pkt->data, p, len);
901
                    pkt->stream_index = pes->st->index;
902
                    pkt->pts = pes->pts;
903
                    pkt->dts = pes->dts;
904
                    /* reset pts values */
905
                    pes->pts = AV_NOPTS_VALUE;
906
                    pes->dts = AV_NOPTS_VALUE;
907
                    ts->stop_parse = 1;
908
                    return;
909
                }
910
            }
911
            buf_size = 0;
912
            break;
913
        case MPEGTS_SKIP:
914
            buf_size = 0;
915
            break;
916
        }
917
    }
918
}
919

    
920
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
921
{
922
    AVStream *st;
923
    int codec_type, codec_id;
924

    
925
    switch(pes->stream_type){
926
    case STREAM_TYPE_AUDIO_MPEG1:
927
    case STREAM_TYPE_AUDIO_MPEG2:
928
        codec_type = CODEC_TYPE_AUDIO;
929
        codec_id = CODEC_ID_MP3;
930
        break;
931
    case STREAM_TYPE_VIDEO_MPEG1:
932
    case STREAM_TYPE_VIDEO_MPEG2:
933
        codec_type = CODEC_TYPE_VIDEO;
934
        codec_id = CODEC_ID_MPEG2VIDEO;
935
        break;
936
    case STREAM_TYPE_VIDEO_MPEG4:
937
        codec_type = CODEC_TYPE_VIDEO;
938
        codec_id = CODEC_ID_MPEG4;
939
        break;
940
    case STREAM_TYPE_VIDEO_H264:
941
        codec_type = CODEC_TYPE_VIDEO;
942
        codec_id = CODEC_ID_H264;
943
        break;
944
    case STREAM_TYPE_VIDEO_VC1:
945
        codec_type = CODEC_TYPE_VIDEO;
946
        codec_id = CODEC_ID_VC1;
947
        break;
948
    case STREAM_TYPE_AUDIO_AAC:
949
        codec_type = CODEC_TYPE_AUDIO;
950
        codec_id = CODEC_ID_AAC;
951
        break;
952
    case STREAM_TYPE_AUDIO_AC3:
953
        codec_type = CODEC_TYPE_AUDIO;
954
        codec_id = CODEC_ID_AC3;
955
        break;
956
    case STREAM_TYPE_AUDIO_DTS:
957
    case STREAM_TYPE_AUDIO_HDMV_DTS:
958
        codec_type = CODEC_TYPE_AUDIO;
959
        codec_id = CODEC_ID_DTS;
960
        break;
961
    case STREAM_TYPE_SUBTITLE_DVB:
962
        codec_type = CODEC_TYPE_SUBTITLE;
963
        codec_id = CODEC_ID_DVB_SUBTITLE;
964
        break;
965
    default:
966
        if (code >= 0x1c0 && code <= 0x1df) {
967
            codec_type = CODEC_TYPE_AUDIO;
968
            codec_id = CODEC_ID_MP2;
969
        } else if (code == 0x1bd) {
970
            codec_type = CODEC_TYPE_AUDIO;
971
            codec_id = CODEC_ID_AC3;
972
        } else {
973
            codec_type = CODEC_TYPE_VIDEO;
974
            codec_id = CODEC_ID_MPEG1VIDEO;
975
        }
976
        break;
977
    }
978
    st = av_new_stream(pes->stream, pes->pid);
979
    if (st) {
980
        av_set_pts_info(st, 33, 1, 90000);
981
        st->priv_data = pes;
982
        st->codec->codec_type = codec_type;
983
        st->codec->codec_id = codec_id;
984
        st->need_parsing = AVSTREAM_PARSE_FULL;
985
        pes->st = st;
986
    }
987
    return st;
988
}
989

    
990

    
991
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
992
{
993
    MpegTSFilter *tss;
994
    PESContext *pes;
995

    
996
    /* if no pid found, then add a pid context */
997
    pes = av_mallocz(sizeof(PESContext));
998
    if (!pes)
999
        return 0;
1000
    pes->ts = ts;
1001
    pes->stream = ts->stream;
1002
    pes->pid = pid;
1003
    pes->pcr_pid = pcr_pid;
1004
    pes->stream_type = stream_type;
1005
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1006
    if (!tss) {
1007
        av_free(pes);
1008
        return 0;
1009
    }
1010
    return pes;
1011
}
1012

    
1013
/* handle one TS packet */
1014
static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1015
{
1016
    AVFormatContext *s = ts->stream;
1017
    MpegTSFilter *tss;
1018
    int len, pid, cc, cc_ok, afc, is_start;
1019
    const uint8_t *p, *p_end;
1020

    
1021
    pid = AV_RB16(packet + 1) & 0x1fff;
1022
    if(pid && discard_pid(ts, pid))
1023
        return;
1024
    is_start = packet[1] & 0x40;
1025
    tss = ts->pids[pid];
1026
    if (ts->auto_guess && tss == NULL && is_start) {
1027
        add_pes_stream(ts, pid, -1, 0);
1028
        tss = ts->pids[pid];
1029
    }
1030
    if (!tss)
1031
        return;
1032

    
1033
    /* continuity check (currently not used) */
1034
    cc = (packet[3] & 0xf);
1035
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1036
    tss->last_cc = cc;
1037

    
1038
    /* skip adaptation field */
1039
    afc = (packet[3] >> 4) & 3;
1040
    p = packet + 4;
1041
    if (afc == 0) /* reserved value */
1042
        return;
1043
    if (afc == 2) /* adaptation field only */
1044
        return;
1045
    if (afc == 3) {
1046
        /* skip adapation field */
1047
        p += p[0] + 1;
1048
    }
1049
    /* if past the end of packet, ignore */
1050
    p_end = packet + TS_PACKET_SIZE;
1051
    if (p >= p_end)
1052
        return;
1053

    
1054
    ts->pos47= url_ftell(ts->stream->pb) % ts->raw_packet_size;
1055

    
1056
    if (tss->type == MPEGTS_SECTION) {
1057
        if (is_start) {
1058
            /* pointer field present */
1059
            len = *p++;
1060
            if (p + len > p_end)
1061
                return;
1062
            if (len && cc_ok) {
1063
                /* write remaining section bytes */
1064
                write_section_data(s, tss,
1065
                                   p, len, 0);
1066
                /* check whether filter has been closed */
1067
                if (!ts->pids[pid])
1068
                    return;
1069
            }
1070
            p += len;
1071
            if (p < p_end) {
1072
                write_section_data(s, tss,
1073
                                   p, p_end - p, 1);
1074
            }
1075
        } else {
1076
            if (cc_ok) {
1077
                write_section_data(s, tss,
1078
                                   p, p_end - p, 0);
1079
            }
1080
        }
1081
    } else {
1082
        tss->u.pes_filter.pes_cb(tss,
1083
                                 p, p_end - p, is_start);
1084
    }
1085
}
1086

    
1087
/* XXX: try to find a better synchro over several packets (use
1088
   get_packet_size() ?) */
1089
static int mpegts_resync(ByteIOContext *pb)
1090
{
1091
    int c, i;
1092

    
1093
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1094
        c = url_fgetc(pb);
1095
        if (c < 0)
1096
            return -1;
1097
        if (c == 0x47) {
1098
            url_fseek(pb, -1, SEEK_CUR);
1099
            return 0;
1100
        }
1101
    }
1102
    /* no sync found */
1103
    return -1;
1104
}
1105

    
1106
/* return -1 if error or EOF. Return 0 if OK. */
1107
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1108
{
1109
    int skip, len;
1110

    
1111
    for(;;) {
1112
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1113
        if (len != TS_PACKET_SIZE)
1114
            return AVERROR(EIO);
1115
        /* check paquet sync byte */
1116
        if (buf[0] != 0x47) {
1117
            /* find a new packet start */
1118
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1119
            if (mpegts_resync(pb) < 0)
1120
                return AVERROR_INVALIDDATA;
1121
            else
1122
                continue;
1123
        } else {
1124
            skip = raw_packet_size - TS_PACKET_SIZE;
1125
            if (skip > 0)
1126
                url_fskip(pb, skip);
1127
            break;
1128
        }
1129
    }
1130
    return 0;
1131
}
1132

    
1133
static int handle_packets(MpegTSContext *ts, int nb_packets)
1134
{
1135
    AVFormatContext *s = ts->stream;
1136
    ByteIOContext *pb = s->pb;
1137
    uint8_t packet[TS_PACKET_SIZE];
1138
    int packet_num, ret;
1139

    
1140
    ts->stop_parse = 0;
1141
    packet_num = 0;
1142
    for(;;) {
1143
        if (ts->stop_parse>0)
1144
            break;
1145
        packet_num++;
1146
        if (nb_packets != 0 && packet_num >= nb_packets)
1147
            break;
1148
        ret = read_packet(pb, packet, ts->raw_packet_size);
1149
        if (ret != 0)
1150
            return ret;
1151
        handle_packet(ts, packet);
1152
    }
1153
    return 0;
1154
}
1155

    
1156
static int mpegts_probe(AVProbeData *p)
1157
{
1158
#if 1
1159
    const int size= p->buf_size;
1160
    int score, fec_score, dvhs_score;
1161
#define CHECK_COUNT 10
1162

    
1163
    if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1164
        return -1;
1165

    
1166
    score    = analyze(p->buf, TS_PACKET_SIZE    *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1167
    dvhs_score  = analyze(p->buf, TS_DVHS_PACKET_SIZE    *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1168
    fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1169
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1170

    
1171
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1172
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1173
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1174
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1175
    else                                    return -1;
1176
#else
1177
    /* only use the extension for safer guess */
1178
    if (match_ext(p->filename, "ts"))
1179
        return AVPROBE_SCORE_MAX;
1180
    else
1181
        return 0;
1182
#endif
1183
}
1184

    
1185
/* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1186
   (-1) if not available */
1187
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1188
                     const uint8_t *packet)
1189
{
1190
    int afc, len, flags;
1191
    const uint8_t *p;
1192
    unsigned int v;
1193

    
1194
    afc = (packet[3] >> 4) & 3;
1195
    if (afc <= 1)
1196
        return -1;
1197
    p = packet + 4;
1198
    len = p[0];
1199
    p++;
1200
    if (len == 0)
1201
        return -1;
1202
    flags = *p++;
1203
    len--;
1204
    if (!(flags & 0x10))
1205
        return -1;
1206
    if (len < 6)
1207
        return -1;
1208
    v = AV_RB32(p);
1209
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1210
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1211
    return 0;
1212
}
1213

    
1214
static int mpegts_read_header(AVFormatContext *s,
1215
                              AVFormatParameters *ap)
1216
{
1217
    MpegTSContext *ts = s->priv_data;
1218
    ByteIOContext *pb = s->pb;
1219
    uint8_t buf[1024];
1220
    int len;
1221
    int64_t pos;
1222

    
1223
    if (ap) {
1224
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1225
        if(ap->mpeg2ts_raw){
1226
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1227
            return -1;
1228
        }
1229
    }
1230

    
1231
    /* read the first 1024 bytes to get packet size */
1232
    pos = url_ftell(pb);
1233
    len = get_buffer(pb, buf, sizeof(buf));
1234
    if (len != sizeof(buf))
1235
        goto fail;
1236
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1237
    if (ts->raw_packet_size <= 0)
1238
        goto fail;
1239
    ts->stream = s;
1240
    ts->auto_guess = 0;
1241

    
1242
    if (s->iformat == &mpegts_demuxer) {
1243
        /* normal demux */
1244

    
1245
        /* first do a scaning to get all the services */
1246
        url_fseek(pb, pos, SEEK_SET);
1247
        mpegts_scan_sdt(ts);
1248

    
1249
        mpegts_set_service(ts);
1250

    
1251
        handle_packets(ts, s->probesize);
1252
        /* if could not find service, enable auto_guess */
1253

    
1254
        ts->auto_guess = 1;
1255

    
1256
#ifdef DEBUG_SI
1257
        av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1258
#endif
1259
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1260
    } else {
1261
        AVStream *st;
1262
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1263
        int64_t pcrs[2], pcr_h;
1264
        int packet_count[2];
1265
        uint8_t packet[TS_PACKET_SIZE];
1266

    
1267
        /* only read packets */
1268

    
1269
        st = av_new_stream(s, 0);
1270
        if (!st)
1271
            goto fail;
1272
        av_set_pts_info(st, 60, 1, 27000000);
1273
        st->codec->codec_type = CODEC_TYPE_DATA;
1274
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1275

    
1276
        /* we iterate until we find two PCRs to estimate the bitrate */
1277
        pcr_pid = -1;
1278
        nb_pcrs = 0;
1279
        nb_packets = 0;
1280
        for(;;) {
1281
            ret = read_packet(s->pb, packet, ts->raw_packet_size);
1282
            if (ret < 0)
1283
                return -1;
1284
            pid = AV_RB16(packet + 1) & 0x1fff;
1285
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1286
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1287
                pcr_pid = pid;
1288
                packet_count[nb_pcrs] = nb_packets;
1289
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1290
                nb_pcrs++;
1291
                if (nb_pcrs >= 2)
1292
                    break;
1293
            }
1294
            nb_packets++;
1295
        }
1296

    
1297
        /* NOTE1: the bitrate is computed without the FEC */
1298
        /* NOTE2: it is only the bitrate of the start of the stream */
1299
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1300
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1301
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1302
        st->codec->bit_rate = s->bit_rate;
1303
        st->start_time = ts->cur_pcr;
1304
#if 0
1305
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1306
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1307
#endif
1308
    }
1309

    
1310
    url_fseek(pb, pos, SEEK_SET);
1311
    return 0;
1312
 fail:
1313
    return -1;
1314
}
1315

    
1316
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1317

    
1318
static int mpegts_raw_read_packet(AVFormatContext *s,
1319
                                  AVPacket *pkt)
1320
{
1321
    MpegTSContext *ts = s->priv_data;
1322
    int ret, i;
1323
    int64_t pcr_h, next_pcr_h, pos;
1324
    int pcr_l, next_pcr_l;
1325
    uint8_t pcr_buf[12];
1326

    
1327
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1328
        return AVERROR(ENOMEM);
1329
    pkt->pos= url_ftell(s->pb);
1330
    ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1331
    if (ret < 0) {
1332
        av_free_packet(pkt);
1333
        return ret;
1334
    }
1335
    if (ts->mpeg2ts_compute_pcr) {
1336
        /* compute exact PCR for each packet */
1337
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1338
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1339
            pos = url_ftell(s->pb);
1340
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1341
                url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1342
                get_buffer(s->pb, pcr_buf, 12);
1343
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1344
                    /* XXX: not precise enough */
1345
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1346
                        (i + 1);
1347
                    break;
1348
                }
1349
            }
1350
            url_fseek(s->pb, pos, SEEK_SET);
1351
            /* no next PCR found: we use previous increment */
1352
            ts->cur_pcr = pcr_h * 300 + pcr_l;
1353
        }
1354
        pkt->pts = ts->cur_pcr;
1355
        pkt->duration = ts->pcr_incr;
1356
        ts->cur_pcr += ts->pcr_incr;
1357
    }
1358
    pkt->stream_index = 0;
1359
    return 0;
1360
}
1361

    
1362
static int mpegts_read_packet(AVFormatContext *s,
1363
                              AVPacket *pkt)
1364
{
1365
    MpegTSContext *ts = s->priv_data;
1366

    
1367
    ts->pkt = pkt;
1368
    return handle_packets(ts, 0);
1369
}
1370

    
1371
static int mpegts_read_close(AVFormatContext *s)
1372
{
1373
    MpegTSContext *ts = s->priv_data;
1374
    int i;
1375

    
1376
    clear_programs(ts);
1377

    
1378
    for(i=0;i<NB_PID_MAX;i++)
1379
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1380

    
1381
    return 0;
1382
}
1383

    
1384
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1385
                              int64_t *ppos, int64_t pos_limit)
1386
{
1387
    MpegTSContext *ts = s->priv_data;
1388
    int64_t pos, timestamp;
1389
    uint8_t buf[TS_PACKET_SIZE];
1390
    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1391
    const int find_next= 1;
1392
    pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1393
    if (find_next) {
1394
        for(;;) {
1395
            url_fseek(s->pb, pos, SEEK_SET);
1396
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1397
                return AV_NOPTS_VALUE;
1398
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1399
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1400
                break;
1401
            }
1402
            pos += ts->raw_packet_size;
1403
        }
1404
    } else {
1405
        for(;;) {
1406
            pos -= ts->raw_packet_size;
1407
            if (pos < 0)
1408
                return AV_NOPTS_VALUE;
1409
            url_fseek(s->pb, pos, SEEK_SET);
1410
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1411
                return AV_NOPTS_VALUE;
1412
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1413
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1414
                break;
1415
            }
1416
        }
1417
    }
1418
    *ppos = pos;
1419

    
1420
    return timestamp;
1421
}
1422

    
1423
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1424
    MpegTSContext *ts = s->priv_data;
1425
    uint8_t buf[TS_PACKET_SIZE];
1426
    int64_t pos;
1427

    
1428
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1429
        return -1;
1430

    
1431
    pos= url_ftell(s->pb);
1432

    
1433
    for(;;) {
1434
        url_fseek(s->pb, pos, SEEK_SET);
1435
        if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1436
            return -1;
1437
//        pid = AV_RB16(buf + 1) & 0x1fff;
1438
        if(buf[1] & 0x40) break;
1439
        pos += ts->raw_packet_size;
1440
    }
1441
    url_fseek(s->pb, pos, SEEK_SET);
1442

    
1443
    return 0;
1444
}
1445

    
1446
/**************************************************************/
1447
/* parsing functions - called from other demuxers such as RTP */
1448

    
1449
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1450
{
1451
    MpegTSContext *ts;
1452

    
1453
    ts = av_mallocz(sizeof(MpegTSContext));
1454
    if (!ts)
1455
        return NULL;
1456
    /* no stream case, currently used by RTP */
1457
    ts->raw_packet_size = TS_PACKET_SIZE;
1458
    ts->stream = s;
1459
    ts->auto_guess = 1;
1460
    return ts;
1461
}
1462

    
1463
/* return the consumed length if a packet was output, or -1 if no
1464
   packet is output */
1465
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1466
                        const uint8_t *buf, int len)
1467
{
1468
    int len1;
1469

    
1470
    len1 = len;
1471
    ts->pkt = pkt;
1472
    ts->stop_parse = 0;
1473
    for(;;) {
1474
        if (ts->stop_parse>0)
1475
            break;
1476
        if (len < TS_PACKET_SIZE)
1477
            return -1;
1478
        if (buf[0] != 0x47) {
1479
            buf++;
1480
            len--;
1481
        } else {
1482
            handle_packet(ts, buf);
1483
            buf += TS_PACKET_SIZE;
1484
            len -= TS_PACKET_SIZE;
1485
        }
1486
    }
1487
    return len1 - len;
1488
}
1489

    
1490
void mpegts_parse_close(MpegTSContext *ts)
1491
{
1492
    int i;
1493

    
1494
    for(i=0;i<NB_PID_MAX;i++)
1495
        av_free(ts->pids[i]);
1496
    av_free(ts);
1497
}
1498

    
1499
AVInputFormat mpegts_demuxer = {
1500
    "mpegts",
1501
    "MPEG2 transport stream format",
1502
    sizeof(MpegTSContext),
1503
    mpegts_probe,
1504
    mpegts_read_header,
1505
    mpegts_read_packet,
1506
    mpegts_read_close,
1507
    read_seek,
1508
    mpegts_get_pcr,
1509
    .flags = AVFMT_SHOW_IDS,
1510
};
1511

    
1512
AVInputFormat mpegtsraw_demuxer = {
1513
    "mpegtsraw",
1514
    "MPEG2 raw transport stream format",
1515
    sizeof(MpegTSContext),
1516
    NULL,
1517
    mpegts_read_header,
1518
    mpegts_raw_read_packet,
1519
    mpegts_read_close,
1520
    read_seek,
1521
    mpegts_get_pcr,
1522
    .flags = AVFMT_SHOW_IDS,
1523
};