mpegts.c 76.9 KB
Newer Older
1
/*
2
 * MPEG-2 transport stream (aka DVB) demuxer
3
 * Copyright (c) 2002-2003 Fabrice Bellard
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * Libav is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

22
#include "libavutil/buffer.h"
23
#include "libavutil/crc.h"
24
#include "libavutil/intreadwrite.h"
25
#include "libavutil/log.h"
26
#include "libavutil/dict.h"
27
#include "libavutil/mathematics.h"
28
#include "libavutil/opt.h"
29 30

#include "libavcodec/bitstream.h"
31
#include "libavcodec/bytestream.h"
32
#include "libavcodec/opus.h"
33

34
#include "avformat.h"
35
#include "mpegts.h"
36
#include "internal.h"
37
#include "avio_internal.h"
38
#include "mpeg.h"
39
#include "isom.h"
40

41 42
/* maximum size in which we look for synchronization if
 * synchronization is lost */
43
#define MAX_RESYNC_SIZE 65536
44

45
#define MAX_PES_PAYLOAD 200 * 1024
46

47 48
#define MAX_MP4_DESCR_COUNT 16

49 50
#define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend)                \
    do {                                                                       \
51
        if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
52 53
            (modulus) = (dividend) % (divisor);                                \
        (prev_dividend) = (dividend);                                          \
54 55
    } while (0)

56 57 58
enum MpegTSFilterType {
    MPEGTS_PES,
    MPEGTS_SECTION,
59 60
};

61 62
typedef struct MpegTSFilter MpegTSFilter;

63 64
typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
                         int is_start, int64_t pos);
65

66 67 68 69 70
typedef struct MpegTSPESFilter {
    PESCallback *pes_cb;
    void *opaque;
} MpegTSPESFilter;

71
typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
72

73
typedef void SetServiceCallback (void *opaque, int ret);
74 75 76 77

typedef struct MpegTSSectionFilter {
    int section_index;
    int section_h_size;
78
    int last_ver;
79
    uint8_t *section_buf;
80 81
    unsigned int check_crc : 1;
    unsigned int end_of_section_reached : 1;
82 83 84 85
    SectionCallback *section_cb;
    void *opaque;
} MpegTSSectionFilter;

86
struct MpegTSFilter {
87
    int pid;
Alex Converse's avatar
Alex Converse committed
88
    int es_id;
89
    int last_cc; /* last cc code (-1 if first packet) */
90 91 92 93 94
    enum MpegTSFilterType type;
    union {
        MpegTSPESFilter pes_filter;
        MpegTSSectionFilter section_filter;
    } u;
95
};
96

97
#define MAX_PIDS_PER_PROGRAM 64
98
struct Program {
99
    unsigned int id; // program id/service id
100 101
    unsigned int nb_pids;
    unsigned int pids[MAX_PIDS_PER_PROGRAM];
102
};
103

Måns Rullgård's avatar
Måns Rullgård committed
104
struct MpegTSContext {
105
    const AVClass *class;
106 107
    /* user data */
    AVFormatContext *stream;
108
    /** raw packet size, including FEC if present */
109
    int raw_packet_size;
110 111

    int pos47;
112 113
    /** position corresponding to pos47, or 0 if pos47 invalid */
    int64_t pos;
114

115
    /** if true, all pids are analyzed to find streams */
116
    int auto_guess;
117

118
    /** compute exact PCR for each transport stream packet */
119
    int mpeg2ts_compute_pcr;
120

121 122
    int64_t cur_pcr;    /**< used to estimate the exact PCR */
    int pcr_incr;       /**< used to estimate the exact PCR */
123

124
    /* data needed to handle file based ts */
125
    /** stop parsing loop */
126
    int stop_parse;
127
    /** packet containing Audio/Video data */
128
    AVPacket *pkt;
129
    /** to detect seek */
130
    int64_t last_pos;
131

132 133
    int resync_size;

134 135 136
    /******************************************/
    /* private mpegts data */
    /* scan context */
137
    /** structure to keep track of Program->pids mapping */
138
    unsigned int nb_prg;
139
    struct Program *prg;
140

141
    /** filters for various streams specified by PMT + for the PAT and PMT */
142
    MpegTSFilter *pids[NB_PID_MAX];
Måns Rullgård's avatar
Måns Rullgård committed
143
};
144

145
#define MPEGTS_OPTIONS \
146
    { "resync_size",   "Size limit for looking up a new synchronization.", offsetof(MpegTSContext, resync_size), AV_OPT_TYPE_INT,  { .i64 =  MAX_RESYNC_SIZE}, 0, INT_MAX,  AV_OPT_FLAG_DECODING_PARAM }
147

148
static const AVOption options[] = {
149 150 151 152 153 154 155 156 157 158 159 160 161
    MPEGTS_OPTIONS,
    { NULL },
};

static const AVClass mpegts_class = {
    .class_name = "mpegts demuxer",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

static const AVOption raw_options[] = {
    MPEGTS_OPTIONS,
162 163 164 165 166 167 168
    { "compute_pcr",   "Compute exact PCR for each transport stream packet.",
          offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
          { .i64 = 0 }, 0, 1,  AV_OPT_FLAG_DECODING_PARAM },
    { "ts_packetsize", "Output option carrying the raw packet size.",
      offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
      { .i64 = 0 }, 0, 0,
      AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
169 170 171 172 173 174
    { NULL },
};

static const AVClass mpegtsraw_class = {
    .class_name = "mpegtsraw demuxer",
    .item_name  = av_default_item_name,
175
    .option     = raw_options,
176 177 178
    .version    = LIBAVUTIL_VERSION_INT,
};

179 180 181 182
/* TS stream handling */

enum MpegTSState {
    MPEGTS_HEADER = 0,
183
    MPEGTS_PESHEADER,
184 185 186 187 188 189
    MPEGTS_PESHEADER_FILL,
    MPEGTS_PAYLOAD,
    MPEGTS_SKIP,
};

/* enough for PES header + length */
190 191
#define PES_START_SIZE  6
#define PES_HEADER_SIZE 9
192 193
#define MAX_PES_HEADER_SIZE (9 + 255)

194
typedef struct PESContext {
195
    int pid;
196
    int pcr_pid; /**< if -1 then all packets containing PCR are considered */
197 198 199 200
    int stream_type;
    MpegTSContext *ts;
    AVFormatContext *stream;
    AVStream *st;
201
    AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
202 203 204
    enum MpegTSState state;
    /* used to get the format */
    int data_index;
205
    int flags; /**< copied to the AVPacket flags */
206 207
    int total_size;
    int pes_header_size;
208
    int extended_stream_id;
209
    int64_t pts, dts;
210
    int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
211
    uint8_t header[MAX_PES_HEADER_SIZE];
212
    AVBufferRef *buffer;
Alex Converse's avatar
Alex Converse committed
213
    SLConfigDescr sl;
214
} PESContext;
215

216
extern AVInputFormat ff_mpegts_demuxer;
217

218 219 220 221
static void clear_program(MpegTSContext *ts, unsigned int programid)
{
    int i;

222 223
    for (i = 0; i < ts->nb_prg; i++)
        if (ts->prg[i].id == programid)
224 225 226 227 228 229
            ts->prg[i].nb_pids = 0;
}

static void clear_programs(MpegTSContext *ts)
{
    av_freep(&ts->prg);
230
    ts->nb_prg = 0;
231 232 233 234
}

static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
{
235
    struct Program *p;
236 237
    if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
        ts->nb_prg = 0;
238
        return;
239
    }
240 241 242 243 244 245
    p = &ts->prg[ts->nb_prg];
    p->id = programid;
    p->nb_pids = 0;
    ts->nb_prg++;
}

246 247
static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
                           unsigned int pid)
248 249
{
    int i;
250
    struct Program *p = NULL;
251 252
    for (i = 0; i < ts->nb_prg; i++) {
        if (ts->prg[i].id == programid) {
253 254 255 256
            p = &ts->prg[i];
            break;
        }
    }
257
    if (!p)
258 259
        return;

260
    if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
261 262 263 264 265
        return;
    p->pids[p->nb_pids++] = pid;
}

/**
266
 * @brief discard_pid() decides if the pid is to be discarded according
267
 *                      to caller's programs selection
268 269 270
 * @param ts    : - TS context
 * @param pid   : - pid
 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
271 272 273 274 275 276
 *         0 otherwise
 */
static int discard_pid(MpegTSContext *ts, unsigned int pid)
{
    int i, j, k;
    int used = 0, discarded = 0;
277
    struct Program *p;
278 279

    /* If none of the programs have .discard=AVDISCARD_ALL then there's
280 281
     * no way we have to discard this packet */
    for (k = 0; k < ts->stream->nb_programs; k++)
282 283 284 285 286
        if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
            break;
    if (k == ts->stream->nb_programs)
        return 0;

287
    for (i = 0; i < ts->nb_prg; i++) {
288
        p = &ts->prg[i];
289 290
        for (j = 0; j < p->nb_pids; j++) {
            if (p->pids[j] != pid)
291
                continue;
292 293 294 295
            // is program with id p->id set to be discarded?
            for (k = 0; k < ts->stream->nb_programs; k++) {
                if (ts->stream->programs[k]->id == p->id) {
                    if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
296 297 298 299 300 301 302 303
                        discarded++;
                    else
                        used++;
                }
            }
        }
    }

304
    return !used && discarded;
305 306
}

307
/**
308
 *  Assemble PES packets out of TS packets, and then call the "section_cb"
309 310
 *  function when they are complete.
 */
311
static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
312 313 314 315
                               const uint8_t *buf, int buf_size, int is_start)
{
    MpegTSSectionFilter *tss = &tss1->u.section_filter;
    int len;
316

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    if (is_start) {
        memcpy(tss->section_buf, buf, buf_size);
        tss->section_index = buf_size;
        tss->section_h_size = -1;
        tss->end_of_section_reached = 0;
    } else {
        if (tss->end_of_section_reached)
            return;
        len = 4096 - tss->section_index;
        if (buf_size < len)
            len = buf_size;
        memcpy(tss->section_buf + tss->section_index, buf, len);
        tss->section_index += len;
    }

    /* compute section length if possible */
    if (tss->section_h_size == -1 && tss->section_index >= 3) {
334
        len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
335 336 337 338 339
        if (len > 4096)
            return;
        tss->section_h_size = len;
    }

340 341
    if (tss->section_h_size != -1 &&
        tss->section_index >= tss->section_h_size) {
342
        tss->end_of_section_reached = 1;
343
        if (!tss->check_crc ||
Aurelien Jacobs's avatar
Aurelien Jacobs committed
344 345
            av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
                   tss->section_buf, tss->section_h_size) == 0)
346
            tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
347 348 349
    }
}

