]> git.sesse.net Git - ffmpeg/blob - libavformat/mpegts.c
mov: Write prof section of tapt tag
[ffmpeg] / libavformat / mpegts.c
1 /*
2  * MPEG2 transport stream (aka DVB) demuxer
3  * Copyright (c) 2002-2003 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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/intreadwrite.h"
25 #include "libavutil/log.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/mathematics.h"
28 #include "libavutil/opt.h"
29 #include "libavcodec/bytestream.h"
30 #include "libavcodec/get_bits.h"
31 #include "avformat.h"
32 #include "mpegts.h"
33 #include "internal.h"
34 #include "avio_internal.h"
35 #include "seek.h"
36 #include "mpeg.h"
37 #include "isom.h"
38
39 /* maximum size in which we look for synchronisation if
40  * synchronisation is lost */
41 #define MAX_RESYNC_SIZE 65536
42
43 #define MAX_PES_PAYLOAD 200 * 1024
44
45 #define MAX_MP4_DESCR_COUNT 16
46
47 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend)                \
48     do {                                                                       \
49         if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
50             (modulus) = (dividend) % (divisor);                                \
51         (prev_dividend) = (dividend);                                          \
52     } while (0)
53
54 enum MpegTSFilterType {
55     MPEGTS_PES,
56     MPEGTS_SECTION,
57 };
58
59 typedef struct MpegTSFilter MpegTSFilter;
60
61 typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
62                          int is_start, int64_t pos);
63
64 typedef struct MpegTSPESFilter {
65     PESCallback *pes_cb;
66     void *opaque;
67 } MpegTSPESFilter;
68
69 typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
70
71 typedef void SetServiceCallback (void *opaque, int ret);
72
73 typedef struct MpegTSSectionFilter {
74     int section_index;
75     int section_h_size;
76     uint8_t *section_buf;
77     unsigned int check_crc : 1;
78     unsigned int end_of_section_reached : 1;
79     SectionCallback *section_cb;
80     void *opaque;
81 } MpegTSSectionFilter;
82
83 struct MpegTSFilter {
84     int pid;
85     int es_id;
86     int last_cc; /* last cc code (-1 if first packet) */
87     enum MpegTSFilterType type;
88     union {
89         MpegTSPESFilter pes_filter;
90         MpegTSSectionFilter section_filter;
91     } u;
92 };
93
94 #define MAX_PIDS_PER_PROGRAM 64
95 struct Program {
96     unsigned int id; // program id/service id
97     unsigned int nb_pids;
98     unsigned int pids[MAX_PIDS_PER_PROGRAM];
99 };
100
101 struct MpegTSContext {
102     const AVClass *class;
103     /* user data */
104     AVFormatContext *stream;
105     /** raw packet size, including FEC if present */
106     int raw_packet_size;
107
108     int pos47;
109     /** position corresponding to pos47, or 0 if pos47 invalid */
110     int64_t pos;
111
112     /** if true, all pids are analyzed to find streams */
113     int auto_guess;
114
115     /** compute exact PCR for each transport stream packet */
116     int mpeg2ts_compute_pcr;
117
118     int64_t cur_pcr;    /**< used to estimate the exact PCR */
119     int pcr_incr;       /**< used to estimate the exact PCR */
120
121     /* data needed to handle file based ts */
122     /** stop parsing loop */
123     int stop_parse;
124     /** packet containing Audio/Video data */
125     AVPacket *pkt;
126     /** to detect seek */
127     int64_t last_pos;
128
129     /******************************************/
130     /* private mpegts data */
131     /* scan context */
132     /** structure to keep track of Program->pids mapping */
133     unsigned int nb_prg;
134     struct Program *prg;
135
136     /** filters for various streams specified by PMT + for the PAT and PMT */
137     MpegTSFilter *pids[NB_PID_MAX];
138 };
139
140 static const AVOption options[] = {
141     { "compute_pcr",   "Compute exact PCR for each transport stream packet.",
142           offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
143           { .i64 = 0 }, 0, 1,  AV_OPT_FLAG_DECODING_PARAM },
144     { "ts_packetsize", "Output option carrying the raw packet size.",
145       offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
146       { .i64 = 0 }, 0, 0,
147       AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
148     { NULL },
149 };
150
151 static const AVClass mpegtsraw_class = {
152     .class_name = "mpegtsraw demuxer",
153     .item_name  = av_default_item_name,
154     .option     = options,
155     .version    = LIBAVUTIL_VERSION_INT,
156 };
157
158 /* TS stream handling */
159
160 enum MpegTSState {
161     MPEGTS_HEADER = 0,
162     MPEGTS_PESHEADER,
163     MPEGTS_PESHEADER_FILL,
164     MPEGTS_PAYLOAD,
165     MPEGTS_SKIP,
166 };
167
168 /* enough for PES header + length */
169 #define PES_START_SIZE  6
170 #define PES_HEADER_SIZE 9
171 #define MAX_PES_HEADER_SIZE (9 + 255)
172
173 typedef struct PESContext {
174     int pid;
175     int pcr_pid; /**< if -1 then all packets containing PCR are considered */
176     int stream_type;
177     MpegTSContext *ts;
178     AVFormatContext *stream;
179     AVStream *st;
180     AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
181     enum MpegTSState state;
182     /* used to get the format */
183     int data_index;
184     int flags; /**< copied to the AVPacket flags */
185     int total_size;
186     int pes_header_size;
187     int extended_stream_id;
188     int64_t pts, dts;
189     int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
190     uint8_t header[MAX_PES_HEADER_SIZE];
191     AVBufferRef *buffer;
192     SLConfigDescr sl;
193 } PESContext;
194
195 extern AVInputFormat ff_mpegts_demuxer;
196
197 static void clear_program(MpegTSContext *ts, unsigned int programid)
198 {
199     int i;
200
201     for (i = 0; i < ts->nb_prg; i++)
202         if (ts->prg[i].id == programid)
203             ts->prg[i].nb_pids = 0;
204 }
205
206 static void clear_programs(MpegTSContext *ts)
207 {
208     av_freep(&ts->prg);
209     ts->nb_prg = 0;
210 }
211
212 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
213 {
214     struct Program *p;
215     if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
216         ts->nb_prg = 0;
217         return;
218     }
219     p = &ts->prg[ts->nb_prg];
220     p->id = programid;
221     p->nb_pids = 0;
222     ts->nb_prg++;
223 }
224
225 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
226                            unsigned int pid)
227 {
228     int i;
229     struct Program *p = NULL;
230     for (i = 0; i < ts->nb_prg; i++) {
231         if (ts->prg[i].id == programid) {
232             p = &ts->prg[i];
233             break;
234         }
235     }
236     if (!p)
237         return;
238
239     if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
240         return;
241     p->pids[p->nb_pids++] = pid;
242 }
243
244 /**
245  * @brief discard_pid() decides if the pid is to be discarded according
246  *                      to caller's programs selection
247  * @param ts    : - TS context
248  * @param pid   : - pid
249  * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
250  *         0 otherwise
251  */
252 static int discard_pid(MpegTSContext *ts, unsigned int pid)
253 {
254     int i, j, k;
255     int used = 0, discarded = 0;
256     struct Program *p;
257
258     /* If none of the programs have .discard=AVDISCARD_ALL then there's
259      * no way we have to discard this packet */
260     for (k = 0; k < ts->stream->nb_programs; k++)
261         if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
262             break;
263     if (k == ts->stream->nb_programs)
264         return 0;
265
266     for (i = 0; i < ts->nb_prg; i++) {
267         p = &ts->prg[i];
268         for (j = 0; j < p->nb_pids; j++) {
269             if (p->pids[j] != pid)
270                 continue;
271             // is program with id p->id set to be discarded?
272             for (k = 0; k < ts->stream->nb_programs; k++) {
273                 if (ts->stream->programs[k]->id == p->id) {
274                     if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
275                         discarded++;
276                     else
277                         used++;
278                 }
279             }
280         }
281     }
282
283     return !used && discarded;
284 }
285
286 /**
287  *  Assemble PES packets out of TS packets, and then call the "section_cb"
288  *  function when they are complete.
289  */
290 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
291                                const uint8_t *buf, int buf_size, int is_start)
292 {
293     MpegTSSectionFilter *tss = &tss1->u.section_filter;
294     int len;
295
296     if (is_start) {
297         memcpy(tss->section_buf, buf, buf_size);
298         tss->section_index = buf_size;
299         tss->section_h_size = -1;
300         tss->end_of_section_reached = 0;
301     } else {
302         if (tss->end_of_section_reached)
303             return;
304         len = 4096 - tss->section_index;
305         if (buf_size < len)
306             len = buf_size;
307         memcpy(tss->section_buf + tss->section_index, buf, len);
308         tss->section_index += len;
309     }
310
311     /* compute section length if possible */
312     if (tss->section_h_size == -1 && tss->section_index >= 3) {
313         len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
314         if (len > 4096)
315             return;
316         tss->section_h_size = len;
317     }
318
319     if (tss->section_h_size != -1 &&
320         tss->section_index >= tss->section_h_size) {
321         tss->end_of_section_reached = 1;
322         if (!tss->check_crc ||
323             av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
324                    tss->section_buf, tss->section_h_size) == 0)
325             tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
326     }
327 }
328
329 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
330                                                 unsigned int pid,
331                                                 SectionCallback *section_cb,
332                                                 void *opaque,
333                                                 int check_crc)
334 {
335     MpegTSFilter *filter;
336     MpegTSSectionFilter *sec;
337
338     av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
339
340     if (pid >= NB_PID_MAX || ts->pids[pid])
341         return NULL;
342     filter = av_mallocz(sizeof(MpegTSFilter));
343     if (!filter)
344         return NULL;
345     ts->pids[pid] = filter;
346
347     filter->type    = MPEGTS_SECTION;
348     filter->pid     = pid;
349     filter->es_id   = -1;
350     filter->last_cc = -1;
351
352     sec = &filter->u.section_filter;
353     sec->section_cb  = section_cb;
354     sec->opaque      = opaque;
355     sec->section_buf = av_malloc(MAX_SECTION_SIZE);
356     sec->check_crc   = check_crc;
357     if (!sec->section_buf) {
358         av_free(filter);
359         return NULL;
360     }
361     return filter;
362 }
363
364 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
365                                             PESCallback *pes_cb,
366                                             void *opaque)
367 {
368     MpegTSFilter *filter;
369     MpegTSPESFilter *pes;
370
371     if (pid >= NB_PID_MAX || ts->pids[pid])
372         return NULL;
373     filter = av_mallocz(sizeof(MpegTSFilter));
374     if (!filter)
375         return NULL;
376
377     ts->pids[pid] = filter;
378     filter->type    = MPEGTS_PES;
379     filter->pid     = pid;
380     filter->es_id   = -1;
381     filter->last_cc = -1;
382
383     pes = &filter->u.pes_filter;
384     pes->pes_cb = pes_cb;
385     pes->opaque = opaque;
386     return filter;
387 }
388
389 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
390 {
391     int pid;
392
393     pid = filter->pid;
394     if (filter->type == MPEGTS_SECTION)
395         av_freep(&filter->u.section_filter.section_buf);
396     else if (filter->type == MPEGTS_PES) {
397         PESContext *pes = filter->u.pes_filter.opaque;
398         av_buffer_unref(&pes->buffer);
399         /* referenced private data will be freed later in
400          * avformat_close_input */
401         if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
402             av_freep(&filter->u.pes_filter.opaque);
403         }
404     }
405
406     av_free(filter);
407     ts->pids[pid] = NULL;
408 }
409
410 static int analyze(const uint8_t *buf, int size, int packet_size, int *index)
411 {
412     int stat[TS_MAX_PACKET_SIZE];
413     int i;
414     int x = 0;
415     int best_score = 0;
416
417     memset(stat, 0, packet_size * sizeof(int));
418
419     for (x = i = 0; i < size - 3; i++) {
420         if (buf[i] == 0x47 && !(buf[i + 1] & 0x80) && (buf[i + 3] & 0x30)) {
421             stat[x]++;
422             if (stat[x] > best_score) {
423                 best_score = stat[x];
424                 if (index)
425                     *index = x;
426             }
427         }
428
429         x++;
430         if (x == packet_size)
431             x = 0;
432     }
433
434     return best_score;
435 }
436
437 /* autodetect fec presence. Must have at least 1024 bytes  */
438 static int get_packet_size(const uint8_t *buf, int size)
439 {
440     int score, fec_score, dvhs_score;
441
442     if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
443         return AVERROR_INVALIDDATA;
444
445     score      = analyze(buf, size, TS_PACKET_SIZE, NULL);
446     dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
447     fec_score  = analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
448     av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
449             score, dvhs_score, fec_score);
450
451     if (score > fec_score && score > dvhs_score)
452         return TS_PACKET_SIZE;
453     else if (dvhs_score > score && dvhs_score > fec_score)
454         return TS_DVHS_PACKET_SIZE;
455     else if (score < fec_score && dvhs_score < fec_score)
456         return TS_FEC_PACKET_SIZE;
457     else
458         return AVERROR_INVALIDDATA;
459 }
460
461 typedef struct SectionHeader {
462     uint8_t tid;
463     uint16_t id;
464     uint8_t version;
465     uint8_t sec_num;
466     uint8_t last_sec_num;
467 } SectionHeader;
468
469 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
470 {
471     const uint8_t *p;
472     int c;
473
474     p = *pp;
475     if (p >= p_end)
476         return AVERROR_INVALIDDATA;
477     c   = *p++;
478     *pp = p;
479     return c;
480 }
481
482 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
483 {
484     const uint8_t *p;
485     int c;
486
487     p = *pp;
488     if ((p + 1) >= p_end)
489         return AVERROR_INVALIDDATA;
490     c   = AV_RB16(p);
491     p  += 2;
492     *pp = p;
493     return c;
494 }
495
496 /* read and allocate a DVB string preceded by its length */
497 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
498 {
499     int len;
500     const uint8_t *p;
501     char *str;
502
503     p   = *pp;
504     len = get8(&p, p_end);
505     if (len < 0)
506         return NULL;
507     if ((p + len) > p_end)
508         return NULL;
509     str = av_malloc(len + 1);
510     if (!str)
511         return NULL;
512     memcpy(str, p, len);
513     str[len] = '\0';
514     p  += len;
515     *pp = p;
516     return str;
517 }
518
519 static int parse_section_header(SectionHeader *h,
520                                 const uint8_t **pp, const uint8_t *p_end)
521 {
522     int val;
523
524     val = get8(pp, p_end);
525     if (val < 0)
526         return val;
527     h->tid = val;
528     *pp += 2;
529     val  = get16(pp, p_end);
530     if (val < 0)
531         return val;
532     h->id = val;
533     val = get8(pp, p_end);
534     if (val < 0)
535         return val;
536     h->version = (val >> 1) & 0x1f;
537     val = get8(pp, p_end);
538     if (val < 0)
539         return val;
540     h->sec_num = val;
541     val = get8(pp, p_end);
542     if (val < 0)
543         return val;
544     h->last_sec_num = val;
545     return 0;
546 }
547
548 typedef struct {
549     uint32_t stream_type;
550     enum AVMediaType codec_type;
551     enum AVCodecID codec_id;
552 } StreamType;
553
554 static const StreamType ISO_types[] = {
555     { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
556     { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
557     { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
558     { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3        },
559     { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC        },
560     { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4      },
561     { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM   }, /* LATM syntax */
562     { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264       },
563     { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC       },
564     { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS       },
565     { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC      },
566     { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1        },
567     { 0 },
568 };
569
570 static const StreamType HDMV_types[] = {
571     { 0x80, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_PCM_BLURAY        },
572     { 0x81, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3               },
573     { 0x82, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               },
574     { 0x83, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_TRUEHD            },
575     { 0x84, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3              },
576     { 0x85, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD */
577     { 0x86, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS               }, /* DTS HD MASTER*/
578     { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
579     { 0 },
580 };
581
582 /* ATSC ? */
583 static const StreamType MISC_types[] = {
584     { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
585     { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
586     { 0 },
587 };
588
589 static const StreamType REGD_types[] = {
590     { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
591     { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3   },
592     { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
593     { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
594     { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
595     { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS   },
596     { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC  },
597     { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1   },
598     { 0 },
599 };
600
601 /* descriptor present */
602 static const StreamType DESC_types[] = {
603     { 0x6a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_AC3          }, /* AC-3 descriptor */
604     { 0x7a, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_EAC3         }, /* E-AC-3 descriptor */
605     { 0x7b, AVMEDIA_TYPE_AUDIO,    AV_CODEC_ID_DTS          },
606     { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
607     { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
608     { 0 },
609 };
610
611 static void mpegts_find_stream_type(AVStream *st,
612                                     uint32_t stream_type,
613                                     const StreamType *types)
614 {
615     for (; types->stream_type; types++)
616         if (stream_type == types->stream_type) {
617             st->codec->codec_type = types->codec_type;
618             st->codec->codec_id   = types->codec_id;
619             return;
620         }
621 }
622
623 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
624                                   uint32_t stream_type, uint32_t prog_reg_desc)
625 {
626     avpriv_set_pts_info(st, 33, 1, 90000);
627     st->priv_data         = pes;
628     st->codec->codec_type = AVMEDIA_TYPE_DATA;
629     st->codec->codec_id   = AV_CODEC_ID_NONE;
630     st->need_parsing      = AVSTREAM_PARSE_FULL;
631     pes->st          = st;
632     pes->stream_type = stream_type;
633
634     av_log(pes->stream, AV_LOG_DEBUG,
635            "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
636            st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
637
638     st->codec->codec_tag = pes->stream_type;
639
640     mpegts_find_stream_type(st, pes->stream_type, ISO_types);
641     if (prog_reg_desc == AV_RL32("HDMV") &&
642         st->codec->codec_id == AV_CODEC_ID_NONE) {
643         mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
644         if (pes->stream_type == 0x83) {
645             // HDMV TrueHD streams also contain an AC3 coded version of the
646             // audio track - add a second stream for this
647             AVStream *sub_st;
648             // priv_data cannot be shared between streams
649             PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
650             if (!sub_pes)
651                 return AVERROR(ENOMEM);
652             memcpy(sub_pes, pes, sizeof(*sub_pes));
653
654             sub_st = avformat_new_stream(pes->stream, NULL);
655             if (!sub_st) {
656                 av_free(sub_pes);
657                 return AVERROR(ENOMEM);
658             }
659
660             sub_st->id = pes->pid;
661             avpriv_set_pts_info(sub_st, 33, 1, 90000);
662             sub_st->priv_data         = sub_pes;
663             sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
664             sub_st->codec->codec_id   = AV_CODEC_ID_AC3;
665             sub_st->need_parsing      = AVSTREAM_PARSE_FULL;
666             sub_pes->sub_st           = pes->sub_st = sub_st;
667         }
668     }
669     if (st->codec->codec_id == AV_CODEC_ID_NONE)
670         mpegts_find_stream_type(st, pes->stream_type, MISC_types);
671
672     return 0;
673 }
674
675 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
676 {
677     av_init_packet(pkt);
678
679     pkt->buf  = pes->buffer;
680     pkt->data = pes->buffer->data;
681     pkt->size = pes->data_index;
682
683     if (pes->total_size != MAX_PES_PAYLOAD &&
684         pes->pes_header_size + pes->data_index != pes->total_size +
685         PES_START_SIZE) {
686         av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
687         pes->flags |= AV_PKT_FLAG_CORRUPT;
688     }
689     memset(pkt->data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
690
691     // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
692     if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
693         pkt->stream_index = pes->sub_st->index;
694     else
695         pkt->stream_index = pes->st->index;
696     pkt->pts = pes->pts;
697     pkt->dts = pes->dts;
698     /* store position of first TS packet of this PES packet */
699     pkt->pos   = pes->ts_packet_pos;
700     pkt->flags = pes->flags;
701
702     /* reset pts values */
703     pes->pts        = AV_NOPTS_VALUE;
704     pes->dts        = AV_NOPTS_VALUE;
705     pes->buffer     = NULL;
706     pes->data_index = 0;
707     pes->flags      = 0;
708 }
709
710 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
711                           const uint8_t *buf, int buf_size)
712 {
713     GetBitContext gb;
714     int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
715     int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
716     int dts_flag = -1, cts_flag = -1;
717     int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
718     init_get_bits(&gb, buf, buf_size * 8);
719
720     if (sl->use_au_start)
721         au_start_flag = get_bits1(&gb);
722     if (sl->use_au_end)
723         au_end_flag = get_bits1(&gb);
724     if (!sl->use_au_start && !sl->use_au_end)
725         au_start_flag = au_end_flag = 1;
726     if (sl->ocr_len > 0)
727         ocr_flag = get_bits1(&gb);
728     if (sl->use_idle)
729         idle_flag = get_bits1(&gb);
730     if (sl->use_padding)
731         padding_flag = get_bits1(&gb);
732     if (padding_flag)
733         padding_bits = get_bits(&gb, 3);
734
735     if (!idle_flag && (!padding_flag || padding_bits != 0)) {
736         if (sl->packet_seq_num_len)
737             skip_bits_long(&gb, sl->packet_seq_num_len);
738         if (sl->degr_prior_len)
739             if (get_bits1(&gb))
740                 skip_bits(&gb, sl->degr_prior_len);
741         if (ocr_flag)
742             skip_bits_long(&gb, sl->ocr_len);
743         if (au_start_flag) {
744             if (sl->use_rand_acc_pt)
745                 get_bits1(&gb);
746             if (sl->au_seq_num_len > 0)
747                 skip_bits_long(&gb, sl->au_seq_num_len);
748             if (sl->use_timestamps) {
749                 dts_flag = get_bits1(&gb);
750                 cts_flag = get_bits1(&gb);
751             }
752         }
753         if (sl->inst_bitrate_len)
754             inst_bitrate_flag = get_bits1(&gb);
755         if (dts_flag == 1)
756             dts = get_bits64(&gb, sl->timestamp_len);
757         if (cts_flag == 1)
758             cts = get_bits64(&gb, sl->timestamp_len);
759         if (sl->au_len > 0)
760             skip_bits_long(&gb, sl->au_len);
761         if (inst_bitrate_flag)
762             skip_bits_long(&gb, sl->inst_bitrate_len);
763     }
764
765     if (dts != AV_NOPTS_VALUE)
766         pes->dts = dts;
767     if (cts != AV_NOPTS_VALUE)
768         pes->pts = cts;
769
770     if (sl->timestamp_len && sl->timestamp_res)
771         avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
772
773     return (get_bits_count(&gb) + 7) >> 3;
774 }
775
776 /* return non zero if a packet could be constructed */
777 static int mpegts_push_data(MpegTSFilter *filter,
778                             const uint8_t *buf, int buf_size, int is_start,
779                             int64_t pos)
780 {
781     PESContext *pes   = filter->u.pes_filter.opaque;
782     MpegTSContext *ts = pes->ts;
783     const uint8_t *p;
784     int len, code;
785
786     if (!ts->pkt)
787         return 0;
788
789     if (is_start) {
790         if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
791             new_pes_packet(pes, ts->pkt);
792             ts->stop_parse = 1;
793         }
794         pes->state         = MPEGTS_HEADER;
795         pes->data_index    = 0;
796         pes->ts_packet_pos = pos;
797     }
798     p = buf;
799     while (buf_size > 0) {
800         switch (pes->state) {
801         case MPEGTS_HEADER:
802             len = PES_START_SIZE - pes->data_index;
803             if (len > buf_size)
804                 len = buf_size;
805             memcpy(pes->header + pes->data_index, p, len);
806             pes->data_index += len;
807             p += len;
808             buf_size -= len;
809             if (pes->data_index == PES_START_SIZE) {
810                 /* we got all the PES or section header. We can now
811                  * decide */
812                 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
813                     pes->header[2] == 0x01) {
814                     /* it must be an mpeg2 PES stream */
815                     code = pes->header[3] | 0x100;
816                     av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid,
817                             code);
818
819                     if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
820                          (!pes->sub_st ||
821                           pes->sub_st->discard == AVDISCARD_ALL)) ||
822                         code == 0x1be) /* padding_stream */
823                         goto skip;
824
825                     /* stream not present in PMT */
826                     if (!pes->st) {
827                         pes->st = avformat_new_stream(ts->stream, NULL);
828                         if (!pes->st)
829                             return AVERROR(ENOMEM);
830                         pes->st->id = pes->pid;
831                         mpegts_set_stream_info(pes->st, pes, 0, 0);
832                     }
833
834                     pes->total_size = AV_RB16(pes->header + 4);
835                     /* NOTE: a zero total size means the PES size is
836                      * unbounded */
837                     if (!pes->total_size)
838                         pes->total_size = MAX_PES_PAYLOAD;
839
840                     /* allocate pes buffer */
841                     pes->buffer = av_buffer_alloc(pes->total_size +
842                                                   FF_INPUT_BUFFER_PADDING_SIZE);
843                     if (!pes->buffer)
844                         return AVERROR(ENOMEM);
845
846                     if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
847                         code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
848                         code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
849                         code != 0x1f8) {                  /* ITU-T Rec. H.222.1 type E stream */
850                         pes->state = MPEGTS_PESHEADER;
851                         if (pes->st->codec->codec_id == AV_CODEC_ID_NONE) {
852                             av_dlog(pes->stream,
853                                     "pid=%x stream_type=%x probing\n",
854                                     pes->pid,
855                                     pes->stream_type);
856                             pes->st->codec->codec_id = AV_CODEC_ID_PROBE;
857                         }
858                     } else {
859                         pes->state      = MPEGTS_PAYLOAD;
860                         pes->data_index = 0;
861                     }
862                 } else {
863                     /* otherwise, it should be a table */
864                     /* skip packet */
865 skip:
866                     pes->state = MPEGTS_SKIP;
867                     continue;
868                 }
869             }
870             break;
871         /**********************************************/
872         /* PES packing parsing */
873         case MPEGTS_PESHEADER:
874             len = PES_HEADER_SIZE - pes->data_index;
875             if (len < 0)
876                 return AVERROR_INVALIDDATA;
877             if (len > buf_size)
878                 len = buf_size;
879             memcpy(pes->header + pes->data_index, p, len);
880             pes->data_index += len;
881             p += len;
882             buf_size -= len;
883             if (pes->data_index == PES_HEADER_SIZE) {
884                 pes->pes_header_size = pes->header[8] + 9;
885                 pes->state           = MPEGTS_PESHEADER_FILL;
886             }
887             break;
888         case MPEGTS_PESHEADER_FILL:
889             len = pes->pes_header_size - pes->data_index;
890             if (len < 0)
891                 return AVERROR_INVALIDDATA;
892             if (len > buf_size)
893                 len = buf_size;
894             memcpy(pes->header + pes->data_index, p, len);
895             pes->data_index += len;
896             p += len;
897             buf_size -= len;
898             if (pes->data_index == pes->pes_header_size) {
899                 const uint8_t *r;
900                 unsigned int flags, pes_ext, skip;
901
902                 flags = pes->header[7];
903                 r = pes->header + 9;
904                 pes->pts = AV_NOPTS_VALUE;
905                 pes->dts = AV_NOPTS_VALUE;
906                 if ((flags & 0xc0) == 0x80) {
907                     pes->dts = pes->pts = ff_parse_pes_pts(r);
908                     r += 5;
909                 } else if ((flags & 0xc0) == 0xc0) {
910                     pes->pts = ff_parse_pes_pts(r);
911                     r += 5;
912                     pes->dts = ff_parse_pes_pts(r);
913                     r += 5;
914                 }
915                 pes->extended_stream_id = -1;
916                 if (flags & 0x01) { /* PES extension */
917                     pes_ext = *r++;
918                     /* Skip PES private data, program packet sequence counter and P-STD buffer */
919                     skip  = (pes_ext >> 4) & 0xb;
920                     skip += skip & 0x9;
921                     r    += skip;
922                     if ((pes_ext & 0x41) == 0x01 &&
923                         (r + 2) <= (pes->header + pes->pes_header_size)) {
924                         /* PES extension 2 */
925                         if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
926                             pes->extended_stream_id = r[1];
927                     }
928                 }
929
930                 /* we got the full header. We parse it and get the payload */
931                 pes->state = MPEGTS_PAYLOAD;
932                 pes->data_index = 0;
933                 if (pes->stream_type == 0x12 && buf_size > 0) {
934                     int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
935                                                          buf_size);
936                     pes->pes_header_size += sl_header_bytes;
937                     p += sl_header_bytes;
938                     buf_size -= sl_header_bytes;
939                 }
940             }
941             break;
942         case MPEGTS_PAYLOAD:
943             if (buf_size > 0 && pes->buffer) {
944                 if (pes->data_index > 0 &&
945                     pes->data_index + buf_size > pes->total_size) {
946                     new_pes_packet(pes, ts->pkt);
947                     pes->total_size = MAX_PES_PAYLOAD;
948                     pes->buffer = av_buffer_alloc(pes->total_size +
949                                                   FF_INPUT_BUFFER_PADDING_SIZE);
950                     if (!pes->buffer)
951                         return AVERROR(ENOMEM);
952                     ts->stop_parse = 1;
953                 } else if (pes->data_index == 0 &&
954                            buf_size > pes->total_size) {
955                     // pes packet size is < ts size packet and pes data is padded with 0xff
956                     // not sure if this is legal in ts but see issue #2392
957                     buf_size = pes->total_size;
958                 }
959                 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
960                 pes->data_index += buf_size;
961             }
962             buf_size = 0;
963             /* emit complete packets with known packet size
964              * decreases demuxer delay for infrequent packets like subtitles from
965              * a couple of seconds to milliseconds for properly muxed files.
966              * total_size is the number of bytes following pes_packet_length
967              * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
968             if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
969                 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
970                 ts->stop_parse = 1;
971                 new_pes_packet(pes, ts->pkt);
972             }
973             break;
974         case MPEGTS_SKIP:
975             buf_size = 0;
976             break;
977         }
978     }
979
980     return 0;
981 }
982
983 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
984 {
985     MpegTSFilter *tss;
986     PESContext *pes;
987
988     /* if no pid found, then add a pid context */
989     pes = av_mallocz(sizeof(PESContext));
990     if (!pes)
991         return 0;
992     pes->ts      = ts;
993     pes->stream  = ts->stream;
994     pes->pid     = pid;
995     pes->pcr_pid = pcr_pid;
996     pes->state   = MPEGTS_SKIP;
997     pes->pts     = AV_NOPTS_VALUE;
998     pes->dts     = AV_NOPTS_VALUE;
999     tss          = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1000     if (!tss) {
1001         av_free(pes);
1002         return 0;
1003     }
1004     return pes;
1005 }
1006
1007 #define MAX_LEVEL 4
1008 typedef struct {
1009     AVFormatContext *s;
1010     AVIOContext pb;
1011     Mp4Descr *descr;
1012     Mp4Descr *active_descr;
1013     int descr_count;
1014     int max_descr_count;
1015     int level;
1016 } MP4DescrParseContext;
1017
1018 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
1019                                      const uint8_t *buf, unsigned size,
1020                                      Mp4Descr *descr, int max_descr_count)
1021 {
1022     int ret;
1023     if (size > (1 << 30))
1024         return AVERROR_INVALIDDATA;
1025
1026     if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
1027                                  NULL, NULL, NULL, NULL)) < 0)
1028         return ret;
1029
1030     d->s               = s;
1031     d->level           = 0;
1032     d->descr_count     = 0;
1033     d->descr           = descr;
1034     d->active_descr    = NULL;
1035     d->max_descr_count = max_descr_count;
1036
1037     return 0;
1038 }
1039
1040 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1041 {
1042     int64_t new_off = avio_tell(pb);
1043     (*len) -= new_off - *off;
1044     *off    = new_off;
1045 }
1046
1047 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1048                            int target_tag);
1049
1050 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1051 {
1052     while (len > 0) {
1053         int ret = parse_mp4_descr(d, off, len, 0);
1054         if (ret < 0)
1055             return ret;
1056         update_offsets(&d->pb, &off, &len);
1057     }
1058     return 0;
1059 }
1060
1061 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1062 {
1063     avio_rb16(&d->pb); // ID
1064     avio_r8(&d->pb);
1065     avio_r8(&d->pb);
1066     avio_r8(&d->pb);
1067     avio_r8(&d->pb);
1068     avio_r8(&d->pb);
1069     update_offsets(&d->pb, &off, &len);
1070     return parse_mp4_descr_arr(d, off, len);
1071 }
1072
1073 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1074 {
1075     int id_flags;
1076     if (len < 2)
1077         return 0;
1078     id_flags = avio_rb16(&d->pb);
1079     if (!(id_flags & 0x0020)) { // URL_Flag
1080         update_offsets(&d->pb, &off, &len);
1081         return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1082     } else {
1083         return 0;
1084     }
1085 }
1086
1087 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1088 {
1089     int es_id = 0;
1090     if (d->descr_count >= d->max_descr_count)
1091         return AVERROR_INVALIDDATA;
1092     ff_mp4_parse_es_descr(&d->pb, &es_id);
1093     d->active_descr = d->descr + (d->descr_count++);
1094
1095     d->active_descr->es_id = es_id;
1096     update_offsets(&d->pb, &off, &len);
1097     parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1098     update_offsets(&d->pb, &off, &len);
1099     if (len > 0)
1100         parse_mp4_descr(d, off, len, MP4SLDescrTag);
1101     d->active_descr = NULL;
1102     return 0;
1103 }
1104
1105 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
1106                                       int len)
1107 {
1108     Mp4Descr *descr = d->active_descr;
1109     if (!descr)
1110         return AVERROR_INVALIDDATA;
1111     d->active_descr->dec_config_descr = av_malloc(len);
1112     if (!descr->dec_config_descr)
1113         return AVERROR(ENOMEM);
1114     descr->dec_config_descr_len = len;
1115     avio_read(&d->pb, descr->dec_config_descr, len);
1116     return 0;
1117 }
1118
1119 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1120 {
1121     Mp4Descr *descr = d->active_descr;
1122     int predefined;
1123     if (!descr)
1124         return AVERROR_INVALIDDATA;
1125
1126     predefined = avio_r8(&d->pb);
1127     if (!predefined) {
1128         int lengths;
1129         int flags = avio_r8(&d->pb);
1130         descr->sl.use_au_start    = !!(flags & 0x80);
1131         descr->sl.use_au_end      = !!(flags & 0x40);
1132         descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1133         descr->sl.use_padding     = !!(flags & 0x08);
1134         descr->sl.use_timestamps  = !!(flags & 0x04);
1135         descr->sl.use_idle        = !!(flags & 0x02);
1136         descr->sl.timestamp_res   = avio_rb32(&d->pb);
1137         avio_rb32(&d->pb);
1138         descr->sl.timestamp_len      = avio_r8(&d->pb);
1139         descr->sl.ocr_len            = avio_r8(&d->pb);
1140         descr->sl.au_len             = avio_r8(&d->pb);
1141         descr->sl.inst_bitrate_len   = avio_r8(&d->pb);
1142         lengths                      = avio_rb16(&d->pb);
1143         descr->sl.degr_prior_len     = lengths >> 12;
1144         descr->sl.au_seq_num_len     = (lengths >> 7) & 0x1f;
1145         descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1146     } else {
1147         avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1148     }
1149     return 0;
1150 }
1151
1152 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1153                            int target_tag)
1154 {
1155     int tag;
1156     int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1157     update_offsets(&d->pb, &off, &len);
1158     if (len < 0 || len1 > len || len1 <= 0) {
1159         av_log(d->s, AV_LOG_ERROR,
1160                "Tag %x length violation new length %d bytes remaining %d\n",
1161                tag, len1, len);
1162         return AVERROR_INVALIDDATA;
1163     }
1164
1165     if (d->level++ >= MAX_LEVEL) {
1166         av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1167         goto done;
1168     }
1169
1170     if (target_tag && tag != target_tag) {
1171         av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1172                target_tag);
1173         goto done;
1174     }
1175
1176     switch (tag) {
1177     case MP4IODescrTag:
1178         parse_MP4IODescrTag(d, off, len1);
1179         break;
1180     case MP4ODescrTag:
1181         parse_MP4ODescrTag(d, off, len1);
1182         break;
1183     case MP4ESDescrTag:
1184         parse_MP4ESDescrTag(d, off, len1);
1185         break;
1186     case MP4DecConfigDescrTag:
1187         parse_MP4DecConfigDescrTag(d, off, len1);
1188         break;
1189     case MP4SLDescrTag:
1190         parse_MP4SLDescrTag(d, off, len1);
1191         break;
1192     }
1193
1194
1195 done:
1196     d->level--;
1197     avio_seek(&d->pb, off + len1, SEEK_SET);
1198     return 0;
1199 }
1200
1201 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1202                          Mp4Descr *descr, int *descr_count, int max_descr_count)
1203 {
1204     MP4DescrParseContext d;
1205     int ret;
1206
1207     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1208     if (ret < 0)
1209         return ret;
1210
1211     ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1212
1213     *descr_count = d.descr_count;
1214     return ret;
1215 }
1216
1217 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1218                        Mp4Descr *descr, int *descr_count, int max_descr_count)
1219 {
1220     MP4DescrParseContext d;
1221     int ret;
1222
1223     ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1224     if (ret < 0)
1225         return ret;
1226
1227     ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1228
1229     *descr_count = d.descr_count;
1230     return ret;
1231 }
1232
1233 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1234                     int section_len)
1235 {
1236     MpegTSContext *ts = filter->u.section_filter.opaque;
1237     SectionHeader h;
1238     const uint8_t *p, *p_end;
1239     AVIOContext pb;
1240     int mp4_descr_count = 0;
1241     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1242     int i, pid;
1243     AVFormatContext *s = ts->stream;
1244
1245     p_end = section + section_len - 4;
1246     p = section;
1247     if (parse_section_header(&h, &p, p_end) < 0)
1248         return;
1249     if (h.tid != M4OD_TID)
1250         return;
1251
1252     mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1253                 MAX_MP4_DESCR_COUNT);
1254
1255     for (pid = 0; pid < NB_PID_MAX; pid++) {
1256         if (!ts->pids[pid])
1257             continue;
1258         for (i = 0; i < mp4_descr_count; i++) {
1259             PESContext *pes;
1260             AVStream *st;
1261             if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1262                 continue;
1263             if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1264                 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1265                 continue;
1266             }
1267             pes = ts->pids[pid]->u.pes_filter.opaque;
1268             st  = pes->st;
1269             if (!st)
1270                 continue;
1271
1272             pes->sl = mp4_descr[i].sl;
1273
1274             ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1275                               mp4_descr[i].dec_config_descr_len, 0,
1276                               NULL, NULL, NULL, NULL);
1277             ff_mp4_read_dec_config_descr(s, st, &pb);
1278             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1279                 st->codec->extradata_size > 0)
1280                 st->need_parsing = 0;
1281             if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1282                 st->codec->extradata_size > 0)
1283                 st->need_parsing = 0;
1284
1285             if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1286                 // do nothing
1287             } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO)
1288                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1289             else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
1290                 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1291             else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
1292                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1293         }
1294     }
1295     for (i = 0; i < mp4_descr_count; i++)
1296         av_free(mp4_descr[i].dec_config_descr);
1297 }
1298
1299 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1300                               const uint8_t **pp, const uint8_t *desc_list_end,
1301                               Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1302                               MpegTSContext *ts)
1303 {
1304     const uint8_t *desc_end;
1305     int desc_len, desc_tag, desc_es_id;
1306     char language[252];
1307     int i;
1308
1309     desc_tag = get8(pp, desc_list_end);
1310     if (desc_tag < 0)
1311         return AVERROR_INVALIDDATA;
1312     desc_len = get8(pp, desc_list_end);
1313     if (desc_len < 0)
1314         return AVERROR_INVALIDDATA;
1315     desc_end = *pp + desc_len;
1316     if (desc_end > desc_list_end)
1317         return AVERROR_INVALIDDATA;
1318
1319     av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1320
1321     if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1322         stream_type == STREAM_TYPE_PRIVATE_DATA)
1323         mpegts_find_stream_type(st, desc_tag, DESC_types);
1324
1325     switch (desc_tag) {
1326     case 0x1E: /* SL descriptor */
1327         desc_es_id = get16(pp, desc_end);
1328         if (ts && ts->pids[pid])
1329             ts->pids[pid]->es_id = desc_es_id;
1330         for (i = 0; i < mp4_descr_count; i++)
1331             if (mp4_descr[i].dec_config_descr_len &&
1332                 mp4_descr[i].es_id == desc_es_id) {
1333                 AVIOContext pb;
1334                 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1335                                   mp4_descr[i].dec_config_descr_len, 0,
1336                                   NULL, NULL, NULL, NULL);
1337                 ff_mp4_read_dec_config_descr(fc, st, &pb);
1338                 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1339                     st->codec->extradata_size > 0)
1340                     st->need_parsing = 0;
1341                 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1342                     mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1343             }
1344         break;
1345     case 0x1F: /* FMC descriptor */
1346         get16(pp, desc_end);
1347         if (mp4_descr_count > 0 &&
1348             st->codec->codec_id == AV_CODEC_ID_AAC_LATM &&
1349             mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1350             AVIOContext pb;
1351             ffio_init_context(&pb, mp4_descr->dec_config_descr,
1352                               mp4_descr->dec_config_descr_len, 0,
1353                               NULL, NULL, NULL, NULL);
1354             ff_mp4_read_dec_config_descr(fc, st, &pb);
1355             if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1356                 st->codec->extradata_size > 0)
1357                 st->need_parsing = 0;
1358         }
1359         break;
1360     case 0x56: /* DVB teletext descriptor */
1361         language[0] = get8(pp, desc_end);
1362         language[1] = get8(pp, desc_end);
1363         language[2] = get8(pp, desc_end);
1364         language[3] = 0;
1365         av_dict_set(&st->metadata, "language", language, 0);
1366         break;
1367     case 0x59: /* subtitling descriptor */
1368         language[0] = get8(pp, desc_end);
1369         language[1] = get8(pp, desc_end);
1370         language[2] = get8(pp, desc_end);
1371         language[3] = 0;
1372         /* hearing impaired subtitles detection */
1373         switch (get8(pp, desc_end)) {
1374         case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1375         case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1376         case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1377         case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1378         case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1379         case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1380             st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1381             break;
1382         }
1383         if (st->codec->extradata) {
1384             if (st->codec->extradata_size == 4 &&
1385                 memcmp(st->codec->extradata, *pp, 4))
1386                 avpriv_request_sample(fc, "DVB sub with multiple IDs");
1387         } else {
1388             st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
1389             if (st->codec->extradata) {
1390                 st->codec->extradata_size = 4;
1391                 memcpy(st->codec->extradata, *pp, 4);
1392             }
1393         }
1394         *pp += 4;
1395         av_dict_set(&st->metadata, "language", language, 0);
1396         break;
1397     case 0x0a: /* ISO 639 language descriptor */
1398         for (i = 0; i + 4 <= desc_len; i += 4) {
1399             language[i + 0] = get8(pp, desc_end);
1400             language[i + 1] = get8(pp, desc_end);
1401             language[i + 2] = get8(pp, desc_end);
1402             language[i + 3] = ',';
1403             switch (get8(pp, desc_end)) {
1404             case 0x01:
1405                 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
1406                 break;
1407             case 0x02:
1408                 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1409                 break;
1410             case 0x03:
1411                 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1412                 break;
1413             }
1414         }
1415         if (i) {
1416             language[i - 1] = 0;
1417             av_dict_set(&st->metadata, "language", language, 0);
1418         }
1419         break;
1420     case 0x05: /* registration descriptor */
1421         st->codec->codec_tag = bytestream_get_le32(pp);
1422         av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag);
1423         if (st->codec->codec_id == AV_CODEC_ID_NONE)
1424             mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1425         break;
1426     default:
1427         break;
1428     }
1429     *pp = desc_end;
1430     return 0;
1431 }
1432
1433 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1434 {
1435     MpegTSContext *ts = filter->u.section_filter.opaque;
1436     SectionHeader h1, *h = &h1;
1437     PESContext *pes;
1438     AVStream *st;
1439     const uint8_t *p, *p_end, *desc_list_end;
1440     int program_info_length, pcr_pid, pid, stream_type;
1441     int desc_list_len;
1442     uint32_t prog_reg_desc = 0; /* registration descriptor */
1443
1444     int mp4_descr_count = 0;
1445     Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1446     int i;
1447
1448     av_dlog(ts->stream, "PMT: len %i\n", section_len);
1449     hex_dump_debug(ts->stream, section, section_len);
1450
1451     p_end = section + section_len - 4;
1452     p = section;
1453     if (parse_section_header(h, &p, p_end) < 0)
1454         return;
1455
1456     av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1457             h->id, h->sec_num, h->last_sec_num);
1458
1459     if (h->tid != PMT_TID)
1460         return;
1461
1462     clear_program(ts, h->id);
1463     pcr_pid = get16(&p, p_end);
1464     if (pcr_pid < 0)
1465         return;
1466     pcr_pid &= 0x1fff;
1467     add_pid_to_pmt(ts, h->id, pcr_pid);
1468
1469     av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1470
1471     program_info_length = get16(&p, p_end);
1472     if (program_info_length < 0)
1473         return;
1474     program_info_length &= 0xfff;
1475     while (program_info_length >= 2) {
1476         uint8_t tag, len;
1477         tag = get8(&p, p_end);
1478         len = get8(&p, p_end);
1479
1480         av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1481
1482         if (len > program_info_length - 2)
1483             // something else is broken, exit the program_descriptors_loop
1484             break;
1485         program_info_length -= len + 2;
1486         if (tag == 0x1d) { // IOD descriptor
1487             get8(&p, p_end); // scope
1488             get8(&p, p_end); // label
1489             len -= 2;
1490             mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1491                           &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1492         } else if (tag == 0x05 && len >= 4) { // registration descriptor
1493             prog_reg_desc = bytestream_get_le32(&p);
1494             len -= 4;
1495         }
1496         p += len;
1497     }
1498     p += program_info_length;
1499     if (p >= p_end)
1500         goto out;
1501
1502     // stop parsing after pmt, we found header
1503     if (!ts->stream->nb_streams)
1504         ts->stop_parse = 1;
1505
1506
1507     for (;;) {
1508         st = 0;
1509         pes = NULL;
1510         stream_type = get8(&p, p_end);
1511         if (stream_type < 0)
1512             break;
1513         pid = get16(&p, p_end);
1514         if (pid < 0)
1515             break;
1516         pid &= 0x1fff;
1517
1518         /* now create stream */
1519         if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1520             pes = ts->pids[pid]->u.pes_filter.opaque;
1521             if (!pes->st) {
1522                 pes->st     = avformat_new_stream(pes->stream, NULL);
1523                 pes->st->id = pes->pid;
1524             }
1525             st = pes->st;
1526         } else if (stream_type != 0x13) {
1527             if (ts->pids[pid])
1528                 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
1529             pes = add_pes_stream(ts, pid, pcr_pid);
1530             if (pes) {
1531                 st = avformat_new_stream(pes->stream, NULL);
1532                 st->id = pes->pid;
1533             }
1534         } else {
1535             int idx = ff_find_stream_index(ts->stream, pid);
1536             if (idx >= 0) {
1537                 st = ts->stream->streams[idx];
1538             } else {
1539                 st = avformat_new_stream(ts->stream, NULL);
1540                 st->id = pid;
1541                 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1542             }
1543         }
1544
1545         if (!st)
1546             goto out;
1547
1548         if (pes && !pes->stream_type)
1549             mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1550
1551         add_pid_to_pmt(ts, h->id, pid);
1552
1553         ff_program_add_stream_index(ts->stream, h->id, st->index);
1554
1555         desc_list_len = get16(&p, p_end);
1556         if (desc_list_len < 0)
1557             break;
1558         desc_list_len &= 0xfff;
1559         desc_list_end  = p + desc_list_len;
1560         if (desc_list_end > p_end)
1561             break;
1562         for (;;) {
1563             if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
1564                                           desc_list_end, mp4_descr,
1565                                           mp4_descr_count, pid, ts) < 0)
1566                 break;
1567
1568             if (pes && prog_reg_desc == AV_RL32("HDMV") &&
1569                 stream_type == 0x83 && pes->sub_st) {
1570                 ff_program_add_stream_index(ts->stream, h->id,
1571                                             pes->sub_st->index);
1572                 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1573             }
1574         }
1575         p = desc_list_end;
1576     }
1577
1578 out:
1579     for (i = 0; i < mp4_descr_count; i++)
1580         av_free(mp4_descr[i].dec_config_descr);
1581 }
1582
1583 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1584 {
1585     MpegTSContext *ts = filter->u.section_filter.opaque;
1586     SectionHeader h1, *h = &h1;
1587     const uint8_t *p, *p_end;
1588     int sid, pmt_pid;
1589
1590     av_dlog(ts->stream, "PAT:\n");
1591     hex_dump_debug(ts->stream, section, section_len);
1592
1593     p_end = section + section_len - 4;
1594     p     = section;
1595     if (parse_section_header(h, &p, p_end) < 0)
1596         return;
1597     if (h->tid != PAT_TID)
1598         return;
1599
1600     clear_programs(ts);
1601     for (;;) {
1602         sid = get16(&p, p_end);
1603         if (sid < 0)
1604             break;
1605         pmt_pid = get16(&p, p_end);
1606         if (pmt_pid < 0)
1607             break;
1608         pmt_pid &= 0x1fff;
1609
1610         av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1611
1612         if (sid == 0x0000) {
1613             /* NIT info */
1614         } else {
1615             av_new_program(ts->stream, sid);
1616             if (ts->pids[pmt_pid])
1617                 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1618             mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1619             add_pat_entry(ts, sid);
1620             add_pid_to_pmt(ts, sid, 0); // add pat pid to program
1621             add_pid_to_pmt(ts, sid, pmt_pid);
1622         }
1623     }
1624 }
1625
1626 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1627 {
1628     MpegTSContext *ts = filter->u.section_filter.opaque;
1629     SectionHeader h1, *h = &h1;
1630     const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1631     int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1632     char *name, *provider_name;
1633
1634     av_dlog(ts->stream, "SDT:\n");
1635     hex_dump_debug(ts->stream, section, section_len);
1636
1637     p_end = section + section_len - 4;
1638     p     = section;
1639     if (parse_section_header(h, &p, p_end) < 0)
1640         return;
1641     if (h->tid != SDT_TID)
1642         return;
1643     onid = get16(&p, p_end);
1644     if (onid < 0)
1645         return;
1646     val = get8(&p, p_end);
1647     if (val < 0)
1648         return;
1649     for (;;) {
1650         sid = get16(&p, p_end);
1651         if (sid < 0)
1652             break;
1653         val = get8(&p, p_end);
1654         if (val < 0)
1655             break;
1656         desc_list_len = get16(&p, p_end);
1657         if (desc_list_len < 0)
1658             break;
1659         desc_list_len &= 0xfff;
1660         desc_list_end  = p + desc_list_len;
1661         if (desc_list_end > p_end)
1662             break;
1663         for (;;) {
1664             desc_tag = get8(&p, desc_list_end);
1665             if (desc_tag < 0)
1666                 break;
1667             desc_len = get8(&p, desc_list_end);
1668             desc_end = p + desc_len;
1669             if (desc_end > desc_list_end)
1670                 break;
1671
1672             av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1673                     desc_tag, desc_len);
1674
1675             switch (desc_tag) {
1676             case 0x48:
1677                 service_type = get8(&p, p_end);
1678                 if (service_type < 0)
1679                     break;
1680                 provider_name = getstr8(&p, p_end);
1681                 if (!provider_name)
1682                     break;
1683                 name = getstr8(&p, p_end);
1684                 if (name) {
1685                     AVProgram *program = av_new_program(ts->stream, sid);
1686                     if (program) {
1687                         av_dict_set(&program->metadata, "service_name", name, 0);
1688                         av_dict_set(&program->metadata, "service_provider",
1689                                     provider_name, 0);
1690                     }
1691                 }
1692                 av_free(name);
1693                 av_free(provider_name);
1694                 break;
1695             default:
1696                 break;
1697             }
1698             p = desc_end;
1699         }
1700         p = desc_list_end;
1701     }
1702 }
1703
1704 /* handle one TS packet */
1705 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1706 {
1707     AVFormatContext *s = ts->stream;
1708     MpegTSFilter *tss;
1709     int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1710         has_adaptation, has_payload;
1711     const uint8_t *p, *p_end;
1712     int64_t pos;
1713
1714     pid = AV_RB16(packet + 1) & 0x1fff;
1715     if (pid && discard_pid(ts, pid))
1716         return 0;
1717     is_start = packet[1] & 0x40;
1718     tss = ts->pids[pid];
1719     if (ts->auto_guess && tss == NULL && is_start) {
1720         add_pes_stream(ts, pid, -1);
1721         tss = ts->pids[pid];
1722     }
1723     if (!tss)
1724         return 0;
1725
1726     afc = (packet[3] >> 4) & 3;
1727     if (afc == 0) /* reserved value */
1728         return 0;
1729     has_adaptation   = afc & 2;
1730     has_payload      = afc & 1;
1731     is_discontinuity = has_adaptation &&
1732                        packet[4] != 0 && /* with length > 0 */
1733                        (packet[5] & 0x80); /* and discontinuity indicated */
1734
1735     /* continuity check (currently not used) */
1736     cc = (packet[3] & 0xf);
1737     expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1738     cc_ok = pid == 0x1FFF || // null packet PID
1739             is_discontinuity ||
1740             tss->last_cc < 0 ||
1741             expected_cc == cc;
1742
1743     tss->last_cc = cc;
1744     if (!cc_ok) {
1745         av_log(ts->stream, AV_LOG_WARNING,
1746                "Continuity check failed for pid %d expected %d got %d\n",
1747                pid, expected_cc, cc);
1748         if (tss->type == MPEGTS_PES) {
1749             PESContext *pc = tss->u.pes_filter.opaque;
1750             pc->flags |= AV_PKT_FLAG_CORRUPT;
1751         }
1752     }
1753
1754     if (!has_payload)
1755         return 0;
1756     p = packet + 4;
1757     if (has_adaptation) {
1758         /* skip adaptation field */
1759         p += p[0] + 1;
1760     }
1761     /* if past the end of packet, ignore */
1762     p_end = packet + TS_PACKET_SIZE;
1763     if (p >= p_end)
1764         return 0;
1765
1766     pos = avio_tell(ts->stream->pb);
1767     MOD_UNLIKELY(ts->pos47, pos, ts->raw_packet_size, ts->pos);
1768
1769     if (tss->type == MPEGTS_SECTION) {
1770         if (is_start) {
1771             /* pointer field present */
1772             len = *p++;
1773             if (p + len > p_end)
1774                 return 0;
1775             if (len && cc_ok) {
1776                 /* write remaining section bytes */
1777                 write_section_data(s, tss,
1778                                    p, len, 0);
1779                 /* check whether filter has been closed */
1780                 if (!ts->pids[pid])
1781                     return 0;
1782             }
1783             p += len;
1784             if (p < p_end) {
1785                 write_section_data(s, tss,
1786                                    p, p_end - p, 1);
1787             }
1788         } else {
1789             if (cc_ok) {
1790                 write_section_data(s, tss,
1791                                    p, p_end - p, 0);
1792             }
1793         }
1794     } else {
1795         int ret;
1796         // Note: The position here points actually behind the current packet.
1797         if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1798                                             pos - ts->raw_packet_size)) < 0)
1799             return ret;
1800     }
1801
1802     return 0;
1803 }
1804
1805 /* XXX: try to find a better synchro over several packets (use
1806  * get_packet_size() ?) */
1807 static int mpegts_resync(AVFormatContext *s)
1808 {
1809     AVIOContext *pb = s->pb;
1810     int c, i;
1811
1812     for (i = 0; i < MAX_RESYNC_SIZE; i++) {
1813         c = avio_r8(pb);
1814         if (pb->eof_reached)
1815             return AVERROR_EOF;
1816         if (c == 0x47) {
1817             avio_seek(pb, -1, SEEK_CUR);
1818             return 0;
1819         }
1820     }
1821     av_log(s, AV_LOG_ERROR,
1822            "max resync size reached, could not find sync byte\n");
1823     /* no sync found */
1824     return AVERROR_INVALIDDATA;
1825 }
1826
1827 /* return AVERROR_something if error or EOF. Return 0 if OK. */
1828 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
1829                        const uint8_t **data)
1830 {
1831     AVIOContext *pb = s->pb;
1832     int len;
1833
1834     for (;;) {
1835         len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
1836         if (len != TS_PACKET_SIZE)
1837             return len < 0 ? len : AVERROR_EOF;
1838         /* check packet sync byte */
1839         if ((*data)[0] != 0x47) {
1840             /* find a new packet start */
1841             avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1842             if (mpegts_resync(s) < 0)
1843                 return AVERROR(EAGAIN);
1844             else
1845                 continue;
1846         } else {
1847             break;
1848         }
1849     }
1850     return 0;
1851 }
1852
1853 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
1854 {
1855     AVIOContext *pb = s->pb;
1856     int skip = raw_packet_size - TS_PACKET_SIZE;
1857     if (skip > 0)
1858         avio_skip(pb, skip);
1859 }
1860
1861 static int handle_packets(MpegTSContext *ts, int nb_packets)
1862 {
1863     AVFormatContext *s = ts->stream;
1864     uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
1865     const uint8_t *data;
1866     int packet_num, ret = 0;
1867
1868     if (avio_tell(s->pb) != ts->last_pos) {
1869         int i;
1870         av_dlog(ts->stream, "Skipping after seek\n");
1871         /* seek detected, flush pes buffer */
1872         for (i = 0; i < NB_PID_MAX; i++) {
1873             if (ts->pids[i]) {
1874                 if (ts->pids[i]->type == MPEGTS_PES) {
1875                     PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1876                     av_buffer_unref(&pes->buffer);
1877                     pes->data_index = 0;
1878                     pes->state = MPEGTS_SKIP; /* skip until pes header */
1879                 }
1880                 ts->pids[i]->last_cc = -1;
1881             }
1882         }
1883     }
1884
1885     ts->stop_parse = 0;
1886     packet_num = 0;
1887     memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1888     for (;;) {
1889         if (ts->stop_parse > 0)
1890             break;
1891         packet_num++;
1892         if (nb_packets != 0 && packet_num >= nb_packets)
1893             break;
1894         ret = read_packet(s, packet, ts->raw_packet_size, &data);
1895         if (ret != 0)
1896             break;
1897         ret = handle_packet(ts, data);
1898         finished_reading_packet(s, ts->raw_packet_size);
1899         if (ret != 0)
1900             break;
1901     }
1902     ts->last_pos = avio_tell(s->pb);
1903     return ret;
1904 }
1905
1906 static int mpegts_probe(AVProbeData *p)
1907 {
1908     const int size = p->buf_size;
1909     int score, fec_score, dvhs_score;
1910     int check_count = size / TS_FEC_PACKET_SIZE;
1911 #define CHECK_COUNT 10
1912
1913     if (check_count < CHECK_COUNT)
1914         return AVERROR_INVALIDDATA;
1915
1916     score = analyze(p->buf, TS_PACKET_SIZE * check_count,
1917                     TS_PACKET_SIZE, NULL) * CHECK_COUNT / check_count;
1918     dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE * check_count,
1919                          TS_DVHS_PACKET_SIZE, NULL) * CHECK_COUNT / check_count;
1920     fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE * check_count,
1921                         TS_FEC_PACKET_SIZE, NULL) * CHECK_COUNT / check_count;
1922     av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
1923             score, dvhs_score, fec_score);
1924
1925     /* we need a clear definition for the returned score otherwise
1926      * things will become messy sooner or later */
1927     if (score > fec_score && score > dvhs_score && score > 6)
1928         return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1929     else if (dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6)
1930         return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1931     else if (fec_score > 6)
1932         return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1933     else
1934         return AVERROR_INVALIDDATA;
1935 }
1936
1937 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1938  * (-1) if not available */
1939 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
1940 {
1941     int afc, len, flags;
1942     const uint8_t *p;
1943     unsigned int v;
1944
1945     afc = (packet[3] >> 4) & 3;
1946     if (afc <= 1)
1947         return AVERROR_INVALIDDATA;
1948     p   = packet + 4;
1949     len = p[0];
1950     p++;
1951     if (len == 0)
1952         return AVERROR_INVALIDDATA;
1953     flags = *p++;
1954     len--;
1955     if (!(flags & 0x10))
1956         return AVERROR_INVALIDDATA;
1957     if (len < 6)
1958         return AVERROR_INVALIDDATA;
1959     v          = AV_RB32(p);
1960     *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
1961     *ppcr_low  = ((p[4] & 1) << 8) | p[5];
1962     return 0;
1963 }
1964
1965 static int mpegts_read_header(AVFormatContext *s)
1966 {
1967     MpegTSContext *ts = s->priv_data;
1968     AVIOContext *pb   = s->pb;
1969     uint8_t buf[5 * 1024];
1970     int len;
1971     int64_t pos;
1972
1973     /* read the first 1024 bytes to get packet size */
1974     pos = avio_tell(pb);
1975     len = avio_read(pb, buf, sizeof(buf));
1976     if (len < 0)
1977         return len;
1978     if (len != sizeof(buf))
1979         return AVERROR_BUG;
1980     ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1981     if (ts->raw_packet_size <= 0)
1982         return AVERROR_INVALIDDATA;
1983     ts->stream     = s;
1984     ts->auto_guess = 0;
1985
1986     if (s->iformat == &ff_mpegts_demuxer) {
1987         /* normal demux */
1988
1989         /* first do a scan to get all the services */
1990         if (avio_seek(pb, pos, SEEK_SET) < 0 && pb->seekable)
1991             av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1992
1993         mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1994
1995         mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1996
1997         handle_packets(ts, s->probesize / ts->raw_packet_size);
1998         /* if could not find service, enable auto_guess */
1999
2000         ts->auto_guess = 1;
2001
2002         av_dlog(ts->stream, "tuning done\n");
2003
2004         s->ctx_flags |= AVFMTCTX_NOHEADER;
2005     } else {
2006         AVStream *st;
2007         int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2008         int64_t pcrs[2], pcr_h;
2009         int packet_count[2];
2010         uint8_t packet[TS_PACKET_SIZE];
2011         const uint8_t *data;
2012
2013         /* only read packets */
2014
2015         st = avformat_new_stream(s, NULL);
2016         if (!st)
2017             return AVERROR(ENOMEM);
2018         avpriv_set_pts_info(st, 60, 1, 27000000);
2019         st->codec->codec_type = AVMEDIA_TYPE_DATA;
2020         st->codec->codec_id   = AV_CODEC_ID_MPEG2TS;
2021
2022         /* we iterate until we find two PCRs to estimate the bitrate */
2023         pcr_pid    = -1;
2024         nb_pcrs    = 0;
2025         nb_packets = 0;
2026         for (;;) {
2027             ret = read_packet(s, packet, ts->raw_packet_size, &data);
2028             if (ret < 0)
2029                 return ret;
2030             pid = AV_RB16(data + 1) & 0x1fff;
2031             if ((pcr_pid == -1 || pcr_pid == pid) &&
2032                 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2033                 finished_reading_packet(s, ts->raw_packet_size);
2034                 pcr_pid = pid;
2035                 packet_count[nb_pcrs] = nb_packets;
2036                 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2037                 nb_pcrs++;
2038                 if (nb_pcrs >= 2)
2039                     break;
2040             } else {
2041                 finished_reading_packet(s, ts->raw_packet_size);
2042             }
2043             nb_packets++;
2044         }
2045
2046         /* NOTE1: the bitrate is computed without the FEC */
2047         /* NOTE2: it is only the bitrate of the start of the stream */
2048         ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2049         ts->cur_pcr  = pcrs[0] - ts->pcr_incr * packet_count[0];
2050         s->bit_rate  = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr;
2051         st->codec->bit_rate = s->bit_rate;
2052         st->start_time      = ts->cur_pcr;
2053         av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2054                 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2055     }
2056
2057     avio_seek(pb, pos, SEEK_SET);
2058     return 0;
2059 }
2060
2061 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2062
2063 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
2064 {
2065     MpegTSContext *ts = s->priv_data;
2066     int ret, i;
2067     int64_t pcr_h, next_pcr_h, pos;
2068     int pcr_l, next_pcr_l;
2069     uint8_t pcr_buf[12];
2070     const uint8_t *data;
2071
2072     if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2073         return AVERROR(ENOMEM);
2074     ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2075     pkt->pos = avio_tell(s->pb);
2076     if (ret < 0) {
2077         av_free_packet(pkt);
2078         return ret;
2079     }
2080     if (data != pkt->data)
2081         memcpy(pkt->data, data, ts->raw_packet_size);
2082     finished_reading_packet(s, ts->raw_packet_size);
2083     if (ts->mpeg2ts_compute_pcr) {
2084         /* compute exact PCR for each packet */
2085         if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2086             /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2087             pos = avio_tell(s->pb);
2088             for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
2089                 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2090                 avio_read(s->pb, pcr_buf, 12);
2091                 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2092                     /* XXX: not precise enough */
2093                     ts->pcr_incr =
2094                         ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2095                         (i + 1);
2096                     break;
2097                 }
2098             }
2099             avio_seek(s->pb, pos, SEEK_SET);
2100             /* no next PCR found: we use previous increment */
2101             ts->cur_pcr = pcr_h * 300 + pcr_l;
2102         }
2103         pkt->pts      = ts->cur_pcr;
2104         pkt->duration = ts->pcr_incr;
2105         ts->cur_pcr  += ts->pcr_incr;
2106     }
2107     pkt->stream_index = 0;
2108     return 0;
2109 }
2110
2111 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
2112 {
2113     MpegTSContext *ts = s->priv_data;
2114     int ret, i;
2115
2116     pkt->size = -1;
2117     ts->pkt = pkt;
2118     ret = handle_packets(ts, 0);
2119     if (ret < 0) {
2120         /* flush pes data left */
2121         for (i = 0; i < NB_PID_MAX; i++)
2122             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2123                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2124                 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2125                     new_pes_packet(pes, pkt);
2126                     pes->state = MPEGTS_SKIP;
2127                     ret = 0;
2128                     break;
2129                 }
2130             }
2131     }
2132
2133     if (!ret && pkt->size < 0)
2134         ret = AVERROR(EINTR);
2135     return ret;
2136 }
2137
2138 static void mpegts_free(MpegTSContext *ts)
2139 {
2140     int i;
2141
2142     clear_programs(ts);
2143
2144     for (i = 0; i < NB_PID_MAX; i++)
2145         if (ts->pids[i])
2146             mpegts_close_filter(ts, ts->pids[i]);
2147 }
2148
2149 static int mpegts_read_close(AVFormatContext *s)
2150 {
2151     MpegTSContext *ts = s->priv_data;
2152     mpegts_free(ts);
2153     return 0;
2154 }
2155
2156 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2157                               int64_t *ppos, int64_t pos_limit)
2158 {
2159     MpegTSContext *ts = s->priv_data;
2160     int64_t pos, timestamp;
2161     uint8_t buf[TS_PACKET_SIZE];
2162     int pcr_l, pcr_pid =
2163         ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
2164     const int find_next = 1;
2165     pos =
2166         ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) *
2167         ts->raw_packet_size + ts->pos47;
2168     if (find_next) {
2169         for (;;) {
2170             avio_seek(s->pb, pos, SEEK_SET);
2171             if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2172                 return AV_NOPTS_VALUE;
2173             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2174                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2175                 break;
2176             }
2177             pos += ts->raw_packet_size;
2178         }
2179     } else {
2180         for (;;) {
2181             pos -= ts->raw_packet_size;
2182             if (pos < 0)
2183                 return AV_NOPTS_VALUE;
2184             avio_seek(s->pb, pos, SEEK_SET);
2185             if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2186                 return AV_NOPTS_VALUE;
2187             if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2188                 parse_pcr(&timestamp, &pcr_l, buf) == 0) {
2189                 break;
2190             }
2191         }
2192     }
2193     *ppos = pos;
2194
2195     return timestamp;
2196 }
2197
2198 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
2199 {
2200     MpegTSContext *ts = s->priv_data;
2201     uint8_t buf[TS_PACKET_SIZE];
2202     int64_t pos;
2203     int ret;
2204
2205     ret = ff_seek_frame_binary(s, stream_index, target_ts, flags);
2206     if (ret < 0)
2207         return ret;
2208
2209     pos = avio_tell(s->pb);
2210
2211     for (;;) {
2212         avio_seek(s->pb, pos, SEEK_SET);
2213         ret = avio_read(s->pb, buf, TS_PACKET_SIZE);
2214         if (ret < 0)
2215             return ret;
2216         if (ret != TS_PACKET_SIZE)
2217             return AVERROR_EOF;
2218         // pid = AV_RB16(buf + 1) & 0x1fff;
2219         if (buf[1] & 0x40)
2220             break;
2221         pos += ts->raw_packet_size;
2222     }
2223     avio_seek(s->pb, pos, SEEK_SET);
2224
2225     return 0;
2226 }
2227
2228 /**************************************************************/
2229 /* parsing functions - called from other demuxers such as RTP */
2230
2231 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2232 {
2233     MpegTSContext *ts;
2234
2235     ts = av_mallocz(sizeof(MpegTSContext));
2236     if (!ts)
2237         return NULL;
2238     /* no stream case, currently used by RTP */
2239     ts->raw_packet_size = TS_PACKET_SIZE;
2240     ts->stream = s;
2241     ts->auto_guess = 1;
2242     return ts;
2243 }
2244
2245 /* return the consumed length if a packet was output, or -1 if no
2246  * packet is output */
2247 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2248                            const uint8_t *buf, int len)
2249 {
2250     int len1;
2251
2252     len1 = len;
2253     ts->pkt = pkt;
2254     ts->stop_parse = 0;
2255     for (;;) {
2256         if (ts->stop_parse > 0)
2257             break;
2258         if (len < TS_PACKET_SIZE)
2259             return AVERROR_INVALIDDATA;
2260         if (buf[0] != 0x47) {
2261             buf++;
2262             len--;
2263         } else {
2264             handle_packet(ts, buf);
2265             buf += TS_PACKET_SIZE;
2266             len -= TS_PACKET_SIZE;
2267         }
2268     }
2269     return len1 - len;
2270 }
2271
2272 void ff_mpegts_parse_close(MpegTSContext *ts)
2273 {
2274     mpegts_free(ts);
2275     av_free(ts);
2276 }
2277
2278 AVInputFormat ff_mpegts_demuxer = {
2279     .name           = "mpegts",
2280     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2281     .priv_data_size = sizeof(MpegTSContext),
2282     .read_probe     = mpegts_probe,
2283     .read_header    = mpegts_read_header,
2284     .read_packet    = mpegts_read_packet,
2285     .read_close     = mpegts_read_close,
2286     .read_seek      = read_seek,
2287     .read_timestamp = mpegts_get_pcr,
2288     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2289 };
2290
2291 AVInputFormat ff_mpegtsraw_demuxer = {
2292     .name           = "mpegtsraw",
2293     .long_name      = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2294     .priv_data_size = sizeof(MpegTSContext),
2295     .read_header    = mpegts_read_header,
2296     .read_packet    = mpegts_raw_read_packet,
2297     .read_close     = mpegts_read_close,
2298     .read_seek      = read_seek,
2299     .read_timestamp = mpegts_get_pcr,
2300     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2301     .priv_class     = &mpegtsraw_class,
2302 };