libavformat/mpegts.c
fe9cf0d4
 /*
41ed7ab4
  * MPEG-2 transport stream (aka DVB) demuxer
406792e7
  * Copyright (c) 2002-2003 Fabrice Bellard
fe9cf0d4
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
19720f15
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
fe9cf0d4
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
fe9cf0d4
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
fe9cf0d4
  *
19720f15
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
fe9cf0d4
  */
245976da
 
1afddbe5
 #include "libavutil/buffer.h"
245976da
 #include "libavutil/crc.h"
229843aa
 #include "libavutil/internal.h"
6a5d31ac
 #include "libavutil/intreadwrite.h"
17a5556d
 #include "libavutil/log.h"
d2d67e42
 #include "libavutil/dict.h"
d3f751e6
 #include "libavutil/mathematics.h"
17a5556d
 #include "libavutil/opt.h"
7846280d
 #include "libavutil/avassert.h"
4f1db48e
 #include "libavcodec/bytestream.h"
ca65932b
 #include "libavcodec/get_bits.h"
61e42c11
 #include "libavcodec/opus.h"
fe9cf0d4
 #include "avformat.h"
5dbafeb7
 #include "mpegts.h"
ecfb51d1
 #include "internal.h"
ae99313a
 #include "avio_internal.h"
e5e3897b
 #include "mpeg.h"
798c6fac
 #include "isom.h"
fe9cf0d4
 
41ed7ab4
 /* maximum size in which we look for synchronization if
  * synchronization is lost */
1303d62d
 #define MAX_RESYNC_SIZE 65536
5dbafeb7
 
86ba2327
 #define MAX_PES_PAYLOAD 200 * 1024
0c137557
 
c3bc6096
 #define MAX_MP4_DESCR_COUNT 16
 
86ba2327
 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend)                \
     do {                                                                       \
5397386e
         if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
86ba2327
             (modulus) = (dividend) % (divisor);                                \
         (prev_dividend) = (dividend);                                          \
5397386e
     } while (0)
 
5dbafeb7
 enum MpegTSFilterType {
     MPEGTS_PES,
     MPEGTS_SECTION,
d83a5b52
     MPEGTS_PCR,
fe9cf0d4
 };
 
b474d1f3
 typedef struct MpegTSFilter MpegTSFilter;
 
86ba2327
 typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
4acc86bc
                          int is_start, int64_t pos);
fe9cf0d4
 
5dbafeb7
 typedef struct MpegTSPESFilter {
     PESCallback *pes_cb;
     void *opaque;
 } MpegTSPESFilter;
 
86ba2327
 typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
5dbafeb7
 
86ba2327
 typedef void SetServiceCallback (void *opaque, int ret);
5dbafeb7
 
 typedef struct MpegTSSectionFilter {
     int section_index;
     int section_h_size;
82de8d71
     int last_ver;
e0153145
     unsigned crc;
     unsigned last_crc;
5dbafeb7
     uint8_t *section_buf;
86ba2327
     unsigned int check_crc : 1;
     unsigned int end_of_section_reached : 1;
5dbafeb7
     SectionCallback *section_cb;
     void *opaque;
 } MpegTSSectionFilter;
 
b474d1f3
 struct MpegTSFilter {
fe9cf0d4
     int pid;
c5302670
     int es_id;
fe9cf0d4
     int last_cc; /* last cc code (-1 if first packet) */
4acc86bc
     int64_t last_pcr;
5dbafeb7
     enum MpegTSFilterType type;
     union {
         MpegTSPESFilter pes_filter;
         MpegTSSectionFilter section_filter;
     } u;
b474d1f3
 };
5dbafeb7
 
172d1171
 #define MAX_PIDS_PER_PROGRAM 64
8c39a758
 struct Program {
86ba2327
     unsigned int id; // program id/service id
172d1171
     unsigned int nb_pids;
     unsigned int pids[MAX_PIDS_PER_PROGRAM];
6eda91ad
 
     /** have we found pmt for this program */
     int pmt_found;
8c39a758
 };
172d1171
 
0694a009
 struct MpegTSContext {
17a5556d
     const AVClass *class;
5dbafeb7
     /* user data */
     AVFormatContext *stream;
86ba2327
     /** raw packet size, including FEC if present */
e995cfca
     int raw_packet_size;
5fd63f3c
 
c666c59a
     int size_stat[3];
     int size_stat_count;
 #define SIZE_STAT_THRESHOLD 10
 
5b13778f
     int64_t pos47_full;
5fd63f3c
 
86ba2327
     /** if true, all pids are analyzed to find streams */
e995cfca
     int auto_guess;
5dbafeb7
 
86ba2327
     /** compute exact PCR for each transport stream packet */
e995cfca
     int mpeg2ts_compute_pcr;
b45a7a18
 
a7bb12a3
     /** fix dvb teletext pts                                 */
     int fix_teletext_pts;
 
86ba2327
     int64_t cur_pcr;    /**< used to estimate the exact PCR */
     int pcr_incr;       /**< used to estimate the exact PCR */
115329f1
 
5dbafeb7
     /* data needed to handle file based ts */
86ba2327
     /** stop parsing loop */
e995cfca
     int stop_parse;
86ba2327
     /** packet containing Audio/Video data */
e995cfca
     AVPacket *pkt;
86ba2327
     /** to detect seek */
0c137557
     int64_t last_pos;
5dbafeb7
 
c6c172d1
     int skip_changes;
4470a3ee
     int skip_clear;
c6c172d1
 
29b1af40
     int scan_all_pmts;
 
7968059e
     int resync_size;
 
5dbafeb7
     /******************************************/
     /* private mpegts data */
     /* scan context */
86ba2327
     /** structure to keep track of Program->pids mapping */
172d1171
     unsigned int nb_prg;
8c39a758
     struct Program *prg;
115329f1
 
f464b02d
     int8_t crc_validity[NB_PID_MAX];
e995cfca
     /** filters for various streams specified by PMT + for the PAT and PMT */
5dbafeb7
     MpegTSFilter *pids[NB_PID_MAX];
327cd0d0
     int current_pid;
0694a009
 };
fe9cf0d4
 
7968059e
 #define MPEGTS_OPTIONS \
fedc4226
     { "resync_size",   "set 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 }
7968059e
 
ee83f667
 static const AVOption options[] = {
     MPEGTS_OPTIONS,
43ecec0f
     {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
a7bb12a3
      {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
fedc4226
     {"ts_packetsize", "output option carrying the raw packet size", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
c849b00b
      {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
43ecec0f
     {"scan_all_pmts",   "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
29b1af40
      { .i64 =  -1}, -1, 1,  AV_OPT_FLAG_DECODING_PARAM },
43ecec0f
     {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
c6c172d1
      {.i64 = 0}, 0, 1, 0 },
43ecec0f
     {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
4470a3ee
      {.i64 = 0}, 0, 1, 0 },
a7bb12a3
     { NULL },
 };
 
 static const AVClass mpegts_class = {
     .class_name = "mpegts demuxer",
     .item_name  = av_default_item_name,
ee83f667
     .option     = options,
17a5556d
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
e489e834
 static const AVOption raw_options[] = {
     MPEGTS_OPTIONS,
fedc4226
     { "compute_pcr",   "compute exact PCR for each transport stream packet",
43ecec0f
           offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
e489e834
           { .i64 = 0 }, 0, 1,  AV_OPT_FLAG_DECODING_PARAM },
fedc4226
     { "ts_packetsize", "output option carrying the raw packet size",
e489e834
       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 },
     { NULL },
 };
 
 static const AVClass mpegtsraw_class = {
     .class_name = "mpegtsraw demuxer",
     .item_name  = av_default_item_name,
     .option     = raw_options,
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
ecc31d1d
 /* TS stream handling */
 
 enum MpegTSState {
     MPEGTS_HEADER = 0,
b2984add
     MPEGTS_PESHEADER,
ecc31d1d
     MPEGTS_PESHEADER_FILL,
     MPEGTS_PAYLOAD,
     MPEGTS_SKIP,
 };
 
 /* enough for PES header + length */
b2984add
 #define PES_START_SIZE  6
 #define PES_HEADER_SIZE 9
ecc31d1d
 #define MAX_PES_HEADER_SIZE (9 + 255)
 
10061cd6
 typedef struct PESContext {
ecc31d1d
     int pid;
dbf6b678
     int pcr_pid; /**< if -1 then all packets containing PCR are considered */
ecc31d1d
     int stream_type;
     MpegTSContext *ts;
     AVFormatContext *stream;
     AVStream *st;
63380b5e
     AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
ecc31d1d
     enum MpegTSState state;
     /* used to get the format */
     int data_index;
ce9e3165
     int flags; /**< copied to the AVPacket flags */
ecc31d1d
     int total_size;
     int pes_header_size;
63380b5e
     int extended_stream_id;
14f7a3d5
     uint8_t stream_id;
ecc31d1d
     int64_t pts, dts;
4c6b49bf
     int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
ecc31d1d
     uint8_t header[MAX_PES_HEADER_SIZE];
1afddbe5
     AVBufferRef *buffer;
ca65932b
     SLConfigDescr sl;
10061cd6
 } PESContext;
ecc31d1d
 
66355be3
 extern AVInputFormat ff_mpegts_demuxer;
6369638b
 
6eda91ad
 static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
 {
     int i;
ceb0d79f
     for (i = 0; i < ts->nb_prg; i++) {
         if (ts->prg[i].id == programid) {
6eda91ad
             return &ts->prg[i];
         }
     }
     return NULL;
 }
 
4c41fc88
 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
 {
     AVProgram *prg = NULL;
     int i;
c6c172d1
 
ceb0d79f
     for (i = 0; i < ts->stream->nb_programs; i++)
         if (ts->stream->programs[i]->id == programid) {
4c41fc88
             prg = ts->stream->programs[i];
             break;
         }
     if (!prg)
         return;
     prg->nb_stream_indexes = 0;
 }
 
172d1171
 static void clear_program(MpegTSContext *ts, unsigned int programid)
 {
     int i;
 
4c41fc88
     clear_avprogram(ts, programid);
86ba2327
     for (i = 0; i < ts->nb_prg; i++)
ceb0d79f
         if (ts->prg[i].id == programid) {
172d1171
             ts->prg[i].nb_pids = 0;
6eda91ad
             ts->prg[i].pmt_found = 0;
         }
172d1171
 }
 
 static void clear_programs(MpegTSContext *ts)
 {
     av_freep(&ts->prg);
86ba2327
     ts->nb_prg = 0;
172d1171
 }
 
 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
 {
8c39a758
     struct Program *p;
f369b935
     if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
         ts->nb_prg = 0;
172d1171
         return;
f369b935
     }
172d1171
     p = &ts->prg[ts->nb_prg];
     p->id = programid;
     p->nb_pids = 0;
6eda91ad
     p->pmt_found = 0;
172d1171
     ts->nb_prg++;
 }
 
86ba2327
 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
                            unsigned int pid)
172d1171
 {
6eda91ad
     struct Program *p = get_program(ts, programid);
a6593f7c
     int i;
86ba2327
     if (!p)
172d1171
         return;
 
86ba2327
     if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
172d1171
         return;
a6593f7c
 
78659418
     for (i = 0; i < p->nb_pids; i++)
a6593f7c
         if (p->pids[i] == pid)
             return;
 
172d1171
     p->pids[p->nb_pids++] = pid;
 }
 
6eda91ad
 static void set_pmt_found(MpegTSContext *ts, unsigned int programid)
 {
     struct Program *p = get_program(ts, programid);
ceb0d79f
     if (!p)
6eda91ad
         return;
 
     p->pmt_found = 1;
 }
 
5501afa6
 static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
 {
     int i;
ceb0d79f
     for (i = 0; i < s->nb_programs; i++) {
         if (s->programs[i]->id == programid) {
5501afa6
             s->programs[i]->pcr_pid = pid;
             break;
         }
     }
 }
 
172d1171
 /**
adbfc605
  * @brief discard_pid() decides if the pid is to be discarded according
172d1171
  *                      to caller's programs selection
adbfc605
  * @param ts    : - TS context
  * @param pid   : - pid
  * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
172d1171
  *         0 otherwise
  */
 static int discard_pid(MpegTSContext *ts, unsigned int pid)
 {
     int i, j, k;
     int used = 0, discarded = 0;
8c39a758
     struct Program *p;
c84ea750
 
     /* If none of the programs have .discard=AVDISCARD_ALL then there's
86ba2327
      * no way we have to discard this packet */
     for (k = 0; k < ts->stream->nb_programs; k++)
c84ea750
         if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
             break;
     if (k == ts->stream->nb_programs)
         return 0;
 
86ba2327
     for (i = 0; i < ts->nb_prg; i++) {
172d1171
         p = &ts->prg[i];
86ba2327
         for (j = 0; j < p->nb_pids; j++) {
             if (p->pids[j] != pid)
172d1171
                 continue;
86ba2327
             // 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)
172d1171
                         discarded++;
                     else
                         used++;
                 }
             }
         }
     }
 
ccd425e7
     return !used && discarded;
172d1171
 }
 
e995cfca
 /**
49bd8e4b
  *  Assemble PES packets out of TS packets, and then call the "section_cb"
e995cfca
  *  function when they are complete.
  */
86359543
 static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
5dbafeb7
                                const uint8_t *buf, int buf_size, int is_start)
 {
     MpegTSSectionFilter *tss = &tss1->u.section_filter;
     int len;
115329f1
 
5dbafeb7
     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) {
80fb8234
         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
5dbafeb7
         if (len > 4096)
             return;
         tss->section_h_size = len;
     }
 
86ba2327
     if (tss->section_h_size != -1 &&
         tss->section_index >= tss->section_h_size) {
f464b02d
         int crc_valid = 1;
5dbafeb7
         tss->end_of_section_reached = 1;
f464b02d
 
ceb0d79f
         if (tss->check_crc) {
f464b02d
             crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
e0153145
             if (tss->section_h_size >= 4)
                 tss->crc = AV_RB32(tss->section_buf + tss->section_h_size - 4);
 
ceb0d79f
             if (crc_valid) {
f464b02d
                 ts->crc_validity[ tss1->pid ] = 100;
ceb0d79f
             }else if (ts->crc_validity[ tss1->pid ] > -10) {
f464b02d
                 ts->crc_validity[ tss1->pid ]--;
             }else
                 crc_valid = 2;
         }
4b6be54b
         if (crc_valid) {
4d9a577e
             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
4b6be54b
             if (crc_valid != 1)
                 tss->last_ver = -1;
         }
5dbafeb7
     }
 }
 
6bab55b8
 static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
                                         enum MpegTSFilterType type)