350 351 352 353 354
static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
                                                unsigned int pid,
                                                SectionCallback *section_cb,
                                                void *opaque,
                                                int check_crc)
355 356 357
{
    MpegTSFilter *filter;
    MpegTSSectionFilter *sec;
358

359
    av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x\n", pid);
360

361 362 363
    if (pid >= NB_PID_MAX || ts->pids[pid])
        return NULL;
    filter = av_mallocz(sizeof(MpegTSFilter));
364
    if (!filter)
365 366
        return NULL;
    ts->pids[pid] = filter;
367 368 369 370

    filter->type    = MPEGTS_SECTION;
    filter->pid     = pid;
    filter->es_id   = -1;
371
    filter->last_cc = -1;
372

373
    sec = &filter->u.section_filter;
374 375
    sec->section_cb  = section_cb;
    sec->opaque      = opaque;
376
    sec->section_buf = av_malloc(MAX_SECTION_SIZE);
377
    sec->check_crc   = check_crc;
378 379
    sec->last_ver    = -1;

380 381 382 383 384 385 386
    if (!sec->section_buf) {
        av_free(filter);
        return NULL;
    }
    return filter;
}

387
static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
388 389
                                            PESCallback *pes_cb,
                                            void *opaque)
390 391 392 393 394 395 396
{
    MpegTSFilter *filter;
    MpegTSPESFilter *pes;

    if (pid >= NB_PID_MAX || ts->pids[pid])
        return NULL;
    filter = av_mallocz(sizeof(MpegTSFilter));
397
    if (!filter)
398
        return NULL;
399

400
    ts->pids[pid] = filter;
401 402 403
    filter->type    = MPEGTS_PES;
    filter->pid     = pid;
    filter->es_id   = -1;
404
    filter->last_cc = -1;
405

406 407 408 409 410 411
    pes = &filter->u.pes_filter;
    pes->pes_cb = pes_cb;
    pes->opaque = opaque;
    return filter;
}

412
static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
413 414 415 416 417 418
{
    int pid;

    pid = filter->pid;
    if (filter->type == MPEGTS_SECTION)
        av_freep(&filter->u.section_filter.section_buf);
419
    else if (filter->type == MPEGTS_PES) {
420
        PESContext *pes = filter->u.pes_filter.opaque;
421
        av_buffer_unref(&pes->buffer);
422
        /* referenced private data will be freed later in
423
         * avformat_close_input */
424 425 426 427
        if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
            av_freep(&filter->u.pes_filter.opaque);
        }
    }
428

429 430 431 432
    av_free(filter);
    ts->pids[pid] = NULL;
}

433 434
static int analyze(const uint8_t *buf, int size, int packet_size, int *index,
                   int probe)
435
{
436
    int stat[TS_MAX_PACKET_SIZE];
437
    int i;
438 439
    int x = 0;
    int best_score = 0;
440

441
    memset(stat, 0, packet_size * sizeof(int));
442

443
    for (x = i = 0; i < size - 3; i++) {
444 445
        if (buf[i] == 0x47 &&
            (!probe || (!(buf[i + 1] & 0x80) && (buf[i + 3] & 0x30)))) {
446
            stat[x]++;
447 448 449 450
            if (stat[x] > best_score) {
                best_score = stat[x];
                if (index)
                    *index = x;
451 452 453 454
            }
        }

        x++;
455 456
        if (x == packet_size)
            x = 0;
457 458 459 460 461
    }

    return best_score;
}

462
/* autodetect fec presence. Must have at least 1024 bytes  */
463
static int get_packet_size(const uint8_t *buf, int size)
464
{
465
    int score, fec_score, dvhs_score;
466 467

    if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
468
        return AVERROR_INVALIDDATA;
469

470 471 472
    score      = analyze(buf, size, TS_PACKET_SIZE,      NULL, 0);
    dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL, 0);
    fec_score  = analyze(buf, size, TS_FEC_PACKET_SIZE,  NULL, 0);
473
    av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
474
            score, dvhs_score, fec_score);
475

476 477 478 479 480 481 482
    if (score > fec_score && score > dvhs_score)
        return TS_PACKET_SIZE;
    else if (dvhs_score > score && dvhs_score > fec_score)
        return TS_DVHS_PACKET_SIZE;
    else if (score < fec_score && dvhs_score < fec_score)
        return TS_FEC_PACKET_SIZE;
    else
483
        return AVERROR_INVALIDDATA;
484 485
}

486 487 488 489 490 491 492 493 494
typedef struct SectionHeader {
    uint8_t tid;
    uint16_t id;
    uint8_t version;
    uint8_t sec_num;
    uint8_t last_sec_num;
} SectionHeader;

static inline int get8(const uint8_t **pp, const uint8_t *p_end)
495
{
496 497 498 499 500
    const uint8_t *p;
    int c;

    p = *pp;
    if (p >= p_end)
501
        return AVERROR_INVALIDDATA;
502
    c   = *p++;
503 504
    *pp = p;
    return c;
505 506
}

507 508 509 510 511 512 513
static inline int get16(const uint8_t **pp, const uint8_t *p_end)
{
    const uint8_t *p;
    int c;

    p = *pp;
    if ((p + 1) >= p_end)
514
        return AVERROR_INVALIDDATA;
515 516
    c   = AV_RB16(p);
    p  += 2;
517 518 519 520
    *pp = p;
    return c;
}

521
/* read and allocate a DVB string preceded by its length */
522
static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
523 524
{
    int len;
525 526
    const uint8_t *p;
    char *str;
527

528
    p   = *pp;
529 530 531 532 533 534 535 536 537 538
    len = get8(&p, p_end);
    if (len < 0)
        return NULL;
    if ((p + len) > p_end)
        return NULL;
    str = av_malloc(len + 1);
    if (!str)
        return NULL;
    memcpy(str, p, len);
    str[len] = '\0';
539
    p  += len;
540 541 542 543
    *pp = p;
    return str;
}

544
static int parse_section_header(SectionHeader *h,
545 546 547 548 549 550
                                const uint8_t **pp, const uint8_t *p_end)
{
    int val;

    val = get8(pp, p_end);
    if (val < 0)
551
        return val;
552 553
    h->tid = val;
    *pp += 2;
554
    val  = get16(pp, p_end);
555
    if (val < 0)
556
        return val;
557 558 559
    h->id = val;
    val = get8(pp, p_end);
    if (val < 0)
560
        return val;
561 562 563
    h->version = (val >> 1) & 0x1f;
    val = get8(pp, p_end);
    if (val < 0)
564
        return val;
565 566 567
    h->sec_num = val;
    val = get8(pp, p_end);
    if (val < 0)
568
        return val;
569
    h->last_sec_num = val;
570
    return 0;
571 572
}

573
typedef struct StreamType {
574
    uint32_t stream_type;
575
    enum AVMediaType codec_type;
576
    enum AVCodecID codec_id;
577 578 579
} StreamType;

