Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ 3ba1438d

History | View | Annotate | Download (40.5 KB)

1
/*
2
 * MPEG2 transport stream (aka DVB) demux
3
 * Copyright (c) 2002-2003 Fabrice Bellard.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
#include "avformat.h"
20

    
21
#include "mpegts.h"
22

    
23
//#define DEBUG_SI
24
//#define DEBUG_SEEK
25

    
26
/* 1.0 second at 24Mbit/s */
27
#define MAX_SCAN_PACKETS 32000
28

    
29
/* maximum size in which we look for synchronisation if
30
   synchronisation is lost */
31
#define MAX_RESYNC_SIZE 4096
32

    
33
static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
34

    
35
enum MpegTSFilterType {
36
    MPEGTS_PES,
37
    MPEGTS_SECTION,
38
};
39

    
40
typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
41

    
42
typedef struct MpegTSPESFilter {
43
    PESCallback *pes_cb;
44
    void *opaque;
45
} MpegTSPESFilter;
46

    
47
typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
48

    
49
typedef void SetServiceCallback(void *opaque, int ret);
50

    
51
typedef struct MpegTSSectionFilter {
52
    int section_index;
53
    int section_h_size;
54
    uint8_t *section_buf;
55
    int check_crc:1;
56
    int end_of_section_reached:1;
57
    SectionCallback *section_cb;
58
    void *opaque;
59
} MpegTSSectionFilter;
60

    
61
typedef struct MpegTSFilter {
62
    int pid;
63
    int last_cc; /* last cc code (-1 if first packet) */
64
    enum MpegTSFilterType type;
65
    union {
66
        MpegTSPESFilter pes_filter;
67
        MpegTSSectionFilter section_filter;
68
    } u;
69
} MpegTSFilter;
70

    
71
typedef struct MpegTSService {
72
    int running:1;
73
    int sid;
74
    char *provider_name;
75
    char *name;
76
} MpegTSService;
77

    
78
struct MpegTSContext {
79
    /* user data */
80
    AVFormatContext *stream;
81
    int raw_packet_size; /* raw packet size, including FEC if present */
82
    int auto_guess; /* if true, all pids are analized to find streams */
83
    int set_service_ret;
84

    
85
    int mpeg2ts_raw;  /* force raw MPEG2 transport stream output, if possible */
86
    int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
87

    
88
    /* used to estimate the exact PCR */
89
    int64_t cur_pcr;
90
    int pcr_incr;
91
    int pcr_pid;
92
    
93
    /* data needed to handle file based ts */
94
    int stop_parse; /* stop parsing loop */
95
    AVPacket *pkt; /* packet containing av data */
96

    
97
    /******************************************/
98
    /* private mpegts data */
99
    /* scan context */
100
    MpegTSFilter *sdt_filter;
101
    int nb_services;
102
    MpegTSService **services;
103
    
104
    /* set service context (XXX: allocated it ?) */
105
    SetServiceCallback *set_service_cb;
106
    void *set_service_opaque;
107
    MpegTSFilter *pat_filter;
108
    MpegTSFilter *pmt_filter;
109
    int req_sid;
110

    
111
    MpegTSFilter *pids[NB_PID_MAX];
112
};
113

    
114
static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
115
                               const uint8_t *buf, int buf_size, int is_start)
116
{
117
    MpegTSSectionFilter *tss = &tss1->u.section_filter;
118
    int len;
119
    unsigned int crc;
120
    
121
    if (is_start) {
122
        memcpy(tss->section_buf, buf, buf_size);
123
        tss->section_index = buf_size;
124
        tss->section_h_size = -1;
125
        tss->end_of_section_reached = 0;
126
    } else {
127
        if (tss->end_of_section_reached)
128
            return;
129
        len = 4096 - tss->section_index;
130
        if (buf_size < len)
131
            len = buf_size;
132
        memcpy(tss->section_buf + tss->section_index, buf, len);
133
        tss->section_index += len;
134
    }
135

    
136
    /* compute section length if possible */
137
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
138
        len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
139
        if (len > 4096)
140
            return;
141
        tss->section_h_size = len;
142
    }
143

    
144
    if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
145
        if (tss->check_crc) {
146
            crc = mpegts_crc32(tss->section_buf, tss->section_h_size);
147
            if (crc != 0)
148
                goto invalid_crc;
149
        }
150
        tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
151
    invalid_crc:
152
        tss->end_of_section_reached = 1;
153
    }
154
}
155

    
156
MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid, 
157
                                         SectionCallback *section_cb, void *opaque,
158
                                         int check_crc)
159

    
160
{
161
    MpegTSFilter *filter;
162
    MpegTSSectionFilter *sec;
163
    
164
#ifdef DEBUG_SI
165
    printf("Filter: pid=0x%x\n", pid);
166
#endif
167
    if (pid >= NB_PID_MAX || ts->pids[pid])
168
        return NULL;
169
    filter = av_mallocz(sizeof(MpegTSFilter));
170
    if (!filter) 
171
        return NULL;
172
    ts->pids[pid] = filter;
173
    filter->type = MPEGTS_SECTION;
174
    filter->pid = pid;
175
    filter->last_cc = -1;
176
    sec = &filter->u.section_filter;
177
    sec->section_cb = section_cb;
178
    sec->opaque = opaque;
179
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
180
    sec->check_crc = check_crc;
181
    if (!sec->section_buf) {
182
        av_free(filter);
183
        return NULL;
184
    }
185
    return filter;
186
}
187

    
188
MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid, 
189
                                     PESCallback *pes_cb,