5dbafeb7
 {
     MpegTSFilter *filter;
115329f1
 
e9391ab1
     av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
ebcf352a
 
5dbafeb7
     if (pid >= NB_PID_MAX || ts->pids[pid])
         return NULL;
     filter = av_mallocz(sizeof(MpegTSFilter));
115329f1
     if (!filter)
5dbafeb7
         return NULL;
     ts->pids[pid] = filter;
86ba2327
 
6bab55b8
     filter->type    = type;
86ba2327
     filter->pid     = pid;
     filter->es_id   = -1;
5dbafeb7
     filter->last_cc = -1;
4acc86bc
     filter->last_pcr= -1;
86ba2327
 
6bab55b8
     return filter;
 }
 
 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
                                                 unsigned int pid,
                                                 SectionCallback *section_cb,
                                                 void *opaque,
                                                 int check_crc)
 {
     MpegTSFilter *filter;
     MpegTSSectionFilter *sec;
 
     if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION)))
         return NULL;
5dbafeb7
     sec = &filter->u.section_filter;
86ba2327
     sec->section_cb  = section_cb;
     sec->opaque      = opaque;
5dbafeb7
     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
86ba2327
     sec->check_crc   = check_crc;
82de8d71
     sec->last_ver    = -1;
 
5dbafeb7
     if (!sec->section_buf) {
         av_free(filter);
         return NULL;
     }
     return filter;
 }
 
7b49ce2e
 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
86ba2327
                                             PESCallback *pes_cb,
                                             void *opaque)
5dbafeb7
 {
     MpegTSFilter *filter;
     MpegTSPESFilter *pes;
 
6bab55b8
     if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
5dbafeb7
         return NULL;
86ba2327
 
5dbafeb7
     pes = &filter->u.pes_filter;
     pes->pes_cb = pes_cb;
     pes->opaque = opaque;
     return filter;
 }
 
d83a5b52
 static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
 {
     return mpegts_open_filter(ts, pid, MPEGTS_PCR);
 }
 
7b49ce2e
 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
5dbafeb7
 {
     int pid;
 
     pid = filter->pid;
     if (filter->type == MPEGTS_SECTION)
         av_freep(&filter->u.section_filter.section_buf);
dcd913d9
     else if (filter->type == MPEGTS_PES) {
0c137557
         PESContext *pes = filter->u.pes_filter.opaque;
1afddbe5
         av_buffer_unref(&pes->buffer);
dcd913d9
         /* referenced private data will be freed later in
cd3716b9
          * avformat_close_input */
dcd913d9
         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
             av_freep(&filter->u.pes_filter.opaque);
         }
     }
ec7d0d2e
 
5dbafeb7
     av_free(filter);
     ts->pids[pid] = NULL;
 }
 
38a6242b
 static int analyze(const uint8_t *buf, int size, int packet_size,
1509c018
                    int probe)
86ba2327
 {
cf5ec607
     int stat[TS_MAX_PACKET_SIZE];
296cd9c4
     int stat_all = 0;
a0b8f70c
     int i;
86ba2327
     int best_score = 0;
a0b8f70c
 
ceb0d79f
     memset(stat, 0, packet_size * sizeof(*stat));
a0b8f70c
 
ceb0d79f
     for (i = 0; i < size - 3; i++) {
e01b19de
         if (buf[i] == 0x47) {
             int pid = AV_RB16(buf+1) & 0x1FFF;
             int asc = buf[i + 3] & 0x30;
             if (!probe || pid == 0x1FFF || asc) {
                 int x = i % packet_size;
                 stat[x]++;
                 stat_all++;
                 if (stat[x] > best_score) {
                     best_score = stat[x];
                 }
a0b8f70c
             }
         }
     }
 
296cd9c4
     return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
a0b8f70c
 }
 
fe9cf0d4
 /* autodetect fec presence. Must have at least 1024 bytes  */
5dbafeb7
 static int get_packet_size(const uint8_t *buf, int size)
fe9cf0d4
 {
5d4d67e0
     int score, fec_score, dvhs_score;
fe9cf0d4
 
     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
ca80e158
         return AVERROR_INVALIDDATA;
115329f1
 
38a6242b
     score      = analyze(buf, size, TS_PACKET_SIZE,      0);
     dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, 0);
     fec_score  = analyze(buf, size, TS_FEC_PACKET_SIZE,  0);
1a3eb042
     av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
72eaba5e
             score, dvhs_score, fec_score);
115329f1
 
86ba2327
     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
ca80e158
         return AVERROR_INVALIDDATA;
fe9cf0d4
 }
 
5dbafeb7
 typedef struct SectionHeader {
     uint8_t tid;
     uint16_t id;
     uint8_t version;
     uint8_t sec_num;
     uint8_t last_sec_num;
 } SectionHeader;
 
4e8d01f2
 static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
 {
e0153145
     if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
4e8d01f2
         return 1;
 
     tssf->last_ver = h->version;
e0153145
     tssf->last_crc = tssf->crc;
4e8d01f2
 
     return 0;
 }
 
5dbafeb7
 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
fe9cf0d4
 {
5dbafeb7
     const uint8_t *p;
     int c;
 
     p = *pp;
     if (p >= p_end)
ca80e158
         return AVERROR_INVALIDDATA;
86ba2327
     c   = *p++;
5dbafeb7
     *pp = p;
     return c;
fe9cf0d4
 }
 
5dbafeb7
 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
 {
     const uint8_t *p;
     int c;
 
     p = *pp;
1b3b018a
     if (1 >= p_end - p)
ca80e158
         return AVERROR_INVALIDDATA;
86ba2327
     c   = AV_RB16(p);
     p  += 2;
5dbafeb7
     *pp = p;
     return c;
 }
 
eac778de
 /* read and allocate a DVB string preceded by its length */
5dbafeb7
 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
fe9cf0d4
 {
     int len;
5dbafeb7
     const uint8_t *p;
     char *str;
fe9cf0d4
 
86ba2327
     p   = *pp;
5dbafeb7
     len = get8(&p, p_end);
     if (len < 0)
         return NULL;
1b3b018a
     if (len > p_end - p)
5dbafeb7
         return NULL;
     str = av_malloc(len + 1);
     if (!str)
         return NULL;
     memcpy(str, p, len);
     str[len] = '\0';
86ba2327
     p  += len;
5dbafeb7
     *pp = p;
     return str;
 }
 
115329f1
 static int parse_section_header(SectionHeader *h,
5dbafeb7
                                 const uint8_t **pp, const uint8_t *p_end)
 {
     int val;
 
     val = get8(pp, p_end);
     if (val < 0)
ca80e158
         return val;
5dbafeb7
     h->tid = val;
     *pp += 2;
86ba2327
     val  = get16(pp, p_end);
5dbafeb7
     if (val < 0)
ca80e158
         return val;
5dbafeb7
     h->id = val;
     val = get8(pp, p_end);
     if (val < 0)
ca80e158
         return val;
5dbafeb7
     h->version = (val >> 1) & 0x1f;
     val = get8(pp, p_end);
     if (val < 0)
ca80e158
         return val;
5dbafeb7
     h->sec_num = val;
     val = get8(pp, p_end);
     if (val < 0)
ca80e158
         return val;
5dbafeb7
     h->last_sec_num = val;
fe9cf0d4
     return 0;
5dbafeb7
 }
 
