Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ e0c850a8

History | View | Annotate | Download (40.8 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
#include "allformats.h"
25

    
26
//#define DEBUG_SI
27
//#define DEBUG_SEEK
28

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

    
32
/* maximum size in which we look for synchronisation if
33
   synchronisation is lost */
34
#define MAX_RESYNC_SIZE 4096
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

    
41
enum MpegTSFilterType {
42
    MPEGTS_PES,
43
    MPEGTS_SECTION,
44
};
45

    
46
typedef struct MpegTSFilter MpegTSFilter;
47

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

    
50
typedef struct MpegTSPESFilter {
51
    PESCallback *pes_cb;
52
    void *opaque;
53
} MpegTSPESFilter;
54

    
55
typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
56

    
57
typedef void SetServiceCallback(void *opaque, int ret);
58

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

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

    
79
typedef struct MpegTSService {
80
    int running:1;
81
    int sid;    /**< MPEG Program Number of stream */
82
    char *provider_name; /**< DVB Network name, "" if not DVB stream */
83
    char *name; /**< DVB Service name, "MPEG Program [sid]" if not DVB stream*/
84
} MpegTSService;
85

    
86
struct MpegTSContext {
87
    /* user data */
88
    AVFormatContext *stream;
89
    /** raw packet size, including FEC if present            */
90
    int raw_packet_size;
91
    /** if true, all pids are analyzed to find streams       */
92
    int auto_guess;
93

    
94
    /** compute exact PCR for each transport stream packet   */
95
    int mpeg2ts_compute_pcr;
96

    
97
    int64_t cur_pcr;    /**< used to estimate the exact PCR  */
98
    int pcr_incr;       /**< used to estimate the exact PCR  */
99

    
100
    /* data needed to handle file based ts */
101
    /** stop parsing loop                                    */
102
    int stop_parse;
103
    /** packet containing Audio/Video data                   */
104
    AVPacket *pkt;
105

    
106
    /******************************************/
107
    /* private mpegts data */
108
    /* scan context */
109
    /** number of PMTs in the last PAT seen                  */
110
    int nb_services;
111
    /** list of PMTs in the last PAT seen                    */
112
    MpegTSService **services;
113

    
114

    
115
    /** filters for various streams specified by PMT + for the PAT and PMT */
116
    MpegTSFilter *pids[NB_PID_MAX];
117
};
118

    
119
/* TS stream handling */
120

    
121
enum MpegTSState {
122
    MPEGTS_HEADER = 0,
123
    MPEGTS_PESHEADER_FILL,
124
    MPEGTS_PAYLOAD,
125
    MPEGTS_SKIP,
126
};
127

    
128
/* enough for PES header + length */
129
#define PES_START_SIZE 9
130
#define MAX_PES_HEADER_SIZE (9 + 255)
131

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

    
148
/**
149
 *  Assembles PES packets out of TS packets, and then calls the "section_cb"
150
 *  function when they are complete.
151
 */
152
static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
153
                               const uint8_t *buf, int buf_size, int is_start)
154
{
155
    MpegTSSectionFilter *tss = &tss1->u.section_filter;
156
    int len;
157

    
158
    if (is_start) {
159
        memcpy(tss->section_buf, buf, buf_size);
160
        tss->section_index = buf_size;
161
        tss->section_h_size = -1;
162
        tss->end_of_section_reached = 0;
163
    } else {
164
        if (tss->end_of_section_reached)
165
            return;
166
        len = 4096 - tss->section_index;
167
        if (buf_size < len)
168
            len = buf_size;
169
        memcpy(tss->section_buf + tss->section_index, buf, len);
170
        tss->section_index += len;
171
    }
172

    
173
    /* compute section length if possible */
174
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
175
        len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
176
        if (len > 4096)
177
            return;
178
        tss->section_h_size = len;
179
    }
180

    
181
    if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
182
        tss->end_of_section_reached = 1;
183
        if (!tss->check_crc ||
184
            av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
185
            tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
186
    }
187
}
188

    
189
static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
190
                                         SectionCallback *section_cb, void *opaque,
191
                                         int check_crc)
192

    
193
{
194
    MpegTSFilter *filter;
195
    MpegTSSectionFilter *sec;
196

    
197
#ifdef DEBUG_SI
198
    av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
199
#endif
200
    if (pid >= NB_PID_MAX || ts->pids[pid])
201
        return NULL;
202
    filter = av_mallocz(sizeof(MpegTSFilter));
203
    if (!filter)
204
        return NULL;
205
    ts->pids[pid] = filter;
206
    filter->type = MPEGTS_SECTION;
207
    filter->pid = pid;
208
    filter->last_cc = -1;
209
    sec = &filter->u.section_filter;
210
    sec->section_cb = section_cb;
211
    sec->opaque = opaque;
212
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
213
    sec->check_crc = check_crc;
214
    if (!sec->section_buf) {
215
        av_free(filter);
216
        return NULL;
217
    }
218
    return filter;
219
}
220

    
221
static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
222
                                     PESCallback *pes_cb,
223
                                     void *opaque)
