~ubuntu-branches/ubuntu/gutsy/blender/gutsy-security

« back to all changes in this revision

Viewing changes to extern/ffmpeg/libavformat/mpegts.c

  • Committer: Bazaar Package Importer
  • Author(s): Lukas Fittl
  • Date: 2006-09-20 01:57:27 UTC
  • mfrom: (1.2.4 upstream)
  • Revision ID: james.westby@ubuntu.com-20060920015727-gmoqlxwstx9wwqs3
Tags: 2.42a-1ubuntu1
* Merge from Debian unstable (Closes: Malone #55903). Remaining changes:
  - debian/genpot: Add python scripts from Lee June <blender@eyou.com> to
    generate a reasonable PO template from the sources. Since gettext is used
    in a highly nonstandard way, xgettext does not work for this job.
  - debian/rules: Call the scripts, generate po/blender.pot, and clean it up
    in the clean target.
  - Add a proper header to the generated PO template.
* debian/control: Build depend on libavformat-dev >= 3:0.cvs20060823-3.1,
  otherwise this package will FTBFS

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
18
 */
 
19
#include "avformat.h"
 
20
#include "crc.h"
 
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
typedef struct PESContext PESContext;
 
34
 
 
35
static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
 
36
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
 
37
 
 
38
enum MpegTSFilterType {
 
39
    MPEGTS_PES,
 
40
    MPEGTS_SECTION,
 
41
};
 
42
 
 
43
typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
 
44
 
 
45
typedef struct MpegTSPESFilter {
 
46
    PESCallback *pes_cb;
 
47
    void *opaque;
 
48
} MpegTSPESFilter;
 
49
 
 
50
typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
 
51
 
 
52
typedef void SetServiceCallback(void *opaque, int ret);
 
53
 
 
54
typedef struct MpegTSSectionFilter {
 
55
    int section_index;
 
56
    int section_h_size;
 
57
    uint8_t *section_buf;
 
58
    int check_crc:1;
 
59
    int end_of_section_reached:1;
 
60
    SectionCallback *section_cb;
 
61
    void *opaque;
 
62
} MpegTSSectionFilter;
 
63
 
 
64
typedef struct MpegTSFilter {
 
65
    int pid;
 
66
    int last_cc; /* last cc code (-1 if first packet) */
 
67
    enum MpegTSFilterType type;
 
68
    union {
 
69
        MpegTSPESFilter pes_filter;
 
70
        MpegTSSectionFilter section_filter;
 
71
    } u;
 
72
} MpegTSFilter;
 
73
 
 
74
typedef struct MpegTSService {
 
75
    int running:1;
 
76
    int sid;
 
77
    char *provider_name;
 
78
    char *name;
 
79
} MpegTSService;
 
80
 
 
81
struct MpegTSContext {
 
82
    /* user data */
 
83
    AVFormatContext *stream;
 
84
    int raw_packet_size; /* raw packet size, including FEC if present */
 
85
    int auto_guess; /* if true, all pids are analized to find streams */
 
86
    int set_service_ret;
 
87
 
 
88
    int mpeg2ts_raw;  /* force raw MPEG2 transport stream output, if possible */
 
89
    int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
 
90
 
 
91
    /* used to estimate the exact PCR */
 
92
    int64_t cur_pcr;
 
93
    int pcr_incr;
 
94
    int pcr_pid;
 
95
 
 
96
    /* data needed to handle file based ts */
 
97
    int stop_parse; /* stop parsing loop */
 
98
    AVPacket *pkt; /* packet containing av data */
 
99
 
 
100
    /******************************************/
 
101
    /* private mpegts data */
 
102
    /* scan context */
 
103
    MpegTSFilter *sdt_filter;
 
104
    int nb_services;
 
105
    MpegTSService **services;
 
106
 
 
107
    /* set service context (XXX: allocated it ?) */
 
108
    SetServiceCallback *set_service_cb;
 
109
    void *set_service_opaque;
 
110
    MpegTSFilter *pat_filter;
 
111
    MpegTSFilter *pmt_filter;
 
112
    int req_sid;
 
113
 
 
114
    MpegTSFilter *pids[NB_PID_MAX];
 
115
};
 
116
 
 
117
static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
 
118
                               const uint8_t *buf, int buf_size, int is_start)
 
119
{
 
120
    MpegTSSectionFilter *tss = &tss1->u.section_filter;
 
121
    int len;
 
122
 
 
123
    if (is_start) {
 
124
        memcpy(tss->section_buf, buf, buf_size);
 
125
        tss->section_index = buf_size;
 
126
        tss->section_h_size = -1;
 
127
        tss->end_of_section_reached = 0;
 
128
    } else {
 
129
        if (tss->end_of_section_reached)
 
130
            return;
 
131
        len = 4096 - tss->section_index;
 
132
        if (buf_size < len)
 
133
            len = buf_size;
 
134
        memcpy(tss->section_buf + tss->section_index, buf, len);
 
135
        tss->section_index += len;
 
136
    }
 
137
 
 
138
    /* compute section length if possible */
 
139
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
 
140
        len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
 
141
        if (len > 4096)
 
142
            return;
 
143
        tss->section_h_size = len;
 
144
    }
 
145
 
 
146
    if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
 
147
        tss->end_of_section_reached = 1;
 
148
        if (!tss->check_crc ||
 
149
            av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
 
150
            tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
 
151
    }
 
152
}
 
153
 
 
154
MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
 
155
                                         SectionCallback *section_cb, void *opaque,
 
156
                                         int check_crc)
 
157
 
 
158
{
 
159
    MpegTSFilter *filter;
 
160
    MpegTSSectionFilter *sec;
 
161
 
 
162
#ifdef DEBUG_SI
 
163
    printf("Filter: pid=0x%x\n", pid);
 
164
#endif
 
165
    if (pid >= NB_PID_MAX || ts->pids[pid])
 
166
        return NULL;
 
167
    filter = av_mallocz(sizeof(MpegTSFilter));
 
168
    if (!filter)
 
169
        return NULL;
 
170
    ts->pids[pid] = filter;
 
171
    filter->type = MPEGTS_SECTION;
 
172
    filter->pid = pid;
 
173
    filter->last_cc = -1;
 
174
    sec = &filter->u.section_filter;
 
175
    sec->section_cb = section_cb;
 
176
    sec->opaque = opaque;
 
177
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
 
178
    sec->check_crc = check_crc;
 
179
    if (!sec->section_buf) {
 
180
        av_free(filter);
 
181
        return NULL;
 
182
    }
 
183
    return filter;
 
184
}
 
185
 
 
186
MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
 
187
                                     PESCallback *pes_cb,
 
188
                                     void *opaque)
 
