Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpegts.c @ b795ff97

History | View | Annotate | Download (56.7 KB)

1 fe9cf0d4 Fabrice Bellard
/*
2 7fbde343 Aurelien Jacobs
 * MPEG2 transport stream (aka DVB) demuxer
3 406792e7 Diego Biurrun
 * 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 245976da Diego Biurrun
22 e9859317 Baptiste Coudurier
//#define DEBUG
23
//#define DEBUG_SEEK
24 af8aae3f Ivan Schreter
//#define USE_SYNCPOINT_SEARCH
25 e9859317 Baptiste Coudurier
26 245976da Diego Biurrun
#include "libavutil/crc.h"
27 6a5d31ac Diego Biurrun
#include "libavutil/intreadwrite.h"
28 4f1db48e Baptiste Coudurier
#include "libavcodec/bytestream.h"
29 fe9cf0d4 Fabrice Bellard
#include "avformat.h"
30 5dbafeb7 Fabrice Bellard
#include "mpegts.h"
31 ecfb51d1 Diego Biurrun
#include "internal.h"
32 a8dd8dc6 Ivan Schreter
#include "seek.h"
33 798c6fac Baptiste Coudurier
#include "isom.h"
34 fe9cf0d4 Fabrice Bellard
35 5dbafeb7 Fabrice Bellard
/* 1.0 second at 24Mbit/s */
36 fc48fe84 Fabrice Bellard
#define MAX_SCAN_PACKETS 32000
37
38
/* maximum size in which we look for synchronisation if
39
   synchronisation is lost */
40 1303d62d Baptiste Coudurier
#define MAX_RESYNC_SIZE 65536
41 5dbafeb7 Fabrice Bellard
42 0c137557 Baptiste Coudurier
#define MAX_PES_PAYLOAD 200*1024
43
44 5dbafeb7 Fabrice Bellard
enum MpegTSFilterType {
45
    MPEGTS_PES,
46
    MPEGTS_SECTION,
47 fe9cf0d4 Fabrice Bellard
};
48
49 b474d1f3 Måns Rullgård
typedef struct MpegTSFilter MpegTSFilter;
50
51 bdfa9824 Baptiste Coudurier
typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
52 fe9cf0d4 Fabrice Bellard
53 5dbafeb7 Fabrice Bellard
typedef struct MpegTSPESFilter {
54
    PESCallback *pes_cb;
55
    void *opaque;
56
} MpegTSPESFilter;
57
58 b474d1f3 Måns Rullgård
typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
59 5dbafeb7 Fabrice Bellard
60
typedef void SetServiceCallback(void *opaque, int ret);
61
62
typedef struct MpegTSSectionFilter {
63
    int section_index;
64
    int section_h_size;
65
    uint8_t *section_buf;
66 72e043dd Erik Hovland
    unsigned int check_crc:1;
67
    unsigned int end_of_section_reached:1;
68 5dbafeb7 Fabrice Bellard
    SectionCallback *section_cb;
69
    void *opaque;
70
} MpegTSSectionFilter;
71
72 b474d1f3 Måns Rullgård
struct MpegTSFilter {
73 fe9cf0d4 Fabrice Bellard
    int pid;
74
    int last_cc; /* last cc code (-1 if first packet) */
75 5dbafeb7 Fabrice Bellard
    enum MpegTSFilterType type;
76
    union {
77
        MpegTSPESFilter pes_filter;
78
        MpegTSSectionFilter section_filter;
79
    } u;
80 b474d1f3 Måns Rullgård
};
81 5dbafeb7 Fabrice Bellard
82 172d1171 Nico Sabbi
#define MAX_PIDS_PER_PROGRAM 64
83 8c39a758 Måns Rullgård
struct Program {
84 172d1171 Nico Sabbi
    unsigned int id; //program id/service id
85
    unsigned int nb_pids;
86
    unsigned int pids[MAX_PIDS_PER_PROGRAM];
87 8c39a758 Måns Rullgård
};
88 172d1171 Nico Sabbi
89 0694a009 Måns Rullgård
struct MpegTSContext {
90 5dbafeb7 Fabrice Bellard
    /* user data */
91
    AVFormatContext *stream;
92 e995cfca Daniel Kristjansson
    /** raw packet size, including FEC if present            */
93
    int raw_packet_size;
94 5fd63f3c Michael Niedermayer
95
    int pos47;
96
97 e995cfca Daniel Kristjansson
    /** if true, all pids are analyzed to find streams       */
98
    int auto_guess;
99 5dbafeb7 Fabrice Bellard
100 e995cfca Daniel Kristjansson
    /** compute exact PCR for each transport stream packet   */
101
    int mpeg2ts_compute_pcr;
102 b45a7a18 Fabrice Bellard
103 e995cfca Daniel Kristjansson
    int64_t cur_pcr;    /**< used to estimate the exact PCR  */
104
    int pcr_incr;       /**< used to estimate the exact PCR  */
105 115329f1 Diego Biurrun
106 5dbafeb7 Fabrice Bellard
    /* data needed to handle file based ts */
107 e995cfca Daniel Kristjansson
    /** stop parsing loop                                    */
108
    int stop_parse;
109
    /** packet containing Audio/Video data                   */
110
    AVPacket *pkt;
111 0c137557 Baptiste Coudurier
    /** to detect seek                                       */
112
    int64_t last_pos;
113 5dbafeb7 Fabrice Bellard
114
    /******************************************/
115
    /* private mpegts data */
116
    /* scan context */
117 172d1171 Nico Sabbi
    /** structure to keep track of Program->pids mapping     */
118
    unsigned int nb_prg;
119 8c39a758 Måns Rullgård
    struct Program *prg;
120 115329f1 Diego Biurrun
121 5dbafeb7 Fabrice Bellard
122 e995cfca Daniel Kristjansson
    /** filters for various streams specified by PMT + for the PAT and PMT */
123 5dbafeb7 Fabrice Bellard
    MpegTSFilter *pids[NB_PID_MAX];
124 0694a009 Måns Rullgård
};
125 fe9cf0d4 Fabrice Bellard
126 ecc31d1d Michael Niedermayer
/* TS stream handling */
127
128
enum MpegTSState {
129
    MPEGTS_HEADER = 0,
130 b2984add Baptiste Coudurier
    MPEGTS_PESHEADER,
131 ecc31d1d Michael Niedermayer
    MPEGTS_PESHEADER_FILL,
132
    MPEGTS_PAYLOAD,
133
    MPEGTS_SKIP,
134
};
135
136
/* enough for PES header + length */
137 b2984add Baptiste Coudurier
#define PES_START_SIZE  6
138
#define PES_HEADER_SIZE 9
139 ecc31d1d Michael Niedermayer
#define MAX_PES_HEADER_SIZE (9 + 255)
140
141 10061cd6 Baptiste Coudurier
typedef struct PESContext {
142 ecc31d1d Michael Niedermayer
    int pid;
143 dbf6b678 Michael Niedermayer
    int pcr_pid; /**< if -1 then all packets containing PCR are considered */
144 ecc31d1d Michael Niedermayer
    int stream_type;
145
    MpegTSContext *ts;
146
    AVFormatContext *stream;
147
    AVStream *st;
148 63380b5e Ian Caulfield
    AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
149 ecc31d1d Michael Niedermayer
    enum MpegTSState state;
150
    /* used to get the format */
151
    int data_index;
152
    int total_size;
153
    int pes_header_size;
154 63380b5e Ian Caulfield
    int extended_stream_id;
155 ecc31d1d Michael Niedermayer
    int64_t pts, dts;
156 4c6b49bf Ivan Schreter
    int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
157 ecc31d1d Michael Niedermayer
    uint8_t header[MAX_PES_HEADER_SIZE];
158 0c137557 Baptiste Coudurier
    uint8_t *buffer;
159 10061cd6 Baptiste Coudurier
} PESContext;
160 ecc31d1d Michael Niedermayer
161 6369638b Aurelien Jacobs
extern AVInputFormat mpegts_demuxer;
162
163 172d1171 Nico Sabbi
static void clear_program(MpegTSContext *ts, unsigned int programid)
164
{
165
    int i;
166
167
    for(i=0; i<ts->nb_prg; i++)
168
        if(ts->prg[i].id == programid)
169
            ts->prg[i].nb_pids = 0;
170
}
171
172
static void clear_programs(MpegTSContext *ts)
173
{
174
    av_freep(&ts->prg);
175
    ts->nb_prg=0;
176
}
177
178
static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
179
{
180 8c39a758 Måns Rullgård
    struct Program *p;
181
    void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
182 172d1171 Nico Sabbi
    if(!tmp)
183
        return;
184
    ts->prg = tmp;
185
    p = &ts->prg[ts->nb_prg];
186
    p->id = programid;
187
    p->nb_pids = 0;
188
    ts->nb_prg++;
189
}
190
191
static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
192
{
193
    int i;
194 8c39a758 Måns Rullgård
    struct Program *p = NULL;
195 172d1171 Nico Sabbi
    for(i=0; i<ts->nb_prg; i++) {
196
        if(ts->prg[i].id == programid) {
197
            p = &ts->prg[i];
198
            break;
199
        }
200
    }
201
    if(!p)
202
        return;
203
204
    if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
205
        return;
206
    p->pids[p->nb_pids++] = pid;
207
}
208
209
/**
210
 * \brief discard_pid() decides if the pid is to be discarded according
211
 *                      to caller's programs selection
212
 * \param ts    : - TS context
213
 * \param pid   : - pid
214
 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
215
 *         0 otherwise
216
 */
217
static int discard_pid(MpegTSContext *ts, unsigned int pid)
218
{
219
    int i, j, k;
220
    int used = 0, discarded = 0;
221 8c39a758 Måns Rullgård
    struct Program *p;
222 172d1171 Nico Sabbi
    for(i=0; i<ts->nb_prg; i++) {
223
        p = &ts->prg[i];
224
        for(j=0; j<p->nb_pids; j++) {
225
            if(p->pids[j] != pid)
226
                continue;
227
            //is program with id p->id set to be discarded?
228
            for(k=0; k<ts->stream->nb_programs; k++) {
229
                if(ts->stream->programs[k]->id == p->id) {
230
                    if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
231
                        discarded++;
232
                    else
233
                        used++;
234
                }
235
            }
236
        }
237
    }
238
239 ccd425e7 Diego Biurrun
    return !used && discarded;
240 172d1171 Nico Sabbi
}
241
242 e995cfca Daniel Kristjansson
/**
243 49bd8e4b Måns Rullgård
 *  Assemble PES packets out of TS packets, and then call the "section_cb"
244 e995cfca Daniel Kristjansson
 *  function when they are complete.
245
 */
