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