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