246 5dbafeb7 Fabrice Bellard
static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
247
                               const uint8_t *buf, int buf_size, int is_start)
248
{
249
    MpegTSSectionFilter *tss = &tss1->u.section_filter;
250
    int len;
251 115329f1 Diego Biurrun
252 5dbafeb7 Fabrice Bellard
    if (is_start) {
253
        memcpy(tss->section_buf, buf, buf_size);
254
        tss->section_index = buf_size;
255
        tss->section_h_size = -1;
256
        tss->end_of_section_reached = 0;
257
    } else {
258
        if (tss->end_of_section_reached)
259
            return;
260
        len = 4096 - tss->section_index;
261
        if (buf_size < len)
262
            len = buf_size;
263
        memcpy(tss->section_buf + tss->section_index, buf, len);
264
        tss->section_index += len;
265
    }
266
267
    /* compute section length if possible */
268
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
269 80fb8234 Ronald S. Bultje
        len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
270 5dbafeb7 Fabrice Bellard
        if (len > 4096)
271
            return;
272
        tss->section_h_size = len;
273
    }
274
275
    if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
276
        tss->end_of_section_reached = 1;
277 27bb1ed3 Wolfram Gloger
        if (!tss->check_crc ||
278 3abe5fbd Aurelien Jacobs
            av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
279
                   tss->section_buf, tss->section_h_size) == 0)
280 4d9a577e Michael Niedermayer
            tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
281 5dbafeb7 Fabrice Bellard
    }
282
}
283
284 7b49ce2e Stefan Huehner
static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
285 5dbafeb7 Fabrice Bellard
                                         SectionCallback *section_cb, void *opaque,
286
                                         int check_crc)
287
288
{
289
    MpegTSFilter *filter;
290
    MpegTSSectionFilter *sec;
291 115329f1 Diego Biurrun
292 ebcf352a Baptiste Coudurier
    dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
293
294 5dbafeb7 Fabrice Bellard
    if (pid >= NB_PID_MAX || ts->pids[pid])
295
        return NULL;
296
    filter = av_mallocz(sizeof(MpegTSFilter));
297 115329f1 Diego Biurrun
    if (!filter)
298 5dbafeb7 Fabrice Bellard
        return NULL;
299
    ts->pids[pid] = filter;
300
    filter->type = MPEGTS_SECTION;
301
    filter->pid = pid;
302
    filter->last_cc = -1;
303
    sec = &filter->u.section_filter;
304
    sec->section_cb = section_cb;
305
    sec->opaque = opaque;
306
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
307
    sec->check_crc = check_crc;
308
    if (!sec->section_buf) {
309
        av_free(filter);
310
        return NULL;
311
    }
312
    return filter;
313
}
314
315 7b49ce2e Stefan Huehner
static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
316 5dbafeb7 Fabrice Bellard
                                     PESCallback *pes_cb,
317
                                     void *opaque)
318
{
319
    MpegTSFilter *filter;
320
    MpegTSPESFilter *pes;
321
322
    if (pid >= NB_PID_MAX || ts->pids[pid])
323
        return NULL;
324
    filter = av_mallocz(sizeof(MpegTSFilter));
325 115329f1 Diego Biurrun
    if (!filter)
326 5dbafeb7 Fabrice Bellard
        return NULL;
327
    ts->pids[pid] = filter;
328
    filter->type = MPEGTS_PES;
329
    filter->pid = pid;
330
    filter->last_cc = -1;
331
    pes = &filter->u.pes_filter;
332
    pes->pes_cb = pes_cb;
333
    pes->opaque = opaque;
334
    return filter;
335
}
336
337 7b49ce2e Stefan Huehner
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
338 5dbafeb7 Fabrice Bellard
{
339
    int pid;
340
341
    pid = filter->pid;
342
    if (filter->type == MPEGTS_SECTION)
343
        av_freep(&filter->u.section_filter.section_buf);
344 dcd913d9 Jindřich Makovička
    else if (filter->type == MPEGTS_PES) {
345 0c137557 Baptiste Coudurier
        PESContext *pes = filter->u.pes_filter.opaque;
346
        av_freep(&pes->buffer);
347 dcd913d9 Jindřich Makovička
        /* referenced private data will be freed later in
348
         * av_close_input_stream */
349
        if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
350
            av_freep(&filter->u.pes_filter.opaque);
351
        }
352
    }
353 ec7d0d2e Gildas Bazin
354 5dbafeb7 Fabrice Bellard
    av_free(filter);
355
    ts->pids[pid] = NULL;
356
}
357
358 a0b8f70c Michael Niedermayer
static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
359 cf5ec607 Måns Rullgård
    int stat[TS_MAX_PACKET_SIZE];
360 a0b8f70c Michael Niedermayer
    int i;
361
    int x=0;
362
    int best_score=0;
363
364
    memset(stat, 0, packet_size*sizeof(int));
365
366 c6002ea1 Måns Rullgård
    for(x=i=0; i<size-3; i++){
367
        if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
368 a0b8f70c Michael Niedermayer
            stat[x]++;
369
            if(stat[x] > best_score){
370
                best_score= stat[x];
371
                if(index) *index= x;
372
            }
373
        }
374
375
        x++;
376
        if(x == packet_size) x= 0;
377
    }
378
379
    return best_score;
