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