daf8cf35
 typedef struct StreamType {
08f94e98
     uint32_t stream_type;
72415b2a
     enum AVMediaType codec_type;
36ef5369
     enum AVCodecID codec_id;
08f94e98
 } StreamType;
 
 static const StreamType ISO_types[] = {
36ef5369
     { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
     { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
86ba2327
     { 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      },
c41bf905
     /* Makito encoder sets stream type 0x11 for AAC,
      * so auto-detect LOAS/LATM instead of hardcoding it. */
f8b6d481
 #if !CONFIG_LOAS_DEMUXER
86ba2327
     { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM   }, /* LATM syntax */
f8b6d481
 #endif
86ba2327
     { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
373b8206
     { 0x1c, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC        },
a9d700f2
     { 0x20, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
42bc768e
     { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000   },
86ba2327
     { 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        },
08f94e98
     { 0 },
 };
 
 static const StreamType HDMV_types[] = {
86ba2327
     { 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*/
ceb0d79f
     { 0xa1, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3              }, /* E-AC3 Secondary Audio */
     { 0xa2, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS Express Secondary Audio */
36ef5369
     { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
5d12d7de
     { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
08f94e98
     { 0 },
 };
 
5db3c947
 /* SCTE types */
 static const StreamType SCTE_types[] = {
     { 0x86, AVMEDIA_TYPE_DATA,  AV_CODEC_ID_SCTE_35    },
     { 0 },
 };
 
08f94e98
 /* ATSC ? */
 static const StreamType MISC_types[] = {
86ba2327
     { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
     { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
08f94e98
     { 0 },
 };
 
 static const StreamType REGD_types[] = {
86ba2327
     { 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   },
80d14de5
     { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3  },
86ba2327
     { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC  },
ceb0d79f
     { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA,  AV_CODEC_ID_SMPTE_KLV },
4b38df82
     { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA,  AV_CODEC_ID_TIMED_ID3 },
86ba2327
     { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1   },
61e42c11
     { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS  },
08f94e98
     { 0 },
 };
 
69a042ee
 static const StreamType METADATA_types[] = {
     { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
4a4437c0
     { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
69a042ee
     { 0 },
 };
 
6a2a50f8
 /* descriptor present */
 static const StreamType DESC_types[] = {
86ba2327
     { 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          },
36ef5369
     { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
     { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
896f2b32
     { 0 },
6a2a50f8
 };
 
08f94e98
 static void mpegts_find_stream_type(AVStream *st,
86ba2327
                                     uint32_t stream_type,
                                     const StreamType *types)
08f94e98
 {
86ba2327
     for (; types->stream_type; types++)
08f94e98
         if (stream_type == types->stream_type) {
6f69f7a8
             if (st->codecpar->codec_type != types->codec_type ||
                 st->codecpar->codec_id   != types->codec_id) {
                 st->codecpar->codec_type = types->codec_type;
                 st->codecpar->codec_id   = types->codec_id;
                 st->internal->need_context_update = 1;
             }
             st->request_probe        = 0;
08f94e98
             return;
         }
 }
 
b3f9f7a3
 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
                                   uint32_t stream_type, uint32_t prog_reg_desc)
08f94e98
 {
6f69f7a8
     int old_codec_type = st->codecpar->codec_type;
     int old_codec_id   = st->codecpar->codec_id;
     int old_codec_tag  = st->codecpar->codec_tag;
4facddd5
 
6f69f7a8
     if (avcodec_is_open(st->internal->avctx)) {
         av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, internal codec is open\n");
4facddd5
         return 0;
     }
 
c3f9ebf7
     avpriv_set_pts_info(st, 33, 1, 90000);
86ba2327
     st->priv_data         = pes;
9200514a
     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
     st->codecpar->codec_id   = AV_CODEC_ID_NONE;
86ba2327
     st->need_parsing      = AVSTREAM_PARSE_FULL;
     pes->st          = st;
b3f9f7a3
     pes->stream_type = stream_type;
08f94e98
 
b3f9f7a3
     av_log(pes->stream, AV_LOG_DEBUG,
            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
86ba2327
            st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
08f94e98
 
9200514a
     st->codecpar->codec_tag = pes->stream_type;
7103a77b
 
f2c357d9
     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
ca72cd13
     if (pes->stream_type == 4 || pes->stream_type == 0x0f)
4bec36f9
         st->request_probe = 50;
6aaf6db2
     if ((prog_reg_desc == AV_RL32("HDMV") ||
          prog_reg_desc == AV_RL32("HDPR")) &&
9200514a
         st->codecpar->codec_id == AV_CODEC_ID_NONE) {
f2c357d9
         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
63380b5e
         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)
b3f9f7a3
                 return AVERROR(ENOMEM);
63380b5e
             memcpy(sub_pes, pes, sizeof(*sub_pes));
 
84ad31ff
             sub_st = avformat_new_stream(pes->stream, NULL);
63380b5e
             if (!sub_st) {
                 av_free(sub_pes);
b3f9f7a3
                 return AVERROR(ENOMEM);
63380b5e
             }
 
84ad31ff
             sub_st->id = pes->pid;
c3f9ebf7
             avpriv_set_pts_info(sub_st, 33, 1, 90000);
86ba2327
             sub_st->priv_data         = sub_pes;
9200514a
             sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
             sub_st->codecpar->codec_id   = AV_CODEC_ID_AC3;
86ba2327
             sub_st->need_parsing      = AVSTREAM_PARSE_FULL;
             sub_pes->sub_st           = pes->sub_st = sub_st;
63380b5e
         }
     }
9200514a
     if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
f2c357d9
         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
6f69f7a8
     if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
         st->codecpar->codec_id  = old_codec_id;
         st->codecpar->codec_type = old_codec_type;
e78d1a59
     }
6f69f7a8
     if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
d59a033a
             (st->request_probe > 0 && st->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
3692d859
         st->probe_packets > 0 &&
b64e7043
         stream_type == STREAM_TYPE_PRIVATE_DATA) {
6f69f7a8
         st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
         st->codecpar->codec_id   = AV_CODEC_ID_BIN_DATA;
d59a033a
         st->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
     }
08f94e98
 
6f69f7a8
     /* queue a context update if properties changed */
     if (old_codec_type != st->codecpar->codec_type ||
         old_codec_id   != st->codecpar->codec_id   ||
         old_codec_tag  != st->codecpar->codec_tag)
         st->internal->need_context_update = 1;
08f94e98
 
b3f9f7a3
     return 0;
08f94e98
 }
5dbafeb7
 
d7ca9149
 static void reset_pes_packet_state(PESContext *pes)
 {
     pes->pts        = AV_NOPTS_VALUE;
     pes->dts        = AV_NOPTS_VALUE;
     pes->data_index = 0;
     pes->flags      = 0;
a7827432
     av_buffer_unref(&pes->buffer);
d7ca9149
 }
 
5db3c947
 static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
 {
     av_init_packet(pkt);
79d232fc
     pkt->data = (uint8_t *)buffer;
5db3c947
     pkt->size = len;
 }
 
14f7a3d5
 static int new_pes_packet(PESContext *pes, AVPacket *pkt)
609d8646
 {
f51a271f
     uint8_t *sd;
14f7a3d5
 
609d8646
     av_init_packet(pkt);
 
1afddbe5
     pkt->buf  = pes->buffer;
     pkt->data = pes->buffer->data;
609d8646
     pkt->size = pes->data_index;
50815142
 
86ba2327
     if (pes->total_size != MAX_PES_PAYLOAD &&
         pes->pes_header_size + pes->data_index != pes->total_size +
         PES_START_SIZE) {
03990448
         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
50815142
         pes->flags |= AV_PKT_FLAG_CORRUPT;
     }
059a9348
     memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
609d8646
 
     // 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 */
86ba2327
     pkt->pos   = pes->ts_packet_pos;
ce9e3165
     pkt->flags = pes->flags;
609d8646
 
a7827432
     pes->buffer = NULL;
d7ca9149
     reset_pes_packet_state(pes);
14f7a3d5
 
     sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
     if (!sd)
         return AVERROR(ENOMEM);
     *sd = pes->stream_id;
 
     return 0;
609d8646
 }
 
b2b12a10
 static uint64_t get_ts64(GetBitContext *gb, int bits)
ca65932b
 {
4a310a19
     if (get_bits_left(gb) < bits)
         return AV_NOPTS_VALUE;
57cee850
     return get_bits64(gb, bits);
ca65932b
 }
 
86ba2327
 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
                           const uint8_t *buf, int buf_size)
ca65932b
 {
     GetBitContext gb;
     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;
29d147c9
     uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
     int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
e732d0f6
 
27f6da29
     memcpy(buf_padded, buf, buf_padded_size);
 
     init_get_bits(&gb, buf_padded, buf_padded_size * 8);
ca65932b
 
     if (sl->use_au_start)
         au_start_flag = get_bits1(&gb);
     if (sl->use_au_end)
         au_end_flag = get_bits1(&gb);
     if (!sl->use_au_start && !sl->use_au_end)
         au_start_flag = au_end_flag = 1;
     if (sl->ocr_len > 0)
         ocr_flag = get_bits1(&gb);
     if (sl->use_idle)
         idle_flag = get_bits1(&gb);
     if (sl->use_padding)
         padding_flag = get_bits1(&gb);
     if (padding_flag)
         padding_bits = get_bits(&gb, 3);
 
     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
         if (sl->packet_seq_num_len)
             skip_bits_long(&gb, sl->packet_seq_num_len);
         if (sl->degr_prior_len)
             if (get_bits1(&gb))
                 skip_bits(&gb, sl->degr_prior_len);
         if (ocr_flag)
             skip_bits_long(&gb, sl->ocr_len);
         if (au_start_flag) {
             if (sl->use_rand_acc_pt)
                 get_bits1(&gb);
             if (sl->au_seq_num_len > 0)
                 skip_bits_long(&gb, sl->au_seq_num_len);
             if (sl->use_timestamps) {
                 dts_flag = get_bits1(&gb);
                 cts_flag = get_bits1(&gb);
             }
         }
         if (sl->inst_bitrate_len)
             inst_bitrate_flag = get_bits1(&gb);
         if (dts_flag == 1)
b2b12a10
             dts = get_ts64(&gb, sl->timestamp_len);
ca65932b
         if (cts_flag == 1)
b2b12a10
             cts = get_ts64(&gb, sl->timestamp_len);
ca65932b
         if (sl->au_len > 0)
             skip_bits_long(&gb, sl->au_len);
         if (inst_bitrate_flag)
             skip_bits_long(&gb, sl->inst_bitrate_len);
     }
 
     if (dts != AV_NOPTS_VALUE)
         pes->dts = dts;
     if (cts != AV_NOPTS_VALUE)
         pes->pts = cts;
 
41bdd4ad
     if (sl->timestamp_len && sl->timestamp_res)
         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
ca65932b
 
     return (get_bits_count(&gb) + 7) >> 3;
 }
 
609d8646
 /* 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,
4acc86bc
                             int64_t pos)
609d8646
 {
86ba2327
     PESContext *pes   = filter->u.pes_filter.opaque;
609d8646
     MpegTSContext *ts = pes->ts;
     const uint8_t *p;
14f7a3d5
     int ret, len, code;
609d8646
 
86ba2327
     if (!ts->pkt)
609d8646
         return 0;
 
     if (is_start) {
         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
14f7a3d5
             ret = new_pes_packet(pes, ts->pkt);
             if (ret < 0)
                 return ret;
609d8646
             ts->stop_parse = 1;
6c537510
         } else {
             reset_pes_packet_state(pes);
609d8646
         }
86ba2327
         pes->state         = MPEGTS_HEADER;
609d8646
         pes->ts_packet_pos = pos;
     }
     p = buf;
     while (buf_size > 0) {
86ba2327
         switch (pes->state) {
609d8646
         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
86ba2327
                  * decide */
609d8646
                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
                     pes->header[2] == 0x01) {
41ed7ab4
                     /* it must be an MPEG-2 PES stream */
609d8646
                     code = pes->header[3] | 0x100;
1a3eb042
                     av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
86ba2327
                             code);
14f7a3d5
                     pes->stream_id = pes->header[3];
609d8646
 
07584eaf
                     if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
86ba2327
                          (!pes->sub_st ||
                           pes->sub_st->discard == AVDISCARD_ALL)) ||
609d8646
                         code == 0x1be) /* padding_stream */
                         goto skip;
 
                     /* stream not present in PMT */
                     if (!pes->st) {
c6c172d1
                         if (ts->skip_changes)
                             goto skip;
 
84ad31ff
                         pes->st = avformat_new_stream(ts->stream, NULL);
609d8646
                         if (!pes->st)
                             return AVERROR(ENOMEM);
84ad31ff
                         pes->st->id = pes->pid;
609d8646
                         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
86ba2327
                      * unbounded */
609d8646
                     if (!pes->total_size)
                         pes->total_size = MAX_PES_PAYLOAD;
 
                     /* allocate pes buffer */
1afddbe5
                     pes->buffer = av_buffer_alloc(pes->total_size +
059a9348
                                                   AV_INPUT_BUFFER_PADDING_SIZE);
609d8646
                     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;
6f69f7a8
                         if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
1a3eb042
                             av_log(pes->stream, AV_LOG_TRACE,
86ba2327
                                     "pid=%x stream_type=%x probing\n",
                                     pes->pid,
                                     pes->stream_type);
ceb0d79f
                             pes->st->request_probe = 1;
609d8646
                         }
                     } else {
757cb0f2
                         pes->pes_header_size = 6;
86ba2327
                         pes->state      = MPEGTS_PAYLOAD;
609d8646
                         pes->data_index = 0;
                     }
                 } else {
                     /* otherwise, it should be a table */
                     /* skip packet */
86ba2327
 skip:
609d8646
                     pes->state = MPEGTS_SKIP;
                     continue;
                 }
             }
             break;
86ba2327
         /**********************************************/
         /* PES packing parsing */
609d8646
         case MPEGTS_PESHEADER:
             len = PES_HEADER_SIZE - pes->data_index;
             if (len < 0)
ca80e158
                 return AVERROR_INVALIDDATA;
609d8646
             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;
86ba2327
                 pes->state           = MPEGTS_PESHEADER_FILL;
609d8646
             }
             break;
         case MPEGTS_PESHEADER_FILL:
             len = pes->pes_header_size - pes->data_index;
             if (len < 0)
ca80e158
                 return AVERROR_INVALIDDATA;
609d8646
             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) {
0bf88286
                     pes->dts = pes->pts = ff_parse_pes_pts(r);
609d8646
                     r += 5;
                 } else if ((flags & 0xc0) == 0xc0) {
e5e3897b
                     pes->pts = ff_parse_pes_pts(r);
609d8646
                     r += 5;
e5e3897b
                     pes->dts = ff_parse_pes_pts(r);
609d8646
                     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 */
86ba2327
                     skip  = (pes_ext >> 4) & 0xb;
609d8646
                     skip += skip & 0x9;
86ba2327
                     r    += skip;
609d8646
                     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;
4df36969
                 if (pes->stream_type == 0x12 && buf_size > 0) {
86ba2327
                     int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
                                                          buf_size);
ca65932b
                     pes->pes_header_size += sl_header_bytes;
                     p += sl_header_bytes;
                     buf_size -= sl_header_bytes;
                 }
69a042ee
                 if (pes->stream_type == 0x15 && buf_size >= 5) {
                     /* skip metadata access unit header */
                     pes->pes_header_size += 5;
                     p += 5;
                     buf_size -= 5;
                 }
42aa0241
                 if (   pes->ts->fix_teletext_pts
6f69f7a8
                     && (   pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
                         || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
42aa0241
                     ) {
a7bb12a3
                     AVProgram *p = NULL;
                     while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
                         if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
                             MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
d2f60547
                             if (f) {
                                 AVStream *st = NULL;
                                 if (f->type == MPEGTS_PES) {
                                     PESContext *pcrpes = f->u.pes_filter.opaque;
                                     if (pcrpes)
                                         st = pcrpes->st;
                                 } else if (f->type == MPEGTS_PCR) {
                                     int i;
                                     for (i = 0; i < p->nb_stream_indexes; i++) {
                                         AVStream *pst = pes->stream->streams[p->stream_index[i]];
6f69f7a8
                                         if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
d2f60547
                                             st = pst;
                                     }
                                 }
                                 if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
a7bb12a3
                                     // teletext packets do not always have correct timestamps,
                                     // the standard says they should be handled after 40.6 ms at most,
                                     // and the pcr error to this packet should be no more than 100 ms.
                                     // TODO: we should interpolate the PCR, not just use the last one
4acc86bc
                                     int64_t pcr = f->last_pcr / 300;
d2f60547
                                     pes->st->pts_wrap_reference = st->pts_wrap_reference;
                                     pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
a7bb12a3
                                     if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
                                         pes->pts = pes->dts = pcr;
6f69f7a8
                                     } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
42aa0241
                                                pes->dts > pcr + 3654 + 9000) {
                                         pes->pts = pes->dts = pcr + 3654 + 9000;
6f69f7a8
                                     } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
42aa0241
                                                pes->dts > pcr + 10*90000) { //10sec
a7bb12a3
                                         pes->pts = pes->dts = pcr + 3654 + 9000;
                                     }
                                     break;
                                 }
                             }
                         }
                     }
                 }
