Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ 9d4edf96

History | View | Annotate | Download (40.8 KB)

1 fe9cf0d4 Fabrice Bellard
/*
2 7fbde343 Aurelien Jacobs
 * MPEG2 transport stream (aka DVB) demuxer
3 5dbafeb7 Fabrice Bellard
 * Copyright (c) 2002-2003 Fabrice Bellard.
4 fe9cf0d4 Fabrice Bellard
 *
5 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 19720f15 Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
11 fe9cf0d4 Fabrice Bellard
 *
12 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
13 fe9cf0d4 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 19720f15 Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16 fe9cf0d4 Fabrice Bellard
 *
17 19720f15 Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
18 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
19 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 fe9cf0d4 Fabrice Bellard
 */
21
#include "avformat.h"
22 43a80cce Michael Niedermayer
#include "crc.h"
23 5dbafeb7 Fabrice Bellard
#include "mpegts.h"
24 38c48be2 Michael Niedermayer
#include "allformats.h"
25 fe9cf0d4 Fabrice Bellard
26 5dbafeb7 Fabrice Bellard
//#define DEBUG_SI
27 27f388aa Fabrice Bellard
//#define DEBUG_SEEK
28 5dbafeb7 Fabrice Bellard
29
/* 1.0 second at 24Mbit/s */
30 fc48fe84 Fabrice Bellard
#define MAX_SCAN_PACKETS 32000
31
32
/* maximum size in which we look for synchronisation if
33
   synchronisation is lost */
34
#define MAX_RESYNC_SIZE 4096
35 5dbafeb7 Fabrice Bellard
36 c6ec28b1 Michael Niedermayer
typedef struct PESContext PESContext;
37
38 dbf6b678 Michael Niedermayer
static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
39 c6ec28b1 Michael Niedermayer
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
40 5dbafeb7 Fabrice Bellard
41
enum MpegTSFilterType {
42
    MPEGTS_PES,
43
    MPEGTS_SECTION,
44 fe9cf0d4 Fabrice Bellard
};
45
46 b474d1f3 Måns Rullgård
typedef struct MpegTSFilter MpegTSFilter;
47
48
typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start);
49 fe9cf0d4 Fabrice Bellard
50 5dbafeb7 Fabrice Bellard
typedef struct MpegTSPESFilter {
51
    PESCallback *pes_cb;
52
    void *opaque;
53
} MpegTSPESFilter;
54
55 b474d1f3 Måns Rullgård
typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
56 5dbafeb7 Fabrice Bellard
57
typedef void SetServiceCallback(void *opaque, int ret);
58
59
typedef struct MpegTSSectionFilter {
60
    int section_index;
61
    int section_h_size;
62
    uint8_t *section_buf;
63
    int check_crc:1;
64
    int end_of_section_reached:1;
65
    SectionCallback *section_cb;
66
    void *opaque;
67
} MpegTSSectionFilter;
68
69 b474d1f3 Måns Rullgård
struct MpegTSFilter {
70 fe9cf0d4 Fabrice Bellard
    int pid;
71
    int last_cc; /* last cc code (-1 if first packet) */
72 5dbafeb7 Fabrice Bellard
    enum MpegTSFilterType type;
73
    union {
74
        MpegTSPESFilter pes_filter;
75
        MpegTSSectionFilter section_filter;
76
    } u;
77 b474d1f3 Måns Rullgård
};
78 5dbafeb7 Fabrice Bellard
79
typedef struct MpegTSService {
80
    int running:1;
81 e995cfca Daniel Kristjansson
    int sid;    /**< MPEG Program Number of stream */
82
    char *provider_name; /**< DVB Network name, "" if not DVB stream */
83
    char *name; /**< DVB Service name, "MPEG Program [sid]" if not DVB stream*/
84 5dbafeb7 Fabrice Bellard
} MpegTSService;
85 fe9cf0d4 Fabrice Bellard
86 b45a7a18 Fabrice Bellard
struct MpegTSContext {
87 5dbafeb7 Fabrice Bellard
    /* user data */
88
    AVFormatContext *stream;
89 e995cfca Daniel Kristjansson
    /** raw packet size, including FEC if present            */
90
    int raw_packet_size;
91
    /** if true, all pids are analyzed to find streams       */
92
    int auto_guess;
93 5dbafeb7 Fabrice Bellard
94 e995cfca Daniel Kristjansson
    /** compute exact PCR for each transport stream packet   */
95
    int mpeg2ts_compute_pcr;
96 b45a7a18 Fabrice Bellard
97 e995cfca Daniel Kristjansson
    int64_t cur_pcr;    /**< used to estimate the exact PCR  */
98
    int pcr_incr;       /**< used to estimate the exact PCR  */
99 115329f1 Diego Biurrun
100 5dbafeb7 Fabrice Bellard
    /* data needed to handle file based ts */
101 e995cfca Daniel Kristjansson
    /** stop parsing loop                                    */
102
    int stop_parse;
103
    /** packet containing Audio/Video data                   */
104
    AVPacket *pkt;
105 5dbafeb7 Fabrice Bellard
106
    /******************************************/
107
    /* private mpegts data */
108
    /* scan context */
109 e995cfca Daniel Kristjansson
    /** number of PMTs in the last PAT seen                  */
110 5dbafeb7 Fabrice Bellard
    int nb_services;
111 e995cfca Daniel Kristjansson
    /** list of PMTs in the last PAT seen                    */
112 5dbafeb7 Fabrice Bellard
    MpegTSService **services;
113 115329f1 Diego Biurrun
114 5dbafeb7 Fabrice Bellard
115 e995cfca Daniel Kristjansson
    /** filters for various streams specified by PMT + for the PAT and PMT */
116 5dbafeb7 Fabrice Bellard
    MpegTSFilter *pids[NB_PID_MAX];
117 b45a7a18 Fabrice Bellard
};
118 fe9cf0d4 Fabrice Bellard
119 ecc31d1d Michael Niedermayer
/* TS stream handling */
120
121
enum MpegTSState {
122
    MPEGTS_HEADER = 0,
123
    MPEGTS_PESHEADER_FILL,
124
    MPEGTS_PAYLOAD,
125
    MPEGTS_SKIP,
126
};
127
128
/* enough for PES header + length */
129
#define PES_START_SIZE 9
130
#define MAX_PES_HEADER_SIZE (9 + 255)
131
132
struct PESContext {
133
    int pid;
134 dbf6b678 Michael Niedermayer
    int pcr_pid; /**< if -1 then all packets containing PCR are considered */
135 ecc31d1d Michael Niedermayer
    int stream_type;
136
    MpegTSContext *ts;
137
    AVFormatContext *stream;
138
    AVStream *st;
139
    enum MpegTSState state;
140
    /* used to get the format */
141
    int data_index;
142
    int total_size;
143
    int pes_header_size;
144
    int64_t pts, dts;
145
    uint8_t header[MAX_PES_HEADER_SIZE];
146
};
147
148 e995cfca Daniel Kristjansson
/**
149
 *  Assembles PES packets out of TS packets, and then calls the "section_cb"
150
 *  function when they are complete.
151
 */
152 5dbafeb7 Fabrice Bellard
static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
153
                               const uint8_t *buf, int buf_size, int is_start)
154
{
155
    MpegTSSectionFilter *tss = &tss1->u.section_filter;
156
    int len;
157 115329f1 Diego Biurrun
158 5dbafeb7 Fabrice Bellard
    if (is_start) {
159
        memcpy(tss->section_buf, buf, buf_size);
160
        tss->section_index = buf_size;
161
        tss->section_h_size = -1;
162
        tss->end_of_section_reached = 0;
163
    } else {
164
        if (tss->end_of_section_reached)
165
            return;
166
        len = 4096 - tss->section_index;
167
        if (buf_size < len)
168
            len = buf_size;
169
        memcpy(tss->section_buf + tss->section_index, buf, len);
170
        tss->section_index += len;
171
    }
172
173
    /* compute section length if possible */
174
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
175 80fb8234 Ronald S. Bultje
        len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
176 5dbafeb7 Fabrice Bellard
        if (len > 4096)
177
            return;
178
        tss->section_h_size = len;
179
    }