static const StreamType ISO_types[] = {
580 581
    { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
    { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
582 583 584 585 586 587
    { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
    { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
    { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC        },
    { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4      },
    { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM   }, /* LATM syntax */
    { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
588
    { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000   },
589 590 591 592
    { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC       },
    { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS       },
    { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC      },
    { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1        },
593 594 595 596
    { 0 },
};

static const StreamType HDMV_types[] = {
597 598 599 600 601 602 603
    { 0x80, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_PCM_BLURAY        },
    { 0x81, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3               },
    { 0x82, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               },
    { 0x83, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_TRUEHD            },
    { 0x84, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3              },
    { 0x85, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD */
    { 0x86, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD MASTER*/
604
    { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
605 606 607 608 609
    { 0 },
};

/* ATSC ? */
static const StreamType MISC_types[] = {
610 611
    { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
    { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
612 613 614 615
    { 0 },
};

static const StreamType REGD_types[] = {
616 617 618 619 620 621 622 623
    { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
    { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3   },
    { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
    { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
    { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
    { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
    { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC  },
    { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1   },
624
    { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS  },
625 626 627
    { 0 },
};

Baptiste Coudurier's avatar
Baptiste Coudurier committed
628 629
/* descriptor present */
static const StreamType DESC_types[] = {
630 631 632
    { 0x6a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3          }, /* AC-3 descriptor */
    { 0x7a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3         }, /* E-AC-3 descriptor */
    { 0x7b, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS          },
633 634
    { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
    { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
635
    { 0 },
Baptiste Coudurier's avatar
Baptiste Coudurier committed
636 637
};

638
static void mpegts_find_stream_type(AVStream *st,
639 640
                                    uint32_t stream_type,
                                    const StreamType *types)
641
{
642
    for (; types->stream_type; types++)
643
        if (stream_type == types->stream_type) {
644 645
            st->codecpar->codec_type = types->codec_type;
            st->codecpar->codec_id   = types->codec_id;
646 647 648 649
            return;
        }
}

650 651
static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
                                  uint32_t stream_type, uint32_t prog_reg_desc)
652
{
653
    avpriv_set_pts_info(st, 33, 1, 90000);
654
    st->priv_data         = pes;
655 656
    st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
    st->codecpar->codec_id   = AV_CODEC_ID_NONE;
657 658
    st->need_parsing      = AVSTREAM_PARSE_FULL;
    pes->st          = st;
659
    pes->stream_type = stream_type;
660

661 662
    av_log(pes->stream, AV_LOG_DEBUG,
           "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
663
           st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
664

665
    st->codecpar->codec_tag = pes->stream_type;
666

Baptiste Coudurier's avatar
Baptiste Coudurier committed
667 668
    mpegts_find_stream_type(st, pes->stream_type, ISO_types);
    if (prog_reg_desc == AV_RL32("HDMV") &&
669
        st->codecpar->codec_id == AV_CODEC_ID_NONE) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
670
        mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
671 672 673 674 675 676 677
        if (pes->stream_type == 0x83) {
            // HDMV TrueHD streams also contain an AC3 coded version of the
            // audio track - add a second stream for this
            AVStream *sub_st;
            // priv_data cannot be shared between streams
            PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
            if (!sub_pes)
678
                return AVERROR(ENOMEM);
679 680
            memcpy(sub_pes, pes, sizeof(*sub_pes));

681
            sub_st = avformat_new_stream(pes->stream, NULL);
682 683
            if (!sub_st) {
                av_free(sub_pes);
684
                return AVERROR(ENOMEM);
685 686
            }

687
            sub_st->id = pes->pid;
688
            avpriv_set_pts_info(sub_st, 33, 1, 90000);
689
            sub_st->priv_data         = sub_pes;
690 691
            sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
            sub_st->codecpar->codec_id   = AV_CODEC_ID_AC3;
692 693
            sub_st->need_parsing      = AVSTREAM_PARSE_FULL;
            sub_pes->sub_st           = pes->sub_st = sub_st;
694 695
        }
    }
696
    if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
Baptiste Coudurier's avatar
Baptiste Coudurier committed
697
        mpegts_find_stream_type(st, pes->stream_type, MISC_types);
698

699
    return 0;
700
}
701

702 703 704 705
static void new_pes_packet(PESContext *pes, AVPacket *pkt)
{
    av_init_packet(pkt);

706 707
    pkt->buf  = pes->buffer;
    pkt->data = pes->buffer->data;
708
    pkt->size = pes->data_index;
709

710 711 712
    if (pes->total_size != MAX_PES_PAYLOAD &&
        pes->pes_header_size + pes->data_index != pes->total_size +
        PES_START_SIZE) {
713
        av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
714 715
        pes->flags |= AV_PKT_FLAG_CORRUPT;
    }
716
    memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
717 718 719 720 721 722 723 724 725

    // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
    if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
        pkt->stream_index = pes->sub_st->index;
    else
        pkt->stream_index = pes->st->index;
    pkt->pts = pes->pts;
    pkt->dts = pes->dts;
    /* store position of first TS packet of this PES packet */
726
    pkt->pos   = pes->ts_packet_pos;
727
    pkt->flags = pes->flags;
728 729

    /* reset pts values */
730 731 732
    pes->pts        = AV_NOPTS_VALUE;
    pes->dts        = AV_NOPTS_VALUE;
    pes->buffer     = NULL;
733
    pes->data_index = 0;
734
    pes->flags      = 0;
735 736
}

737 738
static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
                          const uint8_t *buf, int buf_size)
Alex Converse's avatar
Alex Converse committed
739
{
740
    BitstreamContext bc;
Alex Converse's avatar
Alex Converse committed
741 742 743 744
    int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
    int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
    int dts_flag = -1, cts_flag = -1;
    int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
745
    bitstream_init8(&bc, buf, buf_size);
Alex Converse's avatar
Alex Converse committed
746 747

    if (sl->use_au_start)
748
        au_start_flag = bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
749
    if (sl->use_au_end)
750
        au_end_flag = bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
751 752 753
    if (!sl->use_au_start && !sl->use_au_end)
        au_start_flag = au_end_flag = 1;
    if (sl->ocr_len > 0)
754
        ocr_flag = bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
755
    if (sl->use_idle)
756
        idle_flag = bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
757
    if (sl->use_padding)
758
        padding_flag = bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
759
    if (padding_flag)
760
        padding_bits = bitstream_read(&bc, 3);
Alex Converse's avatar
Alex Converse committed
761 762 763

    if (!idle_flag && (!padding_flag || padding_bits != 0)) {
        if (sl->packet_seq_num_len)
764
            bitstream_skip(&bc, sl->packet_seq_num_len);
Alex Converse's avatar
Alex Converse committed
765
        if (sl->degr_prior_len)
766 767
            if (bitstream_read_bit(&bc))
                bitstream_skip(&bc, sl->degr_prior_len);
Alex Converse's avatar
Alex Converse committed
768
        if (ocr_flag)
769
            bitstream_skip(&bc, sl->ocr_len);
Alex Converse's avatar
Alex Converse committed
770 771
        if (au_start_flag) {
            if (sl->use_rand_acc_pt)
772
                bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
773
            if (sl->au_seq_num_len > 0)
774
                bitstream_skip(&bc, sl->au_seq_num_len);
Alex Converse's avatar
Alex Converse committed
775
            if (sl->use_timestamps) {
776 777
                dts_flag = bitstream_read_bit(&bc);
                cts_flag = bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
778 779 780
            }
        }
        if (sl->inst_bitrate_len)
781
            inst_bitrate_flag = bitstream_read_bit(&bc);
Alex Converse's avatar
Alex Converse committed
782
        if (dts_flag == 1)
783
            dts = bitstream_read_63(&bc, sl->timestamp_len);
Alex Converse's avatar
Alex Converse committed
784
        if (cts_flag == 1)
785
            cts = bitstream_read_63(&bc, sl->timestamp_len);
Alex Converse's avatar
Alex Converse committed
786
        if (sl->au_len > 0)
787
            bitstream_skip(&bc, sl->au_len);
Alex Converse's avatar
Alex Converse committed
788
        if (inst_bitrate_flag)
789
            bitstream_skip(&bc, sl->inst_bitrate_len);
Alex Converse's avatar
Alex Converse committed
790 791 792 793 794 795 796
    }

    if (dts != AV_NOPTS_VALUE)
        pes->dts = dts;
    if (cts != AV_NOPTS_VALUE)
        pes->pts = cts;

797 798
    if (sl->timestamp_len && sl->timestamp_res)
        avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
Alex Converse's avatar
Alex Converse committed
799

800
    return (bitstream_tell(&bc) + 7) >> 3;
Alex Converse's avatar
Alex Converse committed
801 802
}

803 804 805 806 807
/* return non zero if a packet could be constructed */
static int mpegts_push_data(MpegTSFilter *filter,
                            const uint8_t *buf, int buf_size, int is_start,
                            int64_t pos)
{
808
    PESContext *pes   = filter->u.pes_filter.opaque;
809 810 811 812
    MpegTSContext *ts = pes->ts;
    const uint8_t *p;
    int len, code;

813
    if (!ts->pkt)
814 815 816 817 818 819 820
        return 0;

    if (is_start) {
        if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
            new_pes_packet(pes, ts->pkt);
            ts->stop_parse = 1;
        }
821 822
        pes->state         = MPEGTS_HEADER;
        pes->data_index    = 0;
823 824 825 826
        pes->ts_packet_pos = pos;
    }
    p = buf;
    while (buf_size > 0) {
827
        switch (pes->state) {
828 829 830 831 832 833 834 835 836 837
        case MPEGTS_HEADER:
            len = PES_START_SIZE - pes->data_index;
            if (len > buf_size)
                len = buf_size;
            memcpy(pes->header + pes->data_index, p, len);
            pes->data_index += len;
            p += len;
            buf_size -= len;
            if (pes->data_index == PES_START_SIZE) {
                /* we got all the PES or section header. We can now
838
                 * decide */
839 840
                if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
                    pes->header[2] == 0x01) {
841
                    /* it must be an MPEG-2 PES stream */
842
                    code = pes->header[3] | 0x100;
843
                    av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
844
                            code);
845

846
                    if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
847 848
                         (!pes->sub_st ||
                          pes->sub_st->discard == AVDISCARD_ALL)) ||
849 850 851 852 853
                        code == 0x1be) /* padding_stream */
                        goto skip;

                    /* stream not present in PMT */
                    if (!pes->st) {
854
                        pes->st = avformat_new_stream(ts->stream, NULL);
855 856
                        if (!pes->st)
                            return AVERROR(ENOMEM);
857
                        pes->st->id = pes->pid;
858 859 860 861 862
                        mpegts_set_stream_info(pes->st, pes, 0, 0);
                    }

                    pes->total_size = AV_RB16(pes->header + 4);
                    /* NOTE: a zero total size means the PES size is
863
                     * unbounded */
864 865 866 867
                    if (!pes->total_size)
                        pes->total_size = MAX_PES_PAYLOAD;

                    /* allocate pes buffer */
868
                    pes->buffer = av_buffer_alloc(pes->total_size +
869
                                                  AV_INPUT_BUFFER_PADDING_SIZE);
870 871 872 873 874 875 876 877
                    if (!pes->buffer)
                        return AVERROR(ENOMEM);

                    if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
                        code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
                        code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
                        code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
                        pes->state = MPEGTS_PESHEADER;
878
                        if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE) {
879
                            av_log(pes->stream, AV_LOG_TRACE,
880 881 882
                                    "pid=%x stream_type=%x probing\n",
                                    pes->pid,
                                    pes->stream_type);
883
                            pes->st->codecpar->codec_id = AV_CODEC_ID_PROBE;
884 885
                        }
                    } else {
886
                        pes->state      = MPEGTS_PAYLOAD;
887 888 889 890 891
                        pes->data_index = 0;
                    }
                } else {
                    /* otherwise, it should be a table */
                    /* skip packet */
892
skip:
893 894 895 896 897
                    pes->state = MPEGTS_SKIP;
                    continue;
                }
            }
            break;
898 899
        /**********************************************/
        /* PES packing parsing */
900 901 902
        case MPEGTS_PESHEADER:
            len = PES_HEADER_SIZE - pes->data_index;
            if (len < 0)
903
                return AVERROR_INVALIDDATA;
904 905 906 907 908 909 910 911
            if (len > buf_size)
                len = buf_size;
            memcpy(pes->header + pes->data_index, p, len);
            pes->data_index += len;
            p += len;
            buf_size -= len;
            if (pes->data_index == PES_HEADER_SIZE) {
                pes->pes_header_size = pes->header[8] + 9;
912
                pes->state           = MPEGTS_PESHEADER_FILL;
913 914 915 916 917
            }
            break;
        case MPEGTS_PESHEADER_FILL:
            len = pes->pes_header_size - pes->data_index;
            if (len < 0)
918
                return AVERROR_INVALIDDATA;
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
            if (len > buf_size)
                len = buf_size;
            memcpy(pes->header + pes->data_index, p, len);
            pes->data_index += len;
            p += len;
            buf_size -= len;
            if (pes->data_index == pes->pes_header_size) {
                const uint8_t *r;
                unsigned int flags, pes_ext, skip;

                flags = pes->header[7];
                r = pes->header + 9;
                pes->pts = AV_NOPTS_VALUE;
                pes->dts = AV_NOPTS_VALUE;
                if ((flags & 0xc0) == 0x80) {
934
                    pes->dts = pes->pts = ff_parse_pes_pts(r);
935 936
                    r += 5;
                } else if ((flags & 0xc0) == 0xc0) {
937
                    pes->pts = ff_parse_pes_pts(r);
938
                    r += 5;
939
                    pes->dts = ff_parse_pes_pts(r);
940 941 942 943 944 945
                    r += 5;
                }
                pes->extended_stream_id = -1;
                if (flags & 0x01) { /* PES extension */
                    pes_ext = *r++;
                    /* Skip PES private data, program packet sequence counter and P-STD buffer */
946
                    skip  = (pes_ext >> 4) & 0xb;
947
                    skip += skip & 0x9;
948
                    r    += skip;
949 950 951 952 953 954 955 956 957 958 959
                    if ((pes_ext & 0x41) == 0x01 &&
                        (r + 2) <= (pes->header + pes->pes_header_size)) {
                        /* PES extension 2 */
                        if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
                            pes->extended_stream_id = r[1];
                    }
                }

                /* we got the full header. We parse it and get the payload */
                pes->state = MPEGTS_PAYLOAD;
                pes->data_index = 0;
960
                if (pes->stream_type == 0x12 && buf_size > 0) {
961 962
                    int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
                                                         buf_size);
Alex Converse's avatar
Alex Converse committed
963 964 965 966
                    pes->pes_header_size += sl_header_bytes;
                    p += sl_header_bytes;
                    buf_size -= sl_header_bytes;
                }
967 968 969 970
            }
            break;
        case MPEGTS_PAYLOAD:
            if (buf_size > 0 && pes->buffer) {
971 972
                if (pes->data_index > 0 &&
                    pes->data_index + buf_size > pes->total_size) {
973 974
                    new_pes_packet(pes, ts->pkt);
                    pes->total_size = MAX_PES_PAYLOAD;
975
                    pes->buffer = av_buffer_alloc(pes->total_size +
976
                                                  AV_INPUT_BUFFER_PADDING_SIZE);
977 978 979
                    if (!pes->buffer)
                        return AVERROR(ENOMEM);
                    ts->stop_parse = 1;
980 981
                } else if (pes->data_index == 0 &&
                           buf_size > pes->total_size) {
982 983 984
                    // pes packet size is < ts size packet and pes data is padded with 0xff
                    // not sure if this is legal in ts but see issue #2392
                    buf_size = pes->total_size;
985
                }
986
                memcpy(pes->buffer->data + pes->data_index, p, buf_size);
987 988 989
                pes->data_index += buf_size;
            }
            buf_size = 0;
990 991 992 993
            /* emit complete packets with known packet size
             * decreases demuxer delay for infrequent packets like subtitles from
             * a couple of seconds to milliseconds for properly muxed files.
             * total_size is the number of bytes following pes_packet_length
994
             * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
995
            if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
996
                pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
997 998 999
                ts->stop_parse = 1;
                new_pes_packet(pes, ts->pkt);
            }
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
            break;
        case MPEGTS_SKIP:
            buf_size = 0;
            break;
        }
    }

    return 0;
}

static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
{
    MpegTSFilter *tss;
    PESContext *pes;

    /* if no pid found, then add a pid context */
    pes = av_mallocz(sizeof(PESContext));
    if (!pes)
        return 0;
1019 1020 1021
    pes->ts      = ts;
    pes->stream  = ts->stream;
    pes->pid     = pid;
1022
    pes->pcr_pid = pcr_pid;
1023 1024 1025 1026
    pes->state   = MPEGTS_SKIP;
    pes->pts     = AV_NOPTS_VALUE;
    pes->dts     = AV_NOPTS_VALUE;
    tss          = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1027 1028 1029 1030 1031 1032 1033
    if (!tss) {
        av_free(pes);
        return 0;
    }
    return pes;
}

1034
#define MAX_LEVEL 4
1035
typedef struct MP4DescrParseContext {
1036
    AVFormatContext *s;
1037
    AVIOContext pb;
1038 1039 1040 1041 1042 1043 1044
    Mp4Descr *descr;
    Mp4Descr *active_descr;
    int descr_count;
    int max_descr_count;
    int level;
} MP4DescrParseContext;

1045 1046 1047
static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
                                     const uint8_t *buf, unsigned size,
                                     Mp4Descr *descr, int max_descr_count)
1048 1049
{
    int ret;
1050
    if (size > (1 << 30))
1051 1052
        return AVERROR_INVALIDDATA;

1053 1054
    if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
                                 NULL, NULL, NULL, NULL)) < 0)
1055 1056
        return ret;

1057 1058 1059 1060 1061
    d->s               = s;
    d->level           = 0;
    d->descr_count     = 0;
    d->descr           = descr;
    d->active_descr    = NULL;
1062 1063 1064 1065 1066
    d->max_descr_count = max_descr_count;

    return 0;
}

1067 1068
static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
{
1069 1070
    int64_t new_off = avio_tell(pb);
    (*len) -= new_off - *off;
1071
    *off    = new_off;
1072 1073 1074 1075 1076 1077 1078 1079
}

static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
                           int target_tag);

static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
{
    while (len > 0) {
1080 1081 1082
        int ret = parse_mp4_descr(d, off, len, 0);
        if (ret < 0)
            return ret;
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
        update_offsets(&d->pb, &off, &len);
    }
    return 0;
}

static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
{
    avio_rb16(&d->pb); // ID
    avio_r8(&d->pb);
    avio_r8(&d->pb);
    avio_r8(&d->pb);
    avio_r8(&d->pb);
    avio_r8(&d->pb);
    update_offsets(&d->pb, &off, &len);
    return parse_mp4_descr_arr(d, off, len);
}

Alex Converse's avatar
Alex Converse committed
1100 1101 1102 1103 1104 1105
static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
{
    int id_flags;
    if (len < 2)
        return 0;
    id_flags = avio_rb16(&d->pb);
1106
    if (!(id_flags & 0x0020)) { // URL_Flag
Alex Converse's avatar
Alex Converse committed
1107
        update_offsets(&d->pb, &off, &len);
1108
        return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
Alex Converse's avatar
Alex Converse committed
1109 1110 1111 1112 1113
    } else {
        return 0;
    }
}

1114 1115 1116
static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
{
    int es_id = 0;
1117 1118
    int ret   = 0;

1119
    if (d->descr_count >= d->max_descr_count)
1120
        return AVERROR_INVALIDDATA;
1121 1122 1123 1124 1125
    ff_mp4_parse_es_descr(&d->pb, &es_id);
    d->active_descr = d->descr + (d->descr_count++);

    d->active_descr->es_id = es_id;
    update_offsets(&d->pb, &off, &len);
1126 1127
    if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
        return ret;
Alex Converse's avatar
Alex Converse committed
1128 1129
    update_offsets(&d->pb, &off, &len);
    if (len > 0)
1130
        ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
1131
    d->active_descr = NULL;
1132
    return ret;
1133 1134
}

1135 1136
static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
                                      int len)
1137 1138 1139
{
    Mp4Descr *descr = d->active_descr;
    if (!descr)
1140
        return AVERROR_INVALIDDATA;
1141 1142 1143 1144 1145 1146 1147 1148
    d->active_descr->dec_config_descr = av_malloc(len);
    if (!descr->dec_config_descr)
        return AVERROR(ENOMEM);
    descr->dec_config_descr_len = len;
    avio_read(&d->pb, descr->dec_config_descr, len);
    return 0;
}

Alex Converse's avatar
Alex Converse committed
1149 1150 1151 1152 1153
static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
{
    Mp4Descr *descr = d->active_descr;
    int predefined;
    if (!descr)
1154
        return AVERROR_INVALIDDATA;
Alex Converse's avatar
Alex Converse committed
1155 1156 1157 1158 1159

    predefined = avio_r8(&d->pb);
    if (!predefined) {
        int lengths;
        int flags = avio_r8(&d->pb);
1160 1161 1162 1163 1164 1165 1166 1167
        descr->sl.use_au_start    = !!(flags & 0x80);
        descr->sl.use_au_end      = !!(flags & 0x40);
        descr->sl.use_rand_acc_pt = !!(flags & 0x20);
        descr->sl.use_padding     = !!(flags & 0x08);
        descr->sl.use_timestamps  = !!(flags & 0x04);
        descr->sl.use_idle        = !!(flags & 0x02);
        descr->sl.timestamp_res   = avio_rb32(&d->pb);
        avio_rb32(&d->pb);
Alex Converse's avatar
Alex Converse committed
1168 1169 1170 1171 1172 1173 1174 1175
        descr->sl.timestamp_len      = avio_r8(&d->pb);
        descr->sl.ocr_len            = avio_r8(&d->pb);
        descr->sl.au_len             = avio_r8(&d->pb);
        descr->sl.inst_bitrate_len   = avio_r8(&d->pb);
        lengths                      = avio_rb16(&d->pb);
        descr->sl.degr_prior_len     = lengths >> 12;
        descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
        descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1176 1177 1178 1179 1180
        if (descr->sl.timestamp_len >= 64 ||
            descr->sl.ocr_len >= 64 ||
            descr->sl.au_len >= 32) {
            return AVERROR_INVALIDDATA;
        }
Alex Converse's avatar
Alex Converse committed
1181
    } else {
1182
        avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
Alex Converse's avatar
Alex Converse committed
1183 1184 1185 1186
    }
    return 0;
}

1187
static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1188 1189
                           int target_tag)
{
1190
    int tag;
1191
    int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1192 1193
    int ret = 0;

1194 1195
    update_offsets(&d->pb, &off, &len);
    if (len < 0 || len1 > len || len1 <= 0) {
1196 1197 1198
        av_log(d->s, AV_LOG_ERROR,
               "Tag %x length violation new length %d bytes remaining %d\n",
               tag, len1, len);
1199
        return AVERROR_INVALIDDATA;
1200 1201 1202 1203
    }

    if (d->level++ >= MAX_LEVEL) {
        av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1204
        ret = AVERROR_INVALIDDATA;
1205 1206 1207 1208
        goto done;
    }

    if (target_tag && tag != target_tag) {
1209 1210
        av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
               target_tag);
1211
        ret = AVERROR_INVALIDDATA;
1212 1213 1214 1215 1216
        goto done;
    }

    switch (tag) {
    case MP4IODescrTag:
1217
        ret = parse_MP4IODescrTag(d, off, len1);
1218
        break;
Alex Converse's avatar
Alex Converse committed
1219
    case MP4ODescrTag:
1220
        ret = parse_MP4ODescrTag(d, off, len1);
Alex Converse's avatar
Alex Converse committed
1221
        break;
1222
    case MP4ESDescrTag:
1223
        ret = parse_MP4ESDescrTag(d, off, len1);
1224 1225
        break;
    case MP4DecConfigDescrTag:
1226
        ret = parse_MP4DecConfigDescrTag(d, off, len1);
1227
        break;
Alex Converse's avatar
Alex Converse committed
1228
    case MP4SLDescrTag:
1229
        ret = parse_MP4SLDescrTag(d, off, len1);
Alex Converse's avatar
Alex Converse committed
1230
        break;
1231
    }
1232

1233

1234 1235 1236
done:
    d->level--;
    avio_seek(&d->pb, off + len1, SEEK_SET);
1237
    return ret;
1238 1239 1240 1241 1242 1243
}

static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
                         Mp4Descr *descr, int *descr_count, int max_descr_count)
{
    MP4DescrParseContext d;
1244 1245 1246 1247 1248
    int ret;

    ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
    if (ret < 0)
        return ret;
1249

1250
    ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1251 1252

    *descr_count = d.descr_count;
1253
    return ret;
1254 1255
}