189
{
 
190
    MpegTSFilter *filter;
 
191
    MpegTSPESFilter *pes;
 
192
 
 
193
    if (pid >= NB_PID_MAX || ts->pids[pid])
 
194
        return NULL;
 
195
    filter = av_mallocz(sizeof(MpegTSFilter));
 
196
    if (!filter)
 
197
        return NULL;
 
198
    ts->pids[pid] = filter;
 
199
    filter->type = MPEGTS_PES;
 
200
    filter->pid = pid;
 
201
    filter->last_cc = -1;
 
202
    pes = &filter->u.pes_filter;
 
203
    pes->pes_cb = pes_cb;
 
204
    pes->opaque = opaque;
 
205
    return filter;
 
206
}
 
207
 
 
208
void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
 
209
{
 
210
    int pid;
 
211
 
 
212
    pid = filter->pid;
 
213
    if (filter->type == MPEGTS_SECTION)
 
214
        av_freep(&filter->u.section_filter.section_buf);
 
215
    else if (filter->type == MPEGTS_PES)
 
216
        av_freep(&filter->u.pes_filter.opaque);
 
217
 
 
218
    av_free(filter);
 
219
    ts->pids[pid] = NULL;
 
220
}
 
221
 
 
222
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
 
223
    int stat[packet_size];
 
224
    int i;
 
225
    int x=0;
 
226
    int best_score=0;
 
227
 
 
228
    memset(stat, 0, packet_size*sizeof(int));
 
229
 
 
230
    for(x=i=0; i<size; i++){
 
231
        if(buf[i] == 0x47){
 
232
            stat[x]++;
 
233
            if(stat[x] > best_score){
 
234
                best_score= stat[x];
 
235
                if(index) *index= x;
 
236
            }
 
237
        }
 
238
 
 
239
        x++;
 
240
        if(x == packet_size) x= 0;
 
241
    }
 
242
 
 
243
    return best_score;
 
244
}
 
245
 
 
246
/* autodetect fec presence. Must have at least 1024 bytes  */
 
247
static int get_packet_size(const uint8_t *buf, int size)
 
248
{
 
249
    int score, fec_score, dvhs_score;
 
250
 
 
251
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
 
252
        return -1;
 
253
 
 
254
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
 
255
    dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
 
256
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
 
257
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
 
258
 
 
259
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
 
260
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
 
261
    else if(score < fec_score && dvhs_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
    PESContext *pes;
 
377
    AVStream *st;
 
378
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
 
379
    int program_info_length, pcr_pid, pid, stream_type;
 
380
    int desc_list_len, desc_len, desc_tag;
 
381
    int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
 
382
    char language[4];
 
383
 
 
384
#ifdef DEBUG_SI
 
385
    printf("PMT:\n");
 
386
    av_hex_dump(stdout, (uint8_t *)section, section_len);
 
387
#endif
 
388
    p_end = section + section_len - 4;
 
389
    p = section;
 
390
    if (parse_section_header(h, &p, p_end) < 0)
 
391
        return;
 
392
#ifdef DEBUG_SI
 
393
    printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
 
394
#endif
 
395
    if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
 
396
        return;
 
397
 
 
398
    pcr_pid = get16(&p, p_end) & 0x1fff;
 
399
    if (pcr_pid < 0)
 
400
        return;
 
401
    ts->pcr_pid = pcr_pid;
 
402
#ifdef DEBUG_SI
 
403
    printf("pcr_pid=0x%x\n", pcr_pid);
 
404
#endif
 
405
    program_info_length = get16(&p, p_end) & 0xfff;
 
406
    if (program_info_length < 0)
 
407
        return;
 
408
    p += program_info_length;
 
409
    if (p >= p_end)
 
410
        return;
 
411
    for(;;) {
 
412
        language[0] = 0;
 
413
        st = 0;
 
414
        stream_type = get8(&p, p_end);
 
415
        if (stream_type < 0)
 
416
            break;
 
417
        pid = get16(&p, p_end) & 0x1fff;
 
418
        if (pid < 0)
 
419
            break;
 
420
        desc_list_len = get16(&p, p_end) & 0xfff;
 
421
        if (desc_list_len < 0)
 
422
            break;
 
423
        desc_list_end = p + desc_list_len;
 
424
        if (desc_list_end > p_end)
 
425
            break;
 
426
        for(;;) {
 
427
            desc_tag = get8(&p, desc_list_end);
 
428
            if (desc_tag < 0)
 
429
                break;
 
430
            if (stream_type == STREAM_TYPE_PRIVATE_DATA &&
 
431
                ((desc_tag == 0x6A) || (desc_tag == 0x7A))) {
 
432
                    /*assume DVB AC-3 Audio*/
 
433
                    stream_type = STREAM_TYPE_AUDIO_AC3;
 
434
            }
 
435
            desc_len = get8(&p, desc_list_end);
 
436
            desc_end = p + desc_len;
 
437
            if (desc_end > desc_list_end)
 
438
                break;
 
439
#ifdef DEBUG_SI
 
440
            printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
 
441
#endif
 
442
            switch(desc_tag) {
 
443
            case DVB_SUBT_DESCID:
 
444
                if (stream_type == STREAM_TYPE_PRIVATE_DATA)
 
445
                    stream_type = STREAM_TYPE_SUBTITLE_DVB;
 
446
 
 
447
                language[0] = get8(&p, desc_end);
 
448
                language[1] = get8(&p, desc_end);
 
449
                language[2] = get8(&p, desc_end);
 
450
                language[3] = 0;
 
451
                get8(&p, desc_end);
 
452
                comp_page = get16(&p, desc_end);
 
453
                anc_page = get16(&p, desc_end);
 
454
 
 
455
                break;
 
456
            case 0x0a: /* ISO 639 language descriptor */
 
457
                language[0] = get8(&p, desc_end);
 
458
                language[1] = get8(&p, desc_end);
 
459
                language[2] = get8(&p, desc_end);
 
460
                language[3] = 0;
 
461
                break;
 
462
            default:
 
463
                break;
 
464
            }
 
465
            p = desc_end;
 
466
        }
 
467
        p = desc_list_end;
 
468
 
 
469
#ifdef DEBUG_SI
 
470
        printf("stream_type=%d pid=0x%x\n", stream_type, pid);
 
471
#endif
 
472
 
 
473
        /* now create ffmpeg stream */
 
474
        switch(stream_type) {
 
475
        case STREAM_TYPE_AUDIO_MPEG1:
 
476
        case STREAM_TYPE_AUDIO_MPEG2:
 
477
        case STREAM_TYPE_VIDEO_MPEG1:
 
478
        case STREAM_TYPE_VIDEO_MPEG2:
 
479
        case STREAM_TYPE_VIDEO_MPEG4:
 
480
        case STREAM_TYPE_VIDEO_H264:
 
481
        case STREAM_TYPE_AUDIO_AAC:
 
482
        case STREAM_TYPE_AUDIO_AC3:
 
483
        case STREAM_TYPE_AUDIO_DTS:
 
484
        case STREAM_TYPE_SUBTITLE_DVB:
 
485
            pes = add_pes_stream(ts, pid, stream_type);
 
486
            if (pes)
 
487
                st = new_pes_av_stream(pes, 0);
 
488
            break;
 
489
        default:
 
490
            /* we ignore the other streams */
 
491
            break;
 
492
        }
 
493
 
 
494
        if (st) {
 
495
            if (language[0] != 0) {
 
496
                st->language[0] = language[0];
 
497
                st->language[1] = language[1];
 
498
                st->language[2] = language[2];
 
499
                st->language[3] = language[3];
 
500
            }
 
501
 
 
502
            if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
 
503
                st->codec->sub_id = (anc_page << 16) | comp_page;
 
504
            }
 
505
        }
 
506
    }
 
507
    /* all parameters are there */
 
508
    ts->set_service_cb(ts->set_service_opaque, 0);
 
509
    mpegts_close_filter(ts, ts->pmt_filter);
 
510
    ts->pmt_filter = NULL;
 
511
}
 