180
181
    if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
182
        tss->end_of_section_reached = 1;
183 27bb1ed3 Wolfram Gloger
        if (!tss->check_crc ||
184 43a80cce Michael Niedermayer
            av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
185 4d9a577e Michael Niedermayer
            tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
186 5dbafeb7 Fabrice Bellard
    }
187
}
188
189 7b49ce2e Stefan Huehner
static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
190 5dbafeb7 Fabrice Bellard
                                         SectionCallback *section_cb, void *opaque,
191
                                         int check_crc)
192
193
{
194
    MpegTSFilter *filter;
195
    MpegTSSectionFilter *sec;
196 115329f1 Diego Biurrun
197 b45a7a18 Fabrice Bellard
#ifdef DEBUG_SI
198 f0ee3ea6 Michel Bardiaux
    av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
199 b45a7a18 Fabrice Bellard
#endif
200 5dbafeb7 Fabrice Bellard
    if (pid >= NB_PID_MAX || ts->pids[pid])
201
        return NULL;
202
    filter = av_mallocz(sizeof(MpegTSFilter));
203 115329f1 Diego Biurrun
    if (!filter)
204 5dbafeb7 Fabrice Bellard
        return NULL;
205
    ts->pids[pid] = filter;
206
    filter->type = MPEGTS_SECTION;
207
    filter->pid = pid;
208
    filter->last_cc = -1;
209
    sec = &filter->u.section_filter;
210
    sec->section_cb = section_cb;
211
    sec->opaque = opaque;
212
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
213
    sec->check_crc = check_crc;
214
    if (!sec->section_buf) {
215
        av_free(filter);
216
        return NULL;
217
    }
218
    return filter;
219
}
220
221 7b49ce2e Stefan Huehner
static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
222 5dbafeb7 Fabrice Bellard
                                     PESCallback *pes_cb,
223
                                     void *opaque)
224
{
225
    MpegTSFilter *filter;
226
    MpegTSPESFilter *pes;
227
228
    if (pid >= NB_PID_MAX || ts->pids[pid])
229
        return NULL;
230
    filter = av_mallocz(sizeof(MpegTSFilter));
231 115329f1 Diego Biurrun
    if (!filter)
232 5dbafeb7 Fabrice Bellard
        return NULL;
233
    ts->pids[pid] = filter;
234
    filter->type = MPEGTS_PES;
235
    filter->pid = pid;
236
    filter->last_cc = -1;
237
    pes = &filter->u.pes_filter;
238
    pes->pes_cb = pes_cb;
239
    pes->opaque = opaque;
240
    return filter;
241
}
242
243 7b49ce2e Stefan Huehner
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
244 5dbafeb7 Fabrice Bellard
{
245
    int pid;
246
247
    pid = filter->pid;
248
    if (filter->type == MPEGTS_SECTION)
249
        av_freep(&filter->u.section_filter.section_buf);
250 ec7d0d2e Gildas Bazin
    else if (filter->type == MPEGTS_PES)
251
        av_freep(&filter->u.pes_filter.opaque);
252
253 5dbafeb7 Fabrice Bellard
    av_free(filter);
254
    ts->pids[pid] = NULL;
255
}
256
257 a0b8f70c Michael Niedermayer
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
258
    int stat[packet_size];
259
    int i;
260
    int x=0;
261
    int best_score=0;
262
263
    memset(stat, 0, packet_size*sizeof(int));
264
265
    for(x=i=0; i<size; i++){
266
        if(buf[i] == 0x47){
267
            stat[x]++;
268
            if(stat[x] > best_score){
269
                best_score= stat[x];
270
                if(index) *index= x;
271
            }
272
        }
273
274
        x++;
275
        if(x == packet_size) x= 0;
276
    }
277
278
    return best_score;
279
}
280
281 fe9cf0d4 Fabrice Bellard
/* autodetect fec presence. Must have at least 1024 bytes  */
282 5dbafeb7 Fabrice Bellard
static int get_packet_size(const uint8_t *buf, int size)
283 fe9cf0d4 Fabrice Bellard
{
284 5d4d67e0 Nico Sabbi
    int score, fec_score, dvhs_score;
285 fe9cf0d4 Fabrice Bellard
286
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
287
        return -1;
288 115329f1 Diego Biurrun
289 a0b8f70c Michael Niedermayer
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
290 5d4d67e0 Nico Sabbi
    dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
291 a0b8f70c Michael Niedermayer
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
292 5d4d67e0 Nico Sabbi
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
293 115329f1 Diego Biurrun
294 5d4d67e0 Nico Sabbi
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
295
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
296
    else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
297 a0b8f70c Michael Niedermayer
    else                       return -1;
298 fe9cf0d4 Fabrice Bellard
}
299
300 5dbafeb7 Fabrice Bellard
typedef struct SectionHeader {
301
    uint8_t tid;
302
    uint16_t id;
303
    uint8_t version;
304
    uint8_t sec_num;
305
    uint8_t last_sec_num;
306
} SectionHeader;
307
308
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
309 fe9cf0d4 Fabrice Bellard
{
310 5dbafeb7 Fabrice Bellard
    const uint8_t *p;
311
    int c;
312
313
    p = *pp;
314
    if (p >= p_end)
315
        return -1;
316
    c = *p++;
317
    *pp = p;
318
    return c;
319 fe9cf0d4 Fabrice Bellard
}
320
321 5dbafeb7 Fabrice Bellard
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
322
{
323
    const uint8_t *p;
324
    int c;
325
326
    p = *pp;
327
    if ((p + 1) >= p_end)
328
        return -1;
329 80fb8234 Ronald S. Bultje
    c = AV_RB16(p);
330 5dbafeb7 Fabrice Bellard
    p += 2;
331
    *pp = p;
332
    return c;
333
}
334
335
/* read and allocate a DVB string preceeded by its length */
336
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
337 fe9cf0d4 Fabrice Bellard
{
338
    int len;
339 5dbafeb7 Fabrice Bellard
    const uint8_t *p;
340
    char *str;
341 fe9cf0d4 Fabrice Bellard
342 5dbafeb7 Fabrice Bellard
    p = *pp;
343
    len = get8(&p, p_end);
344
    if (len < 0)
345
        return NULL;
346
    if ((p + len) > p_end)
347
        return NULL;
348
    str = av_malloc(len + 1);
349
    if (!str)
350
        return NULL;
351
    memcpy(str, p, len);
352
    str[len] = '\0';
353
    p += len;
354
    *pp = p;
355
    return str;
356
}
357
358 115329f1 Diego Biurrun
static int parse_section_header(SectionHeader *h,
359 5dbafeb7 Fabrice Bellard
                                const uint8_t **pp, const uint8_t *p_end)
360
{
361
    int val;
362
363
    val = get8(pp, p_end);
364
    if (val < 0)
365
        return -1;
366
    h->tid = val;
367
    *pp += 2;
368
    val = get16(pp, p_end);
369
    if (val < 0)
370
        return -1;
371
    h->id = val;
372
    val = get8(pp, p_end);
373
    if (val < 0)
374
        return -1;
375
    h->version = (val >> 1) & 0x1f;
376
    val = get8(pp, p_end);
377
    if (val < 0)
378
        return -1;
379
    h->sec_num = val;
380
    val = get8(pp, p_end);
381
    if (val < 0)
382
        return -1;
383
    h->last_sec_num = val;
384 fe9cf0d4 Fabrice Bellard
    return 0;
385 5dbafeb7 Fabrice Bellard
}
386
387 115329f1 Diego Biurrun
static MpegTSService *new_service(MpegTSContext *ts, int sid,
388 5dbafeb7 Fabrice Bellard
                                  char *provider_name, char *name)
