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