]> git.sesse.net Git - ffmpeg/blob - libavformat/mpegts.c
Merge commit 'fdd021884d5c06fb9ad65cb0040bb5717a7b084b'
[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_INT,
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_INT,
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_INT,
176      {.i64 = 0}, 0, 1, 0 },
177     {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_INT,
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_INT,
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     { 0 },
722 };
723
724 /* ATSC ? */
725 static const StreamType MISC_types[] = {
726     { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
727     { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
728     { 0 },
729 };
730
731 static const StreamType REGD_types[] = {
732     { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
733     { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3   },
734     { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
735     { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
736     { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
737     { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
738     { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC  },
739     { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA,  AV_CODEC_ID_SMPTE_KLV },
740     { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1   },
741     { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS  },
742     { 0 },
743 };
744
745 static const StreamType METADATA_types[] = {
746     { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
747     { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
748     { 0 },
749 };
750
751 /* descriptor present */
752 static const StreamType DESC_types[] = {
753     { 0x6a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3          }, /* AC-3 descriptor */
754     { 0x7a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3         }, /* E-AC-3 descriptor */
755     { 0x7b, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS          },
756     { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
757     { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
758     { 0 },
759 };
760
761 static void mpegts_find_stream_type(AVStream *st,
762                                     uint32_t stream_type,
763                                     const StreamType *types)
764 {
765     if (avcodec_is_open(st->codec)) {
766         av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
767         return;
768     }
769
770     for (; types->stream_type; types++)
771         if (stream_type == types->stream_type) {
772             st->codec->codec_type = types->codec_type;
773             st->codec->codec_id   = types->codec_id;
774             st->request_probe     = 0;
775             return;
776         }
777 }
778
779 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
780                                   uint32_t stream_type, uint32_t prog_reg_desc)
781 {
782     int old_codec_type = st->codec->codec_type;
783     int old_codec_id  = st->codec->codec_id;
784
785     if (avcodec_is_open(st->codec)) {
786         av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
787         return 0;
788     }
789
790     avpriv_set_pts_info(st, 33, 1, 90000);
791     st->priv_data         = pes;
792     st->codec->codec_type = AVMEDIA_TYPE_DATA;
793     st->codec->codec_id   = AV_CODEC_ID_NONE;
794     st->need_parsing      = AVSTREAM_PARSE_FULL;
795     pes->st          = st;
796     pes->stream_type = stream_type;
797
798     av_log(pes->stream, AV_LOG_DEBUG,
799            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
800            st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
801
802     st->codec->codec_tag = pes->stream_type;
803
804     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
805     if ((prog_reg_desc == AV_RL32("HDMV") ||
806          prog_reg_desc == AV_RL32("HDPR")) &&
807         st->codec->codec_id == AV_CODEC_ID_NONE) {
808         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
809         if (pes->stream_type == 0x83) {
810             // HDMV TrueHD streams also contain an AC3 coded version of the
811             // audio track - add a second stream for this
812             AVStream *sub_st;
813             // priv_data cannot be shared between streams
814             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
815             if (!sub_pes)
816                 return AVERROR(ENOMEM);
817             memcpy(sub_pes, pes, sizeof(*sub_pes));
818
819             sub_st = avformat_new_stream(pes->stream, NULL);
820             if (!sub_st) {
821                 av_free(sub_pes);
822                 return AVERROR(ENOMEM);
823             }
824
825             sub_st->id = pes->pid;
826             avpriv_set_pts_info(sub_st, 33, 1, 90000);
827             sub_st->priv_data         = sub_pes;
828             sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
829             sub_st->codec->codec_id   = AV_CODEC_ID_AC3;
830             sub_st->need_parsing      = AVSTREAM_PARSE_FULL;
831             sub_pes->sub_st           = pes->sub_st = sub_st;
832         }
833     }
834     if (st->codec->codec_id == AV_CODEC_ID_NONE)
835         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
836     if (st->codec->codec_id == AV_CODEC_ID_NONE) {
837         st->codec->codec_id  = old_codec_id;
838         st->codec->codec_type = old_codec_type;
839     }
840     if ((st->codec->codec_id == AV_CODEC_ID_NONE ||
841             (st->request_probe > 0 && st->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
842         !avcodec_is_open(st->codec) &&
843         stream_type == STREAM_TYPE_PRIVATE_DATA) {
844         st->codec->codec_type = AVMEDIA_TYPE_DATA;
845         st->codec->codec_id   = AV_CODEC_ID_BIN_DATA;
846         st->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
847     }
848
849     return 0;
850 }
851
852 static void reset_pes_packet_state(PESContext *pes)
853 {
854     pes->pts        = AV_NOPTS_VALUE;
855     pes->dts        = AV_NOPTS_VALUE;
856     pes->data_index = 0;
857     pes->flags      = 0;
858     av_buffer_unref(&pes->buffer);
859 }
860
861 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
862 {
863     av_init_packet(pkt);
864
865     pkt->buf  = pes->buffer;
866     pkt->data = pes->buffer->data;
867     pkt->size = pes->data_index;
868
869     if (pes->total_size != MAX_PES_PAYLOAD &&
870         pes->pes_header_size + pes->data_index != pes->total_size +
871         PES_START_SIZE) {
872         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
873         pes->flags |= AV_PKT_FLAG_CORRUPT;
874     }
875     memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
876
877     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
878     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
879         pkt->stream_index = pes->sub_st->index;
880     else
881         pkt->stream_index = pes->st->index;
882     pkt->pts = pes->pts;
883     pkt->dts = pes->dts;
884     /* store position of first TS packet of this PES packet */
885     pkt->pos   = pes->ts_packet_pos;
886     pkt->flags = pes->flags;
887
888     pes->buffer = NULL;
889     reset_pes_packet_state(pes);
890 }
891
892 static uint64_t get_ts64(GetBitContext *gb, int bits)
893 {
894     if (get_bits_left(gb) < bits)
895         return AV_NOPTS_VALUE;
896     return get_bits64(gb, bits);
897 }
898
899 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
900                           const uint8_t *buf, int buf_size)
901 {
902     GetBitContext gb;
903     int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
904     int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
905     int dts_flag = -1, cts_flag = -1;
906     int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
907     uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
908     int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
909
910     memcpy(buf_padded, buf, buf_padded_size);
911
912     init_get_bits(&gb, buf_padded, buf_padded_size * 8);
913
914     if (sl->use_au_start)
915         au_start_flag = get_bits1(&gb);
916     if (sl->use_au_end)
917         au_end_flag = get_bits1(&gb);
918     if (!sl->use_au_start && !sl->use_au_end)
919         au_start_flag = au_end_flag = 1;
920     if (sl->ocr_len > 0)
921         ocr_flag = get_bits1(&gb);
922     if (sl->use_idle)
923         idle_flag = get_bits1(&gb);
924     if (sl->use_padding)
925         padding_flag = get_bits1(&gb);
926     if (padding_flag)
927         padding_bits = get_bits(&gb, 3);
928
929     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
930         if (sl->packet_seq_num_len)
931             skip_bits_long(&gb, sl->packet_seq_num_len);
932         if (sl->degr_prior_len)
933             if (get_bits1(&gb))
934                 skip_bits(&gb, sl->degr_prior_len);
935         if (ocr_flag)
936             skip_bits_long(&gb, sl->ocr_len);
937         if (au_start_flag) {
938             if (sl->use_rand_acc_pt)
939                 get_bits1(&gb);
940             if (sl->au_seq_num_len > 0)
941                 skip_bits_long(&gb, sl->au_seq_num_len);
942             if (sl->use_timestamps) {
943                 dts_flag = get_bits1(&gb);
944                 cts_flag = get_bits1(&gb);
945             }
946         }
947         if (sl->inst_bitrate_len)
948             inst_bitrate_flag = get_bits1(&gb);
949         if (dts_flag == 1)
950             dts = get_ts64(&gb, sl->timestamp_len);
951         if (cts_flag == 1)
952             cts = get_ts64(&gb, sl->timestamp_len);
953         if (sl->au_len > 0)
954             skip_bits_long(&gb, sl->au_len);
955         if (inst_bitrate_flag)
956             skip_bits_long(&gb, sl->inst_bitrate_len);
957     }
958
959     if (dts != AV_NOPTS_VALUE)
960         pes->dts = dts;
961     if (cts != AV_NOPTS_VALUE)
962         pes->pts = cts;
963
964     if (sl->timestamp_len && sl->timestamp_res)
965         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
966
967     return (get_bits_count(&gb) + 7) >> 3;
968 }
969
970 /* return non zero if a packet could be constructed */
971 static int mpegts_push_data(MpegTSFilter *filter,
972                             const uint8_t *buf, int buf_size, int is_start,
973                             int64_t pos)
974 {
975     PESContext *pes   = filter->u.pes_filter.opaque;
976     MpegTSContext *ts = pes->ts;
977     const uint8_t *p;
978     int len, code;
979
980     if (!ts->pkt)
981         return 0;
982
983     if (is_start) {
984         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
985             new_pes_packet(pes, ts->pkt);
986             ts->stop_parse = 1;
987         } else {
988             reset_pes_packet_state(pes);
989         }
990         pes->state         = MPEGTS_HEADER;
991         pes->ts_packet_pos = pos;
992     }
993     p = buf;
994     while (buf_size > 0) {
995         switch (pes->state) {
996         case MPEGTS_HEADER:
997             len = PES_START_SIZE - pes->data_index;
998             if (len > buf_size)
999                 len = buf_size;
1000             memcpy(pes->header + pes->data_index, p, len);
1001             pes->data_index += len;
1002             p += len;
1003             buf_size -= len;
1004             if (pes->data_index == PES_START_SIZE) {
1005                 /* we got all the PES or section header. We can now
1006                  * decide */
1007                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
1008                     pes->header[2] == 0x01) {
1009                     /* it must be an mpeg2 PES stream */
1010                     code = pes->header[3] | 0x100;
1011                     av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
1012                             code);
1013
1014                     if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
1015                          (!pes->sub_st ||
1016                           pes->sub_st->discard == AVDISCARD_ALL)) ||
1017                         code == 0x1be) /* padding_stream */
1018                         goto skip;
1019
1020                     /* stream not present in PMT */
1021                     if (!pes->st) {
1022                         if (ts->skip_changes)
1023                             goto skip;
1024
1025                         pes->st = avformat_new_stream(ts->stream, NULL);
1026                         if (!pes->st)
1027                             return AVERROR(ENOMEM);
1028                         pes->st->id = pes->pid;
1029                         mpegts_set_stream_info(pes->st, pes, 0, 0);
1030                     }
1031
1032                     pes->total_size = AV_RB16(pes->header + 4);
1033                     /* NOTE: a zero total size means the PES size is
1034                      * unbounded */
1035                     if (!pes->total_size)
1036                         pes->total_size = MAX_PES_PAYLOAD;
1037
1038                     /* allocate pes buffer */
1039                     pes->buffer = av_buffer_alloc(pes->total_size +
1040                                                   AV_INPUT_BUFFER_PADDING_SIZE);
1041                     if (!pes->buffer)
1042                         return AVERROR(ENOMEM);
1043
1044                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
1045                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
1046                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
1047                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
1048                         pes->state = MPEGTS_PESHEADER;
1049                         if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
1050                             av_log(pes->stream, AV_LOG_TRACE,
1051                                     "pid=%x stream_type=%x probing\n",
1052                                     pes->pid,
1053                                     pes->stream_type);
1054                             pes->st->request_probe = 1;
1055                         }
1056                     } else {
1057                         pes->state      = MPEGTS_PAYLOAD;
1058                         pes->data_index = 0;
1059                     }
1060                 } else {
1061                     /* otherwise, it should be a table */
1062                     /* skip packet */
1063 skip:
1064                     pes->state = MPEGTS_SKIP;
1065                     continue;
1066                 }
1067             }
1068             break;
1069         /**********************************************/
1070         /* PES packing parsing */
1071         case MPEGTS_PESHEADER:
1072             len = PES_HEADER_SIZE - pes->data_index;
1073             if (len < 0)
1074                 return AVERROR_INVALIDDATA;
1075             if (len > buf_size)
1076                 len = buf_size;
1077             memcpy(pes->header + pes->data_index, p, len);
1078             pes->data_index += len;
1079             p += len;
1080             buf_size -= len;
1081             if (pes->data_index == PES_HEADER_SIZE) {
1082                 pes->pes_header_size = pes->header[8] + 9;
1083                 pes->state           = MPEGTS_PESHEADER_FILL;
1084             }
1085             break;
1086         case MPEGTS_PESHEADER_FILL:
1087             len = pes->pes_header_size - pes->data_index;
1088             if (len < 0)
1089                 return AVERROR_INVALIDDATA;
1090             if (len > buf_size)
1091                 len = buf_size;
1092             memcpy(pes->header + pes->data_index, p, len);
1093             pes->data_index += len;
1094             p += len;
1095             buf_size -= len;
1096             if (pes->data_index == pes->pes_header_size) {
1097                 const uint8_t *r;
1098                 unsigned int flags, pes_ext, skip;
1099
1100                 flags = pes->header[7];
1101                 r = pes->header + 9;
1102                 pes->pts = AV_NOPTS_VALUE;
1103                 pes->dts = AV_NOPTS_VALUE;
1104                 if ((flags & 0xc0) == 0x80) {
1105                     pes->dts = pes->pts = ff_parse_pes_pts(r);
1106                     r += 5;
1107                 } else if ((flags & 0xc0) == 0xc0) {
1108                     pes->pts = ff_parse_pes_pts(r);
1109                     r += 5;
1110                     pes->dts = ff_parse_pes_pts(r);
1111                     r += 5;
1112                 }
1113                 pes->extended_stream_id = -1;
1114                 if (flags & 0x01) { /* PES extension */
1115                     pes_ext = *r++;
1116                     /* Skip PES private data, program packet sequence counter and P-STD buffer */
1117                     skip  = (pes_ext >> 4) & 0xb;
1118                     skip += skip & 0x9;
1119                     r    += skip;
1120                     if ((pes_ext & 0x41) == 0x01 &&
1121                         (r + 2) <= (pes->header + pes->pes_header_size)) {
1122                         /* PES extension 2 */
1123                         if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1124                             pes->extended_stream_id = r[1];
1125                     }
1126                 }
1127
1128                 /* we got the full header. We parse it and get the payload */
1129                 pes->state = MPEGTS_PAYLOAD;
1130                 pes->data_index = 0;
1131                 if (pes->stream_type == 0x12 && buf_size > 0) {
1132                     int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
1133                                                          buf_size);
1134                     pes->pes_header_size += sl_header_bytes;
1135                     p += sl_header_bytes;
1136                     buf_size -= sl_header_bytes;
1137                 }
1138                 if (pes->stream_type == 0x15 && buf_size >= 5) {
1139                     /* skip metadata access unit header */
1140                     pes->pes_header_size += 5;
1141                     p += 5;
1142                     buf_size -= 5;
1143                 }
1144                 if (   pes->ts->fix_teletext_pts
1145                     && (   pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT
1146                         || pes->st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1147                     ) {
1148                     AVProgram *p = NULL;
1149                     while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1150                         if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1151                             MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1152                             if (f) {
1153                                 AVStream *st = NULL;
1154                                 if (f->type == MPEGTS_PES) {
1155                                     PESContext *pcrpes = f->u.pes_filter.opaque;
1156                                     if (pcrpes)
1157                                         st = pcrpes->st;
1158                                 } else if (f->type == MPEGTS_PCR) {
1159                                     int i;
1160                                     for (i = 0; i < p->nb_stream_indexes; i++) {
1161                                         AVStream *pst = pes->stream->streams[p->stream_index[i]];
1162                                         if (pst->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1163                                             st = pst;
1164                                     }
1165                                 }
1166                                 if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
1167                                     // teletext packets do not always have correct timestamps,
1168                                     // the standard says they should be handled after 40.6 ms at most,
1169                                     // and the pcr error to this packet should be no more than 100 ms.
1170                                     // TODO: we should interpolate the PCR, not just use the last one
1171                                     int64_t pcr = f->last_pcr / 300;
1172                                     pes->st->pts_wrap_reference = st->pts_wrap_reference;
1173                                     pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
1174                                     if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1175                                         pes->pts = pes->dts = pcr;
1176                                     } else if (pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1177                                                pes->dts > pcr + 3654 + 9000) {
1178                                         pes->pts = pes->dts = pcr + 3654 + 9000;
1179                                     } else if (pes->st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1180                                                pes->dts > pcr + 10*90000) { //10sec
1181                                         pes->pts = pes->dts = pcr + 3654 + 9000;
1182                                     }
1183                                     break;
1184                                 }
1185                             }
1186                         }
1187                     }
1188                 }
1189             }
1190             break;
1191         case MPEGTS_PAYLOAD:
1192             if (pes->buffer) {
1193                 if (pes->data_index > 0 &&
1194                     pes->data_index + buf_size > pes->total_size) {
1195                     new_pes_packet(pes, ts->pkt);
1196                     pes->total_size = MAX_PES_PAYLOAD;
1197                     pes->buffer = av_buffer_alloc(pes->total_size +
1198                                                   AV_INPUT_BUFFER_PADDING_SIZE);
1199                     if (!pes->buffer)
1200                         return AVERROR(ENOMEM);
1201                     ts->stop_parse = 1;
1202                 } else if (pes->data_index == 0 &&
1203                            buf_size > pes->total_size) {
1204                     // pes packet size is < ts size packet and pes data is padded with 0xff
1205                     // not sure if this is legal in ts but see issue #2392
1206                     buf_size = pes->total_size;
1207                 }
1208                 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1209                 pes->data_index += buf_size;
1210                 /* emit complete packets with known packet size
1211                  * decreases demuxer delay for infrequent packets like subtitles from
1212                  * a couple of seconds to milliseconds for properly muxed files.
1213                  * total_size is the number of bytes following pes_packet_length
1214                  * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1215                 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1216                     pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1217                     ts->stop_parse = 1;
1218                     new_pes_packet(pes, ts->pkt);
1219                 }
1220             }
1221             buf_size = 0;
1222             break;
1223         case MPEGTS_SKIP:
1224             buf_size = 0;
1225             break;
1226         }
1227     }
1228
1229     return 0;
1230 }
1231
1232 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1233 {
1234     MpegTSFilter *tss;
1235     PESContext *pes;
1236
1237     /* if no pid found, then add a pid context */
1238     pes = av_mallocz(sizeof(PESContext));
1239     if (!pes)
1240         return 0;
1241     pes->ts      = ts;
1242     pes->stream  = ts->stream;
1243     pes->pid     = pid;
1244     pes->pcr_pid = pcr_pid;
1245     pes->state   = MPEGTS_SKIP;
1246     pes->pts     = AV_NOPTS_VALUE;
1247     pes->dts     = AV_NOPTS_VALUE;
1248     tss          = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1249     if (!tss) {
1250         av_free(pes);
1251         return 0;
1252     }
1253     return pes;
1254 }
1255
1256 #define MAX_LEVEL 4
1257 typedef struct MP4DescrParseContext {
1258     AVFormatContext *s;
1259     AVIOContext pb;
1260     Mp4Descr *descr;
1261     Mp4Descr *active_descr;
1262     int descr_count;
1263     int max_descr_count;
1264     int level;
1265     int predefined_SLConfigDescriptor_seen;
1266 } MP4DescrParseContext;
1267
1268 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
1269                                      const uint8_t *buf, unsigned size,
1270                                      Mp4Descr *descr, int max_descr_count)
1271 {
1272     int ret;
1273     if (size > (1 << 30))
1274         return AVERROR_INVALIDDATA;
1275
1276     if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
1277                                  NULL, NULL, NULL, NULL)) < 0)
1278         return ret;
1279
1280     d->s               = s;
1281     d->level           = 0;
1282     d->descr_count     = 0;
1283     d->descr           = descr;
1284     d->active_descr    = NULL;
1285     d->max_descr_count = max_descr_count;
1286
1287     return 0;
1288 }
1289
1290 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1291 {
1292     int64_t new_off = avio_tell(pb);
1293     (*len) -= new_off - *off;
1294     *off    = new_off;
1295 }
1296
1297 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1298                            int target_tag);
1299
1300 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1301 {
1302     while (len > 0) {
1303         int ret = parse_mp4_descr(d, off, len, 0);
1304         if (ret < 0)
1305             return ret;
1306         update_offsets(&d->pb, &off, &len);
1307     }
1308     return 0;
1309 }
1310
1311 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1312 {
1313     avio_rb16(&d->pb); // ID
1314     avio_r8(&d->pb);
1315     avio_r8(&d->pb);
1316     avio_r8(&d->pb);
1317     avio_r8(&d->pb);
1318     avio_r8(&d->pb);
1319     update_offsets(&d->pb, &off, &len);
1320     return parse_mp4_descr_arr(d, off, len);
1321 }
1322
1323 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1324 {
1325     int id_flags;
1326     if (len < 2)
1327         return 0;
1328     id_flags = avio_rb16(&d->pb);
1329     if (!(id_flags & 0x0020)) { // URL_Flag
1330         update_offsets(&d->pb, &off, &len);
1331         return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1332     } else {
1333         return 0;
1334     }
1335 }
1336
1337 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1338 {
1339     int es_id = 0;
1340     if (d->descr_count >= d->max_descr_count)
1341         return AVERROR_INVALIDDATA;
1342     ff_mp4_parse_es_descr(&d->pb, &es_id);
1343     d->active_descr = d->descr + (d->descr_count++);
1344
1345     d->active_descr->es_id = es_id;
1346     update_offsets(&d->pb, &off, &len);
1347     parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1348     update_offsets(&d->pb, &off, &len);
1349     if (len > 0)
1350         parse_mp4_descr(d, off, len, MP4SLDescrTag);
1351     d->active_descr = NULL;
1352     return 0;
1353 }
1354
1355 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
1356                                       int len)
1357 {
1358     Mp4Descr *descr = d->active_descr;
1359     if (!descr)
1360         return AVERROR_INVALIDDATA;
1361     d->active_descr->dec_config_descr = av_malloc(len);
1362     if (!descr->dec_config_descr)
1363         return AVERROR(ENOMEM);
1364     descr->dec_config_descr_len = len;
1365     avio_read(&d->pb, descr->dec_config_descr, len);
1366     return 0;
1367 }
1368
1369 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1370 {
1371     Mp4Descr *descr = d->active_descr;
1372     int predefined;
1373     if (!descr)
1374         return AVERROR_INVALIDDATA;
1375
1376     predefined = avio_r8(&d->pb);
1377     if (!predefined) {
1378         int lengths;
1379         int flags = avio_r8(&d->pb);
1380         descr->sl.use_au_start    = !!(flags & 0x80);
1381         descr->sl.use_au_end      = !!(flags & 0x40);
1382         descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1383         descr->sl.use_padding     = !!(flags & 0x08);
1384         descr->sl.use_timestamps  = !!(flags & 0x04);
1385         descr->sl.use_idle        = !!(flags & 0x02);
1386         descr->sl.timestamp_res   = avio_rb32(&d->pb);
1387         avio_rb32(&d->pb);
1388         descr->sl.timestamp_len      = avio_r8(&d->pb);
1389         if (descr->sl.timestamp_len > 64) {
1390             avpriv_request_sample(NULL, "timestamp_len > 64");
1391             descr->sl.timestamp_len = 64;
1392             return AVERROR_PATCHWELCOME;
1393         }
1394         descr->sl.ocr_len            = avio_r8(&d->pb);
1395         descr->sl.au_len             = avio_r8(&d->pb);
1396         descr->sl.inst_bitrate_len   = avio_r8(&d->pb);
1397         lengths                      = avio_rb16(&d->pb);
1398         descr->sl.degr_prior_len     = lengths >> 12;
1399         descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
1400         descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1401     } else if (!d->predefined_SLConfigDescriptor_seen){
1402         avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1403         d->predefined_SLConfigDescriptor_seen = 1;
1404     }
1405     return 0;
1406 }
1407
1408 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1409                            int target_tag)
1410 {
1411     int tag;
1412     int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1413     update_offsets(&d->pb, &off, &len);
1414     if (len < 0 || len1 > len || len1 <= 0) {
1415         av_log(d->s, AV_LOG_ERROR,
1416                "Tag %x length violation new length %d bytes remaining %d\n",
1417                tag, len1, len);
1418         return AVERROR_INVALIDDATA;
1419     }
1420
1421     if (d->level++ >= MAX_LEVEL) {
1422         av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1423         goto done;
1424     }
1425
1426     if (target_tag && tag != target_tag) {
1427         av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1428                target_tag);
1429         goto done;
1430     }
1431
1432     switch (tag) {
1433     case MP4IODescrTag:
1434         parse_MP4IODescrTag(d, off, len1);
1435         break;
1436     case MP4ODescrTag:
1437         parse_MP4ODescrTag(d, off, len1);
1438         break;
1439     case MP4ESDescrTag:
1440         parse_MP4ESDescrTag(d, off, len1);
1441         break;
1442     case MP4DecConfigDescrTag:
1443         parse_MP4DecConfigDescrTag(d, off, len1);
1444         break;
1445     case MP4SLDescrTag:
1446         parse_MP4SLDescrTag(d, off, len1);
1447         break;
1448     }
1449
1450
1451 done:
1452     d->level--;
1453     avio_seek(&d->pb, off + len1, SEEK_SET);
1454     return 0;
1455 }
1456
1457 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1458                          Mp4Descr *descr, int *descr_count, int max_descr_count)
1459 {
1460     MP4DescrParseContext d;
1461     int ret;
1462
1463     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1464     if (ret < 0)
1465         return ret;
1466
1467     ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1468
1469     *descr_count = d.descr_count;
1470     return ret;
1471 }
1472
1473 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1474                        Mp4Descr *descr, int *descr_count, int max_descr_count)
1475 {
1476     MP4DescrParseContext d;
1477     int ret;
1478
1479     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1480     if (ret < 0)
1481         return ret;
1482
1483     ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1484
1485     *descr_count = d.descr_count;
1486     return ret;
1487 }
1488
1489 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1490                     int section_len)
1491 {
1492     MpegTSContext *ts = filter->u.section_filter.opaque;
1493     MpegTSSectionFilter *tssf = &filter->u.section_filter;
1494     SectionHeader h;
1495     const uint8_t *p, *p_end;
1496     AVIOContext pb;
1497     int mp4_descr_count = 0;
1498     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1499     int i, pid;
1500     AVFormatContext *s = ts->stream;
1501
1502     p_end = section + section_len - 4;
1503     p = section;
1504     if (parse_section_header(&h, &p, p_end) < 0)
1505         return;
1506     if (h.tid != M4OD_TID)
1507         return;
1508     if (skip_identical(&h, tssf))
1509         return;
1510
1511     mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1512                 MAX_MP4_DESCR_COUNT);
1513
1514     for (pid = 0; pid < NB_PID_MAX; pid++) {
1515         if (!ts->pids[pid])
1516             continue;
1517         for (i = 0; i < mp4_descr_count; i++) {
1518             PESContext *pes;
1519             AVStream *st;
1520             if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1521                 continue;
1522             if (ts->pids[pid]->type != MPEGTS_PES) {
1523                 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1524                 continue;
1525             }
1526             pes = ts->pids[pid]->u.pes_filter.opaque;
1527             st  = pes->st;
1528             if (!st)
1529                 continue;
1530
1531             pes->sl = mp4_descr[i].sl;
1532
1533             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1534                               mp4_descr[i].dec_config_descr_len, 0,
1535                               NULL, NULL, NULL, NULL);
1536             ff_mp4_read_dec_config_descr(s, st, &pb);
1537             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1538                 st->codec->extradata_size > 0)
1539                 st->need_parsing = 0;
1540             if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1541                 st->codec->extradata_size > 0)
1542                 st->need_parsing = 0;
1543
1544             if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1545                 // do nothing
1546             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO)
1547                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1548             else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
1549                 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1550             else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
1551                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1552         }
1553     }
1554     for (i = 0; i < mp4_descr_count; i++)
1555         av_free(mp4_descr[i].dec_config_descr);
1556 }
1557
1558 static const uint8_t opus_coupled_stream_cnt[9] = {
1559     1, 0, 1, 1, 2, 2, 2, 3, 3
1560 };
1561
1562 static const uint8_t opus_stream_cnt[9] = {
1563     1, 1, 1, 2, 2, 3, 4, 4, 5,
1564 };
1565
1566 static const uint8_t opus_channel_map[8][8] = {
1567     { 0 },
1568     { 0,1 },
1569     { 0,2,1 },
1570     { 0,1,2,3 },
1571     { 0,4,1,2,3 },
1572     { 0,4,1,2,3,5 },
1573     { 0,4,1,2,3,5,6 },
1574     { 0,6,1,2,3,4,5,7 },
1575 };
1576
1577 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1578                               const uint8_t **pp, const uint8_t *desc_list_end,
1579                               Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1580                               MpegTSContext *ts)
1581 {
1582     const uint8_t *desc_end;
1583     int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
1584     char language[252];
1585     int i;
1586
1587     desc_tag = get8(pp, desc_list_end);
1588     if (desc_tag < 0)
1589         return AVERROR_INVALIDDATA;
1590     desc_len = get8(pp, desc_list_end);
1591     if (desc_len < 0)
1592         return AVERROR_INVALIDDATA;
1593     desc_end = *pp + desc_len;
1594     if (desc_end > desc_list_end)
1595         return AVERROR_INVALIDDATA;
1596
1597     av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1598
1599     if ((st->codec->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
1600         stream_type == STREAM_TYPE_PRIVATE_DATA)
1601         mpegts_find_stream_type(st, desc_tag, DESC_types);
1602
1603     switch (desc_tag) {
1604     case 0x1E: /* SL descriptor */
1605         desc_es_id = get16(pp, desc_end);
1606         if (desc_es_id < 0)
1607             break;
1608         if (ts && ts->pids[pid])
1609             ts->pids[pid]->es_id = desc_es_id;
1610         for (i = 0; i < mp4_descr_count; i++)
1611             if (mp4_descr[i].dec_config_descr_len &&
1612                 mp4_descr[i].es_id == desc_es_id) {
1613                 AVIOContext pb;
1614                 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1615                                   mp4_descr[i].dec_config_descr_len, 0,
1616                                   NULL, NULL, NULL, NULL);
1617                 ff_mp4_read_dec_config_descr(fc, st, &pb);
1618                 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1619                     st->codec->extradata_size > 0)
1620                     st->need_parsing = 0;
1621                 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1622                     mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1623             }
1624         break;
1625     case 0x1F: /* FMC descriptor */
1626         if (get16(pp, desc_end) < 0)
1627             break;
1628         if (mp4_descr_count > 0 &&
1629             (st->codec->codec_id == AV_CODEC_ID_AAC_LATM ||
1630              (st->request_probe == 0 && st->codec->codec_id == AV_CODEC_ID_NONE) ||
1631              st->request_probe > 0) &&
1632             mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1633             AVIOContext pb;
1634             ffio_init_context(&pb, mp4_descr->dec_config_descr,
1635                               mp4_descr->dec_config_descr_len, 0,
1636                               NULL, NULL, NULL, NULL);
1637             ff_mp4_read_dec_config_descr(fc, st, &pb);
1638             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1639                 st->codec->extradata_size > 0) {
1640                 st->request_probe = st->need_parsing = 0;
1641                 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1642             }
1643         }
1644         break;
1645     case 0x56: /* DVB teletext descriptor */
1646         {
1647             uint8_t *extradata = NULL;
1648             int language_count = desc_len / 5;
1649
1650             if (desc_len > 0 && desc_len % 5 != 0)
1651                 return AVERROR_INVALIDDATA;
1652
1653             if (language_count > 0) {
1654                 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1655                 av_assert0(language_count <= sizeof(language) / 4);
1656
1657                 if (st->codec->extradata == NULL) {
1658                     if (ff_alloc_extradata(st->codec, language_count * 2)) {
1659                         return AVERROR(ENOMEM);
1660                     }
1661                 }
1662
1663                if (st->codec->extradata_size < language_count * 2)
1664                    return AVERROR_INVALIDDATA;
1665
1666                extradata = st->codec->extradata;
1667
1668                 for (i = 0; i < language_count; i++) {
1669                     language[i * 4 + 0] = get8(pp, desc_end);
1670                     language[i * 4 + 1] = get8(pp, desc_end);
1671                     language[i * 4 + 2] = get8(pp, desc_end);
1672                     language[i * 4 + 3] = ',';
1673
1674                     memcpy(extradata, *pp, 2);
1675                     extradata += 2;
1676
1677                     *pp += 2;
1678                 }
1679
1680                 language[i * 4 - 1] = 0;
1681                 av_dict_set(&st->metadata, "language", language, 0);
1682             }
1683         }
1684         break;
1685     case 0x59: /* subtitling descriptor */
1686         {
1687             /* 8 bytes per DVB subtitle substream data:
1688              * ISO_639_language_code (3 bytes),
1689              * subtitling_type (1 byte),
1690              * composition_page_id (2 bytes),
1691              * ancillary_page_id (2 bytes) */
1692             int language_count = desc_len / 8;
1693
1694             if (desc_len > 0 && desc_len % 8 != 0)
1695                 return AVERROR_INVALIDDATA;
1696
1697             if (language_count > 1) {
1698                 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
1699             }
1700
1701             if (language_count > 0) {
1702                 uint8_t *extradata;
1703
1704                 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1705                 av_assert0(language_count <= sizeof(language) / 4);
1706
1707                 if (st->codec->extradata == NULL) {
1708                     if (ff_alloc_extradata(st->codec, language_count * 5)) {
1709                         return AVERROR(ENOMEM);
1710                     }
1711                 }
1712
1713                 if (st->codec->extradata_size < language_count * 5)
1714                     return AVERROR_INVALIDDATA;
1715
1716                 extradata = st->codec->extradata;
1717
1718                 for (i = 0; i < language_count; i++) {
1719                     language[i * 4 + 0] = get8(pp, desc_end);
1720                     language[i * 4 + 1] = get8(pp, desc_end);
1721                     language[i * 4 + 2] = get8(pp, desc_end);
1722                     language[i * 4 + 3] = ',';
1723
1724                     /* hearing impaired subtitles detection using subtitling_type */
1725                     switch (*pp[0]) {
1726                     case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1727                     case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1728                     case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1729                     case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1730                     case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1731                     case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1732                         st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1733                         break;
1734                     }
1735
1736                     extradata[4] = get8(pp, desc_end); /* subtitling_type */
1737                     memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
1738                     extradata += 5;
1739
1740                     *pp += 4;
1741                 }
1742
1743                 language[i * 4 - 1] = 0;
1744                 av_dict_set(&st->metadata, "language", language, 0);
1745             }
1746         }
1747         break;
1748     case 0x0a: /* ISO 639 language descriptor */
1749         for (i = 0; i + 4 <= desc_len; i += 4) {
1750             language[i + 0] = get8(pp, desc_end);
1751             language[i + 1] = get8(pp, desc_end);
1752             language[i + 2] = get8(pp, desc_end);
1753             language[i + 3] = ',';
1754             switch (get8(pp, desc_end)) {
1755             case 0x01:
1756                 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
1757                 break;
1758             case 0x02:
1759                 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1760                 break;
1761             case 0x03:
1762                 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1763                 break;
1764             }
1765         }
1766         if (i && language[0]) {
1767             language[i - 1] = 0;
1768             av_dict_set(&st->metadata, "language", language, 0);
1769         }
1770         break;
1771     case 0x05: /* registration descriptor */
1772         st->codec->codec_tag = bytestream_get_le32(pp);
1773         av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);
1774         if (st->codec->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0)
1775             mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1776         break;
1777     case 0x52: /* stream identifier descriptor */
1778         st->stream_identifier = 1 + get8(pp, desc_end);
1779         break;
1780     case 0x26: /* metadata descriptor */
1781         if (get16(pp, desc_end) == 0xFFFF)
1782             *pp += 4;
1783         if (get8(pp, desc_end) == 0xFF) {
1784             st->codec->codec_tag = bytestream_get_le32(pp);
1785             if (st->codec->codec_id == AV_CODEC_ID_NONE)
1786                 mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
1787         }
1788         break;
1789     case 0x7f: /* DVB extension descriptor */
1790         ext_desc_tag = get8(pp, desc_end);
1791         if (ext_desc_tag < 0)
1792             return AVERROR_INVALIDDATA;
1793         if (st->codec->codec_id == AV_CODEC_ID_OPUS &&
1794             ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
1795             if (!st->codec->extradata) {
1796                 st->codec->extradata = av_mallocz(sizeof(opus_default_extradata) +
1797                                                   AV_INPUT_BUFFER_PADDING_SIZE);
1798                 if (!st->codec->extradata)
1799                     return AVERROR(ENOMEM);
1800
1801                 st->codec->extradata_size = sizeof(opus_default_extradata);
1802                 memcpy(st->codec->extradata, opus_default_extradata, sizeof(opus_default_extradata));
1803
1804                 channel_config_code = get8(pp, desc_end);
1805                 if (channel_config_code < 0)
1806                     return AVERROR_INVALIDDATA;
1807                 if (channel_config_code <= 0x8) {
1808                     st->codec->extradata[9]  = channels = channel_config_code ? channel_config_code : 2;
1809                     st->codec->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
1810                     st->codec->extradata[19] = opus_stream_cnt[channel_config_code];
1811                     st->codec->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
1812                     memcpy(&st->codec->extradata[21], opus_channel_map[channels - 1], channels);
1813                 } else {
1814                     avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
1815                 }
1816                 st->need_parsing = AVSTREAM_PARSE_FULL;
1817             }
1818         }
1819         break;
1820     default:
1821         break;
1822     }
1823     *pp = desc_end;
1824     return 0;
1825 }
1826
1827 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1828 {
1829     MpegTSContext *ts = filter->u.section_filter.opaque;
1830     MpegTSSectionFilter *tssf = &filter->u.section_filter;
1831     SectionHeader h1, *h = &h1;
1832     PESContext *pes;
1833     AVStream *st;
1834     const uint8_t *p, *p_end, *desc_list_end;
1835     int program_info_length, pcr_pid, pid, stream_type;
1836     int desc_list_len;
1837     uint32_t prog_reg_desc = 0; /* registration descriptor */
1838
1839     int mp4_descr_count = 0;
1840     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1841     int i;
1842
1843     av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
1844     hex_dump_debug(ts->stream, section, section_len);
1845
1846     p_end = section + section_len - 4;
1847     p = section;
1848     if (parse_section_header(h, &p, p_end) < 0)
1849         return;
1850     if (skip_identical(h, tssf))
1851         return;
1852
1853     av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d\n",
1854             h->id, h->sec_num, h->last_sec_num, h->version);
1855
1856     if (h->tid != PMT_TID)
1857         return;
1858     if (!ts->scan_all_pmts && ts->skip_changes)
1859         return;
1860
1861     if (!ts->skip_clear)
1862         clear_program(ts, h->id);
1863
1864     pcr_pid = get16(&p, p_end);
1865     if (pcr_pid < 0)
1866         return;
1867     pcr_pid &= 0x1fff;
1868     add_pid_to_pmt(ts, h->id, pcr_pid);
1869     set_pcr_pid(ts->stream, h->id, pcr_pid);
1870
1871     av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
1872
1873     program_info_length = get16(&p, p_end);
1874     if (program_info_length < 0)
1875         return;
1876     program_info_length &= 0xfff;
1877     while (program_info_length >= 2) {
1878         uint8_t tag, len;
1879         tag = get8(&p, p_end);
1880         len = get8(&p, p_end);
1881
1882         av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
1883
1884         if (len > program_info_length - 2)
1885             // something else is broken, exit the program_descriptors_loop
1886             break;
1887         program_info_length -= len + 2;
1888         if (tag == 0x1d) { // IOD descriptor
1889             get8(&p, p_end); // scope
1890             get8(&p, p_end); // label
1891             len -= 2;
1892             mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1893                           &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1894         } else if (tag == 0x05 && len >= 4) { // registration descriptor
1895             prog_reg_desc = bytestream_get_le32(&p);
1896             len -= 4;
1897         }
1898         p += len;
1899     }
1900     p += program_info_length;
1901     if (p >= p_end)
1902         goto out;
1903
1904     // stop parsing after pmt, we found header
1905     if (!ts->stream->nb_streams)
1906         ts->stop_parse = 2;
1907
1908     set_pmt_found(ts, h->id);
1909
1910
1911     for (;;) {
1912         st = 0;
1913         pes = NULL;
1914         stream_type = get8(&p, p_end);
1915         if (stream_type < 0)
1916             break;
1917         pid = get16(&p, p_end);
1918         if (pid < 0)
1919             goto out;
1920         pid &= 0x1fff;
1921         if (pid == ts->current_pid)
1922             goto out;
1923
1924         /* now create stream */
1925         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1926             pes = ts->pids[pid]->u.pes_filter.opaque;
1927             if (!pes->st) {
1928                 pes->st     = avformat_new_stream(pes->stream, NULL);
1929                 if (!pes->st)
1930                     goto out;
1931                 pes->st->id = pes->pid;
1932             }
1933             st = pes->st;
1934         } else if (stream_type != 0x13) {
1935             if (ts->pids[pid])
1936                 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
1937             pes = add_pes_stream(ts, pid, pcr_pid);
1938             if (pes) {
1939                 st = avformat_new_stream(pes->stream, NULL);
1940                 if (!st)
1941                     goto out;
1942                 st->id = pes->pid;
1943             }
1944         } else {
1945             int idx = ff_find_stream_index(ts->stream, pid);
1946             if (idx >= 0) {
1947                 st = ts->stream->streams[idx];
1948             } else {
1949                 st = avformat_new_stream(ts->stream, NULL);
1950                 if (!st)
1951                     goto out;
1952                 st->id = pid;
1953                 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1954             }
1955         }
1956
1957         if (!st)
1958             goto out;
1959
1960         if (pes && !pes->stream_type)
1961             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1962
1963         add_pid_to_pmt(ts, h->id, pid);
1964
1965         ff_program_add_stream_index(ts->stream, h->id, st->index);
1966
1967         desc_list_len = get16(&p, p_end);
1968         if (desc_list_len < 0)
1969             goto out;
1970         desc_list_len &= 0xfff;
1971         desc_list_end  = p + desc_list_len;
1972         if (desc_list_end > p_end)
1973             goto out;
1974         for (;;) {
1975             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
1976                                           desc_list_end, mp4_descr,
1977                                           mp4_descr_count, pid, ts) < 0)
1978                 break;
1979
1980             if (pes && prog_reg_desc == AV_RL32("HDMV") &&
1981                 stream_type == 0x83 && pes->sub_st) {
1982                 ff_program_add_stream_index(ts->stream, h->id,
1983                                             pes->sub_st->index);
1984                 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1985             }
1986         }
1987         p = desc_list_end;
1988     }
1989
1990     if (!ts->pids[pcr_pid])
1991         mpegts_open_pcr_filter(ts, pcr_pid);
1992
1993 out:
1994     for (i = 0; i < mp4_descr_count; i++)
1995         av_free(mp4_descr[i].dec_config_descr);
1996 }
1997
1998 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1999 {
2000     MpegTSContext *ts = filter->u.section_filter.opaque;
2001     MpegTSSectionFilter *tssf = &filter->u.section_filter;
2002     SectionHeader h1, *h = &h1;
2003     const uint8_t *p, *p_end;
2004     int sid, pmt_pid;
2005     AVProgram *program;
2006
2007     av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
2008     hex_dump_debug(ts->stream, section, section_len);
2009
2010     p_end = section + section_len - 4;
2011     p     = section;
2012     if (parse_section_header(h, &p, p_end) < 0)
2013         return;
2014     if (h->tid != PAT_TID)
2015         return;
2016     if (ts->skip_changes)
2017         return;
2018
2019     if (skip_identical(h, tssf))
2020         return;
2021     ts->stream->ts_id = h->id;
2022
2023     clear_programs(ts);
2024     for (;;) {
2025         sid = get16(&p, p_end);
2026         if (sid < 0)
2027             break;
2028         pmt_pid = get16(&p, p_end);
2029         if (pmt_pid < 0)
2030             break;
2031         pmt_pid &= 0x1fff;
2032
2033         if (pmt_pid == ts->current_pid)
2034             break;
2035
2036         av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
2037
2038         if (sid == 0x0000) {
2039             /* NIT info */
2040         } else {
2041             MpegTSFilter *fil = ts->pids[pmt_pid];
2042             program = av_new_program(ts->stream, sid);
2043             if (program) {
2044                 program->program_num = sid;
2045                 program->pmt_pid = pmt_pid;
2046             }
2047             if (fil)
2048                 if (   fil->type != MPEGTS_SECTION
2049                     || fil->pid != pmt_pid
2050                     || fil->u.section_filter.section_cb != pmt_cb)
2051                     mpegts_close_filter(ts, ts->pids[pmt_pid]);
2052
2053             if (!ts->pids[pmt_pid])
2054                 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
2055             add_pat_entry(ts, sid);
2056             add_pid_to_pmt(ts, sid, 0); // add pat pid to program
2057             add_pid_to_pmt(ts, sid, pmt_pid);
2058         }
2059     }
2060
2061     if (sid < 0) {
2062         int i,j;
2063         for (j=0; j<ts->stream->nb_programs; j++) {
2064             for (i = 0; i < ts->nb_prg; i++)
2065                 if (ts->prg[i].id == ts->stream->programs[j]->id)
2066                     break;
2067             if (i==ts->nb_prg && !ts->skip_clear)
2068                 clear_avprogram(ts, ts->stream->programs[j]->id);
2069         }
2070     }
2071 }
2072
2073 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2074 {
2075     MpegTSContext *ts = filter->u.section_filter.opaque;
2076     MpegTSSectionFilter *tssf = &filter->u.section_filter;
2077     SectionHeader h1, *h = &h1;
2078     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
2079     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
2080     char *name, *provider_name;
2081
2082     av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
2083     hex_dump_debug(ts->stream, section, section_len);
2084
2085     p_end = section + section_len - 4;
2086     p     = section;
2087     if (parse_section_header(h, &p, p_end) < 0)
2088         return;
2089     if (h->tid != SDT_TID)
2090         return;
2091     if (ts->skip_changes)
2092         return;
2093     if (skip_identical(h, tssf))
2094         return;
2095
2096     onid = get16(&p, p_end);
2097     if (onid < 0)
2098         return;
2099     val = get8(&p, p_end);
2100     if (val < 0)
2101         return;
2102     for (;;) {
2103         sid = get16(&p, p_end);
2104         if (sid < 0)
2105             break;
2106         val = get8(&p, p_end);
2107         if (val < 0)
2108             break;
2109         desc_list_len = get16(&p, p_end);
2110         if (desc_list_len < 0)
2111             break;
2112         desc_list_len &= 0xfff;
2113         desc_list_end  = p + desc_list_len;
2114         if (desc_list_end > p_end)
2115             break;
2116         for (;;) {
2117             desc_tag = get8(&p, desc_list_end);
2118             if (desc_tag < 0)
2119                 break;
2120             desc_len = get8(&p, desc_list_end);
2121             desc_end = p + desc_len;
2122             if (desc_len < 0 || desc_end > desc_list_end)
2123                 break;
2124
2125             av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
2126                     desc_tag, desc_len);
2127
2128             switch (desc_tag) {
2129             case 0x48:
2130                 service_type = get8(&p, p_end);
2131                 if (service_type < 0)
2132                     break;
2133                 provider_name = getstr8(&p, p_end);
2134                 if (!provider_name)
2135                     break;
2136                 name = getstr8(&p, p_end);
2137                 if (name) {
2138                     AVProgram *program = av_new_program(ts->stream, sid);
2139                     if (program) {
2140                         av_dict_set(&program->metadata, "service_name", name, 0);
2141                         av_dict_set(&program->metadata, "service_provider",
2142                                     provider_name, 0);
2143                     }
2144                 }
2145                 av_free(name);
2146                 av_free(provider_name);
2147                 break;
2148             default:
2149                 break;
2150             }
2151             p = desc_end;
2152         }
2153         p = desc_list_end;
2154     }
2155 }
2156
2157 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2158                      const uint8_t *packet);
2159
2160 /* handle one TS packet */
2161 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
2162 {
2163     MpegTSFilter *tss;
2164     int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
2165         has_adaptation, has_payload;
2166     const uint8_t *p, *p_end;
2167     int64_t pos;
2168
2169     pid = AV_RB16(packet + 1) & 0x1fff;
2170     if (pid && discard_pid(ts, pid))
2171         return 0;
2172     is_start = packet[1] & 0x40;
2173     tss = ts->pids[pid];
2174     if (ts->auto_guess && !tss && is_start) {
2175         add_pes_stream(ts, pid, -1);
2176         tss = ts->pids[pid];
2177     }
2178     if (!tss)
2179         return 0;
2180     ts->current_pid = pid;
2181
2182     afc = (packet[3] >> 4) & 3;
2183     if (afc == 0) /* reserved value */
2184         return 0;
2185     has_adaptation   = afc & 2;
2186     has_payload      = afc & 1;
2187     is_discontinuity = has_adaptation &&
2188                        packet[4] != 0 && /* with length > 0 */
2189                        (packet[5] & 0x80); /* and discontinuity indicated */
2190
2191     /* continuity check (currently not used) */
2192     cc = (packet[3] & 0xf);
2193     expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
2194     cc_ok = pid == 0x1FFF || // null packet PID
2195             is_discontinuity ||
2196             tss->last_cc < 0 ||
2197             expected_cc == cc;
2198
2199     tss->last_cc = cc;
2200     if (!cc_ok) {
2201         av_log(ts->stream, AV_LOG_DEBUG,
2202                "Continuity check failed for pid %d expected %d got %d\n",
2203                pid, expected_cc, cc);
2204         if (tss->type == MPEGTS_PES) {
2205             PESContext *pc = tss->u.pes_filter.opaque;
2206             pc->flags |= AV_PKT_FLAG_CORRUPT;
2207         }
2208     }
2209
2210     p = packet + 4;
2211     if (has_adaptation) {
2212         int64_t pcr_h;
2213         int pcr_l;
2214         if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
2215             tss->last_pcr = pcr_h * 300 + pcr_l;
2216         /* skip adaptation field */
2217         p += p[0] + 1;
2218     }
2219     /* if past the end of packet, ignore */
2220     p_end = packet + TS_PACKET_SIZE;
2221     if (p >= p_end || !has_payload)
2222         return 0;
2223
2224     pos = avio_tell(ts->stream->pb);
2225     if (pos >= 0) {
2226         av_assert0(pos >= TS_PACKET_SIZE);
2227         ts->pos47_full = pos - TS_PACKET_SIZE;
2228     }
2229
2230     if (tss->type == MPEGTS_SECTION) {
2231         if (is_start) {
2232             /* pointer field present */
2233             len = *p++;
2234             if (len > p_end - p)
2235                 return 0;
2236             if (len && cc_ok) {
2237                 /* write remaining section bytes */
2238                 write_section_data(ts, tss,
2239                                    p, len, 0);
2240                 /* check whether filter has been closed */
2241                 if (!ts->pids[pid])
2242                     return 0;
2243             }
2244             p += len;
2245             if (p < p_end) {
2246                 write_section_data(ts, tss,
2247                                    p, p_end - p, 1);
2248             }
2249         } else {
2250             if (cc_ok) {
2251                 write_section_data(ts, tss,
2252                                    p, p_end - p, 0);
2253             }
2254         }
2255
2256         // stop find_stream_info from waiting for more streams
2257         // when all programs have received a PMT
2258         if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
2259             int i;
2260             for (i = 0; i < ts->nb_prg; i++) {
2261                 if (!ts->prg[i].pmt_found)
2262                     break;
2263             }
2264             if (i == ts->nb_prg && ts->nb_prg > 0) {
2265                 int types = 0;
2266                 for (i = 0; i < ts->stream->nb_streams; i++) {
2267                     AVStream *st = ts->stream->streams[i];
2268                     types |= 1<<st->codec->codec_type;
2269                 }
2270                 if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
2271                     av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
2272                     ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
2273                 }
2274             }
2275         }
2276
2277     } else {
2278         int ret;
2279         // Note: The position here points actually behind the current packet.
2280         if (tss->type == MPEGTS_PES) {
2281             if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
2282                                                 pos - ts->raw_packet_size)) < 0)
2283                 return ret;
2284         }
2285     }
2286
2287     return 0;
2288 }
2289
2290 static void reanalyze(MpegTSContext *ts) {
2291     AVIOContext *pb = ts->stream->pb;
2292     int64_t pos = avio_tell(pb);
2293     if (pos < 0)
2294         return;
2295     pos -= ts->pos47_full;
2296     if (pos == TS_PACKET_SIZE) {
2297         ts->size_stat[0] ++;
2298     } else if (pos == TS_DVHS_PACKET_SIZE) {
2299         ts->size_stat[1] ++;
2300     } else if (pos == TS_FEC_PACKET_SIZE) {
2301         ts->size_stat[2] ++;
2302     }
2303
2304     ts->size_stat_count ++;
2305     if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
2306         int newsize = 0;
2307         if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
2308             newsize = TS_PACKET_SIZE;
2309         } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
2310             newsize = TS_DVHS_PACKET_SIZE;
2311         } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
2312             newsize = TS_FEC_PACKET_SIZE;
2313         }
2314         if (newsize && newsize != ts->raw_packet_size) {
2315             av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
2316             ts->raw_packet_size = newsize;
2317         }
2318         ts->size_stat_count = 0;
2319         memset(ts->size_stat, 0, sizeof(ts->size_stat));
2320     }
2321 }
2322
2323 /* XXX: try to find a better synchro over several packets (use
2324  * get_packet_size() ?) */
2325 static int mpegts_resync(AVFormatContext *s)
2326 {
2327     MpegTSContext *ts = s->priv_data;
2328     AVIOContext *pb = s->pb;
2329     int c, i;
2330
2331     for (i = 0; i < ts->resync_size; i++) {
2332         c = avio_r8(pb);
2333         if (avio_feof(pb))
2334             return AVERROR_EOF;
2335         if (c == 0x47) {
2336             avio_seek(pb, -1, SEEK_CUR);
2337             reanalyze(s->priv_data);
2338             return 0;
2339         }
2340     }
2341     av_log(s, AV_LOG_ERROR,
2342            "max resync size reached, could not find sync byte\n");
2343     /* no sync found */
2344     return AVERROR_INVALIDDATA;
2345 }
2346
2347 /* return AVERROR_something if error or EOF. Return 0 if OK. */
2348 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
2349                        const uint8_t **data)
2350 {
2351     AVIOContext *pb = s->pb;
2352     int len;
2353
2354     for (;;) {
2355         len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2356         if (len != TS_PACKET_SIZE)
2357             return len < 0 ? len : AVERROR_EOF;
2358         /* check packet sync byte */
2359         if ((*data)[0] != 0x47) {
2360             /* find a new packet start */
2361             uint64_t pos = avio_tell(pb);
2362             avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
2363
2364             if (mpegts_resync(s) < 0)
2365                 return AVERROR(EAGAIN);
2366             else
2367                 continue;
2368         } else {
2369             break;
2370         }
2371     }
2372     return 0;
2373 }
2374
2375 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2376 {
2377     AVIOContext *pb = s->pb;
2378     int skip = raw_packet_size - TS_PACKET_SIZE;
2379     if (skip > 0)
2380         avio_skip(pb, skip);
2381 }
2382
2383 static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
2384 {
2385     AVFormatContext *s = ts->stream;
2386     uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
2387     const uint8_t *data;
2388     int64_t packet_num;
2389     int ret = 0;
2390
2391     if (avio_tell(s->pb) != ts->last_pos) {
2392         int i;
2393         av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
2394         /* seek detected, flush pes buffer */
2395         for (i = 0; i < NB_PID_MAX; i++) {
2396             if (ts->pids[i]) {
2397                 if (ts->pids[i]->type == MPEGTS_PES) {
2398                     PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2399                     av_buffer_unref(&pes->buffer);
2400                     pes->data_index = 0;
2401                     pes->state = MPEGTS_SKIP; /* skip until pes header */
2402                 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
2403                     ts->pids[i]->u.section_filter.last_ver = -1;
2404                 }
2405                 ts->pids[i]->last_cc = -1;
2406                 ts->pids[i]->last_pcr = -1;
2407             }
2408         }
2409     }
2410
2411     ts->stop_parse = 0;
2412     packet_num = 0;
2413     memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2414     for (;;) {
2415         packet_num++;
2416         if (nb_packets != 0 && packet_num >= nb_packets ||
2417             ts->stop_parse > 1) {
2418             ret = AVERROR(EAGAIN);
2419             break;
2420         }
2421         if (ts->stop_parse > 0)
2422             break;
2423
2424         ret = read_packet(s, packet, ts->raw_packet_size, &data);
2425         if (ret != 0)
2426             break;
2427         ret = handle_packet(ts, data);
2428         finished_reading_packet(s, ts->raw_packet_size);
2429         if (ret != 0)
2430             break;
2431     }
2432     ts->last_pos = avio_tell(s->pb);
2433     return ret;
2434 }
2435
2436 static int mpegts_probe(AVProbeData *p)
2437 {
2438     const int size = p->buf_size;
2439     int maxscore = 0;
2440     int sumscore = 0;
2441     int i;
2442     int check_count = size / TS_FEC_PACKET_SIZE;
2443 #define CHECK_COUNT 10
2444 #define CHECK_BLOCK 100
2445
2446     if (check_count < CHECK_COUNT)
2447         return 0;
2448
2449     for (i = 0; i<check_count; i+=CHECK_BLOCK) {
2450         int left = FFMIN(check_count - i, CHECK_BLOCK);
2451         int score      = analyze(p->buf + TS_PACKET_SIZE     *i, TS_PACKET_SIZE     *left, TS_PACKET_SIZE     , NULL, 1);
2452         int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL, 1);
2453         int fec_score  = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL, 1);
2454         score = FFMAX3(score, dvhs_score, fec_score);
2455         sumscore += score;
2456         maxscore = FFMAX(maxscore, score);
2457     }
2458
2459     sumscore = sumscore * CHECK_COUNT / check_count;
2460     maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
2461
2462     ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2463
2464     if      (sumscore > 6) return AVPROBE_SCORE_MAX   + sumscore - CHECK_COUNT;
2465     else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2466     else
2467         return 0;
2468 }
2469
2470 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2471  * (-1) if not available */
2472 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
2473 {
2474     int afc, len, flags;
2475     const uint8_t *p;
2476     unsigned int v;
2477
2478     afc = (packet[3] >> 4) & 3;
2479     if (afc <= 1)
2480         return AVERROR_INVALIDDATA;
2481     p   = packet + 4;
2482     len = p[0];
2483     p++;
2484     if (len == 0)
2485         return AVERROR_INVALIDDATA;
2486     flags = *p++;
2487     len--;
2488     if (!(flags & 0x10))
2489         return AVERROR_INVALIDDATA;
2490     if (len < 6)
2491         return AVERROR_INVALIDDATA;
2492     v          = AV_RB32(p);
2493     *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
2494     *ppcr_low  = ((p[4] & 1) << 8) | p[5];
2495     return 0;
2496 }
2497
2498 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2499
2500     /* NOTE: We attempt to seek on non-seekable files as well, as the
2501      * probe buffer usually is big enough. Only warn if the seek failed
2502      * on files where the seek should work. */
2503     if (avio_seek(pb, pos, SEEK_SET) < 0)
2504         av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2505 }
2506
2507 static int mpegts_read_header(AVFormatContext *s)
2508 {
2509     MpegTSContext *ts = s->priv_data;
2510     AVIOContext *pb   = s->pb;
2511     uint8_t buf[8 * 1024] = {0};
2512     int len;
2513     int64_t pos, probesize = s->probesize ? s->probesize : s->probesize2;
2514
2515     if (ffio_ensure_seekback(pb, probesize) < 0)
2516         av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
2517
2518     /* read the first 8192 bytes to get packet size */
2519     pos = avio_tell(pb);
2520     len = avio_read(pb, buf, sizeof(buf));
2521     ts->raw_packet_size = get_packet_size(buf, len);
2522     if (ts->raw_packet_size <= 0) {
2523         av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2524         ts->raw_packet_size = TS_PACKET_SIZE;
2525     }
2526     ts->stream     = s;
2527     ts->auto_guess = 0;
2528
2529     if (s->iformat == &ff_mpegts_demuxer) {
2530         /* normal demux */
2531
2532         /* first do a scan to get all the services */
2533         seek_back(s, pb, pos);
2534
2535         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2536
2537         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2538
2539         handle_packets(ts, probesize / ts->raw_packet_size);
2540         /* if could not find service, enable auto_guess */
2541
2542         ts->auto_guess = 1;
2543
2544         av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
2545
2546         s->ctx_flags |= AVFMTCTX_NOHEADER;
2547     } else {
2548         AVStream *st;
2549         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2550         int64_t pcrs[2], pcr_h;
2551         int packet_count[2];
2552         uint8_t packet[TS_PACKET_SIZE];
2553         const uint8_t *data;
2554
2555         /* only read packets */
2556
2557         st = avformat_new_stream(s, NULL);
2558         if (!st)
2559             return AVERROR(ENOMEM);
2560         avpriv_set_pts_info(st, 60, 1, 27000000);
2561         st->codec->codec_type = AVMEDIA_TYPE_DATA;
2562         st->codec->codec_id   = AV_CODEC_ID_MPEG2TS;
2563
2564         /* we iterate until we find two PCRs to estimate the bitrate */
2565         pcr_pid    = -1;
2566         nb_pcrs    = 0;
2567         nb_packets = 0;
2568         for (;;) {
2569             ret = read_packet(s, packet, ts->raw_packet_size, &data);
2570             if (ret < 0)
2571                 return ret;
2572             pid = AV_RB16(data + 1) & 0x1fff;
2573             if ((pcr_pid == -1 || pcr_pid == pid) &&
2574                 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2575                 finished_reading_packet(s, ts->raw_packet_size);
2576                 pcr_pid = pid;
2577                 packet_count[nb_pcrs] = nb_packets;
2578                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2579                 nb_pcrs++;
2580                 if (nb_pcrs >= 2)
2581                     break;
2582             } else {
2583                 finished_reading_packet(s, ts->raw_packet_size);
2584             }
2585             nb_packets++;
2586         }
2587
2588         /* NOTE1: the bitrate is computed without the FEC */
2589         /* NOTE2: it is only the bitrate of the start of the stream */
2590         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2591         ts->cur_pcr  = pcrs[0] - ts->pcr_incr * packet_count[0];
2592         s->bit_rate  = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
2593         st->codec->bit_rate = s->bit_rate;
2594         st->start_time      = ts->cur_pcr;
2595         av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
2596                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2597     }
2598
2599     seek_back(s, pb, pos);
2600     return 0;
2601 }
2602
2603 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2604
2605 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
2606 {
2607     MpegTSContext *ts = s->priv_data;
2608     int ret, i;
2609     int64_t pcr_h, next_pcr_h, pos;
2610     int pcr_l, next_pcr_l;
2611     uint8_t pcr_buf[12];
2612     const uint8_t *data;
2613
2614     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2615         return AVERROR(ENOMEM);
2616     ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2617     pkt->pos = avio_tell(s->pb);
2618     if (ret < 0) {
2619         av_free_packet(pkt);
2620         return ret;
2621     }
2622     if (data != pkt->data)
2623         memcpy(pkt->data, data, ts->raw_packet_size);
2624     finished_reading_packet(s, ts->raw_packet_size);
2625     if (ts->mpeg2ts_compute_pcr) {
2626         /* compute exact PCR for each packet */
2627         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2628             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2629             pos = avio_tell(s->pb);
2630             for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
2631                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2632                 avio_read(s->pb, pcr_buf, 12);
2633                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2634                     /* XXX: not precise enough */
2635                     ts->pcr_incr =
2636                         ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2637                         (i + 1);
2638                     break;
2639                 }
2640             }
2641             avio_seek(s->pb, pos, SEEK_SET);
2642             /* no next PCR found: we use previous increment */
2643             ts->cur_pcr = pcr_h * 300 + pcr_l;
2644         }
2645         pkt->pts      = ts->cur_pcr;
2646         pkt->duration = ts->pcr_incr;
2647         ts->cur_pcr  += ts->pcr_incr;
2648     }
2649     pkt->stream_index = 0;
2650     return 0;
2651 }
2652
2653 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
2654 {
2655     MpegTSContext *ts = s->priv_data;
2656     int ret, i;
2657
2658     pkt->size = -1;
2659     ts->pkt = pkt;
2660     ret = handle_packets(ts, 0);
2661     if (ret < 0) {
2662         av_free_packet(ts->pkt);
2663         /* flush pes data left */
2664         for (i = 0; i < NB_PID_MAX; i++)
2665             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2666                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2667                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2668                     new_pes_packet(pes, pkt);
2669                     pes->state = MPEGTS_SKIP;
2670                     ret = 0;
2671                     break;
2672                 }
2673             }
2674     }
2675
2676     if (!ret && pkt->size < 0)
2677         ret = AVERROR(EINTR);
2678     return ret;
2679 }
2680
2681 static void mpegts_free(MpegTSContext *ts)
2682 {
2683     int i;
2684
2685     clear_programs(ts);
2686
2687     for (i = 0; i < NB_PID_MAX; i++)
2688         if (ts->pids[i])
2689             mpegts_close_filter(ts, ts->pids[i]);
2690 }
2691
2692 static int mpegts_read_close(AVFormatContext *s)
2693 {
2694     MpegTSContext *ts = s->priv_data;
2695     mpegts_free(ts);
2696     return 0;
2697 }
2698
2699 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2700                               int64_t *ppos, int64_t pos_limit)
2701 {
2702     MpegTSContext *ts = s->priv_data;
2703     int64_t pos, timestamp;
2704     uint8_t buf[TS_PACKET_SIZE];
2705     int pcr_l, pcr_pid =
2706         ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
2707     int pos47 = ts->pos47_full % ts->raw_packet_size;
2708     pos =
2709         ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
2710         ts->raw_packet_size + pos47;
2711     while(pos < pos_limit) {
2712         if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2713             return AV_NOPTS_VALUE;
2714         if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2715             return AV_NOPTS_VALUE;
2716         if (buf[0] != 0x47) {
2717             avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
2718             if (mpegts_resync(s) < 0)
2719                 return AV_NOPTS_VALUE;
2720             pos = avio_tell(s->pb);
2721             continue;
2722         }
2723         if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2724             parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2725             *ppos = pos;
2726             return timestamp;
2727         }
2728         pos += ts->raw_packet_size;
2729     }
2730
2731     return AV_NOPTS_VALUE;
2732 }
2733
2734 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2735                               int64_t *ppos, int64_t pos_limit)
2736 {
2737     MpegTSContext *ts = s->priv_data;
2738     int64_t pos;
2739     int pos47 = ts->pos47_full % ts->raw_packet_size;
2740     pos = ((*ppos  + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2741     ff_read_frame_flush(s);
2742     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2743         return AV_NOPTS_VALUE;
2744     while(pos < pos_limit) {
2745         int ret;
2746         AVPacket pkt;
2747         av_init_packet(&pkt);
2748         ret = av_read_frame(s, &pkt);
2749         if (ret < 0)
2750             return AV_NOPTS_VALUE;
2751         av_free_packet(&pkt);
2752         if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
2753             ff_reduce_index(s, pkt.stream_index);
2754             av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2755             if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
2756                 *ppos = pkt.pos;
2757                 return pkt.dts;
2758             }
2759         }
2760         pos = pkt.pos;
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 };