389
{
390 657ced8c Michael Niedermayer
    MpegTSService *service=NULL;
391
    int i;
392 5dbafeb7 Fabrice Bellard
393
#ifdef DEBUG_SI
394 f0ee3ea6 Michel Bardiaux
    av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
395 2ddb79be Daniel Kristjansson
           "sid=0x%04x provider='%s' name='%s'\n",
396 5dbafeb7 Fabrice Bellard
           sid, provider_name, name);
397
#endif
398
399 657ced8c Michael Niedermayer
    for(i=0; i<ts->nb_services; i++)
400
        if(ts->services[i]->sid == sid)
401
            service= ts->services[i];
402
403
    if(!service){
404
        service = av_mallocz(sizeof(MpegTSService));
405
        if (!service)
406
            return NULL;
407
        dynarray_add(&ts->services, &ts->nb_services, service);
408
    }
409 5dbafeb7 Fabrice Bellard
    service->sid = sid;
410 657ced8c Michael Niedermayer
    assert((!provider_name) == (!name));
411
    if(name){
412
        av_free(service->provider_name);
413
        av_free(service->         name);
414
        service->provider_name = provider_name;
415
        service->         name =          name;
416
    }
417 5dbafeb7 Fabrice Bellard
    return service;
418
}
419
420 4d9a577e Michael Niedermayer
static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
421 5dbafeb7 Fabrice Bellard
{
422 4d9a577e Michael Niedermayer
    MpegTSContext *ts = filter->u.section_filter.opaque;
423 5dbafeb7 Fabrice Bellard
    SectionHeader h1, *h = &h1;
424 c6ec28b1 Michael Niedermayer
    PESContext *pes;
425
    AVStream *st;
426
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
427
    int program_info_length, pcr_pid, pid, stream_type;
428
    int desc_list_len, desc_len, desc_tag;
429 79396ac6 Måns Rullgård
    int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
430 828bb5f1 Glenn A. Serre
    char language[4] = {0}; /* initialize to kill warnings */
431 115329f1 Diego Biurrun
432 5dbafeb7 Fabrice Bellard
#ifdef DEBUG_SI
433 f0ee3ea6 Michel Bardiaux
    av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
434 750f0e1f Panagiotis Issaris
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
435 5dbafeb7 Fabrice Bellard
#endif
436
    p_end = section + section_len - 4;
437
    p = section;
438
    if (parse_section_header(h, &p, p_end) < 0)
439
        return;
440
#ifdef DEBUG_SI
441 f0ee3ea6 Michel Bardiaux
    av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
442 2ddb79be Daniel Kristjansson
           h->id, h->sec_num, h->last_sec_num);
443 5dbafeb7 Fabrice Bellard
#endif
444 90d13e30 Michael Niedermayer
    if (h->tid != PMT_TID)
445 5dbafeb7 Fabrice Bellard
        return;
446
447
    pcr_pid = get16(&p, p_end) & 0x1fff;
448
    if (pcr_pid < 0)
449
        return;
450
#ifdef DEBUG_SI
451 f0ee3ea6 Michel Bardiaux
    av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
452 5dbafeb7 Fabrice Bellard
#endif
453
    program_info_length = get16(&p, p_end) & 0xfff;
454
    if (program_info_length < 0)
455
        return;
456
    p += program_info_length;
457
    if (p >= p_end)
458
        return;
459
    for(;;) {
460 c6ec28b1 Michael Niedermayer
        language[0] = 0;
461
        st = 0;
462 5dbafeb7 Fabrice Bellard
        stream_type = get8(&p, p_end);
463
        if (stream_type < 0)
464
            break;
465
        pid = get16(&p, p_end) & 0x1fff;
466
        if (pid < 0)
467
            break;
468 c6ec28b1 Michael Niedermayer
        desc_list_len = get16(&p, p_end) & 0xfff;
469
        if (desc_list_len < 0)
470
            break;
471
        desc_list_end = p + desc_list_len;
472
        if (desc_list_end > p_end)
473 5dbafeb7 Fabrice Bellard
            break;
474 c6ec28b1 Michael Niedermayer
        for(;;) {
475
            desc_tag = get8(&p, desc_list_end);
476
            if (desc_tag < 0)
477
                break;
478 2eb1a65d Nico Sabbi
            if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
479
                if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
480 9d9b432a Måns Rullgård
                    /*assume DVB AC-3 Audio*/
481
                    stream_type = STREAM_TYPE_AUDIO_AC3;
482 2eb1a65d Nico Sabbi
                } else if(desc_tag == 0x7B) {
483
                    /* DVB DTS audio */
484
                    stream_type = STREAM_TYPE_AUDIO_DTS;
485
                }
486 9d9b432a Måns Rullgård
            }
487 c6ec28b1 Michael Niedermayer
            desc_len = get8(&p, desc_list_end);
488
            desc_end = p + desc_len;
489
            if (desc_end > desc_list_end)
490
                break;
491
#ifdef DEBUG_SI
492 f0ee3ea6 Michel Bardiaux
            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
493 2ddb79be Daniel Kristjansson
                   desc_tag, desc_len);
494 c6ec28b1 Michael Niedermayer
#endif
495
            switch(desc_tag) {
496
            case DVB_SUBT_DESCID:
497
                if (stream_type == STREAM_TYPE_PRIVATE_DATA)
498
                    stream_type = STREAM_TYPE_SUBTITLE_DVB;
499
500
                language[0] = get8(&p, desc_end);
501
                language[1] = get8(&p, desc_end);
502
                language[2] = get8(&p, desc_end);
503
                language[3] = 0;
504
                get8(&p, desc_end);
505
                comp_page = get16(&p, desc_end);
506
                anc_page = get16(&p, desc_end);
507
508
                break;
509
            case 0x0a: /* ISO 639 language descriptor */
510
                language[0] = get8(&p, desc_end);
511
                language[1] = get8(&p, desc_end);
512
                language[2] = get8(&p, desc_end);
513
                language[3] = 0;
514
                break;
515
            default:
516
                break;
517
            }
518
            p = desc_end;
519
        }
520
        p = desc_list_end;
521 5dbafeb7 Fabrice Bellard
522
#ifdef DEBUG_SI
523 f0ee3ea6 Michel Bardiaux
        av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
524 2ddb79be Daniel Kristjansson
               stream_type, pid);
525 5dbafeb7 Fabrice Bellard
#endif
526
527
        /* now create ffmpeg stream */
528
        switch(stream_type) {
529 ce34182d Michael Niedermayer
        case STREAM_TYPE_AUDIO_MPEG1:
530
        case STREAM_TYPE_AUDIO_MPEG2:
531
        case STREAM_TYPE_VIDEO_MPEG1:
532
        case STREAM_TYPE_VIDEO_MPEG2:
533 278de475 Måns Rullgård
        case STREAM_TYPE_VIDEO_MPEG4:
534
        case STREAM_TYPE_VIDEO_H264:
535 cf10ee18 Nico Sabbi
        case STREAM_TYPE_VIDEO_VC1:
536 278de475 Måns Rullgård
        case STREAM_TYPE_AUDIO_AAC:
537 ec23a472 Isaac Richards
        case STREAM_TYPE_AUDIO_AC3:
538 23c99253 Michael Niedermayer
        case STREAM_TYPE_AUDIO_DTS:
539 c6ec28b1 Michael Niedermayer
        case STREAM_TYPE_SUBTITLE_DVB:
540 90d13e30 Michael Niedermayer
            if(ts->pids[pid]){
541 5b83843f Alex Beregszaszi
                assert(ts->pids[pid]->type == MPEGTS_PES);
542 90d13e30 Michael Niedermayer
                pes= ts->pids[pid]->u.pes_filter.opaque;
543
                st= pes->st;
544
            }else{
545 dbf6b678 Michael Niedermayer
                pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
546 28f03d04 Michael Niedermayer
                if (pes)
547
                    st = new_pes_av_stream(pes, 0);
548 90d13e30 Michael Niedermayer
            }
549 04ec18b8 Michael Niedermayer
            break;
550 5dbafeb7 Fabrice Bellard
        default:
551
            /* we ignore the other streams */
552
            break;
553
        }