512
 
 
513
static void pat_cb(void *opaque, const uint8_t *section, int section_len)
 
514
{
 
515
    MpegTSContext *ts = opaque;
 
516
    SectionHeader h1, *h = &h1;
 
517
    const uint8_t *p, *p_end;
 
518
    int sid, pmt_pid;
 
519
 
 
520
#ifdef DEBUG_SI
 
521
    printf("PAT:\n");
 
522
    av_hex_dump(stdout, (uint8_t *)section, section_len);
 
523
#endif
 
524
    p_end = section + section_len - 4;
 
525
    p = section;
 
526
    if (parse_section_header(h, &p, p_end) < 0)
 
527
        return;
 
528
    if (h->tid != PAT_TID)
 
529
        return;
 
530
 
 
531
    for(;;) {
 
532
        sid = get16(&p, p_end);
 
533
        if (sid < 0)
 
534
            break;
 
535
        pmt_pid = get16(&p, p_end) & 0x1fff;
 
536
        if (pmt_pid < 0)
 
537
            break;
 
538
#ifdef DEBUG_SI
 
539
        printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
 
540
#endif
 
541
        if (sid == 0x0000) {
 
542
            /* NIT info */
 
543
        } else {
 
544
            if (ts->req_sid == sid) {
 
545
                ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
 
546
                                                            pmt_cb, ts, 1);
 
547
                goto found;
 
548
            }
 
549
        }
 
550
    }
 
551
    /* not found */
 
552
    ts->set_service_cb(ts->set_service_opaque, -1);
 
553
 
 
554
 found:
 
555
    mpegts_close_filter(ts, ts->pat_filter);
 
556
    ts->pat_filter = NULL;
 
557
}
 
558
 
 
559
/* add all services found in the PAT */
 
560
static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
 
561
{
 
562
    MpegTSContext *ts = opaque;
 
563
    SectionHeader h1, *h = &h1;
 
564
    const uint8_t *p, *p_end;
 
565
    int sid, pmt_pid;
 
566
    char *provider_name, *name;
 
567
    char buf[256];
 
568
 
 
569
#ifdef DEBUG_SI
 
570
    printf("PAT:\n");
 
571
    av_hex_dump(stdout, (uint8_t *)section, section_len);
 
572
#endif
 
573
    p_end = section + section_len - 4;
 
574
    p = section;
 
575
    if (parse_section_header(h, &p, p_end) < 0)
 
576
        return;
 
577
    if (h->tid != PAT_TID)
 
578
        return;
 
579
 
 
580
    for(;;) {
 
581
        sid = get16(&p, p_end);
 
582
        if (sid < 0)
 
583
            break;
 
584
        pmt_pid = get16(&p, p_end) & 0x1fff;
 
585
        if (pmt_pid < 0)
 
586
            break;
 
587
#ifdef DEBUG_SI
 
588
        printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
 
589
#endif
 
590
        if (sid == 0x0000) {
 
591
            /* NIT info */
 
592
        } else {
 
593
            /* add the service with a dummy name */
 
594
            snprintf(buf, sizeof(buf), "Service %x\n", sid);
 
595
            name = av_strdup(buf);
 
596
            provider_name = av_strdup("");
 
597
            if (name && provider_name) {
 
598
                new_service(ts, sid, provider_name, name);
 
599
            } else {
 
600
                av_freep(&name);
 
601
                av_freep(&provider_name);
 
602
            }
 
603
        }
 
604
    }
 
605
    ts->stop_parse = 1;
 
606
 
 
607
    /* remove filter */
 
608
    mpegts_close_filter(ts, ts->pat_filter);
 
609
    ts->pat_filter = NULL;
 
610
}
 
611
 
 
612
void mpegts_set_service(MpegTSContext *ts, int sid,
 
613
                        SetServiceCallback *set_service_cb, void *opaque)
 
614
{
 
615
    ts->set_service_cb = set_service_cb;
 
616
    ts->set_service_opaque = opaque;
 
617
    ts->req_sid = sid;
 
618
    ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
 
619
                                                pat_cb, ts, 1);
 
620
}
 
621
 
 
622
static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
 
623
{
 
624
    MpegTSContext *ts = opaque;
 
625
    SectionHeader h1, *h = &h1;
 
626
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
 
627
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
 
628
    char *name, *provider_name;
 
629
 
 
630
#ifdef DEBUG_SI
 
631
    printf("SDT:\n");
 
632
    av_hex_dump(stdout, (uint8_t *)section, section_len);
 
633
#endif
 
634
 
 
635
    p_end = section + section_len - 4;
 
636
    p = section;
 
637
    if (parse_section_header(h, &p, p_end) < 0)
 
638
        return;
 
639
    if (h->tid != SDT_TID)
 
640
        return;
 
641
    onid = get16(&p, p_end);
 
642
    if (onid < 0)
 
643
        return;
 
644
    val = get8(&p, p_end);
 
645
    if (val < 0)
 
646
        return;
 
647
    for(;;) {
 
648
        sid = get16(&p, p_end);
 
649
        if (sid < 0)
 
650
            break;
 
651
        val = get8(&p, p_end);
 
652
        if (val < 0)
 
653
            break;
 
654
        desc_list_len = get16(&p, p_end) & 0xfff;
 
655
        if (desc_list_len < 0)
 
656
            break;
 
657
        desc_list_end = p + desc_list_len;
 
658
        if (desc_list_end > p_end)
 
659
            break;
 
660
        for(;;) {
 
661
            desc_tag = get8(&p, desc_list_end);
 
662
            if (desc_tag < 0)
 
663
                break;
 
664
            desc_len = get8(&p, desc_list_end);
 
665
            desc_end = p + desc_len;
 
666
            if (desc_end > desc_list_end)
 
667
                break;
 
668
#ifdef DEBUG_SI
 
669
            printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
 
670
#endif
 
671
            switch(desc_tag) {
 
672
            case 0x48:
 
673
                service_type = get8(&p, p_end);
 
674
                if (service_type < 0)
 
675
                    break;
 
676
                provider_name = getstr8(&p, p_end);
 
677
                if (!provider_name)
 
678
                    break;
 
679
                name = getstr8(&p, p_end);
 
680
                if (!name)
 
681
                    break;
 
682
                new_service(ts, sid, provider_name, name);
 
683
                break;
 
684
            default:
 
685
                break;
 
686
            }
 
687
            p = desc_end;
 
688
        }
 
689
        p = desc_list_end;
 
690
    }
 
691
    ts->stop_parse = 1;
 
692
 
 
693
    /* remove filter */
 
694
    mpegts_close_filter(ts, ts->sdt_filter);
 
695
    ts->sdt_filter = NULL;
 
696
}
 