Alex Converse's avatar
Alex Converse committed
1256 1257 1258 1259
static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
                       Mp4Descr *descr, int *descr_count, int max_descr_count)
{
    MP4DescrParseContext d;
1260 1261 1262 1263 1264
    int ret;

    ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
    if (ret < 0)
        return ret;
Alex Converse's avatar
Alex Converse committed
1265

1266
    ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
Alex Converse's avatar
Alex Converse committed
1267 1268

    *descr_count = d.descr_count;
1269
    return ret;
Alex Converse's avatar
Alex Converse committed
1270 1271
}

1272 1273
static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
                    int section_len)
Alex Converse's avatar
Alex Converse committed
1274
{
Alex Converse's avatar
Alex Converse committed
1275
    MpegTSContext *ts = filter->u.section_filter.opaque;
1276
    MpegTSSectionFilter *tssf = &filter->u.section_filter;
Alex Converse's avatar
Alex Converse committed
1277 1278
    SectionHeader h;
    const uint8_t *p, *p_end;
Alex Converse's avatar
Alex Converse committed
1279 1280
    AVIOContext pb;
    int mp4_descr_count = 0;
1281
    Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
Alex Converse's avatar
Alex Converse committed
1282
    int i, pid;
Alex Converse's avatar
Alex Converse committed
1283 1284 1285 1286 1287 1288 1289 1290
    AVFormatContext *s = ts->stream;

    p_end = section + section_len - 4;
    p = section;
    if (parse_section_header(&h, &p, p_end) < 0)
        return;
    if (h.tid != M4OD_TID)
        return;
1291 1292 1293
    if (h.version == tssf->last_ver)
        return;
    tssf->last_ver = h.version;
Alex Converse's avatar
Alex Converse committed
1294

1295 1296
    mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
                MAX_MP4_DESCR_COUNT);