554 c6ec28b1 Michael Niedermayer
555
        if (st) {
556
            if (language[0] != 0) {
557 b3e10436 Michael Niedermayer
                memcpy(st->language, language, 4);
558 c6ec28b1 Michael Niedermayer
            }
559
560
            if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
561 01f4895c Michael Niedermayer
                st->codec->sub_id = (anc_page << 16) | comp_page;
562 c6ec28b1 Michael Niedermayer
            }
563
        }
564 5dbafeb7 Fabrice Bellard
    }
565
    /* all parameters are there */
566 90d13e30 Michael Niedermayer
    ts->stop_parse++;
567 4d9a577e Michael Niedermayer
    mpegts_close_filter(ts, filter);
568 5dbafeb7 Fabrice Bellard
}
569
570 4d9a577e Michael Niedermayer
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
571 5dbafeb7 Fabrice Bellard
{
572 4d9a577e Michael Niedermayer
    MpegTSContext *ts = filter->u.section_filter.opaque;
573 5dbafeb7 Fabrice Bellard
    SectionHeader h1, *h = &h1;
574
    const uint8_t *p, *p_end;
575
    int sid, pmt_pid;
576
577
#ifdef DEBUG_SI
578 f0ee3ea6 Michel Bardiaux
    av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
579 750f0e1f Panagiotis Issaris
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
580 5dbafeb7 Fabrice Bellard
#endif
581
    p_end = section + section_len - 4;
582
    p = section;
583
    if (parse_section_header(h, &p, p_end) < 0)
584
        return;
585
    if (h->tid != PAT_TID)
586
        return;
587
588
    for(;;) {
589
        sid = get16(&p, p_end);
590
        if (sid < 0)
591
            break;
592
        pmt_pid = get16(&p, p_end) & 0x1fff;
593
        if (pmt_pid < 0)
594
            break;
595
#ifdef DEBUG_SI
596 f0ee3ea6 Michel Bardiaux
        av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
597 5dbafeb7 Fabrice Bellard
#endif
598
        if (sid == 0x0000) {
599
            /* NIT info */
600
        } else {
601 ad39abcd Michael Niedermayer
            new_service(ts, sid, NULL, NULL);
602 90d13e30 Michael Niedermayer
            ts->stop_parse--;
603 28f03d04 Michael Niedermayer
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
604 5dbafeb7 Fabrice Bellard
        }
605
    }
606
    /* not found */
607 90d13e30 Michael Niedermayer
    ts->stop_parse++;
608 5dbafeb7 Fabrice Bellard
609 4d9a577e Michael Niedermayer
    mpegts_close_filter(ts, filter);
610 5dbafeb7 Fabrice Bellard
}
611
612 90d13e30 Michael Niedermayer
static void mpegts_set_service(MpegTSContext *ts)
613 5dbafeb7 Fabrice Bellard
{
614 4d9a577e Michael Niedermayer
    mpegts_open_section_filter(ts, PAT_PID,
615 5dbafeb7 Fabrice Bellard
                                                pat_cb, ts, 1);
616
}
617
618 4d9a577e Michael Niedermayer
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
619 5dbafeb7 Fabrice Bellard
{
620 4d9a577e Michael Niedermayer
    MpegTSContext *ts = filter->u.section_filter.opaque;
621 5dbafeb7 Fabrice Bellard
    SectionHeader h1, *h = &h1;
622
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
623
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
624
    char *name, *provider_name;
625
626
#ifdef DEBUG_SI
627 f0ee3ea6 Michel Bardiaux
    av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
628 750f0e1f Panagiotis Issaris
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
629 5dbafeb7 Fabrice Bellard
#endif
630
631
    p_end = section + section_len - 4;
632
    p = section;
633
    if (parse_section_header(h, &p, p_end) < 0)
634
        return;
635
    if (h->tid != SDT_TID)
636
        return;
637
    onid = get16(&p, p_end);
638
    if (onid < 0)
639
        return;
640
    val = get8(&p, p_end);
641
    if (val < 0)
642
        return;
643
    for(;;) {
644
        sid = get16(&p, p_end);
645
        if (sid < 0)
646
            break;
647
        val = get8(&p, p_end);
648
        if (val < 0)
649
            break;
650
        desc_list_len = get16(&p, p_end) & 0xfff;
651
        if (desc_list_len < 0)
652
            break;
653
        desc_list_end = p + desc_list_len;
654
        if (desc_list_end > p_end)
655
            break;
656
        for(;;) {
657
            desc_tag = get8(&p, desc_list_end);
658
            if (desc_tag < 0)
659
                break;
660
            desc_len = get8(&p, desc_list_end);
661
            desc_end = p + desc_len;
662
            if (desc_end > desc_list_end)
663
                break;
664
#ifdef DEBUG_SI
665 f0ee3ea6 Michel Bardiaux
            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
666 2ddb79be Daniel Kristjansson
                   desc_tag, desc_len);
667 5dbafeb7 Fabrice Bellard
#endif
668
            switch(desc_tag) {
669
            case 0x48:
670
                service_type = get8(&p, p_end);
671
                if (service_type < 0)
672
                    break;
673
                provider_name = getstr8(&p, p_end);
674
                if (!provider_name)
675
                    break;
676
                name = getstr8(&p, p_end);
677
                if (!name)
678
                    break;
679
                new_service(ts, sid, provider_name, name);
680
                break;
681
            default:
682
                break;
683
            }
684
            p = desc_end;
685
        }
686
        p = desc_list_end;
687
    }
688
}
689
690 fc48fe84 Fabrice Bellard
/* scan services in a transport stream by looking at the SDT */
691 7b49ce2e Stefan Huehner
static void mpegts_scan_sdt(MpegTSContext *ts)
692 5dbafeb7 Fabrice Bellard
{
693 37dfd633 Michael Niedermayer
    mpegts_open_section_filter(ts, SDT_PID,
694 5dbafeb7 Fabrice Bellard
                                                sdt_cb, ts, 1);
695
}
696
697
static int64_t get_pts(const uint8_t *p)
698
{
699 80fb8234 Ronald S. Bultje
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
700
    pts |= (AV_RB16(p + 1) >> 1) << 15;
701
    pts |=  AV_RB16(p + 3) >> 1;
702 5dbafeb7 Fabrice Bellard
    return pts;
703 fe9cf0d4 Fabrice Bellard
}
704
705
/* return non zero if a packet could be constructed */
706 4d9a577e Michael Niedermayer
static void mpegts_push_data(MpegTSFilter *filter,
707 5dbafeb7 Fabrice Bellard
                             const uint8_t *buf, int buf_size, int is_start)