380
}
381
382 fe9cf0d4 Fabrice Bellard
/* autodetect fec presence. Must have at least 1024 bytes  */
383 5dbafeb7 Fabrice Bellard
static int get_packet_size(const uint8_t *buf, int size)
384 fe9cf0d4 Fabrice Bellard
{
385 5d4d67e0 Nico Sabbi
    int score, fec_score, dvhs_score;
386 fe9cf0d4 Fabrice Bellard
387
    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
388
        return -1;
389 115329f1 Diego Biurrun
390 a0b8f70c Michael Niedermayer
    score    = analyze(buf, size, TS_PACKET_SIZE, NULL);
391 5d4d67e0 Nico Sabbi
    dvhs_score    = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
392 a0b8f70c Michael Niedermayer
    fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
393 5d4d67e0 Nico Sabbi
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
394 115329f1 Diego Biurrun
395 5d4d67e0 Nico Sabbi
    if     (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
396
    else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
397
    else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
398 a0b8f70c Michael Niedermayer
    else                       return -1;
399 fe9cf0d4 Fabrice Bellard
}
400
401 5dbafeb7 Fabrice Bellard
typedef struct SectionHeader {
402
    uint8_t tid;
403
    uint16_t id;
404
    uint8_t version;
405
    uint8_t sec_num;
406
    uint8_t last_sec_num;
407
} SectionHeader;
408
409
static inline int get8(const uint8_t **pp, const uint8_t *p_end)
410 fe9cf0d4 Fabrice Bellard
{
411 5dbafeb7 Fabrice Bellard
    const uint8_t *p;
412
    int c;
413
414
    p = *pp;
415
    if (p >= p_end)
416
        return -1;
417
    c = *p++;
418
    *pp = p;
419
    return c;
420 fe9cf0d4 Fabrice Bellard
}
421
422 5dbafeb7 Fabrice Bellard
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
423
{
424
    const uint8_t *p;
425
    int c;
426
427
    p = *pp;
428
    if ((p + 1) >= p_end)
429
        return -1;
430 80fb8234 Ronald S. Bultje
    c = AV_RB16(p);
431 5dbafeb7 Fabrice Bellard
    p += 2;
432
    *pp = p;
433
    return c;
434
}
435
436
/* read and allocate a DVB string preceeded by its length */
437
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
438 fe9cf0d4 Fabrice Bellard
{
439
    int len;
440 5dbafeb7 Fabrice Bellard
    const uint8_t *p;
441
    char *str;
442 fe9cf0d4 Fabrice Bellard
443 5dbafeb7 Fabrice Bellard
    p = *pp;
444
    len = get8(&p, p_end);
445
    if (len < 0)
446
        return NULL;
447
    if ((p + len) > p_end)
448
        return NULL;
449
    str = av_malloc(len + 1);
450
    if (!str)
451
        return NULL;
452
    memcpy(str, p, len);
453
    str[len] = '\0';
454
    p += len;
455
    *pp = p;
456
    return str;
457
}
458
459 115329f1 Diego Biurrun
static int parse_section_header(SectionHeader *h,
460 5dbafeb7 Fabrice Bellard
                                const uint8_t **pp, const uint8_t *p_end)
461
{
462
    int val;
463
464
    val = get8(pp, p_end);
465
    if (val < 0)
466
        return -1;
467
    h->tid = val;
468
    *pp += 2;
469
    val = get16(pp, p_end);
470
    if (val < 0)
471
        return -1;
472
    h->id = val;
473
    val = get8(pp, p_end);
474
    if (val < 0)
475
        return -1;
476
    h->version = (val >> 1) & 0x1f;
477
    val = get8(pp, p_end);
478
    if (val < 0)
479
        return -1;
480
    h->sec_num = val;
481
    val = get8(pp, p_end);
482
    if (val < 0)
483
        return -1;
484
    h->last_sec_num = val;
485 fe9cf0d4 Fabrice Bellard
    return 0;
486 5dbafeb7 Fabrice Bellard
}
487
488 08f94e98 Baptiste Coudurier
typedef struct {
489
    uint32_t stream_type;
490 72415b2a Stefano Sabatini
    enum AVMediaType codec_type;
491 08f94e98 Baptiste Coudurier
    enum CodecID codec_id;
492
} StreamType;
493
494
static const StreamType ISO_types[] = {
495 72415b2a Stefano Sabatini
    { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
496
    { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
497
    { 0x03, AVMEDIA_TYPE_AUDIO,        CODEC_ID_MP3 },
498
    { 0x04, AVMEDIA_TYPE_AUDIO,        CODEC_ID_MP3 },
499
    { 0x0f, AVMEDIA_TYPE_AUDIO,        CODEC_ID_AAC },
500
    { 0x10, AVMEDIA_TYPE_VIDEO,      CODEC_ID_MPEG4 },
501 915bfa33 Janne Grunau
    { 0x11, AVMEDIA_TYPE_AUDIO,   CODEC_ID_AAC_LATM }, /* LATM syntax */
502 72415b2a Stefano Sabatini
    { 0x1b, AVMEDIA_TYPE_VIDEO,       CODEC_ID_H264 },
503
    { 0xd1, AVMEDIA_TYPE_VIDEO,      CODEC_ID_DIRAC },
504
    { 0xea, AVMEDIA_TYPE_VIDEO,        CODEC_ID_VC1 },
505 08f94e98 Baptiste Coudurier
    { 0 },
506
};
507
508
static const StreamType HDMV_types[] = {
509 72415b2a Stefano Sabatini
    { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
510
    { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
511
    { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
512
    { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
513
    { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
514
    { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
515 08f94e98 Baptiste Coudurier
    { 0 },
516
};
517
518
/* ATSC ? */
519
static const StreamType MISC_types[] = {
520 72415b2a Stefano Sabatini
    { 0x81, AVMEDIA_TYPE_AUDIO,   CODEC_ID_AC3 },
521
    { 0x8a, AVMEDIA_TYPE_AUDIO,   CODEC_ID_DTS },
522 08f94e98 Baptiste Coudurier
    { 0 },
523
};
524
525
static const StreamType REGD_types[] = {
526 72415b2a Stefano Sabatini
    { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
527
    { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO,   CODEC_ID_AC3 },
528 08f94e98 Baptiste Coudurier
    { 0 },
529
};
530
531 6a2a50f8 Baptiste Coudurier
/* descriptor present */
532
static const StreamType DESC_types[] = {
533 72415b2a Stefano Sabatini
    { 0x6a, AVMEDIA_TYPE_AUDIO,             CODEC_ID_AC3 }, /* AC-3 descriptor */
534
    { 0x7a, AVMEDIA_TYPE_AUDIO,            CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
535
    { 0x7b, AVMEDIA_TYPE_AUDIO,             CODEC_ID_DTS },
536
    { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
537
    { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
538 896f2b32 Wolfram Gloger
    { 0 },
539 6a2a50f8 Baptiste Coudurier
};
540
541 08f94e98 Baptiste Coudurier
static void mpegts_find_stream_type(AVStream *st,
542
                                    uint32_t stream_type, const StreamType *types)
543
{
544
    for (; types->stream_type; types++) {
545
        if (stream_type == types->stream_type) {
546
            st->codec->codec_type = types->codec_type;
547
            st->codec->codec_id   = types->codec_id;
548
            return;
549
        }
550
    }
551
}
552
553 b3f9f7a3 Baptiste Coudurier
static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
554
                                  uint32_t stream_type, uint32_t prog_reg_desc)
555 08f94e98 Baptiste Coudurier
{
556
    av_set_pts_info(st, 33, 1, 90000);
557
    st->priv_data = pes;
558 72415b2a Stefano Sabatini
    st->codec->codec_type = AVMEDIA_TYPE_DATA;
559 d23612ef Baptiste Coudurier
    st->codec->codec_id   = CODEC_ID_NONE;
560 08f94e98 Baptiste Coudurier
    st->need_parsing = AVSTREAM_PARSE_FULL;
561
    pes->st = st;
562 b3f9f7a3 Baptiste Coudurier
    pes->stream_type = stream_type;
563 08f94e98 Baptiste Coudurier
564 b3f9f7a3 Baptiste Coudurier
    av_log(pes->stream, AV_LOG_DEBUG,
565
           "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
566
           st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
567 08f94e98 Baptiste Coudurier
568 7103a77b Baptiste Coudurier
    st->codec->codec_tag = pes->stream_type;
569
570 f2c357d9 Baptiste Coudurier
    mpegts_find_stream_type(st, pes->stream_type, ISO_types);
571
    if (prog_reg_desc == AV_RL32("HDMV") &&
572 63380b5e Ian Caulfield
        st->codec->codec_id == CODEC_ID_NONE) {
573 f2c357d9 Baptiste Coudurier
        mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
574 63380b5e Ian Caulfield
        if (pes->stream_type == 0x83) {
575
            // HDMV TrueHD streams also contain an AC3 coded version of the
576
            // audio track - add a second stream for this
577
            AVStream *sub_st;
578
            // priv_data cannot be shared between streams
579
            PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
580
            if (!sub_pes)
581 b3f9f7a3 Baptiste Coudurier
                return AVERROR(ENOMEM);
582 63380b5e Ian Caulfield
            memcpy(sub_pes, pes, sizeof(*sub_pes));
583
584
            sub_st = av_new_stream(pes->stream, pes->pid);
585
            if (!sub_st) {
586
                av_free(sub_pes);
587 b3f9f7a3 Baptiste Coudurier
                return AVERROR(ENOMEM);
588 63380b5e Ian Caulfield
            }
589
590
            av_set_pts_info(sub_st, 33, 1, 90000);
591
            sub_st->priv_data = sub_pes;
592 72415b2a Stefano Sabatini
            sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
593 63380b5e Ian Caulfield
            sub_st->codec->codec_id   = CODEC_ID_AC3;
594
            sub_st->need_parsing = AVSTREAM_PARSE_FULL;
595
            sub_pes->sub_st = pes->sub_st = sub_st;
596
        }
597
    }
598 d23612ef Baptiste Coudurier
    if (st->codec->codec_id == CODEC_ID_NONE)
599 f2c357d9 Baptiste Coudurier
        mpegts_find_stream_type(st, pes->stream_type, MISC_types);
600 08f94e98 Baptiste Coudurier
601 b3f9f7a3 Baptiste Coudurier
    return 0;
602 08f94e98 Baptiste Coudurier
}
603 5dbafeb7 Fabrice Bellard
604 609d8646 Baptiste Coudurier
static int64_t get_pts(const uint8_t *p)
605
{
606
    int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
607
    pts |= (AV_RB16(p + 1) >> 1) << 15;
608
    pts |=  AV_RB16(p + 3) >> 1;
609
    return pts;
610
}
611
612
static void new_pes_packet(PESContext *pes, AVPacket *pkt)
613
{
614
    av_init_packet(pkt);
615
616
    pkt->destruct = av_destruct_packet;
617
    pkt->data = pes->buffer;
618
    pkt->size = pes->data_index;
619
    memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
620
621
    // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
622
    if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
623
        pkt->stream_index = pes->sub_st->index;
624
    else
625
        pkt->stream_index = pes->st->index;
626
    pkt->pts = pes->pts;
627
    pkt->dts = pes->dts;
628
    /* store position of first TS packet of this PES packet */
629
    pkt->pos = pes->ts_packet_pos;
630
631
    /* reset pts values */
632
    pes->pts = AV_NOPTS_VALUE;
633
    pes->dts = AV_NOPTS_VALUE;
634
    pes->buffer = NULL;
635
    pes->data_index = 0;
636
}
637
638
/* return non zero if a packet could be constructed */
639
static int mpegts_push_data(MpegTSFilter *filter,
640
                            const uint8_t *buf, int buf_size, int is_start,
641
                            int64_t pos)
642
{
643
    PESContext *pes = filter->u.pes_filter.opaque;
644
    MpegTSContext *ts = pes->ts;
645
    const uint8_t *p;
646
    int len, code;
647
648
    if(!ts->pkt)
649
        return 0;
650
651
    if (is_start) {
652
        if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
653
            new_pes_packet(pes, ts->pkt);
654
            ts->stop_parse = 1;
655
        }
656
        pes->state = MPEGTS_HEADER;
657
        pes->data_index = 0;
658
        pes->ts_packet_pos = pos;
659
    }
660
    p = buf;
661
    while (buf_size > 0) {
662
        switch(pes->state) {
663
        case MPEGTS_HEADER:
664
            len = PES_START_SIZE - pes->data_index;
665
            if (len > buf_size)
666
                len = buf_size;
667
            memcpy(pes->header + pes->data_index, p, len);
668
            pes->data_index += len;
669
            p += len;
670
            buf_size -= len;
671
            if (pes->data_index == PES_START_SIZE) {
672
                /* we got all the PES or section header. We can now
673
                   decide */
674
#if 0
675
                av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
676
#endif
677
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
678
                    pes->header[2] == 0x01) {
679
                    /* it must be an mpeg2 PES stream */
680
                    code = pes->header[3] | 0x100;
681
                    dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
682
683 6b2b3376 Aurelien Jacobs
                    if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
684 609d8646 Baptiste Coudurier
                        code == 0x1be) /* padding_stream */
685
                        goto skip;
686
687 54036be1 Aurelien Jacobs
#if FF_API_MAX_STREAMS
688 6b2b3376 Aurelien Jacobs
                    if (!pes->st && pes->stream->nb_streams == MAX_STREAMS)
689
                        goto skip;
690
#endif
691
692 609d8646 Baptiste Coudurier
                    /* stream not present in PMT */
693
                    if (!pes->st) {
694
                        pes->st = av_new_stream(ts->stream, pes->pid);
695
                        if (!pes->st)
696
                            return AVERROR(ENOMEM);
697
                        mpegts_set_stream_info(pes->st, pes, 0, 0);
698
                    }
699
700
                    pes->total_size = AV_RB16(pes->header + 4);
701
                    /* NOTE: a zero total size means the PES size is
702
                       unbounded */
703
                    if (!pes->total_size)
704
                        pes->total_size = MAX_PES_PAYLOAD;
705
706
                    /* allocate pes buffer */
707
                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
708
                    if (!pes->buffer)
709
                        return AVERROR(ENOMEM);
710
711
                    if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
712
                        code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
713
                        code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
714
                        code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
715
                        pes->state = MPEGTS_PESHEADER;
716
                        if (pes->st->codec->codec_id == CODEC_ID_NONE) {
717
                            dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
718
                                    pes->pid, pes->stream_type);
719
                            pes->st->codec->codec_id = CODEC_ID_PROBE;
720
                        }
721
                    } else {
722
                        pes->state = MPEGTS_PAYLOAD;
723
                        pes->data_index = 0;
724
                    }
725
                } else {
726
                    /* otherwise, it should be a table */
727
                    /* skip packet */
728
                skip:
729
                    pes->state = MPEGTS_SKIP;
730
                    continue;
731
                }
732
            }
733
            break;
734
            /**********************************************/
735
            /* PES packing parsing */
736
        case MPEGTS_PESHEADER:
737
            len = PES_HEADER_SIZE - pes->data_index;
738
            if (len < 0)
739
                return -1;
740
            if (len > buf_size)
741
                len = buf_size;
742
            memcpy(pes->header + pes->data_index, p, len);
743
            pes->data_index += len;
744
            p += len;
745
            buf_size -= len;
746
            if (pes->data_index == PES_HEADER_SIZE) {
747
                pes->pes_header_size = pes->header[8] + 9;
748
                pes->state = MPEGTS_PESHEADER_FILL;
749
            }
750
            break;
751
        case MPEGTS_PESHEADER_FILL:
752
            len = pes->pes_header_size - pes->data_index;
753
            if (len < 0)
754
                return -1;
755
            if (len > buf_size)
756
                len = buf_size;
757
            memcpy(pes->header + pes->data_index, p, len);
758
            pes->data_index += len;
759
            p += len;
760
            buf_size -= len;
761
            if (pes->data_index == pes->pes_header_size) {
762
                const uint8_t *r;
763
                unsigned int flags, pes_ext, skip;
764
765
                flags = pes->header[7];
766
                r = pes->header + 9;
767
                pes->pts = AV_NOPTS_VALUE;
768
                pes->dts = AV_NOPTS_VALUE;
769
                if ((flags & 0xc0) == 0x80) {
770
                    pes->dts = pes->pts = get_pts(r);
771
                    r += 5;
772
                } else if ((flags & 0xc0) == 0xc0) {
773
                    pes->pts = get_pts(r);
774
                    r += 5;
775
                    pes->dts = get_pts(r);
776
                    r += 5;
777
                }
778
                pes->extended_stream_id = -1;
779
                if (flags & 0x01) { /* PES extension */
780
                    pes_ext = *r++;
781
                    /* Skip PES private data, program packet sequence counter and P-STD buffer */
782
                    skip = (pes_ext >> 4) & 0xb;
783
                    skip += skip & 0x9;
784
                    r += skip;
785
                    if ((pes_ext & 0x41) == 0x01 &&
786
                        (r + 2) <= (pes->header + pes->pes_header_size)) {
787
                        /* PES extension 2 */
788
                        if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
789
                            pes->extended_stream_id = r[1];
790
                    }
791
                }
792
793
                /* we got the full header. We parse it and get the payload */
794
                pes->state = MPEGTS_PAYLOAD;
795
                pes->data_index = 0;
796
            }
797
            break;
798
        case MPEGTS_PAYLOAD:
799
            if (buf_size > 0 && pes->buffer) {
800
                if (pes->data_index+buf_size > pes->total_size) {
801
                    new_pes_packet(pes, ts->pkt);
802
                    pes->total_size = MAX_PES_PAYLOAD;
803
                    pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
804
                    if (!pes->buffer)
805
                        return AVERROR(ENOMEM);
806
                    ts->stop_parse = 1;
807
                }
808
                memcpy(pes->buffer+pes->data_index, p, buf_size);
809
                pes->data_index += buf_size;
810
            }
811
            buf_size = 0;
812 b74f67eb Janne Grunau
            /* emit complete packets with known packet size
813
             * decreases demuxer delay for infrequent packets like subtitles from
814
             * a couple of seconds to milliseconds for properly muxed files.
815
             * total_size is the number of bytes following pes_packet_length
816
             * in the pes header, i.e. not counting the first 6 bytes */
817
            if (pes->total_size < MAX_PES_PAYLOAD &&
818
                pes->pes_header_size + pes->data_index == pes->total_size + 6) {
819
                ts->stop_parse = 1;
820
                new_pes_packet(pes, ts->pkt);
821
            }
822 609d8646 Baptiste Coudurier
            break;
823
        case MPEGTS_SKIP:
824
            buf_size = 0;
825
            break;
826
        }
827
    }
828
829
    return 0;
830
}
831
832
static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
833
{
834
    MpegTSFilter *tss;
835
    PESContext *pes;
836
837
    /* if no pid found, then add a pid context */
838
    pes = av_mallocz(sizeof(PESContext));
839
    if (!pes)
840
        return 0;
841
    pes->ts = ts;
842
    pes->stream = ts->stream;
843
    pes->pid = pid;
844
    pes->pcr_pid = pcr_pid;
845
    pes->state = MPEGTS_SKIP;
846
    pes->pts = AV_NOPTS_VALUE;
847
    pes->dts = AV_NOPTS_VALUE;
848
    tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
849
    if (!tss) {
850
        av_free(pes);
851
        return 0;
852
    }
853
    return pes;
854
}
855
856 8ee764b0 Baptiste Coudurier
static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
857
                         int *es_id, uint8_t **dec_config_descr,
858 798c6fac Baptiste Coudurier
                         int *dec_config_descr_size)
859
{
860
    ByteIOContext pb;
861
    int tag;
862
    unsigned len;
863
864
    init_put_byte(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
865
866
    len = ff_mp4_read_descr(s, &pb, &tag);
867
    if (tag == MP4IODescrTag) {
868
        get_be16(&pb); // ID
869
        get_byte(&pb);
870
        get_byte(&pb);
871
        get_byte(&pb);
872
        get_byte(&pb);
873
        get_byte(&pb);
874
        len = ff_mp4_read_descr(s, &pb, &tag);
875
        if (tag == MP4ESDescrTag) {
876
            *es_id = get_be16(&pb); /* ES_ID */
877
            dprintf(s, "ES_ID %#x\n", *es_id);
878
            get_byte(&pb); /* priority */
879
            len = ff_mp4_read_descr(s, &pb, &tag);
880
            if (tag == MP4DecConfigDescrTag) {
881
                *dec_config_descr = av_malloc(len);
882
                if (!*dec_config_descr)
883
                    return AVERROR(ENOMEM);
884
                *dec_config_descr_size = len;
885
                get_buffer(&pb, *dec_config_descr, len);
886
            }
887
        }
888
    }
889
    return 0;
890
}
891
892 4d9a577e Michael Niedermayer
static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
893 5dbafeb7 Fabrice Bellard
{
894 4d9a577e Michael Niedermayer
    MpegTSContext *ts = filter->u.section_filter.opaque;
895 5dbafeb7 Fabrice Bellard
    SectionHeader h1, *h = &h1;
896 c6ec28b1 Michael Niedermayer
    PESContext *pes;
897
    AVStream *st;
898
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
899
    int program_info_length, pcr_pid, pid, stream_type;
900
    int desc_list_len, desc_len, desc_tag;
901 ed68efad Baptiste Coudurier
    char language[4];
902 8430f3ec Baptiste Coudurier
    uint32_t prog_reg_desc = 0; /* registration descriptor */
903 798c6fac Baptiste Coudurier
    uint8_t *mp4_dec_config_descr = NULL;
904
    int mp4_dec_config_descr_len = 0;
905
    int mp4_es_id = 0;
906 115329f1 Diego Biurrun
907 ebcf352a Baptiste Coudurier
#ifdef DEBUG
908
    dprintf(ts->stream, "PMT: len %i\n", section_len);
909 750f0e1f Panagiotis Issaris
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
910 5dbafeb7 Fabrice Bellard
#endif
911 ebcf352a Baptiste Coudurier
912 5dbafeb7 Fabrice Bellard
    p_end = section + section_len - 4;
913
    p = section;
914
    if (parse_section_header(h, &p, p_end) < 0)
915
        return;
916 ebcf352a Baptiste Coudurier
917
    dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
918 2ddb79be Daniel Kristjansson
           h->id, h->sec_num, h->last_sec_num);
919 ebcf352a Baptiste Coudurier
920 90d13e30 Michael Niedermayer
    if (h->tid != PMT_TID)
921 5dbafeb7 Fabrice Bellard
        return;
922
923 172d1171 Nico Sabbi
    clear_program(ts, h->id);
924 5dbafeb7 Fabrice Bellard
    pcr_pid = get16(&p, p_end) & 0x1fff;
925
    if (pcr_pid < 0)
926
        return;
927 172d1171 Nico Sabbi
    add_pid_to_pmt(ts, h->id, pcr_pid);
928 ebcf352a Baptiste Coudurier
929
    dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
930
931 5dbafeb7 Fabrice Bellard
    program_info_length = get16(&p, p_end) & 0xfff;
932
    if (program_info_length < 0)
933
        return;
934 a45b40c4 Nico Sabbi
    while(program_info_length >= 2) {
935
        uint8_t tag, len;
936
        tag = get8(&p, p_end);
937
        len = get8(&p, p_end);
938 798c6fac Baptiste Coudurier
939
        dprintf(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
940
941 a45b40c4 Nico Sabbi
        if(len > program_info_length - 2)
942
            //something else is broken, exit the program_descriptors_loop
943
            break;
944
        program_info_length -= len + 2;
945 798c6fac Baptiste Coudurier
        if (tag == 0x1d) { // IOD descriptor
946
            get8(&p, p_end); // scope
947
            get8(&p, p_end); // label
948
            len -= 2;
949
            mp4_read_iods(ts->stream, p, len, &mp4_es_id,
950
                          &mp4_dec_config_descr, &mp4_dec_config_descr_len);
951
        } else if (tag == 0x05 && len >= 4) { // registration descriptor
952 8430f3ec Baptiste Coudurier
            prog_reg_desc = bytestream_get_le32(&p);
953 a45b40c4 Nico Sabbi
            len -= 4;
954
        }
955
        p += len;
956
    }
957 5dbafeb7 Fabrice Bellard
    p += program_info_length;
958
    if (p >= p_end)
959 175272cb Baptiste Coudurier
        goto out;
960 d46c84ea Baptiste Coudurier
961
    // stop parsing after pmt, we found header
962
    if (!ts->stream->nb_streams)
963
        ts->stop_parse = 1;
964
965 5dbafeb7 Fabrice Bellard
    for(;;) {
966 c6ec28b1 Michael Niedermayer
        st = 0;
967 5dbafeb7 Fabrice Bellard
        stream_type = get8(&p, p_end);
968
        if (stream_type < 0)
969
            break;
970
        pid = get16(&p, p_end) & 0x1fff;
971
        if (pid < 0)
972
            break;
973 f42d1d82 Baptiste Coudurier
974
        /* now create ffmpeg stream */
975
        if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
976
            pes = ts->pids[pid]->u.pes_filter.opaque;
977
            st = pes->st;
978
        } else {
979
            if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
980 b3f9f7a3 Baptiste Coudurier
            pes = add_pes_stream(ts, pid, pcr_pid);
981 f42d1d82 Baptiste Coudurier
            if (pes)
982 b3f9f7a3 Baptiste Coudurier
                st = av_new_stream(pes->stream, pes->pid);
983 f42d1d82 Baptiste Coudurier
        }
984
985
        if (!st)
986 175272cb Baptiste Coudurier
            goto out;
987 f42d1d82 Baptiste Coudurier
988 b3f9f7a3 Baptiste Coudurier
        if (!pes->stream_type)
989
            mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
990
991 f42d1d82 Baptiste Coudurier
        add_pid_to_pmt(ts, h->id, pid);
992
993 588af13f Aurelien Jacobs
        ff_program_add_stream_index(ts->stream, h->id, st->index);
994 f42d1d82 Baptiste Coudurier
995 c6ec28b1 Michael Niedermayer
        desc_list_len = get16(&p, p_end) & 0xfff;
996
        if (desc_list_len < 0)
997
            break;
998
        desc_list_end = p + desc_list_len;
999 a4d2af9b Björn Axelsson
        if (desc_list_end > p_end)
1000 5dbafeb7 Fabrice Bellard
            break;
1001 c6ec28b1 Michael Niedermayer
        for(;;) {
1002
            desc_tag = get8(&p, desc_list_end);
1003
            if (desc_tag < 0)
1004
                break;
1005
            desc_len = get8(&p, desc_list_end);
1006 a4d2af9b Björn Axelsson
            if (desc_len < 0)
1007
                break;
1008 c6ec28b1 Michael Niedermayer
            desc_end = p + desc_len;
1009
            if (desc_end > desc_list_end)
1010
                break;
1011 ebcf352a Baptiste Coudurier
1012
            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
1013 2ddb79be Daniel Kristjansson
                   desc_tag, desc_len);
1014 ebcf352a Baptiste Coudurier
1015 d23612ef Baptiste Coudurier
            if (st->codec->codec_id == CODEC_ID_NONE &&
1016 6a2a50f8 Baptiste Coudurier
                stream_type == STREAM_TYPE_PRIVATE_DATA)
1017
                mpegts_find_stream_type(st, desc_tag, DESC_types);
1018
1019 c6ec28b1 Michael Niedermayer
            switch(desc_tag) {
1020 798c6fac Baptiste Coudurier
            case 0x1F: /* FMC descriptor */
1021
                get16(&p, desc_end);
1022
                if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
1023
                    mp4_dec_config_descr_len && mp4_es_id == pid) {
1024
                    ByteIOContext pb;
1025
                    init_put_byte(&pb, mp4_dec_config_descr,
1026
                                  mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1027
                    ff_mp4_read_dec_config_descr(ts->stream, st, &pb);
1028
                    if (st->codec->codec_id == CODEC_ID_AAC &&
1029
                        st->codec->extradata_size > 0)
1030
                        st->need_parsing = 0;
1031
                }
1032
                break;
1033 e58992e4 Francesco Lavra
            case 0x56: /* DVB teletext descriptor */
1034
                language[0] = get8(&p, desc_end);
1035
                language[1] = get8(&p, desc_end);
1036
                language[2] = get8(&p, desc_end);
1037
                language[3] = 0;
1038 2ef6c124 Stefano Sabatini
                av_metadata_set2(&st->metadata, "language", language, 0);
1039 e58992e4 Francesco Lavra
                break;
1040 2fef7b53 Baptiste Coudurier
            case 0x59: /* subtitling descriptor */
1041 c6ec28b1 Michael Niedermayer
                language[0] = get8(&p, desc_end);
1042
                language[1] = get8(&p, desc_end);
1043
                language[2] = get8(&p, desc_end);
1044
                language[3] = 0;
1045
                get8(&p, desc_end);
1046 b834becd Reimar Döffinger
                if (st->codec->extradata) {
1047
                    if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, p, 4))
1048
                        av_log_ask_for_sample(ts->stream, "DVB sub with multiple IDs\n");
1049
                } else {
1050
                    st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
1051
                    if (st->codec->extradata) {
1052
                        st->codec->extradata_size = 4;
1053
                        memcpy(st->codec->extradata, p, 4);
1054
                    }
1055
                }
1056
                p += 4;
1057 2ef6c124 Stefano Sabatini
                av_metadata_set2(&st->metadata, "language", language, 0);
1058 c6ec28b1 Michael Niedermayer
                break;
1059
            case 0x0a: /* ISO 639 language descriptor */
1060
                language[0] = get8(&p, desc_end);
1061
                language[1] = get8(&p, desc_end);
1062
                language[2] = get8(&p, desc_end);
1063
                language[3] = 0;
1064 2ef6c124 Stefano Sabatini
                av_metadata_set2(&st->metadata, "language", language, 0);
1065 c6ec28b1 Michael Niedermayer
                break;
1066 2fef7b53 Baptiste Coudurier
            case 0x05: /* registration descriptor */
1067 5b3c4c8a Baptiste Coudurier
                st->codec->codec_tag = bytestream_get_le32(&p);
1068 1f076543 Baptiste Coudurier
                dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1069 d23612ef Baptiste Coudurier
                if (st->codec->codec_id == CODEC_ID_NONE &&
1070 f42d1d82 Baptiste Coudurier
                    stream_type == STREAM_TYPE_PRIVATE_DATA)
1071 5b3c4c8a Baptiste Coudurier
                    mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1072 4f1db48e Baptiste Coudurier
                break;
1073 c6ec28b1 Michael Niedermayer
            default:
1074
                break;
1075
            }
1076
            p = desc_end;
1077 63380b5e Ian Caulfield
1078
            if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1079 588af13f Aurelien Jacobs
                ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1080 63380b5e Ian Caulfield
                pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1081
            }
1082 c6ec28b1 Michael Niedermayer
        }
1083
        p = desc_list_end;
1084 5dbafeb7 Fabrice Bellard
    }
1085 175272cb Baptiste Coudurier
1086
 out:
1087
    av_free(mp4_dec_config_descr);
1088 5dbafeb7 Fabrice Bellard
}
1089
1090 4d9a577e Michael Niedermayer
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1091 5dbafeb7 Fabrice Bellard
{
1092 4d9a577e Michael Niedermayer
    MpegTSContext *ts = filter->u.section_filter.opaque;
1093 5dbafeb7 Fabrice Bellard
    SectionHeader h1, *h = &h1;
1094
    const uint8_t *p, *p_end;
1095
    int sid, pmt_pid;
1096
1097 ebcf352a Baptiste Coudurier
#ifdef DEBUG
1098
    dprintf(ts->stream, "PAT:\n");
1099 750f0e1f Panagiotis Issaris
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1100 5dbafeb7 Fabrice Bellard
#endif
1101
    p_end = section + section_len - 4;
1102
    p = section;
1103
    if (parse_section_header(h, &p, p_end) < 0)
1104
        return;
1105
    if (h->tid != PAT_TID)
1106
        return;
1107
1108 172d1171 Nico Sabbi
    clear_programs(ts);
1109 5dbafeb7 Fabrice Bellard
    for(;;) {
1110
        sid = get16(&p, p_end);
1111
        if (sid < 0)
1112
            break;
1113
        pmt_pid = get16(&p, p_end) & 0x1fff;
1114
        if (pmt_pid < 0)
1115
            break;
1116 ebcf352a Baptiste Coudurier
1117
        dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1118
1119 5dbafeb7 Fabrice Bellard
        if (sid == 0x0000) {
1120
            /* NIT info */
1121
        } else {
1122 1d257254 Nico Sabbi
            av_new_program(ts->stream, sid);
1123 b795ff97 Baptiste Coudurier
            if (ts->pids[pmt_pid])
1124
                mpegts_close_filter(ts, ts->pids[pmt_pid]);
1125 28f03d04 Michael Niedermayer
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1126 172d1171 Nico Sabbi
            add_pat_entry(ts, sid);
1127
            add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1128
            add_pid_to_pmt(ts, sid, pmt_pid);
1129 5dbafeb7 Fabrice Bellard
        }
1130
    }
1131
}
1132
1133 4d9a577e Michael Niedermayer
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1134 5dbafeb7 Fabrice Bellard
{
1135 4d9a577e Michael Niedermayer
    MpegTSContext *ts = filter->u.section_filter.opaque;
1136 5dbafeb7 Fabrice Bellard
    SectionHeader h1, *h = &h1;
1137
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1138
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1139
    char *name, *provider_name;
1140
1141 ebcf352a Baptiste Coudurier
#ifdef DEBUG
1142
    dprintf(ts->stream, "SDT:\n");
1143 750f0e1f Panagiotis Issaris
    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1144 5dbafeb7 Fabrice Bellard
#endif
1145
1146
    p_end = section + section_len - 4;
1147
    p = section;
1148
    if (parse_section_header(h, &p, p_end) < 0)
1149
        return;
1150
    if (h->tid != SDT_TID)
1151
        return;
1152
    onid = get16(&p, p_end);
1153
    if (onid < 0)
1154
        return;
1155
    val = get8(&p, p_end);
1156
    if (val < 0)
1157
        return;
1158
    for(;;) {
1159
        sid = get16(&p, p_end);
1160
        if (sid < 0)
1161
            break;
1162
        val = get8(&p, p_end);
1163
        if (val < 0)
1164
            break;
1165
        desc_list_len = get16(&p, p_end) & 0xfff;
1166
        if (desc_list_len < 0)
1167
            break;
1168
        desc_list_end = p + desc_list_len;
1169
        if (desc_list_end > p_end)
1170
            break;
1171
        for(;;) {
1172
            desc_tag = get8(&p, desc_list_end);
1173
            if (desc_tag < 0)
1174
                break;
1175
            desc_len = get8(&p, desc_list_end);
1176
            desc_end = p + desc_len;
1177
            if (desc_end > desc_list_end)
1178
                break;
1179 ebcf352a Baptiste Coudurier
1180
            dprintf(ts->stream, "tag: 0x%02x len=%d\n",
1181 2ddb79be Daniel Kristjansson
                   desc_tag, desc_len);
1182 ebcf352a Baptiste Coudurier
1183 5dbafeb7 Fabrice Bellard
            switch(desc_tag) {
1184
            case 0x48:
1185
                service_type = get8(&p, p_end);
1186
                if (service_type < 0)
1187
                    break;
1188
                provider_name = getstr8(&p, p_end);
1189
                if (!provider_name)
1190
                    break;
1191
                name = getstr8(&p, p_end);
1192 1d257254 Nico Sabbi
                if (name) {
1193
                    AVProgram *program = av_new_program(ts->stream, sid);
1194 08681191 Aurelien Jacobs
                    if(program) {
1195 2ef6c124 Stefano Sabatini
                        av_metadata_set2(&program->metadata, "name", name, 0);
1196
                        av_metadata_set2(&program->metadata, "provider_name", provider_name, 0);
1197 08681191 Aurelien Jacobs
                    }
1198 1d257254 Nico Sabbi
                }
1199 81d5ae6d Michael Niedermayer
                av_free(name);
1200
                av_free(provider_name);
1201 5dbafeb7 Fabrice Bellard
                break;
1202
            default:
1203
                break;
1204
            }
1205
            p = desc_end;
1206
        }
1207
        p = desc_list_end;
1208
    }
1209
}
1210
1211
/* handle one TS packet */
1212 bdfa9824 Baptiste Coudurier
static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1213 fe9cf0d4 Fabrice Bellard
{
1214 b45a7a18 Fabrice Bellard
    AVFormatContext *s = ts->stream;
1215 5dbafeb7 Fabrice Bellard
    MpegTSFilter *tss;
1216
    int len, pid, cc, cc_ok, afc, is_start;
1217
    const uint8_t *p, *p_end;
1218 4c6b49bf Ivan Schreter
    int64_t pos;
1219 5dbafeb7 Fabrice Bellard
1220 80fb8234 Ronald S. Bultje
    pid = AV_RB16(packet + 1) & 0x1fff;
1221 172d1171 Nico Sabbi
    if(pid && discard_pid(ts, pid))
1222 bdfa9824 Baptiste Coudurier
        return 0;
1223 5dbafeb7 Fabrice Bellard
    is_start = packet[1] & 0x40;
1224
    tss = ts->pids[pid];
1225
    if (ts->auto_guess && tss == NULL && is_start) {
1226 b3f9f7a3 Baptiste Coudurier
        add_pes_stream(ts, pid, -1);
1227 5dbafeb7 Fabrice Bellard
        tss = ts->pids[pid];
1228
    }
1229
    if (!tss)
1230 bdfa9824 Baptiste Coudurier
        return 0;
1231 5dbafeb7 Fabrice Bellard
1232
    /* continuity check (currently not used) */
1233
    cc = (packet[3] & 0xf);
1234
    cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1235
    tss->last_cc = cc;
1236 115329f1 Diego Biurrun
1237 5dbafeb7 Fabrice Bellard
    /* skip adaptation field */
1238
    afc = (packet[3] >> 4) & 3;
1239
    p = packet + 4;
1240
    if (afc == 0) /* reserved value */
1241 bdfa9824 Baptiste Coudurier
        return 0;
1242 5dbafeb7 Fabrice Bellard
    if (afc == 2) /* adaptation field only */
1243 bdfa9824 Baptiste Coudurier
        return 0;
1244 5dbafeb7 Fabrice Bellard
    if (afc == 3) {
1245
        /* skip adapation field */
1246
        p += p[0] + 1;
1247
    }
1248
    /* if past the end of packet, ignore */
1249
    p_end = packet + TS_PACKET_SIZE;
1250
    if (p >= p_end)
1251 bdfa9824 Baptiste Coudurier
        return 0;
1252 115329f1 Diego Biurrun
1253 4c6b49bf Ivan Schreter
    pos = url_ftell(ts->stream->pb);
1254
    ts->pos47= pos % ts->raw_packet_size;
1255 5fd63f3c Michael Niedermayer
1256 5dbafeb7 Fabrice Bellard
    if (tss->type == MPEGTS_SECTION) {
1257
        if (is_start) {
1258
            /* pointer field present */
1259
            len = *p++;
1260
            if (p + len > p_end)
1261 bdfa9824 Baptiste Coudurier
                return 0;
1262 5dbafeb7 Fabrice Bellard
            if (len && cc_ok) {
1263 27bb1ed3 Wolfram Gloger
                /* write remaining section bytes */
1264 115329f1 Diego Biurrun
                write_section_data(s, tss,
1265 5dbafeb7 Fabrice Bellard
                                   p, len, 0);
1266 27bb1ed3 Wolfram Gloger
                /* check whether filter has been closed */
1267
                if (!ts->pids[pid])
1268 bdfa9824 Baptiste Coudurier
                    return 0;
1269 5dbafeb7 Fabrice Bellard
            }
1270
            p += len;
1271
            if (p < p_end) {
1272 115329f1 Diego Biurrun
                write_section_data(s, tss,
1273 5dbafeb7 Fabrice Bellard
                                   p, p_end - p, 1);
1274
            }
1275
        } else {
1276
            if (cc_ok) {
1277 115329f1 Diego Biurrun
                write_section_data(s, tss,
1278 5dbafeb7 Fabrice Bellard
                                   p, p_end - p, 0);
1279 fc48fe84 Fabrice Bellard
            }
1280 5dbafeb7 Fabrice Bellard
        }
1281
    } else {
1282 bdfa9824 Baptiste Coudurier
        int ret;
1283 4c6b49bf Ivan Schreter
        // Note: The position here points actually behind the current packet.
1284 bdfa9824 Baptiste Coudurier
        if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1285
                                            pos - ts->raw_packet_size)) < 0)
1286
            return ret;
1287 5dbafeb7 Fabrice Bellard
    }
1288 bdfa9824 Baptiste Coudurier
1289
    return 0;
1290 5dbafeb7 Fabrice Bellard
}
1291
1292 fc48fe84 Fabrice Bellard
/* XXX: try to find a better synchro over several packets (use
1293
   get_packet_size() ?) */