Alex Converse's avatar
Alex Converse committed
1297 1298 1299

    for (pid = 0; pid < NB_PID_MAX; pid++) {
        if (!ts->pids[pid])
1300
            continue;
Alex Converse's avatar
Alex Converse committed
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
        for (i = 0; i < mp4_descr_count; i++) {
            PESContext *pes;
            AVStream *st;
            if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
                continue;
            if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
                av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
                continue;
            }
            pes = ts->pids[pid]->u.pes_filter.opaque;
1311 1312
            st  = pes->st;
            if (!st)
Alex Converse's avatar
Alex Converse committed
1313 1314
                continue;

Alex Converse's avatar
Alex Converse committed
1315 1316
            pes->sl = mp4_descr[i].sl;

Alex Converse's avatar
Alex Converse committed
1317
            ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1318 1319
                              mp4_descr[i].dec_config_descr_len, 0,
                              NULL, NULL, NULL, NULL);
Alex Converse's avatar
Alex Converse committed
1320
            ff_mp4_read_dec_config_descr(s, st, &pb);
1321 1322
            if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
                st->codecpar->extradata_size > 0)
Alex Converse's avatar
Alex Converse committed
1323
                st->need_parsing = 0;
1324 1325
            if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
                st->codecpar->extradata_size > 0)
Alex Converse's avatar
Alex Converse committed
1326 1327
                st->need_parsing = 0;

1328
            st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
Alex Converse's avatar
Alex Converse committed
1329 1330 1331 1332 1333 1334
        }
    }
    for (i = 0; i < mp4_descr_count; i++)
        av_free(mp4_descr[i].dec_config_descr);
}

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
static const uint8_t opus_coupled_stream_cnt[9] = {
    1, 0, 1, 1, 2, 2, 2, 3, 3
};

static const uint8_t opus_stream_cnt[9] = {
    1, 1, 1, 2, 2, 3, 4, 4, 5,
};

static const uint8_t opus_channel_map[8][8] = {
    { 0 },
    { 0,1 },
    { 0,2,1 },
    { 0,1,2,3 },
    { 0,4,1,2,3 },
    { 0,4,1,2,3,5 },
    { 0,4,1,2,3,5,6 },
    { 0,6,1,2,3,4,5,7 },
};

1354 1355
int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
                              const uint8_t **pp, const uint8_t *desc_list_end,
1356 1357
                              Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
                              MpegTSContext *ts)
1358 1359
{
    const uint8_t *desc_end;
1360
    int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
1361 1362
    char language[252];
    int i;
1363 1364 1365

    desc_tag = get8(pp, desc_list_end);
    if (desc_tag < 0)
1366
        return AVERROR_INVALIDDATA;
1367 1368
    desc_len = get8(pp, desc_list_end);
    if (desc_len < 0)
1369
        return AVERROR_INVALIDDATA;
1370 1371
    desc_end = *pp + desc_len;
    if (desc_end > desc_list_end)
1372
        return AVERROR_INVALIDDATA;
1373

1374
    av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1375

1376
    if (st->codecpar->codec_id == AV_CODEC_ID_NONE &&
1377 1378 1379
        stream_type == STREAM_TYPE_PRIVATE_DATA)
        mpegts_find_stream_type(st, desc_tag, DESC_types);

1380
    switch (desc_tag) {
1381 1382
    case 0x1E: /* SL descriptor */
        desc_es_id = get16(pp, desc_end);
1383 1384
        if (desc_es_id < 0)
            break;
Alex Converse's avatar
Alex Converse committed
1385 1386
        if (ts && ts->pids[pid])
            ts->pids[pid]->es_id = desc_es_id;
1387
        for (i = 0; i < mp4_descr_count; i++)
1388 1389 1390 1391 1392 1393 1394
            if (mp4_descr[i].dec_config_descr_len &&
                mp4_descr[i].es_id == desc_es_id) {
                AVIOContext pb;
                ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
                                  mp4_descr[i].dec_config_descr_len, 0,
                                  NULL, NULL, NULL, NULL);
                ff_mp4_read_dec_config_descr(fc, st, &pb);
1395 1396
                if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
                    st->codecpar->extradata_size > 0)
1397
                    st->need_parsing = 0;
1398
                if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1399 1400
                    mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
            }
1401
        break;
1402
    case 0x1F: /* FMC descriptor */
1403 1404
        if (get16(pp, desc_end) < 0)
            break;
1405
        if (mp4_descr_count > 0 &&
1406
            st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM &&
1407
            mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1408
            AVIOContext pb;
1409
            ffio_init_context(&pb, mp4_descr->dec_config_descr,
1410 1411
                              mp4_descr->dec_config_descr_len, 0,
                              NULL, NULL, NULL, NULL);
1412
            ff_mp4_read_dec_config_descr(fc, st, &pb);
1413 1414
            if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
                st->codecpar->extradata_size > 0)
1415 1416 1417 1418 1419 1420 1421 1422
                st->need_parsing = 0;
        }
        break;
    case 0x56: /* DVB teletext descriptor */
        language[0] = get8(pp, desc_end);
        language[1] = get8(pp, desc_end);
        language[2] = get8(pp, desc_end);
        language[3] = 0;
1423
        av_dict_set(&st->metadata, "language", language, 0);
1424 1425 1426 1427 1428 1429
        break;
    case 0x59: /* subtitling descriptor */
        language[0] = get8(pp, desc_end);
        language[1] = get8(pp, desc_end);
        language[2] = get8(pp, desc_end);
        language[3] = 0;
1430
        /* hearing impaired subtitles detection */
1431
        switch (get8(pp, desc_end)) {
1432 1433 1434 1435 1436 1437 1438 1439 1440
        case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
        case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
        case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
        case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
        case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
        case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
            st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
            break;
        }
1441 1442 1443
        if (st->codecpar->extradata) {
            if (st->codecpar->extradata_size == 4 &&
                memcmp(st->codecpar->extradata, *pp, 4))
1444
                avpriv_request_sample(fc, "DVB sub with multiple IDs");
1445
        } else {
1446 1447 1448 1449
            st->codecpar->extradata = av_malloc(4 + AV_INPUT_BUFFER_PADDING_SIZE);
            if (st->codecpar->extradata) {
                st->codecpar->extradata_size = 4;
                memcpy(st->codecpar->extradata, *pp, 4);
1450 1451 1452
            }
        }
        *pp += 4;
1453
        av_dict_set(&st->metadata, "language", language, 0);
1454 1455
        break;
    case 0x0a: /* ISO 639 language descriptor */
1456 1457 1458 1459 1460
        for (i = 0; i + 4 <= desc_len; i += 4) {
            language[i + 0] = get8(pp, desc_end);
            language[i + 1] = get8(pp, desc_end);
            language[i + 2] = get8(pp, desc_end);
            language[i + 3] = ',';
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
            switch (get8(pp, desc_end)) {
            case 0x01:
                st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
                break;
            case 0x02:
                st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
                break;
            case 0x03:
                st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
                break;
            }
1472
        }
1473
        if (i && language[0]) {
1474
            language[i - 1] = 0;
1475
            av_dict_set(&st->metadata, "language", language, 0);
1476
        }
1477 1478
        break;
    case 0x05: /* registration descriptor */
1479 1480 1481 1482
        st->codecpar->codec_tag = bytestream_get_le32(pp);
        av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
        if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
            mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
1483
        break;
1484 1485 1486 1487
    case 0x7f: /* DVB extension descriptor */
        ext_desc_tag = get8(pp, desc_end);
        if (ext_desc_tag < 0)
            return AVERROR_INVALIDDATA;
1488
        if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
1489
            ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
1490 1491 1492 1493
            if (!st->codecpar->extradata) {
                st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
                                                     AV_INPUT_BUFFER_PADDING_SIZE);
                if (!st->codecpar->extradata)
1494 1495
                    return AVERROR(ENOMEM);

1496 1497
                st->codecpar->extradata_size = sizeof(opus_default_extradata);
                memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
1498 1499 1500 1501 1502

                channel_config_code = get8(pp, desc_end);
                if (channel_config_code < 0)
                    return AVERROR_INVALIDDATA;
                if (channel_config_code <= 0x8) {
1503 1504 1505 1506 1507
                    st->codecpar->extradata[9]  = channels = channel_config_code ? channel_config_code : 2;
                    st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : 255;
                    st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
                    st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
                    memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
1508 1509 1510 1511 1512 1513 1514
                } else {
                    avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
                }
                st->need_parsing = AVSTREAM_PARSE_FULL;
            }
        }
        break;