224
{
225
    MpegTSFilter *filter;
226
    MpegTSPESFilter *pes;
227

    
228
    if (pid >= NB_PID_MAX || ts->pids[pid])
229
        return NULL;
230
    filter = av_mallocz(sizeof(MpegTSFilter));
231
    if (!filter)
232
        return NULL;
233
    ts->pids[pid] = filter;
234
    filter->type = MPEGTS_PES;
235
    filter->pid = pid;
236
    filter->last_cc = -1;
237
    pes = &filter->u.pes_filter;
238
    pes->pes_cb = pes_cb;
239
    pes->opaque = opaque;
240
    return filter;
241
}
242

    
243
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
244
{
245
    int pid;
246

    
247
    pid = filter->pid;
248
    if (filter->type == MPEGTS_SECTION)
249
        av_freep(&filter->u.section_filter.section_buf);
250
    else if (filter->type == MPEGTS_PES)
251
        av_freep(&filter->u.pes_filter.opaque);
252

    
253
    av_free(filter);
254
    ts->pids[pid] = NULL;
255
}
256

    
257
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
258
    int stat[packet_size];
259
    int i;
260
    int x=0;
261
    int best_score=0;
262

    
263
    memset(stat, 0, packet_size*sizeof(int));
264

    
265
    for(x=i=0; i<size; i++){
266
        if(buf[i] == 0x47){
267
            stat[x]++;
268
            if(stat[x] > best_score){
269
                best_score= stat[x];
270
                if(index) *index= x;
271
            }
272
        }
273

    
274
        x++;
275
        if(x == packet_size) x= 0;
276
    }
277

    
278
    return best_score;
279
}
280

    
281
/* autodetect fec presence. Must have at least 1024 bytes  */
282
static int get_packet_size(const uint8_t *buf, int size)
283
{
284
    int score, fec_score, dvhs_score;
285

    
286
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
287
        return -1;
288

    
289
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
290
    dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
291
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
292
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
293

    
294
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
295
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
296
    else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
297
    else                       return -1;
298
}
299

    
300
typedef struct SectionHeader {
301
    uint8_t tid;
302
    uint16_t id;
303
    uint8_t version;
304
    uint8_t sec_num;
305
    uint8_t last_sec_num;
306
} SectionHeader;
307

    
308
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
309
{
310
    const uint8_t *p;
311
    int c;
312

    
313
    p = *pp;
314
    if (p >= p_end)
315
        return -1;
316
    c = *p++;
317
    *pp = p;
318
    return c;
319
}
320

    
321
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
322
{
323
    const uint8_t *p;
324
    int c;
325

    
326
    p = *pp;
327
    if ((p + 1) >= p_end)
328
        return -1;
329
    c = AV_RB16(p);
330
    p += 2;
331
    *pp = p;
332
    return c;
333
}
334

    
335
/* read and allocate a DVB string preceeded by its length */
336
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
337
{
338
    int len;
339
    const uint8_t *p;
340
    char *str;
341

    
342
    p = *pp;
343
    len = get8(&p, p_end);
344
    if (len < 0)
345
        return NULL;
346
    if ((p + len) > p_end)
347
        return NULL;
348
    str = av_malloc(len + 1);
349
    if (!str)
350
        return NULL;
351
    memcpy(str, p, len);
352
    str[len] = '\0';
353
    p += len;
354
    *pp = p;
355
    return str;
356
}
357

    
358
static int parse_section_header(SectionHeader *h,
359
                                const uint8_t **pp, const uint8_t *p_end)
360
{
361
    int val;
362

    
363
    val = get8(pp, p_end);
364
    if (val < 0)
365
        return -1;
366
    h->tid = val;
367
    *pp += 2;
368
    val = get16(pp, p_end);
369
    if (val < 0)
370
        return -1;
371
    h->id = val;
372
    val = get8(pp, p_end);
373
    if (val < 0)
374
        return -1;
375
    h->version = (val >> 1) & 0x1f;
376
    val = get8(pp, p_end);
377
    if (val < 0)
378
        return -1;
379
    h->sec_num = val;
380
    val = get8(pp, p_end);
381
    if (val < 0)
382
        return -1;
383
    h->last_sec_num = val;
384
    return 0;
385
}
386

    
387
static MpegTSService *new_service(MpegTSContext *ts, int sid,
388
                                  char *provider_name, char *name)
389
{
390
    MpegTSService *service=NULL;
391
    int i;
392

    
393
#ifdef DEBUG_SI
394
    av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
395
           "sid=0x%04x provider='%s' name='%s'\n",
396
           sid, provider_name, name);
397
#endif
398

    
399
    for(i=0; i<ts->nb_services; i++)
400
        if(ts->services[i]->sid == sid)
401
            service= ts->services[i];
402

    
403
    if(!service){
404
        service = av_mallocz(sizeof(MpegTSService));
405
        if (!service)
406
            return NULL;
407
        dynarray_add(&ts->services, &ts->nb_services, service);
408
    }
409
    service->sid = sid;
410
    assert((!provider_name) == (!name));
411
    if(name){
412
        av_free(service->provider_name);
413
        av_free(service->         name);
414
        service->provider_name = provider_name;
415
        service->         name =          name;
416
    }
417
    return service;
418
}
419

    
420
static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
421
{
422
    MpegTSContext *ts = filter->u.section_filter.opaque;
423
    SectionHeader h1, *h = &h1;
424
    PESContext *pes;
425
    AVStream *st;
426
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
427
    int program_info_length, pcr_pid, pid, stream_type;
428
    int desc_list_len, desc_len, desc_tag;
429
    int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
430
    char language[4] = {0}; /* initialize to kill warnings */
431

    
432
#ifdef DEBUG_SI
433
    av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
434
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
435
#endif
436
    p_end = section + section_len - 4;
437
    p = section;
438
    if (parse_section_header(h, &p, p_end) < 0)
439
        return;
440
#ifdef DEBUG_SI
441
    av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
442
           h->id, h->sec_num, h->last_sec_num);