609d8646
             }
             break;
         case MPEGTS_PAYLOAD:
a82e8761
             if (pes->buffer) {
86ba2327
                 if (pes->data_index > 0 &&
                     pes->data_index + buf_size > pes->total_size) {
14f7a3d5
                     ret = new_pes_packet(pes, ts->pkt);
                     if (ret < 0)
                         return ret;
609d8646
                     pes->total_size = MAX_PES_PAYLOAD;
86ba2327
                     pes->buffer = av_buffer_alloc(pes->total_size +
059a9348
                                                   AV_INPUT_BUFFER_PADDING_SIZE);
609d8646
                     if (!pes->buffer)
                         return AVERROR(ENOMEM);
                     ts->stop_parse = 1;
86ba2327
                 } else if (pes->data_index == 0 &&
                            buf_size > pes->total_size) {
74f72620
                     // 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;
609d8646
                 }
1afddbe5
                 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
609d8646
                 pes->data_index += buf_size;
e2752de3
                 /* 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
                  * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
                 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
                     pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
                     ts->stop_parse = 1;
14f7a3d5
                     ret = new_pes_packet(pes, ts->pkt);
                     if (ret < 0)
                         return ret;
e2752de3
                 }
9ba8debc
             }
             buf_size = 0;
609d8646
             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;
86ba2327
     pes->ts      = ts;
     pes->stream  = ts->stream;
     pes->pid     = pid;
609d8646
     pes->pcr_pid = pcr_pid;
86ba2327
     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);
609d8646
     if (!tss) {
         av_free(pes);
         return 0;
     }
     return pes;
 }
 
fec28364
 #define MAX_LEVEL 4
daf8cf35
 typedef struct MP4DescrParseContext {
fec28364
     AVFormatContext *s;
ae628ec1
     AVIOContext pb;
fec28364
     Mp4Descr *descr;
     Mp4Descr *active_descr;
     int descr_count;
     int max_descr_count;
     int level;
958168d5
     int predefined_SLConfigDescriptor_seen;
fec28364
 } MP4DescrParseContext;
 
86ba2327
 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
                                      const uint8_t *buf, unsigned size,
                                      Mp4Descr *descr, int max_descr_count)
fec28364
 {
     int ret;
86ba2327
     if (size > (1 << 30))
fec28364
         return AVERROR_INVALIDDATA;
 
86ba2327
     if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
                                  NULL, NULL, NULL, NULL)) < 0)
fec28364
         return ret;
 
86ba2327
     d->s               = s;
     d->level           = 0;
     d->descr_count     = 0;
     d->descr           = descr;
     d->active_descr    = NULL;
fec28364
     d->max_descr_count = max_descr_count;
 
     return 0;
 }
 
86ba2327
 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
 {
fec28364
     int64_t new_off = avio_tell(pb);
     (*len) -= new_off - *off;
86ba2327
     *off    = new_off;
fec28364
 }
 
 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) {
ca80e158
         int ret = parse_mp4_descr(d, off, len, 0);
         if (ret < 0)
             return ret;
fec28364
         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);
 }
 
c5302670
 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);
86ba2327
     if (!(id_flags & 0x0020)) { // URL_Flag
c5302670
         update_offsets(&d->pb, &off, &len);
86ba2327
         return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
c5302670
     } else {
         return 0;
     }
 }
 
fec28364
 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
 {
     int es_id = 0;
9765549f
     int ret   = 0;
 
fec28364
     if (d->descr_count >= d->max_descr_count)
ca80e158
         return AVERROR_INVALIDDATA;
fec28364
     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);
9765549f
     if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
         return ret;
ca65932b
     update_offsets(&d->pb, &off, &len);
     if (len > 0)
9765549f
         ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
fec28364
     d->active_descr = NULL;
9765549f
     return ret;
fec28364
 }
 
86ba2327
 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
                                       int len)
fec28364
 {
     Mp4Descr *descr = d->active_descr;
     if (!descr)
ca80e158
         return AVERROR_INVALIDDATA;
fec28364
     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;
 }
 
ca65932b
 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
 {
     Mp4Descr *descr = d->active_descr;
     int predefined;
     if (!descr)
ca80e158
         return AVERROR_INVALIDDATA;
ca65932b
 
82439dec
 #define R8_CHECK_CLIP_MAX(dst, maxv) do {                       \
     descr->sl.dst = avio_r8(&d->pb);                            \
     if (descr->sl.dst > maxv) {                                 \
         descr->sl.dst = maxv;                                   \
         return AVERROR_INVALIDDATA;                             \
     }                                                           \
 } while (0)
 
ca65932b
     predefined = avio_r8(&d->pb);
     if (!predefined) {
         int lengths;
         int flags = avio_r8(&d->pb);
86ba2327
         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);
82439dec
         R8_CHECK_CLIP_MAX(timestamp_len, 63);
         R8_CHECK_CLIP_MAX(ocr_len,       63);
         R8_CHECK_CLIP_MAX(au_len,        31);
ca65932b
         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;
958168d5
     } else if (!d->predefined_SLConfigDescriptor_seen){
63d744e2
         avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
958168d5
         d->predefined_SLConfigDescriptor_seen = 1;
ca65932b
     }
     return 0;
 }
 
fec28364
 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
86ba2327
                            int target_tag)
 {
798c6fac
     int tag;
fec28364
     int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
9765549f
     int ret = 0;
 
fec28364
     update_offsets(&d->pb, &off, &len);
     if (len < 0 || len1 > len || len1 <= 0) {
86ba2327
         av_log(d->s, AV_LOG_ERROR,
                "Tag %x length violation new length %d bytes remaining %d\n",
                tag, len1, len);
ca80e158
         return AVERROR_INVALIDDATA;
fec28364
     }
 
     if (d->level++ >= MAX_LEVEL) {
         av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
9765549f
         ret = AVERROR_INVALIDDATA;
fec28364
         goto done;
     }
 
     if (target_tag && tag != target_tag) {
86ba2327
         av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
                target_tag);
9765549f
         ret = AVERROR_INVALIDDATA;
fec28364
         goto done;
     }
 
     switch (tag) {
     case MP4IODescrTag:
9765549f
         ret = parse_MP4IODescrTag(d, off, len1);
fec28364
         break;
c5302670
     case MP4ODescrTag:
9765549f
         ret = parse_MP4ODescrTag(d, off, len1);
c5302670
         break;
fec28364
     case MP4ESDescrTag:
9765549f
         ret = parse_MP4ESDescrTag(d, off, len1);
fec28364
         break;
     case MP4DecConfigDescrTag:
9765549f
         ret = parse_MP4DecConfigDescrTag(d, off, len1);
fec28364
         break;
ca65932b
     case MP4SLDescrTag:
9765549f
         ret = parse_MP4SLDescrTag(d, off, len1);
ca65932b
         break;
798c6fac
     }
fec28364
 
ca80e158
 
fec28364
 done:
     d->level--;
     avio_seek(&d->pb, off + len1, SEEK_SET);
9765549f
     return ret;
fec28364
 }
 
8ee764b0
 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
fec28364
                          Mp4Descr *descr, int *descr_count, int max_descr_count)
 {
     MP4DescrParseContext d;
ca80e158
     int ret;
 
     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
     if (ret < 0)
         return ret;
fec28364
 
ca80e158
     ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
fec28364
 
     *descr_count = d.descr_count;
ca80e158
     return ret;
798c6fac
 }
 
c5302670
 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
                        Mp4Descr *descr, int *descr_count, int max_descr_count)
798c6fac
 {
c5302670
     MP4DescrParseContext d;
ca80e158
     int ret;
 
     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
     if (ret < 0)
         return ret;
c5302670
 
ca80e158
     ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
c5302670
 
     *descr_count = d.descr_count;
ca80e158
     return ret;
c5302670
 }
 
86ba2327
 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
                     int section_len)
c5302670
 {
ca65932b
     MpegTSContext *ts = filter->u.section_filter.opaque;
82de8d71
     MpegTSSectionFilter *tssf = &filter->u.section_filter;
ca65932b
     SectionHeader h;
     const uint8_t *p, *p_end;
471fe57e
     AVIOContext pb;
c5302670
     int mp4_descr_count = 0;
86ba2327
     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
c5302670
     int i, pid;
ca65932b
     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;
4e8d01f2
     if (skip_identical(&h, tssf))
82de8d71
         return;
c5302670
 
86ba2327
     mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
                 MAX_MP4_DESCR_COUNT);
c5302670
 
     for (pid = 0; pid < NB_PID_MAX; pid++) {
         if (!ts->pids[pid])
86ba2327
             continue;
c5302670
         for (i = 0; i < mp4_descr_count; i++) {
             PESContext *pes;
             AVStream *st;
             if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
                 continue;
ff6fa0b4
             if (ts->pids[pid]->type != MPEGTS_PES) {
c5302670
                 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
                 continue;
             }
             pes = ts->pids[pid]->u.pes_filter.opaque;
86ba2327
             st  = pes->st;
             if (!st)
c5302670
                 continue;
 
ca65932b
             pes->sl = mp4_descr[i].sl;
 
c5302670
             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
86ba2327
                               mp4_descr[i].dec_config_descr_len, 0,
                               NULL, NULL, NULL, NULL);
c5302670
             ff_mp4_read_dec_config_descr(s, st, &pb);
9200514a
             if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
                 st->codecpar->extradata_size > 0)
c5302670
                 st->need_parsing = 0;
9200514a
             if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
                 st->codecpar->extradata_size > 0)
c5302670
                 st->need_parsing = 0;
 
9200514a
             st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
6f69f7a8
             st->internal->need_context_update = 1;
798c6fac
         }
     }
c5302670
     for (i = 0; i < mp4_descr_count; i++)
         av_free(mp4_descr[i].dec_config_descr);
798c6fac
 }
 
5db3c947
 static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
                     int section_len)
 {
     AVProgram *prg = NULL;
     MpegTSContext *ts = filter->u.section_filter.opaque;
 
     int idx = ff_find_stream_index(ts->stream, filter->pid);
728ccae8
     if (idx < 0)
         return;
 
5db3c947
     new_data_packet(section, section_len, ts->pkt);
728ccae8
     ts->pkt->stream_index = idx;
5db3c947
     prg = av_find_program_from_stream(ts->stream, NULL, idx);
     if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
         MpegTSFilter *f = ts->pids[prg->pcr_pid];
728ccae8
         if (f && f->last_pcr != -1)
5db3c947
             ts->pkt->pts = ts->pkt->dts = f->last_pcr/300;
     }
     ts->stop_parse = 1;
 
 }
 
61e42c11
 static const uint8_t opus_coupled_stream_cnt[9] = {
     1, 0, 1, 1, 2, 2, 2, 3, 3
 };
 
9cfa68c5
 static const uint8_t opus_stream_cnt[9] = {
     1, 1, 1, 2, 2, 3, 4, 4, 5,
 };
 
61e42c11
 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 },
 };
 
cc9038e9
 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
                               const uint8_t **pp, const uint8_t *desc_list_end,
4682a1dc
                               Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
                               MpegTSContext *ts)
cc9038e9
 {
     const uint8_t *desc_end;
61e42c11
     int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
b543e1dc
     char language[252];
     int i;
cc9038e9
 
     desc_tag = get8(pp, desc_list_end);
     if (desc_tag < 0)
ca80e158
         return AVERROR_INVALIDDATA;
cc9038e9
     desc_len = get8(pp, desc_list_end);
     if (desc_len < 0)
ca80e158
         return AVERROR_INVALIDDATA;
cc9038e9
     desc_end = *pp + desc_len;
     if (desc_end > desc_list_end)
ca80e158
         return AVERROR_INVALIDDATA;
cc9038e9
 
1a3eb042
     av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
cc9038e9
 
6f69f7a8
     if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
cc9038e9
         stream_type == STREAM_TYPE_PRIVATE_DATA)
         mpegts_find_stream_type(st, desc_tag, DESC_types);
 
86ba2327
     switch (desc_tag) {
476d04a5
     case 0x1E: /* SL descriptor */
         desc_es_id = get16(pp, desc_end);
8b263331
         if (desc_es_id < 0)
             break;
c5302670
         if (ts && ts->pids[pid])
             ts->pids[pid]->es_id = desc_es_id;
c3bc6096
         for (i = 0; i < mp4_descr_count; i++)
86ba2327
             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);