1294 1303d62d Baptiste Coudurier
static int mpegts_resync(AVFormatContext *s)
1295 fc48fe84 Fabrice Bellard
{
1296 1303d62d Baptiste Coudurier
    ByteIOContext *pb = s->pb;
1297 fc48fe84 Fabrice Bellard
    int c, i;
1298
1299
    for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1300
        c = url_fgetc(pb);
1301
        if (c < 0)
1302
            return -1;
1303
        if (c == 0x47) {
1304
            url_fseek(pb, -1, SEEK_CUR);
1305
            return 0;
1306
        }
1307
    }
1308 1303d62d Baptiste Coudurier
    av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1309 fc48fe84 Fabrice Bellard
    /* no sync found */
1310
    return -1;
1311
}
1312
1313 b45a7a18 Fabrice Bellard
/* return -1 if error or EOF. Return 0 if OK. */
1314 1303d62d Baptiste Coudurier
static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1315 5dbafeb7 Fabrice Bellard
{
1316 1303d62d Baptiste Coudurier
    ByteIOContext *pb = s->pb;
1317 b45a7a18 Fabrice Bellard
    int skip, len;
1318
1319
    for(;;) {
1320
        len = get_buffer(pb, buf, TS_PACKET_SIZE);
1321
        if (len != TS_PACKET_SIZE)
1322 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
1323 b45a7a18 Fabrice Bellard
        /* check paquet sync byte */
1324
        if (buf[0] != 0x47) {
1325
            /* find a new packet start */
1326
            url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1327 1303d62d Baptiste Coudurier
            if (mpegts_resync(s) < 0)
1328
                return AVERROR(EAGAIN);
1329 b45a7a18 Fabrice Bellard
            else
1330
                continue;
1331
        } else {
1332
            skip = raw_packet_size - TS_PACKET_SIZE;
1333
            if (skip > 0)
1334
                url_fskip(pb, skip);
1335
            break;
1336
        }
1337
    }
1338
    return 0;
1339
}
1340
1341
static int handle_packets(MpegTSContext *ts, int nb_packets)
1342
{
1343
    AVFormatContext *s = ts->stream;
1344
    uint8_t packet[TS_PACKET_SIZE];
1345
    int packet_num, ret;
1346 5dbafeb7 Fabrice Bellard
1347
    ts->stop_parse = 0;
1348
    packet_num = 0;
1349 fe9cf0d4 Fabrice Bellard
    for(;;) {
1350 90d13e30 Michael Niedermayer
        if (ts->stop_parse>0)
1351 5dbafeb7 Fabrice Bellard
            break;
1352
        packet_num++;
1353
        if (nb_packets != 0 && packet_num >= nb_packets)
1354
            break;
1355 1303d62d Baptiste Coudurier
        ret = read_packet(s, packet, ts->raw_packet_size);
1356 b45a7a18 Fabrice Bellard
        if (ret != 0)
1357
            return ret;
1358 bdfa9824 Baptiste Coudurier
        ret = handle_packet(ts, packet);
1359
        if (ret != 0)
1360
            return ret;
1361 5dbafeb7 Fabrice Bellard
    }
1362
    return 0;
1363
}
1364 fe9cf0d4 Fabrice Bellard
1365 5dbafeb7 Fabrice Bellard
static int mpegts_probe(AVProbeData *p)
1366
{
1367 fc48fe84 Fabrice Bellard
#if 1
1368 a0b8f70c Michael Niedermayer
    const int size= p->buf_size;
1369 5d4d67e0 Nico Sabbi
    int score, fec_score, dvhs_score;
1370 1558d0b9 Michael Niedermayer
    int check_count= size / TS_FEC_PACKET_SIZE;
1371 a0b8f70c Michael Niedermayer
#define CHECK_COUNT 10
1372 115329f1 Diego Biurrun
1373 1558d0b9 Michael Niedermayer
    if (check_count < CHECK_COUNT)
1374 a0b8f70c Michael Niedermayer
        return -1;
1375 115329f1 Diego Biurrun
1376 1558d0b9 Michael Niedermayer
    score     = analyze(p->buf, TS_PACKET_SIZE     *check_count, TS_PACKET_SIZE     , NULL)*CHECK_COUNT/check_count;
1377
    dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1378
    fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1379 5d4d67e0 Nico Sabbi
//    av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1380 115329f1 Diego Biurrun
1381 a0b8f70c Michael Niedermayer
// we need a clear definition for the returned score otherwise things will become messy sooner or later
1382 5d4d67e0 Nico Sabbi
    if     (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score     - CHECK_COUNT;
1383
    else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score  - CHECK_COUNT;
1384 a0b8f70c Michael Niedermayer
    else if(                 fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1385
    else                                    return -1;
1386 fc48fe84 Fabrice Bellard
#else
1387
    /* only use the extension for safer guess */
1388 4837bb52 Stefano Sabatini
    if (av_match_ext(p->filename, "ts"))
1389 fc48fe84 Fabrice Bellard
        return AVPROBE_SCORE_MAX;
1390
    else
1391
        return 0;
1392
#endif
1393 5dbafeb7 Fabrice Bellard
}
1394
1395 910f02a0 Diego Biurrun
/* return the 90kHz PCR and the extension for the 27MHz PCR. return
1396 b45a7a18 Fabrice Bellard
   (-1) if not available */
1397 115329f1 Diego Biurrun
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1398 b45a7a18 Fabrice Bellard
                     const uint8_t *packet)
1399
{
1400
    int afc, len, flags;
1401
    const uint8_t *p;
1402
    unsigned int v;
1403
1404
    afc = (packet[3] >> 4) & 3;
1405
    if (afc <= 1)
1406
        return -1;
1407
    p = packet + 4;
1408
    len = p[0];
1409
    p++;
1410
    if (len == 0)
1411
        return -1;
1412
    flags = *p++;
1413
    len--;
1414
    if (!(flags & 0x10))
1415
        return -1;
1416
    if (len < 6)
1417
        return -1;
1418 80fb8234 Ronald S. Bultje
    v = AV_RB32(p);
1419 b45a7a18 Fabrice Bellard
    *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1420
    *ppcr_low = ((p[4] & 1) << 8) | p[5];
1421
    return 0;
1422
}
1423
1424 5dbafeb7 Fabrice Bellard
static int mpegts_read_header(AVFormatContext *s,
1425
                              AVFormatParameters *ap)
1426
{
1427
    MpegTSContext *ts = s->priv_data;
1428 899681cd Björn Axelsson
    ByteIOContext *pb = s->pb;
1429 1558d0b9 Michael Niedermayer
    uint8_t buf[5*1024];
1430 4dc8a963 Michael Niedermayer
    int len;
1431 5dbafeb7 Fabrice Bellard
    int64_t pos;
1432 e05655fb Michael Niedermayer
1433 b45a7a18 Fabrice Bellard
    if (ap) {
1434
        ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1435 38c48be2 Michael Niedermayer
        if(ap->mpeg2ts_raw){
1436
            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1437
            return -1;
1438
        }
1439 b45a7a18 Fabrice Bellard
    }
1440
1441 5dbafeb7 Fabrice Bellard
    /* read the first 1024 bytes to get packet size */
1442
    pos = url_ftell(pb);
1443
    len = get_buffer(pb, buf, sizeof(buf));
1444
    if (len != sizeof(buf))
1445
        goto fail;
1446
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1447
    if (ts->raw_packet_size <= 0)
1448
        goto fail;
1449 b45a7a18 Fabrice Bellard
    ts->stream = s;
1450 5dbafeb7 Fabrice Bellard
    ts->auto_guess = 0;
1451
1452 38c48be2 Michael Niedermayer
    if (s->iformat == &mpegts_demuxer) {
1453 b45a7a18 Fabrice Bellard
        /* normal demux */
1454 fc48fe84 Fabrice Bellard
1455 a45ec414 Benoit Fouet
        /* first do a scaning to get all the services */
1456 8dd25c52 Martin Storsjö
        if (url_fseek(pb, pos, SEEK_SET) < 0)
1457
            av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1458 c950c25a Baptiste Coudurier
1459
        mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1460 115329f1 Diego Biurrun
1461 7b9677f6 Baptiste Coudurier
        mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1462 115329f1 Diego Biurrun
1463 45a49840 Baptiste Coudurier
        handle_packets(ts, s->probesize / ts->raw_packet_size);
1464 a45ec414 Benoit Fouet
        /* if could not find service, enable auto_guess */
1465 115329f1 Diego Biurrun
1466 a45ec414 Benoit Fouet
        ts->auto_guess = 1;
1467 115329f1 Diego Biurrun
1468 ebcf352a Baptiste Coudurier
        dprintf(ts->stream, "tuning done\n");
1469
1470 b45a7a18 Fabrice Bellard
        s->ctx_flags |= AVFMTCTX_NOHEADER;
1471
    } else {
1472
        AVStream *st;
1473
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1474
        int64_t pcrs[2], pcr_h;
1475
        int packet_count[2];
1476
        uint8_t packet[TS_PACKET_SIZE];
1477 115329f1 Diego Biurrun
1478 b45a7a18 Fabrice Bellard
        /* only read packets */
1479 115329f1 Diego Biurrun
1480 b45a7a18 Fabrice Bellard
        st = av_new_stream(s, 0);
1481
        if (!st)
1482
            goto fail;
1483 9ee91c2f Michael Niedermayer
        av_set_pts_info(st, 60, 1, 27000000);
1484 72415b2a Stefano Sabatini
        st->codec->codec_type = AVMEDIA_TYPE_DATA;
1485 01f4895c Michael Niedermayer
        st->codec->codec_id = CODEC_ID_MPEG2TS;
1486 115329f1 Diego Biurrun
1487 b45a7a18 Fabrice Bellard
        /* we iterate until we find two PCRs to estimate the bitrate */
1488
        pcr_pid = -1;
1489
        nb_pcrs = 0;
1490
        nb_packets = 0;
1491
        for(;;) {
1492 1303d62d Baptiste Coudurier
            ret = read_packet(s, packet, ts->raw_packet_size);
1493 b45a7a18 Fabrice Bellard
            if (ret < 0)
1494
                return -1;
1495 80fb8234 Ronald S. Bultje
            pid = AV_RB16(packet + 1) & 0x1fff;
1496 b45a7a18 Fabrice Bellard
            if ((pcr_pid == -1 || pcr_pid == pid) &&
1497
                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1498
                pcr_pid = pid;
1499
                packet_count[nb_pcrs] = nb_packets;
1500
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1501
                nb_pcrs++;
1502
                if (nb_pcrs >= 2)
1503
                    break;
1504
            }
1505
            nb_packets++;
1506
        }
1507 5dbafeb7 Fabrice Bellard
1508 b45a7a18 Fabrice Bellard
        /* NOTE1: the bitrate is computed without the FEC */
1509
        /* NOTE2: it is only the bitrate of the start of the stream */
1510
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1511
        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1512
        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1513 01f4895c Michael Niedermayer
        st->codec->bit_rate = s->bit_rate;
1514 c0df9d75 Michael Niedermayer
        st->start_time = ts->cur_pcr;
1515 b45a7a18 Fabrice Bellard
#if 0
1516 f0ee3ea6 Michel Bardiaux
        av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1517 b45a7a18 Fabrice Bellard
               st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1518 5dbafeb7 Fabrice Bellard
#endif
1519 fe9cf0d4 Fabrice Bellard
    }
1520 5dbafeb7 Fabrice Bellard
1521
    url_fseek(pb, pos, SEEK_SET);
1522 fe9cf0d4 Fabrice Bellard
    return 0;
1523 5dbafeb7 Fabrice Bellard
 fail:
1524
    return -1;
1525
}
1526
1527 b45a7a18 Fabrice Bellard
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1528
1529
static int mpegts_raw_read_packet(AVFormatContext *s,
1530
                                  AVPacket *pkt)
1531
{
1532
    MpegTSContext *ts = s->priv_data;
1533
    int ret, i;
1534
    int64_t pcr_h, next_pcr_h, pos;
1535
    int pcr_l, next_pcr_l;
1536
    uint8_t pcr_buf[12];
1537
1538
    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1539 8fa36ae0 François Revol
        return AVERROR(ENOMEM);
1540 899681cd Björn Axelsson
    pkt->pos= url_ftell(s->pb);
1541 1303d62d Baptiste Coudurier
    ret = read_packet(s, pkt->data, ts->raw_packet_size);
1542 b45a7a18 Fabrice Bellard
    if (ret < 0) {
1543
        av_free_packet(pkt);
1544
        return ret;
1545
    }
1546
    if (ts->mpeg2ts_compute_pcr) {
1547
        /* compute exact PCR for each packet */
1548
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1549
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1550 899681cd Björn Axelsson
            pos = url_ftell(s->pb);
1551 b45a7a18 Fabrice Bellard
            for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1552 899681cd Björn Axelsson
                url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1553
                get_buffer(s->pb, pcr_buf, 12);
1554 b45a7a18 Fabrice Bellard
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1555
                    /* XXX: not precise enough */
1556 115329f1 Diego Biurrun
                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1557 b45a7a18 Fabrice Bellard
                        (i + 1);
1558
                    break;
1559
                }
1560
            }
1561 899681cd Björn Axelsson
            url_fseek(s->pb, pos, SEEK_SET);
1562 b45a7a18 Fabrice Bellard
            /* no next PCR found: we use previous increment */
1563
            ts->cur_pcr = pcr_h * 300 + pcr_l;
1564
        }