708 fe9cf0d4 Fabrice Bellard
{
709 4d9a577e Michael Niedermayer
    PESContext *pes = filter->u.pes_filter.opaque;
710 b45a7a18 Fabrice Bellard
    MpegTSContext *ts = pes->ts;
711 5dbafeb7 Fabrice Bellard
    const uint8_t *p;
712 c6ec28b1 Michael Niedermayer
    int len, code;
713 115329f1 Diego Biurrun
714 b2292194 Michael Niedermayer
    if(!ts->pkt)
715
        return;
716
717 fe9cf0d4 Fabrice Bellard
    if (is_start) {
718 5dbafeb7 Fabrice Bellard
        pes->state = MPEGTS_HEADER;
719
        pes->data_index = 0;
720 fe9cf0d4 Fabrice Bellard
    }
721
    p = buf;
722
    while (buf_size > 0) {
723 5dbafeb7 Fabrice Bellard
        switch(pes->state) {
724 fe9cf0d4 Fabrice Bellard
        case MPEGTS_HEADER:
725 5dbafeb7 Fabrice Bellard
            len = PES_START_SIZE - pes->data_index;
726
            if (len > buf_size)
727
                len = buf_size;
728
            memcpy(pes->header + pes->data_index, p, len);
729
            pes->data_index += len;
730 fe9cf0d4 Fabrice Bellard
            p += len;
731
            buf_size -= len;
732 5dbafeb7 Fabrice Bellard
            if (pes->data_index == PES_START_SIZE) {
733 fe9cf0d4 Fabrice Bellard
                /* we got all the PES or section header. We can now
734
                   decide */
735
#if 0
736 750f0e1f Panagiotis Issaris
                av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
737 fe9cf0d4 Fabrice Bellard
#endif
738 5dbafeb7 Fabrice Bellard
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
739
                    pes->header[2] == 0x01) {
740 fe9cf0d4 Fabrice Bellard
                    /* it must be an mpeg2 PES stream */
741 5dbafeb7 Fabrice Bellard
                    code = pes->header[3] | 0x100;
742 fe9cf0d4 Fabrice Bellard
                    if (!((code >= 0x1c0 && code <= 0x1df) ||
743 ec23a472 Isaac Richards
                          (code >= 0x1e0 && code <= 0x1ef) ||
744 cf10ee18 Nico Sabbi
                          (code == 0x1bd) || (code == 0x1fd)))
745 fe9cf0d4 Fabrice Bellard
                        goto skip;
746 5dbafeb7 Fabrice Bellard
                    if (!pes->st) {
747 fe9cf0d4 Fabrice Bellard
                        /* allocate stream */
748 c6ec28b1 Michael Niedermayer
                        new_pes_av_stream(pes, code);
749 fe9cf0d4 Fabrice Bellard
                    }
750 5dbafeb7 Fabrice Bellard
                    pes->state = MPEGTS_PESHEADER_FILL;
751 80fb8234 Ronald S. Bultje
                    pes->total_size = AV_RB16(pes->header + 4);
752 5dbafeb7 Fabrice Bellard
                    /* NOTE: a zero total size means the PES size is
753
                       unbounded */
754
                    if (pes->total_size)
755
                        pes->total_size += 6;
756
                    pes->pes_header_size = pes->header[8] + 9;
757 fe9cf0d4 Fabrice Bellard
                } else {
758
                    /* otherwise, it should be a table */
759
                    /* skip packet */
760
                skip:
761 5dbafeb7 Fabrice Bellard
                    pes->state = MPEGTS_SKIP;
762 fe9cf0d4 Fabrice Bellard
                    continue;
763
                }
764
            }
765
            break;
766
            /**********************************************/
767
            /* PES packing parsing */
768
        case MPEGTS_PESHEADER_FILL:
769 5dbafeb7 Fabrice Bellard
            len = pes->pes_header_size - pes->data_index;
770
            if (len > buf_size)
771
                len = buf_size;
772
            memcpy(pes->header + pes->data_index, p, len);
773
            pes->data_index += len;
774 fe9cf0d4 Fabrice Bellard
            p += len;
775
            buf_size -= len;
776 5dbafeb7 Fabrice Bellard
            if (pes->data_index == pes->pes_header_size) {
777
                const uint8_t *r;
778
                unsigned int flags;
779
780
                flags = pes->header[7];
781
                r = pes->header + 9;
782
                pes->pts = AV_NOPTS_VALUE;
783
                pes->dts = AV_NOPTS_VALUE;
784
                if ((flags & 0xc0) == 0x80) {
785
                    pes->pts = get_pts(r);
786
                    r += 5;
787
                } else if ((flags & 0xc0) == 0xc0) {
788
                    pes->pts = get_pts(r);
789
                    r += 5;
790
                    pes->dts = get_pts(r);
791
                    r += 5;
792
                }
793
                /* we got the full header. We parse it and get the payload */
794
                pes->state = MPEGTS_PAYLOAD;
795
            }
796 fe9cf0d4 Fabrice Bellard
            break;
797
        case MPEGTS_PAYLOAD:
798 5dbafeb7 Fabrice Bellard
            if (pes->total_size) {
799
                len = pes->total_size - pes->data_index;
800
                if (len > buf_size)
801
                    len = buf_size;
802
            } else {
803
                len = buf_size;
804
            }
805 fe9cf0d4 Fabrice Bellard
            if (len > 0) {
806 5dbafeb7 Fabrice Bellard
                AVPacket *pkt = ts->pkt;
807
                if (pes->st && av_new_packet(pkt, len) == 0) {
808
                    memcpy(pkt->data, p, len);
809
                    pkt->stream_index = pes->st->index;
810
                    pkt->pts = pes->pts;
811 2092bd75 Gildas Bazin
                    pkt->dts = pes->dts;
812 5dbafeb7 Fabrice Bellard
                    /* reset pts values */
813
                    pes->pts = AV_NOPTS_VALUE;
814
                    pes->dts = AV_NOPTS_VALUE;
815
                    ts->stop_parse = 1;
816
                    return;
817 fe9cf0d4 Fabrice Bellard
                }
818
            }
819
            buf_size = 0;
820
            break;
821
        case MPEGTS_SKIP:
822
            buf_size = 0;
823
            break;
824
        }
825
    }