697
 
 
698
/* scan services in a transport stream by looking at the SDT */
 
699
void mpegts_scan_sdt(MpegTSContext *ts)
 
700
{
 
701
    ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
 
702
                                                sdt_cb, ts, 1);
 
703
}
 
704
 
 
705
/* scan services in a transport stream by looking at the PAT (better
 
706
   than nothing !) */
 
707
void mpegts_scan_pat(MpegTSContext *ts)
 
708
{
 
709
    ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
 
710
                                                pat_scan_cb, ts, 1);
 
711
}
 
712
 
 
713
/* TS stream handling */
 
714
 
 
715
enum MpegTSState {
 
716
    MPEGTS_HEADER = 0,
 
717
    MPEGTS_PESHEADER_FILL,
 
718
    MPEGTS_PAYLOAD,
 
719
    MPEGTS_SKIP,
 
720
};
 
721
 
 
722
/* enough for PES header + length */
 
723
#define PES_START_SIZE 9
 
724
#define MAX_PES_HEADER_SIZE (9 + 255)
 
725
 
 
726
struct PESContext {
 
727
    int pid;
 
728
    int stream_type;
 
729
    MpegTSContext *ts;
 
730
    AVFormatContext *stream;
 
731
    AVStream *st;
 
732
    enum MpegTSState state;
 
733
    /* used to get the format */
 
734
    int data_index;
 
735
    int total_size;
 
736
    int pes_header_size;
 
737
    int64_t pts, dts;
 
738
    uint8_t header[MAX_PES_HEADER_SIZE];
 
739
};
 
740
 
 
741
static int64_t get_pts(const uint8_t *p)
 
742
{
 
743
    int64_t pts;
 
744
    int val;
 
745
 
 
746
    pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
 
747
    val = (p[1] << 8) | p[2];
 
748
    pts |= (int64_t)(val >> 1) << 15;
 
749
    val = (p[3] << 8) | p[4];
 
750
    pts |= (int64_t)(val >> 1);
 
751
    return pts;
 
752
}
 
753
 
 
754
/* return non zero if a packet could be constructed */
 
755
static void mpegts_push_data(void *opaque,
 
756
                             const uint8_t *buf, int buf_size, int is_start)
 
757
{
 
758
    PESContext *pes = opaque;
 
759
    MpegTSContext *ts = pes->ts;
 
760
    const uint8_t *p;
 
761
    int len, code;
 
762
 
 
763
    if (is_start) {
 
764
        pes->state = MPEGTS_HEADER;
 
765
        pes->data_index = 0;
 
766
    }
 
767
    p = buf;
 
768
    while (buf_size > 0) {
 
769
        switch(pes->state) {
 
770
        case MPEGTS_HEADER:
 
771
            len = PES_START_SIZE - pes->data_index;
 
772
            if (len > buf_size)
 
773
                len = buf_size;
 
774
            memcpy(pes->header + pes->data_index, p, len);
 
775
            pes->data_index += len;
 
776
            p += len;
 
777
            buf_size -= len;
 
778
            if (pes->data_index == PES_START_SIZE) {
 
779
                /* we got all the PES or section header. We can now
 
780
                   decide */
 
781
#if 0
 
782
                av_hex_dump(pes->header, pes->data_index);
 
783
#endif
 
784
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
 
785
                    pes->header[2] == 0x01) {
 
786
                    /* it must be an mpeg2 PES stream */
 
787
                    code = pes->header[3] | 0x100;
 
788
                    if (!((code >= 0x1c0 && code <= 0x1df) ||
 
789
                          (code >= 0x1e0 && code <= 0x1ef) ||
 
790
                          (code == 0x1bd)))
 
791
                        goto skip;
 
792
                    if (!pes->st) {
 
793
                        /* allocate stream */
 
794
                        new_pes_av_stream(pes, code);
 
795
                    }
 
796
                    pes->state = MPEGTS_PESHEADER_FILL;
 
797
                    pes->total_size = (pes->header[4] << 8) | pes->header[5];
 
798
                    /* NOTE: a zero total size means the PES size is
 
799
                       unbounded */
 
800
                    if (pes->total_size)
 
801
                        pes->total_size += 6;
 
802
                    pes->pes_header_size = pes->header[8] + 9;
 
803
                } else {
 
804
                    /* otherwise, it should be a table */
 
805
                    /* skip packet */
 
806
                skip:
 
807
                    pes->state = MPEGTS_SKIP;
 
808
                    continue;
 
809
                }
 
810
            }
 
811
            break;
 
812
            /**********************************************/
 
813
            /* PES packing parsing */
 
814
        case MPEGTS_PESHEADER_FILL:
 
815
            len = pes->pes_header_size - pes->data_index;
 
816
            if (len > buf_size)
 
817
                len = buf_size;
 
818
            memcpy(pes->header + pes->data_index, p, len);
 
819
            pes->data_index += len;
 
820
            p += len;
 
821
            buf_size -= len;
 
822
            if (pes->data_index == pes->pes_header_size) {
 
823
                const uint8_t *r;
 
824
                unsigned int flags;
 
825
 
 
826
                flags = pes->header[7];
 
827
                r = pes->header + 9;
 
828
                pes->pts = AV_NOPTS_VALUE;
 
829
                pes->dts = AV_NOPTS_VALUE;
 
830
                if ((flags & 0xc0) == 0x80) {
 
831
                    pes->pts = get_pts(r);
 
832
                    r += 5;
 
833
                } else if ((flags & 0xc0) == 0xc0) {
 
834
                    pes->pts = get_pts(r);
 
835
                    r += 5;
 
836
                    pes->dts = get_pts(r);
 
837
                    r += 5;
 
838
                }
 
839
                /* we got the full header. We parse it and get the payload */
 
840
                pes->state = MPEGTS_PAYLOAD;
 
841
            }
 
842
            break;
 
843
        case MPEGTS_PAYLOAD:
 
844
            if (pes->total_size) {
 
845
                len = pes->total_size - pes->data_index;
 
846
                if (len > buf_size)
 
847
                    len = buf_size;
 
848
            } else {
 
849
                len = buf_size;
 
850
            }
 
851
            if (len > 0) {
 
852
                AVPacket *pkt = ts->pkt;
 
853
                if (pes->st && av_new_packet(pkt, len) == 0) {
 
854
                    memcpy(pkt->data, p, len);
 
855
                    pkt->stream_index = pes->st->index;
 
856
                    pkt->pts = pes->pts;
 
857
                    pkt->dts = pes->dts;
 
858
                    /* reset pts values */
 
859
                    pes->pts = AV_NOPTS_VALUE;
 
860
                    pes->dts = AV_NOPTS_VALUE;
 
861
                    ts->stop_parse = 1;
 
862
                    return;
 
863
                }
 
864
            }
 
865
            buf_size = 0;
 
866
            break;
 
867
        case MPEGTS_SKIP:
 
868
            buf_size = 0;
 
869
            break;
 
870
        }
 
871
    }
 