443
#endif
444
    if (h->tid != PMT_TID)
445
        return;
446

    
447
    pcr_pid = get16(&p, p_end) & 0x1fff;
448
    if (pcr_pid < 0)
449
        return;
450
#ifdef DEBUG_SI
451
    av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
452
#endif
453
    program_info_length = get16(&p, p_end) & 0xfff;
454
    if (program_info_length < 0)
455
        return;
456
    p += program_info_length;
457
    if (p >= p_end)
458
        return;
459
    for(;;) {
460
        language[0] = 0;
461
        st = 0;
462
        stream_type = get8(&p, p_end);
463
        if (stream_type < 0)
464
            break;
465
        pid = get16(&p, p_end) & 0x1fff;
466
        if (pid < 0)
467
            break;
468
        desc_list_len = get16(&p, p_end) & 0xfff;
469
        if (desc_list_len < 0)
470
            break;
471
        desc_list_end = p + desc_list_len;
472
        if (desc_list_end > p_end)
473
            break;
474
        for(;;) {
475
            desc_tag = get8(&p, desc_list_end);
476
            if (desc_tag < 0)
477
                break;
478
            if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
479
                if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
480
                    /*assume DVB AC-3 Audio*/
481
                    stream_type = STREAM_TYPE_AUDIO_AC3;
482
                } else if(desc_tag == 0x7B) {
483
                    /* DVB DTS audio */
484
                    stream_type = STREAM_TYPE_AUDIO_DTS;
485
                }
486
            }
487
            desc_len = get8(&p, desc_list_end);
488
            desc_end = p + desc_len;
489
            if (desc_end > desc_list_end)
490
                break;
491
#ifdef DEBUG_SI
492
            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
493
                   desc_tag, desc_len);
494
#endif
495
            switch(desc_tag) {
496
            case DVB_SUBT_DESCID:
497
                if (stream_type == STREAM_TYPE_PRIVATE_DATA)
498
                    stream_type = STREAM_TYPE_SUBTITLE_DVB;
499

    
500
                language[0] = get8(&p, desc_end);
501
                language[1] = get8(&p, desc_end);
502
                language[2] = get8(&p, desc_end);
503
                language[3] = 0;
504
                get8(&p, desc_end);
505
                comp_page = get16(&p, desc_end);
506
                anc_page = get16(&p, desc_end);
507

    
508
                break;
509
            case 0x0a: /* ISO 639 language descriptor */
510
                language[0] = get8(&p, desc_end);
511
                language[1] = get8(&p, desc_end);
512
                language[2] = get8(&p, desc_end);
513
                language[3] = 0;
514
                break;
515
            default:
516
                break;
517
            }
518
            p = desc_end;
519
        }
520
        p = desc_list_end;
521

    
522
#ifdef DEBUG_SI
523
        av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
524
               stream_type, pid);
525
#endif
526

    
527
        /* now create ffmpeg stream */
528
        switch(stream_type) {
529
        case STREAM_TYPE_AUDIO_MPEG1:
530
        case STREAM_TYPE_AUDIO_MPEG2:
531
        case STREAM_TYPE_VIDEO_MPEG1:
532
        case STREAM_TYPE_VIDEO_MPEG2:
533
        case STREAM_TYPE_VIDEO_MPEG4:
534
        case STREAM_TYPE_VIDEO_H264:
535
        case STREAM_TYPE_VIDEO_VC1:
536
        case STREAM_TYPE_AUDIO_AAC:
537
        case STREAM_TYPE_AUDIO_AC3:
538
        case STREAM_TYPE_AUDIO_DTS:
539
        case STREAM_TYPE_SUBTITLE_DVB:
540
            if(ts->pids[pid]){
541
                assert(ts->pids[pid]->type == MPEGTS_PES);
542
                pes= ts->pids[pid]->u.pes_filter.opaque;
543
                st= pes->st;
544
            }else{
545
                pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
546
                if (pes)
547
                    st = new_pes_av_stream(pes, 0);
548
            }
549
            break;
550
        default:
551
            /* we ignore the other streams */
552
            break;
553
        }
554

    
555
        if (st) {
556
            if (language[0] != 0) {
557
                memcpy(st->language, language, 4);
558
            }
559

    
560
            if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
561
                st->codec->sub_id = (anc_page << 16) | comp_page;
562
            }
563
        }
564
    }
565
    /* all parameters are there */
566
    ts->stop_parse++;
567
    mpegts_close_filter(ts, filter);