1515 1516 1517 1518 1519 1520 1521
    default:
        break;
    }
    *pp = desc_end;
    return 0;
}

1522
static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1523
{
1524
    MpegTSContext *ts = filter->u.section_filter.opaque;
1525
    MpegTSSectionFilter *tssf = &filter->u.section_filter;
1526
    SectionHeader h1, *h = &h1;
1527 1528
    PESContext *pes;
    AVStream *st;
1529
    const uint8_t *p, *p_end, *desc_list_end;
1530
    int program_info_length, pcr_pid, pid, stream_type;
1531
    int desc_list_len;
1532
    uint32_t prog_reg_desc = 0; /* registration descriptor */
1533 1534

    int mp4_descr_count = 0;
1535
    Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1536
    int i;
1537

1538
    av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
1539
    hex_dump_debug(ts->stream, section, section_len);
1540

1541 1542 1543 1544
    p_end = section + section_len - 4;
    p = section;
    if (parse_section_header(h, &p, p_end) < 0)
        return;
1545 1546 1547
    if (h->version == tssf->last_ver)
        return;
    tssf->last_ver = h->version;
1548

1549
    av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d\n",
1550
            h->id, h->sec_num, h->last_sec_num);
1551

1552
    if (h->tid != PMT_TID)
1553 1554
        return;

1555
    clear_program(ts, h->id);
1556
    pcr_pid = get16(&p, p_end);
1557 1558
    if (pcr_pid < 0)
        return;
1559
    pcr_pid &= 0x1fff;
1560
    add_pid_to_pmt(ts, h->id, pcr_pid);
1561

1562
    av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
1563

1564
    program_info_length = get16(&p, p_end);
1565 1566
    if (program_info_length < 0)
        return;
1567
    program_info_length &= 0xfff;
1568
    while (program_info_length >= 2) {
1569 1570 1571
        uint8_t tag, len;
        tag = get8(&p, p_end);
        len = get8(&p, p_end);
1572

1573
        av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
1574

1575 1576
        if (len > program_info_length - 2)
            // something else is broken, exit the program_descriptors_loop
1577 1578
            break;
        program_info_length -= len + 2;
1579 1580 1581 1582
        if (tag == 0x1d) { // IOD descriptor
            get8(&p, p_end); // scope
            get8(&p, p_end); // label
            len -= 2;
1583 1584
            mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
                          &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1585
        } else if (tag == 0x05 && len >= 4) { // registration descriptor
1586
            prog_reg_desc = bytestream_get_le32(&p);
1587 1588 1589 1590
            len -= 4;
        }
        p += len;
    }
1591 1592
    p += program_info_length;
    if (p >= p_end)
1593
        goto out;
1594 1595 1596 1597 1598

    // stop parsing after pmt, we found header
    if (!ts->stream->nb_streams)
        ts->stop_parse = 1;

1599 1600

    for (;;) {
1601
        st = 0;
1602
        pes = NULL;
1603 1604 1605
        stream_type = get8(&p, p_end);
        if (stream_type < 0)
            break;
1606
        pid = get16(&p, p_end);
1607 1608
        if (pid < 0)
            break;
1609
        pid &= 0x1fff;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
1610

1611
        /* now create stream */
Baptiste Coudurier's avatar
Baptiste Coudurier committed
1612 1613
        if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
            pes = ts->pids[pid]->u.pes_filter.opaque;
1614
            if (!pes->st) {
1615
                pes->st     = avformat_new_stream(pes->stream, NULL);
1616
                pes->st->id = pes->pid;
1617
            }
Baptiste Coudurier's avatar
Baptiste Coudurier committed
1618
            st = pes->st;
1619
        } else if (stream_type != 0x13) {
1620 1621
            if (ts->pids[pid])
                mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
1622
            pes = add_pes_stream(ts, pid, pcr_pid);
1623 1624 1625 1626
            if (pes) {
                st = avformat_new_stream(pes->stream, NULL);
                st->id = pes->pid;
            }
1627 1628 1629 1630 1631
        } else {
            int idx = ff_find_stream_index(ts->stream, pid);
            if (idx >= 0) {
                st = ts->stream->streams[idx];
            } else {
1632
                st = avformat_new_stream(ts->stream, NULL);
1633
                st->id = pid;
1634
                st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
1635
            }
Baptiste Coudurier's avatar
Baptiste Coudurier committed
1636 1637 1638
        }

        if (!st)
1639
            goto out;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
1640

1641
        if (pes && !pes->stream_type)
1642 1643
            mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);

Baptiste Coudurier's avatar
Baptiste Coudurier committed
1644 1645
        add_pid_to_pmt(ts, h->id, pid);

1646
        ff_program_add_stream_index(ts->stream, h->id, st->index);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
1647

1648
        desc_list_len = get16(&p, p_end);
1649 1650
        if (desc_list_len < 0)
            break;
1651
        desc_list_len &= 0xfff;
1652
        desc_list_end  = p + desc_list_len;
1653
        if (desc_list_end > p_end)
1654
            break;
1655 1656 1657 1658
        for (;;) {
            if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
                                          desc_list_end, mp4_descr,
                                          mp4_descr_count, pid, ts) < 0)
1659
                break;
1660

1661 1662 1663 1664
            if (pes && prog_reg_desc == AV_RL32("HDMV") &&
                stream_type == 0x83 && pes->sub_st) {
                ff_program_add_stream_index(ts->stream, h->id,
                                            pes->sub_st->index);
1665
                pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
1666
            }
1667 1668
        }
        p = desc_list_end;
1669
    }
1670

1671
out:
1672 1673
    for (i = 0; i < mp4_descr_count; i++)
        av_free(mp4_descr[i].dec_config_descr);
1674 1675
}

1676
static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1677
{
1678
    MpegTSContext *ts = filter->u.section_filter.opaque;
1679
    MpegTSSectionFilter *tssf = &filter->u.section_filter;
1680 1681 1682 1683
    SectionHeader h1, *h = &h1;
    const uint8_t *p, *p_end;
    int sid, pmt_pid;

1684
    av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
1685
    hex_dump_debug(ts->stream, section, section_len);
1686

1687
    p_end = section + section_len - 4;
1688
    p     = section;
1689 1690 1691 1692
    if (parse_section_header(h, &p, p_end) < 0)
        return;
    if (h->tid != PAT_TID)
        return;
1693 1694 1695
    if (h->version == tssf->last_ver)
        return;
    tssf->last_ver = h->version;
1696

1697
    clear_programs(ts);
1698
    for (;;) {
1699 1700 1701
        sid = get16(&p, p_end);
        if (sid < 0)
            break;
1702
        pmt_pid = get16(&p, p_end);
1703 1704
        if (pmt_pid < 0)
            break;
1705
        pmt_pid &= 0x1fff;
1706

1707
        av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1708

1709 1710 1711
        if (sid == 0x0000) {
            /* NIT info */
        } else {
1712
            av_new_program(ts->stream, sid);
1713 1714
            if (ts->pids[pmt_pid])
                mpegts_close_filter(ts, ts->pids[pmt_pid]);
Michael Niedermayer's avatar
Michael Niedermayer committed
1715
            mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1716
            add_pat_entry(ts, sid);
1717
            add_pid_to_pmt(ts, sid, 0); // add pat pid to program
1718
            add_pid_to_pmt(ts, sid, pmt_pid);
1719 1720 1721 1722
        }
    }
}

1723
static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1724
{
1725
    MpegTSContext *ts = filter->u.section_filter.opaque;
1726
    MpegTSSectionFilter *tssf = &filter->u.section_filter;
1727 1728 1729 1730 1731
    SectionHeader h1, *h = &h1;
    const uint8_t *p, *p_end, *desc_list_end, *desc_end;
    int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
    char *name, *provider_name;

1732
    av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
1733
    hex_dump_debug(ts->stream, section, section_len);
1734 1735

    p_end = section + section_len - 4;
1736
    p     = section;
1737 1738 1739 1740
    if (parse_section_header(h, &p, p_end) < 0)
        return;
    if (h->tid != SDT_TID)
        return;
1741 1742 1743 1744
    if (h->version == tssf->last_ver)
        return;
    tssf->last_ver = h->version;

1745 1746 1747 1748 1749 1750
    onid = get16(&p, p_end);
    if (onid < 0)
        return;
    val = get8(&p, p_end);
    if (val < 0)
        return;
1751
    for (;;) {
1752 1753 1754 1755 1756 1757
        sid = get16(&p, p_end);
        if (sid < 0)
            break;
        val = get8(&p, p_end);
        if (val < 0)
            break;
1758
        desc_list_len = get16(&p, p_end);
1759 1760
        if (desc_list_len < 0)
            break;
1761
        desc_list_len &= 0xfff;
1762
        desc_list_end  = p + desc_list_len;
1763 1764
        if (desc_list_end > p_end)
            break;
1765
        for (;;) {
1766 1767 1768 1769 1770 1771 1772
            desc_tag = get8(&p, desc_list_end);
            if (desc_tag < 0)
                break;
            desc_len = get8(&p, desc_list_end);
            desc_end = p + desc_len;
            if (desc_end > desc_list_end)
                break;
1773

1774
            av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
1775
                    desc_tag, desc_len);
1776

1777
            switch (desc_tag) {
1778 1779 1780 1781 1782 1783 1784 1785
            case 0x48:
                service_type = get8(&p, p_end);
                if (service_type < 0)
                    break;
                provider_name = getstr8(&p, p_end);
                if (!provider_name)
                    break;
                name = getstr8(&p, p_end);
1786 1787
                if (name) {
                    AVProgram *program = av_new_program(ts->stream, sid);
1788
                    if (program) {
1789
                        av_dict_set(&program->metadata, "service_name", name, 0);
1790 1791
                        av_dict_set(&program->metadata, "service_provider",
                                    provider_name, 0);
1792
                    }
1793
                }
Michael Niedermayer's avatar
Michael Niedermayer committed
1794 1795
                av_free(name);
                av_free(provider_name);
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
                break;
            default:
                break;
            }
            p = desc_end;
        }
        p = desc_list_end;
    }
}