872
}
 
873
 
 
874
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
 
875
{
 
876
    AVStream *st;
 
877
    int codec_type, codec_id;
 
878
 
 
879
    switch(pes->stream_type){
 
880
    case STREAM_TYPE_AUDIO_MPEG1:
 
881
    case STREAM_TYPE_AUDIO_MPEG2:
 
882
        codec_type = CODEC_TYPE_AUDIO;
 
883
        codec_id = CODEC_ID_MP3;
 
884
        break;
 
885
    case STREAM_TYPE_VIDEO_MPEG1:
 
886
    case STREAM_TYPE_VIDEO_MPEG2:
 
887
        codec_type = CODEC_TYPE_VIDEO;
 
888
        codec_id = CODEC_ID_MPEG2VIDEO;
 
889
        break;
 
890
    case STREAM_TYPE_VIDEO_MPEG4:
 
891
        codec_type = CODEC_TYPE_VIDEO;
 
892
        codec_id = CODEC_ID_MPEG4;
 
893
        break;
 
894
    case STREAM_TYPE_VIDEO_H264:
 
895
        codec_type = CODEC_TYPE_VIDEO;
 
896
        codec_id = CODEC_ID_H264;
 
897
        break;
 
898
    case STREAM_TYPE_AUDIO_AAC:
 
899
        codec_type = CODEC_TYPE_AUDIO;
 
900
        codec_id = CODEC_ID_AAC;
 
901
        break;
 
902
    case STREAM_TYPE_AUDIO_AC3:
 
903
        codec_type = CODEC_TYPE_AUDIO;
 
904
        codec_id = CODEC_ID_AC3;
 
905
        break;
 
906
    case STREAM_TYPE_AUDIO_DTS:
 
907
        codec_type = CODEC_TYPE_AUDIO;
 
908
        codec_id = CODEC_ID_DTS;
 
909
        break;
 
910
    case STREAM_TYPE_SUBTITLE_DVB:
 
911
        codec_type = CODEC_TYPE_SUBTITLE;
 
912
        codec_id = CODEC_ID_DVB_SUBTITLE;
 
913
        break;
 
914
    default:
 
915
        if (code >= 0x1c0 && code <= 0x1df) {
 
916
            codec_type = CODEC_TYPE_AUDIO;
 
917
            codec_id = CODEC_ID_MP2;
 
918
        } else if (code == 0x1bd) {
 
919
            codec_type = CODEC_TYPE_AUDIO;
 
920
            codec_id = CODEC_ID_AC3;
 
921
        } else {
 
922
            codec_type = CODEC_TYPE_VIDEO;
 
923
            codec_id = CODEC_ID_MPEG1VIDEO;
 
924
        }
 
925
        break;
 
926
    }
 
927
    st = av_new_stream(pes->stream, pes->pid);
 
928
    if (st) {
 
929
        av_set_pts_info(st, 33, 1, 90000);
 
930
        st->priv_data = pes;
 
931
        st->codec->codec_type = codec_type;
 
932
        st->codec->codec_id = codec_id;
 
933
        st->need_parsing = 1;
 
934
        pes->st = st;
 
935
    }
 
936
    return st;
 
937
}
 
938
 
 
939
 
 
940
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
 
941
{
 
942
    MpegTSFilter *tss;
 
943
    PESContext *pes;
 
944
 
 
945
    /* if no pid found, then add a pid context */
 
946
    pes = av_mallocz(sizeof(PESContext));
 
947
    if (!pes)
 
948
        return 0;
 
949
    pes->ts = ts;
 
950
    pes->stream = ts->stream;
 
951
    pes->pid = pid;
 
952
    pes->stream_type = stream_type;
 
953
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
 
954
    if (!tss) {
 
955
        av_free(pes);
 
956
        return 0;
 
957
    }
 
958
    return pes;
 
959
}
 
960
 
 
961
/* handle one TS packet */
 
962
static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
 
963
{
 
964
    AVFormatContext *s = ts->stream;
 
965
    MpegTSFilter *tss;
 
966
    int len, pid, cc, cc_ok, afc, is_start;
 
967
    const uint8_t *p, *p_end;
 
968
 
 
969
    pid = ((packet[1] & 0x1f) << 8) | packet[2];
 
970
    is_start = packet[1] & 0x40;
 
971
    tss = ts->pids[pid];
 
972
    if (ts->auto_guess && tss == NULL && is_start) {
 
973
        add_pes_stream(ts, pid, 0);
 
974
        tss = ts->pids[pid];
 
975
    }
 
976
    if (!tss)
 
977
        return;
 
978
 
 
979
    /* continuity check (currently not used) */
 
980
    cc = (packet[3] & 0xf);
 
981
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
 
982
    tss->last_cc = cc;
 
983
 
 
984
    /* skip adaptation field */
 
985
    afc = (packet[3] >> 4) & 3;
 
986
    p = packet + 4;
 
987
    if (afc == 0) /* reserved value */
 
988
        return;
 
989
    if (afc == 2) /* adaptation field only */
 
990
        return;
 
991
    if (afc == 3) {
 
992
        /* skip adapation field */
 
993
        p += p[0] + 1;
 
994
    }
 
995
    /* if past the end of packet, ignore */
 
996
    p_end = packet + TS_PACKET_SIZE;
 
997
    if (p >= p_end)
 
998
        return;
 
999
 
 
1000
    if (tss->type == MPEGTS_SECTION) {
 
1001
        if (is_start) {
 
1002
            /* pointer field present */
 
1003
            len = *p++;
 
1004
            if (p + len > p_end)
 
1005
                return;
 
1006
            if (len && cc_ok) {
 
1007
                /* write remaining section bytes */
 
1008
                write_section_data(s, tss,
 
1009
                                   p, len, 0);
 
1010
                /* check whether filter has been closed */
 
1011
                if (!ts->pids[pid])
 
1012
                    return;
 
1013
            }
 
1014
            p += len;
 
1015
            if (p < p_end) {
 
1016
                write_section_data(s, tss,
 
1017
                                   p, p_end - p, 1);
 
1018
            }
 
1019
        } else {
 
1020
            if (cc_ok) {
 
1021
                write_section_data(s, tss,
 
1022
                                   p, p_end - p, 0);
 
1023
            }
 
1024
        }
 
1025
    } else {
 
1026
        tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
 
1027
                                 p, p_end - p, is_start);
 
1028
    }
 