190
                                     void *opaque)
191
{
192
    MpegTSFilter *filter;
193
    MpegTSPESFilter *pes;
194

    
195
    if (pid >= NB_PID_MAX || ts->pids[pid])
196
        return NULL;
197
    filter = av_mallocz(sizeof(MpegTSFilter));
198
    if (!filter) 
199
        return NULL;
200
    ts->pids[pid] = filter;
201
    filter->type = MPEGTS_PES;
202
    filter->pid = pid;
203
    filter->last_cc = -1;
204
    pes = &filter->u.pes_filter;
205
    pes->pes_cb = pes_cb;
206
    pes->opaque = opaque;
207
    return filter;
208
}
209

    
210
void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
211
{
212
    int pid;
213

    
214
    pid = filter->pid;
215
    if (filter->type == MPEGTS_SECTION)
216
        av_freep(&filter->u.section_filter.section_buf);
217
    else if (filter->type == MPEGTS_PES)
218
        av_freep(&filter->u.pes_filter.opaque);
219

    
220
    av_free(filter);
221
    ts->pids[pid] = NULL;
222
}
223

    
224
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
225
    int stat[packet_size];
226
    int i;
227
    int x=0;
228
    int best_score=0;
229

    
230
    memset(stat, 0, packet_size*sizeof(int));
231

    
232
    for(x=i=0; i<size; i++){
233
        if(buf[i] == 0x47){
234
            stat[x]++;
235
            if(stat[x] > best_score){
236
                best_score= stat[x];
237
                if(index) *index= x;
238
            }
239
        }
240

    
241
        x++;
242
        if(x == packet_size) x= 0;
243
    }
244

    
245
    return best_score;
246
}
247

    
248
/* autodetect fec presence. Must have at least 1024 bytes  */
249
static int get_packet_size(const uint8_t *buf, int size)
250
{
251
    int score, fec_score;
252

    
253
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
254
        return -1;
255
        
256
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
257
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
258
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
259
    
260
    if     (score > fec_score) return TS_PACKET_SIZE;
261
    else if(score < fec_score) return TS_FEC_PACKET_SIZE;
262
    else                       return -1;
263
}
264

    
265
typedef struct SectionHeader {
266
    uint8_t tid;
267
    uint16_t id;
268
    uint8_t version;
269
    uint8_t sec_num;
270
    uint8_t last_sec_num;
271
} SectionHeader;
272

    
273
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
274
{
275
    const uint8_t *p;
276
    int c;
277

    
278
    p = *pp;
279
    if (p >= p_end)
280
        return -1;
281
    c = *p++;
282
    *pp = p;
283
    return c;
284
}
285

    
286
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
287
{
288
    const uint8_t *p;
289
    int c;
290

    
291
    p = *pp;
292
    if ((p + 1) >= p_end)
293
        return -1;
294
    c = (p[0] << 8) | p[1];
295
    p += 2;
296
    *pp = p;
297
    return c;
298
}
299

    
300
/* read and allocate a DVB string preceeded by its length */
301
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
302
{
303
    int len;
304
    const uint8_t *p;
305
    char *str;
306

    
307
    p = *pp;
308
    len = get8(&p, p_end);
309
    if (len < 0)
310
        return NULL;
311
    if ((p + len) > p_end)
312
        return NULL;
313
    str = av_malloc(len + 1);
314
    if (!str)
315
        return NULL;
316
    memcpy(str, p, len);
317
    str[len] = '\0';
318
    p += len;
319
    *pp = p;
320
    return str;
321
}
322

    
323
static int parse_section_header(SectionHeader *h, 
324
                                const uint8_t **pp, const uint8_t *p_end)
325
{
326
    int val;
327

    
328
    val = get8(pp, p_end);
329
    if (val < 0)
330
        return -1;
331
    h->tid = val;
332
    *pp += 2;
333
    val = get16(pp, p_end);
334
    if (val < 0)
335
        return -1;
336
    h->id = val;
337
    val = get8(pp, p_end);
338
    if (val < 0)
339
        return -1;
340
    h->version = (val >> 1) & 0x1f;
341
    val = get8(pp, p_end);
342
    if (val < 0)
343
        return -1;
344
    h->sec_num = val;
345
    val = get8(pp, p_end);
346
    if (val < 0)
347
        return -1;
348
    h->last_sec_num = val;
349
    return 0;
350
}
351

    
352
static MpegTSService *new_service(MpegTSContext *ts, int sid, 
353
                                  char *provider_name, char *name)
