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