1029
}
 
1030
 
 
1031
/* XXX: try to find a better synchro over several packets (use
 
1032
   get_packet_size() ?) */
 
1033
static int mpegts_resync(ByteIOContext *pb)
 
1034
{
 
1035
    int c, i;
 
1036
 
 
1037
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
 
1038
        c = url_fgetc(pb);
 
1039
        if (c < 0)
 
1040
            return -1;
 
1041
        if (c == 0x47) {
 
1042
            url_fseek(pb, -1, SEEK_CUR);
 
1043
            return 0;
 
1044
        }
 
1045
    }
 
1046
    /* no sync found */
 
1047
    return -1;
 
1048
}
 
1049
 
 
1050
/* return -1 if error or EOF. Return 0 if OK. */
 
1051
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
 
1052
{
 
1053
    int skip, len;
 
1054
 
 
1055
    for(;;) {
 
1056
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
 
1057
        if (len != TS_PACKET_SIZE)
 
1058
            return AVERROR_IO;
 
1059
        /* check paquet sync byte */
 
1060
        if (buf[0] != 0x47) {
 
1061
            /* find a new packet start */
 
1062
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
 
1063
            if (mpegts_resync(pb) < 0)
 
1064
                return AVERROR_INVALIDDATA;
 
1065
            else
 
1066
                continue;
 
1067
        } else {
 
1068
            skip = raw_packet_size - TS_PACKET_SIZE;
 
1069
            if (skip > 0)
 
1070
                url_fskip(pb, skip);
 
1071
            break;
 
1072
        }
 
1073
    }
 
1074
    return 0;
 
1075
}
 
1076
 
 
1077
static int handle_packets(MpegTSContext *ts, int nb_packets)
 
1078
{
 
1079
    AVFormatContext *s = ts->stream;
 
1080
    ByteIOContext *pb = &s->pb;
 
1081
    uint8_t packet[TS_PACKET_SIZE];
 
1082
    int packet_num, ret;
 
1083
 
 
1084
    ts->stop_parse = 0;
 
1085
    packet_num = 0;
 
1086
    for(;;) {
 
1087
        if (ts->stop_parse)
 
1088
            break;
 
1089
        packet_num++;
 
1090
        if (nb_packets != 0 && packet_num >= nb_packets)
 
1091
            break;
 
1092
        ret = read_packet(pb, packet, ts->raw_packet_size);
 
1093
        if (ret != 0)
 
1094
            return ret;
 
1095
        handle_packet(ts, packet);
 
1096
    }
 
1097
    return 0;
 
1098
}
 
1099
 
 
1100
static int mpegts_probe(AVProbeData *p)
 
1101
{
 
1102
#if 1
 
1103
    const int size= p->buf_size;
 
1104
    int score, fec_score, dvhs_score;
 
1105
#define CHECK_COUNT 10
 
1106
 
 
1107
    if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
 
1108
        return -1;
 
1109
 
 
1110
    score    = analyze(p->buf, TS_PACKET_SIZE    *CHECK_COUNT, TS_PACKET_SIZE, NULL);
 
1111
    dvhs_score  = analyze(p->buf, TS_DVHS_PACKET_SIZE    *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
 
1112
    fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
 
1113
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
 
1114
 
 
1115
// we need a clear definition for the returned score otherwise things will become messy sooner or later
 
1116
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
 
1117
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
 
1118
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
 
1119
    else                                    return -1;
 
1120
#else
 
1121
    /* only use the extension for safer guess */
 
1122
    if (match_ext(p->filename, "ts"))
 
1123
        return AVPROBE_SCORE_MAX;
 
1124
    else
 
1125
        return 0;
 
1126
#endif
 
1127
}
 
1128
 
 
1129
void set_service_cb(void *opaque, int ret)
 
1130
{
 
1131
    MpegTSContext *ts = opaque;
 
1132
    ts->set_service_ret = ret;
 
1133
    ts->stop_parse = 1;
 
1134
}
 
1135
 
 
1136
/* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
 
1137
   (-1) if not available */
 
1138
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
 
1139
                     const uint8_t *packet)
 
1140
{
 
1141
    int afc, len, flags;
 
1142
    const uint8_t *p;
 
1143
    unsigned int v;
 
1144
 
 
1145
    afc = (packet[3] >> 4) & 3;
 
1146
    if (afc <= 1)
 
1147
        return -1;
 
1148
    p = packet + 4;
 
1149
    len = p[0];
 
1150
    p++;
 
1151
    if (len == 0)
 
1152
        return -1;
 
1153
    flags = *p++;
 
1154
    len--;
 
1155
    if (!(flags & 0x10))
 
1156
        return -1;
 
1157
    if (len < 6)
 
1158
        return -1;
 
1159
    v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
 
1160
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
 
1161
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
 
1162
    return 0;
 
1163
}
 
1164
 
 
1165
static int mpegts_read_header(AVFormatContext *s,
 
1166
                              AVFormatParameters *ap)
 