826 5dbafeb7 Fabrice Bellard
}
827
828 c6ec28b1 Michael Niedermayer
static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
829
{
830
    AVStream *st;
831
    int codec_type, codec_id;
832
833
    switch(pes->stream_type){
834
    case STREAM_TYPE_AUDIO_MPEG1:
835
    case STREAM_TYPE_AUDIO_MPEG2:
836
        codec_type = CODEC_TYPE_AUDIO;
837
        codec_id = CODEC_ID_MP3;
838
        break;
839
    case STREAM_TYPE_VIDEO_MPEG1:
840
    case STREAM_TYPE_VIDEO_MPEG2:
841
        codec_type = CODEC_TYPE_VIDEO;
842
        codec_id = CODEC_ID_MPEG2VIDEO;
843
        break;
844
    case STREAM_TYPE_VIDEO_MPEG4:
845
        codec_type = CODEC_TYPE_VIDEO;
846
        codec_id = CODEC_ID_MPEG4;
847
        break;
848
    case STREAM_TYPE_VIDEO_H264:
849
        codec_type = CODEC_TYPE_VIDEO;
850
        codec_id = CODEC_ID_H264;
851
        break;
852 cf10ee18 Nico Sabbi
    case STREAM_TYPE_VIDEO_VC1:
853
        codec_type = CODEC_TYPE_VIDEO;
854
        codec_id = CODEC_ID_VC1;
855
        break;
856 c6ec28b1 Michael Niedermayer
    case STREAM_TYPE_AUDIO_AAC:
857
        codec_type = CODEC_TYPE_AUDIO;
858
        codec_id = CODEC_ID_AAC;
859
        break;
860
    case STREAM_TYPE_AUDIO_AC3:
861
        codec_type = CODEC_TYPE_AUDIO;
862
        codec_id = CODEC_ID_AC3;
863
        break;
864
    case STREAM_TYPE_AUDIO_DTS:
865
        codec_type = CODEC_TYPE_AUDIO;
866
        codec_id = CODEC_ID_DTS;
867
        break;
868
    case STREAM_TYPE_SUBTITLE_DVB:
869
        codec_type = CODEC_TYPE_SUBTITLE;
870
        codec_id = CODEC_ID_DVB_SUBTITLE;
871
        break;
872
    default:
873
        if (code >= 0x1c0 && code <= 0x1df) {
874
            codec_type = CODEC_TYPE_AUDIO;
875
            codec_id = CODEC_ID_MP2;
876
        } else if (code == 0x1bd) {
877
            codec_type = CODEC_TYPE_AUDIO;
878
            codec_id = CODEC_ID_AC3;
879
        } else {
880
            codec_type = CODEC_TYPE_VIDEO;
881
            codec_id = CODEC_ID_MPEG1VIDEO;
882
        }
883
        break;
884
    }
885
    st = av_new_stream(pes->stream, pes->pid);
886
    if (st) {
887
        av_set_pts_info(st, 33, 1, 90000);
888
        st->priv_data = pes;
889 01f4895c Michael Niedermayer
        st->codec->codec_type = codec_type;
890
        st->codec->codec_id = codec_id;
891 57004ff1 Aurelien Jacobs
        st->need_parsing = AVSTREAM_PARSE_FULL;
892 c6ec28b1 Michael Niedermayer
        pes->st = st;
893
    }
894
    return st;
895
}
896
897
898 dbf6b678 Michael Niedermayer
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
899 5dbafeb7 Fabrice Bellard
{
900
    MpegTSFilter *tss;
901
    PESContext *pes;
902
903
    /* if no pid found, then add a pid context */
904
    pes = av_mallocz(sizeof(PESContext));
905
    if (!pes)
906 c6ec28b1 Michael Niedermayer
        return 0;
907 b45a7a18 Fabrice Bellard
    pes->ts = ts;
908
    pes->stream = ts->stream;
909 5dbafeb7 Fabrice Bellard
    pes->pid = pid;
910 dbf6b678 Michael Niedermayer
    pes->pcr_pid = pcr_pid;
911 278de475 Måns Rullgård
    pes->stream_type = stream_type;
912 5dbafeb7 Fabrice Bellard
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
913
    if (!tss) {
914
        av_free(pes);
915 c6ec28b1 Michael Niedermayer
        return 0;
916 5dbafeb7 Fabrice Bellard
    }
917 c6ec28b1 Michael Niedermayer
    return pes;
918 fe9cf0d4 Fabrice Bellard
}
919
920 5dbafeb7 Fabrice Bellard
/* handle one TS packet */
921 b45a7a18 Fabrice Bellard
static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
922 fe9cf0d4 Fabrice Bellard
{
923 b45a7a18 Fabrice Bellard
    AVFormatContext *s = ts->stream;
924 5dbafeb7 Fabrice Bellard
    MpegTSFilter *tss;
925
    int len, pid, cc, cc_ok, afc, is_start;
926
    const uint8_t *p, *p_end;
927
928 80fb8234 Ronald S. Bultje
    pid = AV_RB16(packet + 1) & 0x1fff;
929 5dbafeb7 Fabrice Bellard
    is_start = packet[1] & 0x40;
930
    tss = ts->pids[pid];
931
    if (ts->auto_guess && tss == NULL && is_start) {
932 dbf6b678 Michael Niedermayer
        add_pes_stream(ts, pid, -1, 0);
933 5dbafeb7 Fabrice Bellard
        tss = ts->pids[pid];
934
    }
935
    if (!tss)
936
        return;
937
938
    /* continuity check (currently not used) */
939
    cc = (packet[3] & 0xf);
940
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
941
    tss->last_cc = cc;
942 115329f1 Diego Biurrun
943 5dbafeb7 Fabrice Bellard
    /* skip adaptation field */
944
    afc = (packet[3] >> 4) & 3;
945
    p = packet + 4;
946
    if (afc == 0) /* reserved value */
947
        return;
948
    if (afc == 2) /* adaptation field only */
949
        return;
950
    if (afc == 3) {
951
        /* skip adapation field */
952
        p += p[0] + 1;
953
    }
954
    /* if past the end of packet, ignore */
955
    p_end = packet + TS_PACKET_SIZE;
956
    if (p >= p_end)
957
        return;
958 115329f1 Diego Biurrun
959 5dbafeb7 Fabrice Bellard
    if (tss->type == MPEGTS_SECTION) {
960
        if (is_start) {
961
            /* pointer field present */
962
            len = *p++;
963
            if (p + len > p_end)
964
                return;
965
            if (len && cc_ok) {
966 27bb1ed3 Wolfram Gloger
                /* write remaining section bytes */
967 115329f1 Diego Biurrun
                write_section_data(s, tss,
968 5dbafeb7 Fabrice Bellard
                                   p, len, 0);
969 27bb1ed3 Wolfram Gloger
                /* check whether filter has been closed */
970
                if (!ts->pids[pid])
971
                    return;
972 5dbafeb7 Fabrice Bellard
            }
973
            p += len;
974
            if (p < p_end) {
975 115329f1 Diego Biurrun
                write_section_data(s, tss,
976 5dbafeb7 Fabrice Bellard
                                   p, p_end - p, 1);
977
            }
978
        } else {
979
            if (cc_ok) {
980 115329f1 Diego Biurrun
                write_section_data(s, tss,
981 5dbafeb7 Fabrice Bellard
                                   p, p_end - p, 0);
982 fc48fe84 Fabrice Bellard
            }
983 5dbafeb7 Fabrice Bellard
        }
984
    } else {
985 4d9a577e Michael Niedermayer
        tss->u.pes_filter.pes_cb(tss,
986 5dbafeb7 Fabrice Bellard
                                 p, p_end - p, is_start);
987
    }
988
}
989
990 fc48fe84 Fabrice Bellard
/* XXX: try to find a better synchro over several packets (use
991
   get_packet_size() ?) */
992 b45a7a18 Fabrice Bellard
static int mpegts_resync(ByteIOContext *pb)
993 fc48fe84 Fabrice Bellard
{
994
    int c, i;
995
996
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
997
        c = url_fgetc(pb);
998
        if (c < 0)
999
            return -1;
1000
        if (c == 0x47) {
1001
            url_fseek(pb, -1, SEEK_CUR);
1002
            return 0;
1003
        }
1004
    }
1005
    /* no sync found */
1006
    return -1;