568
}
569

    
570
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
571
{
572
    MpegTSContext *ts = filter->u.section_filter.opaque;
573
    SectionHeader h1, *h = &h1;
574
    const uint8_t *p, *p_end;
575
    int sid, pmt_pid;
576

    
577
#ifdef DEBUG_SI
578
    av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
579
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
580
#endif
581
    p_end = section + section_len - 4;
582
    p = section;
583
    if (parse_section_header(h, &p, p_end) < 0)
584
        return;
585
    if (h->tid != PAT_TID)
586
        return;
587

    
588
    for(;;) {
589
        sid = get16(&p, p_end);
590
        if (sid < 0)
591
            break;
592
        pmt_pid = get16(&p, p_end) & 0x1fff;
593
        if (pmt_pid < 0)
594
            break;
595
#ifdef DEBUG_SI
596
        av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
597
#endif
598
        if (sid == 0x0000) {
599
            /* NIT info */
600
        } else {
601
            new_service(ts, sid, NULL, NULL);
602
            ts->stop_parse--;
603
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
604
        }
605
    }
606
    /* not found */
607
    ts->stop_parse++;
608

    
609
    mpegts_close_filter(ts, filter);
610
}
611

    
612
static void mpegts_set_service(MpegTSContext *ts)
613
{
614
    mpegts_open_section_filter(ts, PAT_PID,
615
                                                pat_cb, ts, 1);
616
}
617

    
618
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
619
{
620
    MpegTSContext *ts = filter->u.section_filter.opaque;
621
    SectionHeader h1, *h = &h1;
622
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
623
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
624
    char *name, *provider_name;
625

    
626
#ifdef DEBUG_SI
627
    av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
628
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
629
#endif
630

    
631
    p_end = section + section_len - 4;
632
    p = section;
633
    if (parse_section_header(h, &p, p_end) < 0)
634
        return;
635
    if (h->tid != SDT_TID)
636
        return;
637
    onid = get16(&p, p_end);
638
    if (onid < 0)
639
        return;
640
    val = get8(&p, p_end);
641
    if (val < 0)
642
        return;
643
    for(;;) {
644
        sid = get16(&p, p_end);
645
        if (sid < 0)
646
            break;
647
        val = get8(&p, p_end);
648
        if (val < 0)
649
            break;
650
        desc_list_len = get16(&p, p_end) & 0xfff;
651
        if (desc_list_len < 0)
652
            break;
653
        desc_list_end = p + desc_list_len;
654
        if (desc_list_end > p_end)
655
            break;
656
        for(;;) {
657
            desc_tag = get8(&p, desc_list_end);
658
            if (desc_tag < 0)
659
                break;
660
            desc_len = get8(&p, desc_list_end);
661
            desc_end = p + desc_len;
662
            if (desc_end > desc_list_end)
663
                break;
664
#ifdef DEBUG_SI
665
            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
666
                   desc_tag, desc_len);
667
#endif
668
            switch(desc_tag) {
669
            case 0x48:
670
                service_type = get8(&p, p_end);
671
                if (service_type < 0)
672
                    break;
673
                provider_name = getstr8(&p, p_end);
674
                if (!provider_name)
675
                    break;
676
                name = getstr8(&p, p_end);
677
                if (!name)
678
                    break;
679
                new_service(ts, sid, provider_name, name);
680
                break;
681
            default:
682
                break;
683
            }
684
            p = desc_end;
685
        }
686
        p = desc_list_end;
687
    }
688
}
689

    
690
/* scan services in a transport stream by looking at the SDT */
691
static void mpegts_scan_sdt(MpegTSContext *ts)
692
{
693
    mpegts_open_section_filter(ts, SDT_PID,
694
                                                sdt_cb, ts, 1);
695
}
696

    
697
static int64_t get_pts(const uint8_t *p)
698
{
699
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
700
    pts |= (AV_RB16(p + 1) >> 1) << 15;
701
    pts |=  AV_RB16(p + 3) >> 1;
702
    return pts;
703
}
704

    
705
/* return non zero if a packet could be constructed */
706
static void mpegts_push_data(MpegTSFilter *filter,
707
                             const uint8_t *buf, int buf_size, int is_start)
708
{
709
    PESContext *pes = filter->u.pes_filter.opaque;
710
    MpegTSContext *ts = pes->ts;
711
    const uint8_t *p;
712
    int len, code;
713

    
714
    if(!ts->pkt)
715
        return;
716

    
717
    if (is_start) {
718
        pes->state = MPEGTS_HEADER;
719
        pes->data_index = 0;
720
    }
721
    p = buf;
722
    while (buf_size > 0) {
723
        switch(pes->state) {
724
        case MPEGTS_HEADER:
725
            len = PES_START_SIZE - pes->data_index;
726
            if (len > buf_size)
727
                len = buf_size;
728
            memcpy(pes->header + pes->data_index, p, len);
729
            pes->data_index += len;
730
            p += len;
731
            buf_size -= len;
732
            if (pes->data_index == PES_START_SIZE) {
733
                /* we got all the PES or section header. We can now
734
                   decide */
735
#if 0
736
                av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
737
#endif
738
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
739
                    pes->header[2] == 0x01) {
740
                    /* it must be an mpeg2 PES stream */
741
                    code = pes->header[3] | 0x100;
742
                    if (!((code >= 0x1c0 && code <= 0x1df) ||
743
                          (code >= 0x1e0 && code <= 0x1ef) ||
744
                          (code == 0x1bd) || (code == 0x1fd)))
745
                        goto skip;
746
                    if (!pes->st) {
747
                        /* allocate stream */
748
                        new_pes_av_stream(pes, code);
749
                    }
750
                    pes->state = MPEGTS_PESHEADER_FILL;
751
                    pes->total_size = AV_RB16(pes->header + 4);
752
                    /* NOTE: a zero total size means the PES size is
753
                       unbounded */
754
                    if (pes->total_size)
755
                        pes->total_size += 6;
756
                    pes->pes_header_size = pes->header[8] + 9;
757
                } else {
758
                    /* otherwise, it should be a table */
759
                    /* skip packet */
760
                skip:
761
                    pes->state = MPEGTS_SKIP;
762
                    continue;
763
                }
764
            }
765
            break;
766
            /**********************************************/
767
            /* PES packing parsing */
768
        case MPEGTS_PESHEADER_FILL:
769
            len = pes->pes_header_size - pes->data_index;
770
            if (len > buf_size)
771
                len = buf_size;
772
            memcpy(pes->header + pes->data_index, p, len);
773
            pes->data_index += len;
774
            p += len;
775
            buf_size -= len;
776
            if (pes->data_index == pes->pes_header_size) {
777
                const uint8_t *r;
778
                unsigned int flags;
779

    
780
                flags = pes->header[7];
781
                r = pes->header + 9;
782
                pes->pts = AV_NOPTS_VALUE;
783
                pes->dts = AV_NOPTS_VALUE;
784
                if ((flags & 0xc0) == 0x80) {
785
                    pes->pts = get_pts(r);
786
                    r += 5;
787
                } else if ((flags & 0xc0) == 0xc0) {
788
                    pes->pts = get_pts(r);
789
                    r += 5;
790
                    pes->dts = get_pts(r);
791
                    r += 5;
792
                }
793
                /* we got the full header. We parse it and get the payload */
794
                pes->state = MPEGTS_PAYLOAD;
795
            }
796
            break;
797
        case MPEGTS_PAYLOAD:
798
            if (pes->total_size) {
799
                len = pes->total_size - pes->data_index;
800
                if (len > buf_size)
801
                    len = buf_size;
802
            } else {
803
                len = buf_size;
804
            }
805
            if (len > 0) {
806
                AVPacket *pkt = ts->pkt;
807
                if (pes->st && av_new_packet(pkt, len) == 0) {
808
                    memcpy(pkt->data, p, len);
809
                    pkt->stream_index = pes->st->index;
810
                    pkt->pts = pes->pts;
811
                    pkt->dts = pes->dts;
812
                    /* reset pts values */
813
                    pes->pts = AV_NOPTS_VALUE;
814
                    pes->dts = AV_NOPTS_VALUE;
815
                    ts->stop_parse = 1;
816
                    return;
817
                }
818
            }
819
            buf_size = 0;
820
            break;
821
        case MPEGTS_SKIP:
822
            buf_size = 0;
823
            break;
824
        }
825
    }
