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