1167
{
 
1168
    MpegTSContext *ts = s->priv_data;
 
1169
    ByteIOContext *pb = &s->pb;
 
1170
    uint8_t buf[1024];
 
1171
    int len, sid, i;
 
1172
    int64_t pos;
 
1173
    MpegTSService *service;
 
1174
 
 
1175
    if (ap) {
 
1176
        ts->mpeg2ts_raw = ap->mpeg2ts_raw;
 
1177
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
 
1178
    }
 
1179
 
 
1180
    /* read the first 1024 bytes to get packet size */
 
1181
    pos = url_ftell(pb);
 
1182
    len = get_buffer(pb, buf, sizeof(buf));
 
1183
    if (len != sizeof(buf))
 
1184
        goto fail;
 
1185
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
 
1186
    if (ts->raw_packet_size <= 0)
 
1187
        goto fail;
 
1188
    ts->stream = s;
 
1189
    ts->auto_guess = 0;
 
1190
 
 
1191
goto_auto_guess:
 
1192
    if (!ts->mpeg2ts_raw) {
 
1193
        /* normal demux */
 
1194
 
 
1195
        if (!ts->auto_guess) {
 
1196
            ts->set_service_ret = -1;
 
1197
 
 
1198
            /* first do a scaning to get all the services */
 
1199
            url_fseek(pb, pos, SEEK_SET);
 
1200
            mpegts_scan_sdt(ts);
 
1201
 
 
1202
            handle_packets(ts, MAX_SCAN_PACKETS);
 
1203
 
 
1204
            if (ts->nb_services <= 0) {
 
1205
                /* no SDT found, we try to look at the PAT */
 
1206
 
 
1207
                /* First remove the SDT filters from each PID */
 
1208
                int i;
 
1209
                for (i=0; i < NB_PID_MAX; i++) {
 
1210
                    if (ts->pids[i])
 
1211
                        mpegts_close_filter(ts, ts->pids[i]);
 
1212
                }
 
1213
                url_fseek(pb, pos, SEEK_SET);
 
1214
                mpegts_scan_pat(ts);
 
1215
 
 
1216
                handle_packets(ts, MAX_SCAN_PACKETS);
 
1217
            }
 
1218
 
 
1219
            if (ts->nb_services <= 0) {
 
1220
                /* raw transport stream */
 
1221
                ts->auto_guess = 1;
 
1222
                s->ctx_flags |= AVFMTCTX_NOHEADER;
 
1223
                goto do_pcr;
 
1224
            }
 
1225
 
 
1226
            /* tune to first service found */
 
1227
            for(i=0; i<ts->nb_services && ts->set_service_ret; i++){
 
1228
                service = ts->services[i];
 
1229
                sid = service->sid;
 
1230
#ifdef DEBUG_SI
 
1231
                printf("tuning to '%s'\n", service->name);
 
1232
#endif
 
1233
 
 
1234
                /* now find the info for the first service if we found any,
 
1235
                otherwise try to filter all PATs */
 
1236
 
 
1237
                url_fseek(pb, pos, SEEK_SET);
 
1238
                mpegts_set_service(ts, sid, set_service_cb, ts);
 
1239
 
 
1240
                handle_packets(ts, MAX_SCAN_PACKETS);
 
1241
            }
 
1242
            /* if could not find service, exit */
 
1243
 
 
1244
            if (ts->set_service_ret != 0) {
 
1245
                if(ts->auto_guess)
 
1246
                  return -1;
 
1247
                else {
 
1248
                  //let's retry with auto_guess set
 
1249
                 ts->auto_guess = 1;
 
1250
                 goto goto_auto_guess;
 
1251
                }
 
1252
            }
 
1253
 
 
1254
#ifdef DEBUG_SI
 
1255
            printf("tuning done\n");
 
1256
#endif
 
1257
        }
 
1258
        s->ctx_flags |= AVFMTCTX_NOHEADER;
 
1259
    } else {
 
1260
        AVStream *st;
 
1261
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
 
1262
        int64_t pcrs[2], pcr_h;
 
1263
        int packet_count[2];
 
1264
        uint8_t packet[TS_PACKET_SIZE];
 
1265
 
 
1266
        /* only read packets */
 
1267
 
 
1268
    do_pcr:
 
1269
        st = av_new_stream(s, 0);
 
1270
        if (!st)
 
1271
            goto fail;
 
1272
        av_set_pts_info(st, 60, 1, 27000000);
 
1273
        st->codec->codec_type = CODEC_TYPE_DATA;
 
1274
        st->codec->codec_id = CODEC_ID_MPEG2TS;
 
1275
 
 
1276
        /* we iterate until we find two PCRs to estimate the bitrate */
 
1277
        pcr_pid = -1;
 
1278
        nb_pcrs = 0;
 
1279
        nb_packets = 0;
 
1280
        for(;;) {
 
1281
            ret = read_packet(&s->pb, packet, ts->raw_packet_size);
 
1282
            if (ret < 0)
 
1283
                return -1;
 
1284
            pid = ((packet[1] & 0x1f) << 8) | packet[2];
 
1285
            if ((pcr_pid == -1 || pcr_pid == pid) &&
 
1286
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
 
1287
                pcr_pid = pid;
 
1288
                packet_count[nb_pcrs] = nb_packets;
 
1289
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
 
1290
                nb_pcrs++;
 
1291
                if (nb_pcrs >= 2)
 
1292
                    break;
 
1293
            }
 
1294
            nb_packets++;
 
1295
        }
 
1296
        ts->pcr_pid = pcr_pid;
 
1297
 
 
1298
        /* NOTE1: the bitrate is computed without the FEC */
 
1299
        /* NOTE2: it is only the bitrate of the start of the stream */
 
1300
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
 
1301
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
 
1302
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
 
1303
        st->codec->bit_rate = s->bit_rate;
 
1304
        st->start_time = ts->cur_pcr;
 
1305
#if 0
 
1306
        printf("start=%0.3f pcr=%0.3f incr=%d\n",
 
1307
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
 
1308
#endif
 
1309
    }
 
1310
 
 
1311
    url_fseek(pb, pos, SEEK_SET);
 
1312
    return 0;
 
1313
 fail:
 
1314
    return -1;
 
1315
}
 
1316
 
 
1317
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
 
1318
 
 
1319
static int mpegts_raw_read_packet(AVFormatContext *s,
 
1320
                                  AVPacket *pkt)
 
1321
{
 
1322
    MpegTSContext *ts = s->priv_data;
 
1323
    int ret, i;
 
1324
    int64_t pcr_h, next_pcr_h, pos;
 
1325
    int pcr_l, next_pcr_l;
 
1326
    uint8_t pcr_buf[12];
 
1327
 
 
1328
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
 
1329
        return -ENOMEM;
 
1330
    pkt->pos= url_ftell(&s->pb);
 
1331
    ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
 
1332
    if (ret < 0) {
 
1333
        av_free_packet(pkt);
 
1334
        return ret;
 
1335
    }
 
1336
    if (ts->mpeg2ts_compute_pcr) {
 
1337
        /* compute exact PCR for each packet */
 
1338
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
 
1339
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
 
1340
            pos = url_ftell(&s->pb);
 
1341
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
 
1342
                url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
 
1343
                get_buffer(&s->pb, pcr_buf, 12);
 
1344
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
 
1345
                    /* XXX: not precise enough */
 
1346
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
 
1347
                        (i + 1);
 
1348
                    break;
 
1349
                }
 
1350
            }
 
1351
            url_fseek(&s->pb, pos, SEEK_SET);
 
1352
            /* no next PCR found: we use previous increment */
 
1353
            ts->cur_pcr = pcr_h * 300 + pcr_l;
 
1354
        }
 