826
}
827

    
828
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
829
{
830
    AVStream *st;
831
    int codec_type, codec_id;
832

    
833
    switch(pes->stream_type){
834
    case STREAM_TYPE_AUDIO_MPEG1:
835
    case STREAM_TYPE_AUDIO_MPEG2:
836
        codec_type = CODEC_TYPE_AUDIO;
837
        codec_id = CODEC_ID_MP3;
838
        break;
839
    case STREAM_TYPE_VIDEO_MPEG1:
840
    case STREAM_TYPE_VIDEO_MPEG2:
841
        codec_type = CODEC_TYPE_VIDEO;
842
        codec_id = CODEC_ID_MPEG2VIDEO;
843
        break;
844
    case STREAM_TYPE_VIDEO_MPEG4:
845
        codec_type = CODEC_TYPE_VIDEO;
846
        codec_id = CODEC_ID_MPEG4;
847
        break;
848
    case STREAM_TYPE_VIDEO_H264:
849
        codec_type = CODEC_TYPE_VIDEO;
850
        codec_id = CODEC_ID_H264;
851
        break;
852
    case STREAM_TYPE_VIDEO_VC1:
853
        codec_type = CODEC_TYPE_VIDEO;
854
        codec_id = CODEC_ID_VC1;
855
        break;
856
    case STREAM_TYPE_AUDIO_AAC:
857
        codec_type = CODEC_TYPE_AUDIO;
858
        codec_id = CODEC_ID_AAC;
859
        break;
860
    case STREAM_TYPE_AUDIO_AC3:
861
        codec_type = CODEC_TYPE_AUDIO;
862
        codec_id = CODEC_ID_AC3;
863
        break;
864
    case STREAM_TYPE_AUDIO_DTS:
865
        codec_type = CODEC_TYPE_AUDIO;
866
        codec_id = CODEC_ID_DTS;
867
        break;
868
    case STREAM_TYPE_SUBTITLE_DVB:
869
        codec_type = CODEC_TYPE_SUBTITLE;
870
        codec_id = CODEC_ID_DVB_SUBTITLE;
871
        break;
872
    default:
873
        if (code >= 0x1c0 && code <= 0x1df) {
874
            codec_type = CODEC_TYPE_AUDIO;
875
            codec_id = CODEC_ID_MP2;
876
        } else if (code == 0x1bd) {
877
            codec_type = CODEC_TYPE_AUDIO;
878
            codec_id = CODEC_ID_AC3;
879
        } else {
880
            codec_type = CODEC_TYPE_VIDEO;
881
            codec_id = CODEC_ID_MPEG1VIDEO;
882
        }
883
        break;
884
    }
885
    st = av_new_stream(pes->stream, pes->pid);
886
    if (st) {
887
        av_set_pts_info(st, 33, 1, 90000);
888
        st->priv_data = pes;
889
        st->codec->codec_type = codec_type;
890
        st->codec->codec_id = codec_id;
891
        st->need_parsing = AVSTREAM_PARSE_FULL;
892
        pes->st = st;
893
    }
894
    return st;
895
}
896

    
897

    
898
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
899
{
900
    MpegTSFilter *tss;
901
    PESContext *pes;
902

    
903
    /* if no pid found, then add a pid context */
904
    pes = av_mallocz(sizeof(PESContext));
905
    if (!pes)
906
        return 0;
907
    pes->ts = ts;
908
    pes->stream = ts->stream;
909
    pes->pid = pid;
910
    pes->pcr_pid = pcr_pid;
911
    pes->stream_type = stream_type;
912
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
913
    if (!tss) {
914
        av_free(pes);
915
        return 0;
916
    }
917
    return pes;
918
}
919

    
920
/* handle one TS packet */
921
static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
922
{
923
    AVFormatContext *s = ts->stream;
924
    MpegTSFilter *tss;
925
    int len, pid, cc, cc_ok, afc, is_start;
926
    const uint8_t *p, *p_end;
927

    
928
    pid = AV_RB16(packet + 1) & 0x1fff;
929
    is_start = packet[1] & 0x40;
930
    tss = ts->pids[pid];
931
    if (ts->auto_guess && tss == NULL && is_start) {
932
        add_pes_stream(ts, pid, -1, 0);
933
        tss = ts->pids[pid];
934
    }
935
    if (!tss)
936
        return;
937

    
938
    /* continuity check (currently not used) */
939
    cc = (packet[3] & 0xf);
940
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
941
    tss->last_cc = cc;
942

    
943
    /* skip adaptation field */
944
    afc = (packet[3] >> 4) & 3;
945
    p = packet + 4;
946
    if (afc == 0) /* reserved value */
947
        return;
948
    if (afc == 2) /* adaptation field only */
949
        return;
950
    if (afc == 3) {
951
        /* skip adapation field */
952
        p += p[0] + 1;
953
    }
954
    /* if past the end of packet, ignore */
955
    p_end = packet + TS_PACKET_SIZE;
956
    if (p >= p_end)
957
        return;
958

    
959
    if (tss->type == MPEGTS_SECTION) {
960
        if (is_start) {
961
            /* pointer field present */
962
            len = *p++;
963
            if (p + len > p_end)
964
                return;
965
            if (len && cc_ok) {
966
                /* write remaining section bytes */
967
                write_section_data(s, tss,
968
                                   p, len, 0);
969
                /* check whether filter has been closed */
970
                if (!ts->pids[pid])
971
                    return;
972
            }
973
            p += len;
974
            if (p < p_end) {
975
                write_section_data(s, tss,
976
                                   p, p_end - p, 1);
977
            }
978
        } else {
979
            if (cc_ok) {
980
                write_section_data(s, tss,
981
                                   p, p_end - p, 0);
982
            }
983
        }
984
    } else {
985
        tss->u.pes_filter.pes_cb(tss,
986
                                 p, p_end - p, is_start);
987
    }
988
}
989

    
990
/* XXX: try to find a better synchro over several packets (use
991
   get_packet_size() ?) */
