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