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