9200514a
                 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
6f69f7a8
                     st->codecpar->extradata_size > 0) {
86ba2327
                     st->need_parsing = 0;
6f69f7a8
                     st->internal->need_context_update = 1;
                 }
9200514a
                 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
86ba2327
                     mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
             }
476d04a5
         break;
cc9038e9
     case 0x1F: /* FMC descriptor */
8b263331
         if (get16(pp, desc_end) < 0)
             break;
86ba2327
         if (mp4_descr_count > 0 &&
6f69f7a8
             (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
              (st->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
14e9a200
              st->request_probe > 0) &&
c3bc6096
             mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
471fe57e
             AVIOContext pb;
c3bc6096
             ffio_init_context(&pb, mp4_descr->dec_config_descr,
86ba2327
                               mp4_descr->dec_config_descr_len, 0,
                               NULL, NULL, NULL, NULL);
cc9038e9
             ff_mp4_read_dec_config_descr(fc, st, &pb);
9200514a
             if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
6f69f7a8
                 st->codecpar->extradata_size > 0) {
ceb0d79f
                 st->request_probe = st->need_parsing = 0;
6f69f7a8
                 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
                 st->internal->need_context_update = 1;
c643ba81
             }
cc9038e9
         }
         break;
     case 0x56: /* DVB teletext descriptor */
1d073850
         {
             uint8_t *extradata = NULL;
             int language_count = desc_len / 5;
 
             if (desc_len > 0 && desc_len % 5 != 0)
                 return AVERROR_INVALIDDATA;
 
             if (language_count > 0) {
                 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
c8c86b8f
                 av_assert0(language_count <= sizeof(language) / 4);
1d073850
 
6f69f7a8
                 if (st->codecpar->extradata == NULL) {
                     if (ff_alloc_extradata(st->codecpar, language_count * 2)) {
1d073850
                         return AVERROR(ENOMEM);
                     }
                 }
 
6f69f7a8
                if (st->codecpar->extradata_size < language_count * 2)
1d073850
                    return AVERROR_INVALIDDATA;
 
6f69f7a8
                extradata = st->codecpar->extradata;
1d073850
 
                 for (i = 0; i < language_count; i++) {
                     language[i * 4 + 0] = get8(pp, desc_end);
                     language[i * 4 + 1] = get8(pp, desc_end);
                     language[i * 4 + 2] = get8(pp, desc_end);
                     language[i * 4 + 3] = ',';
 
                     memcpy(extradata, *pp, 2);
                     extradata += 2;
 
                     *pp += 2;
                 }
 
                 language[i * 4 - 1] = 0;
                 av_dict_set(&st->metadata, "language", language, 0);
6f69f7a8
                 st->internal->need_context_update = 1;
1d073850
             }
         }
cc9038e9
         break;
     case 0x59: /* subtitling descriptor */
e2707a7c
         {
             /* 8 bytes per DVB subtitle substream data:
              * ISO_639_language_code (3 bytes),
              * subtitling_type (1 byte),
              * composition_page_id (2 bytes),
              * ancillary_page_id (2 bytes) */
             int language_count = desc_len / 8;
 
             if (desc_len > 0 && desc_len % 8 != 0)
                 return AVERROR_INVALIDDATA;
 
             if (language_count > 1) {
                 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
             }
 
             if (language_count > 0) {
                 uint8_t *extradata;
 
                 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
c8c86b8f
                 av_assert0(language_count <= sizeof(language) / 4);
e2707a7c
 
6f69f7a8
                 if (st->codecpar->extradata == NULL) {
                     if (ff_alloc_extradata(st->codecpar, language_count * 5)) {
e2707a7c
                         return AVERROR(ENOMEM);
                     }
                 }
 
6f69f7a8
                 if (st->codecpar->extradata_size < language_count * 5)
e2707a7c
                     return AVERROR_INVALIDDATA;
 
6f69f7a8
                 extradata = st->codecpar->extradata;
e2707a7c
 
                 for (i = 0; i < language_count; i++) {
                     language[i * 4 + 0] = get8(pp, desc_end);
                     language[i * 4 + 1] = get8(pp, desc_end);
                     language[i * 4 + 2] = get8(pp, desc_end);
                     language[i * 4 + 3] = ',';
 
                     /* hearing impaired subtitles detection using subtitling_type */
ceb0d79f
                     switch (*pp[0]) {
e2707a7c
                     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;
                     }
 
                     extradata[4] = get8(pp, desc_end); /* subtitling_type */
                     memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
                     extradata += 5;
 
                     *pp += 4;
                 }
 
                 language[i * 4 - 1] = 0;
                 av_dict_set(&st->metadata, "language", language, 0);
6f69f7a8
                 st->internal->need_context_update = 1;
cc9038e9
             }
         }
         break;
     case 0x0a: /* ISO 639 language descriptor */
b543e1dc
         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] = ',';
86ba2327
             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;
             }
b543e1dc
         }
fc27e727
         if (i && language[0]) {
b543e1dc
             language[i - 1] = 0;
d2d67e42
             av_dict_set(&st->metadata, "language", language, 0);
b543e1dc
         }
cc9038e9
         break;
     case 0x05: /* registration descriptor */
9200514a
         st->codecpar->codec_tag = bytestream_get_le32(pp);
         av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
a5eb70ad
         if (st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) {
9200514a
             mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
a5eb70ad
             if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
                 st->request_probe = 50;
         }
cc9038e9
         break;
fa12fb3b
     case 0x52: /* stream identifier descriptor */
         st->stream_identifier = 1 + get8(pp, desc_end);
         break;
69a042ee
     case 0x26: /* metadata descriptor */
         if (get16(pp, desc_end) == 0xFFFF)
             *pp += 4;
         if (get8(pp, desc_end) == 0xFF) {
6f69f7a8
             st->codecpar->codec_tag = bytestream_get_le32(pp);
             if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
                 mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
69a042ee
         }
         break;
61e42c11
     case 0x7f: /* DVB extension descriptor */
         ext_desc_tag = get8(pp, desc_end);
         if (ext_desc_tag < 0)
             return AVERROR_INVALIDDATA;
9200514a
         if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
61e42c11
             ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
9200514a
             if (!st->codecpar->extradata) {
                 st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
                                                      AV_INPUT_BUFFER_PADDING_SIZE);
                 if (!st->codecpar->extradata)
61e42c11
                     return AVERROR(ENOMEM);
 
9200514a
                 st->codecpar->extradata_size = sizeof(opus_default_extradata);
                 memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
61e42c11
 
                 channel_config_code = get8(pp, desc_end);
                 if (channel_config_code < 0)
                     return AVERROR_INVALIDDATA;
                 if (channel_config_code <= 0x8) {
9200514a
                     st->codecpar->extradata[9]  = channels = channel_config_code ? channel_config_code : 2;
6f69f7a8
                     st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
9200514a
                     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);
61e42c11
                 } else {
                     avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
                 }
                 st->need_parsing = AVSTREAM_PARSE_FULL;
6f69f7a8
                 st->internal->need_context_update = 1;
61e42c11
             }
         }
         break;
cc9038e9
     default:
         break;
     }
     *pp = desc_end;
     return 0;
 }
 