1565
        pkt->pts = ts->cur_pcr;
1566
        pkt->duration = ts->pcr_incr;
1567
        ts->cur_pcr += ts->pcr_incr;
1568
    }
1569
    pkt->stream_index = 0;
1570
    return 0;
1571
}
1572
1573 5dbafeb7 Fabrice Bellard
static int mpegts_read_packet(AVFormatContext *s,
1574
                              AVPacket *pkt)
1575
{
1576
    MpegTSContext *ts = s->priv_data;
1577 0c137557 Baptiste Coudurier
    int ret, i;
1578
1579
    if (url_ftell(s->pb) != ts->last_pos) {
1580
        /* seek detected, flush pes buffer */
1581
        for (i = 0; i < NB_PID_MAX; i++) {
1582
            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1583
                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1584
                av_freep(&pes->buffer);
1585
                pes->data_index = 0;
1586
                pes->state = MPEGTS_SKIP; /* skip until pes header */
1587
            }
1588
        }
1589
    }
1590 b45a7a18 Fabrice Bellard
1591 38c48be2 Michael Niedermayer
    ts->pkt = pkt;
1592 0c137557 Baptiste Coudurier
    ret = handle_packets(ts, 0);
1593
    if (ret < 0) {
1594
        /* flush pes data left */
1595
        for (i = 0; i < NB_PID_MAX; i++) {
1596
            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1597
                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1598
                if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1599
                    new_pes_packet(pes, pkt);
1600 8956f680 Baptiste Coudurier
                    pes->state = MPEGTS_SKIP;
1601 0c137557 Baptiste Coudurier
                    ret = 0;
1602
                    break;
1603
                }
1604
            }
