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