1007
}
1008
1009 b45a7a18 Fabrice Bellard
/* return -1 if error or EOF. Return 0 if OK. */
1010
static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1011 5dbafeb7 Fabrice Bellard
{
1012 b45a7a18 Fabrice Bellard
    int skip, len;
1013
1014
    for(;;) {
1015
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1016
        if (len != TS_PACKET_SIZE)
1017 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
1018 b45a7a18 Fabrice Bellard
        /* check paquet sync byte */
1019
        if (buf[0] != 0x47) {
1020
            /* find a new packet start */
1021
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1022
            if (mpegts_resync(pb) < 0)
1023
                return AVERROR_INVALIDDATA;
1024
            else
1025
                continue;
1026
        } else {
1027
            skip = raw_packet_size - TS_PACKET_SIZE;
1028
            if (skip > 0)
1029
                url_fskip(pb, skip);
1030
            break;
1031
        }
1032
    }
1033
    return 0;
1034
}
1035
1036
static int handle_packets(MpegTSContext *ts, int nb_packets)
1037
{
1038
    AVFormatContext *s = ts->stream;
1039 5dbafeb7 Fabrice Bellard
    ByteIOContext *pb = &s->pb;
1040 b45a7a18 Fabrice Bellard
    uint8_t packet[TS_PACKET_SIZE];
1041
    int packet_num, ret;
1042 5dbafeb7 Fabrice Bellard
1043
    ts->stop_parse = 0;
1044
    packet_num = 0;
1045 fe9cf0d4 Fabrice Bellard
    for(;;) {
1046 90d13e30 Michael Niedermayer
        if (ts->stop_parse>0)
1047 5dbafeb7 Fabrice Bellard
            break;
1048
        packet_num++;
1049
        if (nb_packets != 0 && packet_num >= nb_packets)
1050
            break;
1051 b45a7a18 Fabrice Bellard
        ret = read_packet(pb, packet, ts->raw_packet_size);
1052
        if (ret != 0)
1053
            return ret;
1054
        handle_packet(ts, packet);
1055 5dbafeb7 Fabrice Bellard
    }
1056
    return 0;
1057
}
1058 fe9cf0d4 Fabrice Bellard
1059 5dbafeb7 Fabrice Bellard
static int mpegts_probe(AVProbeData *p)
1060
{
1061 fc48fe84 Fabrice Bellard
#if 1
1062 a0b8f70c Michael Niedermayer
    const int size= p->buf_size;
1063 5d4d67e0 Nico Sabbi
    int score, fec_score, dvhs_score;
1064 a0b8f70c Michael Niedermayer
#define CHECK_COUNT 10
1065 115329f1 Diego Biurrun
1066 a0b8f70c Michael Niedermayer
    if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1067
        return -1;
1068 115329f1 Diego Biurrun
1069 a0b8f70c Michael Niedermayer
    score    = analyze(p->buf, TS_PACKET_SIZE    *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1070 5d4d67e0 Nico Sabbi
    dvhs_score  = analyze(p->buf, TS_DVHS_PACKET_SIZE    *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1071 a0b8f70c Michael Niedermayer
    fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1072 5d4d67e0 Nico Sabbi
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1073 115329f1 Diego Biurrun
1074 a0b8f70c Michael Niedermayer
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1075 5d4d67e0 Nico Sabbi
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1076
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1077 a0b8f70c Michael Niedermayer
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1078
    else                                    return -1;
1079 fc48fe84 Fabrice Bellard
#else
1080
    /* only use the extension for safer guess */
1081
    if (match_ext(p->filename, "ts"))
1082
        return AVPROBE_SCORE_MAX;
1083
    else
1084
        return 0;
1085
#endif
1086 5dbafeb7 Fabrice Bellard
}
1087
1088 b45a7a18 Fabrice Bellard
/* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1089
   (-1) if not available */
1090 115329f1 Diego Biurrun
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1091 b45a7a18 Fabrice Bellard
                     const uint8_t *packet)
1092
{
1093
    int afc, len, flags;
1094
    const uint8_t *p;
1095
    unsigned int v;
1096
1097
    afc = (packet[3] >> 4) & 3;
1098
    if (afc <= 1)
1099
        return -1;
1100
    p = packet + 4;
1101
    len = p[0];
1102
    p++;
1103
    if (len == 0)
1104
        return -1;
1105
    flags = *p++;
1106
    len--;
1107
    if (!(flags & 0x10))
1108
        return -1;
1109
    if (len < 6)
1110
        return -1;
1111 80fb8234 Ronald S. Bultje
    v = AV_RB32(p);
1112 b45a7a18 Fabrice Bellard
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1113
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1114
    return 0;
1115
}
1116
1117 5dbafeb7 Fabrice Bellard
static int mpegts_read_header(AVFormatContext *s,
1118
                              AVFormatParameters *ap)
1119
{
1120
    MpegTSContext *ts = s->priv_data;
1121
    ByteIOContext *pb = &s->pb;
1122
    uint8_t buf[1024];
1123 4dc8a963 Michael Niedermayer
    int len;
1124 5dbafeb7 Fabrice Bellard
    int64_t pos;
1125 e05655fb Michael Niedermayer
1126 b45a7a18 Fabrice Bellard
    if (ap) {
1127
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1128 38c48be2 Michael Niedermayer
        if(ap->mpeg2ts_raw){
1129
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1130
            return -1;
1131
        }
1132 b45a7a18 Fabrice Bellard
    }
1133
1134 5dbafeb7 Fabrice Bellard
    /* read the first 1024 bytes to get packet size */
1135
    pos = url_ftell(pb);
1136
    len = get_buffer(pb, buf, sizeof(buf));
1137
    if (len != sizeof(buf))
1138
        goto fail;
1139
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1140
    if (ts->raw_packet_size <= 0)
1141
        goto fail;
1142 b45a7a18 Fabrice Bellard
    ts->stream = s;
1143 5dbafeb7 Fabrice Bellard
    ts->auto_guess = 0;
1144
1145 38c48be2 Michael Niedermayer
    if (s->iformat == &mpegts_demuxer) {
1146 b45a7a18 Fabrice Bellard
        /* normal demux */
1147 fc48fe84 Fabrice Bellard
1148 a45ec414 Benoit Fouet
        /* first do a scaning to get all the services */
1149
        url_fseek(pb, pos, SEEK_SET);
1150
        mpegts_scan_sdt(ts);
1151 115329f1 Diego Biurrun
1152 28f03d04 Michael Niedermayer
        mpegts_set_service(ts);
1153 115329f1 Diego Biurrun
1154 28f03d04 Michael Niedermayer
        handle_packets(ts, s->probesize);
1155 a45ec414 Benoit Fouet
        /* if could not find service, enable auto_guess */
1156 115329f1 Diego Biurrun
1157 a45ec414 Benoit Fouet
        ts->auto_guess = 1;
1158 115329f1 Diego Biurrun
1159 b45a7a18 Fabrice Bellard
#ifdef DEBUG_SI
1160 a45ec414 Benoit Fouet
        av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1161 b45a7a18 Fabrice Bellard
#endif
1162
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1163
    } else {
1164
        AVStream *st;
1165
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1166
        int64_t pcrs[2], pcr_h;
1167
        int packet_count[2];
1168
        uint8_t packet[TS_PACKET_SIZE];
1169 115329f1 Diego Biurrun
1170 b45a7a18 Fabrice Bellard
        /* only read packets */
1171 115329f1 Diego Biurrun
1172 b45a7a18 Fabrice Bellard
        st = av_new_stream(s, 0);
1173
        if (!st)
1174
            goto fail;
1175 9ee91c2f Michael Niedermayer
        av_set_pts_info(st, 60, 1, 27000000);
1176 01f4895c Michael Niedermayer
        st->codec->codec_type = CODEC_TYPE_DATA;
1177
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1178 115329f1 Diego Biurrun
1179 b45a7a18 Fabrice Bellard
        /* we iterate until we find two PCRs to estimate the bitrate */
1180
        pcr_pid = -1;
1181
        nb_pcrs = 0;
1182
        nb_packets = 0;
1183
        for(;;) {
1184
            ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1185
            if (ret < 0)
1186
                return -1;
1187 80fb8234 Ronald S. Bultje
            pid = AV_RB16(packet + 1) & 0x1fff;
1188 b45a7a18 Fabrice Bellard
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1189
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1190
                pcr_pid = pid;
1191
                packet_count[nb_pcrs] = nb_packets;
1192
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1193
                nb_pcrs++;
1194
                if (nb_pcrs >= 2)
1195
                    break;
1196
            }
1197
            nb_packets++;
1198
        }
1199 5dbafeb7 Fabrice Bellard
1200 b45a7a18 Fabrice Bellard
        /* NOTE1: the bitrate is computed without the FEC */
1201
        /* NOTE2: it is only the bitrate of the start of the stream */
1202
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1203
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1204
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1205 01f4895c Michael Niedermayer
        st->codec->bit_rate = s->bit_rate;
1206 c0df9d75 Michael Niedermayer
        st->start_time = ts->cur_pcr;
1207 b45a7a18 Fabrice Bellard
#if 0
1208 f0ee3ea6 Michel Bardiaux
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1209 b45a7a18 Fabrice Bellard
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1210 5dbafeb7 Fabrice Bellard
#endif
1211 fe9cf0d4 Fabrice Bellard
    }
1212 5dbafeb7 Fabrice Bellard
1213
    url_fseek(pb, pos, SEEK_SET);
1214 fe9cf0d4 Fabrice Bellard
    return 0;
1215 5dbafeb7 Fabrice Bellard
 fail:
1216
    return -1;
1217
}
1218
1219 b45a7a18 Fabrice Bellard
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1220
1221
static int mpegts_raw_read_packet(AVFormatContext *s,
1222
                                  AVPacket *pkt)