992
static int mpegts_resync(ByteIOContext *pb)
993
{
994
    int c, i;
995

    
996
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
997
        c = url_fgetc(pb);
998
        if (c < 0)
999
            return -1;
1000
        if (c == 0x47) {
1001
            url_fseek(pb, -1, SEEK_CUR);
1002
            return 0;
1003
        }
1004
    }
1005
    /* no sync found */
1006
    return -1;
1007
}
1008

    
1009
/* return -1 if error or EOF. Return 0 if OK. */
1010
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1011
{
1012
    int skip, len;
1013

    
1014
    for(;;) {
1015
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1016
        if (len != TS_PACKET_SIZE)
1017
            return AVERROR(EIO);
1018
        /* check paquet sync byte */
1019
        if (buf[0] != 0x47) {
1020
            /* find a new packet start */
1021
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1022
            if (mpegts_resync(pb) < 0)
1023
                return AVERROR_INVALIDDATA;
1024
            else
1025
                continue;
1026
        } else {
1027
            skip = raw_packet_size - TS_PACKET_SIZE;
1028
            if (skip > 0)
1029
                url_fskip(pb, skip);
1030
            break;
1031
        }
1032
    }
1033
    return 0;
1034
}
1035

    
1036
static int handle_packets(MpegTSContext *ts, int nb_packets)
1037
{
1038
    AVFormatContext *s = ts->stream;
1039
    ByteIOContext *pb = &s->pb;
1040
    uint8_t packet[TS_PACKET_SIZE];
1041
    int packet_num, ret;
1042

    
1043
    ts->stop_parse = 0;
1044
    packet_num = 0;
1045
    for(;;) {
1046
        if (ts->stop_parse>0)
1047
            break;
1048
        packet_num++;
1049
        if (nb_packets != 0 && packet_num >= nb_packets)
1050
            break;
1051
        ret = read_packet(pb, packet, ts->raw_packet_size);
1052
        if (ret != 0)
1053
            return ret;
1054
        handle_packet(ts, packet);
1055
    }
1056
    return 0;
1057
}
1058

    
1059
static int mpegts_probe(AVProbeData *p)
1060
{
1061
#if 1
1062
    const int size= p->buf_size;
1063
    int score, fec_score, dvhs_score;
1064
#define CHECK_COUNT 10
1065

    
1066
    if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1067
        return -1;
1068

    
1069
    score    = analyze(p->buf, TS_PACKET_SIZE    *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1070
    dvhs_score  = analyze(p->buf, TS_DVHS_PACKET_SIZE    *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1071
    fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1072
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1073

    
1074
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1075
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1076
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1077
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1078
    else                                    return -1;
1079
#else
1080
    /* only use the extension for safer guess */
1081
    if (match_ext(p->filename, "ts"))
1082
        return AVPROBE_SCORE_MAX;
1083
    else
1084
        return 0;
1085
#endif
1086
}
1087

    
1088
/* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1089
   (-1) if not available */
1090
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1091
                     const uint8_t *packet)
1092
{
1093
    int afc, len, flags;
1094
    const uint8_t *p;
1095
    unsigned int v;
1096

    
1097
    afc = (packet[3] >> 4) & 3;
1098
    if (afc <= 1)
1099
        return -1;
1100
    p = packet + 4;
1101
    len = p[0];
1102
    p++;
1103
    if (len == 0)
1104
        return -1;
1105
    flags = *p++;
1106
    len--;
1107
    if (!(flags & 0x10))
1108
        return -1;
1109
    if (len < 6)
1110
        return -1;
1111
    v = AV_RB32(p);
1112
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1113
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1114
    return 0;
1115
}
1116

    
1117
static int mpegts_read_header(AVFormatContext *s,
1118
                              AVFormatParameters *ap)
1119
{
1120
    MpegTSContext *ts = s->priv_data;
1121
    ByteIOContext *pb = &s->pb;
1122
    uint8_t buf[1024];
1123
    int len;
1124
    int64_t pos;
1125

    
1126
    if (ap) {
1127
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1128
        if(ap->mpeg2ts_raw){
1129
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1130
            return -1;
1131
        }
1132
    }
1133

    
1134
    /* read the first 1024 bytes to get packet size */
1135
    pos = url_ftell(pb);
1136
    len = get_buffer(pb, buf, sizeof(buf));
1137
    if (len != sizeof(buf))
1138
        goto fail;
1139
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1140
    if (ts->raw_packet_size <= 0)
1141
        goto fail;
1142
    ts->stream = s;
1143
    ts->auto_guess = 0;
1144

    
1145
    if (s->iformat == &mpegts_demuxer) {
1146
        /* normal demux */
1147

    
1148
        /* first do a scaning to get all the services */
1149
        url_fseek(pb, pos, SEEK_SET);
1150
        mpegts_scan_sdt(ts);
1151

    
1152
        mpegts_set_service(ts);
1153

    
1154
        handle_packets(ts, s->probesize);
1155
        /* if could not find service, enable auto_guess */
1156

    
1157
        ts->auto_guess = 1;
1158

    
1159
#ifdef DEBUG_SI
1160
        av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1161
#endif
1162
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1163
    } else {
1164
        AVStream *st;
1165
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1166
        int64_t pcrs[2], pcr_h;
1167
        int packet_count[2];
1168
        uint8_t packet[TS_PACKET_SIZE];
1169

    
1170
        /* only read packets */
1171

    
1172
        st = av_new_stream(s, 0);
1173
        if (!st)
1174
            goto fail;
1175
        av_set_pts_info(st, 60, 1, 27000000);
1176
        st->codec->codec_type = CODEC_TYPE_DATA;
1177
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1178

    
1179
        /* we iterate until we find two PCRs to estimate the bitrate */
1180
        pcr_pid = -1;
1181
        nb_pcrs = 0;
1182
        nb_packets = 0;
1183
        for(;;) {
1184
            ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1185
            if (ret < 0)
1186
                return -1;
1187
            pid = AV_RB16(packet + 1) & 0x1fff;
1188
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1189
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1190
                pcr_pid = pid;
1191
                packet_count[nb_pcrs] = nb_packets;
1192
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1193
                nb_pcrs++;
1194
                if (nb_pcrs >= 2)
1195
                    break;
1196
            }
1197
            nb_packets++;
1198
        }
1199

    
1200
        /* NOTE1: the bitrate is computed without the FEC */
1201
        /* NOTE2: it is only the bitrate of the start of the stream */
1202
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1203
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1204
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1205
        st->codec->bit_rate = s->bit_rate;
1206
        st->start_time = ts->cur_pcr;
1207
#if 0
1208
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1209
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1210
#endif
1211
    }
1212

    
1213
    url_fseek(pb, pos, SEEK_SET);
1214
    return 0;
1215
 fail:
1216
    return -1;
1217
}
1218

    
1219
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1220

    
1221
static int mpegts_raw_read_packet(AVFormatContext *s,
1222
                                  AVPacket *pkt)