5db3c947
 static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
 {
     return !(stream_type == 0x13 ||
              (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
 }
 
4d9a577e
 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
5dbafeb7
 {
4d9a577e
     MpegTSContext *ts = filter->u.section_filter.opaque;
82de8d71
     MpegTSSectionFilter *tssf = &filter->u.section_filter;
5dbafeb7
     SectionHeader h1, *h = &h1;
c6ec28b1
     PESContext *pes;
     AVStream *st;
cc9038e9
     const uint8_t *p, *p_end, *desc_list_end;
c6ec28b1
     int program_info_length, pcr_pid, pid, stream_type;
cc9038e9
     int desc_list_len;
8430f3ec
     uint32_t prog_reg_desc = 0; /* registration descriptor */
c3bc6096
 
     int mp4_descr_count = 0;
86ba2327
     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
c3bc6096
     int i;
115329f1
 
1a3eb042
     av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
15d35bee
     hex_dump_debug(ts->stream, section, section_len);
ebcf352a
 
5dbafeb7
     p_end = section + section_len - 4;
     p = section;
     if (parse_section_header(h, &p, p_end) < 0)
         return;
4e8d01f2
     if (skip_identical(h, tssf))
82de8d71
         return;
ebcf352a
 
e9391ab1
     av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
             h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
ebcf352a
 
90d13e30
     if (h->tid != PMT_TID)
5dbafeb7
         return;
29b1af40
     if (!ts->scan_all_pmts && ts->skip_changes)
         return;
5dbafeb7
 
db0471c4
     if (!ts->skip_clear)
         clear_program(ts, h->id);
 
c9024a9f
     pcr_pid = get16(&p, p_end);
5dbafeb7
     if (pcr_pid < 0)
         return;
c9024a9f
     pcr_pid &= 0x1fff;
172d1171
     add_pid_to_pmt(ts, h->id, pcr_pid);
5501afa6
     set_pcr_pid(ts->stream, h->id, pcr_pid);
ebcf352a
 
1a3eb042
     av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
ebcf352a
 
c9024a9f
     program_info_length = get16(&p, p_end);
5dbafeb7
     if (program_info_length < 0)
         return;
c9024a9f
     program_info_length &= 0xfff;
86ba2327
     while (program_info_length >= 2) {
a45b40c4
         uint8_t tag, len;
         tag = get8(&p, p_end);
         len = get8(&p, p_end);
798c6fac
 
1a3eb042
         av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
798c6fac
 
86ba2327
         if (len > program_info_length - 2)
             // something else is broken, exit the program_descriptors_loop
a45b40c4
             break;
         program_info_length -= len + 2;
798c6fac
         if (tag == 0x1d) { // IOD descriptor
             get8(&p, p_end); // scope
             get8(&p, p_end); // label
             len -= 2;
fec28364
             mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
                           &mp4_descr_count, MAX_MP4_DESCR_COUNT);
798c6fac
         } else if (tag == 0x05 && len >= 4) { // registration descriptor
8430f3ec
             prog_reg_desc = bytestream_get_le32(&p);
a45b40c4
             len -= 4;
         }
         p += len;
     }
5dbafeb7
     p += program_info_length;
     if (p >= p_end)
175272cb
         goto out;
d46c84ea
 
     // stop parsing after pmt, we found header
     if (!ts->stream->nb_streams)
49ec0c81
         ts->stop_parse = 2;
d46c84ea
 
6eda91ad
     set_pmt_found(ts, h->id);
 
86ba2327
 
     for (;;) {
c6ec28b1
         st = 0;
4682a1dc
         pes = NULL;
5dbafeb7
         stream_type = get8(&p, p_end);
         if (stream_type < 0)
             break;
c9024a9f
         pid = get16(&p, p_end);
5dbafeb7
         if (pid < 0)
d08bb065
             goto out;
c9024a9f
         pid &= 0x1fff;
327cd0d0
         if (pid == ts->current_pid)
d08bb065
             goto out;
f42d1d82
 
124e2884
         /* now create stream */
f42d1d82
         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
             pes = ts->pids[pid]->u.pes_filter.opaque;
84ad31ff
             if (!pes->st) {
86ba2327
                 pes->st     = avformat_new_stream(pes->stream, NULL);
7726916c
                 if (!pes->st)
                     goto out;
463c8d86
                 pes->st->id = pes->pid;
84ad31ff
             }
f42d1d82
             st = pes->st;
5db3c947
         } else if (is_pes_stream(stream_type, prog_reg_desc)) {
86ba2327
             if (ts->pids[pid])
                 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
b3f9f7a3
             pes = add_pes_stream(ts, pid, pcr_pid);
84ad31ff
             if (pes) {
                 st = avformat_new_stream(pes->stream, NULL);
7726916c
                 if (!st)
                     goto out;
84ad31ff
                 st->id = pes->pid;
             }
4682a1dc
         } else {
             int idx = ff_find_stream_index(ts->stream, pid);
             if (idx >= 0) {
                 st = ts->stream->streams[idx];
             } else {
d9b89b23
                 st = avformat_new_stream(ts->stream, NULL);
7726916c
                 if (!st)
                     goto out;
4682a1dc
                 st->id = pid;
9200514a
                 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
5db3c947
                 if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
                     mpegts_find_stream_type(st, stream_type, SCTE_types);
                     mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
                 }
4682a1dc
             }
f42d1d82
         }
 
         if (!st)
175272cb
             goto out;
f42d1d82
 
4682a1dc
         if (pes && !pes->stream_type)
b3f9f7a3
             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
 
f42d1d82
         add_pid_to_pmt(ts, h->id, pid);
 
676a93f2
         av_program_add_stream_index(ts->stream, h->id, st->index);
f42d1d82
 
c9024a9f
         desc_list_len = get16(&p, p_end);
c6ec28b1
         if (desc_list_len < 0)
d08bb065
             goto out;
c9024a9f
         desc_list_len &= 0xfff;
86ba2327
         desc_list_end  = p + desc_list_len;
a4d2af9b
         if (desc_list_end > p_end)
d08bb065
             goto out;
86ba2327
         for (;;) {
             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
                                           desc_list_end, mp4_descr,
                                           mp4_descr_count, pid, ts) < 0)
798c6fac
                 break;
63380b5e
 
86ba2327
             if (pes && prog_reg_desc == AV_RL32("HDMV") &&
                 stream_type == 0x83 && pes->sub_st) {
676a93f2
                 av_program_add_stream_index(ts->stream, h->id,
86ba2327
                                             pes->sub_st->index);
9200514a
                 pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
63380b5e
             }
c6ec28b1
         }
         p = desc_list_end;
5dbafeb7
     }
175272cb
 
d83a5b52
     if (!ts->pids[pcr_pid])
         mpegts_open_pcr_filter(ts, pcr_pid);
 
86ba2327
 out:
c3bc6096
     for (i = 0; i < mp4_descr_count; i++)
         av_free(mp4_descr[i].dec_config_descr);
5dbafeb7
 }
 
4d9a577e
 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
5dbafeb7
 {
4d9a577e
     MpegTSContext *ts = filter->u.section_filter.opaque;
82de8d71
     MpegTSSectionFilter *tssf = &filter->u.section_filter;
5dbafeb7
     SectionHeader h1, *h = &h1;
     const uint8_t *p, *p_end;
     int sid, pmt_pid;
24adef14
     AVProgram *program;
5dbafeb7
 
1a3eb042
     av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
15d35bee
     hex_dump_debug(ts->stream, section, section_len);
43b6c3eb
 
5dbafeb7
     p_end = section + section_len - 4;
86ba2327
     p     = section;
5dbafeb7
     if (parse_section_header(h, &p, p_end) < 0)
         return;
     if (h->tid != PAT_TID)
         return;
c6c172d1
     if (ts->skip_changes)
         return;
5dbafeb7
 
4e8d01f2
     if (skip_identical(h, tssf))
82de8d71
         return;
24adef14
     ts->stream->ts_id = h->id;
 
172d1171
     clear_programs(ts);
86ba2327
     for (;;) {
5dbafeb7
         sid = get16(&p, p_end);
         if (sid < 0)
             break;
c9024a9f
         pmt_pid = get16(&p, p_end);
5dbafeb7
         if (pmt_pid < 0)
             break;
c9024a9f
         pmt_pid &= 0x1fff;
ebcf352a
 
eab022d8
         if (pmt_pid == ts->current_pid)
             break;
 
1a3eb042
         av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
ebcf352a
 
5dbafeb7
         if (sid == 0x0000) {
             /* NIT info */
         } else {
b0092679
             MpegTSFilter *fil = ts->pids[pmt_pid];
24adef14
             program = av_new_program(ts->stream, sid);
0e406aba
             if (program) {
                 program->program_num = sid;
                 program->pmt_pid = pmt_pid;
             }
b0092679
             if (fil)
                 if (   fil->type != MPEGTS_SECTION
                     || fil->pid != pmt_pid
                     || fil->u.section_filter.section_cb != pmt_cb)
                     mpegts_close_filter(ts, ts->pids[pmt_pid]);
 
             if (!ts->pids[pmt_pid])
                 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
172d1171
             add_pat_entry(ts, sid);
86ba2327
             add_pid_to_pmt(ts, sid, 0); // add pat pid to program
172d1171
             add_pid_to_pmt(ts, sid, pmt_pid);
806a66fd
         }
     }
 
     if (sid < 0) {
         int i,j;
         for (j=0; j<ts->stream->nb_programs; j++) {
ceb0d79f
             for (i = 0; i < ts->nb_prg; i++)
806a66fd
                 if (ts->prg[i].id == ts->stream->programs[j]->id)
                     break;
4470a3ee
             if (i==ts->nb_prg && !ts->skip_clear)
806a66fd
                 clear_avprogram(ts, ts->stream->programs[j]->id);
5dbafeb7
         }
     }
 }
 
4d9a577e
 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
5dbafeb7
 {
4d9a577e
     MpegTSContext *ts = filter->u.section_filter.opaque;
82de8d71
     MpegTSSectionFilter *tssf = &filter->u.section_filter;
5dbafeb7
     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;
 
1a3eb042
     av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
15d35bee
     hex_dump_debug(ts->stream, section, section_len);
5dbafeb7
 
     p_end = section + section_len - 4;
86ba2327
     p     = section;
5dbafeb7
     if (parse_section_header(h, &p, p_end) < 0)
         return;
     if (h->tid != SDT_TID)
         return;
c6c172d1
     if (ts->skip_changes)
         return;
4e8d01f2
     if (skip_identical(h, tssf))
82de8d71
         return;
 
5dbafeb7
     onid = get16(&p, p_end);
     if (onid < 0)
         return;
     val = get8(&p, p_end);
     if (val < 0)
         return;
86ba2327
     for (;;) {
5dbafeb7
         sid = get16(&p, p_end);
         if (sid < 0)
             break;
         val = get8(&p, p_end);
         if (val < 0)
             break;
c9024a9f
         desc_list_len = get16(&p, p_end);
5dbafeb7
         if (desc_list_len < 0)
             break;
c9024a9f
         desc_list_len &= 0xfff;
86ba2327
         desc_list_end  = p + desc_list_len;
5dbafeb7
         if (desc_list_end > p_end)
             break;
86ba2327
         for (;;) {
5dbafeb7
             desc_tag = get8(&p, desc_list_end);
             if (desc_tag < 0)
                 break;
             desc_len = get8(&p, desc_list_end);
             desc_end = p + desc_len;
c3d7f00e
             if (desc_len < 0 || desc_end > desc_list_end)
5dbafeb7
                 break;
ebcf352a
 
1a3eb042
             av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
86ba2327
                     desc_tag, desc_len);
ebcf352a
 
86ba2327
             switch (desc_tag) {
5dbafeb7
             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);
1d257254
                 if (name) {
                     AVProgram *program = av_new_program(ts->stream, sid);
86ba2327
                     if (program) {
d2d67e42
                         av_dict_set(&program->metadata, "service_name", name, 0);
86ba2327
                         av_dict_set(&program->metadata, "service_provider",
                                     provider_name, 0);
08681191
                     }
1d257254
                 }
81d5ae6d
                 av_free(name);
                 av_free(provider_name);
5dbafeb7
                 break;
             default:
                 break;
             }
             p = desc_end;
         }
         p = desc_list_end;
     }
 }
 
d75d9112
 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
                      const uint8_t *packet);
 
5dbafeb7
 /* handle one TS packet */
bdfa9824
 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
