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