1223
{
1224
    MpegTSContext *ts = s->priv_data;
1225
    int ret, i;
1226
    int64_t pcr_h, next_pcr_h, pos;
1227
    int pcr_l, next_pcr_l;
1228
    uint8_t pcr_buf[12];
1229

    
1230
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1231
        return AVERROR(ENOMEM);
1232
    pkt->pos= url_ftell(&s->pb);
1233
    ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1234
    if (ret < 0) {
1235
        av_free_packet(pkt);
1236
        return ret;
1237
    }
1238
    if (ts->mpeg2ts_compute_pcr) {
1239
        /* compute exact PCR for each packet */
1240
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1241
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1242
            pos = url_ftell(&s->pb);
1243
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1244
                url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1245
                get_buffer(&s->pb, pcr_buf, 12);
1246
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1247
                    /* XXX: not precise enough */
1248
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1249
                        (i + 1);
1250
                    break;
1251
                }
1252
            }
1253
            url_fseek(&s->pb, pos, SEEK_SET);
1254
            /* no next PCR found: we use previous increment */
1255
            ts->cur_pcr = pcr_h * 300 + pcr_l;
1256
        }
1257
        pkt->pts = ts->cur_pcr;
1258
        pkt->duration = ts->pcr_incr;
1259
        ts->cur_pcr += ts->pcr_incr;
