LCOV - code coverage report
Current view: top level - libavformat - mpegts.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 912 1632 55.9 %
Date: 2017-12-17 04:34:43 Functions: 46 68 67.6 %

          Line data    Source code
       1             : /*
       2             :  * MPEG-2 transport stream (aka DVB) demuxer
       3             :  * Copyright (c) 2002-2003 Fabrice Bellard
       4             :  *
       5             :  * This file is part of FFmpeg.
       6             :  *
       7             :  * FFmpeg is free software; you can redistribute it and/or
       8             :  * modify it under the terms of the GNU Lesser General Public
       9             :  * License as published by the Free Software Foundation; either
      10             :  * version 2.1 of the License, or (at your option) any later version.
      11             :  *
      12             :  * FFmpeg is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      15             :  * Lesser General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU Lesser General Public
      18             :  * License along with FFmpeg; if not, write to the Free Software
      19             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      20             :  */
      21             : 
      22             : #include "libavutil/buffer.h"
      23             : #include "libavutil/crc.h"
      24             : #include "libavutil/internal.h"
      25             : #include "libavutil/intreadwrite.h"
      26             : #include "libavutil/log.h"
      27             : #include "libavutil/dict.h"
      28             : #include "libavutil/mathematics.h"
      29             : #include "libavutil/opt.h"
      30             : #include "libavutil/avassert.h"
      31             : #include "libavcodec/bytestream.h"
      32             : #include "libavcodec/get_bits.h"
      33             : #include "libavcodec/opus.h"
      34             : #include "avformat.h"
      35             : #include "mpegts.h"
      36             : #include "internal.h"
      37             : #include "avio_internal.h"
      38             : #include "mpeg.h"
      39             : #include "isom.h"
      40             : 
      41             : /* maximum size in which we look for synchronization if
      42             :  * synchronization is lost */
      43             : #define MAX_RESYNC_SIZE 65536
      44             : 
      45             : #define MAX_PES_PAYLOAD 200 * 1024
      46             : 
      47             : #define MAX_MP4_DESCR_COUNT 16
      48             : 
      49             : #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend)                \
      50             :     do {                                                                       \
      51             :         if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
      52             :             (modulus) = (dividend) % (divisor);                                \
      53             :         (prev_dividend) = (dividend);                                          \
      54             :     } while (0)
      55             : 
      56             : enum MpegTSFilterType {
      57             :     MPEGTS_PES,
      58             :     MPEGTS_SECTION,
      59             :     MPEGTS_PCR,
      60             : };
      61             : 
      62             : typedef struct MpegTSFilter MpegTSFilter;
      63             : 
      64             : typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
      65             :                          int is_start, int64_t pos);
      66             : 
      67             : typedef struct MpegTSPESFilter {
      68             :     PESCallback *pes_cb;
      69             :     void *opaque;
      70             : } MpegTSPESFilter;
      71             : 
      72             : typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
      73             : 
      74             : typedef void SetServiceCallback (void *opaque, int ret);
      75             : 
      76             : typedef struct MpegTSSectionFilter {
      77             :     int section_index;
      78             :     int section_h_size;
      79             :     int last_ver;
      80             :     unsigned crc;
      81             :     unsigned last_crc;
      82             :     uint8_t *section_buf;
      83             :     unsigned int check_crc : 1;
      84             :     unsigned int end_of_section_reached : 1;
      85             :     SectionCallback *section_cb;
      86             :     void *opaque;
      87             : } MpegTSSectionFilter;
      88             : 
      89             : struct MpegTSFilter {
      90             :     int pid;
      91             :     int es_id;
      92             :     int last_cc; /* last cc code (-1 if first packet) */
      93             :     int64_t last_pcr;
      94             :     enum MpegTSFilterType type;
      95             :     union {
      96             :         MpegTSPESFilter pes_filter;
      97             :         MpegTSSectionFilter section_filter;
      98             :     } u;
      99             : };
     100             : 
     101             : #define MAX_PIDS_PER_PROGRAM 64
     102             : struct Program {
     103             :     unsigned int id; // program id/service id
     104             :     unsigned int nb_pids;
     105             :     unsigned int pids[MAX_PIDS_PER_PROGRAM];
     106             : 
     107             :     /** have we found pmt for this program */
     108             :     int pmt_found;
     109             : };
     110             : 
     111             : struct MpegTSContext {
     112             :     const AVClass *class;
     113             :     /* user data */
     114             :     AVFormatContext *stream;
     115             :     /** raw packet size, including FEC if present */
     116             :     int raw_packet_size;
     117             : 
     118             :     int size_stat[3];
     119             :     int size_stat_count;
     120             : #define SIZE_STAT_THRESHOLD 10
     121             : 
     122             :     int64_t pos47_full;
     123             : 
     124             :     /** if true, all pids are analyzed to find streams */
     125             :     int auto_guess;
     126             : 
     127             :     /** compute exact PCR for each transport stream packet */
     128             :     int mpeg2ts_compute_pcr;
     129             : 
     130             :     /** fix dvb teletext pts                                 */
     131             :     int fix_teletext_pts;
     132             : 
     133             :     int64_t cur_pcr;    /**< used to estimate the exact PCR */
     134             :     int pcr_incr;       /**< used to estimate the exact PCR */
     135             : 
     136             :     /* data needed to handle file based ts */
     137             :     /** stop parsing loop */
     138             :     int stop_parse;
     139             :     /** packet containing Audio/Video data */
     140             :     AVPacket *pkt;
     141             :     /** to detect seek */
     142             :     int64_t last_pos;
     143             : 
     144             :     int skip_changes;
     145             :     int skip_clear;
     146             : 
     147             :     int scan_all_pmts;
     148             : 
     149             :     int resync_size;
     150             : 
     151             :     /******************************************/
     152             :     /* private mpegts data */
     153             :     /* scan context */
     154             :     /** structure to keep track of Program->pids mapping */
     155             :     unsigned int nb_prg;
     156             :     struct Program *prg;
     157             : 
     158             :     int8_t crc_validity[NB_PID_MAX];
     159             :     /** filters for various streams specified by PMT + for the PAT and PMT */
     160             :     MpegTSFilter *pids[NB_PID_MAX];
     161             :     int current_pid;
     162             : };
     163             : 
     164             : #define MPEGTS_OPTIONS \
     165             :     { "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 }
     166             : 
     167             : static const AVOption options[] = {
     168             :     MPEGTS_OPTIONS,
     169             :     {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
     170             :      {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
     171             :     {"ts_packetsize", "output option carrying the raw packet size", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
     172             :      {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
     173             :     {"scan_all_pmts",   "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
     174             :      { .i64 =  -1}, -1, 1,  AV_OPT_FLAG_DECODING_PARAM },
     175             :     {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
     176             :      {.i64 = 0}, 0, 1, 0 },
     177             :     {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
     178             :      {.i64 = 0}, 0, 1, 0 },
     179             :     { NULL },
     180             : };
     181             : 
     182             : static const AVClass mpegts_class = {
     183             :     .class_name = "mpegts demuxer",
     184             :     .item_name  = av_default_item_name,
     185             :     .option     = options,
     186             :     .version    = LIBAVUTIL_VERSION_INT,
     187             : };
     188             : 
     189             : static const AVOption raw_options[] = {
     190             :     MPEGTS_OPTIONS,
     191             :     { "compute_pcr",   "compute exact PCR for each transport stream packet",
     192             :           offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
     193             :           { .i64 = 0 }, 0, 1,  AV_OPT_FLAG_DECODING_PARAM },
     194             :     { "ts_packetsize", "output option carrying the raw packet size",
     195             :       offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
     196             :       { .i64 = 0 }, 0, 0,
     197             :       AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
     198             :     { NULL },
     199             : };
     200             : 
     201             : static const AVClass mpegtsraw_class = {
     202             :     .class_name = "mpegtsraw demuxer",
     203             :     .item_name  = av_default_item_name,
     204             :     .option     = raw_options,
     205             :     .version    = LIBAVUTIL_VERSION_INT,
     206             : };
     207             : 
     208             : /* TS stream handling */
     209             : 
     210             : enum MpegTSState {
     211             :     MPEGTS_HEADER = 0,
     212             :     MPEGTS_PESHEADER,
     213             :     MPEGTS_PESHEADER_FILL,
     214             :     MPEGTS_PAYLOAD,
     215             :     MPEGTS_SKIP,
     216             : };
     217             : 
     218             : /* enough for PES header + length */
     219             : #define PES_START_SIZE  6
     220             : #define PES_HEADER_SIZE 9
     221             : #define MAX_PES_HEADER_SIZE (9 + 255)
     222             : 
     223             : typedef struct PESContext {
     224             :     int pid;
     225             :     int pcr_pid; /**< if -1 then all packets containing PCR are considered */
     226             :     int stream_type;
     227             :     MpegTSContext *ts;
     228             :     AVFormatContext *stream;
     229             :     AVStream *st;
     230             :     AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
     231             :     enum MpegTSState state;
     232             :     /* used to get the format */
     233             :     int data_index;
     234             :     int flags; /**< copied to the AVPacket flags */
     235             :     int total_size;
     236             :     int pes_header_size;
     237             :     int extended_stream_id;
     238             :     uint8_t stream_id;
     239             :     int64_t pts, dts;
     240             :     int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
     241             :     uint8_t header[MAX_PES_HEADER_SIZE];
     242             :     AVBufferRef *buffer;
     243             :     SLConfigDescr sl;
     244             : } PESContext;
     245             : 
     246             : extern AVInputFormat ff_mpegts_demuxer;
     247             : 
     248        1115 : static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
     249             : {
     250             :     int i;
     251        1115 :     for (i = 0; i < ts->nb_prg; i++) {
     252        1115 :         if (ts->prg[i].id == programid) {
     253        1115 :             return &ts->prg[i];
     254             :         }
     255             :     }
     256           0 :     return NULL;
     257             : }
     258             : 
     259         148 : static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
     260             : {
     261         148 :     AVProgram *prg = NULL;
     262             :     int i;
     263             : 
     264         148 :     for (i = 0; i < ts->stream->nb_programs; i++)
     265         148 :         if (ts->stream->programs[i]->id == programid) {
     266         148 :             prg = ts->stream->programs[i];
     267         148 :             break;
     268             :         }
     269         148 :     if (!prg)
     270           0 :         return;
     271         148 :     prg->nb_stream_indexes = 0;
     272             : }
     273             : 
     274         148 : static void clear_program(MpegTSContext *ts, unsigned int programid)
     275             : {
     276             :     int i;
     277             : 
     278         148 :     clear_avprogram(ts, programid);
     279         296 :     for (i = 0; i < ts->nb_prg; i++)
     280         148 :         if (ts->prg[i].id == programid) {
     281         148 :             ts->prg[i].nb_pids = 0;
     282         148 :             ts->prg[i].pmt_found = 0;
     283             :         }
     284         148 : }
     285             : 
     286         207 : static void clear_programs(MpegTSContext *ts)
     287             : {
     288         207 :     av_freep(&ts->prg);
     289         207 :     ts->nb_prg = 0;
     290         207 : }
     291             : 
     292         176 : static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
     293             : {
     294             :     struct Program *p;
     295         176 :     if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
     296           0 :         ts->nb_prg = 0;
     297           0 :         return;
     298             :     }
     299         176 :     p = &ts->prg[ts->nb_prg];
     300         176 :     p->id = programid;
     301         176 :     p->nb_pids = 0;
     302         176 :     p->pmt_found = 0;
     303         176 :     ts->nb_prg++;
     304             : }
     305             : 
     306         912 : static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
     307             :                            unsigned int pid)
     308             : {
     309         912 :     struct Program *p = get_program(ts, programid);
     310             :     int i;
     311         912 :     if (!p)
     312           0 :         return;
     313             : 
     314         912 :     if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
     315           0 :         return;
     316             : 
     317        1540 :     for (i = 0; i < p->nb_pids; i++)
     318         878 :         if (p->pids[i] == pid)
     319         250 :             return;
     320             : 
     321         662 :     p->pids[p->nb_pids++] = pid;
     322             : }
     323             : 
     324         203 : static void set_pmt_found(MpegTSContext *ts, unsigned int programid)
     325             : {
     326         203 :     struct Program *p = get_program(ts, programid);
     327         203 :     if (!p)
     328           0 :         return;
     329             : 
     330         203 :     p->pmt_found = 1;
     331             : }
     332             : 
     333         203 : static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
     334             : {
     335             :     int i;
     336         203 :     for (i = 0; i < s->nb_programs; i++) {
     337         203 :         if (s->programs[i]->id == programid) {
     338         203 :             s->programs[i]->pcr_pid = pid;
     339         203 :             break;
     340             :         }
     341             :     }
     342         203 : }
     343             : 
     344             : /**
     345             :  * @brief discard_pid() decides if the pid is to be discarded according
     346             :  *                      to caller's programs selection
     347             :  * @param ts    : - TS context
     348             :  * @param pid   : - pid
     349             :  * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
     350             :  *         0 otherwise
     351             :  */
     352      264254 : static int discard_pid(MpegTSContext *ts, unsigned int pid)
     353             : {
     354             :     int i, j, k;
     355      264254 :     int used = 0, discarded = 0;
     356             :     struct Program *p;
     357             : 
     358             :     /* If none of the programs have .discard=AVDISCARD_ALL then there's
     359             :      * no way we have to discard this packet */
     360      525328 :     for (k = 0; k < ts->stream->nb_programs; k++)
     361      261074 :         if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
     362           0 :             break;
     363      264254 :     if (k == ts->stream->nb_programs)
     364      264254 :         return 0;
     365             : 
     366           0 :     for (i = 0; i < ts->nb_prg; i++) {
     367           0 :         p = &ts->prg[i];
     368           0 :         for (j = 0; j < p->nb_pids; j++) {
     369           0 :             if (p->pids[j] != pid)
     370           0 :                 continue;
     371             :             // is program with id p->id set to be discarded?
     372           0 :             for (k = 0; k < ts->stream->nb_programs; k++) {
     373           0 :                 if (ts->stream->programs[k]->id == p->id) {
     374           0 :                     if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
     375           0 :                         discarded++;
     376             :                     else
     377           0 :                         used++;
     378             :                 }
     379             :             }
     380             :         }
     381             :     }
     382             : 
     383           0 :     return !used && discarded;
     384             : }
     385             : 
     386             : /**
     387             :  *  Assemble PES packets out of TS packets, and then call the "section_cb"
     388             :  *  function when they are complete.
     389             :  */
     390        7243 : static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
     391             :                                const uint8_t *buf, int buf_size, int is_start)
     392             : {
     393        7243 :     MpegTSSectionFilter *tss = &tss1->u.section_filter;
     394             :     int len;
     395             : 
     396        7243 :     if (is_start) {
     397        7243 :         memcpy(tss->section_buf, buf, buf_size);
     398        7243 :         tss->section_index = buf_size;
     399        7243 :         tss->section_h_size = -1;
     400        7243 :         tss->end_of_section_reached = 0;
     401             :     } else {
     402           0 :         if (tss->end_of_section_reached)
     403           0 :             return;
     404           0 :         len = 4096 - tss->section_index;
     405           0 :         if (buf_size < len)
     406           0 :             len = buf_size;
     407           0 :         memcpy(tss->section_buf + tss->section_index, buf, len);
     408           0 :         tss->section_index += len;
     409             :     }
     410             : 
     411             :     /* compute section length if possible */
     412        7243 :     if (tss->section_h_size == -1 && tss->section_index >= 3) {
     413        7243 :         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
     414        7243 :         if (len > 4096)
     415           0 :             return;
     416        7243 :         tss->section_h_size = len;
     417             :     }
     418             : 
     419       14486 :     if (tss->section_h_size != -1 &&
     420        7243 :         tss->section_index >= tss->section_h_size) {
     421        7243 :         int crc_valid = 1;
     422        7243 :         tss->end_of_section_reached = 1;
     423             : 
     424        7243 :         if (tss->check_crc) {
     425        7243 :             crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
     426        7243 :             if (tss->section_h_size >= 4)
     427        7243 :                 tss->crc = AV_RB32(tss->section_buf + tss->section_h_size - 4);
     428             : 
     429        7243 :             if (crc_valid) {
     430        7243 :                 ts->crc_validity[ tss1->pid ] = 100;
     431           0 :             }else if (ts->crc_validity[ tss1->pid ] > -10) {
     432           0 :                 ts->crc_validity[ tss1->pid ]--;
     433             :             }else
     434           0 :                 crc_valid = 2;
     435             :         }
     436        7243 :         if (crc_valid) {
     437        7243 :             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
     438        7243 :             if (crc_valid != 1)
     439           0 :                 tss->last_ver = -1;
     440             :         }
     441             :     }
     442             : }
     443             : 
     444         152 : static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
     445             :                                         enum MpegTSFilterType type)
     446             : {
     447             :     MpegTSFilter *filter;
     448             : 
     449         152 :     av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
     450             : 
     451         152 :     if (pid >= NB_PID_MAX || ts->pids[pid])
     452           0 :         return NULL;
     453         152 :     filter = av_mallocz(sizeof(MpegTSFilter));
     454         152 :     if (!filter)
     455           0 :         return NULL;
     456         152 :     ts->pids[pid] = filter;
     457             : 
     458         152 :     filter->type    = type;
     459         152 :     filter->pid     = pid;
     460         152 :     filter->es_id   = -1;
     461         152 :     filter->last_cc = -1;
     462         152 :     filter->last_pcr= -1;
     463             : 
     464         152 :     return filter;
     465             : }
     466             : 
     467          93 : static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
     468             :                                                 unsigned int pid,
     469             :                                                 SectionCallback *section_cb,
     470             :                                                 void *opaque,
     471             :                                                 int check_crc)
     472             : {
     473             :     MpegTSFilter *filter;
     474             :     MpegTSSectionFilter *sec;
     475             : 
     476          93 :     if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION)))
     477           0 :         return NULL;
     478          93 :     sec = &filter->u.section_filter;
     479          93 :     sec->section_cb  = section_cb;
     480          93 :     sec->opaque      = opaque;
     481          93 :     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
     482          93 :     sec->check_crc   = check_crc;
     483          93 :     sec->last_ver    = -1;
     484             : 
     485          93 :     if (!sec->section_buf) {
     486           0 :         av_free(filter);
     487           0 :         return NULL;
     488             :     }
     489          93 :     return filter;
     490             : }
     491             : 
     492          59 : static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
     493             :                                             PESCallback *pes_cb,
     494             :                                             void *opaque)
     495             : {
     496             :     MpegTSFilter *filter;
     497             :     MpegTSPESFilter *pes;
     498             : 
     499          59 :     if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
     500           0 :         return NULL;
     501             : 
     502          59 :     pes = &filter->u.pes_filter;
     503          59 :     pes->pes_cb = pes_cb;
     504          59 :     pes->opaque = opaque;
     505          59 :     return filter;
     506             : }
     507             : 
     508           0 : static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
     509             : {
     510           0 :     return mpegts_open_filter(ts, pid, MPEGTS_PCR);
     511             : }
     512             : 
     513         152 : static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
     514             : {
     515             :     int pid;
     516             : 
     517         152 :     pid = filter->pid;
     518         152 :     if (filter->type == MPEGTS_SECTION)
     519          93 :         av_freep(&filter->u.section_filter.section_buf);
     520          59 :     else if (filter->type == MPEGTS_PES) {
     521          59 :         PESContext *pes = filter->u.pes_filter.opaque;
     522          59 :         av_buffer_unref(&pes->buffer);
     523             :         /* referenced private data will be freed later in
     524             :          * avformat_close_input */
     525          59 :         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
     526          12 :             av_freep(&filter->u.pes_filter.opaque);
     527             :         }
     528             :     }
     529             : 
     530         152 :     av_free(filter);
     531         152 :     ts->pids[pid] = NULL;
     532         152 : }
     533             : 
     534       32223 : static int analyze(const uint8_t *buf, int size, int packet_size,
     535             :                    int probe)
     536             : {
     537             :     int stat[TS_MAX_PACKET_SIZE];
     538       32223 :     int stat_all = 0;
     539             :     int i;
     540       32223 :     int best_score = 0;
     541             : 
     542       32223 :     memset(stat, 0, packet_size * sizeof(*stat));
     543             : 
     544   367242090 :     for (i = 0; i < size - 3; i++) {
     545   367209867 :         if (buf[i] == 0x47) {
     546      664983 :             int pid = AV_RB16(buf+1) & 0x1FFF;
     547      664983 :             int asc = buf[i + 3] & 0x30;
     548      664983 :             if (!probe || pid == 0x1FFF || asc) {
     549      543221 :                 int x = i % packet_size;
     550      543221 :                 stat[x]++;
     551      543221 :                 stat_all++;
     552      543221 :                 if (stat[x] > best_score) {
     553       48787 :                     best_score = stat[x];
     554             :                 }
     555             :             }
     556             :         }
     557             :     }
     558             : 
     559       32223 :     return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
     560             : }
     561             : 
     562             : /* autodetect fec presence. Must have at least 1024 bytes  */
     563          31 : static int get_packet_size(const uint8_t *buf, int size)
     564             : {
     565             :     int score, fec_score, dvhs_score;
     566             : 
     567          31 :     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
     568           0 :         return AVERROR_INVALIDDATA;
     569             : 
     570          31 :     score      = analyze(buf, size, TS_PACKET_SIZE,      0);
     571          31 :     dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, 0);
     572          31 :     fec_score  = analyze(buf, size, TS_FEC_PACKET_SIZE,  0);
     573          31 :     av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
     574             :             score, dvhs_score, fec_score);
     575             : 
     576          31 :     if (score > fec_score && score > dvhs_score)
     577          31 :         return TS_PACKET_SIZE;
     578           0 :     else if (dvhs_score > score && dvhs_score > fec_score)
     579           0 :         return TS_DVHS_PACKET_SIZE;
     580           0 :     else if (score < fec_score && dvhs_score < fec_score)
     581           0 :         return TS_FEC_PACKET_SIZE;
     582             :     else
     583           0 :         return AVERROR_INVALIDDATA;
     584             : }
     585             : 
     586             : typedef struct SectionHeader {
     587             :     uint8_t tid;
     588             :     uint16_t id;
     589             :     uint8_t version;
     590             :     uint8_t sec_num;
     591             :     uint8_t last_sec_num;
     592             : } SectionHeader;
     593             : 
     594        6675 : static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
     595             : {
     596        6675 :     if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
     597        6167 :         return 1;
     598             : 
     599         508 :     tssf->last_ver = h->version;
     600         508 :     tssf->last_crc = tssf->crc;
     601             : 
     602         508 :     return 0;
     603             : }
     604             : 
     605       31347 : static inline int get8(const uint8_t **pp, const uint8_t *p_end)
     606             : {
     607             :     const uint8_t *p;
     608             :     int c;
     609             : 
     610       31347 :     p = *pp;
     611       31347 :     if (p >= p_end)
     612         689 :         return AVERROR_INVALIDDATA;
     613       30658 :     c   = *p++;
     614       30658 :     *pp = p;
     615       30658 :     return c;
     616             : }
     617             : 
     618        9407 : static inline int get16(const uint8_t **pp, const uint8_t *p_end)
     619             : {
     620             :     const uint8_t *p;
     621             :     int c;
     622             : 
     623        9407 :     p = *pp;
     624        9407 :     if (1 >= p_end - p)
     625         305 :         return AVERROR_INVALIDDATA;
     626        9102 :     c   = AV_RB16(p);
     627        9102 :     p  += 2;
     628        9102 :     *pp = p;
     629        9102 :     return c;
     630             : }
     631             : 
     632             : /* read and allocate a DVB string preceded by its length */
     633         258 : static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
     634             : {
     635             :     int len;
     636             :     const uint8_t *p;
     637             :     char *str;
     638             : 
     639         258 :     p   = *pp;
     640         258 :     len = get8(&p, p_end);
     641         258 :     if (len < 0)
     642           0 :         return NULL;
     643         258 :     if (len > p_end - p)
     644           0 :         return NULL;
     645         258 :     str = av_malloc(len + 1);
     646         258 :     if (!str)
     647           0 :         return NULL;
     648         258 :     memcpy(str, p, len);
     649         258 :     str[len] = '\0';
     650         258 :     p  += len;
     651         258 :     *pp = p;
     652         258 :     return str;
     653             : }
     654             : 
     655        7243 : static int parse_section_header(SectionHeader *h,
     656             :                                 const uint8_t **pp, const uint8_t *p_end)
     657             : {
     658             :     int val;
     659             : 
     660        7243 :     val = get8(pp, p_end);
     661        7243 :     if (val < 0)
     662           0 :         return val;
     663        7243 :     h->tid = val;
     664        7243 :     *pp += 2;
     665        7243 :     val  = get16(pp, p_end);
     666        7243 :     if (val < 0)
     667           0 :         return val;
     668        7243 :     h->id = val;
     669        7243 :     val = get8(pp, p_end);
     670        7243 :     if (val < 0)
     671           0 :         return val;
     672        7243 :     h->version = (val >> 1) & 0x1f;
     673        7243 :     val = get8(pp, p_end);
     674        7243 :     if (val < 0)
     675           0 :         return val;
     676        7243 :     h->sec_num = val;
     677        7243 :     val = get8(pp, p_end);
     678        7243 :     if (val < 0)
     679           0 :         return val;
     680        7243 :     h->last_sec_num = val;
     681        7243 :     return 0;
     682             : }
     683             : 
     684             : typedef struct StreamType {
     685             :     uint32_t stream_type;
     686             :     enum AVMediaType codec_type;
     687             :     enum AVCodecID codec_id;
     688             : } StreamType;
     689             : 
     690             : static const StreamType ISO_types[] = {
     691             :     { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
     692             :     { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
     693             :     { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
     694             :     { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
     695             :     { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC        },
     696             :     { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4      },
     697             :     /* Makito encoder sets stream type 0x11 for AAC,
     698             :      * so auto-detect LOAS/LATM instead of hardcoding it. */
     699             : #if !CONFIG_LOAS_DEMUXER
     700             :     { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM   }, /* LATM syntax */
     701             : #endif
     702             :     { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
     703             :     { 0x1c, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC        },
     704             :     { 0x20, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
     705             :     { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000   },
     706             :     { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC       },
     707             :     { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS       },
     708             :     { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC      },
     709             :     { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1        },
     710             :     { 0 },
     711             : };
     712             : 
     713             : static const StreamType HDMV_types[] = {
     714             :     { 0x80, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_PCM_BLURAY        },
     715             :     { 0x81, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3               },
     716             :     { 0x82, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               },
     717             :     { 0x83, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_TRUEHD            },
     718             :     { 0x84, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3              },
     719             :     { 0x85, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD */
     720             :     { 0x86, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD MASTER*/
     721             :     { 0xa1, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3              }, /* E-AC3 Secondary Audio */
     722             :     { 0xa2, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS Express Secondary Audio */
     723             :     { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
     724             :     { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
     725             :     { 0 },
     726             : };
     727             : 
     728             : /* SCTE types */
     729             : static const StreamType SCTE_types[] = {
     730             :     { 0x86, AVMEDIA_TYPE_DATA,  AV_CODEC_ID_SCTE_35    },
     731             :     { 0 },
     732             : };
     733             : 
     734             : /* ATSC ? */
     735             : static const StreamType MISC_types[] = {
     736             :     { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
     737             :     { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
     738             :     { 0 },
     739             : };
     740             : 
     741             : static const StreamType REGD_types[] = {
     742             :     { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
     743             :     { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3   },
     744             :     { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
     745             :     { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
     746             :     { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
     747             :     { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
     748             :     { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3  },
     749             :     { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC  },
     750             :     { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA,  AV_CODEC_ID_SMPTE_KLV },
     751             :     { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA,  AV_CODEC_ID_TIMED_ID3 },
     752             :     { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1   },
     753             :     { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS  },
     754             :     { 0 },
     755             : };
     756             : 
     757             : static const StreamType METADATA_types[] = {
     758             :     { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
     759             :     { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
     760             :     { 0 },
     761             : };
     762             : 
     763             : /* descriptor present */
     764             : static const StreamType DESC_types[] = {
     765             :     { 0x6a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3          }, /* AC-3 descriptor */
     766             :     { 0x7a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3         }, /* E-AC-3 descriptor */
     767             :     { 0x7b, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS          },
     768             :     { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
     769             :     { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
     770             :     { 0 },
     771             : };
     772             : 
     773          61 : static void mpegts_find_stream_type(AVStream *st,
     774             :                                     uint32_t stream_type,
     775             :                                     const StreamType *types)
     776             : {
     777         264 :     for (; types->stream_type; types++)
     778         250 :         if (stream_type == types->stream_type) {
     779          50 :             if (st->codecpar->codec_type != types->codec_type ||
     780           3 :                 st->codecpar->codec_id   != types->codec_id) {
     781          46 :                 st->codecpar->codec_type = types->codec_type;
     782          46 :                 st->codecpar->codec_id   = types->codec_id;
     783          46 :                 st->internal->need_context_update = 1;
     784             :             }
     785          47 :             st->request_probe        = 0;
     786          47 :             return;
     787             :         }
     788             : }
     789             : 
     790          47 : static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
     791             :                                   uint32_t stream_type, uint32_t prog_reg_desc)
     792             : {
     793          47 :     int old_codec_type = st->codecpar->codec_type;
     794          47 :     int old_codec_id   = st->codecpar->codec_id;
     795          47 :     int old_codec_tag  = st->codecpar->codec_tag;
     796             : 
     797          47 :     if (avcodec_is_open(st->internal->avctx)) {
     798           0 :         av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, internal codec is open\n");
     799           0 :         return 0;
     800             :     }
     801             : 
     802          47 :     avpriv_set_pts_info(st, 33, 1, 90000);
     803          47 :     st->priv_data         = pes;
     804          47 :     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
     805          47 :     st->codecpar->codec_id   = AV_CODEC_ID_NONE;
     806          47 :     st->need_parsing      = AVSTREAM_PARSE_FULL;
     807          47 :     pes->st          = st;
     808          47 :     pes->stream_type = stream_type;
     809             : 
     810          47 :     av_log(pes->stream, AV_LOG_DEBUG,
     811             :            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
     812             :            st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
     813             : 
     814          47 :     st->codecpar->codec_tag = pes->stream_type;
     815             : 
     816          47 :     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
     817          47 :     if (pes->stream_type == 4 || pes->stream_type == 0x0f)
     818           3 :         st->request_probe = 50;
     819          94 :     if ((prog_reg_desc == AV_RL32("HDMV") ||
     820          47 :          prog_reg_desc == AV_RL32("HDPR")) &&
     821           0 :         st->codecpar->codec_id == AV_CODEC_ID_NONE) {
     822           0 :         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
     823           0 :         if (pes->stream_type == 0x83) {
     824             :             // HDMV TrueHD streams also contain an AC3 coded version of the
     825             :             // audio track - add a second stream for this
     826             :             AVStream *sub_st;
     827             :             // priv_data cannot be shared between streams
     828           0 :             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
     829           0 :             if (!sub_pes)
     830           0 :                 return AVERROR(ENOMEM);
     831           0 :             memcpy(sub_pes, pes, sizeof(*sub_pes));
     832             : 
     833           0 :             sub_st = avformat_new_stream(pes->stream, NULL);
     834           0 :             if (!sub_st) {
     835           0 :                 av_free(sub_pes);
     836           0 :                 return AVERROR(ENOMEM);
     837             :             }
     838             : 
     839           0 :             sub_st->id = pes->pid;
     840           0 :             avpriv_set_pts_info(sub_st, 33, 1, 90000);
     841           0 :             sub_st->priv_data         = sub_pes;
     842           0 :             sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
     843           0 :             sub_st->codecpar->codec_id   = AV_CODEC_ID_AC3;
     844           0 :             sub_st->need_parsing      = AVSTREAM_PARSE_FULL;
     845           0 :             sub_pes->sub_st           = pes->sub_st = sub_st;
     846             :         }
     847             :     }
     848          47 :     if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
     849           5 :         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
     850          47 :     if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
     851           5 :         st->codecpar->codec_id  = old_codec_id;
     852           5 :         st->codecpar->codec_type = old_codec_type;
     853             :     }
     854          89 :     if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
     855          50 :             (st->request_probe > 0 && st->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
     856          10 :         st->probe_packets > 0 &&
     857             :         stream_type == STREAM_TYPE_PRIVATE_DATA) {
     858           3 :         st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
     859           3 :         st->codecpar->codec_id   = AV_CODEC_ID_BIN_DATA;
     860           3 :         st->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
     861             :     }
     862             : 
     863             :     /* queue a context update if properties changed */
     864          49 :     if (old_codec_type != st->codecpar->codec_type ||
     865           4 :         old_codec_id   != st->codecpar->codec_id   ||
     866           2 :         old_codec_tag  != st->codecpar->codec_tag)
     867          47 :         st->internal->need_context_update = 1;
     868             : 
     869          47 :     return 0;
     870             : }
     871             : 
     872       38328 : static void reset_pes_packet_state(PESContext *pes)
     873             : {
     874       38328 :     pes->pts        = AV_NOPTS_VALUE;
     875       38328 :     pes->dts        = AV_NOPTS_VALUE;
     876       38328 :     pes->data_index = 0;
     877       38328 :     pes->flags      = 0;
     878       38328 :     av_buffer_unref(&pes->buffer);
     879       38328 : }
     880             : 
     881           0 : static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
     882             : {
     883           0 :     av_init_packet(pkt);
     884           0 :     pkt->data = (uint8_t *)buffer;
     885           0 :     pkt->size = len;
     886           0 : }
     887             : 
     888       19749 : static int new_pes_packet(PESContext *pes, AVPacket *pkt)
     889             : {
     890             :     char *sd;
     891             : 
     892       19749 :     av_init_packet(pkt);
     893             : 
     894       19749 :     pkt->buf  = pes->buffer;
     895       19749 :     pkt->data = pes->buffer->data;
     896       19749 :     pkt->size = pes->data_index;
     897             : 
     898       37661 :     if (pes->total_size != MAX_PES_PAYLOAD &&
     899       17912 :         pes->pes_header_size + pes->data_index != pes->total_size +
     900             :         PES_START_SIZE) {
     901          39 :         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
     902          39 :         pes->flags |= AV_PKT_FLAG_CORRUPT;
     903             :     }
     904       19749 :     memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
     905             : 
     906             :     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
     907       19749 :     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
     908           0 :         pkt->stream_index = pes->sub_st->index;
     909             :     else
     910       19749 :         pkt->stream_index = pes->st->index;
     911       19749 :     pkt->pts = pes->pts;
     912       19749 :     pkt->dts = pes->dts;
     913             :     /* store position of first TS packet of this PES packet */
     914       19749 :     pkt->pos   = pes->ts_packet_pos;
     915       19749 :     pkt->flags = pes->flags;
     916             : 
     917       19749 :     pes->buffer = NULL;
     918       19749 :     reset_pes_packet_state(pes);
     919             : 
     920       19749 :     sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
     921       19749 :     if (!sd)
     922           0 :         return AVERROR(ENOMEM);
     923       19749 :     *sd = pes->stream_id;
     924             : 
     925       19749 :     return 0;
     926             : }
     927             : 
     928           0 : static uint64_t get_ts64(GetBitContext *gb, int bits)
     929             : {
     930           0 :     if (get_bits_left(gb) < bits)
     931           0 :         return AV_NOPTS_VALUE;
     932           0 :     return get_bits64(gb, bits);
     933             : }
     934             : 
     935           0 : static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
     936             :                           const uint8_t *buf, int buf_size)
     937             : {
     938             :     GetBitContext gb;
     939           0 :     int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
     940           0 :     int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
     941           0 :     int dts_flag = -1, cts_flag = -1;
     942           0 :     int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
     943             :     uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
     944           0 :     int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
     945             : 
     946           0 :     memcpy(buf_padded, buf, buf_padded_size);
     947             : 
     948           0 :     init_get_bits(&gb, buf_padded, buf_padded_size * 8);
     949             : 
     950           0 :     if (sl->use_au_start)
     951           0 :         au_start_flag = get_bits1(&gb);
     952           0 :     if (sl->use_au_end)
     953           0 :         au_end_flag = get_bits1(&gb);
     954           0 :     if (!sl->use_au_start && !sl->use_au_end)
     955           0 :         au_start_flag = au_end_flag = 1;
     956           0 :     if (sl->ocr_len > 0)
     957           0 :         ocr_flag = get_bits1(&gb);
     958           0 :     if (sl->use_idle)
     959           0 :         idle_flag = get_bits1(&gb);
     960           0 :     if (sl->use_padding)
     961           0 :         padding_flag = get_bits1(&gb);
     962           0 :     if (padding_flag)
     963           0 :         padding_bits = get_bits(&gb, 3);
     964             : 
     965           0 :     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
     966           0 :         if (sl->packet_seq_num_len)
     967           0 :             skip_bits_long(&gb, sl->packet_seq_num_len);
     968           0 :         if (sl->degr_prior_len)
     969           0 :             if (get_bits1(&gb))
     970           0 :                 skip_bits(&gb, sl->degr_prior_len);
     971           0 :         if (ocr_flag)
     972           0 :             skip_bits_long(&gb, sl->ocr_len);
     973           0 :         if (au_start_flag) {
     974           0 :             if (sl->use_rand_acc_pt)
     975           0 :                 get_bits1(&gb);
     976           0 :             if (sl->au_seq_num_len > 0)
     977           0 :                 skip_bits_long(&gb, sl->au_seq_num_len);
     978           0 :             if (sl->use_timestamps) {
     979           0 :                 dts_flag = get_bits1(&gb);
     980           0 :                 cts_flag = get_bits1(&gb);
     981             :             }
     982             :         }
     983           0 :         if (sl->inst_bitrate_len)
     984           0 :             inst_bitrate_flag = get_bits1(&gb);
     985           0 :         if (dts_flag == 1)
     986           0 :             dts = get_ts64(&gb, sl->timestamp_len);
     987           0 :         if (cts_flag == 1)
     988           0 :             cts = get_ts64(&gb, sl->timestamp_len);
     989           0 :         if (sl->au_len > 0)
     990           0 :             skip_bits_long(&gb, sl->au_len);
     991           0 :         if (inst_bitrate_flag)
     992           0 :             skip_bits_long(&gb, sl->inst_bitrate_len);
     993             :     }
     994             : 
     995           0 :     if (dts != AV_NOPTS_VALUE)
     996           0 :         pes->dts = dts;
     997           0 :     if (cts != AV_NOPTS_VALUE)
     998           0 :         pes->pts = cts;
     999             : 
    1000           0 :     if (sl->timestamp_len && sl->timestamp_res)
    1001           0 :         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
    1002             : 
    1003           0 :     return (get_bits_count(&gb) + 7) >> 3;
    1004             : }
    1005             : 
    1006             : /* return non zero if a packet could be constructed */
    1007      250998 : static int mpegts_push_data(MpegTSFilter *filter,
    1008             :                             const uint8_t *buf, int buf_size, int is_start,
    1009             :                             int64_t pos)
    1010             : {
    1011      250998 :     PESContext *pes   = filter->u.pes_filter.opaque;
    1012      250998 :     MpegTSContext *ts = pes->ts;
    1013             :     const uint8_t *p;
    1014             :     int ret, len, code;
    1015             : 
    1016      250998 :     if (!ts->pkt)
    1017           0 :         return 0;
    1018             : 
    1019      250998 :     if (is_start) {
    1020       20375 :         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
    1021        1796 :             ret = new_pes_packet(pes, ts->pkt);
    1022        1796 :             if (ret < 0)
    1023           0 :                 return ret;
    1024        1796 :             ts->stop_parse = 1;
    1025             :         } else {
    1026       18579 :             reset_pes_packet_state(pes);
    1027             :         }
    1028       20375 :         pes->state         = MPEGTS_HEADER;
    1029       20375 :         pes->ts_packet_pos = pos;
    1030             :     }
    1031      250998 :     p = buf;
    1032      813018 :     while (buf_size > 0) {
    1033      311022 :         switch (pes->state) {
    1034       20375 :         case MPEGTS_HEADER:
    1035       20375 :             len = PES_START_SIZE - pes->data_index;
    1036       20375 :             if (len > buf_size)
    1037           1 :                 len = buf_size;
    1038       20375 :             memcpy(pes->header + pes->data_index, p, len);
    1039       20375 :             pes->data_index += len;
    1040       20375 :             p += len;
    1041       20375 :             buf_size -= len;
    1042       20375 :             if (pes->data_index == PES_START_SIZE) {
    1043             :                 /* we got all the PES or section header. We can now
    1044             :                  * decide */
    1045       40742 :                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
    1046       20368 :                     pes->header[2] == 0x01) {
    1047             :                     /* it must be an MPEG-2 PES stream */
    1048       20368 :                     code = pes->header[3] | 0x100;
    1049       20368 :                     av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
    1050             :                             code);
    1051       20368 :                     pes->stream_id = pes->header[3];
    1052             : 
    1053       20911 :                     if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
    1054         543 :                          (!pes->sub_st ||
    1055       19825 :                           pes->sub_st->discard == AVDISCARD_ALL)) ||
    1056             :                         code == 0x1be) /* padding_stream */
    1057             :                         goto skip;
    1058             : 
    1059             :                     /* stream not present in PMT */
    1060       19825 :                     if (!pes->st) {
    1061           0 :                         if (ts->skip_changes)
    1062           0 :                             goto skip;
    1063             : 
    1064           0 :                         pes->st = avformat_new_stream(ts->stream, NULL);
    1065           0 :                         if (!pes->st)
    1066           0 :                             return AVERROR(ENOMEM);
    1067           0 :                         pes->st->id = pes->pid;
    1068           0 :                         mpegts_set_stream_info(pes->st, pes, 0, 0);
    1069             :                     }
    1070             : 
    1071       19825 :                     pes->total_size = AV_RB16(pes->header + 4);
    1072             :                     /* NOTE: a zero total size means the PES size is
    1073             :                      * unbounded */
    1074       19825 :                     if (!pes->total_size)
    1075        1913 :                         pes->total_size = MAX_PES_PAYLOAD;
    1076             : 
    1077             :                     /* allocate pes buffer */
    1078       19825 :                     pes->buffer = av_buffer_alloc(pes->total_size +
    1079             :                                                   AV_INPUT_BUFFER_PADDING_SIZE);
    1080       19825 :                     if (!pes->buffer)
    1081           0 :                         return AVERROR(ENOMEM);
    1082             : 
    1083       39650 :                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
    1084       19825 :                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
    1085       19825 :                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
    1086             :                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
    1087       19825 :                         pes->state = MPEGTS_PESHEADER;
    1088       39650 :                         if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
    1089           2 :                             av_log(pes->stream, AV_LOG_TRACE,
    1090             :                                     "pid=%x stream_type=%x probing\n",
    1091             :                                     pes->pid,
    1092             :                                     pes->stream_type);
    1093           2 :                             pes->st->request_probe = 1;
    1094             :                         }
    1095             :                     } else {
    1096           0 :                         pes->pes_header_size = 6;
    1097           0 :                         pes->state      = MPEGTS_PAYLOAD;
    1098           0 :                         pes->data_index = 0;
    1099             :                     }
    1100             :                 } else {
    1101             :                     /* otherwise, it should be a table */
    1102             :                     /* skip packet */
    1103         549 : skip:
    1104         549 :                     pes->state = MPEGTS_SKIP;
    1105         549 :                     continue;
    1106             :                 }
    1107             :             }
    1108       19826 :             break;
    1109             :         /**********************************************/
    1110             :         /* PES packing parsing */
    1111       19825 :         case MPEGTS_PESHEADER:
    1112       19825 :             len = PES_HEADER_SIZE - pes->data_index;
    1113       19825 :             if (len < 0)
    1114           0 :                 return AVERROR_INVALIDDATA;
    1115       19825 :             if (len > buf_size)
    1116           0 :                 len = buf_size;
    1117       19825 :             memcpy(pes->header + pes->data_index, p, len);
    1118       19825 :             pes->data_index += len;
    1119       19825 :             p += len;
    1120       19825 :             buf_size -= len;
    1121       19825 :             if (pes->data_index == PES_HEADER_SIZE) {
    1122       19825 :                 pes->pes_header_size = pes->header[8] + 9;
    1123       19825 :                 pes->state           = MPEGTS_PESHEADER_FILL;
    1124             :             }
    1125       19825 :             break;
    1126       19825 :         case MPEGTS_PESHEADER_FILL:
    1127       19825 :             len = pes->pes_header_size - pes->data_index;
    1128       19825 :             if (len < 0)
    1129           0 :                 return AVERROR_INVALIDDATA;
    1130       19825 :             if (len > buf_size)
    1131           0 :                 len = buf_size;
    1132       19825 :             memcpy(pes->header + pes->data_index, p, len);
    1133       19825 :             pes->data_index += len;
    1134       19825 :             p += len;
    1135       19825 :             buf_size -= len;
    1136       19825 :             if (pes->data_index == pes->pes_header_size) {
    1137             :                 const uint8_t *r;
    1138             :                 unsigned int flags, pes_ext, skip;
    1139             : 
    1140       19825 :                 flags = pes->header[7];
    1141       19825 :                 r = pes->header + 9;
    1142       19825 :                 pes->pts = AV_NOPTS_VALUE;
    1143       19825 :                 pes->dts = AV_NOPTS_VALUE;
    1144       19825 :                 if ((flags & 0xc0) == 0x80) {
    1145        6134 :                     pes->dts = pes->pts = ff_parse_pes_pts(r);
    1146        6134 :                     r += 5;
    1147       13691 :                 } else if ((flags & 0xc0) == 0xc0) {
    1148        1329 :                     pes->pts = ff_parse_pes_pts(r);
    1149        1329 :                     r += 5;
    1150        1329 :                     pes->dts = ff_parse_pes_pts(r);
    1151        1329 :                     r += 5;
    1152             :                 }
    1153       19825 :                 pes->extended_stream_id = -1;
    1154       19825 :                 if (flags & 0x01) { /* PES extension */
    1155           0 :                     pes_ext = *r++;
    1156             :                     /* Skip PES private data, program packet sequence counter and P-STD buffer */
    1157           0 :                     skip  = (pes_ext >> 4) & 0xb;
    1158           0 :                     skip += skip & 0x9;
    1159           0 :                     r    += skip;
    1160           0 :                     if ((pes_ext & 0x41) == 0x01 &&
    1161           0 :                         (r + 2) <= (pes->header + pes->pes_header_size)) {
    1162             :                         /* PES extension 2 */
    1163           0 :                         if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
    1164           0 :                             pes->extended_stream_id = r[1];
    1165             :                     }
    1166             :                 }
    1167             : 
    1168             :                 /* we got the full header. We parse it and get the payload */
    1169       19825 :                 pes->state = MPEGTS_PAYLOAD;
    1170       19825 :                 pes->data_index = 0;
    1171       19825 :                 if (pes->stream_type == 0x12 && buf_size > 0) {
    1172           0 :                     int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
    1173             :                                                          buf_size);
    1174           0 :                     pes->pes_header_size += sl_header_bytes;
    1175           0 :                     p += sl_header_bytes;
    1176           0 :                     buf_size -= sl_header_bytes;
    1177             :                 }
    1178       19825 :                 if (pes->stream_type == 0x15 && buf_size >= 5) {
    1179             :                     /* skip metadata access unit header */
    1180           0 :                     pes->pes_header_size += 5;
    1181           0 :                     p += 5;
    1182           0 :                     buf_size -= 5;
    1183             :                 }
    1184       19825 :                 if (   pes->ts->fix_teletext_pts
    1185       19825 :                     && (   pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
    1186       19825 :                         || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
    1187             :                     ) {
    1188           0 :                     AVProgram *p = NULL;
    1189           0 :                     while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
    1190           0 :                         if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
    1191           0 :                             MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
    1192           0 :                             if (f) {
    1193           0 :                                 AVStream *st = NULL;
    1194           0 :                                 if (f->type == MPEGTS_PES) {
    1195           0 :                                     PESContext *pcrpes = f->u.pes_filter.opaque;
    1196           0 :                                     if (pcrpes)
    1197           0 :                                         st = pcrpes->st;
    1198           0 :                                 } else if (f->type == MPEGTS_PCR) {
    1199             :                                     int i;
    1200           0 :                                     for (i = 0; i < p->nb_stream_indexes; i++) {
    1201           0 :                                         AVStream *pst = pes->stream->streams[p->stream_index[i]];
    1202           0 :                                         if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
    1203           0 :                                             st = pst;
    1204             :                                     }
    1205             :                                 }
    1206           0 :                                 if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
    1207             :                                     // teletext packets do not always have correct timestamps,
    1208             :                                     // the standard says they should be handled after 40.6 ms at most,
    1209             :                                     // and the pcr error to this packet should be no more than 100 ms.
    1210             :                                     // TODO: we should interpolate the PCR, not just use the last one
    1211           0 :                                     int64_t pcr = f->last_pcr / 300;
    1212           0 :                                     pes->st->pts_wrap_reference = st->pts_wrap_reference;
    1213           0 :                                     pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
    1214           0 :                                     if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
    1215           0 :                                         pes->pts = pes->dts = pcr;
    1216           0 :                                     } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
    1217           0 :                                                pes->dts > pcr + 3654 + 9000) {
    1218           0 :                                         pes->pts = pes->dts = pcr + 3654 + 9000;
    1219           0 :                                     } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
    1220           0 :                                                pes->dts > pcr + 10*90000) { //10sec
    1221           0 :                                         pes->pts = pes->dts = pcr + 3654 + 9000;
    1222             :                                     }
    1223           0 :                                     break;
    1224             :                                 }
    1225             :                             }
    1226             :                         }
    1227             :                     }
    1228             :                 }
    1229             :             }
    1230       19825 :             break;
    1231      244822 :         case MPEGTS_PAYLOAD:
    1232      244822 :             if (pes->buffer) {
    1233      469819 :                 if (pes->data_index > 0 &&
    1234      224997 :                     pes->data_index + buf_size > pes->total_size) {
    1235           0 :                     ret = new_pes_packet(pes, ts->pkt);
    1236           0 :                     if (ret < 0)
    1237           0 :                         return ret;
    1238           0 :                     pes->total_size = MAX_PES_PAYLOAD;
    1239           0 :                     pes->buffer = av_buffer_alloc(pes->total_size +
    1240             :                                                   AV_INPUT_BUFFER_PADDING_SIZE);
    1241           0 :                     if (!pes->buffer)
    1242           0 :                         return AVERROR(ENOMEM);
    1243           0 :                     ts->stop_parse = 1;
    1244      264647 :                 } else if (pes->data_index == 0 &&
    1245       19825 :                            buf_size > pes->total_size) {
    1246             :                     // pes packet size is < ts size packet and pes data is padded with 0xff
    1247             :                     // not sure if this is legal in ts but see issue #2392
    1248           0 :                     buf_size = pes->total_size;
    1249             :                 }
    1250      244822 :                 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
    1251      244822 :                 pes->data_index += buf_size;
    1252             :                 /* emit complete packets with known packet size
    1253             :                  * decreases demuxer delay for infrequent packets like subtitles from
    1254             :                  * a couple of seconds to milliseconds for properly muxed files.
    1255             :                  * total_size is the number of bytes following pes_packet_length
    1256             :                  * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
    1257      376599 :                 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
    1258      131777 :                     pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
    1259       17873 :                     ts->stop_parse = 1;
    1260       17873 :                     ret = new_pes_packet(pes, ts->pkt);
    1261       17873 :                     if (ret < 0)
    1262           0 :                         return ret;
    1263             :                 }
    1264             :             }
    1265      244822 :             buf_size = 0;
    1266      244822 :             break;
    1267        6175 :         case MPEGTS_SKIP:
    1268        6175 :             buf_size = 0;
    1269        6175 :             break;
    1270             :         }
    1271             :     }
    1272             : 
    1273      250998 :     return 0;
    1274             : }
    1275             : 
    1276          59 : static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
    1277             : {
    1278             :     MpegTSFilter *tss;
    1279             :     PESContext *pes;
    1280             : 
    1281             :     /* if no pid found, then add a pid context */
    1282          59 :     pes = av_mallocz(sizeof(PESContext));
    1283          59 :     if (!pes)
    1284           0 :         return 0;
    1285          59 :     pes->ts      = ts;
    1286          59 :     pes->stream  = ts->stream;
    1287          59 :     pes->pid     = pid;
    1288          59 :     pes->pcr_pid = pcr_pid;
    1289          59 :     pes->state   = MPEGTS_SKIP;
    1290          59 :     pes->pts     = AV_NOPTS_VALUE;
    1291          59 :     pes->dts     = AV_NOPTS_VALUE;
    1292          59 :     tss          = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
    1293          59 :     if (!tss) {
    1294           0 :         av_free(pes);
    1295           0 :         return 0;
    1296             :     }
    1297          59 :     return pes;
    1298             : }
    1299             : 
    1300             : #define MAX_LEVEL 4
    1301             : typedef struct MP4DescrParseContext {
    1302             :     AVFormatContext *s;
    1303             :     AVIOContext pb;
    1304             :     Mp4Descr *descr;
    1305             :     Mp4Descr *active_descr;
    1306             :     int descr_count;
    1307             :     int max_descr_count;
    1308             :     int level;
    1309             :     int predefined_SLConfigDescriptor_seen;
    1310             : } MP4DescrParseContext;
    1311             : 
    1312           0 : static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
    1313             :                                      const uint8_t *buf, unsigned size,
    1314             :                                      Mp4Descr *descr, int max_descr_count)
    1315             : {
    1316             :     int ret;
    1317           0 :     if (size > (1 << 30))
    1318           0 :         return AVERROR_INVALIDDATA;
    1319             : 
    1320           0 :     if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
    1321             :                                  NULL, NULL, NULL, NULL)) < 0)
    1322           0 :         return ret;
    1323             : 
    1324           0 :     d->s               = s;
    1325           0 :     d->level           = 0;
    1326           0 :     d->descr_count     = 0;
    1327           0 :     d->descr           = descr;
    1328           0 :     d->active_descr    = NULL;
    1329           0 :     d->max_descr_count = max_descr_count;
    1330             : 
    1331           0 :     return 0;
    1332             : }
    1333             : 
    1334           0 : static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
    1335             : {
    1336           0 :     int64_t new_off = avio_tell(pb);
    1337           0 :     (*len) -= new_off - *off;
    1338           0 :     *off    = new_off;
    1339           0 : }
    1340             : 
    1341             : static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
    1342             :                            int target_tag);
    1343             : 
    1344           0 : static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
    1345             : {
    1346           0 :     while (len > 0) {
    1347           0 :         int ret = parse_mp4_descr(d, off, len, 0);
    1348           0 :         if (ret < 0)
    1349           0 :             return ret;
    1350           0 :         update_offsets(&d->pb, &off, &len);
    1351             :     }
    1352           0 :     return 0;
    1353             : }
    1354             : 
    1355           0 : static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
    1356             : {
    1357           0 :     avio_rb16(&d->pb); // ID
    1358           0 :     avio_r8(&d->pb);
    1359           0 :     avio_r8(&d->pb);
    1360           0 :     avio_r8(&d->pb);
    1361           0 :     avio_r8(&d->pb);
    1362           0 :     avio_r8(&d->pb);
    1363           0 :     update_offsets(&d->pb, &off, &len);
    1364           0 :     return parse_mp4_descr_arr(d, off, len);
    1365             : }
    1366             : 
    1367           0 : static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
    1368             : {
    1369             :     int id_flags;
    1370           0 :     if (len < 2)
    1371           0 :         return 0;
    1372           0 :     id_flags = avio_rb16(&d->pb);
    1373           0 :     if (!(id_flags & 0x0020)) { // URL_Flag
    1374           0 :         update_offsets(&d->pb, &off, &len);
    1375           0 :         return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
    1376             :     } else {
    1377           0 :         return 0;
    1378             :     }
    1379             : }
    1380             : 
    1381           0 : static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
    1382             : {
    1383           0 :     int es_id = 0;
    1384           0 :     int ret   = 0;
    1385             : 
    1386           0 :     if (d->descr_count >= d->max_descr_count)
    1387           0 :         return AVERROR_INVALIDDATA;
    1388           0 :     ff_mp4_parse_es_descr(&d->pb, &es_id);
    1389           0 :     d->active_descr = d->descr + (d->descr_count++);
    1390             : 
    1391           0 :     d->active_descr->es_id = es_id;
    1392           0 :     update_offsets(&d->pb, &off, &len);
    1393           0 :     if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
    1394           0 :         return ret;
    1395           0 :     update_offsets(&d->pb, &off, &len);
    1396           0 :     if (len > 0)
    1397           0 :         ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
    1398           0 :     d->active_descr = NULL;
    1399           0 :     return ret;
    1400             : }
    1401             : 
    1402           0 : static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
    1403             :                                       int len)
    1404             : {
    1405           0 :     Mp4Descr *descr = d->active_descr;
    1406           0 :     if (!descr)
    1407           0 :         return AVERROR_INVALIDDATA;
    1408           0 :     d->active_descr->dec_config_descr = av_malloc(len);
    1409           0 :     if (!descr->dec_config_descr)
    1410           0 :         return AVERROR(ENOMEM);
    1411           0 :     descr->dec_config_descr_len = len;
    1412           0 :     avio_read(&d->pb, descr->dec_config_descr, len);
    1413           0 :     return 0;
    1414             : }
    1415             : 
    1416           0 : static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
    1417             : {
    1418           0 :     Mp4Descr *descr = d->active_descr;
    1419             :     int predefined;
    1420           0 :     if (!descr)
    1421           0 :         return AVERROR_INVALIDDATA;
    1422             : 
    1423             : #define R8_CHECK_CLIP_MAX(dst, maxv) do {                       \
    1424             :     descr->sl.dst = avio_r8(&d->pb);                            \
    1425             :     if (descr->sl.dst > maxv) {                                 \
    1426             :         descr->sl.dst = maxv;                                   \
    1427             :         return AVERROR_INVALIDDATA;                             \
    1428             :     }                                                           \
    1429             : } while (0)
    1430             : 
    1431           0 :     predefined = avio_r8(&d->pb);
    1432           0 :     if (!predefined) {
    1433             :         int lengths;
    1434           0 :         int flags = avio_r8(&d->pb);
    1435           0 :         descr->sl.use_au_start    = !!(flags & 0x80);
    1436           0 :         descr->sl.use_au_end      = !!(flags & 0x40);
    1437           0 :         descr->sl.use_rand_acc_pt = !!(flags & 0x20);
    1438           0 :         descr->sl.use_padding     = !!(flags & 0x08);
    1439           0 :         descr->sl.use_timestamps  = !!(flags & 0x04);
    1440           0 :         descr->sl.use_idle        = !!(flags & 0x02);
    1441           0 :         descr->sl.timestamp_res   = avio_rb32(&d->pb);
    1442           0 :         avio_rb32(&d->pb);
    1443           0 :         R8_CHECK_CLIP_MAX(timestamp_len, 63);
    1444           0 :         R8_CHECK_CLIP_MAX(ocr_len,       63);
    1445           0 :         R8_CHECK_CLIP_MAX(au_len,        31);
    1446           0 :         descr->sl.inst_bitrate_len   = avio_r8(&d->pb);
    1447           0 :         lengths                      = avio_rb16(&d->pb);
    1448           0 :         descr->sl.degr_prior_len     = lengths >> 12;
    1449           0 :         descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
    1450           0 :         descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
    1451           0 :     } else if (!d->predefined_SLConfigDescriptor_seen){
    1452           0 :         avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
    1453           0 :         d->predefined_SLConfigDescriptor_seen = 1;
    1454             :     }
    1455           0 :     return 0;
    1456             : }
    1457             : 
    1458           0 : static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
    1459             :                            int target_tag)
    1460             : {
    1461             :     int tag;
    1462           0 :     int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
    1463           0 :     int ret = 0;
    1464             : 
    1465           0 :     update_offsets(&d->pb, &off, &len);
    1466           0 :     if (len < 0 || len1 > len || len1 <= 0) {
    1467           0 :         av_log(d->s, AV_LOG_ERROR,
    1468             :                "Tag %x length violation new length %d bytes remaining %d\n",
    1469             :                tag, len1, len);
    1470           0 :         return AVERROR_INVALIDDATA;
    1471             :     }
    1472             : 
    1473           0 :     if (d->level++ >= MAX_LEVEL) {
    1474           0 :         av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
    1475           0 :         ret = AVERROR_INVALIDDATA;
    1476           0 :         goto done;
    1477             :     }
    1478             : 
    1479           0 :     if (target_tag && tag != target_tag) {
    1480           0 :         av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
    1481             :                target_tag);
    1482           0 :         ret = AVERROR_INVALIDDATA;
    1483           0 :         goto done;
    1484             :     }
    1485             : 
    1486           0 :     switch (tag) {
    1487           0 :     case MP4IODescrTag:
    1488           0 :         ret = parse_MP4IODescrTag(d, off, len1);
    1489           0 :         break;
    1490           0 :     case MP4ODescrTag:
    1491           0 :         ret = parse_MP4ODescrTag(d, off, len1);
    1492           0 :         break;
    1493           0 :     case MP4ESDescrTag:
    1494           0 :         ret = parse_MP4ESDescrTag(d, off, len1);
    1495           0 :         break;
    1496           0 :     case MP4DecConfigDescrTag:
    1497           0 :         ret = parse_MP4DecConfigDescrTag(d, off, len1);
    1498           0 :         break;
    1499           0 :     case MP4SLDescrTag:
    1500           0 :         ret = parse_MP4SLDescrTag(d, off, len1);
    1501           0 :         break;
    1502             :     }
    1503             : 
    1504             : 
    1505           0 : done:
    1506           0 :     d->level--;
    1507           0 :     avio_seek(&d->pb, off + len1, SEEK_SET);
    1508           0 :     return ret;
    1509             : }
    1510             : 
    1511           0 : static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
    1512             :                          Mp4Descr *descr, int *descr_count, int max_descr_count)
    1513             : {
    1514             :     MP4DescrParseContext d;
    1515             :     int ret;
    1516             : 
    1517           0 :     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
    1518           0 :     if (ret < 0)
    1519           0 :         return ret;
    1520             : 
    1521           0 :     ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
    1522             : 
    1523           0 :     *descr_count = d.descr_count;
    1524           0 :     return ret;
    1525             : }
    1526             : 
    1527           0 : static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
    1528             :                        Mp4Descr *descr, int *descr_count, int max_descr_count)
    1529             : {
    1530             :     MP4DescrParseContext d;
    1531             :     int ret;
    1532             : 
    1533           0 :     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
    1534           0 :     if (ret < 0)
    1535           0 :         return ret;
    1536             : 
    1537           0 :     ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
    1538             : 
    1539           0 :     *descr_count = d.descr_count;
    1540           0 :     return ret;
    1541             : }
    1542             : 
    1543           0 : static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
    1544             :                     int section_len)
    1545             : {
    1546           0 :     MpegTSContext *ts = filter->u.section_filter.opaque;
    1547           0 :     MpegTSSectionFilter *tssf = &filter->u.section_filter;
    1548             :     SectionHeader h;
    1549             :     const uint8_t *p, *p_end;
    1550             :     AVIOContext pb;
    1551           0 :     int mp4_descr_count = 0;
    1552           0 :     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
    1553             :     int i, pid;
    1554           0 :     AVFormatContext *s = ts->stream;
    1555             : 
    1556           0 :     p_end = section + section_len - 4;
    1557           0 :     p = section;
    1558           0 :     if (parse_section_header(&h, &p, p_end) < 0)
    1559           0 :         return;
    1560           0 :     if (h.tid != M4OD_TID)
    1561           0 :         return;
    1562           0 :     if (skip_identical(&h, tssf))
    1563           0 :         return;
    1564             : 
    1565           0 :     mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
    1566             :                 MAX_MP4_DESCR_COUNT);
    1567             : 
    1568           0 :     for (pid = 0; pid < NB_PID_MAX; pid++) {
    1569           0 :         if (!ts->pids[pid])
    1570           0 :             continue;
    1571           0 :         for (i = 0; i < mp4_descr_count; i++) {
    1572             :             PESContext *pes;
    1573             :             AVStream *st;
    1574           0 :             if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
    1575           0 :                 continue;
    1576           0 :             if (ts->pids[pid]->type != MPEGTS_PES) {
    1577           0 :                 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
    1578           0 :                 continue;
    1579             :             }
    1580           0 :             pes = ts->pids[pid]->u.pes_filter.opaque;
    1581           0 :             st  = pes->st;
    1582           0 :             if (!st)
    1583           0 :                 continue;
    1584             : 
    1585           0 :             pes->sl = mp4_descr[i].sl;
    1586             : 
    1587           0 :             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
    1588             :                               mp4_descr[i].dec_config_descr_len, 0,
    1589             :                               NULL, NULL, NULL, NULL);
    1590           0 :             ff_mp4_read_dec_config_descr(s, st, &pb);
    1591           0 :             if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
    1592           0 :                 st->codecpar->extradata_size > 0)
    1593           0 :                 st->need_parsing = 0;
    1594           0 :             if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
    1595           0 :                 st->codecpar->extradata_size > 0)
    1596           0 :                 st->need_parsing = 0;
    1597             : 
    1598           0 :             st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
    1599           0 :             st->internal->need_context_update = 1;
    1600             :         }
    1601             :     }
    1602           0 :     for (i = 0; i < mp4_descr_count; i++)
    1603           0 :         av_free(mp4_descr[i].dec_config_descr);
    1604             : }
    1605             : 
    1606           0 : static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
    1607             :                     int section_len)
    1608             : {
    1609           0 :     AVProgram *prg = NULL;
    1610           0 :     MpegTSContext *ts = filter->u.section_filter.opaque;
    1611             : 
    1612           0 :     int idx = ff_find_stream_index(ts->stream, filter->pid);
    1613           0 :     if (idx < 0)
    1614           0 :         return;
    1615             : 
    1616           0 :     new_data_packet(section, section_len, ts->pkt);
    1617           0 :     ts->pkt->stream_index = idx;
    1618           0 :     prg = av_find_program_from_stream(ts->stream, NULL, idx);
    1619           0 :     if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
    1620           0 :         MpegTSFilter *f = ts->pids[prg->pcr_pid];
    1621           0 :         if (f && f->last_pcr != -1)
    1622           0 :             ts->pkt->pts = ts->pkt->dts = f->last_pcr/300;
    1623             :     }
    1624           0 :     ts->stop_parse = 1;
    1625             : 
    1626             : }
    1627             : 
    1628             : static const uint8_t opus_coupled_stream_cnt[9] = {
    1629             :     1, 0, 1, 1, 2, 2, 2, 3, 3
    1630             : };
    1631             : 
    1632             : static const uint8_t opus_stream_cnt[9] = {
    1633             :     1, 1, 1, 2, 2, 3, 4, 4, 5,
    1634             : };
    1635             : 
    1636             : static const uint8_t opus_channel_map[8][8] = {
    1637             :     { 0 },
    1638             :     { 0,1 },
    1639             :     { 0,2,1 },
    1640             :     { 0,1,2,3 },
    1641             :     { 0,4,1,2,3 },
    1642             :     { 0,4,1,2,3,5 },
    1643             :     { 0,4,1,2,3,5,6 },
    1644             :     { 0,6,1,2,3,4,5,7 },
    1645             : };
    1646             : 
    1647         469 : int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
    1648             :                               const uint8_t **pp, const uint8_t *desc_list_end,
    1649             :                               Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
    1650             :                               MpegTSContext *ts)
    1651             : {
    1652             :     const uint8_t *desc_end;
    1653             :     int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
    1654             :     char language[252];
    1655             :     int i;
    1656             : 
    1657         469 :     desc_tag = get8(pp, desc_list_end);
    1658         469 :     if (desc_tag < 0)
    1659         357 :         return AVERROR_INVALIDDATA;
    1660         112 :     desc_len = get8(pp, desc_list_end);
    1661         112 :     if (desc_len < 0)
    1662           0 :         return AVERROR_INVALIDDATA;
    1663         112 :     desc_end = *pp + desc_len;
    1664         112 :     if (desc_end > desc_list_end)
    1665           0 :         return AVERROR_INVALIDDATA;
    1666             : 
    1667         112 :     av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
    1668             : 
    1669         112 :     if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
    1670             :         stream_type == STREAM_TYPE_PRIVATE_DATA)
    1671           6 :         mpegts_find_stream_type(st, desc_tag, DESC_types);
    1672             : 
    1673         112 :     switch (desc_tag) {
    1674           0 :     case 0x1E: /* SL descriptor */
    1675           0 :         desc_es_id = get16(pp, desc_end);
    1676           0 :         if (desc_es_id < 0)
    1677           0 :             break;
    1678           0 :         if (ts && ts->pids[pid])
    1679           0 :             ts->pids[pid]->es_id = desc_es_id;
    1680           0 :         for (i = 0; i < mp4_descr_count; i++)
    1681           0 :             if (mp4_descr[i].dec_config_descr_len &&
    1682           0 :                 mp4_descr[i].es_id == desc_es_id) {
    1683             :                 AVIOContext pb;
    1684           0 :                 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
    1685           0 :                                   mp4_descr[i].dec_config_descr_len, 0,
    1686             :                                   NULL, NULL, NULL, NULL);
    1687           0 :                 ff_mp4_read_dec_config_descr(fc, st, &pb);
    1688           0 :                 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
    1689           0 :                     st->codecpar->extradata_size > 0) {
    1690           0 :                     st->need_parsing = 0;
    1691           0 :                     st->internal->need_context_update = 1;
    1692             :                 }
    1693           0 :                 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
    1694           0 :                     mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
    1695             :             }
    1696           0 :         break;
    1697           0 :     case 0x1F: /* FMC descriptor */
    1698           0 :         if (get16(pp, desc_end) < 0)
    1699           0 :             break;
    1700           0 :         if (mp4_descr_count > 0 &&
    1701           0 :             (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
    1702           0 :              (st->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
    1703           0 :              st->request_probe > 0) &&
    1704           0 :             mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
    1705             :             AVIOContext pb;
    1706           0 :             ffio_init_context(&pb, mp4_descr->dec_config_descr,
    1707             :                               mp4_descr->dec_config_descr_len, 0,
    1708             :                               NULL, NULL, NULL, NULL);
    1709           0 :             ff_mp4_read_dec_config_descr(fc, st, &pb);
    1710           0 :             if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
    1711           0 :                 st->codecpar->extradata_size > 0) {
    1712           0 :                 st->request_probe = st->need_parsing = 0;
    1713           0 :                 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
    1714           0 :                 st->internal->need_context_update = 1;
    1715             :             }
    1716             :         }
    1717           0 :         break;
    1718           0 :     case 0x56: /* DVB teletext descriptor */
    1719             :         {
    1720           0 :             uint8_t *extradata = NULL;
    1721           0 :             int language_count = desc_len / 5;
    1722             : 
    1723           0 :             if (desc_len > 0 && desc_len % 5 != 0)
    1724           0 :                 return AVERROR_INVALIDDATA;
    1725             : 
    1726           0 :             if (language_count > 0) {
    1727             :                 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
    1728           0 :                 av_assert0(language_count <= sizeof(language) / 4);
    1729             : 
    1730           0 :                 if (st->codecpar->extradata == NULL) {
    1731           0 :                     if (ff_alloc_extradata(st->codecpar, language_count * 2)) {
    1732           0 :                         return AVERROR(ENOMEM);
    1733             :                     }
    1734             :                 }
    1735             : 
    1736           0 :                if (st->codecpar->extradata_size < language_count * 2)
    1737           0 :                    return AVERROR_INVALIDDATA;
    1738             : 
    1739           0 :                extradata = st->codecpar->extradata;
    1740             : 
    1741           0 :                 for (i = 0; i < language_count; i++) {
    1742           0 :                     language[i * 4 + 0] = get8(pp, desc_end);
    1743           0 :                     language[i * 4 + 1] = get8(pp, desc_end);
    1744           0 :                     language[i * 4 + 2] = get8(pp, desc_end);
    1745           0 :                     language[i * 4 + 3] = ',';
    1746             : 
    1747           0 :                     memcpy(extradata, *pp, 2);
    1748           0 :                     extradata += 2;
    1749             : 
    1750           0 :                     *pp += 2;
    1751             :                 }
    1752             : 
    1753           0 :                 language[i * 4 - 1] = 0;
    1754           0 :                 av_dict_set(&st->metadata, "language", language, 0);
    1755           0 :                 st->internal->need_context_update = 1;
    1756             :             }
    1757             :         }
    1758           0 :         break;
    1759           1 :     case 0x59: /* subtitling descriptor */
    1760             :         {
    1761             :             /* 8 bytes per DVB subtitle substream data:
    1762             :              * ISO_639_language_code (3 bytes),
    1763             :              * subtitling_type (1 byte),
    1764             :              * composition_page_id (2 bytes),
    1765             :              * ancillary_page_id (2 bytes) */
    1766           1 :             int language_count = desc_len / 8;
    1767             : 
    1768           1 :             if (desc_len > 0 && desc_len % 8 != 0)
    1769           0 :                 return AVERROR_INVALIDDATA;
    1770             : 
    1771           1 :             if (language_count > 1) {
    1772           0 :                 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
    1773             :             }
    1774             : 
    1775           1 :             if (language_count > 0) {
    1776             :                 uint8_t *extradata;
    1777             : 
    1778             :                 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
    1779           1 :                 av_assert0(language_count <= sizeof(language) / 4);
    1780             : 
    1781           1 :                 if (st->codecpar->extradata == NULL) {
    1782           1 :                     if (ff_alloc_extradata(st->codecpar, language_count * 5)) {
    1783           0 :                         return AVERROR(ENOMEM);
    1784             :                     }
    1785             :                 }
    1786             : 
    1787           1 :                 if (st->codecpar->extradata_size < language_count * 5)
    1788           0 :                     return AVERROR_INVALIDDATA;
    1789             : 
    1790           1 :                 extradata = st->codecpar->extradata;
    1791             : 
    1792           2 :                 for (i = 0; i < language_count; i++) {
    1793           1 :                     language[i * 4 + 0] = get8(pp, desc_end);
    1794           1 :                     language[i * 4 + 1] = get8(pp, desc_end);
    1795           1 :                     language[i * 4 + 2] = get8(pp, desc_end);
    1796           1 :                     language[i * 4 + 3] = ',';
    1797             : 
    1798             :                     /* hearing impaired subtitles detection using subtitling_type */
    1799           1 :                     switch (*pp[0]) {
    1800           0 :                     case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
    1801             :                     case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
    1802             :                     case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
    1803             :                     case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
    1804             :                     case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
    1805             :                     case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
    1806           0 :                         st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
    1807           0 :                         break;
    1808             :                     }
    1809             : 
    1810           1 :                     extradata[4] = get8(pp, desc_end); /* subtitling_type */
    1811           1 :                     memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
    1812           1 :                     extradata += 5;
    1813             : 
    1814           1 :                     *pp += 4;
    1815             :                 }
    1816             : 
    1817           1 :                 language[i * 4 - 1] = 0;
    1818           1 :                 av_dict_set(&st->metadata, "language", language, 0);
    1819           1 :                 st->internal->need_context_update = 1;
    1820             :             }
    1821             :         }
    1822           1 :         break;
    1823          40 :     case 0x0a: /* ISO 639 language descriptor */
    1824          74 :         for (i = 0; i + 4 <= desc_len; i += 4) {
    1825          34 :             language[i + 0] = get8(pp, desc_end);
    1826          34 :             language[i + 1] = get8(pp, desc_end);
    1827          34 :             language[i + 2] = get8(pp, desc_end);
    1828          34 :             language[i + 3] = ',';
    1829          34 :             switch (get8(pp, desc_end)) {
    1830           0 :             case 0x01:
    1831           0 :                 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
    1832           0 :                 break;
    1833           0 :             case 0x02:
    1834           0 :                 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
    1835           0 :                 break;
    1836           0 :             case 0x03:
    1837           0 :                 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
    1838           0 :                 break;
    1839             :             }
    1840             :         }
    1841          40 :         if (i && language[0]) {
    1842          30 :             language[i - 1] = 0;
    1843          30 :             av_dict_set(&st->metadata, "language", language, 0);
    1844             :         }
    1845          40 :         break;
    1846           8 :     case 0x05: /* registration descriptor */
    1847           8 :         st->codecpar->codec_tag = bytestream_get_le32(pp);
    1848           8 :         av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
    1849           8 :         if (st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) {
    1850           3 :             mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
    1851           3 :             if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
    1852           2 :                 st->request_probe = 50;
    1853             :         }
    1854           8 :         break;
    1855           9 :     case 0x52: /* stream identifier descriptor */
    1856           9 :         st->stream_identifier = 1 + get8(pp, desc_end);
    1857           9 :         break;
    1858           0 :     case 0x26: /* metadata descriptor */
    1859           0 :         if (get16(pp, desc_end) == 0xFFFF)
    1860           0 :             *pp += 4;
    1861           0 :         if (get8(pp, desc_end) == 0xFF) {
    1862           0 :             st->codecpar->codec_tag = bytestream_get_le32(pp);
    1863           0 :             if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
    1864           0 :                 mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
    1865             :         }
    1866           0 :         break;
    1867           4 :     case 0x7f: /* DVB extension descriptor */
    1868           4 :         ext_desc_tag = get8(pp, desc_end);
    1869           4 :         if (ext_desc_tag < 0)
    1870           0 :             return AVERROR_INVALIDDATA;
    1871           4 :         if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
    1872             :             ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
    1873           3 :             if (!st->codecpar->extradata) {
    1874           1 :                 st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
    1875             :                                                      AV_INPUT_BUFFER_PADDING_SIZE);
    1876           1 :                 if (!st->codecpar->extradata)
    1877           0 :                     return AVERROR(ENOMEM);
    1878             : 
    1879           1 :                 st->codecpar->extradata_size = sizeof(opus_default_extradata);
    1880           1 :                 memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
    1881             : 
    1882           1 :                 channel_config_code = get8(pp, desc_end);
    1883           1 :                 if (channel_config_code < 0)
    1884           0 :                     return AVERROR_INVALIDDATA;
    1885           1 :                 if (channel_config_code <= 0x8) {
    1886           1 :                     st->codecpar->extradata[9]  = channels = channel_config_code ? channel_config_code : 2;
    1887           1 :                     st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
    1888           1 :                     st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
    1889           1 :                     st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
    1890           1 :                     memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
    1891             :                 } else {
    1892           0 :                     avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
    1893             :                 }
    1894           1 :                 st->need_parsing = AVSTREAM_PARSE_FULL;
    1895           1 :                 st->internal->need_context_update = 1;
    1896             :             }
    1897             :         }
    1898           4 :         break;
    1899          50 :     default:
    1900          50 :         break;
    1901             :     }
    1902         112 :     *pp = desc_end;
    1903         112 :     return 0;
    1904             : }
    1905             : 
    1906          47 : static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
    1907             : {
    1908          94 :     return !(stream_type == 0x13 ||
    1909           0 :              (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
    1910             : }
    1911             : 
    1912        3300 : static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
    1913             : {
    1914        3300 :     MpegTSContext *ts = filter->u.section_filter.opaque;
    1915        3300 :     MpegTSSectionFilter *tssf = &filter->u.section_filter;
    1916        3300 :     SectionHeader h1, *h = &h1;
    1917             :     PESContext *pes;
    1918             :     AVStream *st;
    1919             :     const uint8_t *p, *p_end, *desc_list_end;
    1920             :     int program_info_length, pcr_pid, pid, stream_type;
    1921             :     int desc_list_len;
    1922        3300 :     uint32_t prog_reg_desc = 0; /* registration descriptor */
    1923             : 
    1924        3300 :     int mp4_descr_count = 0;
    1925        3300 :     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
    1926             :     int i;
    1927             : 
    1928        3300 :     av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
    1929             :     hex_dump_debug(ts->stream, section, section_len);
    1930             : 
    1931        3300 :     p_end = section + section_len - 4;
    1932        3300 :     p = section;
    1933        3300 :     if (parse_section_header(h, &p, p_end) < 0)
    1934        3097 :         return;
    1935        3300 :     if (skip_identical(h, tssf))
    1936        3097 :         return;
    1937             : 
    1938        1015 :     av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
    1939        1015 :             h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
    1940             : 
    1941         203 :     if (h->tid != PMT_TID)
    1942           0 :         return;
    1943         203 :     if (!ts->scan_all_pmts && ts->skip_changes)
    1944           0 :         return;
    1945             : 
    1946         203 :     if (!ts->skip_clear)
    1947         148 :         clear_program(ts, h->id);
    1948             : 
    1949         203 :     pcr_pid = get16(&p, p_end);
    1950         203 :     if (pcr_pid < 0)
    1951           0 :         return;
    1952         203 :     pcr_pid &= 0x1fff;
    1953         203 :     add_pid_to_pmt(ts, h->id, pcr_pid);
    1954         203 :     set_pcr_pid(ts->stream, h->id, pcr_pid);
    1955             : 
    1956         203 :     av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
    1957             : 
    1958         203 :     program_info_length = get16(&p, p_end);
    1959         203 :     if (program_info_length < 0)
    1960           0 :         return;
    1961         203 :     program_info_length &= 0xfff;
    1962         430 :     while (program_info_length >= 2) {
    1963             :         uint8_t tag, len;
    1964          24 :         tag = get8(&p, p_end);
    1965          24 :         len = get8(&p, p_end);
    1966             : 
    1967          24 :         av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
    1968             : 
    1969          24 :         if (len > program_info_length - 2)
    1970             :             // something else is broken, exit the program_descriptors_loop
    1971           0 :             break;
    1972          24 :         program_info_length -= len + 2;
    1973          24 :         if (tag == 0x1d) { // IOD descriptor
    1974           0 :             get8(&p, p_end); // scope
    1975           0 :             get8(&p, p_end); // label
    1976           0 :             len -= 2;
    1977           0 :             mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
    1978             :                           &mp4_descr_count, MAX_MP4_DESCR_COUNT);
    1979          24 :         } else if (tag == 0x05 && len >= 4) { // registration descriptor
    1980           0 :             prog_reg_desc = bytestream_get_le32(&p);
    1981           0 :             len -= 4;
    1982             :         }
    1983          24 :         p += len;
    1984             :     }
    1985         203 :     p += program_info_length;
    1986         203 :     if (p >= p_end)
    1987           0 :         goto out;
    1988             : 
    1989             :     // stop parsing after pmt, we found header
    1990         203 :     if (!ts->stream->nb_streams)
    1991          31 :         ts->stop_parse = 2;
    1992             : 
    1993         203 :     set_pmt_found(ts, h->id);
    1994             : 
    1995             : 
    1996             :     for (;;) {
    1997         917 :         st = 0;
    1998         560 :         pes = NULL;
    1999         560 :         stream_type = get8(&p, p_end);
    2000         560 :         if (stream_type < 0)
    2001         203 :             break;
    2002         357 :         pid = get16(&p, p_end);
    2003         357 :         if (pid < 0)
    2004           0 :             goto out;
    2005         357 :         pid &= 0x1fff;
    2006         357 :         if (pid == ts->current_pid)
    2007           0 :             goto out;
    2008             : 
    2009             :         /* now create stream */
    2010         357 :         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
    2011         310 :             pes = ts->pids[pid]->u.pes_filter.opaque;
    2012         310 :             if (!pes->st) {
    2013           0 :                 pes->st     = avformat_new_stream(pes->stream, NULL);
    2014           0 :                 if (!pes->st)
    2015           0 :                     goto out;
    2016           0 :                 pes->st->id = pes->pid;
    2017             :             }
    2018         310 :             st = pes->st;
    2019          47 :         } else if (is_pes_stream(stream_type, prog_reg_desc)) {
    2020          47 :             if (ts->pids[pid])
    2021           0 :                 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
    2022          47 :             pes = add_pes_stream(ts, pid, pcr_pid);
    2023          47 :             if (pes) {
    2024          47 :                 st = avformat_new_stream(pes->stream, NULL);
    2025          47 :                 if (!st)
    2026           0 :                     goto out;
    2027          47 :                 st->id = pes->pid;
    2028             :             }
    2029             :         } else {
    2030           0 :             int idx = ff_find_stream_index(ts->stream, pid);
    2031           0 :             if (idx >= 0) {
    2032           0 :                 st = ts->stream->streams[idx];
    2033             :             } else {
    2034           0 :                 st = avformat_new_stream(ts->stream, NULL);
    2035           0 :                 if (!st)
    2036           0 :                     goto out;
    2037           0 :                 st->id = pid;
    2038           0 :                 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
    2039           0 :                 if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
    2040           0 :                     mpegts_find_stream_type(st, stream_type, SCTE_types);
    2041           0 :                     mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
    2042             :                 }
    2043             :             }
    2044             :         }
    2045             : 
    2046         357 :         if (!st)
    2047           0 :             goto out;
    2048             : 
    2049         357 :         if (pes && !pes->stream_type)
    2050          47 :             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
    2051             : 
    2052         357 :         add_pid_to_pmt(ts, h->id, pid);
    2053             : 
    2054         357 :         av_program_add_stream_index(ts->stream, h->id, st->index);
    2055             : 
    2056         357 :         desc_list_len = get16(&p, p_end);
    2057         357 :         if (desc_list_len < 0)
    2058           0 :             goto out;
    2059         357 :         desc_list_len &= 0xfff;
    2060         357 :         desc_list_end  = p + desc_list_len;
    2061         357 :         if (desc_list_end > p_end)
    2062           0 :             goto out;
    2063             :         for (;;) {
    2064         573 :             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
    2065             :                                           desc_list_end, mp4_descr,
    2066             :                                           mp4_descr_count, pid, ts) < 0)
    2067         357 :                 break;
    2068             : 
    2069         108 :             if (pes && prog_reg_desc == AV_RL32("HDMV") &&
    2070           0 :                 stream_type == 0x83 && pes->sub_st) {
    2071           0 :                 av_program_add_stream_index(ts->stream, h->id,
    2072           0 :                                             pes->sub_st->index);
    2073           0 :                 pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
    2074             :             }
    2075             :         }
    2076         357 :         p = desc_list_end;
    2077             :     }
    2078             : 
    2079         203 :     if (!ts->pids[pcr_pid])
    2080           0 :         mpegts_open_pcr_filter(ts, pcr_pid);
    2081             : 
    2082         406 : out:
    2083         203 :     for (i = 0; i < mp4_descr_count; i++)
    2084           0 :         av_free(mp4_descr[i].dec_config_descr);
    2085             : }
    2086             : 
    2087        3338 : static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
    2088             : {
    2089        3338 :     MpegTSContext *ts = filter->u.section_filter.opaque;
    2090        3338 :     MpegTSSectionFilter *tssf = &filter->u.section_filter;
    2091        3338 :     SectionHeader h1, *h = &h1;
    2092             :     const uint8_t *p, *p_end;
    2093             :     int sid, pmt_pid;
    2094             :     AVProgram *program;
    2095             : 
    2096        3338 :     av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
    2097             :     hex_dump_debug(ts->stream, section, section_len);
    2098             : 
    2099        3338 :     p_end = section + section_len - 4;
    2100        3338 :     p     = section;
    2101        3338 :     if (parse_section_header(h, &p, p_end) < 0)
    2102        3162 :         return;
    2103        3338 :     if (h->tid != PAT_TID)
    2104           0 :         return;
    2105        3338 :     if (ts->skip_changes)
    2106         483 :         return;
    2107             : 
    2108        2855 :     if (skip_identical(h, tssf))
    2109        2679 :         return;
    2110         176 :     ts->stream->ts_id = h->id;
    2111             : 
    2112         176 :     clear_programs(ts);
    2113             :     for (;;) {
    2114         528 :         sid = get16(&p, p_end);
    2115         352 :         if (sid < 0)
    2116         176 :             break;
    2117         176 :         pmt_pid = get16(&p, p_end);
    2118         176 :         if (pmt_pid < 0)
    2119           0 :             break;
    2120         176 :         pmt_pid &= 0x1fff;
    2121             : 
    2122         176 :         if (pmt_pid == ts->current_pid)
    2123           0 :             break;
    2124             : 
    2125         176 :         av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
    2126             : 
    2127         176 :         if (sid == 0x0000) {
    2128             :             /* NIT info */
    2129             :         } else {
    2130         176 :             MpegTSFilter *fil = ts->pids[pmt_pid];
    2131         176 :             program = av_new_program(ts->stream, sid);
    2132         176 :             if (program) {
    2133         176 :                 program->program_num = sid;
    2134         176 :                 program->pmt_pid = pmt_pid;
    2135             :             }
    2136         176 :             if (fil)
    2137         145 :                 if (   fil->type != MPEGTS_SECTION
    2138         145 :                     || fil->pid != pmt_pid
    2139         145 :                     || fil->u.section_filter.section_cb != pmt_cb)
    2140           0 :                     mpegts_close_filter(ts, ts->pids[pmt_pid]);
    2141             : 
    2142         176 :             if (!ts->pids[pmt_pid])
    2143          31 :                 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
    2144         176 :             add_pat_entry(ts, sid);
    2145         176 :             add_pid_to_pmt(ts, sid, 0); // add pat pid to program
    2146         176 :             add_pid_to_pmt(ts, sid, pmt_pid);
    2147             :         }
    2148             :     }
    2149             : 
    2150         176 :     if (sid < 0) {
    2151             :         int i,j;
    2152         352 :         for (j=0; j<ts->stream->nb_programs; j++) {
    2153         176 :             for (i = 0; i < ts->nb_prg; i++)
    2154         176 :                 if (ts->prg[i].id == ts->stream->programs[j]->id)
    2155         176 :                     break;
    2156         176 :             if (i==ts->nb_prg && !ts->skip_clear)
    2157           0 :                 clear_avprogram(ts, ts->stream->programs[j]->id);
    2158             :         }
    2159             :     }
    2160             : }
    2161             : 
    2162         605 : static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
    2163             : {
    2164         605 :     MpegTSContext *ts = filter->u.section_filter.opaque;
    2165         605 :     MpegTSSectionFilter *tssf = &filter->u.section_filter;
    2166         605 :     SectionHeader h1, *h = &h1;
    2167             :     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
    2168             :     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
    2169             :     char *name, *provider_name;
    2170             : 
    2171         605 :     av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
    2172             :     hex_dump_debug(ts->stream, section, section_len);
    2173             : 
    2174         605 :     p_end = section + section_len - 4;
    2175         605 :     p     = section;
    2176         605 :     if (parse_section_header(h, &p, p_end) < 0)
    2177         476 :         return;
    2178         605 :     if (h->tid != SDT_TID)
    2179           0 :         return;
    2180         605 :     if (ts->skip_changes)
    2181          85 :         return;
    2182         520 :     if (skip_identical(h, tssf))
    2183         391 :         return;
    2184             : 
    2185         129 :     onid = get16(&p, p_end);
    2186         129 :     if (onid < 0)
    2187           0 :         return;
    2188         129 :     val = get8(&p, p_end);
    2189         129 :     if (val < 0)
    2190           0 :         return;
    2191             :     for (;;) {
    2192         387 :         sid = get16(&p, p_end);
    2193         258 :         if (sid < 0)
    2194         129 :             break;
    2195         129 :         val = get8(&p, p_end);
    2196         129 :         if (val < 0)
    2197           0 :             break;
    2198         129 :         desc_list_len = get16(&p, p_end);
    2199         129 :         if (desc_list_len < 0)
    2200           0 :             break;
    2201         129 :         desc_list_len &= 0xfff;
    2202         129 :         desc_list_end  = p + desc_list_len;
    2203         129 :         if (desc_list_end > p_end)
    2204           0 :             break;
    2205             :         for (;;) {
    2206         387 :             desc_tag = get8(&p, desc_list_end);
    2207         258 :             if (desc_tag < 0)
    2208         129 :                 break;
    2209         129 :             desc_len = get8(&p, desc_list_end);
    2210         129 :             desc_end = p + desc_len;
    2211         129 :             if (desc_len < 0 || desc_end > desc_list_end)
    2212             :                 break;
    2213             : 
    2214         129 :             av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
    2215             :                     desc_tag, desc_len);
    2216             : 
    2217         129 :             switch (desc_tag) {
    2218         129 :             case 0x48:
    2219         129 :                 service_type = get8(&p, p_end);
    2220         129 :                 if (service_type < 0)
    2221           0 :                     break;
    2222         129 :                 provider_name = getstr8(&p, p_end);
    2223         129 :                 if (!provider_name)
    2224           0 :                     break;
    2225         129 :                 name = getstr8(&p, p_end);
    2226         129 :                 if (name) {
    2227         129 :                     AVProgram *program = av_new_program(ts->stream, sid);
    2228         129 :                     if (program) {
    2229         129 :                         av_dict_set(&program->metadata, "service_name", name, 0);
    2230         129 :                         av_dict_set(&program->metadata, "service_provider",
    2231             :                                     provider_name, 0);
    2232             :                     }
    2233             :                 }
    2234         129 :                 av_free(name);
    2235         129 :                 av_free(provider_name);
    2236         129 :                 break;
    2237           0 :             default:
    2238           0 :                 break;
    2239             :             }
    2240         129 :             p = desc_end;
    2241             :         }
    2242         129 :         p = desc_list_end;
    2243             :     }
    2244             : }
    2245             : 
    2246             : static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
    2247             :                      const uint8_t *packet);
    2248             : 
    2249             : /* handle one TS packet */
    2250      267592 : static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
    2251             : {
    2252             :     MpegTSFilter *tss;
    2253             :     int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
    2254             :         has_adaptation, has_payload;
    2255             :     const uint8_t *p, *p_end;
    2256             :     int64_t pos;
    2257             : 
    2258      267592 :     pid = AV_RB16(packet + 1) & 0x1fff;
    2259      267592 :     if (pid && discard_pid(ts, pid))
    2260           0 :         return 0;
    2261      267592 :     is_start = packet[1] & 0x40;
    2262      267592 :     tss = ts->pids[pid];
    2263      267592 :     if (ts->auto_guess && !tss && is_start) {
    2264          12 :         add_pes_stream(ts, pid, -1);
    2265          12 :         tss = ts->pids[pid];
    2266             :     }
    2267      267592 :     if (!tss)
    2268        7808 :         return 0;
    2269      259784 :     ts->current_pid = pid;
    2270             : 
    2271      259784 :     afc = (packet[3] >> 4) & 3;
    2272      259784 :     if (afc == 0) /* reserved value */
    2273           0 :         return 0;
    2274      259784 :     has_adaptation   = afc & 2;
    2275      259784 :     has_payload      = afc & 1;
    2276      299836 :     is_discontinuity = has_adaptation &&
    2277      299803 :                        packet[4] != 0 && /* with length > 0 */
    2278       40019 :                        (packet[5] & 0x80); /* and discontinuity indicated */
    2279             : 
    2280             :     /* continuity check (currently not used) */
    2281      259784 :     cc = (packet[3] & 0xf);
    2282      259784 :     expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
    2283      519568 :     cc_ok = pid == 0x1FFF || // null packet PID
    2284      259784 :             is_discontinuity ||
    2285      778492 :             tss->last_cc < 0 ||
    2286             :             expected_cc == cc;
    2287             : 
    2288      259784 :     tss->last_cc = cc;
    2289      259784 :     if (!cc_ok) {
    2290          27 :         av_log(ts->stream, AV_LOG_DEBUG,
    2291             :                "Continuity check failed for pid %d expected %d got %d\n",
    2292             :                pid, expected_cc, cc);
    2293          27 :         if (tss->type == MPEGTS_PES) {
    2294           6 :             PESContext *pc = tss->u.pes_filter.opaque;
    2295           6 :             pc->flags |= AV_PKT_FLAG_CORRUPT;
    2296             :         }
    2297             :     }
    2298             : 
    2299      259784 :     if (packet[1] & 0x80) {
    2300           9 :         av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
    2301           9 :         if (tss->type == MPEGTS_PES) {
    2302           9 :             PESContext *pc = tss->u.pes_filter.opaque;
    2303           9 :             pc->flags |= AV_PKT_FLAG_CORRUPT;
    2304             :         }
    2305             :     }
    2306             : 
    2307      259784 :     p = packet + 4;
    2308      259784 :     if (has_adaptation) {
    2309             :         int64_t pcr_h;
    2310             :         int pcr_l;
    2311       40052 :         if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
    2312       18769 :             tss->last_pcr = pcr_h * 300 + pcr_l;
    2313             :         /* skip adaptation field */
    2314       40052 :         p += p[0] + 1;
    2315             :     }
    2316             :     /* if past the end of packet, ignore */
    2317      259784 :     p_end = packet + TS_PACKET_SIZE;
    2318      259784 :     if (p >= p_end || !has_payload)
    2319        1543 :         return 0;
    2320             : 
    2321      258241 :     pos = avio_tell(ts->stream->pb);
    2322      258241 :     if (pos >= 0) {
    2323      258241 :         av_assert0(pos >= TS_PACKET_SIZE);
    2324      258241 :         ts->pos47_full = pos - TS_PACKET_SIZE;
    2325             :     }
    2326             : 
    2327      258241 :     if (tss->type == MPEGTS_SECTION) {
    2328        7243 :         if (is_start) {
    2329             :             /* pointer field present */
    2330        7243 :             len = *p++;
    2331        7243 :             if (len > p_end - p)
    2332           0 :                 return 0;
    2333        7243 :             if (len && cc_ok) {
    2334             :                 /* write remaining section bytes */
    2335           0 :                 write_section_data(ts, tss,
    2336             :                                    p, len, 0);
    2337             :                 /* check whether filter has been closed */
    2338           0 :                 if (!ts->pids[pid])
    2339           0 :                     return 0;
    2340             :             }
    2341        7243 :             p += len;
    2342        7243 :             if (p < p_end) {
    2343        7243 :                 write_section_data(ts, tss,
    2344        7243 :                                    p, p_end - p, 1);
    2345             :             }
    2346             :         } else {
    2347           0 :             if (cc_ok) {
    2348           0 :                 write_section_data(ts, tss,
    2349           0 :                                    p, p_end - p, 0);
    2350             :             }
    2351             :         }
    2352             : 
    2353             :         // stop find_stream_info from waiting for more streams
    2354             :         // when all programs have received a PMT
    2355        7243 :         if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
    2356             :             int i;
    2357         246 :             for (i = 0; i < ts->nb_prg; i++) {
    2358         125 :                 if (!ts->prg[i].pmt_found)
    2359           4 :                     break;
    2360             :             }
    2361         125 :             if (i == ts->nb_prg && ts->nb_prg > 0) {
    2362         121 :                 int types = 0;
    2363         247 :                 for (i = 0; i < ts->stream->nb_streams; i++) {
    2364         126 :                     AVStream *st = ts->stream->streams[i];
    2365         126 :                     if (st->codecpar->codec_type >= 0)
    2366         126 :                         types |= 1<<st->codecpar->codec_type;
    2367             :                 }
    2368         121 :                 if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
    2369           9 :                     av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
    2370           9 :                     ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
    2371             :                 }
    2372             :             }
    2373             :         }
    2374             : 
    2375             :     } else {
    2376             :         int ret;
    2377             :         // Note: The position here points actually behind the current packet.
    2378      250998 :         if (tss->type == MPEGTS_PES) {
    2379      501996 :             if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
    2380      250998 :                                                 pos - ts->raw_packet_size)) < 0)
    2381           0 :                 return ret;
    2382             :         }
    2383             :     }
    2384             : 
    2385      258241 :     return 0;
    2386             : }
    2387             : 
    2388          41 : static void reanalyze(MpegTSContext *ts) {
    2389          41 :     AVIOContext *pb = ts->stream->pb;
    2390          41 :     int64_t pos = avio_tell(pb);
    2391          41 :     if (pos < 0)
    2392           0 :         return;
    2393          41 :     pos -= ts->pos47_full;
    2394          41 :     if (pos == TS_PACKET_SIZE) {
    2395           0 :         ts->size_stat[0] ++;
    2396          41 :     } else if (pos == TS_DVHS_PACKET_SIZE) {
    2397           0 :         ts->size_stat[1] ++;
    2398          41 :     } else if (pos == TS_FEC_PACKET_SIZE) {
    2399           0 :         ts->size_stat[2] ++;
    2400             :     }
    2401             : 
    2402          41 :     ts->size_stat_count ++;
    2403          41 :     if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
    2404           0 :         int newsize = 0;
    2405           0 :         if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
    2406           0 :             newsize = TS_PACKET_SIZE;
    2407           0 :         } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
    2408           0 :             newsize = TS_DVHS_PACKET_SIZE;
    2409           0 :         } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
    2410           0 :             newsize = TS_FEC_PACKET_SIZE;
    2411             :         }
    2412           0 :         if (newsize && newsize != ts->raw_packet_size) {
    2413           0 :             av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
    2414           0 :             ts->raw_packet_size = newsize;
    2415             :         }
    2416           0 :         ts->size_stat_count = 0;
    2417           0 :         memset(ts->size_stat, 0, sizeof(ts->size_stat));
    2418             :     }
    2419             : }
    2420             : 
    2421             : /* XXX: try to find a better synchro over several packets (use
    2422             :  * get_packet_size() ?) */
    2423          41 : static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
    2424             : {
    2425          41 :     MpegTSContext *ts = s->priv_data;
    2426          41 :     AVIOContext *pb = s->pb;
    2427             :     int c, i;
    2428          41 :     uint64_t pos = avio_tell(pb);
    2429             : 
    2430          41 :     avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
    2431             : 
    2432             :     //Special case for files like 01c56b0dc1.ts
    2433          41 :     if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
    2434           0 :         avio_seek(pb, 12, SEEK_CUR);
    2435           0 :         return 0;
    2436             :     }
    2437             : 
    2438        2972 :     for (i = 0; i < ts->resync_size; i++) {
    2439        2972 :         c = avio_r8(pb);
    2440        2972 :         if (avio_feof(pb))
    2441           0 :             return AVERROR_EOF;
    2442        2972 :         if (c == 0x47) {
    2443          41 :             avio_seek(pb, -1, SEEK_CUR);
    2444          41 :             reanalyze(s->priv_data);
    2445          41 :             return 0;
    2446             :         }
    2447             :     }
    2448           0 :     av_log(s, AV_LOG_ERROR,
    2449             :            "max resync size reached, could not find sync byte\n");
    2450             :     /* no sync found */
    2451           0 :     return AVERROR_INVALIDDATA;
    2452             : }
    2453             : 
    2454             : /* return AVERROR_something if error or EOF. Return 0 if OK. */
    2455      267798 : static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
    2456             :                        const uint8_t **data)
    2457             : {
    2458      267798 :     AVIOContext *pb = s->pb;
    2459             :     int len;
    2460             : 
    2461             :     for (;;) {
    2462      267880 :         len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
    2463      267839 :         if (len != TS_PACKET_SIZE)
    2464         206 :             return len < 0 ? len : AVERROR_EOF;
    2465             :         /* check packet sync byte */
    2466      267633 :         if ((*data)[0] != 0x47) {
    2467             :             /* find a new packet start */
    2468             : 
    2469          41 :             if (mpegts_resync(s, raw_packet_size, *data) < 0)
    2470           0 :                 return AVERROR(EAGAIN);
    2471             :             else
    2472          41 :                 continue;
    2473             :         } else {
    2474      267592 :             break;
    2475             :         }
    2476             :     }
    2477      267592 :     return 0;
    2478             : }
    2479             : 
    2480      267592 : static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
    2481             : {
    2482      267592 :     AVIOContext *pb = s->pb;
    2483      267592 :     int skip = raw_packet_size - TS_PACKET_SIZE;
    2484      267592 :     if (skip > 0)
    2485           0 :         avio_skip(pb, skip);
    2486      267592 : }
    2487             : 
    2488       19906 : static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
    2489             : {
    2490       19906 :     AVFormatContext *s = ts->stream;
    2491             :     uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
    2492             :     const uint8_t *data;
    2493             :     int64_t packet_num;
    2494       19906 :     int ret = 0;
    2495             : 
    2496       19906 :     if (avio_tell(s->pb) != ts->last_pos) {
    2497             :         int i;
    2498         198 :         av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
    2499             :         /* seek detected, flush pes buffer */
    2500     1622214 :         for (i = 0; i < NB_PID_MAX; i++) {
    2501     1622016 :             if (ts->pids[i]) {
    2502         963 :                 if (ts->pids[i]->type == MPEGTS_PES) {
    2503         369 :                     PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
    2504         369 :                     av_buffer_unref(&pes->buffer);
    2505         369 :                     pes->data_index = 0;
    2506         369 :                     pes->state = MPEGTS_SKIP; /* skip until pes header */
    2507         594 :                 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
    2508         594 :                     ts->pids[i]->u.section_filter.last_ver = -1;
    2509             :                 }
    2510         963 :                 ts->pids[i]->last_cc = -1;
    2511         963 :                 ts->pids[i]->last_pcr = -1;
    2512             :             }
    2513             :         }
    2514             :     }
    2515             : 
    2516       19906 :     ts->stop_parse = 0;
    2517       19906 :     packet_num = 0;
    2518       19906 :     memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
    2519             :     for (;;) {
    2520      555090 :         packet_num++;
    2521      574996 :         if (nb_packets != 0 && packet_num >= nb_packets ||
    2522      287498 :             ts->stop_parse > 1) {
    2523          31 :             ret = AVERROR(EAGAIN);
    2524          31 :             break;
    2525             :         }
    2526      287467 :         if (ts->stop_parse > 0)
    2527       19669 :             break;
    2528             : 
    2529      267798 :         ret = read_packet(s, packet, ts->raw_packet_size, &data);
    2530      267798 :         if (ret != 0)
    2531         206 :             break;
    2532      267592 :         ret = handle_packet(ts, data);
    2533      267592 :         finished_reading_packet(s, ts->raw_packet_size);
    2534      267592 :         if (ret != 0)
    2535           0 :             break;
    2536             :     }
    2537       19906 :     ts->last_pos = avio_tell(s->pb);
    2538       19906 :     return ret;
    2539             : }
    2540             : 
    2541        6130 : static int mpegts_probe(AVProbeData *p)
    2542             : {
    2543        6130 :     const int size = p->buf_size;
    2544        6130 :     int maxscore = 0;
    2545        6130 :     int sumscore = 0;
    2546             :     int i;
    2547        6130 :     int check_count = size / TS_FEC_PACKET_SIZE;
    2548             : #define CHECK_COUNT 10
    2549             : #define CHECK_BLOCK 100
    2550             : 
    2551        6130 :     if (!check_count)
    2552          11 :         return 0;
    2553             : 
    2554       16829 :     for (i = 0; i<check_count; i+=CHECK_BLOCK) {
    2555       10710 :         int left = FFMIN(check_count - i, CHECK_BLOCK);
    2556       10710 :         int score      = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , 1);
    2557       10710 :         int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
    2558       10710 :         int fec_score  = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
    2559       10710 :         score = FFMAX3(score, dvhs_score, fec_score);
    2560       10710 :         sumscore += score;
    2561       10710 :         maxscore = FFMAX(maxscore, score);
    2562             :     }
    2563             : 
    2564        6119 :     sumscore = sumscore * CHECK_COUNT / check_count;
    2565        6119 :     maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
    2566             : 
    2567             :     ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
    2568             : 
    2569        6119 :     if        (check_count > CHECK_COUNT && sumscore > 6) {
    2570           0 :         return AVPROBE_SCORE_MAX   + sumscore - CHECK_COUNT;
    2571        6119 :     } else if (check_count >= CHECK_COUNT && sumscore > 6) {
    2572          30 :         return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
    2573        6089 :     } else if (check_count >= CHECK_COUNT && maxscore > 6) {
    2574           0 :         return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
    2575        6089 :     } else if (sumscore > 6) {
    2576           1 :         return 2;
    2577             :     } else {
    2578        6088 :         return 0;
    2579             :     }
    2580             : }
    2581             : 
    2582             : /* return the 90kHz PCR and the extension for the 27MHz PCR. return
    2583             :  * (-1) if not available */
    2584       40052 : static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
    2585             : {
    2586             :     int afc, len, flags;
    2587             :     const uint8_t *p;
    2588             :     unsigned int v;
    2589             : 
    2590       40052 :     afc = (packet[3] >> 4) & 3;
    2591       40052 :     if (afc <= 1)
    2592           0 :         return AVERROR_INVALIDDATA;
    2593       40052 :     p   = packet + 4;
    2594       40052 :     len = p[0];
    2595       40052 :     p++;
    2596       40052 :     if (len == 0)
    2597          33 :         return AVERROR_INVALIDDATA;
    2598       40019 :     flags = *p++;
    2599       40019 :     len--;
    2600       40019 :     if (!(flags & 0x10))
    2601       21250 :         return AVERROR_INVALIDDATA;
    2602       18769 :     if (len < 6)
    2603           0 :         return AVERROR_INVALIDDATA;
    2604       18769 :     v          = AV_RB32(p);
    2605       18769 :     *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
    2606       18769 :     *ppcr_low  = ((p[4] & 1) << 8) | p[5];
    2607       18769 :     return 0;
    2608             : }
    2609             : 
    2610          62 : static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
    2611             : 
    2612             :     /* NOTE: We attempt to seek on non-seekable files as well, as the
    2613             :      * probe buffer usually is big enough. Only warn if the seek failed
    2614             :      * on files where the seek should work. */
    2615          62 :     if (avio_seek(pb, pos, SEEK_SET) < 0)
    2616           0 :         av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
    2617          62 : }
    2618             : 
    2619          31 : static int mpegts_read_header(AVFormatContext *s)
    2620             : {
    2621          31 :     MpegTSContext *ts = s->priv_data;
    2622          31 :     AVIOContext *pb   = s->pb;
    2623          31 :     uint8_t buf[8 * 1024] = {0};
    2624             :     int len;
    2625          31 :     int64_t pos, probesize = s->probesize;
    2626             : 
    2627          31 :     s->internal->prefer_codec_framerate = 1;
    2628             : 
    2629          31 :     if (ffio_ensure_seekback(pb, probesize) < 0)
    2630           0 :         av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
    2631             : 
    2632             :     /* read the first 8192 bytes to get packet size */
    2633          31 :     pos = avio_tell(pb);
    2634          31 :     len = avio_read(pb, buf, sizeof(buf));
    2635          31 :     ts->raw_packet_size = get_packet_size(buf, len);
    2636          31 :     if (ts->raw_packet_size <= 0) {
    2637           0 :         av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
    2638           0 :         ts->raw_packet_size = TS_PACKET_SIZE;
    2639             :     }
    2640          31 :     ts->stream     = s;
    2641          31 :     ts->auto_guess = 0;
    2642             : 
    2643          31 :     if (s->iformat == &ff_mpegts_demuxer) {
    2644             :         /* normal demux */
    2645             : 
    2646             :         /* first do a scan to get all the services */
    2647          31 :         seek_back(s, pb, pos);
    2648             : 
    2649          31 :         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
    2650             : 
    2651          31 :         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
    2652             : 
    2653          31 :         handle_packets(ts, probesize / ts->raw_packet_size);
    2654             :         /* if could not find service, enable auto_guess */
    2655             : 
    2656          31 :         ts->auto_guess = 1;
    2657             : 
    2658          31 :         av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
    2659             : 
    2660          31 :         s->ctx_flags |= AVFMTCTX_NOHEADER;
    2661             :     } else {
    2662             :         AVStream *st;
    2663             :         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
    2664             :         int64_t pcrs[2], pcr_h;
    2665             :         int packet_count[2];
    2666             :         uint8_t packet[TS_PACKET_SIZE];
    2667             :         const uint8_t *data;
    2668             : 
    2669             :         /* only read packets */
    2670             : 
    2671           0 :         st = avformat_new_stream(s, NULL);
    2672           0 :         if (!st)
    2673           0 :             return AVERROR(ENOMEM);
    2674           0 :         avpriv_set_pts_info(st, 60, 1, 27000000);
    2675           0 :         st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
    2676           0 :         st->codecpar->codec_id   = AV_CODEC_ID_MPEG2TS;
    2677             : 
    2678             :         /* we iterate until we find two PCRs to estimate the bitrate */
    2679           0 :         pcr_pid    = -1;
    2680           0 :         nb_pcrs    = 0;
    2681           0 :         nb_packets = 0;
    2682             :         for (;;) {
    2683           0 :             ret = read_packet(s, packet, ts->raw_packet_size, &data);
    2684           0 :             if (ret < 0)
    2685           0 :                 return ret;
    2686           0 :             pid = AV_RB16(data + 1) & 0x1fff;
    2687           0 :             if ((pcr_pid == -1 || pcr_pid == pid) &&
    2688           0 :                 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
    2689           0 :                 finished_reading_packet(s, ts->raw_packet_size);
    2690           0 :                 pcr_pid = pid;
    2691           0 :                 packet_count[nb_pcrs] = nb_packets;
    2692           0 :                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
    2693           0 :                 nb_pcrs++;
    2694           0 :                 if (nb_pcrs >= 2) {
    2695           0 :                     if (pcrs[1] - pcrs[0] > 0) {
    2696             :                         /* the difference needs to be positive to make sense for bitrate computation */
    2697           0 :                         break;
    2698             :                     } else {
    2699           0 :                         av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
    2700           0 :                         pcrs[0] = pcrs[1];
    2701           0 :                         packet_count[0] = packet_count[1];
    2702           0 :                         nb_pcrs--;
    2703             :                     }
    2704             :                 }
    2705             :             } else {
    2706           0 :                 finished_reading_packet(s, ts->raw_packet_size);
    2707             :             }
    2708           0 :             nb_packets++;
    2709             :         }
    2710             : 
    2711             :         /* NOTE1: the bitrate is computed without the FEC */
    2712             :         /* NOTE2: it is only the bitrate of the start of the stream */
    2713           0 :         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
    2714           0 :         ts->cur_pcr  = pcrs[0] - ts->pcr_incr * packet_count[0];
    2715           0 :         s->bit_rate  = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
    2716           0 :         st->codecpar->bit_rate = s->bit_rate;
    2717           0 :         st->start_time      = ts->cur_pcr;
    2718           0 :         av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
    2719           0 :                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
    2720             :     }
    2721             : 
    2722          31 :     seek_back(s, pb, pos);
    2723          31 :     return 0;
    2724             : }
    2725             : 
    2726             : #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
    2727             : 
    2728           0 : static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
    2729             : {
    2730           0 :     MpegTSContext *ts = s->priv_data;
    2731             :     int ret, i;
    2732             :     int64_t pcr_h, next_pcr_h, pos;
    2733             :     int pcr_l, next_pcr_l;
    2734             :     uint8_t pcr_buf[12];
    2735             :     const uint8_t *data;
    2736             : 
    2737           0 :     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
    2738           0 :         return AVERROR(ENOMEM);
    2739           0 :     ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
    2740           0 :     pkt->pos = avio_tell(s->pb);
    2741           0 :     if (ret < 0) {
    2742           0 :         av_packet_unref(pkt);
    2743           0 :         return ret;
    2744             :     }
    2745           0 :     if (data != pkt->data)
    2746           0 :         memcpy(pkt->data, data, ts->raw_packet_size);
    2747           0 :     finished_reading_packet(s, ts->raw_packet_size);
    2748           0 :     if (ts->mpeg2ts_compute_pcr) {
    2749             :         /* compute exact PCR for each packet */
    2750           0 :         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
    2751             :             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
    2752           0 :             pos = avio_tell(s->pb);
    2753           0 :             for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
    2754           0 :                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
    2755           0 :                 avio_read(s->pb, pcr_buf, 12);
    2756           0 :                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
    2757             :                     /* XXX: not precise enough */
    2758           0 :                     ts->pcr_incr =
    2759           0 :                         ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
    2760           0 :                         (i + 1);
    2761           0 :                     break;
    2762             :                 }
    2763             :             }
    2764           0 :             avio_seek(s->pb, pos, SEEK_SET);
    2765             :             /* no next PCR found: we use previous increment */
    2766           0 :             ts->cur_pcr = pcr_h * 300 + pcr_l;
    2767             :         }
    2768           0 :         pkt->pts      = ts->cur_pcr;
    2769           0 :         pkt->duration = ts->pcr_incr;
    2770           0 :         ts->cur_pcr  += ts->pcr_incr;
    2771             :     }
    2772           0 :     pkt->stream_index = 0;
    2773           0 :     return 0;
    2774             : }
    2775             : 
    2776       19875 : static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
    2777             : {
    2778       19875 :     MpegTSContext *ts = s->priv_data;
    2779             :     int ret, i;
    2780             : 
    2781       19875 :     pkt->size = -1;
    2782       19875 :     ts->pkt = pkt;
    2783       19875 :     ret = handle_packets(ts, 0);
    2784       19875 :     if (ret < 0) {
    2785         206 :         av_packet_unref(ts->pkt);
    2786             :         /* flush pes data left */
    2787     1213511 :         for (i = 0; i < NB_PID_MAX; i++)
    2788     1213385 :             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
    2789         348 :                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
    2790         348 :                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
    2791          80 :                     ret = new_pes_packet(pes, pkt);
    2792          80 :                     if (ret < 0)
    2793           0 :                         return ret;
    2794          80 :                     pes->state = MPEGTS_SKIP;
    2795          80 :                     ret = 0;
    2796          80 :                     break;
    2797             :                 }
    2798             :             }
    2799             :     }
    2800             : 
    2801       19875 :     if (!ret && pkt->size < 0)
    2802           0 :         ret = AVERROR_INVALIDDATA;
    2803       19875 :     return ret;
    2804             : }
    2805             : 
    2806          31 : static void mpegts_free(MpegTSContext *ts)
    2807             : {
    2808             :     int i;
    2809             : 
    2810          31 :     clear_programs(ts);
    2811             : 
    2812      253983 :     for (i = 0; i < NB_PID_MAX; i++)
    2813      253952 :         if (ts->pids[i])
    2814         152 :             mpegts_close_filter(ts, ts->pids[i]);
    2815          31 : }
    2816             : 
    2817          31 : static int mpegts_read_close(AVFormatContext *s)
    2818             : {
    2819          31 :     MpegTSContext *ts = s->priv_data;
    2820          31 :     mpegts_free(ts);
    2821          31 :     return 0;
    2822             : }
    2823             : 
    2824           0 : static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
    2825             :                               int64_t *ppos, int64_t pos_limit)
    2826             : {
    2827           0 :     MpegTSContext *ts = s->priv_data;
    2828             :     int64_t pos, timestamp;
    2829             :     uint8_t buf[TS_PACKET_SIZE];
    2830           0 :     int pcr_l, pcr_pid =
    2831           0 :         ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
    2832           0 :     int pos47 = ts->pos47_full % ts->raw_packet_size;
    2833           0 :     pos =
    2834           0 :         ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
    2835           0 :         ts->raw_packet_size + pos47;
    2836           0 :     while(pos < pos_limit) {
    2837           0 :         if (avio_seek(s->pb, pos, SEEK_SET) < 0)
    2838           0 :             return AV_NOPTS_VALUE;
    2839           0 :         if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
    2840           0 :             return AV_NOPTS_VALUE;
    2841           0 :         if (buf[0] != 0x47) {
    2842           0 :             if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
    2843           0 :                 return AV_NOPTS_VALUE;
    2844           0 :             pos = avio_tell(s->pb);
    2845           0 :             continue;
    2846             :         }
    2847           0 :         if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
    2848           0 :             parse_pcr(&timestamp, &pcr_l, buf) == 0) {
    2849           0 :             *ppos = pos;
    2850           0 :             return timestamp;
    2851             :         }
    2852           0 :         pos += ts->raw_packet_size;
    2853             :     }
    2854             : 
    2855           0 :     return AV_NOPTS_VALUE;
    2856             : }
    2857             : 
    2858          86 : static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
    2859             :                               int64_t *ppos, int64_t pos_limit)
    2860             : {
    2861          86 :     MpegTSContext *ts = s->priv_data;
    2862             :     int64_t pos;
    2863          86 :     int pos47 = ts->pos47_full % ts->raw_packet_size;
    2864          86 :     pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
    2865          86 :     ff_read_frame_flush(s);
    2866          86 :     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
    2867           0 :         return AV_NOPTS_VALUE;
    2868         578 :     while(pos < pos_limit) {
    2869             :         int ret;
    2870             :         AVPacket pkt;
    2871         480 :         av_init_packet(&pkt);
    2872         480 :         ret = av_read_frame(s, &pkt);
    2873         480 :         if (ret < 0)
    2874          92 :             return AV_NOPTS_VALUE;
    2875         462 :         if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
    2876         159 :             ff_reduce_index(s, pkt.stream_index);
    2877         159 :             av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
    2878         159 :             if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
    2879          56 :                 int64_t dts = pkt.dts;
    2880          56 :                 *ppos = pkt.pos;
    2881          56 :                 av_packet_unref(&pkt);
    2882          56 :                 return dts;
    2883             :             }
    2884             :         }
    2885         406 :         pos = pkt.pos;
    2886         406 :         av_packet_unref(&pkt);
    2887             :     }
    2888             : 
    2889          12 :     return AV_NOPTS_VALUE;
    2890             : }
    2891             : 
    2892             : /**************************************************************/
    2893             : /* parsing functions - called from other demuxers such as RTP */
    2894             : 
    2895           0 : MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
    2896             : {
    2897             :     MpegTSContext *ts;
    2898             : 
    2899           0 :     ts = av_mallocz(sizeof(MpegTSContext));
    2900           0 :     if (!ts)
    2901           0 :         return NULL;
    2902             :     /* no stream case, currently used by RTP */
    2903           0 :     ts->raw_packet_size = TS_PACKET_SIZE;
    2904           0 :     ts->stream = s;
    2905           0 :     ts->auto_guess = 1;
    2906           0 :     mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
    2907           0 :     mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
    2908             : 
    2909           0 :     return ts;
    2910             : }
    2911             : 
    2912             : /* return the consumed length if a packet was output, or -1 if no
    2913             :  * packet is output */
    2914           0 : int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
    2915             :                                const uint8_t *buf, int len)
    2916             : {
    2917             :     int len1;
    2918             : 
    2919           0 :     len1 = len;
    2920           0 :     ts->pkt = pkt;
    2921             :     for (;;) {
    2922           0 :         ts->stop_parse = 0;
    2923           0 :         if (len < TS_PACKET_SIZE)
    2924           0 :             return AVERROR_INVALIDDATA;
    2925           0 :         if (buf[0] != 0x47) {
    2926           0 :             buf++;
    2927           0 :             len--;
    2928             :         } else {
    2929           0 :             handle_packet(ts, buf);
    2930           0 :             buf += TS_PACKET_SIZE;
    2931           0 :             len -= TS_PACKET_SIZE;
    2932           0 :             if (ts->stop_parse == 1)
    2933           0 :                 break;
    2934             :         }
    2935             :     }
    2936           0 :     return len1 - len;
    2937             : }
    2938             : 
    2939           0 : void avpriv_mpegts_parse_close(MpegTSContext *ts)
    2940             : {
    2941           0 :     mpegts_free(ts);
    2942           0 :     av_free(ts);
    2943           0 : }
    2944             : 
    2945             : AVInputFormat ff_mpegts_demuxer = {
    2946             :     .name           = "mpegts",
    2947             :     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
    2948             :     .priv_data_size = sizeof(MpegTSContext),
    2949             :     .read_probe     = mpegts_probe,
    2950             :     .read_header    = mpegts_read_header,
    2951             :     .read_packet    = mpegts_read_packet,
    2952             :     .read_close     = mpegts_read_close,
    2953             :     .read_timestamp = mpegts_get_dts,
    2954             :     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
    2955             :     .priv_class     = &mpegts_class,
    2956             : };
    2957             : 
    2958             : AVInputFormat ff_mpegtsraw_demuxer = {
    2959             :     .name           = "mpegtsraw",
    2960             :     .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
    2961             :     .priv_data_size = sizeof(MpegTSContext),
    2962             :     .read_header    = mpegts_read_header,
    2963             :     .read_packet    = mpegts_raw_read_packet,
    2964             :     .read_close     = mpegts_read_close,
    2965             :     .read_timestamp = mpegts_get_dts,
    2966             :     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
    2967             :     .priv_class     = &mpegtsraw_class,
    2968             : };

Generated by: LCOV version 1.13