1605
        }
1606
    }
1607
1608
    ts->last_pos = url_ftell(s->pb);
1609
1610
    return ret;
1611 fe9cf0d4 Fabrice Bellard
}
1612
1613
static int mpegts_read_close(AVFormatContext *s)
1614
{
1615
    MpegTSContext *ts = s->priv_data;
1616
    int i;
1617 81d5ae6d Michael Niedermayer
1618
    clear_programs(ts);
1619
1620 fe9cf0d4 Fabrice Bellard
    for(i=0;i<NB_PID_MAX;i++)
1621 ec7d0d2e Gildas Bazin
        if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1622 00a6b92b Måns Rullgård
1623 fe9cf0d4 Fabrice Bellard
    return 0;
1624
}
1625
1626 115329f1 Diego Biurrun
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1627 cdd5034f Michael Niedermayer
                              int64_t *ppos, int64_t pos_limit)
1628 27f388aa Fabrice Bellard
{
1629
    MpegTSContext *ts = s->priv_data;
1630
    int64_t pos, timestamp;
1631
    uint8_t buf[TS_PACKET_SIZE];
1632 dbf6b678 Michael Niedermayer
    int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1633 cdd5034f Michael Niedermayer
    const int find_next= 1;
1634 5fd63f3c Michael Niedermayer
    pos = ((*ppos  + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1635 27f388aa Fabrice Bellard
    if (find_next) {
1636
        for(;;) {
1637 899681cd Björn Axelsson
            url_fseek(s->pb, pos, SEEK_SET);
1638
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1639 27f388aa Fabrice Bellard
                return AV_NOPTS_VALUE;
1640 80fb8234 Ronald S. Bultje
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1641 27f388aa Fabrice Bellard
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1642
                break;
1643
            }
1644
            pos += ts->raw_packet_size;
1645
        }
1646
    } else {
1647
        for(;;) {
1648
            pos -= ts->raw_packet_size;
1649
            if (pos < 0)
1650
                return AV_NOPTS_VALUE;
1651 899681cd Björn Axelsson
            url_fseek(s->pb, pos, SEEK_SET);
1652
            if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1653 27f388aa Fabrice Bellard
                return AV_NOPTS_VALUE;
1654 80fb8234 Ronald S. Bultje
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1655 27f388aa Fabrice Bellard
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
1656
                break;
1657
            }
1658
        }
1659
    }
1660
    *ppos = pos;
1661
1662 cdd5034f Michael Niedermayer
    return timestamp;
1663 27f388aa Fabrice Bellard
}
1664
1665 af8aae3f Ivan Schreter
#ifdef USE_SYNCPOINT_SEARCH
1666
1667 608be2ac Ivan Schreter
static int read_seek2(AVFormatContext *s,
1668
                      int stream_index,
1669
                      int64_t min_ts,
1670
                      int64_t target_ts,
1671
                      int64_t max_ts,
1672
                      int flags)