354
{
355
    MpegTSService *service;
356

    
357
#ifdef DEBUG_SI
358
    printf("new_service: sid=0x%04x provider='%s' name='%s'\n", 
359
           sid, provider_name, name);
360
#endif
361

    
362
    service = av_mallocz(sizeof(MpegTSService));
363
    if (!service)
364
        return NULL;
365
    service->sid = sid;
366
    service->provider_name = provider_name;
367
    service->name = name;
368
    dynarray_add(&ts->services, &ts->nb_services, service);
369
    return service;
370
}
371

    
372
static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
373
{
374
    MpegTSContext *ts = opaque;
375
    SectionHeader h1, *h = &h1;
376
    const uint8_t *p, *p_end;
377
    int program_info_length, pcr_pid, pid, stream_type, desc_length;
378
    
379
#ifdef DEBUG_SI
380
    printf("PMT:\n");
381
    av_hex_dump(stdout, (uint8_t *)section, section_len);
382
#endif
383
    p_end = section + section_len - 4;
384
    p = section;
385
    if (parse_section_header(h, &p, p_end) < 0)
386
        return;
387
#ifdef DEBUG_SI
388
    printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
389
#endif
390
    if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
391
        return;
392

    
393
    pcr_pid = get16(&p, p_end) & 0x1fff;
394
    if (pcr_pid < 0)
395
        return;
396
    ts->pcr_pid = pcr_pid;
397
#ifdef DEBUG_SI
398
    printf("pcr_pid=0x%x\n", pcr_pid);
399
#endif
400
    program_info_length = get16(&p, p_end) & 0xfff;
401
    if (program_info_length < 0)
402
        return;
403
    p += program_info_length;
404
    if (p >= p_end)
405
        return;
406
    for(;;) {
407
        stream_type = get8(&p, p_end);
408
        if (stream_type < 0)
409
            break;
410
        pid = get16(&p, p_end) & 0x1fff;
411
        if (pid < 0)
412
            break;
413
        desc_length = get16(&p, p_end) & 0xfff;
414
        if (desc_length < 0)
415
            break;
416
        p += desc_length;
417
        if (p > p_end)
418
            return;
419

    
420
#ifdef DEBUG_SI
421
        printf("stream_type=%d pid=0x%x\n", stream_type, pid);
422
#endif
423

    
424
        /* now create ffmpeg stream */
425
        switch(stream_type) {
426
        case STREAM_TYPE_AUDIO_MPEG1:
427
        case STREAM_TYPE_AUDIO_MPEG2:
428
        case STREAM_TYPE_VIDEO_MPEG1:
429
        case STREAM_TYPE_VIDEO_MPEG2:
430
        case STREAM_TYPE_VIDEO_MPEG4:
431
        case STREAM_TYPE_VIDEO_H264:
432
        case STREAM_TYPE_AUDIO_AAC:
433
        case STREAM_TYPE_AUDIO_AC3:
434
        case STREAM_TYPE_AUDIO_DTS:
435
            add_pes_stream(ts, pid, stream_type);
436
            break;
437
        default:
438
            /* we ignore the other streams */
439
            break;
440
        }
441
    }
442
    /* all parameters are there */
443
    ts->set_service_cb(ts->set_service_opaque, 0);
444
    mpegts_close_filter(ts, ts->pmt_filter);
445
    ts->pmt_filter = NULL;
446
}
447

    
448
static void pat_cb(void *opaque, const uint8_t *section, int section_len)
449
{
450
    MpegTSContext *ts = opaque;
451
    SectionHeader h1, *h = &h1;
452
    const uint8_t *p, *p_end;
453
    int sid, pmt_pid;
454

    
455
#ifdef DEBUG_SI
456
    printf("PAT:\n");
457
    av_hex_dump(stdout, (uint8_t *)section, section_len);
458
#endif
459
    p_end = section + section_len - 4;
460
    p = section;
461
    if (parse_section_header(h, &p, p_end) < 0)
462
        return;
463
    if (h->tid != PAT_TID)
464
        return;
465

    
466
    for(;;) {
467
        sid = get16(&p, p_end);
468
        if (sid < 0)
469
            break;
470
        pmt_pid = get16(&p, p_end) & 0x1fff;
471
        if (pmt_pid < 0)
472
            break;
473
#ifdef DEBUG_SI
474
        printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
475
#endif
476
        if (sid == 0x0000) {
477
            /* NIT info */
478
        } else {
479
            if (ts->req_sid == sid) {
480
                ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid, 
481
                                                            pmt_cb, ts, 1);
482
                goto found;
483
            }
484
        }
485
    }
486
    /* not found */
487
    ts->set_service_cb(ts->set_service_opaque, -1);
488

    
489
 found:
490
    mpegts_close_filter(ts, ts->pat_filter);
491
    ts->pat_filter = NULL;
492
}
493

    
494
/* add all services found in the PAT */
495
static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
496
{
497
    MpegTSContext *ts = opaque;
498
    SectionHeader h1, *h = &h1;
499
    const uint8_t *p, *p_end;
500
    int sid, pmt_pid;
501
    char *provider_name, *name;
502
    char buf[256];
503

    
504
#ifdef DEBUG_SI
505
    printf("PAT:\n");
506
    av_hex_dump(stdout, (uint8_t *)section, section_len);
507
#endif
508
    p_end = section + section_len - 4;
509
    p = section;
510
    if (parse_section_header(h, &p, p_end) < 0)
511
        return;
512
    if (h->tid != PAT_TID)
513
        return;
514

    
515
    for(;;) {
516
        sid = get16(&p, p_end);
517
        if (sid < 0)
518
            break;
519
        pmt_pid = get16(&p, p_end) & 0x1fff;
520
        if (pmt_pid < 0)
521
            break;
522
#ifdef DEBUG_SI
523
        printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
524
#endif
525
        if (sid == 0x0000) {
526
            /* NIT info */
527
        } else {
528
            /* add the service with a dummy name */
529
            snprintf(buf, sizeof(buf), "Service %x\n", sid);
530
            name = av_strdup(buf);
531
            provider_name = av_strdup("");
532
            if (name && provider_name) {
533
                new_service(ts, sid, provider_name, name);
534
            } else {
535
                av_freep(&name);
536
                av_freep(&provider_name);
537
            }
538
        }
539
    }
540
    ts->stop_parse = 1;
541

    
542
    /* remove filter */
543
    mpegts_close_filter(ts, ts->pat_filter);
544
    ts->pat_filter = NULL;
545
}
546

    
547
void mpegts_set_service(MpegTSContext *ts, int sid,
548
                        SetServiceCallback *set_service_cb, void *opaque)