/* handle one TS packet */
1807
static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1808
{
1809
    MpegTSFilter *tss;
1810 1811
    int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
        has_adaptation, has_payload;
1812
    const uint8_t *p, *p_end;
1813
    int64_t pos;
1814

1815
    pid = AV_RB16(packet + 1) & 0x1fff;
1816
    if (pid && discard_pid(ts, pid))
1817
        return 0;
1818 1819
    is_start = packet[1] & 0x40;
    tss = ts->pids[pid];
1820
    if (ts->auto_guess && !tss && is_start) {
1821
        add_pes_stream(ts, pid, -1);
1822 1823 1824
        tss = ts->pids[pid];
    }
    if (!tss)
1825
        return 0;
1826

1827 1828 1829
    afc = (packet[3] >> 4) & 3;
    if (afc == 0) /* reserved value */
        return 0;
1830 1831 1832 1833 1834
    has_adaptation   = afc & 2;
    has_payload      = afc & 1;
    is_discontinuity = has_adaptation &&
                       packet[4] != 0 && /* with length > 0 */
                       (packet[5] & 0x80); /* and discontinuity indicated */
1835

1836 1837
    /* continuity check (currently not used) */
    cc = (packet[3] & 0xf);
1838
    expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1839 1840 1841 1842
    cc_ok = pid == 0x1FFF || // null packet PID
            is_discontinuity ||
            tss->last_cc < 0 ||
            expected_cc == cc;
1843

1844
    tss->last_cc = cc;
1845
    if (!cc_ok) {
1846 1847 1848
        av_log(ts->stream, AV_LOG_WARNING,
               "Continuity check failed for pid %d expected %d got %d\n",
               pid, expected_cc, cc);
1849
        if (tss->type == MPEGTS_PES) {
1850 1851 1852 1853
            PESContext *pc = tss->u.pes_filter.opaque;
            pc->flags |= AV_PKT_FLAG_CORRUPT;
        }
    }
1854

1855
    if (!has_payload)
1856
        return 0;
1857 1858
    p = packet + 4;
    if (has_adaptation) {
1859
        /* skip adaptation field */
1860 1861 1862 1863 1864
        p += p[0] + 1;
    }
    /* if past the end of packet, ignore */
    p_end = packet + TS_PACKET_SIZE;
    if (p >= p_end)
1865
        return 0;
1866

1867
    pos = avio_tell(ts->stream->pb);
1868
    MOD_UNLIKELY(ts->pos47, pos, ts->raw_packet_size, ts->pos);
1869

1870 1871 1872 1873 1874
    if (tss->type == MPEGTS_SECTION) {
        if (is_start) {
            /* pointer field present */
            len = *p++;
            if (p + len > p_end)
1875
                return 0;
1876
            if (len && cc_ok) {
1877
                /* write remaining section bytes */
1878
                write_section_data(ts, tss,
1879
                                   p, len, 0);
1880 1881
                /* check whether filter has been closed */
                if (!ts->pids[pid])
1882
                    return 0;
1883 1884 1885
            }
            p += len;
            if (p < p_end) {
1886
                write_section_data(ts, tss,
1887 1888 1889 1890
                                   p, p_end - p, 1);
            }
        } else {
            if (cc_ok) {
1891
                write_section_data(ts, tss,
1892
                                   p, p_end - p, 0);
1893
            }
1894 1895
        }
    } else {
1896
        int ret;
1897
        // Note: The position here points actually behind the current packet.
1898 1899 1900
        if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
                                            pos - ts->raw_packet_size)) < 0)
            return ret;
1901
    }
1902 1903

    return 0;
1904 1905
}

1906
/* XXX: try to find a better synchro over several packets (use
1907
 * get_packet_size() ?) */
1908
static int mpegts_resync(AVFormatContext *s)
1909
{
1910
    MpegTSContext *ts = s->priv_data;
1911
    AVIOContext *pb = s->pb;
1912 1913
    int c, i;

1914
    for (i = 0; i < ts->resync_size; i++) {
1915
        c = avio_r8(pb);
Anton Khirnov's avatar
Anton Khirnov committed
1916
        if (pb->eof_reached)
1917
            return AVERROR_EOF;
1918
        if (c == 0x47) {
1919
            avio_seek(pb, -1, SEEK_CUR);
1920 1921 1922
            return 0;
        }
    }
1923 1924
    av_log(s, AV_LOG_ERROR,
           "max resync size reached, could not find sync byte\n");
1925
    /* no sync found */
1926
    return AVERROR_INVALIDDATA;
1927 1928
}

1929
/* return AVERROR_something if error or EOF. Return 0 if OK. */
1930 1931
static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
                       const uint8_t **data)
1932
{
1933
    AVIOContext *pb = s->pb;
1934
    int len;
1935

1936
    for (;;) {
1937
        len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
1938
        if (len != TS_PACKET_SIZE)
1939
            return len < 0 ? len : AVERROR_EOF;
1940
        /* check packet sync byte */
1941
        if ((*data)[0] != 0x47) {
1942
            /* find a new packet start */
1943
            avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1944 1945
            if (mpegts_resync(s) < 0)
                return AVERROR(EAGAIN);
1946 1947 1948 1949 1950 1951 1952 1953 1954
            else
                continue;
        } else {
            break;
        }
    }
    return 0;
}

1955 1956 1957 1958 1959 1960 1961 1962
static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
{
    AVIOContext *pb = s->pb;
    int skip = raw_packet_size - TS_PACKET_SIZE;
    if (skip > 0)
        avio_skip(pb, skip);
}

1963 1964 1965
static int handle_packets(MpegTSContext *ts, int nb_packets)
{
    AVFormatContext *s = ts->stream;
1966
    uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
1967
    const uint8_t *data;
1968 1969 1970 1971
    int packet_num, ret = 0;

    if (avio_tell(s->pb) != ts->last_pos) {
        int i;
1972
        av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
1973 1974
        /* seek detected, flush pes buffer */
        for (i = 0; i < NB_PID_MAX; i++) {
1975 1976
            if (ts->pids[i]) {
                if (ts->pids[i]->type == MPEGTS_PES) {
1977 1978 1979 1980
                    PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
                    av_buffer_unref(&pes->buffer);
                    pes->data_index = 0;
                    pes->state = MPEGTS_SKIP; /* skip until pes header */
1981
                }
1982 1983 1984 1985
                ts->pids[i]->last_cc = -1;
            }
        }
    }
1986 1987 1988

    ts->stop_parse = 0;
    packet_num = 0;
1989
    memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1990 1991
    for (;;) {
        if (ts->stop_parse > 0)
1992 1993 1994 1995
            break;
        packet_num++;
        if (nb_packets != 0 && packet_num >= nb_packets)
            break;
1996
        ret = read_packet(s, packet, ts->raw_packet_size, &data);
1997
        if (ret != 0)
1998
            break;
1999 2000
        ret = handle_packet(ts, data);
        finished_reading_packet(s, ts->raw_packet_size);
2001
        if (ret != 0)
2002
            break;
2003
    }
2004 2005
    ts->last_pos = avio_tell(s->pb);
    return ret;
2006
}
2007

2008 2009
static int mpegts_probe(AVProbeData *p)
{
2010
    const int size = p->buf_size;
2011
    int score, fec_score, dvhs_score;
2012
    int check_count = size / TS_FEC_PACKET_SIZE;
2013
#define CHECK_COUNT 10
2014

2015
    if (check_count < CHECK_COUNT)
2016
        return AVERROR_INVALIDDATA;
2017

2018
    score = analyze(p->buf, TS_PACKET_SIZE * check_count,
2019
                    TS_PACKET_SIZE, NULL, 1) * CHECK_COUNT / check_count;
2020
    dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE * check_count,
2021
                         TS_DVHS_PACKET_SIZE, NULL, 1) * CHECK_COUNT / check_count;
2022
    fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE * check_count,
2023
                        TS_FEC_PACKET_SIZE, NULL, 1) * CHECK_COUNT / check_count;
2024
    av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
2025
            score, dvhs_score, fec_score);
2026

2027 2028 2029 2030 2031 2032 2033 2034 2035
    /* we need a clear definition for the returned score otherwise
     * things will become messy sooner or later */
    if (score > fec_score && score > dvhs_score && score > 6)
        return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
    else if (dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6)
        return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
    else if (fec_score > 6)
        return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
    else
2036
        return AVERROR_INVALIDDATA;
2037 2038
}

Diego Biurrun's avatar
Diego Biurrun committed
2039
/* return the 90kHz PCR and the extension for the 27MHz PCR. return
2040 2041
 * (-1) if not available */
static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
2042 2043 2044 2045 2046 2047 2048
{
    int afc, len, flags;
    const uint8_t *p;
    unsigned int v;

    afc = (packet[3] >> 4) & 3;
    if (afc <= 1)
2049
        return AVERROR_INVALIDDATA;
2050
    p   = packet + 4;
2051 2052 2053
    len = p[0];
    p++;
    if (len == 0)
2054
        return AVERROR_INVALIDDATA;
2055 2056 2057
    flags = *p++;
    len--;
    if (!(flags & 0x10))
2058
        return AVERROR_INVALIDDATA;
2059
    if (len < 6)
2060
        return AVERROR_INVALIDDATA;
2061 2062 2063
    v          = AV_RB32(p);
    *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
    *ppcr_low  = ((p[4] & 1) << 8) | p[5];
2064 2065 2066
    return 0;
}