fe9cf0d4
 {
5dbafeb7
     MpegTSFilter *tss;
8b9df201
     int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
         has_adaptation, has_payload;
5dbafeb7
     const uint8_t *p, *p_end;
4c6b49bf
     int64_t pos;
5dbafeb7
 
80fb8234
     pid = AV_RB16(packet + 1) & 0x1fff;
86ba2327
     if (pid && discard_pid(ts, pid))
bdfa9824
         return 0;
5dbafeb7
     is_start = packet[1] & 0x40;
     tss = ts->pids[pid];
f929ab05
     if (ts->auto_guess && !tss && is_start) {
b3f9f7a3
         add_pes_stream(ts, pid, -1);
5dbafeb7
         tss = ts->pids[pid];
     }
     if (!tss)
bdfa9824
         return 0;
327cd0d0
     ts->current_pid = pid;
5dbafeb7
 
8b9df201
     afc = (packet[3] >> 4) & 3;
     if (afc == 0) /* reserved value */
         return 0;
86ba2327
     has_adaptation   = afc & 2;
     has_payload      = afc & 1;
     is_discontinuity = has_adaptation &&
                        packet[4] != 0 && /* with length > 0 */
                        (packet[5] & 0x80); /* and discontinuity indicated */
8b9df201
 
5dbafeb7
     /* continuity check (currently not used) */
     cc = (packet[3] & 0xf);
8b9df201
     expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
86ba2327
     cc_ok = pid == 0x1FFF || // null packet PID
             is_discontinuity ||
             tss->last_cc < 0 ||
             expected_cc == cc;
8b9df201
 
5dbafeb7
     tss->last_cc = cc;
ce9e3165
     if (!cc_ok) {
7e75f061
         av_log(ts->stream, AV_LOG_DEBUG,
f1f15c3c
                "Continuity check failed for pid %d expected %d got %d\n",
                pid, expected_cc, cc);
86ba2327
         if (tss->type == MPEGTS_PES) {
ce9e3165
             PESContext *pc = tss->u.pes_filter.opaque;
             pc->flags |= AV_PKT_FLAG_CORRUPT;
         }
     }
115329f1
 
8b9df201
     p = packet + 4;
     if (has_adaptation) {
51748b63
         int64_t pcr_h;
         int pcr_l;
         if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
             tss->last_pcr = pcr_h * 300 + pcr_l;
eac778de
         /* skip adaptation field */
5dbafeb7
         p += p[0] + 1;
     }
     /* if past the end of packet, ignore */
     p_end = packet + TS_PACKET_SIZE;
51748b63
     if (p >= p_end || !has_payload)
bdfa9824
         return 0;
115329f1
 
384c9c2f
     pos = avio_tell(ts->stream->pb);
5dc6c0ea
     if (pos >= 0) {
         av_assert0(pos >= TS_PACKET_SIZE);
         ts->pos47_full = pos - TS_PACKET_SIZE;
     }
5fd63f3c
 
5dbafeb7
     if (tss->type == MPEGTS_SECTION) {
         if (is_start) {
             /* pointer field present */
             len = *p++;
1b3b018a
             if (len > p_end - p)
bdfa9824
                 return 0;
5dbafeb7
             if (len && cc_ok) {
27bb1ed3
                 /* write remaining section bytes */
86359543
                 write_section_data(ts, tss,
5dbafeb7
                                    p, len, 0);
27bb1ed3
                 /* check whether filter has been closed */
                 if (!ts->pids[pid])
bdfa9824
                     return 0;
5dbafeb7
             }
             p += len;
             if (p < p_end) {
86359543
                 write_section_data(ts, tss,
5dbafeb7
                                    p, p_end - p, 1);
             }
         } else {
             if (cc_ok) {
86359543
                 write_section_data(ts, tss,
5dbafeb7
                                    p, p_end - p, 0);
fc48fe84
             }
5dbafeb7
         }
6eda91ad
 
         // stop find_stream_info from waiting for more streams
         // when all programs have received a PMT
29b1af40
         if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
6eda91ad
             int i;
ceb0d79f
             for (i = 0; i < ts->nb_prg; i++) {
6eda91ad
                 if (!ts->prg[i].pmt_found)
                     break;
             }
             if (i == ts->nb_prg && ts->nb_prg > 0) {
41ad87ad
                 int types = 0;
                 for (i = 0; i < ts->stream->nb_streams; i++) {
                     AVStream *st = ts->stream->streams[i];
178eebd7
                     if (st->codecpar->codec_type >= 0)
                         types |= 1<<st->codecpar->codec_type;
41ad87ad
                 }
                 if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
29986885
                     av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
                     ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
                 }
6eda91ad
             }
         }
 
5dbafeb7
     } else {
bdfa9824
         int ret;
4c6b49bf
         // Note: The position here points actually behind the current packet.
d83a5b52
         if (tss->type == MPEGTS_PES) {
             if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
                                                 pos - ts->raw_packet_size)) < 0)
                 return ret;
         }
5dbafeb7
     }
bdfa9824
 
     return 0;
5dbafeb7
 }
 
c666c59a
 static void reanalyze(MpegTSContext *ts) {
     AVIOContext *pb = ts->stream->pb;
     int64_t pos = avio_tell(pb);
ceb0d79f
     if (pos < 0)
c666c59a
         return;
0f2f65bd
     pos -= ts->pos47_full;
c666c59a
     if (pos == TS_PACKET_SIZE) {
         ts->size_stat[0] ++;
     } else if (pos == TS_DVHS_PACKET_SIZE) {
         ts->size_stat[1] ++;
     } else if (pos == TS_FEC_PACKET_SIZE) {
         ts->size_stat[2] ++;
     }
 
     ts->size_stat_count ++;
ceb0d79f
     if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
c666c59a
         int newsize = 0;
         if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
             newsize = TS_PACKET_SIZE;
         } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
             newsize = TS_DVHS_PACKET_SIZE;
         } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
             newsize = TS_FEC_PACKET_SIZE;
         }
ee7f2609
         if (newsize && newsize != ts->raw_packet_size) {
c666c59a
             av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
             ts->raw_packet_size = newsize;
         }
         ts->size_stat_count = 0;
         memset(ts->size_stat, 0, sizeof(ts->size_stat));
     }
 }
 
fc48fe84
 /* XXX: try to find a better synchro over several packets (use
86ba2327
  * get_packet_size() ?) */
dbe1dd59
 static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
fc48fe84
 {
7968059e
     MpegTSContext *ts = s->priv_data;
471fe57e
     AVIOContext *pb = s->pb;
fc48fe84
     int c, i;
ea41ab09
     uint64_t pos = avio_tell(pb);
 
     avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
fc48fe84
 
dbe1dd59
     //Special case for files like 01c56b0dc1.ts
     if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
         avio_seek(pb, 12, SEEK_CUR);
         return 0;
     }
 
7968059e
     for (i = 0; i < ts->resync_size; i++) {
1447dc59
         c = avio_r8(pb);
d34ec64a
         if (avio_feof(pb))
ca80e158
             return AVERROR_EOF;
fc48fe84
         if (c == 0x47) {
f59d8ff8
             avio_seek(pb, -1, SEEK_CUR);
c666c59a
             reanalyze(s->priv_data);
fc48fe84
             return 0;
         }
     }
86ba2327
     av_log(s, AV_LOG_ERROR,
            "max resync size reached, could not find sync byte\n");
fc48fe84
     /* no sync found */
ca80e158
     return AVERROR_INVALIDDATA;
fc48fe84
 }
 
ca80e158
 /* return AVERROR_something if error or EOF. Return 0 if OK. */
86ba2327
 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
                        const uint8_t **data)
5dbafeb7
 {
471fe57e
     AVIOContext *pb = s->pb;
cabb1681
     int len;
b45a7a18
 
86ba2327
     for (;;) {
cabb1681
         len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
b45a7a18
         if (len != TS_PACKET_SIZE)
e006d71f
             return len < 0 ? len : AVERROR_EOF;
eac778de
         /* check packet sync byte */
cabb1681
         if ((*data)[0] != 0x47) {
b45a7a18
             /* find a new packet start */
7d0e927a
 
dbe1dd59
             if (mpegts_resync(s, raw_packet_size, *data) < 0)
1303d62d
                 return AVERROR(EAGAIN);
b45a7a18
             else
                 continue;
         } else {
             break;
         }
     }
     return 0;
 }
 
cabb1681
 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);
 }
 
ff9a1541
 static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
b45a7a18
 {
     AVFormatContext *s = ts->stream;
059a9348
     uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
5afe1d27
     const uint8_t *data;
ff9a1541
     int64_t packet_num;
     int ret = 0;
cdb9884a
 
     if (avio_tell(s->pb) != ts->last_pos) {
         int i;
1a3eb042
         av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
cdb9884a
         /* seek detected, flush pes buffer */
         for (i = 0; i < NB_PID_MAX; i++) {
162f1fbc
             if (ts->pids[i]) {
                 if (ts->pids[i]->type == MPEGTS_PES) {
86ba2327
                     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 */
63978149
                 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
                     ts->pids[i]->u.section_filter.last_ver = -1;
162f1fbc
                 }
cdb9884a
                 ts->pids[i]->last_cc = -1;
4acc86bc
                 ts->pids[i]->last_pcr = -1;
cdb9884a
             }
         }
     }
5dbafeb7
 
     ts->stop_parse = 0;
     packet_num = 0;
059a9348
     memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
86ba2327
     for (;;) {
5dbafeb7
         packet_num++;
49ec0c81
         if (nb_packets != 0 && packet_num >= nb_packets ||
             ts->stop_parse > 1) {
             ret = AVERROR(EAGAIN);
             break;
         }
         if (ts->stop_parse > 0)
5dbafeb7
             break;
49ec0c81
 
cabb1681
         ret = read_packet(s, packet, ts->raw_packet_size, &data);
b45a7a18
         if (ret != 0)
cdb9884a
             break;
cabb1681
         ret = handle_packet(ts, data);
         finished_reading_packet(s, ts->raw_packet_size);
bdfa9824
         if (ret != 0)
cdb9884a
             break;
5dbafeb7
     }
cdb9884a
     ts->last_pos = avio_tell(s->pb);
     return ret;
5dbafeb7
 }
fe9cf0d4
 
5dbafeb7
 static int mpegts_probe(AVProbeData *p)
 {
86ba2327
     const int size = p->buf_size;
ceb0d79f
     int maxscore = 0;
     int sumscore = 0;
304ebed5
     int i;
86ba2327
     int check_count = size / TS_FEC_PACKET_SIZE;
a0b8f70c
 #define CHECK_COUNT 10
304ebed5
 #define CHECK_BLOCK 100
115329f1
 
88a849c7
     if (!check_count)
77c0b149
         return 0;
115329f1
 
ceb0d79f
     for (i = 0; i<check_count; i+=CHECK_BLOCK) {
304ebed5
         int left = FFMIN(check_count - i, CHECK_BLOCK);
38a6242b
         int score      = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , 1);
         int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
         int fec_score  = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
304ebed5
         score = FFMAX3(score, dvhs_score, fec_score);
         sumscore += score;
         maxscore = FFMAX(maxscore, score);
     }
 
ceb0d79f
     sumscore = sumscore * CHECK_COUNT / check_count;
     maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
304ebed5
 
229843aa
     ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
115329f1
 
00c4861f
     if        (check_count > CHECK_COUNT && sumscore > 6) {
88a849c7
         return AVPROBE_SCORE_MAX   + sumscore - CHECK_COUNT;
00c4861f
     } else if (check_count >= CHECK_COUNT && sumscore > 6) {
         return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
88a849c7
     } else if (check_count >= CHECK_COUNT && maxscore > 6) {
         return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
     } else if (sumscore > 6) {
         return 2;
     } else {
77c0b149
         return 0;
88a849c7
     }
5dbafeb7
 }
 
910f02a0
 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
86ba2327
  * (-1) if not available */
 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
b45a7a18
 {
     int afc, len, flags;
     const uint8_t *p;
     unsigned int v;
 
     afc = (packet[3] >> 4) & 3;
     if (afc <= 1)
ca80e158
         return AVERROR_INVALIDDATA;
86ba2327
     p   = packet + 4;
b45a7a18
     len = p[0];
     p++;
     if (len == 0)
ca80e158
         return AVERROR_INVALIDDATA;
b45a7a18
     flags = *p++;
     len--;
     if (!(flags & 0x10))
ca80e158
         return AVERROR_INVALIDDATA;
b45a7a18
     if (len < 6)
ca80e158
         return AVERROR_INVALIDDATA;
86ba2327
     v          = AV_RB32(p);
     *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
     *ppcr_low  = ((p[4] & 1) << 8) | p[5];
b45a7a18
     return 0;
 }
 
a5f23d8d
 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
 
     /* NOTE: We attempt to seek on non-seekable files as well, as the
      * probe buffer usually is big enough. Only warn if the seek failed
      * on files where the seek should work. */
     if (avio_seek(pb, pos, SEEK_SET) < 0)
4de591e6
         av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
a5f23d8d
 }
 