549
{
550
    ts->set_service_cb = set_service_cb;
551
    ts->set_service_opaque = opaque;
552
    ts->req_sid = sid;
553
    ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID, 
554
                                                pat_cb, ts, 1);
555
}
556

    
557
static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
558
{
559
    MpegTSContext *ts = opaque;
560
    SectionHeader h1, *h = &h1;
561
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
562
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
563
    char *name, *provider_name;
564

    
565
#ifdef DEBUG_SI
566
    printf("SDT:\n");
567
    av_hex_dump(stdout, (uint8_t *)section, section_len);
568
#endif
569

    
570
    p_end = section + section_len - 4;
571
    p = section;
572
    if (parse_section_header(h, &p, p_end) < 0)
573
        return;
574
    if (h->tid != SDT_TID)
575
        return;
576
    onid = get16(&p, p_end);
577
    if (onid < 0)
578
        return;
579
    val = get8(&p, p_end);
580
    if (val < 0)
581
        return;
582
    for(;;) {
583
        sid = get16(&p, p_end);
584
        if (sid < 0)
585
            break;
586
        val = get8(&p, p_end);
587
        if (val < 0)
588
            break;
589
        desc_list_len = get16(&p, p_end) & 0xfff;
590
        if (desc_list_len < 0)
591
            break;
592
        desc_list_end = p + desc_list_len;
593
        if (desc_list_end > p_end)
594
            break;
595
        for(;;) {
596
            desc_tag = get8(&p, desc_list_end);
597
            if (desc_tag < 0)
598
                break;
599
            desc_len = get8(&p, desc_list_end);
600
            desc_end = p + desc_len;
601
            if (desc_end > desc_list_end)
602
                break;
603
#ifdef DEBUG_SI
604
            printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
605
#endif
606
            switch(desc_tag) {
607
            case 0x48:
608
                service_type = get8(&p, p_end);
609
                if (service_type < 0)
610
                    break;
611
                provider_name = getstr8(&p, p_end);
612
                if (!provider_name)
613
                    break;
614
                name = getstr8(&p, p_end);
615
                if (!name)
616
                    break;
617
                new_service(ts, sid, provider_name, name);
618
                break;
619
            default:
620
                break;
621
            }
622
            p = desc_end;
623
        }
624
        p = desc_list_end;
625
    }
626
    ts->stop_parse = 1;
627

    
628
    /* remove filter */
629
    mpegts_close_filter(ts, ts->sdt_filter);
630
    ts->sdt_filter = NULL;
631
}
632

    
633
/* scan services in a transport stream by looking at the SDT */
634
void mpegts_scan_sdt(MpegTSContext *ts)
635
{
636
    ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID, 
637
                                                sdt_cb, ts, 1);
638
}
639

    
640
/* scan services in a transport stream by looking at the PAT (better
641
   than nothing !) */
642
void mpegts_scan_pat(MpegTSContext *ts)
643
{
644
    ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID, 
645
                                                pat_scan_cb, ts, 1);
646
}
647

    
648
/* TS stream handling */
649

    
650
enum MpegTSState {
651
    MPEGTS_HEADER = 0,
652
    MPEGTS_PESHEADER_FILL,
653
    MPEGTS_PAYLOAD,
654
    MPEGTS_SKIP,
655
};
656

    
657
/* enough for PES header + length */
658
#define PES_START_SIZE 9
659
#define MAX_PES_HEADER_SIZE (9 + 255)
660

    
661
typedef struct PESContext {
662
    int pid;
663
    int stream_type;
664
    MpegTSContext *ts;
665
    AVFormatContext *stream;
666
    AVStream *st;
667
    enum MpegTSState state;
668
    /* used to get the format */
669
    int data_index;
670
    int total_size;
671
    int pes_header_size;
672
    int64_t pts, dts;
673
    uint8_t header[MAX_PES_HEADER_SIZE];
674
} PESContext;
675

    
676
static int64_t get_pts(const uint8_t *p)
677
{
678
    int64_t pts;
679
    int val;
680

    
681
    pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
682
    val = (p[1] << 8) | p[2];
683
    pts |= (int64_t)(val >> 1) << 15;
684
    val = (p[3] << 8) | p[4];
685
    pts |= (int64_t)(val >> 1);
686
    return pts;
687
}
688

    
689
/* return non zero if a packet could be constructed */
690
static void mpegts_push_data(void *opaque,
691
                             const uint8_t *buf, int buf_size, int is_start)
