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