2067
static int mpegts_read_header(AVFormatContext *s)
2068 2069
{
    MpegTSContext *ts = s->priv_data;
2070 2071
    AVIOContext *pb   = s->pb;
    uint8_t buf[5 * 1024];
Michael Niedermayer's avatar
Michael Niedermayer committed
2072
    int len;
2073
    int64_t pos;
2074

2075
    /* read the first 1024 bytes to get packet size */
2076
    pos = avio_tell(pb);
2077
    len = avio_read(pb, buf, sizeof(buf));
2078 2079
    if (len < 0)
        return len;
2080
    if (len != sizeof(buf))
2081
        return AVERROR_BUG;
2082 2083
    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
    if (ts->raw_packet_size <= 0)
2084
        return AVERROR_INVALIDDATA;
2085
    ts->stream     = s;
2086 2087
    ts->auto_guess = 0;

2088
    if (s->iformat == &ff_mpegts_demuxer) {
2089
        /* normal demux */
2090

2091
        /* first do a scan to get all the services */
2092 2093
        if (avio_seek(pb, pos, SEEK_SET) < 0 &&
            (pb->seekable & AVIO_SEEKABLE_NORMAL))
2094
            av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
2095 2096

        mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2097

2098
        mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2099

2100
        handle_packets(ts, s->probesize / ts->raw_packet_size);
Benoit Fouet's avatar
Benoit Fouet committed
2101
        /* if could not find service, enable auto_guess */
2102

Benoit Fouet's avatar
Benoit Fouet committed
2103
        ts->auto_guess = 1;
2104

2105
        av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
2106

2107 2108 2109 2110 2111 2112 2113
        s->ctx_flags |= AVFMTCTX_NOHEADER;
    } else {
        AVStream *st;
        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
        int64_t pcrs[2], pcr_h;
        int packet_count[2];
        uint8_t packet[TS_PACKET_SIZE];
2114
        const uint8_t *data;
2115

2116
        /* only read packets */
2117

2118
        st = avformat_new_stream(s, NULL);
2119
        if (!st)
2120
            return AVERROR(ENOMEM);
2121
        avpriv_set_pts_info(st, 60, 1, 27000000);
2122 2123
        st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
        st->codecpar->codec_id   = AV_CODEC_ID_MPEG2TS;
2124

2125
        /* we iterate until we find two PCRs to estimate the bitrate */
2126 2127
        pcr_pid    = -1;
        nb_pcrs    = 0;
2128
        nb_packets = 0;
2129
        for (;;) {
2130
            ret = read_packet(s, packet, ts->raw_packet_size, &data);
2131
            if (ret < 0)
2132
                return ret;
2133
            pid = AV_RB16(data + 1) & 0x1fff;
2134
            if ((pcr_pid == -1 || pcr_pid == pid) &&
2135 2136
                parse_pcr(&pcr_h, &pcr_l, data) == 0) {
                finished_reading_packet(s, ts->raw_packet_size);
2137 2138 2139 2140 2141 2142
                pcr_pid = pid;
                packet_count[nb_pcrs] = nb_packets;
                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
                nb_pcrs++;
                if (nb_pcrs >= 2)
                    break;
2143 2144
            } else {
                finished_reading_packet(s, ts->raw_packet_size);
2145 2146 2147
            }
            nb_packets++;
        }
2148

2149 2150 2151
        /* NOTE1: the bitrate is computed without the FEC */
        /* NOTE2: it is only the bitrate of the start of the stream */
        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2152 2153
        ts->cur_pcr  = pcrs[0] - ts->pcr_incr * packet_count[0];
        s->bit_rate  = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
2154
        st->codecpar->bit_rate = s->bit_rate;
2155
        st->start_time      = ts->cur_pcr;
2156
        av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
2157
                st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2158
    }
2159

2160
    avio_seek(pb, pos, SEEK_SET);
2161
    return 0;
2162 2163
}

2164 2165
#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)

2166
static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
2167 2168 2169 2170 2171 2172
{
    MpegTSContext *ts = s->priv_data;
    int ret, i;
    int64_t pcr_h, next_pcr_h, pos;
    int pcr_l, next_pcr_l;
    uint8_t pcr_buf[12];
2173
    const uint8_t *data;
2174 2175

    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2176
        return AVERROR(ENOMEM);
2177
    ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2178
    pkt->pos = avio_tell(s->pb);
2179
    if (ret < 0) {
2180
        av_packet_unref(pkt);
2181 2182
        return ret;
    }
2183 2184 2185
    if (data != pkt->data)
        memcpy(pkt->data, data, ts->raw_packet_size);
    finished_reading_packet(s, ts->raw_packet_size);
2186 2187 2188 2189
    if (ts->mpeg2ts_compute_pcr) {
        /* compute exact PCR for each packet */
        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
            /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2190
            pos = avio_tell(s->pb);
2191
            for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
2192
                avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2193
                avio_read(s->pb, pcr_buf, 12);
2194 2195
                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
                    /* XXX: not precise enough */
2196 2197
                    ts->pcr_incr =
                        ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2198 2199 2200 2201
                        (i + 1);
                    break;
                }
            }
2202
            avio_seek(s->pb, pos, SEEK_SET);
2203 2204 2205
            /* no next PCR found: we use previous increment */
            ts->cur_pcr = pcr_h * 300 + pcr_l;
        }
2206
        pkt->pts      = ts->cur_pcr;
2207
        pkt->duration = ts->pcr_incr;
2208
        ts->cur_pcr  += ts->pcr_incr;
2209 2210 2211 2212 2213
    }
    pkt->stream_index = 0;
    return 0;
}

2214
static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
2215 2216
{
    MpegTSContext *ts = s->priv_data;
2217 2218
    int ret, i;

2219
    pkt->size = -1;
2220
    ts->pkt = pkt;
2221 2222 2223
    ret = handle_packets(ts, 0);
    if (ret < 0) {
        /* flush pes data left */
2224
        for (i = 0; i < NB_PID_MAX; i++)
2225 2226 2227 2228
            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
                if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
                    new_pes_packet(pes, pkt);
2229
                    pes->state = MPEGTS_SKIP;
2230 2231 2232 2233 2234 2235
                    ret = 0;
                    break;
                }
            }
    }

2236 2237
    if (!ret && pkt->size < 0)
        ret = AVERROR(EINTR);
2238
    return ret;
2239 2240
}

2241
static void mpegts_free(MpegTSContext *ts)
2242 2243
{
    int i;
Michael Niedermayer's avatar
Michael Niedermayer committed
2244 2245 2246

    clear_programs(ts);

2247 2248 2249
    for (i = 0; i < NB_PID_MAX; i++)
        if (ts->pids[i])
            mpegts_close_filter(ts, ts->pids[i]);
2250
}
2251

2252 2253 2254 2255
static int mpegts_read_close(AVFormatContext *s)
{
    MpegTSContext *ts = s->priv_data;
    mpegts_free(ts);
2256 2257 2258
    return 0;
}

2259
static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2260
                              int64_t *ppos, int64_t pos_limit)
Fabrice Bellard's avatar
Fabrice Bellard committed
2261 2262 2263 2264
{
    MpegTSContext *ts = s->priv_data;
    int64_t pos, timestamp;
    uint8_t buf[TS_PACKET_SIZE];
2265 2266 2267 2268 2269 2270
    int pcr_l, pcr_pid =
        ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
    const int find_next = 1;
    pos =
        ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) *
        ts->raw_packet_size + ts->pos47;
Fabrice Bellard's avatar
Fabrice Bellard committed
2271
    if (find_next) {
2272
        for (;;) {
2273
            avio_seek(s->pb, pos, SEEK_SET);
2274
            if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
Fabrice Bellard's avatar
Fabrice Bellard committed
2275
                return AV_NOPTS_VALUE;
2276
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
Fabrice Bellard's avatar
Fabrice Bellard committed
2277 2278 2279 2280 2281 2282
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
                break;
            }
            pos += ts->raw_packet_size;
        }
    } else {
2283
        for (;;) {
Fabrice Bellard's avatar
Fabrice Bellard committed
2284 2285 2286
            pos -= ts->raw_packet_size;
            if (pos < 0)
                return AV_NOPTS_VALUE;
2287
            avio_seek(s->pb, pos, SEEK_SET);
2288
            if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
Fabrice Bellard's avatar
Fabrice Bellard committed
2289
                return AV_NOPTS_VALUE;
2290
            if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
Fabrice Bellard's avatar
Fabrice Bellard committed
2291 2292 2293 2294 2295 2296 2297
                parse_pcr(&timestamp, &pcr_l, buf) == 0) {
                break;
            }
        }
    }
    *ppos = pos;

2298
    return timestamp;
Fabrice Bellard's avatar
Fabrice Bellard committed
2299 2300
}

2301 2302
static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
{
2303 2304 2305
    MpegTSContext *ts = s->priv_data;
    uint8_t buf[TS_PACKET_SIZE];
    int64_t pos;
2306
    int ret;
2307

2308 2309 2310
    ret = ff_seek_frame_binary(s, stream_index, target_ts, flags);
    if (ret < 0)
        return ret;
2311

2312
    pos = avio_tell(s->pb);
2313

2314
    for (;;) {
2315
        avio_seek(s->pb, pos, SEEK_SET);
2316 2317 2318 2319 2320
        ret = avio_read(s->pb, buf, TS_PACKET_SIZE);
        if (ret < 0)
            return ret;
        if (ret != TS_PACKET_SIZE)
            return AVERROR_EOF;
2321 2322 2323
        // pid = AV_RB16(buf + 1) & 0x1fff;
        if (buf[1] & 0x40)
            break;
2324 2325
        pos += ts->raw_packet_size;
    }
2326
    avio_seek(s->pb, pos, SEEK_SET);
2327 2328 2329 2330

    return 0;
}

2331 2332 2333
/**************************************************************/
/* parsing functions - called from other demuxers such as RTP */

2334
MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2335 2336
{
    MpegTSContext *ts;
2337

2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
    ts = av_mallocz(sizeof(MpegTSContext));
    if (!ts)
        return NULL;
    /* no stream case, currently used by RTP */
    ts->raw_packet_size = TS_PACKET_SIZE;
    ts->stream = s;
    ts->auto_guess = 1;
    return ts;
}

/* return the consumed length if a packet was output, or -1 if no
2349
 * packet is output */
2350
int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2351
                           const uint8_t *buf, int len)
2352 2353 2354 2355 2356 2357
{
    int len1;

    len1 = len;
    ts->pkt = pkt;
    ts->stop_parse = 0;
2358 2359
    for (;;) {
        if (ts->stop_parse > 0)
2360 2361
            break;
        if (len < TS_PACKET_SIZE)
2362
            return AVERROR_INVALIDDATA;
2363
        if (buf[0] != 0x47) {
2364
            buf++;
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374
            len--;
        } else {
            handle_packet(ts, buf);
            buf += TS_PACKET_SIZE;
            len -= TS_PACKET_SIZE;
        }
    }
    return len1 - len;
}

2375
void ff_mpegts_parse_close(MpegTSContext *ts)
2376
{
2377
    mpegts_free(ts);
2378 2379 2380
    av_free(ts);
}

2381
AVInputFormat ff_mpegts_demuxer = {
2382
    .name           = "mpegts",
2383
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2384 2385 2386 2387 2388 2389 2390
    .priv_data_size = sizeof(MpegTSContext),
    .read_probe     = mpegts_probe,
    .read_header    = mpegts_read_header,
    .read_packet    = mpegts_read_packet,
    .read_close     = mpegts_read_close,
    .read_seek      = read_seek,
    .read_timestamp = mpegts_get_pcr,
2391
    .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2392
    .priv_class     = &mpegts_class,
2393
};
2394

2395
AVInputFormat ff_mpegtsraw_demuxer = {
2396
    .name           = "mpegtsraw",
2397
    .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2398 2399 2400 2401 2402 2403
    .priv_data_size = sizeof(MpegTSContext),
    .read_header    = mpegts_read_header,
    .read_packet    = mpegts_raw_read_packet,
    .read_close     = mpegts_read_close,
    .read_seek      = read_seek,
    .read_timestamp = mpegts_get_pcr,
2404 2405
    .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
    .priv_class     = &mpegtsraw_class,
2406
};