1260
    }
1261
    pkt->stream_index = 0;
1262
    return 0;
1263
}
1264

    
1265
static int mpegts_read_packet(AVFormatContext *s,
1266
                              AVPacket *pkt)
1267
{
1268
    MpegTSContext *ts = s->priv_data;
1269

    
1270
    ts->pkt = pkt;
1271
    return handle_packets(ts, 0);
1272
}
1273

    
1274
static int mpegts_read_close(AVFormatContext *s)
1275
{
1276
    MpegTSContext *ts = s->priv_data;
1277
    int i;
1278
    for(i=0;i<NB_PID_MAX;i++)
1279
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1280

    
1281
    for(i = 0; i < ts->nb_services; i++){
1282
        av_free(ts->services[i]->provider_name);
1283
        av_free(ts->services[i]->name);
1284
        av_free(ts->services[i]);
1285
    }
1286
    av_freep(&ts->services);
1287

    
1288
    return 0;
1289
}
1290

    
1291
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1292
                              int64_t *ppos, int64_t pos_limit)
1293
{
1294
    MpegTSContext *ts = s->priv_data;
1295
    int64_t pos, timestamp;
1296
    uint8_t buf[TS_PACKET_SIZE];
1297
    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1298
    const int find_next= 1;
1299
    pos = ((*ppos  + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1300
    if (find_next) {
1301
        for(;;) {
1302
            url_fseek(&s->pb, pos, SEEK_SET);
1303
            if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1304
                return AV_NOPTS_VALUE;
1305
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1306
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1307
                break;
1308
            }
1309
            pos += ts->raw_packet_size;
1310
        }
1311
    } else {
1312
        for(;;) {
1313
            pos -= ts->raw_packet_size;
1314
            if (pos < 0)
1315
                return AV_NOPTS_VALUE;
1316
            url_fseek(&s->pb, pos, SEEK_SET);
1317
            if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1318
                return AV_NOPTS_VALUE;
1319
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1320
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1321
                break;
1322
            }
1323
        }
1324
    }
1325
    *ppos = pos;
1326

    
1327
    return timestamp;
1328
}
1329

    
1330
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1331
    MpegTSContext *ts = s->priv_data;
1332
    uint8_t buf[TS_PACKET_SIZE];
1333
    int64_t pos;
1334

    
1335
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1336
        return -1;
1337

    
1338
    pos= url_ftell(&s->pb);
1339

    
1340
    for(;;) {
1341
        url_fseek(&s->pb, pos, SEEK_SET);
1342
        if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1343
            return -1;
1344
//        pid = AV_RB16(buf + 1) & 0x1fff;
1345
        if(buf[1] & 0x40) break;
1346
        pos += ts->raw_packet_size;
1347
    }
1348
    url_fseek(&s->pb, pos, SEEK_SET);
1349

    
1350
    return 0;
1351
}
1352

    
1353
/**************************************************************/
1354
/* parsing functions - called from other demuxers such as RTP */
1355

    
1356
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1357
{
1358
    MpegTSContext *ts;
1359

    
1360
    ts = av_mallocz(sizeof(MpegTSContext));
1361
    if (!ts)
1362
        return NULL;
1363
    /* no stream case, currently used by RTP */
1364
    ts->raw_packet_size = TS_PACKET_SIZE;
1365
    ts->stream = s;
1366
    ts->auto_guess = 1;
1367
    return ts;
1368
}
1369

    
1370
/* return the consumed length if a packet was output, or -1 if no
1371
   packet is output */
1372
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1373
                        const uint8_t *buf, int len)
1374
{
1375
    int len1;
1376

    
1377
    len1 = len;
1378
    ts->pkt = pkt;
1379
    ts->stop_parse = 0;
1380
    for(;;) {
1381
        if (ts->stop_parse>0)
1382
            break;
1383
        if (len < TS_PACKET_SIZE)
1384
            return -1;
1385
        if (buf[0] != 0x47) {
1386
            buf++;
1387
            len--;
1388
        } else {
1389
            handle_packet(ts, buf);
1390
            buf += TS_PACKET_SIZE;
1391
            len -= TS_PACKET_SIZE;
1392
        }
1393
    }
1394
    return len1 - len;
1395
}
1396

    
1397
void mpegts_parse_close(MpegTSContext *ts)
1398
{
1399
    int i;
1400

    
1401
    for(i=0;i<NB_PID_MAX;i++)
1402
        av_free(ts->pids[i]);
1403
    av_free(ts);
1404
}
1405

    
1406
AVInputFormat mpegts_demuxer = {
1407
    "mpegts",
1408
    "MPEG2 transport stream format",
1409
    sizeof(MpegTSContext),
1410
    mpegts_probe,
1411
    mpegts_read_header,
1412
    mpegts_read_packet,
1413
    mpegts_read_close,
1414
    read_seek,
1415
    mpegts_get_pcr,
1416
    .flags = AVFMT_SHOW_IDS,
1417
};
1418

    
1419
AVInputFormat mpegtsraw_demuxer = {
1420
    "mpegtsraw",
1421
    "MPEG2 raw transport stream format",
1422
    sizeof(MpegTSContext),
1423
    mpegts_probe,
1424
    mpegts_read_header,
1425
    mpegts_raw_read_packet,
1426
    mpegts_read_close,
1427
    read_seek,
1428
    mpegts_get_pcr,
1429
    .flags = AVFMT_SHOW_IDS,
1430
};