692
{
693
    PESContext *pes = opaque;
694
    MpegTSContext *ts = pes->ts;
695
    AVStream *st;
696
    const uint8_t *p;
697
    int len, code, codec_type, codec_id;
698
    
699
    if (is_start) {
700
        pes->state = MPEGTS_HEADER;
701
        pes->data_index = 0;
702
    }
703
    p = buf;
704
    while (buf_size > 0) {
705
        switch(pes->state) {
706
        case MPEGTS_HEADER:
707
            len = PES_START_SIZE - pes->data_index;
708
            if (len > buf_size)
709
                len = buf_size;
710
            memcpy(pes->header + pes->data_index, p, len);
711
            pes->data_index += len;
712
            p += len;
713
            buf_size -= len;
714
            if (pes->data_index == PES_START_SIZE) {
715
                /* we got all the PES or section header. We can now
716
                   decide */
717
#if 0
718
                av_hex_dump(pes->header, pes->data_index);
719
#endif
720
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
721
                    pes->header[2] == 0x01) {
722
                    /* it must be an mpeg2 PES stream */
723
                    code = pes->header[3] | 0x100;
724
                    if (!((code >= 0x1c0 && code <= 0x1df) ||
725
                          (code >= 0x1e0 && code <= 0x1ef) ||
726
                          (code == 0x1bd)))
727
                        goto skip;
728
                    if (!pes->st) {
729
                        /* allocate stream */
730
                        switch(pes->stream_type){
731
                        case STREAM_TYPE_AUDIO_MPEG1:
732
                        case STREAM_TYPE_AUDIO_MPEG2:
733
                            codec_type = CODEC_TYPE_AUDIO;
734
                            codec_id = CODEC_ID_MP3;
735
                            break;
736
                        case STREAM_TYPE_VIDEO_MPEG1:
737
                        case STREAM_TYPE_VIDEO_MPEG2:
738
                            codec_type = CODEC_TYPE_VIDEO;
739
                            codec_id = CODEC_ID_MPEG2VIDEO;
740
                            break;
741
                        case STREAM_TYPE_VIDEO_MPEG4:
742
                            codec_type = CODEC_TYPE_VIDEO;
743
                            codec_id = CODEC_ID_MPEG4;
744
                            break;
745
                        case STREAM_TYPE_VIDEO_H264:
746
                            codec_type = CODEC_TYPE_VIDEO;
747
                            codec_id = CODEC_ID_H264;
748
                            break;
749
                        case STREAM_TYPE_AUDIO_AAC:
750
                            codec_type = CODEC_TYPE_AUDIO;
751
                            codec_id = CODEC_ID_AAC;
752
                            break;
753
                        case STREAM_TYPE_AUDIO_AC3:
754
                            codec_type = CODEC_TYPE_AUDIO;
755
                            codec_id = CODEC_ID_AC3;
756
                            break;
757
                        case STREAM_TYPE_AUDIO_DTS:
758
                            codec_type = CODEC_TYPE_AUDIO;
759
                            codec_id = CODEC_ID_DTS;
760
                            break;
761
                        default:
762
                            if (code >= 0x1c0 && code <= 0x1df) {
763
                                codec_type = CODEC_TYPE_AUDIO;
764
                                codec_id = CODEC_ID_MP2;
765
                            } else if (code == 0x1bd) {
766
                                codec_type = CODEC_TYPE_AUDIO;
767
                                codec_id = CODEC_ID_AC3;
768
                            } else {
769
                                codec_type = CODEC_TYPE_VIDEO;
770
                                codec_id = CODEC_ID_MPEG1VIDEO;
771
                            }
772
                            break;
773
                        }
774
                        st = av_new_stream(pes->stream, pes->pid);
775
                        if (st) {
776
                            av_set_pts_info(st, 60, 1, 90000);
777
                            st->priv_data = pes;
778
                            st->codec.codec_type = codec_type;
779
                            st->codec.codec_id = codec_id;
780
                            st->need_parsing = 1;
781
                            pes->st = st;
782
                        }
783
                    }
784
                    pes->state = MPEGTS_PESHEADER_FILL;
785
                    pes->total_size = (pes->header[4] << 8) | pes->header[5];
786
                    /* NOTE: a zero total size means the PES size is
787
                       unbounded */
788
                    if (pes->total_size)
789
                        pes->total_size += 6;
790
                    pes->pes_header_size = pes->header[8] + 9;
791
                } else {
792
                    /* otherwise, it should be a table */
793
                    /* skip packet */
794
                skip:
795
                    pes->state = MPEGTS_SKIP;
796
                    continue;
797
                }
798
            }
799
            break;
800
            /**********************************************/
801
            /* PES packing parsing */
802
        case MPEGTS_PESHEADER_FILL:
803
            len = pes->pes_header_size - pes->data_index;
804
            if (len > buf_size)
805
                len = buf_size;
806
            memcpy(pes->header + pes->data_index, p, len);
807
            pes->data_index += len;
808
            p += len;
809
            buf_size -= len;
810
            if (pes->data_index == pes->pes_header_size) {
811
                const uint8_t *r;
812
                unsigned int flags;
813

    
814
                flags = pes->header[7];
815
                r = pes->header + 9;
816
                pes->pts = AV_NOPTS_VALUE;
817
                pes->dts = AV_NOPTS_VALUE;
818
                if ((flags & 0xc0) == 0x80) {
819
                    pes->pts = get_pts(r);
820
                    r += 5;
821
                } else if ((flags & 0xc0) == 0xc0) {
822
                    pes->pts = get_pts(r);
823
                    r += 5;
824
                    pes->dts = get_pts(r);
825
                    r += 5;
826
                }
827
                /* we got the full header. We parse it and get the payload */
828
                pes->state = MPEGTS_PAYLOAD;
829
            }
830
            break;
831
        case MPEGTS_PAYLOAD:
832
            if (pes->total_size) {
833
                len = pes->total_size - pes->data_index;
834
                if (len > buf_size)
835
                    len = buf_size;
836
            } else {
837
                len = buf_size;
838
            }
839
            if (len > 0) {
840
                AVPacket *pkt = ts->pkt;
841
                if (pes->st && av_new_packet(pkt, len) == 0) {
842
                    memcpy(pkt->data, p, len);
843
                    pkt->stream_index = pes->st->index;
844
                    pkt->pts = pes->pts;
845
                    pkt->dts = pes->dts;
846
                    /* reset pts values */
847
                    pes->pts = AV_NOPTS_VALUE;
848
                    pes->dts = AV_NOPTS_VALUE;
849
                    ts->stop_parse = 1;
850
                    return;
851
                }
852
            }
853
            buf_size = 0;
854
            break;
855
        case MPEGTS_SKIP:
856
            buf_size = 0;
857
            break;
858
        }
859
    }