1673 a8dd8dc6 Ivan Schreter
{
1674 e05655fb Michael Niedermayer
    int64_t pos;
1675
1676 a8dd8dc6 Ivan Schreter
    int64_t ts_ret, ts_adj;
1677
    int stream_index_gen_search;
1678
    AVStream *st;
1679
    AVParserState *backup;
1680 e05655fb Michael Niedermayer
1681 a8dd8dc6 Ivan Schreter
    backup = ff_store_parser_state(s);
1682 e05655fb Michael Niedermayer
1683 a8dd8dc6 Ivan Schreter
    // detect direction of seeking for search purposes
1684 608be2ac Ivan Schreter
    flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
1685
             AVSEEK_FLAG_BACKWARD : 0;
1686 a8dd8dc6 Ivan Schreter
1687
    if (flags & AVSEEK_FLAG_BYTE) {
1688 608be2ac Ivan Schreter
        // use position directly, we will search starting from it
1689 a8dd8dc6 Ivan Schreter
        pos = target_ts;
1690
    } else {
1691 608be2ac Ivan Schreter
        // search for some position with good timestamp match
1692
        if (stream_index < 0) {
1693 a8dd8dc6 Ivan Schreter
            stream_index_gen_search = av_find_default_stream_index(s);
1694
            if (stream_index_gen_search < 0) {
1695
                ff_restore_parser_state(s, backup);
1696
                return -1;
1697
            }
1698
1699
            st = s->streams[stream_index_gen_search];
1700 608be2ac Ivan Schreter
            // timestamp for default must be expressed in AV_TIME_BASE units
1701
            ts_adj = av_rescale(target_ts,
1702
                                st->time_base.den,
1703
                                AV_TIME_BASE * (int64_t)st->time_base.num);
1704 a8dd8dc6 Ivan Schreter
        } else {
1705
            ts_adj = target_ts;
1706
            stream_index_gen_search = stream_index;
1707
        }
1708
        pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1709
                            0, INT64_MAX, -1,
1710
                            AV_NOPTS_VALUE,
1711
                            AV_NOPTS_VALUE,
1712
                            flags, &ts_ret, mpegts_get_pcr);
1713
        if (pos < 0) {
1714
            ff_restore_parser_state(s, backup);
1715 e05655fb Michael Niedermayer
            return -1;
1716 a8dd8dc6 Ivan Schreter
        }
1717 115329f1 Diego Biurrun
    }