6e9651d1
 static int mpegts_read_header(AVFormatContext *s)
5dbafeb7
 {
     MpegTSContext *ts = s->priv_data;
86ba2327
     AVIOContext *pb   = s->pb;
ceb0d79f
     uint8_t buf[8 * 1024] = {0};
4dc8a963
     int len;
655b6dcb
     int64_t pos, probesize = s->probesize;
e05655fb
 
66cf78e9
     s->internal->prefer_codec_framerate = 1;
 
a4f387bf
     if (ffio_ensure_seekback(pb, probesize) < 0)
         av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
8a8d9a73
 
cb66db80
     /* read the first 8192 bytes to get packet size */
384c9c2f
     pos = avio_tell(pb);
e63a3628
     len = avio_read(pb, buf, sizeof(buf));
04064e1c
     ts->raw_packet_size = get_packet_size(buf, len);
90f5e991
     if (ts->raw_packet_size <= 0) {
         av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
         ts->raw_packet_size = TS_PACKET_SIZE;
     }
86ba2327
     ts->stream     = s;
5dbafeb7
     ts->auto_guess = 0;
 
66355be3
     if (s->iformat == &ff_mpegts_demuxer) {
b45a7a18
         /* normal demux */
fc48fe84
 
da9cea77
         /* first do a scan to get all the services */
a5f23d8d
         seek_back(s, pb, pos);
c950c25a
 
         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
115329f1
 
7b9677f6
         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
115329f1
 
ff9a1541
         handle_packets(ts, probesize / ts->raw_packet_size);
a45ec414
         /* if could not find service, enable auto_guess */
115329f1
 
a45ec414
         ts->auto_guess = 1;
115329f1
 
1a3eb042
         av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
ebcf352a
 
b45a7a18
         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];
5afe1d27
         const uint8_t *data;
115329f1
 
b45a7a18
         /* only read packets */
115329f1
 
3b3bbdd3
         st = avformat_new_stream(s, NULL);
b45a7a18
         if (!st)
ca80e158
             return AVERROR(ENOMEM);
c3f9ebf7
         avpriv_set_pts_info(st, 60, 1, 27000000);
9200514a
         st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
         st->codecpar->codec_id   = AV_CODEC_ID_MPEG2TS;
115329f1
 
b45a7a18
         /* we iterate until we find two PCRs to estimate the bitrate */
86ba2327
         pcr_pid    = -1;
         nb_pcrs    = 0;
b45a7a18
         nb_packets = 0;
86ba2327
         for (;;) {
cabb1681
             ret = read_packet(s, packet, ts->raw_packet_size, &data);
b45a7a18
             if (ret < 0)
ca80e158
                 return ret;
cabb1681
             pid = AV_RB16(data + 1) & 0x1fff;
b45a7a18
             if ((pcr_pid == -1 || pcr_pid == pid) &&
cabb1681
                 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
                 finished_reading_packet(s, ts->raw_packet_size);
b45a7a18
                 pcr_pid = pid;
                 packet_count[nb_pcrs] = nb_packets;
                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
                 nb_pcrs++;
1bbb18fe
                 if (nb_pcrs >= 2) {
                     if (pcrs[1] - pcrs[0] > 0) {
                         /* the difference needs to be positive to make sense for bitrate computation */
                         break;
                     } else {
                         av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
                         pcrs[0] = pcrs[1];
                         packet_count[0] = packet_count[1];
                         nb_pcrs--;
                     }
                 }
cabb1681
             } else {
                 finished_reading_packet(s, ts->raw_packet_size);
b45a7a18
             }
             nb_packets++;
         }
5dbafeb7
 
b45a7a18
         /* 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]);
86ba2327
         ts->cur_pcr  = pcrs[0] - ts->pcr_incr * packet_count[0];
db07fc20
         s->bit_rate  = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
9200514a
         st->codecpar->bit_rate = s->bit_rate;
86ba2327
         st->start_time      = ts->cur_pcr;
1a3eb042
         av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
045dd4b9
                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
fe9cf0d4
     }
5dbafeb7
 
4e996604
     seek_back(s, pb, pos);
fe9cf0d4
     return 0;
5dbafeb7
 }
 
b45a7a18
 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
 
86ba2327
 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
b45a7a18
 {
     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];
5afe1d27
     const uint8_t *data;
b45a7a18
 
     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
8fa36ae0
         return AVERROR(ENOMEM);
cabb1681
     ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
86ba2327
     pkt->pos = avio_tell(s->pb);
b45a7a18
     if (ret < 0) {
ce70f28a
         av_packet_unref(pkt);
b45a7a18
         return ret;
     }
cabb1681
     if (data != pkt->data)
         memcpy(pkt->data, data, ts->raw_packet_size);
     finished_reading_packet(s, ts->raw_packet_size);
b45a7a18
     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 */
384c9c2f
             pos = avio_tell(s->pb);
86ba2327
             for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
f59d8ff8
                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
e63a3628
                 avio_read(s->pb, pcr_buf, 12);
b45a7a18
                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
                     /* XXX: not precise enough */
86ba2327
                     ts->pcr_incr =
                         ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
b45a7a18
                         (i + 1);
                     break;
                 }
             }
f59d8ff8
             avio_seek(s->pb, pos, SEEK_SET);
b45a7a18
             /* no next PCR found: we use previous increment */
             ts->cur_pcr = pcr_h * 300 + pcr_l;
         }
86ba2327
         pkt->pts      = ts->cur_pcr;
b45a7a18
         pkt->duration = ts->pcr_incr;
86ba2327
         ts->cur_pcr  += ts->pcr_incr;
b45a7a18
     }
     pkt->stream_index = 0;
     return 0;
 }
 
86ba2327
 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
5dbafeb7
 {
     MpegTSContext *ts = s->priv_data;
0c137557
     int ret, i;
 
df8aa459
     pkt->size = -1;
38c48be2
     ts->pkt = pkt;
0c137557
     ret = handle_packets(ts, 0);
     if (ret < 0) {
c2f861ca
         av_packet_unref(ts->pkt);
0c137557
         /* flush pes data left */
86ba2327
         for (i = 0; i < NB_PID_MAX; i++)
0c137557
             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) {
14f7a3d5
                     ret = new_pes_packet(pes, pkt);
                     if (ret < 0)
                         return ret;
8956f680
                     pes->state = MPEGTS_SKIP;
0c137557
                     ret = 0;
                     break;
                 }
             }
     }
 
df8aa459
     if (!ret && pkt->size < 0)
085ab749
         ret = AVERROR_INVALIDDATA;
0c137557
     return ret;
fe9cf0d4
 }
 
a717f990
 static void mpegts_free(MpegTSContext *ts)
fe9cf0d4
 {
     int i;
81d5ae6d
 
     clear_programs(ts);
 
86ba2327
     for (i = 0; i < NB_PID_MAX; i++)
         if (ts->pids[i])
             mpegts_close_filter(ts, ts->pids[i]);
a717f990
 }
00a6b92b
 
a717f990
 static int mpegts_read_close(AVFormatContext *s)
 {
     MpegTSContext *ts = s->priv_data;
     mpegts_free(ts);
fe9cf0d4
     return 0;
 }
 
11bc5580
 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
cdd5034f
                               int64_t *ppos, int64_t pos_limit)
27f388aa
 {
     MpegTSContext *ts = s->priv_data;
     int64_t pos, timestamp;
     uint8_t buf[TS_PACKET_SIZE];
86ba2327
     int pcr_l, pcr_pid =
         ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
5b13778f
     int pos47 = ts->pos47_full % ts->raw_packet_size;
86ba2327
     pos =
ceb0d79f
         ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
         ts->raw_packet_size + pos47;
62142663
     while(pos < pos_limit) {
         if (avio_seek(s->pb, pos, SEEK_SET) < 0)
             return AV_NOPTS_VALUE;
         if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
             return AV_NOPTS_VALUE;
9fa47cb7
         if (buf[0] != 0x47) {
dbe1dd59
             if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
9fa47cb7
                 return AV_NOPTS_VALUE;
63b796b0
             pos = avio_tell(s->pb);
9fa47cb7
             continue;
         }
62142663
         if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
             parse_pcr(&timestamp, &pcr_l, buf) == 0) {
             *ppos = pos;
             return timestamp;
27f388aa
         }
62142663
         pos += ts->raw_packet_size;
     }
27f388aa
 
880e8382
     return AV_NOPTS_VALUE;
27f388aa
 }
 
de9862a9
 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
                               int64_t *ppos, int64_t pos_limit)
 {
     MpegTSContext *ts = s->priv_data;
b6ffceef
     int64_t pos;
5b13778f
     int pos47 = ts->pos47_full % ts->raw_packet_size;
     pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
de9862a9
     ff_read_frame_flush(s);
     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
         return AV_NOPTS_VALUE;
     while(pos < pos_limit) {
         int ret;
         AVPacket pkt;
         av_init_packet(&pkt);
ceb0d79f
         ret = av_read_frame(s, &pkt);
         if (ret < 0)
de9862a9
             return AV_NOPTS_VALUE;
ceb0d79f
         if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
db1347f6
             ff_reduce_index(s, pkt.stream_index);
             av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
ceb0d79f
             if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
6255bf3d
                 int64_t dts = pkt.dts;
ceb0d79f
                 *ppos = pkt.pos;
6255bf3d
                 av_packet_unref(&pkt);
                 return dts;
db1347f6
             }
de9862a9
         }
         pos = pkt.pos;
6255bf3d
         av_packet_unref(&pkt);
de9862a9
     }
 
     return AV_NOPTS_VALUE;
 }
 
b45a7a18
 /**************************************************************/
 /* parsing functions - called from other demuxers such as RTP */
 
5b12b4fc
 MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
b45a7a18
 {
     MpegTSContext *ts;
115329f1
 
b45a7a18
     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;
c8ce2b0a
     mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
     mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
 
b45a7a18
     return ts;
 }
 
 /* return the consumed length if a packet was output, or -1 if no
86ba2327
  * packet is output */
5b12b4fc
 int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
                                const uint8_t *buf, int len)
b45a7a18
 {
     int len1;
 
     len1 = len;
     ts->pkt = pkt;
86ba2327
     for (;;) {
bc38e837
         ts->stop_parse = 0;
b45a7a18
         if (len < TS_PACKET_SIZE)
ca80e158
             return AVERROR_INVALIDDATA;
b45a7a18
         if (buf[0] != 0x47) {
550f0a9b
             buf++;
b45a7a18
             len--;
         } else {
             handle_packet(ts, buf);
             buf += TS_PACKET_SIZE;
             len -= TS_PACKET_SIZE;
bc38e837
             if (ts->stop_parse == 1)
                 break;
b45a7a18
         }
     }
     return len1 - len;
 }
 
5b12b4fc
 void avpriv_mpegts_parse_close(MpegTSContext *ts)
b45a7a18
 {
a717f990
     mpegts_free(ts);
b45a7a18
     av_free(ts);
 }
 
66355be3
 AVInputFormat ff_mpegts_demuxer = {
dfc2c4d9
     .name           = "mpegts",
0177b7d2
     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
dfc2c4d9
     .priv_data_size = sizeof(MpegTSContext),
     .read_probe     = mpegts_probe,
     .read_header    = mpegts_read_header,
     .read_packet    = mpegts_read_packet,
     .read_close     = mpegts_read_close,
de9862a9
     .read_timestamp = mpegts_get_dts,
20234a4b
     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
a7bb12a3
     .priv_class     = &mpegts_class,
fe9cf0d4
 };
38c48be2
 
66355be3
 AVInputFormat ff_mpegtsraw_demuxer = {
dfc2c4d9
     .name           = "mpegtsraw",
0177b7d2
     .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
dfc2c4d9
     .priv_data_size = sizeof(MpegTSContext),
     .read_header    = mpegts_read_header,
     .read_packet    = mpegts_raw_read_packet,
     .read_close     = mpegts_read_close,
de9862a9
     .read_timestamp = mpegts_get_dts,
20234a4b
     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
     .priv_class     = &mpegtsraw_class,
38c48be2
 };