1223
{
1224
    MpegTSContext *ts = s->priv_data;
1225
    int ret, i;
1226
    int64_t pcr_h, next_pcr_h, pos;
1227
    int pcr_l, next_pcr_l;
1228
    uint8_t pcr_buf[12];
1229
1230
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1231 8fa36ae0 François Revol
        return AVERROR(ENOMEM);
1232 2692067a Michael Niedermayer
    pkt->pos= url_ftell(&s->pb);
1233 b45a7a18 Fabrice Bellard
    ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1234
    if (ret < 0) {
1235
        av_free_packet(pkt);
1236
        return ret;
1237
    }
1238
    if (ts->mpeg2ts_compute_pcr) {
1239
        /* compute exact PCR for each packet */
1240
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1241
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1242
            pos = url_ftell(&s->pb);
1243
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1244
                url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1245
                get_buffer(&s->pb, pcr_buf, 12);
1246
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1247
                    /* XXX: not precise enough */
1248 115329f1 Diego Biurrun
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1249 b45a7a18 Fabrice Bellard
                        (i + 1);
1250
                    break;
1251
                }
1252
            }
1253
            url_fseek(&s->pb, pos, SEEK_SET);
1254
            /* no next PCR found: we use previous increment */
1255
            ts->cur_pcr = pcr_h * 300 + pcr_l;
1256
        }
1257
        pkt->pts = ts->cur_pcr;
1258
        pkt->duration = ts->pcr_incr;
1259
        ts->cur_pcr += ts->pcr_incr;
1260
    }
1261
    pkt->stream_index = 0;
1262
    return 0;
1263
}
1264
1265 5dbafeb7 Fabrice Bellard
static int mpegts_read_packet(AVFormatContext *s,
1266
                              AVPacket *pkt)
1267
{
1268
    MpegTSContext *ts = s->priv_data;
1269 b45a7a18 Fabrice Bellard
1270 38c48be2 Michael Niedermayer
    ts->pkt = pkt;
1271
    return handle_packets(ts, 0);
1272 fe9cf0d4 Fabrice Bellard
}
1273
1274
static int mpegts_read_close(AVFormatContext *s)
1275
{
1276
    MpegTSContext *ts = s->priv_data;
1277
    int i;
1278
    for(i=0;i<NB_PID_MAX;i++)
1279 ec7d0d2e Gildas Bazin
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1280 00a6b92b Måns Rullgård
1281
    for(i = 0; i < ts->nb_services; i++){
1282
        av_free(ts->services[i]->provider_name);
1283
        av_free(ts->services[i]->name);
1284
        av_free(ts->services[i]);
1285
    }
1286
    av_freep(&ts->services);
1287
1288 fe9cf0d4 Fabrice Bellard
    return 0;
1289
}
1290
1291 115329f1 Diego Biurrun
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1292 cdd5034f Michael Niedermayer
                              int64_t *ppos, int64_t pos_limit)
1293 27f388aa Fabrice Bellard
{
1294
    MpegTSContext *ts = s->priv_data;
1295
    int64_t pos, timestamp;
1296
    uint8_t buf[TS_PACKET_SIZE];
1297 dbf6b678 Michael Niedermayer
    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1298 cdd5034f Michael Niedermayer
    const int find_next= 1;
1299
    pos = ((*ppos  + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1300 27f388aa Fabrice Bellard
    if (find_next) {
1301
        for(;;) {
1302
            url_fseek(&s->pb, pos, SEEK_SET);
1303
            if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1304
                return AV_NOPTS_VALUE;
1305 80fb8234 Ronald S. Bultje
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1306 27f388aa Fabrice Bellard
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1307
                break;
1308
            }
1309
            pos += ts->raw_packet_size;
1310
        }
1311
    } else {
1312
        for(;;) {
1313
            pos -= ts->raw_packet_size;
1314
            if (pos < 0)
1315
                return AV_NOPTS_VALUE;
1316
            url_fseek(&s->pb, pos, SEEK_SET);
1317
            if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1318
                return AV_NOPTS_VALUE;
1319 80fb8234 Ronald S. Bultje
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1320 27f388aa Fabrice Bellard
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1321
                break;
1322
            }
1323
        }
1324
    }
1325
    *ppos = pos;
1326
1327 cdd5034f Michael Niedermayer
    return timestamp;
1328 27f388aa Fabrice Bellard
}
1329
1330 3ba1438d Michael Niedermayer
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1331 e05655fb Michael Niedermayer
    MpegTSContext *ts = s->priv_data;
1332
    uint8_t buf[TS_PACKET_SIZE];
1333
    int64_t pos;
1334
1335 3ba1438d Michael Niedermayer
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1336 e05655fb Michael Niedermayer
        return -1;
1337
1338
    pos= url_ftell(&s->pb);
1339
1340
    for(;;) {
1341
        url_fseek(&s->pb, pos, SEEK_SET);
1342
        if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1343
            return -1;
1344 80fb8234 Ronald S. Bultje
//        pid = AV_RB16(buf + 1) & 0x1fff;
1345 e05655fb Michael Niedermayer
        if(buf[1] & 0x40) break;
1346
        pos += ts->raw_packet_size;
1347 115329f1 Diego Biurrun
    }
1348 e05655fb Michael Niedermayer
    url_fseek(&s->pb, pos, SEEK_SET);
1349
1350
    return 0;
1351
}
1352
1353 b45a7a18 Fabrice Bellard
/**************************************************************/
1354
/* parsing functions - called from other demuxers such as RTP */
1355
1356
MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1357
{
1358
    MpegTSContext *ts;
1359 115329f1 Diego Biurrun
1360 b45a7a18 Fabrice Bellard
    ts = av_mallocz(sizeof(MpegTSContext));
1361
    if (!ts)
1362
        return NULL;
1363
    /* no stream case, currently used by RTP */
1364
    ts->raw_packet_size = TS_PACKET_SIZE;
1365
    ts->stream = s;
1366
    ts->auto_guess = 1;
1367
    return ts;
1368
}
1369
1370
/* return the consumed length if a packet was output, or -1 if no
1371
   packet is output */
1372
int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1373
                        const uint8_t *buf, int len)
1374
{
1375
    int len1;
1376
1377
    len1 = len;
1378
    ts->pkt = pkt;
1379
    ts->stop_parse = 0;
1380
    for(;;) {
1381 90d13e30 Michael Niedermayer
        if (ts->stop_parse>0)
1382 b45a7a18 Fabrice Bellard
            break;
1383
        if (len < TS_PACKET_SIZE)
1384
            return -1;
1385
        if (buf[0] != 0x47) {
1386 550f0a9b Wolfram Gloger
            buf++;
1387 b45a7a18 Fabrice Bellard
            len--;
1388
        } else {
1389
            handle_packet(ts, buf);
1390
            buf += TS_PACKET_SIZE;
1391
            len -= TS_PACKET_SIZE;
1392
        }
1393
    }
1394
    return len1 - len;
1395
}
1396
1397
void mpegts_parse_close(MpegTSContext *ts)
1398
{
1399
    int i;
1400
1401
    for(i=0;i<NB_PID_MAX;i++)
1402
        av_free(ts->pids[i]);
1403
    av_free(ts);
1404
}
1405
1406 d2a067d1 Måns Rullgård
AVInputFormat mpegts_demuxer = {
1407 fe9cf0d4 Fabrice Bellard
    "mpegts",
1408
    "MPEG2 transport stream format",
1409
    sizeof(MpegTSContext),
1410
    mpegts_probe,
1411
    mpegts_read_header,
1412
    mpegts_read_packet,
1413
    mpegts_read_close,
1414 e05655fb Michael Niedermayer
    read_seek,
1415 cdd5034f Michael Niedermayer
    mpegts_get_pcr,
1416 b45a7a18 Fabrice Bellard
    .flags = AVFMT_SHOW_IDS,
1417 fe9cf0d4 Fabrice Bellard
};
1418 38c48be2 Michael Niedermayer
1419
AVInputFormat mpegtsraw_demuxer = {
1420
    "mpegtsraw",
1421
    "MPEG2 raw transport stream format",
1422
    sizeof(MpegTSContext),
1423
    mpegts_probe,
1424
    mpegts_read_header,
1425
    mpegts_raw_read_packet,
1426
    mpegts_read_close,
1427
    read_seek,
1428
    mpegts_get_pcr,
1429
    .flags = AVFMT_SHOW_IDS,
1430
};