860
}
861

    
862
static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
863
{
864
    MpegTSFilter *tss;
865
    PESContext *pes;
866

    
867
    /* if no pid found, then add a pid context */
868
    pes = av_mallocz(sizeof(PESContext));
869
    if (!pes)
870
        return -1;
871
    pes->ts = ts;
872
    pes->stream = ts->stream;
873
    pes->pid = pid;
874
    pes->stream_type = stream_type;
875
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
876
    if (!tss) {
877
        av_free(pes);
878
        return -1;
879
    }
880
    return 0;
881
}
882

    
883
/* handle one TS packet */
884
static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
885
{
886
    AVFormatContext *s = ts->stream;
887
    MpegTSFilter *tss;
888
    int len, pid, cc, cc_ok, afc, is_start;
889
    const uint8_t *p, *p_end;
890

    
891
    pid = ((packet[1] & 0x1f) << 8) | packet[2];
892
    is_start = packet[1] & 0x40;
893
    tss = ts->pids[pid];
894
    if (ts->auto_guess && tss == NULL && is_start) {
895
        add_pes_stream(ts, pid, 0);
896
        tss = ts->pids[pid];
897
    }
898
    if (!tss)
899
        return;
900

    
901
    /* continuity check (currently not used) */
902
    cc = (packet[3] & 0xf);
903
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
904
    tss->last_cc = cc;
905
    
906
    /* skip adaptation field */
907
    afc = (packet[3] >> 4) & 3;
908
    p = packet + 4;
909
    if (afc == 0) /* reserved value */
910
        return;
911
    if (afc == 2) /* adaptation field only */
912
        return;
913
    if (afc == 3) {
914
        /* skip adapation field */
915
        p += p[0] + 1;
916
    }
917
    /* if past the end of packet, ignore */
918
    p_end = packet + TS_PACKET_SIZE;
919
    if (p >= p_end)
920
        return;
921
    
922
    if (tss->type == MPEGTS_SECTION) {
923
        if (is_start) {
924
            /* pointer field present */
925
            len = *p++;
926
            if (p + len > p_end)
927
                return;
928
            if (len && cc_ok) {
929
                /* write remaning section bytes */
930
                write_section_data(s, tss, 
931
                                   p, len, 0);
932
            }
933
            p += len;
934
            if (p < p_end) {
935
                write_section_data(s, tss, 
936
                                   p, p_end - p, 1);
937
            }
938
        } else {
939
            if (cc_ok) {
940
                write_section_data(s, tss, 
941
                                   p, p_end - p, 0);
942
            }
943
        }
944
    } else {
945
        tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque, 
946
                                 p, p_end - p, is_start);
947
    }
948
}
949

    
950
/* XXX: try to find a better synchro over several packets (use
951
   get_packet_size() ?) */
952
static int mpegts_resync(ByteIOContext *pb)
953
{
954
    int c, i;
955

    
956
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
957
        c = url_fgetc(pb);
958
        if (c < 0)
959
            return -1;
960
        if (c == 0x47) {
961
            url_fseek(pb, -1, SEEK_CUR);
962
            return 0;
963
        }
964
    }
965
    /* no sync found */
966
    return -1;
