2 * MPEG-2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavutil/buffer.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/internal.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/log.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/mathematics.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/avassert.h"
31 #include "libavcodec/bytestream.h"
32 #include "libavcodec/get_bits.h"
33 #include "libavcodec/opus.h"
37 #include "avio_internal.h"
44 /* maximum size in which we look for synchronization if
45 * synchronization is lost */
46 #define MAX_RESYNC_SIZE 65536
48 #define MAX_PES_PAYLOAD 200 * 1024
50 #define MAX_MP4_DESCR_COUNT 16
52 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \
54 if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
55 (modulus) = (dividend) % (divisor); \
56 (prev_dividend) = (dividend); \
59 #define PROBE_PACKET_MAX_BUF 8192
60 #define PROBE_PACKET_MARGIN 5
62 enum MpegTSFilterType {
68 typedef struct MpegTSFilter MpegTSFilter;
70 typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
71 int is_start, int64_t pos);
73 typedef struct MpegTSPESFilter {
78 typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
80 typedef void SetServiceCallback (void *opaque, int ret);
82 typedef struct MpegTSSectionFilter {
89 unsigned int check_crc : 1;
90 unsigned int end_of_section_reached : 1;
91 SectionCallback *section_cb;
93 } MpegTSSectionFilter;
98 int last_cc; /* last cc code (-1 if first packet) */
101 enum MpegTSFilterType type;
103 MpegTSPESFilter pes_filter;
104 MpegTSSectionFilter section_filter;
108 #define MAX_PIDS_PER_PROGRAM 64
110 unsigned int id; // program id/service id
111 unsigned int nb_pids;
112 unsigned int pids[MAX_PIDS_PER_PROGRAM];
114 /** have we found pmt for this program */
118 struct MpegTSContext {
119 const AVClass *class;
121 AVFormatContext *stream;
122 /** raw packet size, including FEC if present */
127 #define SIZE_STAT_THRESHOLD 10
131 /** if true, all pids are analyzed to find streams */
134 /** compute exact PCR for each transport stream packet */
135 int mpeg2ts_compute_pcr;
137 /** fix dvb teletext pts */
138 int fix_teletext_pts;
140 int64_t cur_pcr; /**< used to estimate the exact PCR */
141 int pcr_incr; /**< used to estimate the exact PCR */
143 /* data needed to handle file based ts */
144 /** stop parsing loop */
146 /** packet containing Audio/Video data */
148 /** to detect seek */
153 int skip_unknown_pmt;
158 int merge_pmt_versions;
160 /******************************************/
161 /* private mpegts data */
163 /** structure to keep track of Program->pids mapping */
167 int8_t crc_validity[NB_PID_MAX];
168 /** filters for various streams specified by PMT + for the PAT and PMT */
169 MpegTSFilter *pids[NB_PID_MAX];
172 AVStream *epg_stream;
173 AVBufferPool* pools[32];
176 #define MPEGTS_OPTIONS \
177 { "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 }
179 static const AVOption options[] = {
181 {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
182 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
183 {"ts_packetsize", "output option carrying the raw packet size", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
184 {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
185 {"scan_all_pmts", "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
186 {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM },
187 {"skip_unknown_pmt", "skip PMTs for programs not advertised in the PAT", offsetof(MpegTSContext, skip_unknown_pmt), AV_OPT_TYPE_BOOL,
188 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
189 {"merge_pmt_versions", "re-use streams when PMT's version/pids change", offsetof(MpegTSContext, merge_pmt_versions), AV_OPT_TYPE_BOOL,
190 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
191 {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
192 {.i64 = 0}, 0, 1, 0 },
193 {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
194 {.i64 = 0}, 0, 1, 0 },
198 static const AVClass mpegts_class = {
199 .class_name = "mpegts demuxer",
200 .item_name = av_default_item_name,
202 .version = LIBAVUTIL_VERSION_INT,
205 static const AVOption raw_options[] = {
207 { "compute_pcr", "compute exact PCR for each transport stream packet",
208 offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
209 { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
210 { "ts_packetsize", "output option carrying the raw packet size",
211 offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
213 AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
217 static const AVClass mpegtsraw_class = {
218 .class_name = "mpegtsraw demuxer",
219 .item_name = av_default_item_name,
220 .option = raw_options,
221 .version = LIBAVUTIL_VERSION_INT,
224 /* TS stream handling */
229 MPEGTS_PESHEADER_FILL,
234 /* enough for PES header + length */
235 #define PES_START_SIZE 6
236 #define PES_HEADER_SIZE 9
237 #define MAX_PES_HEADER_SIZE (9 + 255)
239 typedef struct PESContext {
241 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
244 AVFormatContext *stream;
246 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
247 enum MpegTSState state;
248 /* used to get the format */
250 int flags; /**< copied to the AVPacket flags */
253 int extended_stream_id;
256 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
257 uint8_t header[MAX_PES_HEADER_SIZE];
263 extern AVInputFormat ff_mpegts_demuxer;
265 static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
268 for (i = 0; i < ts->nb_prg; i++) {
269 if (ts->prg[i].id == programid) {
276 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
278 AVProgram *prg = NULL;
281 for (i = 0; i < ts->stream->nb_programs; i++)
282 if (ts->stream->programs[i]->id == programid) {
283 prg = ts->stream->programs[i];
288 prg->nb_stream_indexes = 0;
291 static void clear_program(MpegTSContext *ts, unsigned int programid)
295 clear_avprogram(ts, programid);
296 for (i = 0; i < ts->nb_prg; i++)
297 if (ts->prg[i].id == programid) {
298 ts->prg[i].nb_pids = 0;
299 ts->prg[i].pmt_found = 0;
303 static void clear_programs(MpegTSContext *ts)
309 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
312 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
316 p = &ts->prg[ts->nb_prg];
323 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
326 struct Program *p = get_program(ts, programid);
331 if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
334 for (i = 0; i < p->nb_pids; i++)
335 if (p->pids[i] == pid)
338 p->pids[p->nb_pids++] = pid;
341 static void set_pmt_found(MpegTSContext *ts, unsigned int programid)
343 struct Program *p = get_program(ts, programid);
350 static void update_av_program_info(AVFormatContext *s, unsigned int programid,
351 unsigned int pid, int version)
354 for (i = 0; i < s->nb_programs; i++) {
355 AVProgram *program = s->programs[i];
356 if (program->id == programid) {
357 int old_pcr_pid = program->pcr_pid,
358 old_version = program->pmt_version;
359 program->pcr_pid = pid;
360 program->pmt_version = version;
362 if (old_version != -1 && old_version != version) {
363 av_log(s, AV_LOG_VERBOSE,
364 "detected PMT change (program=%d, version=%d/%d, pcr_pid=0x%x/0x%x)\n",
365 programid, old_version, version, old_pcr_pid, pid);
373 * @brief discard_pid() decides if the pid is to be discarded according
374 * to caller's programs selection
375 * @param ts : - TS context
377 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
380 static int discard_pid(MpegTSContext *ts, unsigned int pid)
383 int used = 0, discarded = 0;
386 /* If none of the programs have .discard=AVDISCARD_ALL then there's
387 * no way we have to discard this packet */
388 for (k = 0; k < ts->stream->nb_programs; k++)
389 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
391 if (k == ts->stream->nb_programs)
394 for (i = 0; i < ts->nb_prg; i++) {
396 for (j = 0; j < p->nb_pids; j++) {
397 if (p->pids[j] != pid)
399 // is program with id p->id set to be discarded?
400 for (k = 0; k < ts->stream->nb_programs; k++) {
401 if (ts->stream->programs[k]->id == p->id) {
402 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
411 return !used && discarded;
415 * Assemble PES packets out of TS packets, and then call the "section_cb"
416 * function when they are complete.
418 static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
419 const uint8_t *buf, int buf_size, int is_start)
421 MpegTSSectionFilter *tss = &tss1->u.section_filter;
422 uint8_t *cur_section_buf = NULL;
426 memcpy(tss->section_buf, buf, buf_size);
427 tss->section_index = buf_size;
428 tss->section_h_size = -1;
429 tss->end_of_section_reached = 0;
431 if (tss->end_of_section_reached)
433 len = MAX_SECTION_SIZE - tss->section_index;
436 memcpy(tss->section_buf + tss->section_index, buf, len);
437 tss->section_index += len;
441 cur_section_buf = tss->section_buf;
442 while (cur_section_buf - tss->section_buf < MAX_SECTION_SIZE && cur_section_buf[0] != 0xff) {
443 /* compute section length if possible */
444 if (tss->section_h_size == -1 && tss->section_index - offset >= 3) {
445 len = (AV_RB16(cur_section_buf + 1) & 0xfff) + 3;
446 if (len > MAX_SECTION_SIZE)
448 tss->section_h_size = len;
451 if (tss->section_h_size != -1 &&
452 tss->section_index >= offset + tss->section_h_size) {
454 tss->end_of_section_reached = 1;
456 if (tss->check_crc) {
457 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, cur_section_buf, tss->section_h_size);
458 if (tss->section_h_size >= 4)
459 tss->crc = AV_RB32(cur_section_buf + tss->section_h_size - 4);
462 ts->crc_validity[ tss1->pid ] = 100;
463 }else if (ts->crc_validity[ tss1->pid ] > -10) {
464 ts->crc_validity[ tss1->pid ]--;
469 tss->section_cb(tss1, cur_section_buf, tss->section_h_size);
474 cur_section_buf += tss->section_h_size;
475 offset += tss->section_h_size;
476 tss->section_h_size = -1;
478 tss->section_h_size = -1;
479 tss->end_of_section_reached = 0;
485 static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
486 enum MpegTSFilterType type)
488 MpegTSFilter *filter;
490 av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
492 if (pid >= NB_PID_MAX || ts->pids[pid])
494 filter = av_mallocz(sizeof(MpegTSFilter));
497 ts->pids[pid] = filter;
502 filter->last_cc = -1;
503 filter->last_pcr= -1;
508 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
510 SectionCallback *section_cb,
514 MpegTSFilter *filter;
515 MpegTSSectionFilter *sec;
517 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION)))
519 sec = &filter->u.section_filter;
520 sec->section_cb = section_cb;
521 sec->opaque = opaque;
522 sec->section_buf = av_mallocz(MAX_SECTION_SIZE);
523 sec->check_crc = check_crc;
526 if (!sec->section_buf) {
533 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
537 MpegTSFilter *filter;
538 MpegTSPESFilter *pes;
540 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
543 pes = &filter->u.pes_filter;
544 pes->pes_cb = pes_cb;
545 pes->opaque = opaque;
549 static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
551 return mpegts_open_filter(ts, pid, MPEGTS_PCR);
554 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
559 if (filter->type == MPEGTS_SECTION)
560 av_freep(&filter->u.section_filter.section_buf);
561 else if (filter->type == MPEGTS_PES) {
562 PESContext *pes = filter->u.pes_filter.opaque;
563 av_buffer_unref(&pes->buffer);
564 /* referenced private data will be freed later in
565 * avformat_close_input (pes->st->priv_data == pes) */
566 if (!pes->st || pes->merged_st) {
567 av_freep(&filter->u.pes_filter.opaque);
572 ts->pids[pid] = NULL;
575 static int analyze(const uint8_t *buf, int size, int packet_size,
578 int stat[TS_MAX_PACKET_SIZE];
583 memset(stat, 0, packet_size * sizeof(*stat));
585 for (i = 0; i < size - 3; i++) {
586 if (buf[i] == 0x47) {
587 int pid = AV_RB16(buf+1) & 0x1FFF;
588 int asc = buf[i + 3] & 0x30;
589 if (!probe || pid == 0x1FFF || asc) {
590 int x = i % packet_size;
593 if (stat[x] > best_score) {
594 best_score = stat[x];
600 return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
603 /* autodetect fec presence */
604 static int get_packet_size(AVFormatContext* s)
606 int score, fec_score, dvhs_score;
610 /*init buffer to store stream for probing */
611 uint8_t buf[PROBE_PACKET_MAX_BUF] = {0};
614 while (buf_size < PROBE_PACKET_MAX_BUF) {
615 ret = avio_read_partial(s->pb, buf + buf_size, PROBE_PACKET_MAX_BUF - buf_size);
617 return AVERROR_INVALIDDATA;
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);
626 margin = mid_pred(score, fec_score, dvhs_score);
628 if (buf_size < PROBE_PACKET_MAX_BUF)
629 margin += PROBE_PACKET_MARGIN; /*if buffer not filled */
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;
638 return AVERROR_INVALIDDATA;
641 typedef struct SectionHeader {
646 uint8_t last_sec_num;
649 static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
651 if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
654 tssf->last_ver = h->version;
655 tssf->last_crc = tssf->crc;
660 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
667 return AVERROR_INVALIDDATA;
673 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
680 return AVERROR_INVALIDDATA;
687 /* read and allocate a DVB string preceded by its length */
688 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
695 len = get8(&p, p_end);
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 "", "", "", "", "", "", "", ""
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) {
714 snprintf(iso8859, sizeof(iso8859), "ISO-8859-%d", p[2]);
717 cd = iconv_open("UTF-8", iso8859);
718 } else if (p[0] < 0x20) {
721 cd = iconv_open("UTF-8", encodings[*p]);
724 cd = iconv_open("UTF-8", encodings[0]);
726 if (cd == (iconv_t)-1)
728 str = out = av_malloc(outlen);
733 if (iconv(cd, &in, &inlen, &out, &outlen) == -1) {
745 str = av_malloc(len + 1);
755 static int parse_section_header(SectionHeader *h,
756 const uint8_t **pp, const uint8_t *p_end)
760 val = get8(pp, p_end);
765 val = get16(pp, p_end);
769 val = get8(pp, p_end);
772 h->version = (val >> 1) & 0x1f;
773 val = get8(pp, p_end);
777 val = get8(pp, p_end);
780 h->last_sec_num = val;
784 typedef struct StreamType {
785 uint32_t stream_type;
786 enum AVMediaType codec_type;
787 enum AVCodecID codec_id;
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 */
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 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
814 static const StreamType HDMV_types[] = {
815 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
816 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
817 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
818 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
819 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
820 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
821 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
822 { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
823 { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
824 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
825 { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
830 static const StreamType SCTE_types[] = {
831 { 0x86, AVMEDIA_TYPE_DATA, AV_CODEC_ID_SCTE_35 },
836 static const StreamType MISC_types[] = {
837 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
838 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
842 static const StreamType REGD_types[] = {
843 { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
844 { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
845 { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
846 { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
847 { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
848 { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
849 { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
850 { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
851 { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
852 { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
853 { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
854 { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS },
858 static const StreamType METADATA_types[] = {
859 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
860 { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
864 /* descriptor present */
865 static const StreamType DESC_types[] = {
866 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
867 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
868 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
869 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
870 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
874 static void mpegts_find_stream_type(AVStream *st,
875 uint32_t stream_type,
876 const StreamType *types)
878 for (; types->stream_type; types++)
879 if (stream_type == types->stream_type) {
880 if (st->codecpar->codec_type != types->codec_type ||
881 st->codecpar->codec_id != types->codec_id) {
882 st->codecpar->codec_type = types->codec_type;
883 st->codecpar->codec_id = types->codec_id;
884 st->internal->need_context_update = 1;
886 st->request_probe = 0;
891 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
892 uint32_t stream_type, uint32_t prog_reg_desc)
894 int old_codec_type = st->codecpar->codec_type;
895 int old_codec_id = st->codecpar->codec_id;
896 int old_codec_tag = st->codecpar->codec_tag;
898 if (avcodec_is_open(st->internal->avctx)) {
899 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, internal codec is open\n");
903 avpriv_set_pts_info(st, 33, 1, 90000);
905 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
906 st->codecpar->codec_id = AV_CODEC_ID_NONE;
907 st->need_parsing = AVSTREAM_PARSE_FULL;
909 pes->stream_type = stream_type;
911 av_log(pes->stream, AV_LOG_DEBUG,
912 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
913 st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
915 st->codecpar->codec_tag = pes->stream_type;
917 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
918 if (pes->stream_type == 4 || pes->stream_type == 0x0f)
919 st->request_probe = 50;
920 if ((prog_reg_desc == AV_RL32("HDMV") ||
921 prog_reg_desc == AV_RL32("HDPR")) &&
922 st->codecpar->codec_id == AV_CODEC_ID_NONE) {
923 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
924 if (pes->stream_type == 0x83) {
925 // HDMV TrueHD streams also contain an AC3 coded version of the
926 // audio track - add a second stream for this
928 // priv_data cannot be shared between streams
929 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
931 return AVERROR(ENOMEM);
932 memcpy(sub_pes, pes, sizeof(*sub_pes));
934 sub_st = avformat_new_stream(pes->stream, NULL);
937 return AVERROR(ENOMEM);
940 sub_st->id = pes->pid;
941 avpriv_set_pts_info(sub_st, 33, 1, 90000);
942 sub_st->priv_data = sub_pes;
943 sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
944 sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
945 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
946 sub_pes->sub_st = pes->sub_st = sub_st;
949 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
950 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
951 if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
952 st->codecpar->codec_id = old_codec_id;
953 st->codecpar->codec_type = old_codec_type;
955 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
956 (st->request_probe > 0 && st->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
957 st->probe_packets > 0 &&
958 stream_type == STREAM_TYPE_PRIVATE_DATA) {
959 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
960 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
961 st->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
964 /* queue a context update if properties changed */
965 if (old_codec_type != st->codecpar->codec_type ||
966 old_codec_id != st->codecpar->codec_id ||
967 old_codec_tag != st->codecpar->codec_tag)
968 st->internal->need_context_update = 1;
973 static void reset_pes_packet_state(PESContext *pes)
975 pes->pts = AV_NOPTS_VALUE;
976 pes->dts = AV_NOPTS_VALUE;
979 av_buffer_unref(&pes->buffer);
982 static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
985 pkt->data = (uint8_t *)buffer;
989 static int new_pes_packet(PESContext *pes, AVPacket *pkt)
995 pkt->buf = pes->buffer;
996 pkt->data = pes->buffer->data;
997 pkt->size = pes->data_index;
999 if (pes->total_size != MAX_PES_PAYLOAD &&
1000 pes->pes_header_size + pes->data_index != pes->total_size +
1002 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
1003 pes->flags |= AV_PKT_FLAG_CORRUPT;
1005 memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1007 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
1008 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
1009 pkt->stream_index = pes->sub_st->index;
1011 pkt->stream_index = pes->st->index;
1012 pkt->pts = pes->pts;
1013 pkt->dts = pes->dts;
1014 /* store position of first TS packet of this PES packet */
1015 pkt->pos = pes->ts_packet_pos;
1016 pkt->flags = pes->flags;
1019 reset_pes_packet_state(pes);
1021 sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
1023 return AVERROR(ENOMEM);
1024 *sd = pes->stream_id;
1029 static uint64_t get_ts64(GetBitContext *gb, int bits)
1031 if (get_bits_left(gb) < bits)
1032 return AV_NOPTS_VALUE;
1033 return get_bits64(gb, bits);
1036 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
1037 const uint8_t *buf, int buf_size)
1040 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
1041 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
1042 int dts_flag = -1, cts_flag = -1;
1043 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
1044 uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
1045 int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
1047 memcpy(buf_padded, buf, buf_padded_size);
1049 init_get_bits(&gb, buf_padded, buf_padded_size * 8);
1051 if (sl->use_au_start)
1052 au_start_flag = get_bits1(&gb);
1054 au_end_flag = get_bits1(&gb);
1055 if (!sl->use_au_start && !sl->use_au_end)
1056 au_start_flag = au_end_flag = 1;
1057 if (sl->ocr_len > 0)
1058 ocr_flag = get_bits1(&gb);
1060 idle_flag = get_bits1(&gb);
1061 if (sl->use_padding)
1062 padding_flag = get_bits1(&gb);
1064 padding_bits = get_bits(&gb, 3);
1066 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
1067 if (sl->packet_seq_num_len)
1068 skip_bits_long(&gb, sl->packet_seq_num_len);
1069 if (sl->degr_prior_len)
1071 skip_bits(&gb, sl->degr_prior_len);
1073 skip_bits_long(&gb, sl->ocr_len);
1074 if (au_start_flag) {
1075 if (sl->use_rand_acc_pt)
1077 if (sl->au_seq_num_len > 0)
1078 skip_bits_long(&gb, sl->au_seq_num_len);
1079 if (sl->use_timestamps) {
1080 dts_flag = get_bits1(&gb);
1081 cts_flag = get_bits1(&gb);
1084 if (sl->inst_bitrate_len)
1085 inst_bitrate_flag = get_bits1(&gb);
1087 dts = get_ts64(&gb, sl->timestamp_len);
1089 cts = get_ts64(&gb, sl->timestamp_len);
1091 skip_bits_long(&gb, sl->au_len);
1092 if (inst_bitrate_flag)
1093 skip_bits_long(&gb, sl->inst_bitrate_len);
1096 if (dts != AV_NOPTS_VALUE)
1098 if (cts != AV_NOPTS_VALUE)
1101 if (sl->timestamp_len && sl->timestamp_res)
1102 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
1104 return (get_bits_count(&gb) + 7) >> 3;
1107 static AVBufferRef *buffer_pool_get(MpegTSContext *ts, int size)
1109 int index = av_log2(size + AV_INPUT_BUFFER_PADDING_SIZE);
1110 if (!ts->pools[index]) {
1111 int pool_size = FFMIN(MAX_PES_PAYLOAD + AV_INPUT_BUFFER_PADDING_SIZE, 2 << index);
1112 ts->pools[index] = av_buffer_pool_init(pool_size, NULL);
1113 if (!ts->pools[index])
1116 return av_buffer_pool_get(ts->pools[index]);
1119 /* return non zero if a packet could be constructed */
1120 static int mpegts_push_data(MpegTSFilter *filter,
1121 const uint8_t *buf, int buf_size, int is_start,
1124 PESContext *pes = filter->u.pes_filter.opaque;
1125 MpegTSContext *ts = pes->ts;
1133 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1134 ret = new_pes_packet(pes, ts->pkt);
1139 reset_pes_packet_state(pes);
1141 pes->state = MPEGTS_HEADER;
1142 pes->ts_packet_pos = pos;
1145 while (buf_size > 0) {
1146 switch (pes->state) {
1148 len = PES_START_SIZE - pes->data_index;
1151 memcpy(pes->header + pes->data_index, p, len);
1152 pes->data_index += len;
1155 if (pes->data_index == PES_START_SIZE) {
1156 /* we got all the PES or section header. We can now
1158 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
1159 pes->header[2] == 0x01) {
1160 /* it must be an MPEG-2 PES stream */
1161 code = pes->header[3] | 0x100;
1162 av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
1164 pes->stream_id = pes->header[3];
1166 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
1168 pes->sub_st->discard == AVDISCARD_ALL)) ||
1169 code == 0x1be) /* padding_stream */
1172 /* stream not present in PMT */
1174 if (ts->skip_changes)
1176 if (ts->merge_pmt_versions)
1177 goto skip; /* wait for PMT to merge new stream */
1179 pes->st = avformat_new_stream(ts->stream, NULL);
1181 return AVERROR(ENOMEM);
1182 pes->st->id = pes->pid;
1183 mpegts_set_stream_info(pes->st, pes, 0, 0);
1186 pes->total_size = AV_RB16(pes->header + 4);
1187 /* NOTE: a zero total size means the PES size is
1189 if (!pes->total_size)
1190 pes->total_size = MAX_PES_PAYLOAD;
1192 /* allocate pes buffer */
1193 pes->buffer = buffer_pool_get(ts, pes->total_size);
1195 return AVERROR(ENOMEM);
1197 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
1198 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
1199 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
1200 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
1201 pes->state = MPEGTS_PESHEADER;
1202 if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
1203 av_log(pes->stream, AV_LOG_TRACE,
1204 "pid=%x stream_type=%x probing\n",
1207 pes->st->request_probe = 1;
1210 pes->pes_header_size = 6;
1211 pes->state = MPEGTS_PAYLOAD;
1212 pes->data_index = 0;
1215 /* otherwise, it should be a table */
1218 pes->state = MPEGTS_SKIP;
1223 /**********************************************/
1224 /* PES packing parsing */
1225 case MPEGTS_PESHEADER:
1226 len = PES_HEADER_SIZE - pes->data_index;
1228 return AVERROR_INVALIDDATA;
1231 memcpy(pes->header + pes->data_index, p, len);
1232 pes->data_index += len;
1235 if (pes->data_index == PES_HEADER_SIZE) {
1236 pes->pes_header_size = pes->header[8] + 9;
1237 pes->state = MPEGTS_PESHEADER_FILL;
1240 case MPEGTS_PESHEADER_FILL:
1241 len = pes->pes_header_size - pes->data_index;
1243 return AVERROR_INVALIDDATA;
1246 memcpy(pes->header + pes->data_index, p, len);
1247 pes->data_index += len;
1250 if (pes->data_index == pes->pes_header_size) {
1252 unsigned int flags, pes_ext, skip;
1254 flags = pes->header[7];
1255 r = pes->header + 9;
1256 pes->pts = AV_NOPTS_VALUE;
1257 pes->dts = AV_NOPTS_VALUE;
1258 if ((flags & 0xc0) == 0x80) {
1259 pes->dts = pes->pts = ff_parse_pes_pts(r);
1261 } else if ((flags & 0xc0) == 0xc0) {
1262 pes->pts = ff_parse_pes_pts(r);
1264 pes->dts = ff_parse_pes_pts(r);
1267 pes->extended_stream_id = -1;
1268 if (flags & 0x01) { /* PES extension */
1270 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1271 skip = (pes_ext >> 4) & 0xb;
1274 if ((pes_ext & 0x41) == 0x01 &&
1275 (r + 2) <= (pes->header + pes->pes_header_size)) {
1276 /* PES extension 2 */
1277 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1278 pes->extended_stream_id = r[1];
1282 /* we got the full header. We parse it and get the payload */
1283 pes->state = MPEGTS_PAYLOAD;
1284 pes->data_index = 0;
1285 if (pes->stream_type == 0x12 && buf_size > 0) {
1286 int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
1288 pes->pes_header_size += sl_header_bytes;
1289 p += sl_header_bytes;
1290 buf_size -= sl_header_bytes;
1292 if (pes->stream_type == 0x15 && buf_size >= 5) {
1293 /* skip metadata access unit header */
1294 pes->pes_header_size += 5;
1298 if ( pes->ts->fix_teletext_pts
1299 && ( pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
1300 || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1302 AVProgram *p = NULL;
1304 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1305 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1306 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1308 AVStream *st = NULL;
1309 if (f->type == MPEGTS_PES) {
1310 PESContext *pcrpes = f->u.pes_filter.opaque;
1313 } else if (f->type == MPEGTS_PCR) {
1315 for (i = 0; i < p->nb_stream_indexes; i++) {
1316 AVStream *pst = pes->stream->streams[p->stream_index[i]];
1317 if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1321 if (f->last_pcr != -1 && !f->discard) {
1322 // teletext packets do not always have correct timestamps,
1323 // the standard says they should be handled after 40.6 ms at most,
1324 // and the pcr error to this packet should be no more than 100 ms.
1325 // TODO: we should interpolate the PCR, not just use the last one
1326 int64_t pcr = f->last_pcr / 300;
1329 pes->st->pts_wrap_reference = st->pts_wrap_reference;
1330 pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
1332 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1333 pes->pts = pes->dts = pcr;
1334 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1335 pes->dts > pcr + 3654 + 9000) {
1336 pes->pts = pes->dts = pcr + 3654 + 9000;
1337 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1338 pes->dts > pcr + 10*90000) { //10sec
1339 pes->pts = pes->dts = pcr + 3654 + 9000;
1348 av_log(pes->stream, AV_LOG_VERBOSE,
1349 "Forcing DTS/PTS to be unset for a "
1350 "non-trustworthy PES packet for PID %d as "
1351 "PCR hasn't been received yet.\n",
1353 pes->dts = pes->pts = AV_NOPTS_VALUE;
1358 case MPEGTS_PAYLOAD:
1360 if (pes->data_index > 0 &&
1361 pes->data_index + buf_size > pes->total_size) {
1362 ret = new_pes_packet(pes, ts->pkt);
1365 pes->total_size = MAX_PES_PAYLOAD;
1366 pes->buffer = buffer_pool_get(ts, pes->total_size);
1368 return AVERROR(ENOMEM);
1370 } else if (pes->data_index == 0 &&
1371 buf_size > pes->total_size) {
1372 // pes packet size is < ts size packet and pes data is padded with 0xff
1373 // not sure if this is legal in ts but see issue #2392
1374 buf_size = pes->total_size;
1376 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1377 pes->data_index += buf_size;
1378 /* emit complete packets with known packet size
1379 * decreases demuxer delay for infrequent packets like subtitles from
1380 * a couple of seconds to milliseconds for properly muxed files.
1381 * total_size is the number of bytes following pes_packet_length
1382 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1383 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1384 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1386 ret = new_pes_packet(pes, ts->pkt);
1402 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1407 /* if no pid found, then add a pid context */
1408 pes = av_mallocz(sizeof(PESContext));
1412 pes->stream = ts->stream;
1414 pes->pcr_pid = pcr_pid;
1415 pes->state = MPEGTS_SKIP;
1416 pes->pts = AV_NOPTS_VALUE;
1417 pes->dts = AV_NOPTS_VALUE;
1418 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1427 typedef struct MP4DescrParseContext {
1431 Mp4Descr *active_descr;
1433 int max_descr_count;
1435 int predefined_SLConfigDescriptor_seen;
1436 } MP4DescrParseContext;
1438 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
1439 const uint8_t *buf, unsigned size,
1440 Mp4Descr *descr, int max_descr_count)
1443 if (size > (1 << 30))
1444 return AVERROR_INVALIDDATA;
1446 if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
1447 NULL, NULL, NULL, NULL)) < 0)
1454 d->active_descr = NULL;
1455 d->max_descr_count = max_descr_count;
1460 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1462 int64_t new_off = avio_tell(pb);
1463 (*len) -= new_off - *off;
1467 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1470 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1473 int ret = parse_mp4_descr(d, off, len, 0);
1476 update_offsets(&d->pb, &off, &len);
1481 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1483 avio_rb16(&d->pb); // ID
1489 update_offsets(&d->pb, &off, &len);
1490 return parse_mp4_descr_arr(d, off, len);
1493 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1498 id_flags = avio_rb16(&d->pb);
1499 if (!(id_flags & 0x0020)) { // URL_Flag
1500 update_offsets(&d->pb, &off, &len);
1501 return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1507 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1512 if (d->descr_count >= d->max_descr_count)
1513 return AVERROR_INVALIDDATA;
1514 ff_mp4_parse_es_descr(&d->pb, &es_id);
1515 d->active_descr = d->descr + (d->descr_count++);
1517 d->active_descr->es_id = es_id;
1518 update_offsets(&d->pb, &off, &len);
1519 if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
1521 update_offsets(&d->pb, &off, &len);
1523 ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
1524 d->active_descr = NULL;
1528 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
1531 Mp4Descr *descr = d->active_descr;
1533 return AVERROR_INVALIDDATA;
1534 d->active_descr->dec_config_descr = av_malloc(len);
1535 if (!descr->dec_config_descr)
1536 return AVERROR(ENOMEM);
1537 descr->dec_config_descr_len = len;
1538 avio_read(&d->pb, descr->dec_config_descr, len);
1542 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1544 Mp4Descr *descr = d->active_descr;
1547 return AVERROR_INVALIDDATA;
1549 #define R8_CHECK_CLIP_MAX(dst, maxv) do { \
1550 descr->sl.dst = avio_r8(&d->pb); \
1551 if (descr->sl.dst > maxv) { \
1552 descr->sl.dst = maxv; \
1553 return AVERROR_INVALIDDATA; \
1557 predefined = avio_r8(&d->pb);
1560 int flags = avio_r8(&d->pb);
1561 descr->sl.use_au_start = !!(flags & 0x80);
1562 descr->sl.use_au_end = !!(flags & 0x40);
1563 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1564 descr->sl.use_padding = !!(flags & 0x08);
1565 descr->sl.use_timestamps = !!(flags & 0x04);
1566 descr->sl.use_idle = !!(flags & 0x02);
1567 descr->sl.timestamp_res = avio_rb32(&d->pb);
1569 R8_CHECK_CLIP_MAX(timestamp_len, 63);
1570 R8_CHECK_CLIP_MAX(ocr_len, 63);
1571 R8_CHECK_CLIP_MAX(au_len, 31);
1572 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1573 lengths = avio_rb16(&d->pb);
1574 descr->sl.degr_prior_len = lengths >> 12;
1575 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1576 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1577 } else if (!d->predefined_SLConfigDescriptor_seen){
1578 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1579 d->predefined_SLConfigDescriptor_seen = 1;
1584 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1588 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1591 update_offsets(&d->pb, &off, &len);
1592 if (len < 0 || len1 > len || len1 <= 0) {
1593 av_log(d->s, AV_LOG_ERROR,
1594 "Tag %x length violation new length %d bytes remaining %d\n",
1596 return AVERROR_INVALIDDATA;
1599 if (d->level++ >= MAX_LEVEL) {
1600 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1601 ret = AVERROR_INVALIDDATA;
1605 if (target_tag && tag != target_tag) {
1606 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1608 ret = AVERROR_INVALIDDATA;
1614 ret = parse_MP4IODescrTag(d, off, len1);
1617 ret = parse_MP4ODescrTag(d, off, len1);
1620 ret = parse_MP4ESDescrTag(d, off, len1);
1622 case MP4DecConfigDescrTag:
1623 ret = parse_MP4DecConfigDescrTag(d, off, len1);
1626 ret = parse_MP4SLDescrTag(d, off, len1);
1633 avio_seek(&d->pb, off + len1, SEEK_SET);
1637 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1638 Mp4Descr *descr, int *descr_count, int max_descr_count)
1640 MP4DescrParseContext d;
1643 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1647 ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1649 *descr_count = d.descr_count;
1653 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1654 Mp4Descr *descr, int *descr_count, int max_descr_count)
1656 MP4DescrParseContext d;
1659 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1663 ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1665 *descr_count = d.descr_count;
1669 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1672 MpegTSContext *ts = filter->u.section_filter.opaque;
1673 MpegTSSectionFilter *tssf = &filter->u.section_filter;
1675 const uint8_t *p, *p_end;
1677 int mp4_descr_count = 0;
1678 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1680 AVFormatContext *s = ts->stream;
1682 p_end = section + section_len - 4;
1684 if (parse_section_header(&h, &p, p_end) < 0)
1686 if (h.tid != M4OD_TID)
1688 if (skip_identical(&h, tssf))
1691 mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1692 MAX_MP4_DESCR_COUNT);
1694 for (pid = 0; pid < NB_PID_MAX; pid++) {
1697 for (i = 0; i < mp4_descr_count; i++) {
1700 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1702 if (ts->pids[pid]->type != MPEGTS_PES) {
1703 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1706 pes = ts->pids[pid]->u.pes_filter.opaque;
1711 pes->sl = mp4_descr[i].sl;
1713 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1714 mp4_descr[i].dec_config_descr_len, 0,
1715 NULL, NULL, NULL, NULL);
1716 ff_mp4_read_dec_config_descr(s, st, &pb);
1717 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1718 st->codecpar->extradata_size > 0)
1719 st->need_parsing = 0;
1720 if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
1721 st->codecpar->extradata_size > 0)
1722 st->need_parsing = 0;
1724 st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
1725 st->internal->need_context_update = 1;
1728 for (i = 0; i < mp4_descr_count; i++)
1729 av_free(mp4_descr[i].dec_config_descr);
1732 static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
1735 AVProgram *prg = NULL;
1736 MpegTSContext *ts = filter->u.section_filter.opaque;
1738 int idx = ff_find_stream_index(ts->stream, filter->pid);
1743 * In case we receive an SCTE-35 packet before mpegts context is fully
1749 new_data_packet(section, section_len, ts->pkt);
1750 ts->pkt->stream_index = idx;
1751 prg = av_find_program_from_stream(ts->stream, NULL, idx);
1752 if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
1753 MpegTSFilter *f = ts->pids[prg->pcr_pid];
1754 if (f && f->last_pcr != -1)
1755 ts->pkt->pts = ts->pkt->dts = f->last_pcr/300;
1761 static const uint8_t opus_coupled_stream_cnt[9] = {
1762 1, 0, 1, 1, 2, 2, 2, 3, 3
1765 static const uint8_t opus_stream_cnt[9] = {
1766 1, 1, 1, 2, 2, 3, 4, 4, 5,
1769 static const uint8_t opus_channel_map[8][8] = {
1777 { 0,6,1,2,3,4,5,7 },
1780 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1781 const uint8_t **pp, const uint8_t *desc_list_end,
1782 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1785 const uint8_t *desc_end;
1786 int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
1790 desc_tag = get8(pp, desc_list_end);
1792 return AVERROR_INVALIDDATA;
1793 desc_len = get8(pp, desc_list_end);
1795 return AVERROR_INVALIDDATA;
1796 desc_end = *pp + desc_len;
1797 if (desc_end > desc_list_end)
1798 return AVERROR_INVALIDDATA;
1800 av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1802 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
1803 stream_type == STREAM_TYPE_PRIVATE_DATA)
1804 mpegts_find_stream_type(st, desc_tag, DESC_types);
1807 case 0x02: /* video stream descriptor */
1808 if (get8(pp, desc_end) & 0x1) {
1809 st->disposition |= AV_DISPOSITION_STILL_IMAGE;
1812 case 0x1E: /* SL descriptor */
1813 desc_es_id = get16(pp, desc_end);
1816 if (ts && ts->pids[pid])
1817 ts->pids[pid]->es_id = desc_es_id;
1818 for (i = 0; i < mp4_descr_count; i++)
1819 if (mp4_descr[i].dec_config_descr_len &&
1820 mp4_descr[i].es_id == desc_es_id) {
1822 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1823 mp4_descr[i].dec_config_descr_len, 0,
1824 NULL, NULL, NULL, NULL);
1825 ff_mp4_read_dec_config_descr(fc, st, &pb);
1826 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1827 st->codecpar->extradata_size > 0) {
1828 st->need_parsing = 0;
1829 st->internal->need_context_update = 1;
1831 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1832 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1835 case 0x1F: /* FMC descriptor */
1836 if (get16(pp, desc_end) < 0)
1838 if (mp4_descr_count > 0 &&
1839 (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
1840 (st->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
1841 st->request_probe > 0) &&
1842 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1844 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1845 mp4_descr->dec_config_descr_len, 0,
1846 NULL, NULL, NULL, NULL);
1847 ff_mp4_read_dec_config_descr(fc, st, &pb);
1848 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1849 st->codecpar->extradata_size > 0) {
1850 st->request_probe = st->need_parsing = 0;
1851 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1852 st->internal->need_context_update = 1;
1856 case 0x56: /* DVB teletext descriptor */
1858 uint8_t *extradata = NULL;
1859 int language_count = desc_len / 5, ret;
1861 if (desc_len > 0 && desc_len % 5 != 0)
1862 return AVERROR_INVALIDDATA;
1864 if (language_count > 0) {
1865 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1866 av_assert0(language_count <= sizeof(language) / 4);
1868 if (st->codecpar->extradata == NULL) {
1869 ret = ff_alloc_extradata(st->codecpar, language_count * 2);
1874 if (st->codecpar->extradata_size < language_count * 2)
1875 return AVERROR_INVALIDDATA;
1877 extradata = st->codecpar->extradata;
1879 for (i = 0; i < language_count; i++) {
1880 language[i * 4 + 0] = get8(pp, desc_end);
1881 language[i * 4 + 1] = get8(pp, desc_end);
1882 language[i * 4 + 2] = get8(pp, desc_end);
1883 language[i * 4 + 3] = ',';
1885 memcpy(extradata, *pp, 2);
1891 language[i * 4 - 1] = 0;
1892 av_dict_set(&st->metadata, "language", language, 0);
1893 st->internal->need_context_update = 1;
1897 case 0x59: /* subtitling descriptor */
1899 /* 8 bytes per DVB subtitle substream data:
1900 * ISO_639_language_code (3 bytes),
1901 * subtitling_type (1 byte),
1902 * composition_page_id (2 bytes),
1903 * ancillary_page_id (2 bytes) */
1904 int language_count = desc_len / 8, ret;
1906 if (desc_len > 0 && desc_len % 8 != 0)
1907 return AVERROR_INVALIDDATA;
1909 if (language_count > 1) {
1910 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
1913 if (language_count > 0) {
1916 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1917 av_assert0(language_count <= sizeof(language) / 4);
1919 if (st->codecpar->extradata == NULL) {
1920 ret = ff_alloc_extradata(st->codecpar, language_count * 5);
1925 if (st->codecpar->extradata_size < language_count * 5)
1926 return AVERROR_INVALIDDATA;
1928 extradata = st->codecpar->extradata;
1930 for (i = 0; i < language_count; i++) {
1931 language[i * 4 + 0] = get8(pp, desc_end);
1932 language[i * 4 + 1] = get8(pp, desc_end);
1933 language[i * 4 + 2] = get8(pp, desc_end);
1934 language[i * 4 + 3] = ',';
1936 /* hearing impaired subtitles detection using subtitling_type */
1938 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1939 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1940 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1941 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1942 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1943 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1944 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1948 extradata[4] = get8(pp, desc_end); /* subtitling_type */
1949 memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
1955 language[i * 4 - 1] = 0;
1956 av_dict_set(&st->metadata, "language", language, 0);
1957 st->internal->need_context_update = 1;
1961 case 0x0a: /* ISO 639 language descriptor */
1962 for (i = 0; i + 4 <= desc_len; i += 4) {
1963 language[i + 0] = get8(pp, desc_end);
1964 language[i + 1] = get8(pp, desc_end);
1965 language[i + 2] = get8(pp, desc_end);
1966 language[i + 3] = ',';
1967 switch (get8(pp, desc_end)) {
1969 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
1972 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1975 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1976 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1980 if (i && language[0]) {
1981 language[i - 1] = 0;
1982 /* don't overwrite language, as it may already have been set by
1983 * another, more specific descriptor (e.g. supplementary audio) */
1984 av_dict_set(&st->metadata, "language", language, AV_DICT_DONT_OVERWRITE);
1987 case 0x05: /* registration descriptor */
1988 st->codecpar->codec_tag = bytestream_get_le32(pp);
1989 av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
1990 if (st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) {
1991 mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
1992 if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
1993 st->request_probe = 50;
1996 case 0x52: /* stream identifier descriptor */
1997 st->stream_identifier = 1 + get8(pp, desc_end);
1999 case 0x26: /* metadata descriptor */
2000 if (get16(pp, desc_end) == 0xFFFF)
2002 if (get8(pp, desc_end) == 0xFF) {
2003 st->codecpar->codec_tag = bytestream_get_le32(pp);
2004 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
2005 mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
2008 case 0x7f: /* DVB extension descriptor */
2009 ext_desc_tag = get8(pp, desc_end);
2010 if (ext_desc_tag < 0)
2011 return AVERROR_INVALIDDATA;
2012 if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
2013 ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
2014 if (!st->codecpar->extradata) {
2015 st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
2016 AV_INPUT_BUFFER_PADDING_SIZE);
2017 if (!st->codecpar->extradata)
2018 return AVERROR(ENOMEM);
2020 st->codecpar->extradata_size = sizeof(opus_default_extradata);
2021 memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
2023 channel_config_code = get8(pp, desc_end);
2024 if (channel_config_code < 0)
2025 return AVERROR_INVALIDDATA;
2026 if (channel_config_code <= 0x8) {
2027 st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
2028 st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
2029 st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
2030 st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
2031 memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
2033 avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
2035 st->need_parsing = AVSTREAM_PARSE_FULL;
2036 st->internal->need_context_update = 1;
2039 if (ext_desc_tag == 0x06) { /* supplementary audio descriptor */
2043 return AVERROR_INVALIDDATA;
2044 flags = get8(pp, desc_end);
2046 if ((flags & 0x80) == 0) /* mix_type */
2047 st->disposition |= AV_DISPOSITION_DEPENDENT;
2049 switch ((flags >> 2) & 0x1F) { /* editorial_classification */
2051 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2052 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2055 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2058 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2062 if (flags & 0x01) { /* language_code_present */
2064 return AVERROR_INVALIDDATA;
2065 language[0] = get8(pp, desc_end);
2066 language[1] = get8(pp, desc_end);
2067 language[2] = get8(pp, desc_end);
2070 /* This language always has to override a possible
2071 * ISO 639 language descriptor language */
2073 av_dict_set(&st->metadata, "language", language, 0);
2077 case 0x6a: /* ac-3_descriptor */
2079 int component_type_flag = get8(pp, desc_end) & (1 << 7);
2080 if (component_type_flag) {
2081 int component_type = get8(pp, desc_end);
2082 int service_type_mask = 0x38; // 0b00111000
2083 int service_type = ((component_type & service_type_mask) >> 3);
2084 if (service_type == 0x02 /* 0b010 */) {
2085 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2086 av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2091 case 0x7a: /* enhanced_ac-3_descriptor */
2093 int component_type_flag = get8(pp, desc_end) & (1 << 7);
2094 if (component_type_flag) {
2095 int component_type = get8(pp, desc_end);
2096 int service_type_mask = 0x38; // 0b00111000
2097 int service_type = ((component_type & service_type_mask) >> 3);
2098 if (service_type == 0x02 /* 0b010 */) {
2099 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2100 av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2105 case 0xfd: /* ARIB data coding type descriptor */
2106 // STD-B24, fascicle 3, chapter 4 defines private_stream_1
2108 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
2109 // This structure is defined in STD-B10, part 1, listing 5.4 and
2111 // Listing of data_component_ids is in STD-B10, part 2, Annex J.
2112 // Component tag limits are documented in TR-B14, fascicle 2,
2113 // Vol. 3, Section 2, 4.2.8.1
2114 int actual_component_tag = st->stream_identifier - 1;
2115 int picked_profile = FF_PROFILE_UNKNOWN;
2116 int data_component_id = get16(pp, desc_end);
2117 if (data_component_id < 0)
2118 return AVERROR_INVALIDDATA;
2120 switch (data_component_id) {
2122 // [0x30..0x37] are component tags utilized for
2123 // non-mobile captioning service ("profile A").
2124 if (actual_component_tag >= 0x30 &&
2125 actual_component_tag <= 0x37) {
2126 picked_profile = FF_PROFILE_ARIB_PROFILE_A;
2130 // component tag 0x87 signifies a mobile/partial reception
2131 // (1seg) captioning service ("profile C").
2132 if (actual_component_tag == 0x87) {
2133 picked_profile = FF_PROFILE_ARIB_PROFILE_C;
2140 if (picked_profile == FF_PROFILE_UNKNOWN)
2143 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2144 st->codecpar->codec_id = AV_CODEC_ID_ARIB_CAPTION;
2145 st->codecpar->profile = picked_profile;
2146 st->request_probe = 0;
2156 static AVStream *find_matching_stream(MpegTSContext *ts, int pid, unsigned int programid,
2157 int stream_identifier, int pmt_stream_idx)
2159 AVFormatContext *s = ts->stream;
2161 AVStream *found = NULL;
2163 for (i = 0; i < s->nb_streams; i++) {
2164 AVStream *st = s->streams[i];
2165 if (st->program_num != programid)
2167 if (stream_identifier != -1) { /* match based on "stream identifier descriptor" if present */
2168 if (st->stream_identifier == stream_identifier+1) {
2172 } else if (st->pmt_stream_idx == pmt_stream_idx) { /* match based on position within the PMT */
2179 av_log(ts->stream, AV_LOG_VERBOSE,
2180 "re-using existing %s stream %d (pid=0x%x) for new pid=0x%x\n",
2181 av_get_media_type_string(found->codecpar->codec_type),
2188 static int parse_stream_identifier_desc(const uint8_t *p, const uint8_t *p_end)
2190 const uint8_t **pp = &p;
2191 const uint8_t *desc_list_end;
2192 const uint8_t *desc_end;
2194 int desc_len, desc_tag;
2196 desc_list_len = get16(pp, p_end);
2197 if (desc_list_len < 0)
2199 desc_list_len &= 0xfff;
2200 desc_list_end = p + desc_list_len;
2201 if (desc_list_end > p_end)
2205 desc_tag = get8(pp, desc_list_end);
2208 desc_len = get8(pp, desc_list_end);
2211 desc_end = *pp + desc_len;
2212 if (desc_end > desc_list_end)
2215 if (desc_tag == 0x52) {
2216 return get8(pp, desc_end);
2224 static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
2226 return !(stream_type == 0x13 ||
2227 (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
2230 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2232 MpegTSContext *ts = filter->u.section_filter.opaque;
2233 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2234 SectionHeader h1, *h = &h1;
2237 const uint8_t *p, *p_end, *desc_list_end;
2238 int program_info_length, pcr_pid, pid, stream_type;
2240 uint32_t prog_reg_desc = 0; /* registration descriptor */
2241 int stream_identifier = -1;
2243 int mp4_descr_count = 0;
2244 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
2247 av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
2248 hex_dump_debug(ts->stream, section, section_len);
2250 p_end = section + section_len - 4;
2252 if (parse_section_header(h, &p, p_end) < 0)
2254 if (h->tid != PMT_TID)
2256 if (skip_identical(h, tssf))
2259 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
2260 h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
2262 if (!ts->scan_all_pmts && ts->skip_changes)
2265 if (ts->skip_unknown_pmt && !get_program(ts, h->id))
2267 if (!ts->skip_clear)
2268 clear_program(ts, h->id);
2270 pcr_pid = get16(&p, p_end);
2274 add_pid_to_pmt(ts, h->id, pcr_pid);
2275 update_av_program_info(ts->stream, h->id, pcr_pid, h->version);
2277 av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
2279 program_info_length = get16(&p, p_end);
2280 if (program_info_length < 0)
2282 program_info_length &= 0xfff;
2283 while (program_info_length >= 2) {
2285 tag = get8(&p, p_end);
2286 len = get8(&p, p_end);
2288 av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
2290 if (len > program_info_length - 2)
2291 // something else is broken, exit the program_descriptors_loop
2293 program_info_length -= len + 2;
2294 if (tag == 0x1d) { // IOD descriptor
2295 get8(&p, p_end); // scope
2296 get8(&p, p_end); // label
2298 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
2299 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
2300 } else if (tag == 0x05 && len >= 4) { // registration descriptor
2301 prog_reg_desc = bytestream_get_le32(&p);
2306 p += program_info_length;
2310 // stop parsing after pmt, we found header
2311 if (!ts->stream->nb_streams)
2314 set_pmt_found(ts, h->id);
2317 for (i = 0; ; i++) {
2320 stream_type = get8(&p, p_end);
2321 if (stream_type < 0)
2323 pid = get16(&p, p_end);
2327 if (pid == ts->current_pid)
2330 if (ts->merge_pmt_versions)
2331 stream_identifier = parse_stream_identifier_desc(p, p_end);
2333 /* now create stream */
2334 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
2335 pes = ts->pids[pid]->u.pes_filter.opaque;
2336 if (ts->merge_pmt_versions && !pes->st) {
2337 st = find_matching_stream(ts, pid, h->id, stream_identifier, i);
2340 pes->stream_type = stream_type;
2345 pes->st = avformat_new_stream(pes->stream, NULL);
2348 pes->st->id = pes->pid;
2349 pes->st->program_num = h->id;
2350 pes->st->pmt_version = h->version;
2351 pes->st->pmt_stream_idx = i;
2354 } else if (is_pes_stream(stream_type, prog_reg_desc)) {
2356 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
2357 pes = add_pes_stream(ts, pid, pcr_pid);
2358 if (ts->merge_pmt_versions && pes && !pes->st) {
2359 st = find_matching_stream(ts, pid, h->id, stream_identifier, i);
2362 pes->stream_type = stream_type;
2366 if (pes && !pes->st) {
2367 st = avformat_new_stream(pes->stream, NULL);
2371 st->program_num = h->id;
2372 st->pmt_version = h->version;
2373 st->pmt_stream_idx = i;
2376 int idx = ff_find_stream_index(ts->stream, pid);
2378 st = ts->stream->streams[idx];
2380 if (ts->merge_pmt_versions && !st) {
2381 st = find_matching_stream(ts, pid, h->id, stream_identifier, i);
2384 st = avformat_new_stream(ts->stream, NULL);
2388 st->program_num = h->id;
2389 st->pmt_version = h->version;
2390 st->pmt_stream_idx = i;
2391 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2392 if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
2393 mpegts_find_stream_type(st, stream_type, SCTE_types);
2394 mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
2402 if (pes && !pes->stream_type)
2403 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
2405 add_pid_to_pmt(ts, h->id, pid);
2407 av_program_add_stream_index(ts->stream, h->id, st->index);
2409 desc_list_len = get16(&p, p_end);
2410 if (desc_list_len < 0)
2412 desc_list_len &= 0xfff;
2413 desc_list_end = p + desc_list_len;
2414 if (desc_list_end > p_end)
2417 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
2418 desc_list_end, mp4_descr,
2419 mp4_descr_count, pid, ts) < 0)
2422 if (pes && prog_reg_desc == AV_RL32("HDMV") &&
2423 stream_type == 0x83 && pes->sub_st) {
2424 av_program_add_stream_index(ts->stream, h->id,
2425 pes->sub_st->index);
2426 pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
2432 if (!ts->pids[pcr_pid])
2433 mpegts_open_pcr_filter(ts, pcr_pid);
2436 for (i = 0; i < mp4_descr_count; i++)
2437 av_free(mp4_descr[i].dec_config_descr);
2440 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2442 MpegTSContext *ts = filter->u.section_filter.opaque;
2443 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2444 SectionHeader h1, *h = &h1;
2445 const uint8_t *p, *p_end;
2449 av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
2450 hex_dump_debug(ts->stream, section, section_len);
2452 p_end = section + section_len - 4;
2454 if (parse_section_header(h, &p, p_end) < 0)
2456 if (h->tid != PAT_TID)
2458 if (ts->skip_changes)
2461 if (skip_identical(h, tssf))
2463 ts->stream->ts_id = h->id;
2467 sid = get16(&p, p_end);
2470 pmt_pid = get16(&p, p_end);
2475 if (pmt_pid == ts->current_pid)
2478 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
2480 if (sid == 0x0000) {
2483 MpegTSFilter *fil = ts->pids[pmt_pid];
2484 program = av_new_program(ts->stream, sid);
2486 program->program_num = sid;
2487 program->pmt_pid = pmt_pid;
2490 if ( fil->type != MPEGTS_SECTION
2491 || fil->pid != pmt_pid
2492 || fil->u.section_filter.section_cb != pmt_cb)
2493 mpegts_close_filter(ts, ts->pids[pmt_pid]);
2495 if (!ts->pids[pmt_pid])
2496 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
2497 add_pat_entry(ts, sid);
2498 add_pid_to_pmt(ts, sid, 0); // add pat pid to program
2499 add_pid_to_pmt(ts, sid, pmt_pid);
2505 for (j=0; j<ts->stream->nb_programs; j++) {
2506 for (i = 0; i < ts->nb_prg; i++)
2507 if (ts->prg[i].id == ts->stream->programs[j]->id)
2509 if (i==ts->nb_prg && !ts->skip_clear)
2510 clear_avprogram(ts, ts->stream->programs[j]->id);
2515 static void eit_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2517 MpegTSContext *ts = filter->u.section_filter.opaque;
2518 const uint8_t *p, *p_end;
2519 SectionHeader h1, *h = &h1;
2522 * Sometimes we receive EPG packets but SDT table do not have
2523 * eit_pres_following or eit_sched turned on, so we open EPG
2524 * stream directly here.
2526 if (!ts->epg_stream) {
2527 ts->epg_stream = avformat_new_stream(ts->stream, NULL);
2528 if (!ts->epg_stream)
2530 ts->epg_stream->id = EIT_PID;
2531 ts->epg_stream->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2532 ts->epg_stream->codecpar->codec_id = AV_CODEC_ID_EPG;
2535 if (ts->epg_stream->discard == AVDISCARD_ALL)
2538 p_end = section + section_len - 4;
2541 if (parse_section_header(h, &p, p_end) < 0)
2543 if (h->tid < EIT_TID || h->tid > OEITS_END_TID)
2546 av_log(ts->stream, AV_LOG_TRACE, "EIT: tid received = %.02x\n", h->tid);
2549 * Service_id 0xFFFF is reserved, it indicates that the current EIT table
2552 if (h->id == 0xFFFF) {
2553 av_log(ts->stream, AV_LOG_TRACE, "Scrambled EIT table received.\n");
2558 * In case we receive an EPG packet before mpegts context is fully
2564 new_data_packet(section, section_len, ts->pkt);
2565 ts->pkt->stream_index = ts->epg_stream->index;
2569 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2571 MpegTSContext *ts = filter->u.section_filter.opaque;
2572 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2573 SectionHeader h1, *h = &h1;
2574 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
2575 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
2576 char *name, *provider_name;
2578 av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
2579 hex_dump_debug(ts->stream, section, section_len);
2581 p_end = section + section_len - 4;
2583 if (parse_section_header(h, &p, p_end) < 0)
2585 if (h->tid != SDT_TID)
2587 if (ts->skip_changes)
2589 if (skip_identical(h, tssf))
2592 onid = get16(&p, p_end);
2595 val = get8(&p, p_end);
2599 sid = get16(&p, p_end);
2602 val = get8(&p, p_end);
2605 desc_list_len = get16(&p, p_end);
2606 if (desc_list_len < 0)
2608 desc_list_len &= 0xfff;
2609 desc_list_end = p + desc_list_len;
2610 if (desc_list_end > p_end)
2613 desc_tag = get8(&p, desc_list_end);
2616 desc_len = get8(&p, desc_list_end);
2617 desc_end = p + desc_len;
2618 if (desc_len < 0 || desc_end > desc_list_end)
2621 av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
2622 desc_tag, desc_len);
2626 service_type = get8(&p, p_end);
2627 if (service_type < 0)
2629 provider_name = getstr8(&p, p_end);
2632 name = getstr8(&p, p_end);
2634 AVProgram *program = av_new_program(ts->stream, sid);
2636 av_dict_set(&program->metadata, "service_name", name, 0);
2637 av_dict_set(&program->metadata, "service_provider",
2642 av_free(provider_name);
2653 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2654 const uint8_t *packet);
2656 /* handle one TS packet */
2657 static int handle_packet(MpegTSContext *ts, const uint8_t *packet, int64_t pos)
2660 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
2661 has_adaptation, has_payload;
2662 const uint8_t *p, *p_end;
2664 pid = AV_RB16(packet + 1) & 0x1fff;
2665 is_start = packet[1] & 0x40;
2666 tss = ts->pids[pid];
2667 if (ts->auto_guess && !tss && is_start) {
2668 add_pes_stream(ts, pid, -1);
2669 tss = ts->pids[pid];
2674 tss->discard = discard_pid(ts, pid);
2677 ts->current_pid = pid;
2679 afc = (packet[3] >> 4) & 3;
2680 if (afc == 0) /* reserved value */
2682 has_adaptation = afc & 2;
2683 has_payload = afc & 1;
2684 is_discontinuity = has_adaptation &&
2685 packet[4] != 0 && /* with length > 0 */
2686 (packet[5] & 0x80); /* and discontinuity indicated */
2688 /* continuity check (currently not used) */
2689 cc = (packet[3] & 0xf);
2690 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
2691 cc_ok = pid == 0x1FFF || // null packet PID
2698 av_log(ts->stream, AV_LOG_DEBUG,
2699 "Continuity check failed for pid %d expected %d got %d\n",
2700 pid, expected_cc, cc);
2701 if (tss->type == MPEGTS_PES) {
2702 PESContext *pc = tss->u.pes_filter.opaque;
2703 pc->flags |= AV_PKT_FLAG_CORRUPT;
2707 if (packet[1] & 0x80) {
2708 av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
2709 if (tss->type == MPEGTS_PES) {
2710 PESContext *pc = tss->u.pes_filter.opaque;
2711 pc->flags |= AV_PKT_FLAG_CORRUPT;
2716 if (has_adaptation) {
2719 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
2720 tss->last_pcr = pcr_h * 300 + pcr_l;
2721 /* skip adaptation field */
2724 /* if past the end of packet, ignore */
2725 p_end = packet + TS_PACKET_SIZE;
2726 if (p >= p_end || !has_payload)
2730 av_assert0(pos >= TS_PACKET_SIZE);
2731 ts->pos47_full = pos - TS_PACKET_SIZE;
2734 if (tss->type == MPEGTS_SECTION) {
2736 /* pointer field present */
2738 if (len > p_end - p)
2741 /* write remaining section bytes */
2742 write_section_data(ts, tss,
2744 /* check whether filter has been closed */
2750 write_section_data(ts, tss,
2755 write_section_data(ts, tss,
2760 // stop find_stream_info from waiting for more streams
2761 // when all programs have received a PMT
2762 if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
2764 for (i = 0; i < ts->nb_prg; i++) {
2765 if (!ts->prg[i].pmt_found)
2768 if (i == ts->nb_prg && ts->nb_prg > 0) {
2770 for (i = 0; i < ts->stream->nb_streams; i++) {
2771 AVStream *st = ts->stream->streams[i];
2772 if (st->codecpar->codec_type >= 0)
2773 types |= 1<<st->codecpar->codec_type;
2775 if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
2776 av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
2777 ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
2784 // Note: The position here points actually behind the current packet.
2785 if (tss->type == MPEGTS_PES) {
2786 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
2787 pos - ts->raw_packet_size)) < 0)
2795 static void reanalyze(MpegTSContext *ts) {
2796 AVIOContext *pb = ts->stream->pb;
2797 int64_t pos = avio_tell(pb);
2800 pos -= ts->pos47_full;
2801 if (pos == TS_PACKET_SIZE) {
2802 ts->size_stat[0] ++;
2803 } else if (pos == TS_DVHS_PACKET_SIZE) {
2804 ts->size_stat[1] ++;
2805 } else if (pos == TS_FEC_PACKET_SIZE) {
2806 ts->size_stat[2] ++;
2809 ts->size_stat_count ++;
2810 if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
2812 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
2813 newsize = TS_PACKET_SIZE;
2814 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
2815 newsize = TS_DVHS_PACKET_SIZE;
2816 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
2817 newsize = TS_FEC_PACKET_SIZE;
2819 if (newsize && newsize != ts->raw_packet_size) {
2820 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
2821 ts->raw_packet_size = newsize;
2823 ts->size_stat_count = 0;
2824 memset(ts->size_stat, 0, sizeof(ts->size_stat));
2828 /* XXX: try to find a better synchro over several packets (use
2829 * get_packet_size() ?) */
2830 static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
2832 MpegTSContext *ts = s->priv_data;
2833 AVIOContext *pb = s->pb;
2835 uint64_t pos = avio_tell(pb);
2837 avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
2839 //Special case for files like 01c56b0dc1.ts
2840 if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
2841 avio_seek(pb, 12, SEEK_CUR);
2845 for (i = 0; i < ts->resync_size; i++) {
2850 avio_seek(pb, -1, SEEK_CUR);
2851 reanalyze(s->priv_data);
2855 av_log(s, AV_LOG_ERROR,
2856 "max resync size reached, could not find sync byte\n");
2858 return AVERROR_INVALIDDATA;
2861 /* return AVERROR_something if error or EOF. Return 0 if OK. */
2862 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
2863 const uint8_t **data)
2865 AVIOContext *pb = s->pb;
2869 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2870 if (len != TS_PACKET_SIZE)
2871 return len < 0 ? len : AVERROR_EOF;
2872 /* check packet sync byte */
2873 if ((*data)[0] != 0x47) {
2874 /* find a new packet start */
2876 if (mpegts_resync(s, raw_packet_size, *data) < 0)
2877 return AVERROR(EAGAIN);
2887 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2889 AVIOContext *pb = s->pb;
2890 int skip = raw_packet_size - TS_PACKET_SIZE;
2892 avio_skip(pb, skip);
2895 static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
2897 AVFormatContext *s = ts->stream;
2898 uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
2899 const uint8_t *data;
2903 if (avio_tell(s->pb) != ts->last_pos) {
2905 av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
2906 /* seek detected, flush pes buffer */
2907 for (i = 0; i < NB_PID_MAX; i++) {
2909 if (ts->pids[i]->type == MPEGTS_PES) {
2910 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2911 av_buffer_unref(&pes->buffer);
2912 pes->data_index = 0;
2913 pes->state = MPEGTS_SKIP; /* skip until pes header */
2914 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
2915 ts->pids[i]->u.section_filter.last_ver = -1;
2917 ts->pids[i]->last_cc = -1;
2918 ts->pids[i]->last_pcr = -1;
2925 memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2928 if (nb_packets != 0 && packet_num >= nb_packets ||
2929 ts->stop_parse > 1) {
2930 ret = AVERROR(EAGAIN);
2933 if (ts->stop_parse > 0)
2936 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2939 ret = handle_packet(ts, data, avio_tell(s->pb));
2940 finished_reading_packet(s, ts->raw_packet_size);
2944 ts->last_pos = avio_tell(s->pb);
2948 static int mpegts_probe(const AVProbeData *p)
2950 const int size = p->buf_size;
2954 int check_count = size / TS_FEC_PACKET_SIZE;
2955 #define CHECK_COUNT 10
2956 #define CHECK_BLOCK 100
2961 for (i = 0; i<check_count; i+=CHECK_BLOCK) {
2962 int left = FFMIN(check_count - i, CHECK_BLOCK);
2963 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
2964 int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
2965 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
2966 score = FFMAX3(score, dvhs_score, fec_score);
2968 maxscore = FFMAX(maxscore, score);
2971 sumscore = sumscore * CHECK_COUNT / check_count;
2972 maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
2974 ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2976 if (check_count > CHECK_COUNT && sumscore > 6) {
2977 return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2978 } else if (check_count >= CHECK_COUNT && sumscore > 6) {
2979 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2980 } else if (check_count >= CHECK_COUNT && maxscore > 6) {
2981 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2982 } else if (sumscore > 6) {
2989 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2990 * (-1) if not available */
2991 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
2993 int afc, len, flags;
2997 afc = (packet[3] >> 4) & 3;
2999 return AVERROR_INVALIDDATA;
3004 return AVERROR_INVALIDDATA;
3007 if (!(flags & 0x10))
3008 return AVERROR_INVALIDDATA;
3010 return AVERROR_INVALIDDATA;
3012 *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
3013 *ppcr_low = ((p[4] & 1) << 8) | p[5];
3017 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
3019 /* NOTE: We attempt to seek on non-seekable files as well, as the
3020 * probe buffer usually is big enough. Only warn if the seek failed
3021 * on files where the seek should work. */
3022 if (avio_seek(pb, pos, SEEK_SET) < 0)
3023 av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
3026 static int mpegts_read_header(AVFormatContext *s)
3028 MpegTSContext *ts = s->priv_data;
3029 AVIOContext *pb = s->pb;
3030 int64_t pos, probesize = s->probesize;
3032 s->internal->prefer_codec_framerate = 1;
3034 if (ffio_ensure_seekback(pb, probesize) < 0)
3035 av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
3037 pos = avio_tell(pb);
3038 ts->raw_packet_size = get_packet_size(s);
3039 if (ts->raw_packet_size <= 0) {
3040 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
3041 ts->raw_packet_size = TS_PACKET_SIZE;
3046 if (s->iformat == &ff_mpegts_demuxer) {
3049 /* first do a scan to get all the services */
3050 seek_back(s, pb, pos);
3052 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
3053 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
3054 mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
3056 handle_packets(ts, probesize / ts->raw_packet_size);
3057 /* if could not find service, enable auto_guess */
3061 av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
3063 s->ctx_flags |= AVFMTCTX_NOHEADER;
3066 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
3067 int64_t pcrs[2], pcr_h;
3068 int packet_count[2];
3069 uint8_t packet[TS_PACKET_SIZE];
3070 const uint8_t *data;
3072 /* only read packets */
3074 st = avformat_new_stream(s, NULL);
3076 return AVERROR(ENOMEM);
3077 avpriv_set_pts_info(st, 60, 1, 27000000);
3078 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3079 st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
3081 /* we iterate until we find two PCRs to estimate the bitrate */
3086 ret = read_packet(s, packet, ts->raw_packet_size, &data);
3089 pid = AV_RB16(data + 1) & 0x1fff;
3090 if ((pcr_pid == -1 || pcr_pid == pid) &&
3091 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
3092 finished_reading_packet(s, ts->raw_packet_size);
3094 packet_count[nb_pcrs] = nb_packets;
3095 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
3098 if (pcrs[1] - pcrs[0] > 0) {
3099 /* the difference needs to be positive to make sense for bitrate computation */
3102 av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
3104 packet_count[0] = packet_count[1];
3109 finished_reading_packet(s, ts->raw_packet_size);
3114 /* NOTE1: the bitrate is computed without the FEC */
3115 /* NOTE2: it is only the bitrate of the start of the stream */
3116 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
3117 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
3118 s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
3119 st->codecpar->bit_rate = s->bit_rate;
3120 st->start_time = ts->cur_pcr;
3121 av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
3122 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
3125 seek_back(s, pb, pos);
3129 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
3131 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
3133 MpegTSContext *ts = s->priv_data;
3135 int64_t pcr_h, next_pcr_h, pos;
3136 int pcr_l, next_pcr_l;
3137 uint8_t pcr_buf[12];
3138 const uint8_t *data;
3140 if ((ret = av_new_packet(pkt, TS_PACKET_SIZE)) < 0)
3142 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
3143 pkt->pos = avio_tell(s->pb);
3147 if (data != pkt->data)
3148 memcpy(pkt->data, data, ts->raw_packet_size);
3149 finished_reading_packet(s, ts->raw_packet_size);
3150 if (ts->mpeg2ts_compute_pcr) {
3151 /* compute exact PCR for each packet */
3152 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
3153 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
3154 pos = avio_tell(s->pb);
3155 for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
3156 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
3157 avio_read(s->pb, pcr_buf, 12);
3158 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
3159 /* XXX: not precise enough */
3161 ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
3166 avio_seek(s->pb, pos, SEEK_SET);
3167 /* no next PCR found: we use previous increment */
3168 ts->cur_pcr = pcr_h * 300 + pcr_l;
3170 pkt->pts = ts->cur_pcr;
3171 pkt->duration = ts->pcr_incr;
3172 ts->cur_pcr += ts->pcr_incr;
3174 pkt->stream_index = 0;
3178 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
3180 MpegTSContext *ts = s->priv_data;
3185 ret = handle_packets(ts, 0);
3187 av_packet_unref(ts->pkt);
3188 /* flush pes data left */
3189 for (i = 0; i < NB_PID_MAX; i++)
3190 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
3191 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
3192 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
3193 ret = new_pes_packet(pes, pkt);
3196 pes->state = MPEGTS_SKIP;
3203 if (!ret && pkt->size < 0)
3204 ret = AVERROR_INVALIDDATA;
3208 static void mpegts_free(MpegTSContext *ts)
3214 for (i = 0; i < FF_ARRAY_ELEMS(ts->pools); i++)
3215 av_buffer_pool_uninit(&ts->pools[i]);
3217 for (i = 0; i < NB_PID_MAX; i++)
3219 mpegts_close_filter(ts, ts->pids[i]);
3222 static int mpegts_read_close(AVFormatContext *s)
3224 MpegTSContext *ts = s->priv_data;
3229 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
3230 int64_t *ppos, int64_t pos_limit)
3232 MpegTSContext *ts = s->priv_data;
3233 int64_t pos, timestamp;
3234 uint8_t buf[TS_PACKET_SIZE];
3235 int pcr_l, pcr_pid =
3236 ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
3237 int pos47 = ts->pos47_full % ts->raw_packet_size;
3239 ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
3240 ts->raw_packet_size + pos47;
3241 while(pos < pos_limit) {
3242 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3243 return AV_NOPTS_VALUE;
3244 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
3245 return AV_NOPTS_VALUE;
3246 if (buf[0] != 0x47) {
3247 if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
3248 return AV_NOPTS_VALUE;
3249 pos = avio_tell(s->pb);
3252 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
3253 parse_pcr(×tamp, &pcr_l, buf) == 0) {
3257 pos += ts->raw_packet_size;
3260 return AV_NOPTS_VALUE;
3263 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
3264 int64_t *ppos, int64_t pos_limit)
3266 MpegTSContext *ts = s->priv_data;
3268 int pos47 = ts->pos47_full % ts->raw_packet_size;
3269 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
3270 ff_read_frame_flush(s);
3271 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3272 return AV_NOPTS_VALUE;
3273 while(pos < pos_limit) {
3276 av_init_packet(&pkt);
3277 ret = av_read_frame(s, &pkt);
3279 return AV_NOPTS_VALUE;
3280 if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
3281 ff_reduce_index(s, pkt.stream_index);
3282 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
3283 if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
3284 int64_t dts = pkt.dts;
3286 av_packet_unref(&pkt);
3291 av_packet_unref(&pkt);
3294 return AV_NOPTS_VALUE;
3297 /**************************************************************/
3298 /* parsing functions - called from other demuxers such as RTP */
3300 MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
3304 ts = av_mallocz(sizeof(MpegTSContext));
3307 /* no stream case, currently used by RTP */
3308 ts->raw_packet_size = TS_PACKET_SIZE;
3312 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
3313 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
3314 mpegts_open_section_filter(ts, EIT_PID, eit_cb, ts, 1);
3319 /* return the consumed length if a packet was output, or -1 if no
3320 * packet is output */
3321 int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
3322 const uint8_t *buf, int len)
3330 if (len < TS_PACKET_SIZE)
3331 return AVERROR_INVALIDDATA;
3332 if (buf[0] != 0x47) {
3336 handle_packet(ts, buf, len1 - len + TS_PACKET_SIZE);
3337 buf += TS_PACKET_SIZE;
3338 len -= TS_PACKET_SIZE;
3339 if (ts->stop_parse == 1)
3346 void avpriv_mpegts_parse_close(MpegTSContext *ts)
3352 AVInputFormat ff_mpegts_demuxer = {
3354 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
3355 .priv_data_size = sizeof(MpegTSContext),
3356 .read_probe = mpegts_probe,
3357 .read_header = mpegts_read_header,
3358 .read_packet = mpegts_read_packet,
3359 .read_close = mpegts_read_close,
3360 .read_timestamp = mpegts_get_dts,
3361 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3362 .priv_class = &mpegts_class,
3365 AVInputFormat ff_mpegtsraw_demuxer = {
3366 .name = "mpegtsraw",
3367 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
3368 .priv_data_size = sizeof(MpegTSContext),
3369 .read_header = mpegts_read_header,
3370 .read_packet = mpegts_raw_read_packet,
3371 .read_close = mpegts_read_close,
3372 .read_timestamp = mpegts_get_dts,
3373 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3374 .priv_class = &mpegtsraw_class,