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