967
}
968

    
969
/* return -1 if error or EOF. Return 0 if OK. */
970
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
971
{
972
    int skip, len;
973

    
974
    for(;;) {
975
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
976
        if (len != TS_PACKET_SIZE)
977
            return AVERROR_IO;
978
        /* check paquet sync byte */
979
        if (buf[0] != 0x47) {
980
            /* find a new packet start */
981
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
982
            if (mpegts_resync(pb) < 0)
983
                return AVERROR_INVALIDDATA;
984
            else
985
                continue;
986
        } else {
987
            skip = raw_packet_size - TS_PACKET_SIZE;
988
            if (skip > 0)
989
                url_fskip(pb, skip);
990
            break;
991
        }
992
    }
993
    return 0;
994
}
995

    
996
static int handle_packets(MpegTSContext *ts, int nb_packets)
997
{
998
    AVFormatContext *s = ts->stream;
999
    ByteIOContext *pb = &s->pb;
1000
    uint8_t packet[TS_PACKET_SIZE];
1001
    int packet_num, ret;
1002

    
1003
    ts->stop_parse = 0;
1004
    packet_num = 0;
1005
    for(;;) {
1006
        if (ts->stop_parse)
1007
            break;
1008
        packet_num++;
1009
        if (nb_packets != 0 && packet_num >= nb_packets)
1010
            break;
1011
        ret = read_packet(pb, packet, ts->raw_packet_size);
1012
        if (ret != 0)
1013
            return ret;
1014
        handle_packet(ts, packet);
1015
    }
1016
    return 0;
1017
}
1018

    
1019
static int mpegts_probe(AVProbeData *p)
1020
{
1021
#if 1
1022
    const int size= p->buf_size;
1023
    int score, fec_score;
1024
#define CHECK_COUNT 10
1025
    
1026
    if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1027
        return -1;
1028
    
1029
    score    = analyze(p->buf, TS_PACKET_SIZE    *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1030
    fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1031
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
1032
  
1033
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1034
    if     (score > fec_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1035
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1036
    else                                    return -1;
1037
#else
1038
    /* only use the extension for safer guess */
1039
    if (match_ext(p->filename, "ts"))
1040
        return AVPROBE_SCORE_MAX;
1041
    else
1042
        return 0;
1043
#endif
1044
}
1045

    
1046
void set_service_cb(void *opaque, int ret)
1047
{
1048
    MpegTSContext *ts = opaque;
1049
    ts->set_service_ret = ret;
1050
    ts->stop_parse = 1;
1051
}
1052

    
1053
/* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1054
   (-1) if not available */
1055
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, 
1056
                     const uint8_t *packet)
1057
{
1058
    int afc, len, flags;
1059
    const uint8_t *p;
1060
    unsigned int v;
1061

    
1062
    afc = (packet[3] >> 4) & 3;
1063
    if (afc <= 1)
1064
        return -1;
1065
    p = packet + 4;
1066
    len = p[0];
1067
    p++;
1068
    if (len == 0)
1069
        return -1;
1070
    flags = *p++;
1071
    len--;
1072
    if (!(flags & 0x10))
1073
        return -1;
1074
    if (len < 6)
1075
        return -1;
1076
    v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1077
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1078
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1079
    return 0;
1080
}
1081

    
1082
static int mpegts_read_header(AVFormatContext *s,
1083
                              AVFormatParameters *ap)
1084
{
1085
    MpegTSContext *ts = s->priv_data;
1086
    ByteIOContext *pb = &s->pb;
1087
    uint8_t buf[1024];
1088
    int len, sid, i;
1089
    int64_t pos;
1090
    MpegTSService *service;
1091

    
1092
    if (ap) {
1093
        ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1094
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1095
    }
1096

    
1097
    /* read the first 1024 bytes to get packet size */
1098
    pos = url_ftell(pb);
1099
    len = get_buffer(pb, buf, sizeof(buf));
1100
    if (len != sizeof(buf))
1101
        goto fail;
1102
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1103
    if (ts->raw_packet_size <= 0)
1104
        goto fail;
1105
    ts->stream = s;
1106
    ts->auto_guess = 0;
1107

    
1108
    if (!ts->mpeg2ts_raw) {
1109
        /* normal demux */
1110

    
1111
        if (!ts->auto_guess) {
1112
            ts->set_service_ret = -1;
1113

    
1114
            /* first do a scaning to get all the services */
1115
            url_fseek(pb, pos, SEEK_SET);
1116
            mpegts_scan_sdt(ts);
1117
            
1118
            handle_packets(ts, MAX_SCAN_PACKETS);
1119
            
1120
            if (ts->nb_services <= 0) {
1121
                /* no SDT found, we try to look at the PAT */
1122
                
1123
                /* First remove the SDT filters from each PID */
1124
                int i;
1125
                for (i=0; i < NB_PID_MAX; i++) {
1126
                    if (ts->pids[i])
1127
                        mpegts_close_filter(ts, ts->pids[i]);
1128
                }
1129
                url_fseek(pb, pos, SEEK_SET);
1130
                mpegts_scan_pat(ts);
1131
                
1132
                handle_packets(ts, MAX_SCAN_PACKETS);
1133
            }
1134
            
1135
            if (ts->nb_services <= 0) {
1136
                /* raw transport stream */
1137
                ts->auto_guess = 1;
1138
                s->ctx_flags |= AVFMTCTX_NOHEADER;
1139
                goto do_pcr;
1140
            }
1141
            
1142
            /* tune to first service found */
1143
            for(i=0; i<ts->nb_services && ts->set_service_ret; i++){
1144
                service = ts->services[i];
1145
                sid = service->sid;
1146
#ifdef DEBUG_SI
1147
                printf("tuning to '%s'\n", service->name);
1148
#endif
1149
            
1150
                /* now find the info for the first service if we found any,
1151
                otherwise try to filter all PATs */
1152
                
1153
                url_fseek(pb, pos, SEEK_SET);
1154
                mpegts_set_service(ts, sid, set_service_cb, ts);
1155
                
1156
                handle_packets(ts, MAX_SCAN_PACKETS);
1157
            }
1158
            /* if could not find service, exit */
1159
            
1160
            if (ts->set_service_ret != 0)
1161
                return -1;
1162
            
1163
#ifdef DEBUG_SI
1164
            printf("tuning done\n");
1165
#endif
1166
        }
1167
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1168
    } else {
1169
        AVStream *st;
1170
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1171
        int64_t pcrs[2], pcr_h;
1172
        int packet_count[2];
1173
        uint8_t packet[TS_PACKET_SIZE];
1174
        
1175
        /* only read packets */
1176
        
1177
    do_pcr:
1178
        st = av_new_stream(s, 0);
1179
        if (!st)
1180
            goto fail;
1181
        av_set_pts_info(st, 60, 1, 27000000);
1182
        st->codec.codec_type = CODEC_TYPE_DATA;
1183
        st->codec.codec_id = CODEC_ID_MPEG2TS;
1184
        
1185
        /* we iterate until we find two PCRs to estimate the bitrate */
1186
        pcr_pid = -1;
1187
        nb_pcrs = 0;
1188
        nb_packets = 0;
1189
        for(;;) {
1190
            ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1191
            if (ret < 0)
1192
                return -1;
1193
            pid = ((packet[1] & 0x1f) << 8) | packet[2];
1194
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1195
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1196
                pcr_pid = pid;
1197
                packet_count[nb_pcrs] = nb_packets;
1198
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1199
                nb_pcrs++;
1200
                if (nb_pcrs >= 2)
1201
                    break;
1202
            }
1203
            nb_packets++;
1204
        }
1205
        ts->pcr_pid = pcr_pid;
1206

    
1207
        /* NOTE1: the bitrate is computed without the FEC */
1208
        /* NOTE2: it is only the bitrate of the start of the stream */
1209
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1210
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1211
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1212
        st->codec.bit_rate = s->bit_rate;
1213
        st->start_time = ts->cur_pcr * 1000000.0 / 27.0e6;
1214
#if 0
1215
        printf("start=%0.3f pcr=%0.3f incr=%d\n",
1216
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1217
#endif
1218
    }
1219

    
1220
    url_fseek(pb, pos, SEEK_SET);
1221
    return 0;
1222
 fail:
1223
    return -1;
1224
}
1225

    
1226
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1227

    
1228
static int mpegts_raw_read_packet(AVFormatContext *s,
1229
                                  AVPacket *pkt)
1230
{
1231
    MpegTSContext *ts = s->priv_data;
1232
    int ret, i;
1233
    int64_t pcr_h, next_pcr_h, pos;
1234
    int pcr_l, next_pcr_l;
1235
    uint8_t pcr_buf[12];
1236

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

    
1271
static int mpegts_read_packet(AVFormatContext *s,
1272
                              AVPacket *pkt)
1273
{
1274
    MpegTSContext *ts = s->priv_data;
1275

    
1276
    if (!ts->mpeg2ts_raw) {
1277
        ts->pkt = pkt;
1278
        return handle_packets(ts, 0);
1279
    } else {
1280
        return mpegts_raw_read_packet(s, pkt);
1281
    }
1282
}
1283

    
1284
static int mpegts_read_close(AVFormatContext *s)
1285
{
1286
    MpegTSContext *ts = s->priv_data;
1287
    int i;
1288
    for(i=0;i<NB_PID_MAX;i++)
1289
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1290
    return 0;
1291
}
1292

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

    
1331
    return timestamp;
1332
}
1333

    
1334
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1335
    MpegTSContext *ts = s->priv_data;
1336
    uint8_t buf[TS_PACKET_SIZE];
1337
    int64_t pos;
1338

    
1339
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1340
        return -1;
1341

    
1342
    pos= url_ftell(&s->pb);
1343

    
1344
    for(;;) {
1345
        url_fseek(&s->pb, pos, SEEK_SET);
1346
        if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1347
            return -1;
1348
//        pid = ((buf[1] & 0x1f) << 8) | buf[2];
1349
        if(buf[1] & 0x40) break;
1350
        pos += ts->raw_packet_size;
1351
    }    
1352
    url_fseek(&s->pb, pos, SEEK_SET);
1353

    
1354
    return 0;
1355
}
1356

    
1357
/**************************************************************/
1358
/* parsing functions - called from other demuxers such as RTP */
1359

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

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

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

    
1401
void mpegts_parse_close(MpegTSContext *ts)
1402
{
1403
    int i;
1404

    
1405
    for(i=0;i<NB_PID_MAX;i++)
1406
        av_free(ts->pids[i]);
1407
    av_free(ts);
1408
}
1409

    
1410
AVInputFormat mpegts_demux = {
1411
    "mpegts",
1412
    "MPEG2 transport stream format",
1413
    sizeof(MpegTSContext),
1414
    mpegts_probe,
1415
    mpegts_read_header,
1416
    mpegts_read_packet,
1417
    mpegts_read_close,
1418
    read_seek,
1419
    mpegts_get_pcr,
1420
    .flags = AVFMT_SHOW_IDS,
1421
};
1422

    
1423
int mpegts_init(void)
1424
{
1425
    av_register_input_format(&mpegts_demux);
1426
#ifdef CONFIG_ENCODERS
1427
    av_register_output_format(&mpegts_mux);
1428
#endif
1429
    return 0;
1430
}