1355
        pkt->pts = ts->cur_pcr;
 
1356
        pkt->duration = ts->pcr_incr;
 
1357
        ts->cur_pcr += ts->pcr_incr;
 
1358
    }
 
1359
    pkt->stream_index = 0;
 
1360
    return 0;
 
1361
}
 
1362
 
 
1363
static int mpegts_read_packet(AVFormatContext *s,
 
1364
                              AVPacket *pkt)
 
1365
{
 
1366
    MpegTSContext *ts = s->priv_data;
 
1367
 
 
1368
    if (!ts->mpeg2ts_raw) {
 
1369
        ts->pkt = pkt;
 
1370
        return handle_packets(ts, 0);
 
1371
    } else {
 
1372
        return mpegts_raw_read_packet(s, pkt);
 
1373
    }
 
1374
}
 
1375
 
 
1376
static int mpegts_read_close(AVFormatContext *s)
 
1377
{
 
1378
    MpegTSContext *ts = s->priv_data;
 
1379
    int i;
 
1380
    for(i=0;i<NB_PID_MAX;i++)
 
1381
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
 
1382
 
 
1383
    for(i = 0; i < ts->nb_services; i++){
 
1384
        av_free(ts->services[i]->provider_name);
 
1385
        av_free(ts->services[i]->name);
 
1386
        av_free(ts->services[i]);
 
1387
    }
 
1388
    av_freep(&ts->services);
 
1389
 
 
1390
    return 0;
 
1391
}
 
1392
 
 
1393
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
 
1394
                              int64_t *ppos, int64_t pos_limit)
 
1395
{
 
1396
    MpegTSContext *ts = s->priv_data;
 
1397
    int64_t pos, timestamp;
 
1398
    uint8_t buf[TS_PACKET_SIZE];
 
1399
    int pcr_l, pid;
 
1400
    const int find_next= 1;
 
1401
    pos = ((*ppos  + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
 
1402
    if (find_next) {
 
1403
        for(;;) {
 
1404
            url_fseek(&s->pb, pos, SEEK_SET);
 
1405
            if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
 
1406
                return AV_NOPTS_VALUE;
 
1407
            pid = ((buf[1] & 0x1f) << 8) | buf[2];
 
1408
            if (pid == ts->pcr_pid &&
 
1409
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
 
1410
                break;
 
1411
            }
 
1412
            pos += ts->raw_packet_size;
 
1413
        }
 
1414
    } else {
 
1415
        for(;;) {
 
1416
            pos -= ts->raw_packet_size;
 
1417
            if (pos < 0)
 
1418
                return AV_NOPTS_VALUE;
 
1419
            url_fseek(&s->pb, pos, SEEK_SET);
 
1420
            if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
 
1421
                return AV_NOPTS_VALUE;
 
1422
            pid = ((buf[1] & 0x1f) << 8) | buf[2];
 
1423
            if (pid == ts->pcr_pid &&
 
1424
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
 
1425
                break;
 
1426
            }
 
1427
        }
 
1428
    }
 
1429
    *ppos = pos;
 
1430
 
 
1431
    return timestamp;
 
1432
}
 
1433
 
 
1434
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
 
1435
    MpegTSContext *ts = s->priv_data;
 
1436
    uint8_t buf[TS_PACKET_SIZE];
 
1437
    int64_t pos;
 
1438
 
 
1439
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
 
1440
        return -1;
 
1441
 
 
1442
    pos= url_ftell(&s->pb);
 
1443
 
 
1444
    for(;;) {
 
1445
        url_fseek(&s->pb, pos, SEEK_SET);
 
1446
        if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
 
1447
            return -1;
 
1448
//        pid = ((buf[1] & 0x1f) << 8) | buf[2];
 
1449
        if(buf[1] & 0x40) break;
 
1450
        pos += ts->raw_packet_size;
 
1451
    }
 
1452
    url_fseek(&s->pb, pos, SEEK_SET);
 
1453
 
 
1454
    return 0;
 
1455
}
 
1456
 
 
1457
/**************************************************************/
 
1458
/* parsing functions - called from other demuxers such as RTP */
 
1459
 
 
1460
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
 
1461
{
 
1462
    MpegTSContext *ts;
 
1463
 
 
1464
    ts = av_mallocz(sizeof(MpegTSContext));
 
1465
    if (!ts)
 
1466
        return NULL;
 
1467
    /* no stream case, currently used by RTP */
 
1468
    ts->raw_packet_size = TS_PACKET_SIZE;
 
1469
    ts->stream = s;
 
1470
    ts->auto_guess = 1;
 
1471
    return ts;
 
1472
}
 
1473
 
 
1474
/* return the consumed length if a packet was output, or -1 if no
 
1475
   packet is output */
 
1476
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
 
1477
                        const uint8_t *buf, int len)
 
1478
{
 
1479
    int len1;
 
1480
 
 
1481
    len1 = len;
 
1482
    ts->pkt = pkt;
 
1483
    ts->stop_parse = 0;
 
1484
    for(;;) {
 
1485
        if (ts->stop_parse)
 
1486
            break;
 
1487
        if (len < TS_PACKET_SIZE)
 
1488
            return -1;
 
1489
        if (buf[0] != 0x47) {
 
1490
            buf++;
 
1491
            len--;
 
1492
        } else {
 
1493
            handle_packet(ts, buf);
 
1494
            buf += TS_PACKET_SIZE;
 
1495
            len -= TS_PACKET_SIZE;
 
1496
        }
 
1497
    }
 
1498
    return len1 - len;
 
1499
}
 
1500
 
 
1501
void mpegts_parse_close(MpegTSContext *ts)
 
1502
{
 
1503
    int i;
 
1504
 
 
1505
    for(i=0;i<NB_PID_MAX;i++)
 
1506
        av_free(ts->pids[i]);
 
1507
    av_free(ts);
 
1508
}
 
1509
 
 
1510
AVInputFormat mpegts_demux = {
 
1511
    "mpegts",
 
1512
    "MPEG2 transport stream format",
 
1513
    sizeof(MpegTSContext),
 
1514
    mpegts_probe,
 
1515
    mpegts_read_header,
 
1516
    mpegts_read_packet,
 
1517
    mpegts_read_close,
 
1518
    read_seek,
 
1519
    mpegts_get_pcr,
 
1520
    .flags = AVFMT_SHOW_IDS,
 
1521
};
 
1522
 
 
1523
int mpegts_init(void)
 
1524
{
 
1525
    av_register_input_format(&mpegts_demux);
 
1526
#ifdef CONFIG_MUXERS
 
1527
    av_register_output_format(&mpegts_mux);
 
1528
#endif
 
1529
    return 0;
 
1530
}