1718 e05655fb Michael Niedermayer
1719 608be2ac Ivan Schreter
    // search for actual matching keyframe/starting position for all streams
1720
    if (ff_gen_syncpoint_search(s, stream_index, pos,
1721
                                min_ts, target_ts, max_ts,
1722
                                flags) < 0) {
1723 a8dd8dc6 Ivan Schreter
        ff_restore_parser_state(s, backup);
1724
        return -1;
1725
    }
1726
1727
    ff_free_parser_state(s, backup);
1728 e05655fb Michael Niedermayer
    return 0;
1729
}
1730
1731 a8dd8dc6 Ivan Schreter
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1732
{
1733
    int ret;
1734
    if (flags & AVSEEK_FLAG_BACKWARD) {
1735 608be2ac Ivan Schreter
        flags &= ~AVSEEK_FLAG_BACKWARD;
1736
        ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
1737
        if (ret < 0)
1738
            // for compatibility reasons, seek to the best-fitting timestamp
1739
            ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1740 a8dd8dc6 Ivan Schreter
    } else {
1741
        ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1742 608be2ac Ivan Schreter
        if (ret < 0)
1743
            // for compatibility reasons, seek to the best-fitting timestamp
1744 a8dd8dc6 Ivan Schreter
            ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1745
    }
1746
    return ret;
1747
}
1748
1749 af8aae3f Ivan Schreter
#else
1750
1751
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1752
    MpegTSContext *ts = s->priv_data;
1753
    uint8_t buf[TS_PACKET_SIZE];
1754
    int64_t pos;
1755
1756
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1757
        return -1;
1758
1759
    pos= url_ftell(s->pb);
1760
1761
    for(;;) {
1762
        url_fseek(s->pb, pos, SEEK_SET);
1763
        if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1764
            return -1;
1765
//        pid = AV_RB16(buf + 1) & 0x1fff;
1766
        if(buf[1] & 0x40) break;
1767
        pos += ts->raw_packet_size;
1768
    }
1769
    url_fseek(s->pb, pos, SEEK_SET);
1770
1771
    return 0;
1772
}
1773
1774
#endif
1775
1776 b45a7a18 Fabrice Bellard
/**************************************************************/
1777
/* parsing functions - called from other demuxers such as RTP */
1778
1779 9125806e Alexis Ballier
MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
1780 b45a7a18 Fabrice Bellard
{
1781
    MpegTSContext *ts;
1782 115329f1 Diego Biurrun
1783 b45a7a18 Fabrice Bellard
    ts = av_mallocz(sizeof(MpegTSContext));
1784
    if (!ts)
1785
        return NULL;
1786
    /* no stream case, currently used by RTP */
1787
    ts->raw_packet_size = TS_PACKET_SIZE;
1788
    ts->stream = s;
1789
    ts->auto_guess = 1;
1790
    return ts;
1791
}
1792
1793
/* return the consumed length if a packet was output, or -1 if no
1794
   packet is output */
1795 9125806e Alexis Ballier
int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1796 b45a7a18 Fabrice Bellard
                        const uint8_t *buf, int len)
1797
{
1798
    int len1;
1799
1800
    len1 = len;
1801
    ts->pkt = pkt;
1802
    ts->stop_parse = 0;
1803
    for(;;) {
1804 90d13e30 Michael Niedermayer
        if (ts->stop_parse>0)
1805 b45a7a18 Fabrice Bellard
            break;
1806
        if (len < TS_PACKET_SIZE)
1807
            return -1;
1808
        if (buf[0] != 0x47) {
1809 550f0a9b Wolfram Gloger
            buf++;
1810 b45a7a18 Fabrice Bellard
            len--;
1811
        } else {
1812
            handle_packet(ts, buf);
1813
            buf += TS_PACKET_SIZE;
1814
            len -= TS_PACKET_SIZE;
1815
        }
1816
    }
1817
    return len1 - len;
1818
}
1819
1820 9125806e Alexis Ballier
void ff_mpegts_parse_close(MpegTSContext *ts)
1821 b45a7a18 Fabrice Bellard
{
1822
    int i;
1823
1824
    for(i=0;i<NB_PID_MAX;i++)
1825
        av_free(ts->pids[i]);
1826
    av_free(ts);
1827
}
1828
1829 d2a067d1 Måns Rullgård
AVInputFormat mpegts_demuxer = {
1830 fe9cf0d4 Fabrice Bellard
    "mpegts",
1831 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1832 fe9cf0d4 Fabrice Bellard
    sizeof(MpegTSContext),
1833
    mpegts_probe,
1834
    mpegts_read_header,
1835
    mpegts_read_packet,
1836
    mpegts_read_close,
1837 e05655fb Michael Niedermayer
    read_seek,
1838 cdd5034f Michael Niedermayer
    mpegts_get_pcr,
1839 ff9c8d7c Michael Niedermayer
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1840 af8aae3f Ivan Schreter
#ifdef USE_SYNCPOINT_SEARCH
1841 a8dd8dc6 Ivan Schreter
    .read_seek2 = read_seek2,
1842 af8aae3f Ivan Schreter
#endif
1843 fe9cf0d4 Fabrice Bellard
};
1844 38c48be2 Michael Niedermayer
1845
AVInputFormat mpegtsraw_demuxer = {
1846
    "mpegtsraw",
1847 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1848 38c48be2 Michael Niedermayer
    sizeof(MpegTSContext),
1849 056f6b8f Michael Niedermayer
    NULL,
1850 38c48be2 Michael Niedermayer
    mpegts_read_header,
1851
    mpegts_raw_read_packet,
1852
    mpegts_read_close,
1853
    read_seek,
1854
    mpegts_get_pcr,
1855 ff9c8d7c Michael Niedermayer
    .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1856 af8aae3f Ivan Schreter
#ifdef USE_SYNCPOINT_SEARCH
1857 a8dd8dc6 Ivan Schreter
    .read_seek2 = read_seek2,
1858 af8aae3f Ivan Schreter
#endif
1859 38c48be2 Michael Niedermayer
};