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"
41 /* maximum size in which we look for synchronization if
42 * synchronization is lost */
43 #define MAX_RESYNC_SIZE 65536
45 #define MAX_PES_PAYLOAD 200 * 1024
47 #define MAX_MP4_DESCR_COUNT 16
49 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \
51 if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
52 (modulus) = (dividend) % (divisor); \
53 (prev_dividend) = (dividend); \
56 enum MpegTSFilterType {
62 typedef struct MpegTSFilter MpegTSFilter;
64 typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
65 int is_start, int64_t pos);
67 typedef struct MpegTSPESFilter {
72 typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
74 typedef void SetServiceCallback (void *opaque, int ret);
76 typedef struct MpegTSSectionFilter {
83 unsigned int check_crc : 1;
84 unsigned int end_of_section_reached : 1;
85 SectionCallback *section_cb;
87 } MpegTSSectionFilter;
92 int last_cc; /* last cc code (-1 if first packet) */
95 enum MpegTSFilterType type;
97 MpegTSPESFilter pes_filter;
98 MpegTSSectionFilter section_filter;
102 #define MAX_PIDS_PER_PROGRAM 64
104 unsigned int id; // program id/service id
105 unsigned int nb_pids;
106 unsigned int pids[MAX_PIDS_PER_PROGRAM];
108 /** have we found pmt for this program */
112 struct MpegTSContext {
113 const AVClass *class;
115 AVFormatContext *stream;
116 /** raw packet size, including FEC if present */
121 #define SIZE_STAT_THRESHOLD 10
125 /** if true, all pids are analyzed to find streams */
128 /** compute exact PCR for each transport stream packet */
129 int mpeg2ts_compute_pcr;
131 /** fix dvb teletext pts */
132 int fix_teletext_pts;
134 int64_t cur_pcr; /**< used to estimate the exact PCR */
135 int pcr_incr; /**< used to estimate the exact PCR */
137 /* data needed to handle file based ts */
138 /** stop parsing loop */
140 /** packet containing Audio/Video data */
142 /** to detect seek */
147 int skip_unknown_pmt;
152 int merge_pmt_versions;
154 /******************************************/
155 /* private mpegts data */
157 /** structure to keep track of Program->pids mapping */
161 int8_t crc_validity[NB_PID_MAX];
162 /** filters for various streams specified by PMT + for the PAT and PMT */
163 MpegTSFilter *pids[NB_PID_MAX];
167 #define MPEGTS_OPTIONS \
168 { "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 }
170 static const AVOption options[] = {
172 {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
173 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
174 {"ts_packetsize", "output option carrying the raw packet size", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
175 {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
176 {"scan_all_pmts", "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
177 {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM },
178 {"skip_unknown_pmt", "skip PMTs for programs not advertised in the PAT", offsetof(MpegTSContext, skip_unknown_pmt), AV_OPT_TYPE_BOOL,
179 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
180 {"merge_pmt_versions", "re-use streams when PMT's version/pids change", offsetof(MpegTSContext, merge_pmt_versions), AV_OPT_TYPE_BOOL,
181 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
182 {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
183 {.i64 = 0}, 0, 1, 0 },
184 {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
185 {.i64 = 0}, 0, 1, 0 },
189 static const AVClass mpegts_class = {
190 .class_name = "mpegts demuxer",
191 .item_name = av_default_item_name,
193 .version = LIBAVUTIL_VERSION_INT,
196 static const AVOption raw_options[] = {
198 { "compute_pcr", "compute exact PCR for each transport stream packet",
199 offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
200 { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
201 { "ts_packetsize", "output option carrying the raw packet size",
202 offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
204 AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
208 static const AVClass mpegtsraw_class = {
209 .class_name = "mpegtsraw demuxer",
210 .item_name = av_default_item_name,
211 .option = raw_options,
212 .version = LIBAVUTIL_VERSION_INT,
215 /* TS stream handling */
220 MPEGTS_PESHEADER_FILL,
225 /* enough for PES header + length */
226 #define PES_START_SIZE 6
227 #define PES_HEADER_SIZE 9
228 #define MAX_PES_HEADER_SIZE (9 + 255)
230 typedef struct PESContext {
232 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
235 AVFormatContext *stream;
237 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
238 enum MpegTSState state;
239 /* used to get the format */
241 int flags; /**< copied to the AVPacket flags */
244 int extended_stream_id;
247 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
248 uint8_t header[MAX_PES_HEADER_SIZE];
254 extern AVInputFormat ff_mpegts_demuxer;
256 static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
259 for (i = 0; i < ts->nb_prg; i++) {
260 if (ts->prg[i].id == programid) {
267 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
269 AVProgram *prg = NULL;
272 for (i = 0; i < ts->stream->nb_programs; i++)
273 if (ts->stream->programs[i]->id == programid) {
274 prg = ts->stream->programs[i];
279 prg->nb_stream_indexes = 0;
282 static void clear_program(MpegTSContext *ts, unsigned int programid)
286 clear_avprogram(ts, programid);
287 for (i = 0; i < ts->nb_prg; i++)
288 if (ts->prg[i].id == programid) {
289 ts->prg[i].nb_pids = 0;
290 ts->prg[i].pmt_found = 0;
294 static void clear_programs(MpegTSContext *ts)
300 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
303 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
307 p = &ts->prg[ts->nb_prg];
314 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
317 struct Program *p = get_program(ts, programid);
322 if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
325 for (i = 0; i < p->nb_pids; i++)
326 if (p->pids[i] == pid)
329 p->pids[p->nb_pids++] = pid;
332 static void set_pmt_found(MpegTSContext *ts, unsigned int programid)
334 struct Program *p = get_program(ts, programid);
341 static void update_av_program_info(AVFormatContext *s, unsigned int programid,
342 unsigned int pid, int version)
345 for (i = 0; i < s->nb_programs; i++) {
346 AVProgram *program = s->programs[i];
347 if (program->id == programid) {
348 int old_pcr_pid = program->pcr_pid,
349 old_version = program->pmt_version;
350 program->pcr_pid = pid;
351 program->pmt_version = version;
353 if (old_version != -1 && old_version != version) {
354 av_log(s, AV_LOG_VERBOSE,
355 "detected PMT change (program=%d, version=%d/%d, pcr_pid=0x%x/0x%x)\n",
356 programid, old_version, version, old_pcr_pid, pid);
364 * @brief discard_pid() decides if the pid is to be discarded according
365 * to caller's programs selection
366 * @param ts : - TS context
368 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
371 static int discard_pid(MpegTSContext *ts, unsigned int pid)
374 int used = 0, discarded = 0;
377 /* If none of the programs have .discard=AVDISCARD_ALL then there's
378 * no way we have to discard this packet */
379 for (k = 0; k < ts->stream->nb_programs; k++)
380 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
382 if (k == ts->stream->nb_programs)
385 for (i = 0; i < ts->nb_prg; i++) {
387 for (j = 0; j < p->nb_pids; j++) {
388 if (p->pids[j] != pid)
390 // is program with id p->id set to be discarded?
391 for (k = 0; k < ts->stream->nb_programs; k++) {
392 if (ts->stream->programs[k]->id == p->id) {
393 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
402 return !used && discarded;
406 * Assemble PES packets out of TS packets, and then call the "section_cb"
407 * function when they are complete.
409 static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
410 const uint8_t *buf, int buf_size, int is_start)
412 MpegTSSectionFilter *tss = &tss1->u.section_filter;
413 uint8_t *cur_section_buf = NULL;
417 memcpy(tss->section_buf, buf, buf_size);
418 tss->section_index = buf_size;
419 tss->section_h_size = -1;
420 tss->end_of_section_reached = 0;
422 if (tss->end_of_section_reached)
424 len = MAX_SECTION_SIZE - tss->section_index;
427 memcpy(tss->section_buf + tss->section_index, buf, len);
428 tss->section_index += len;
432 cur_section_buf = tss->section_buf;
433 while (cur_section_buf - tss->section_buf < MAX_SECTION_SIZE && cur_section_buf[0] != 0xff) {
434 /* compute section length if possible */
435 if (tss->section_h_size == -1 && tss->section_index - offset >= 3) {
436 len = (AV_RB16(cur_section_buf + 1) & 0xfff) + 3;
437 if (len > MAX_SECTION_SIZE)
439 tss->section_h_size = len;
442 if (tss->section_h_size != -1 &&
443 tss->section_index >= offset + tss->section_h_size) {
445 tss->end_of_section_reached = 1;
447 if (tss->check_crc) {
448 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, cur_section_buf, tss->section_h_size);
449 if (tss->section_h_size >= 4)
450 tss->crc = AV_RB32(cur_section_buf + tss->section_h_size - 4);
453 ts->crc_validity[ tss1->pid ] = 100;
454 }else if (ts->crc_validity[ tss1->pid ] > -10) {
455 ts->crc_validity[ tss1->pid ]--;
460 tss->section_cb(tss1, cur_section_buf, tss->section_h_size);
465 cur_section_buf += tss->section_h_size;
466 offset += tss->section_h_size;
467 tss->section_h_size = -1;
469 tss->section_h_size = -1;
470 tss->end_of_section_reached = 0;
476 static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
477 enum MpegTSFilterType type)
479 MpegTSFilter *filter;
481 av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
483 if (pid >= NB_PID_MAX || ts->pids[pid])
485 filter = av_mallocz(sizeof(MpegTSFilter));
488 ts->pids[pid] = filter;
493 filter->last_cc = -1;
494 filter->last_pcr= -1;
499 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
501 SectionCallback *section_cb,
505 MpegTSFilter *filter;
506 MpegTSSectionFilter *sec;
508 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION)))
510 sec = &filter->u.section_filter;
511 sec->section_cb = section_cb;
512 sec->opaque = opaque;
513 sec->section_buf = av_mallocz(MAX_SECTION_SIZE);
514 sec->check_crc = check_crc;
517 if (!sec->section_buf) {
524 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
528 MpegTSFilter *filter;
529 MpegTSPESFilter *pes;
531 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
534 pes = &filter->u.pes_filter;
535 pes->pes_cb = pes_cb;
536 pes->opaque = opaque;
540 static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
542 return mpegts_open_filter(ts, pid, MPEGTS_PCR);
545 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
550 if (filter->type == MPEGTS_SECTION)
551 av_freep(&filter->u.section_filter.section_buf);
552 else if (filter->type == MPEGTS_PES) {
553 PESContext *pes = filter->u.pes_filter.opaque;
554 av_buffer_unref(&pes->buffer);
555 /* referenced private data will be freed later in
556 * avformat_close_input (pes->st->priv_data == pes) */
557 if (!pes->st || pes->merged_st) {
558 av_freep(&filter->u.pes_filter.opaque);
563 ts->pids[pid] = NULL;
566 static int analyze(const uint8_t *buf, int size, int packet_size,
569 int stat[TS_MAX_PACKET_SIZE];
574 memset(stat, 0, packet_size * sizeof(*stat));
576 for (i = 0; i < size - 3; i++) {
577 if (buf[i] == 0x47) {
578 int pid = AV_RB16(buf+1) & 0x1FFF;
579 int asc = buf[i + 3] & 0x30;
580 if (!probe || pid == 0x1FFF || asc) {
581 int x = i % packet_size;
584 if (stat[x] > best_score) {
585 best_score = stat[x];
591 return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
594 /* autodetect fec presence. Must have at least 1024 bytes */
595 static int get_packet_size(const uint8_t *buf, int size)
597 int score, fec_score, dvhs_score;
599 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
600 return AVERROR_INVALIDDATA;
602 score = analyze(buf, size, TS_PACKET_SIZE, 0);
603 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, 0);
604 fec_score = analyze(buf, size, TS_FEC_PACKET_SIZE, 0);
605 av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
606 score, dvhs_score, fec_score);
608 if (score > fec_score && score > dvhs_score)
609 return TS_PACKET_SIZE;
610 else if (dvhs_score > score && dvhs_score > fec_score)
611 return TS_DVHS_PACKET_SIZE;
612 else if (score < fec_score && dvhs_score < fec_score)
613 return TS_FEC_PACKET_SIZE;
615 return AVERROR_INVALIDDATA;
618 typedef struct SectionHeader {
623 uint8_t last_sec_num;
626 static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
628 if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
631 tssf->last_ver = h->version;
632 tssf->last_crc = tssf->crc;
637 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
644 return AVERROR_INVALIDDATA;
650 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
657 return AVERROR_INVALIDDATA;
664 /* read and allocate a DVB string preceded by its length */
665 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
672 len = get8(&p, p_end);
677 str = av_malloc(len + 1);
687 static int parse_section_header(SectionHeader *h,
688 const uint8_t **pp, const uint8_t *p_end)
692 val = get8(pp, p_end);
697 val = get16(pp, p_end);
701 val = get8(pp, p_end);
704 h->version = (val >> 1) & 0x1f;
705 val = get8(pp, p_end);
709 val = get8(pp, p_end);
712 h->last_sec_num = val;
716 typedef struct StreamType {
717 uint32_t stream_type;
718 enum AVMediaType codec_type;
719 enum AVCodecID codec_id;
722 static const StreamType ISO_types[] = {
723 { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
724 { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
725 { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
726 { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
727 { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
728 { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
729 /* Makito encoder sets stream type 0x11 for AAC,
730 * so auto-detect LOAS/LATM instead of hardcoding it. */
731 #if !CONFIG_LOAS_DEMUXER
732 { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
734 { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
735 { 0x1c, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
736 { 0x20, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
737 { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000 },
738 { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
739 { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
740 { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
741 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
745 static const StreamType HDMV_types[] = {
746 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
747 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
748 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
749 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
750 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
751 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
752 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
753 { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
754 { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
755 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
756 { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
761 static const StreamType SCTE_types[] = {
762 { 0x86, AVMEDIA_TYPE_DATA, AV_CODEC_ID_SCTE_35 },
767 static const StreamType MISC_types[] = {
768 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
769 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
773 static const StreamType REGD_types[] = {
774 { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
775 { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
776 { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
777 { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
778 { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
779 { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
780 { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
781 { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
782 { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
783 { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
784 { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
785 { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS },
789 static const StreamType METADATA_types[] = {
790 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
791 { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
795 /* descriptor present */
796 static const StreamType DESC_types[] = {
797 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
798 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
799 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
800 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
801 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
805 static void mpegts_find_stream_type(AVStream *st,
806 uint32_t stream_type,
807 const StreamType *types)
809 for (; types->stream_type; types++)
810 if (stream_type == types->stream_type) {
811 if (st->codecpar->codec_type != types->codec_type ||
812 st->codecpar->codec_id != types->codec_id) {
813 st->codecpar->codec_type = types->codec_type;
814 st->codecpar->codec_id = types->codec_id;
815 st->internal->need_context_update = 1;
817 st->request_probe = 0;
822 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
823 uint32_t stream_type, uint32_t prog_reg_desc)
825 int old_codec_type = st->codecpar->codec_type;
826 int old_codec_id = st->codecpar->codec_id;
827 int old_codec_tag = st->codecpar->codec_tag;
829 if (avcodec_is_open(st->internal->avctx)) {
830 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, internal codec is open\n");
834 avpriv_set_pts_info(st, 33, 1, 90000);
836 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
837 st->codecpar->codec_id = AV_CODEC_ID_NONE;
838 st->need_parsing = AVSTREAM_PARSE_FULL;
840 pes->stream_type = stream_type;
842 av_log(pes->stream, AV_LOG_DEBUG,
843 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
844 st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
846 st->codecpar->codec_tag = pes->stream_type;
848 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
849 if (pes->stream_type == 4 || pes->stream_type == 0x0f)
850 st->request_probe = 50;
851 if ((prog_reg_desc == AV_RL32("HDMV") ||
852 prog_reg_desc == AV_RL32("HDPR")) &&
853 st->codecpar->codec_id == AV_CODEC_ID_NONE) {
854 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
855 if (pes->stream_type == 0x83) {
856 // HDMV TrueHD streams also contain an AC3 coded version of the
857 // audio track - add a second stream for this
859 // priv_data cannot be shared between streams
860 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
862 return AVERROR(ENOMEM);
863 memcpy(sub_pes, pes, sizeof(*sub_pes));
865 sub_st = avformat_new_stream(pes->stream, NULL);
868 return AVERROR(ENOMEM);
871 sub_st->id = pes->pid;
872 avpriv_set_pts_info(sub_st, 33, 1, 90000);
873 sub_st->priv_data = sub_pes;
874 sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
875 sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
876 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
877 sub_pes->sub_st = pes->sub_st = sub_st;
880 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
881 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
882 if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
883 st->codecpar->codec_id = old_codec_id;
884 st->codecpar->codec_type = old_codec_type;
886 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
887 (st->request_probe > 0 && st->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
888 st->probe_packets > 0 &&
889 stream_type == STREAM_TYPE_PRIVATE_DATA) {
890 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
891 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
892 st->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
895 /* queue a context update if properties changed */
896 if (old_codec_type != st->codecpar->codec_type ||
897 old_codec_id != st->codecpar->codec_id ||
898 old_codec_tag != st->codecpar->codec_tag)
899 st->internal->need_context_update = 1;
904 static void reset_pes_packet_state(PESContext *pes)
906 pes->pts = AV_NOPTS_VALUE;
907 pes->dts = AV_NOPTS_VALUE;
910 av_buffer_unref(&pes->buffer);
913 static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
916 pkt->data = (uint8_t *)buffer;
920 static int new_pes_packet(PESContext *pes, AVPacket *pkt)
926 pkt->buf = pes->buffer;
927 pkt->data = pes->buffer->data;
928 pkt->size = pes->data_index;
930 if (pes->total_size != MAX_PES_PAYLOAD &&
931 pes->pes_header_size + pes->data_index != pes->total_size +
933 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
934 pes->flags |= AV_PKT_FLAG_CORRUPT;
936 memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
938 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
939 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
940 pkt->stream_index = pes->sub_st->index;
942 pkt->stream_index = pes->st->index;
945 /* store position of first TS packet of this PES packet */
946 pkt->pos = pes->ts_packet_pos;
947 pkt->flags = pes->flags;
950 reset_pes_packet_state(pes);
952 sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
954 return AVERROR(ENOMEM);
955 *sd = pes->stream_id;
960 static uint64_t get_ts64(GetBitContext *gb, int bits)
962 if (get_bits_left(gb) < bits)
963 return AV_NOPTS_VALUE;
964 return get_bits64(gb, bits);
967 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
968 const uint8_t *buf, int buf_size)
971 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
972 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
973 int dts_flag = -1, cts_flag = -1;
974 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
975 uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
976 int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
978 memcpy(buf_padded, buf, buf_padded_size);
980 init_get_bits(&gb, buf_padded, buf_padded_size * 8);
982 if (sl->use_au_start)
983 au_start_flag = get_bits1(&gb);
985 au_end_flag = get_bits1(&gb);
986 if (!sl->use_au_start && !sl->use_au_end)
987 au_start_flag = au_end_flag = 1;
989 ocr_flag = get_bits1(&gb);
991 idle_flag = get_bits1(&gb);
993 padding_flag = get_bits1(&gb);
995 padding_bits = get_bits(&gb, 3);
997 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
998 if (sl->packet_seq_num_len)
999 skip_bits_long(&gb, sl->packet_seq_num_len);
1000 if (sl->degr_prior_len)
1002 skip_bits(&gb, sl->degr_prior_len);
1004 skip_bits_long(&gb, sl->ocr_len);
1005 if (au_start_flag) {
1006 if (sl->use_rand_acc_pt)
1008 if (sl->au_seq_num_len > 0)
1009 skip_bits_long(&gb, sl->au_seq_num_len);
1010 if (sl->use_timestamps) {
1011 dts_flag = get_bits1(&gb);
1012 cts_flag = get_bits1(&gb);
1015 if (sl->inst_bitrate_len)
1016 inst_bitrate_flag = get_bits1(&gb);
1018 dts = get_ts64(&gb, sl->timestamp_len);
1020 cts = get_ts64(&gb, sl->timestamp_len);
1022 skip_bits_long(&gb, sl->au_len);
1023 if (inst_bitrate_flag)
1024 skip_bits_long(&gb, sl->inst_bitrate_len);
1027 if (dts != AV_NOPTS_VALUE)
1029 if (cts != AV_NOPTS_VALUE)
1032 if (sl->timestamp_len && sl->timestamp_res)
1033 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
1035 return (get_bits_count(&gb) + 7) >> 3;
1038 /* return non zero if a packet could be constructed */
1039 static int mpegts_push_data(MpegTSFilter *filter,
1040 const uint8_t *buf, int buf_size, int is_start,
1043 PESContext *pes = filter->u.pes_filter.opaque;
1044 MpegTSContext *ts = pes->ts;
1052 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1053 ret = new_pes_packet(pes, ts->pkt);
1058 reset_pes_packet_state(pes);
1060 pes->state = MPEGTS_HEADER;
1061 pes->ts_packet_pos = pos;
1064 while (buf_size > 0) {
1065 switch (pes->state) {
1067 len = PES_START_SIZE - pes->data_index;
1070 memcpy(pes->header + pes->data_index, p, len);
1071 pes->data_index += len;
1074 if (pes->data_index == PES_START_SIZE) {
1075 /* we got all the PES or section header. We can now
1077 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
1078 pes->header[2] == 0x01) {
1079 /* it must be an MPEG-2 PES stream */
1080 code = pes->header[3] | 0x100;
1081 av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
1083 pes->stream_id = pes->header[3];
1085 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
1087 pes->sub_st->discard == AVDISCARD_ALL)) ||
1088 code == 0x1be) /* padding_stream */
1091 /* stream not present in PMT */
1093 if (ts->skip_changes)
1095 if (ts->merge_pmt_versions)
1096 goto skip; /* wait for PMT to merge new stream */
1098 pes->st = avformat_new_stream(ts->stream, NULL);
1100 return AVERROR(ENOMEM);
1101 pes->st->id = pes->pid;
1102 mpegts_set_stream_info(pes->st, pes, 0, 0);
1105 pes->total_size = AV_RB16(pes->header + 4);
1106 /* NOTE: a zero total size means the PES size is
1108 if (!pes->total_size)
1109 pes->total_size = MAX_PES_PAYLOAD;
1111 /* allocate pes buffer */
1112 pes->buffer = av_buffer_alloc(pes->total_size +
1113 AV_INPUT_BUFFER_PADDING_SIZE);
1115 return AVERROR(ENOMEM);
1117 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
1118 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
1119 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
1120 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
1121 pes->state = MPEGTS_PESHEADER;
1122 if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
1123 av_log(pes->stream, AV_LOG_TRACE,
1124 "pid=%x stream_type=%x probing\n",
1127 pes->st->request_probe = 1;
1130 pes->pes_header_size = 6;
1131 pes->state = MPEGTS_PAYLOAD;
1132 pes->data_index = 0;
1135 /* otherwise, it should be a table */
1138 pes->state = MPEGTS_SKIP;
1143 /**********************************************/
1144 /* PES packing parsing */
1145 case MPEGTS_PESHEADER:
1146 len = PES_HEADER_SIZE - pes->data_index;
1148 return AVERROR_INVALIDDATA;
1151 memcpy(pes->header + pes->data_index, p, len);
1152 pes->data_index += len;
1155 if (pes->data_index == PES_HEADER_SIZE) {
1156 pes->pes_header_size = pes->header[8] + 9;
1157 pes->state = MPEGTS_PESHEADER_FILL;
1160 case MPEGTS_PESHEADER_FILL:
1161 len = pes->pes_header_size - pes->data_index;
1163 return AVERROR_INVALIDDATA;
1166 memcpy(pes->header + pes->data_index, p, len);
1167 pes->data_index += len;
1170 if (pes->data_index == pes->pes_header_size) {
1172 unsigned int flags, pes_ext, skip;
1174 flags = pes->header[7];
1175 r = pes->header + 9;
1176 pes->pts = AV_NOPTS_VALUE;
1177 pes->dts = AV_NOPTS_VALUE;
1178 if ((flags & 0xc0) == 0x80) {
1179 pes->dts = pes->pts = ff_parse_pes_pts(r);
1181 } else if ((flags & 0xc0) == 0xc0) {
1182 pes->pts = ff_parse_pes_pts(r);
1184 pes->dts = ff_parse_pes_pts(r);
1187 pes->extended_stream_id = -1;
1188 if (flags & 0x01) { /* PES extension */
1190 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1191 skip = (pes_ext >> 4) & 0xb;
1194 if ((pes_ext & 0x41) == 0x01 &&
1195 (r + 2) <= (pes->header + pes->pes_header_size)) {
1196 /* PES extension 2 */
1197 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1198 pes->extended_stream_id = r[1];
1202 /* we got the full header. We parse it and get the payload */
1203 pes->state = MPEGTS_PAYLOAD;
1204 pes->data_index = 0;
1205 if (pes->stream_type == 0x12 && buf_size > 0) {
1206 int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
1208 pes->pes_header_size += sl_header_bytes;
1209 p += sl_header_bytes;
1210 buf_size -= sl_header_bytes;
1212 if (pes->stream_type == 0x15 && buf_size >= 5) {
1213 /* skip metadata access unit header */
1214 pes->pes_header_size += 5;
1218 if ( pes->ts->fix_teletext_pts
1219 && ( pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
1220 || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1222 AVProgram *p = NULL;
1224 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1225 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1226 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1228 AVStream *st = NULL;
1229 if (f->type == MPEGTS_PES) {
1230 PESContext *pcrpes = f->u.pes_filter.opaque;
1233 } else if (f->type == MPEGTS_PCR) {
1235 for (i = 0; i < p->nb_stream_indexes; i++) {
1236 AVStream *pst = pes->stream->streams[p->stream_index[i]];
1237 if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1241 if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
1242 // teletext packets do not always have correct timestamps,
1243 // the standard says they should be handled after 40.6 ms at most,
1244 // and the pcr error to this packet should be no more than 100 ms.
1245 // TODO: we should interpolate the PCR, not just use the last one
1246 int64_t pcr = f->last_pcr / 300;
1248 pes->st->pts_wrap_reference = st->pts_wrap_reference;
1249 pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
1250 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1251 pes->pts = pes->dts = pcr;
1252 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1253 pes->dts > pcr + 3654 + 9000) {
1254 pes->pts = pes->dts = pcr + 3654 + 9000;
1255 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1256 pes->dts > pcr + 10*90000) { //10sec
1257 pes->pts = pes->dts = pcr + 3654 + 9000;
1266 av_log(pes->stream, AV_LOG_VERBOSE,
1267 "Forcing DTS/PTS to be unset for a "
1268 "non-trustworthy PES packet for PID %d as "
1269 "PCR hasn't been received yet.\n",
1271 pes->dts = pes->pts = AV_NOPTS_VALUE;
1276 case MPEGTS_PAYLOAD:
1278 if (pes->data_index > 0 &&
1279 pes->data_index + buf_size > pes->total_size) {
1280 ret = new_pes_packet(pes, ts->pkt);
1283 pes->total_size = MAX_PES_PAYLOAD;
1284 pes->buffer = av_buffer_alloc(pes->total_size +
1285 AV_INPUT_BUFFER_PADDING_SIZE);
1287 return AVERROR(ENOMEM);
1289 } else if (pes->data_index == 0 &&
1290 buf_size > pes->total_size) {
1291 // pes packet size is < ts size packet and pes data is padded with 0xff
1292 // not sure if this is legal in ts but see issue #2392
1293 buf_size = pes->total_size;
1295 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1296 pes->data_index += buf_size;
1297 /* emit complete packets with known packet size
1298 * decreases demuxer delay for infrequent packets like subtitles from
1299 * a couple of seconds to milliseconds for properly muxed files.
1300 * total_size is the number of bytes following pes_packet_length
1301 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1302 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1303 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1305 ret = new_pes_packet(pes, ts->pkt);
1321 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1326 /* if no pid found, then add a pid context */
1327 pes = av_mallocz(sizeof(PESContext));
1331 pes->stream = ts->stream;
1333 pes->pcr_pid = pcr_pid;
1334 pes->state = MPEGTS_SKIP;
1335 pes->pts = AV_NOPTS_VALUE;
1336 pes->dts = AV_NOPTS_VALUE;
1337 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1346 typedef struct MP4DescrParseContext {
1350 Mp4Descr *active_descr;
1352 int max_descr_count;
1354 int predefined_SLConfigDescriptor_seen;
1355 } MP4DescrParseContext;
1357 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
1358 const uint8_t *buf, unsigned size,
1359 Mp4Descr *descr, int max_descr_count)
1362 if (size > (1 << 30))
1363 return AVERROR_INVALIDDATA;
1365 if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
1366 NULL, NULL, NULL, NULL)) < 0)
1373 d->active_descr = NULL;
1374 d->max_descr_count = max_descr_count;
1379 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1381 int64_t new_off = avio_tell(pb);
1382 (*len) -= new_off - *off;
1386 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1389 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1392 int ret = parse_mp4_descr(d, off, len, 0);
1395 update_offsets(&d->pb, &off, &len);
1400 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1402 avio_rb16(&d->pb); // ID
1408 update_offsets(&d->pb, &off, &len);
1409 return parse_mp4_descr_arr(d, off, len);
1412 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1417 id_flags = avio_rb16(&d->pb);
1418 if (!(id_flags & 0x0020)) { // URL_Flag
1419 update_offsets(&d->pb, &off, &len);
1420 return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1426 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1431 if (d->descr_count >= d->max_descr_count)
1432 return AVERROR_INVALIDDATA;
1433 ff_mp4_parse_es_descr(&d->pb, &es_id);
1434 d->active_descr = d->descr + (d->descr_count++);
1436 d->active_descr->es_id = es_id;
1437 update_offsets(&d->pb, &off, &len);
1438 if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
1440 update_offsets(&d->pb, &off, &len);
1442 ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
1443 d->active_descr = NULL;
1447 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
1450 Mp4Descr *descr = d->active_descr;
1452 return AVERROR_INVALIDDATA;
1453 d->active_descr->dec_config_descr = av_malloc(len);
1454 if (!descr->dec_config_descr)
1455 return AVERROR(ENOMEM);
1456 descr->dec_config_descr_len = len;
1457 avio_read(&d->pb, descr->dec_config_descr, len);
1461 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1463 Mp4Descr *descr = d->active_descr;
1466 return AVERROR_INVALIDDATA;
1468 #define R8_CHECK_CLIP_MAX(dst, maxv) do { \
1469 descr->sl.dst = avio_r8(&d->pb); \
1470 if (descr->sl.dst > maxv) { \
1471 descr->sl.dst = maxv; \
1472 return AVERROR_INVALIDDATA; \
1476 predefined = avio_r8(&d->pb);
1479 int flags = avio_r8(&d->pb);
1480 descr->sl.use_au_start = !!(flags & 0x80);
1481 descr->sl.use_au_end = !!(flags & 0x40);
1482 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1483 descr->sl.use_padding = !!(flags & 0x08);
1484 descr->sl.use_timestamps = !!(flags & 0x04);
1485 descr->sl.use_idle = !!(flags & 0x02);
1486 descr->sl.timestamp_res = avio_rb32(&d->pb);
1488 R8_CHECK_CLIP_MAX(timestamp_len, 63);
1489 R8_CHECK_CLIP_MAX(ocr_len, 63);
1490 R8_CHECK_CLIP_MAX(au_len, 31);
1491 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1492 lengths = avio_rb16(&d->pb);
1493 descr->sl.degr_prior_len = lengths >> 12;
1494 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1495 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1496 } else if (!d->predefined_SLConfigDescriptor_seen){
1497 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1498 d->predefined_SLConfigDescriptor_seen = 1;
1503 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1507 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1510 update_offsets(&d->pb, &off, &len);
1511 if (len < 0 || len1 > len || len1 <= 0) {
1512 av_log(d->s, AV_LOG_ERROR,
1513 "Tag %x length violation new length %d bytes remaining %d\n",
1515 return AVERROR_INVALIDDATA;
1518 if (d->level++ >= MAX_LEVEL) {
1519 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1520 ret = AVERROR_INVALIDDATA;
1524 if (target_tag && tag != target_tag) {
1525 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1527 ret = AVERROR_INVALIDDATA;
1533 ret = parse_MP4IODescrTag(d, off, len1);
1536 ret = parse_MP4ODescrTag(d, off, len1);
1539 ret = parse_MP4ESDescrTag(d, off, len1);
1541 case MP4DecConfigDescrTag:
1542 ret = parse_MP4DecConfigDescrTag(d, off, len1);
1545 ret = parse_MP4SLDescrTag(d, off, len1);
1552 avio_seek(&d->pb, off + len1, SEEK_SET);
1556 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1557 Mp4Descr *descr, int *descr_count, int max_descr_count)
1559 MP4DescrParseContext d;
1562 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1566 ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1568 *descr_count = d.descr_count;
1572 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1573 Mp4Descr *descr, int *descr_count, int max_descr_count)
1575 MP4DescrParseContext d;
1578 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1582 ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1584 *descr_count = d.descr_count;
1588 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1591 MpegTSContext *ts = filter->u.section_filter.opaque;
1592 MpegTSSectionFilter *tssf = &filter->u.section_filter;
1594 const uint8_t *p, *p_end;
1596 int mp4_descr_count = 0;
1597 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1599 AVFormatContext *s = ts->stream;
1601 p_end = section + section_len - 4;
1603 if (parse_section_header(&h, &p, p_end) < 0)
1605 if (h.tid != M4OD_TID)
1607 if (skip_identical(&h, tssf))
1610 mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1611 MAX_MP4_DESCR_COUNT);
1613 for (pid = 0; pid < NB_PID_MAX; pid++) {
1616 for (i = 0; i < mp4_descr_count; i++) {
1619 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1621 if (ts->pids[pid]->type != MPEGTS_PES) {
1622 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1625 pes = ts->pids[pid]->u.pes_filter.opaque;
1630 pes->sl = mp4_descr[i].sl;
1632 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1633 mp4_descr[i].dec_config_descr_len, 0,
1634 NULL, NULL, NULL, NULL);
1635 ff_mp4_read_dec_config_descr(s, st, &pb);
1636 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1637 st->codecpar->extradata_size > 0)
1638 st->need_parsing = 0;
1639 if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
1640 st->codecpar->extradata_size > 0)
1641 st->need_parsing = 0;
1643 st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
1644 st->internal->need_context_update = 1;
1647 for (i = 0; i < mp4_descr_count; i++)
1648 av_free(mp4_descr[i].dec_config_descr);
1651 static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
1654 AVProgram *prg = NULL;
1655 MpegTSContext *ts = filter->u.section_filter.opaque;
1657 int idx = ff_find_stream_index(ts->stream, filter->pid);
1661 new_data_packet(section, section_len, ts->pkt);
1662 ts->pkt->stream_index = idx;
1663 prg = av_find_program_from_stream(ts->stream, NULL, idx);
1664 if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
1665 MpegTSFilter *f = ts->pids[prg->pcr_pid];
1666 if (f && f->last_pcr != -1)
1667 ts->pkt->pts = ts->pkt->dts = f->last_pcr/300;
1673 static const uint8_t opus_coupled_stream_cnt[9] = {
1674 1, 0, 1, 1, 2, 2, 2, 3, 3
1677 static const uint8_t opus_stream_cnt[9] = {
1678 1, 1, 1, 2, 2, 3, 4, 4, 5,
1681 static const uint8_t opus_channel_map[8][8] = {
1689 { 0,6,1,2,3,4,5,7 },
1692 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1693 const uint8_t **pp, const uint8_t *desc_list_end,
1694 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1697 const uint8_t *desc_end;
1698 int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
1702 desc_tag = get8(pp, desc_list_end);
1704 return AVERROR_INVALIDDATA;
1705 desc_len = get8(pp, desc_list_end);
1707 return AVERROR_INVALIDDATA;
1708 desc_end = *pp + desc_len;
1709 if (desc_end > desc_list_end)
1710 return AVERROR_INVALIDDATA;
1712 av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1714 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
1715 stream_type == STREAM_TYPE_PRIVATE_DATA)
1716 mpegts_find_stream_type(st, desc_tag, DESC_types);
1719 case 0x02: /* video stream descriptor */
1720 if (get8(pp, desc_end) & 0x1) {
1721 st->disposition |= AV_DISPOSITION_STILL_IMAGE;
1724 case 0x1E: /* SL descriptor */
1725 desc_es_id = get16(pp, desc_end);
1728 if (ts && ts->pids[pid])
1729 ts->pids[pid]->es_id = desc_es_id;
1730 for (i = 0; i < mp4_descr_count; i++)
1731 if (mp4_descr[i].dec_config_descr_len &&
1732 mp4_descr[i].es_id == desc_es_id) {
1734 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1735 mp4_descr[i].dec_config_descr_len, 0,
1736 NULL, NULL, NULL, NULL);
1737 ff_mp4_read_dec_config_descr(fc, st, &pb);
1738 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1739 st->codecpar->extradata_size > 0) {
1740 st->need_parsing = 0;
1741 st->internal->need_context_update = 1;
1743 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1744 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1747 case 0x1F: /* FMC descriptor */
1748 if (get16(pp, desc_end) < 0)
1750 if (mp4_descr_count > 0 &&
1751 (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
1752 (st->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
1753 st->request_probe > 0) &&
1754 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1756 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1757 mp4_descr->dec_config_descr_len, 0,
1758 NULL, NULL, NULL, NULL);
1759 ff_mp4_read_dec_config_descr(fc, st, &pb);
1760 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1761 st->codecpar->extradata_size > 0) {
1762 st->request_probe = st->need_parsing = 0;
1763 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1764 st->internal->need_context_update = 1;
1768 case 0x56: /* DVB teletext descriptor */
1770 uint8_t *extradata = NULL;
1771 int language_count = desc_len / 5;
1773 if (desc_len > 0 && desc_len % 5 != 0)
1774 return AVERROR_INVALIDDATA;
1776 if (language_count > 0) {
1777 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1778 av_assert0(language_count <= sizeof(language) / 4);
1780 if (st->codecpar->extradata == NULL) {
1781 if (ff_alloc_extradata(st->codecpar, language_count * 2)) {
1782 return AVERROR(ENOMEM);
1786 if (st->codecpar->extradata_size < language_count * 2)
1787 return AVERROR_INVALIDDATA;
1789 extradata = st->codecpar->extradata;
1791 for (i = 0; i < language_count; i++) {
1792 language[i * 4 + 0] = get8(pp, desc_end);
1793 language[i * 4 + 1] = get8(pp, desc_end);
1794 language[i * 4 + 2] = get8(pp, desc_end);
1795 language[i * 4 + 3] = ',';
1797 memcpy(extradata, *pp, 2);
1803 language[i * 4 - 1] = 0;
1804 av_dict_set(&st->metadata, "language", language, 0);
1805 st->internal->need_context_update = 1;
1809 case 0x59: /* subtitling descriptor */
1811 /* 8 bytes per DVB subtitle substream data:
1812 * ISO_639_language_code (3 bytes),
1813 * subtitling_type (1 byte),
1814 * composition_page_id (2 bytes),
1815 * ancillary_page_id (2 bytes) */
1816 int language_count = desc_len / 8;
1818 if (desc_len > 0 && desc_len % 8 != 0)
1819 return AVERROR_INVALIDDATA;
1821 if (language_count > 1) {
1822 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
1825 if (language_count > 0) {
1828 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1829 av_assert0(language_count <= sizeof(language) / 4);
1831 if (st->codecpar->extradata == NULL) {
1832 if (ff_alloc_extradata(st->codecpar, language_count * 5)) {
1833 return AVERROR(ENOMEM);
1837 if (st->codecpar->extradata_size < language_count * 5)
1838 return AVERROR_INVALIDDATA;
1840 extradata = st->codecpar->extradata;
1842 for (i = 0; i < language_count; i++) {
1843 language[i * 4 + 0] = get8(pp, desc_end);
1844 language[i * 4 + 1] = get8(pp, desc_end);
1845 language[i * 4 + 2] = get8(pp, desc_end);
1846 language[i * 4 + 3] = ',';
1848 /* hearing impaired subtitles detection using subtitling_type */
1850 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1851 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1852 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1853 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1854 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1855 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1856 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1860 extradata[4] = get8(pp, desc_end); /* subtitling_type */
1861 memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
1867 language[i * 4 - 1] = 0;
1868 av_dict_set(&st->metadata, "language", language, 0);
1869 st->internal->need_context_update = 1;
1873 case 0x0a: /* ISO 639 language descriptor */
1874 for (i = 0; i + 4 <= desc_len; i += 4) {
1875 language[i + 0] = get8(pp, desc_end);
1876 language[i + 1] = get8(pp, desc_end);
1877 language[i + 2] = get8(pp, desc_end);
1878 language[i + 3] = ',';
1879 switch (get8(pp, desc_end)) {
1881 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
1884 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1887 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1888 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1892 if (i && language[0]) {
1893 language[i - 1] = 0;
1894 /* don't overwrite language, as it may already have been set by
1895 * another, more specific descriptor (e.g. supplementary audio) */
1896 av_dict_set(&st->metadata, "language", language, AV_DICT_DONT_OVERWRITE);
1899 case 0x05: /* registration descriptor */
1900 st->codecpar->codec_tag = bytestream_get_le32(pp);
1901 av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
1902 if (st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) {
1903 mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
1904 if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
1905 st->request_probe = 50;
1908 case 0x52: /* stream identifier descriptor */
1909 st->stream_identifier = 1 + get8(pp, desc_end);
1911 case 0x26: /* metadata descriptor */
1912 if (get16(pp, desc_end) == 0xFFFF)
1914 if (get8(pp, desc_end) == 0xFF) {
1915 st->codecpar->codec_tag = bytestream_get_le32(pp);
1916 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
1917 mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
1920 case 0x7f: /* DVB extension descriptor */
1921 ext_desc_tag = get8(pp, desc_end);
1922 if (ext_desc_tag < 0)
1923 return AVERROR_INVALIDDATA;
1924 if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
1925 ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
1926 if (!st->codecpar->extradata) {
1927 st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
1928 AV_INPUT_BUFFER_PADDING_SIZE);
1929 if (!st->codecpar->extradata)
1930 return AVERROR(ENOMEM);
1932 st->codecpar->extradata_size = sizeof(opus_default_extradata);
1933 memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
1935 channel_config_code = get8(pp, desc_end);
1936 if (channel_config_code < 0)
1937 return AVERROR_INVALIDDATA;
1938 if (channel_config_code <= 0x8) {
1939 st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
1940 st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
1941 st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
1942 st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
1943 memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
1945 avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
1947 st->need_parsing = AVSTREAM_PARSE_FULL;
1948 st->internal->need_context_update = 1;
1951 if (ext_desc_tag == 0x06) { /* supplementary audio descriptor */
1955 return AVERROR_INVALIDDATA;
1956 flags = get8(pp, desc_end);
1958 if ((flags & 0x80) == 0) /* mix_type */
1959 st->disposition |= AV_DISPOSITION_DEPENDENT;
1961 switch ((flags >> 2) & 0x1F) { /* editorial_classification */
1963 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1964 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1967 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1970 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1974 if (flags & 0x01) { /* language_code_present */
1976 return AVERROR_INVALIDDATA;
1977 language[0] = get8(pp, desc_end);
1978 language[1] = get8(pp, desc_end);
1979 language[2] = get8(pp, desc_end);
1982 /* This language always has to override a possible
1983 * ISO 639 language descriptor language */
1985 av_dict_set(&st->metadata, "language", language, 0);
1989 case 0x6a: /* ac-3_descriptor */
1991 int component_type_flag = get8(pp, desc_end) & (1 << 7);
1992 if (component_type_flag) {
1993 int component_type = get8(pp, desc_end);
1994 int service_type_mask = 0x38; // 0b00111000
1995 int service_type = ((component_type & service_type_mask) >> 3);
1996 if (service_type == 0x02 /* 0b010 */) {
1997 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1998 av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2003 case 0x7a: /* enhanced_ac-3_descriptor */
2005 int component_type_flag = get8(pp, desc_end) & (1 << 7);
2006 if (component_type_flag) {
2007 int component_type = get8(pp, desc_end);
2008 int service_type_mask = 0x38; // 0b00111000
2009 int service_type = ((component_type & service_type_mask) >> 3);
2010 if (service_type == 0x02 /* 0b010 */) {
2011 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2012 av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2024 static AVStream *find_matching_stream(MpegTSContext *ts, int pid,
2025 int stream_identifier, int pmt_stream_idx)
2027 AVFormatContext *s = ts->stream;
2029 AVStream *found = NULL;
2031 for (i = 0; i < s->nb_streams; i++) {
2032 AVStream *st = s->streams[i];
2033 if (stream_identifier != -1) { /* match based on "stream identifier descriptor" if present */
2034 if (st->stream_identifier == stream_identifier+1) {
2038 } else if (st->pmt_stream_idx == pmt_stream_idx) { /* match based on position within the PMT */
2045 av_log(ts->stream, AV_LOG_VERBOSE,
2046 "re-using existing %s stream %d (pid=0x%x) for new pid=0x%x\n",
2047 av_get_media_type_string(found->codecpar->codec_type),
2054 static int parse_stream_identifier_desc(const uint8_t *p, const uint8_t *p_end)
2056 const uint8_t **pp = &p;
2057 const uint8_t *desc_list_end;
2058 const uint8_t *desc_end;
2060 int desc_len, desc_tag;
2062 desc_list_len = get16(pp, p_end);
2063 if (desc_list_len < 0)
2065 desc_list_len &= 0xfff;
2066 desc_list_end = p + desc_list_len;
2067 if (desc_list_end > p_end)
2071 desc_tag = get8(pp, desc_list_end);
2074 desc_len = get8(pp, desc_list_end);
2077 desc_end = *pp + desc_len;
2078 if (desc_end > desc_list_end)
2081 if (desc_tag == 0x52) {
2082 return get8(pp, desc_end);
2090 static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
2092 return !(stream_type == 0x13 ||
2093 (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
2096 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2098 MpegTSContext *ts = filter->u.section_filter.opaque;
2099 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2100 SectionHeader h1, *h = &h1;
2103 const uint8_t *p, *p_end, *desc_list_end;
2104 int program_info_length, pcr_pid, pid, stream_type;
2106 uint32_t prog_reg_desc = 0; /* registration descriptor */
2107 int stream_identifier = -1;
2109 int mp4_descr_count = 0;
2110 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
2113 av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
2114 hex_dump_debug(ts->stream, section, section_len);
2116 p_end = section + section_len - 4;
2118 if (parse_section_header(h, &p, p_end) < 0)
2120 if (h->tid != PMT_TID)
2122 if (skip_identical(h, tssf))
2125 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
2126 h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
2128 if (!ts->scan_all_pmts && ts->skip_changes)
2131 if (ts->skip_unknown_pmt && !get_program(ts, h->id))
2133 if (!ts->skip_clear)
2134 clear_program(ts, h->id);
2136 pcr_pid = get16(&p, p_end);
2140 add_pid_to_pmt(ts, h->id, pcr_pid);
2141 update_av_program_info(ts->stream, h->id, pcr_pid, h->version);
2143 av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
2145 program_info_length = get16(&p, p_end);
2146 if (program_info_length < 0)
2148 program_info_length &= 0xfff;
2149 while (program_info_length >= 2) {
2151 tag = get8(&p, p_end);
2152 len = get8(&p, p_end);
2154 av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
2156 if (len > program_info_length - 2)
2157 // something else is broken, exit the program_descriptors_loop
2159 program_info_length -= len + 2;
2160 if (tag == 0x1d) { // IOD descriptor
2161 get8(&p, p_end); // scope
2162 get8(&p, p_end); // label
2164 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
2165 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
2166 } else if (tag == 0x05 && len >= 4) { // registration descriptor
2167 prog_reg_desc = bytestream_get_le32(&p);
2172 p += program_info_length;
2176 // stop parsing after pmt, we found header
2177 if (!ts->stream->nb_streams)
2180 set_pmt_found(ts, h->id);
2183 for (i = 0; ; i++) {
2186 stream_type = get8(&p, p_end);
2187 if (stream_type < 0)
2189 pid = get16(&p, p_end);
2193 if (pid == ts->current_pid)
2196 if (ts->merge_pmt_versions)
2197 stream_identifier = parse_stream_identifier_desc(p, p_end);
2199 /* now create stream */
2200 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
2201 pes = ts->pids[pid]->u.pes_filter.opaque;
2202 if (ts->merge_pmt_versions && !pes->st) {
2203 st = find_matching_stream(ts, pid, stream_identifier, i);
2206 pes->stream_type = stream_type;
2211 pes->st = avformat_new_stream(pes->stream, NULL);
2214 pes->st->id = pes->pid;
2215 pes->st->program_num = h->id;
2216 pes->st->pmt_version = h->version;
2217 pes->st->pmt_stream_idx = i;
2220 } else if (is_pes_stream(stream_type, prog_reg_desc)) {
2222 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
2223 pes = add_pes_stream(ts, pid, pcr_pid);
2224 if (ts->merge_pmt_versions && pes && !pes->st) {
2225 st = find_matching_stream(ts, pid, stream_identifier, i);
2228 pes->stream_type = stream_type;
2232 if (pes && !pes->st) {
2233 st = avformat_new_stream(pes->stream, NULL);
2237 st->program_num = h->id;
2238 st->pmt_version = h->version;
2239 st->pmt_stream_idx = i;
2242 int idx = ff_find_stream_index(ts->stream, pid);
2244 st = ts->stream->streams[idx];
2246 if (ts->merge_pmt_versions && !st) {
2247 st = find_matching_stream(ts, pid, stream_identifier, i);
2250 st = avformat_new_stream(ts->stream, NULL);
2254 st->program_num = h->id;
2255 st->pmt_version = h->version;
2256 st->pmt_stream_idx = i;
2257 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2258 if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
2259 mpegts_find_stream_type(st, stream_type, SCTE_types);
2260 mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
2268 if (pes && !pes->stream_type)
2269 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
2271 add_pid_to_pmt(ts, h->id, pid);
2273 av_program_add_stream_index(ts->stream, h->id, st->index);
2275 desc_list_len = get16(&p, p_end);
2276 if (desc_list_len < 0)
2278 desc_list_len &= 0xfff;
2279 desc_list_end = p + desc_list_len;
2280 if (desc_list_end > p_end)
2283 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
2284 desc_list_end, mp4_descr,
2285 mp4_descr_count, pid, ts) < 0)
2288 if (pes && prog_reg_desc == AV_RL32("HDMV") &&
2289 stream_type == 0x83 && pes->sub_st) {
2290 av_program_add_stream_index(ts->stream, h->id,
2291 pes->sub_st->index);
2292 pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
2298 if (!ts->pids[pcr_pid])
2299 mpegts_open_pcr_filter(ts, pcr_pid);
2302 for (i = 0; i < mp4_descr_count; i++)
2303 av_free(mp4_descr[i].dec_config_descr);
2306 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2308 MpegTSContext *ts = filter->u.section_filter.opaque;
2309 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2310 SectionHeader h1, *h = &h1;
2311 const uint8_t *p, *p_end;
2315 av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
2316 hex_dump_debug(ts->stream, section, section_len);
2318 p_end = section + section_len - 4;
2320 if (parse_section_header(h, &p, p_end) < 0)
2322 if (h->tid != PAT_TID)
2324 if (ts->skip_changes)
2327 if (skip_identical(h, tssf))
2329 ts->stream->ts_id = h->id;
2333 sid = get16(&p, p_end);
2336 pmt_pid = get16(&p, p_end);
2341 if (pmt_pid == ts->current_pid)
2344 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
2346 if (sid == 0x0000) {
2349 MpegTSFilter *fil = ts->pids[pmt_pid];
2350 program = av_new_program(ts->stream, sid);
2352 program->program_num = sid;
2353 program->pmt_pid = pmt_pid;
2356 if ( fil->type != MPEGTS_SECTION
2357 || fil->pid != pmt_pid
2358 || fil->u.section_filter.section_cb != pmt_cb)
2359 mpegts_close_filter(ts, ts->pids[pmt_pid]);
2361 if (!ts->pids[pmt_pid])
2362 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
2363 add_pat_entry(ts, sid);
2364 add_pid_to_pmt(ts, sid, 0); // add pat pid to program
2365 add_pid_to_pmt(ts, sid, pmt_pid);
2371 for (j=0; j<ts->stream->nb_programs; j++) {
2372 for (i = 0; i < ts->nb_prg; i++)
2373 if (ts->prg[i].id == ts->stream->programs[j]->id)
2375 if (i==ts->nb_prg && !ts->skip_clear)
2376 clear_avprogram(ts, ts->stream->programs[j]->id);
2381 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2383 MpegTSContext *ts = filter->u.section_filter.opaque;
2384 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2385 SectionHeader h1, *h = &h1;
2386 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
2387 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
2388 char *name, *provider_name;
2390 av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
2391 hex_dump_debug(ts->stream, section, section_len);
2393 p_end = section + section_len - 4;
2395 if (parse_section_header(h, &p, p_end) < 0)
2397 if (h->tid != SDT_TID)
2399 if (ts->skip_changes)
2401 if (skip_identical(h, tssf))
2404 onid = get16(&p, p_end);
2407 val = get8(&p, p_end);
2411 sid = get16(&p, p_end);
2414 val = get8(&p, p_end);
2417 desc_list_len = get16(&p, p_end);
2418 if (desc_list_len < 0)
2420 desc_list_len &= 0xfff;
2421 desc_list_end = p + desc_list_len;
2422 if (desc_list_end > p_end)
2425 desc_tag = get8(&p, desc_list_end);
2428 desc_len = get8(&p, desc_list_end);
2429 desc_end = p + desc_len;
2430 if (desc_len < 0 || desc_end > desc_list_end)
2433 av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
2434 desc_tag, desc_len);
2438 service_type = get8(&p, p_end);
2439 if (service_type < 0)
2441 provider_name = getstr8(&p, p_end);
2444 name = getstr8(&p, p_end);
2446 AVProgram *program = av_new_program(ts->stream, sid);
2448 av_dict_set(&program->metadata, "service_name", name, 0);
2449 av_dict_set(&program->metadata, "service_provider",
2454 av_free(provider_name);
2465 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2466 const uint8_t *packet);
2468 /* handle one TS packet */
2469 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
2472 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
2473 has_adaptation, has_payload;
2474 const uint8_t *p, *p_end;
2477 pid = AV_RB16(packet + 1) & 0x1fff;
2478 is_start = packet[1] & 0x40;
2479 tss = ts->pids[pid];
2480 if (ts->auto_guess && !tss && is_start) {
2481 add_pes_stream(ts, pid, -1);
2482 tss = ts->pids[pid];
2487 tss->discard = discard_pid(ts, pid);
2490 ts->current_pid = pid;
2492 afc = (packet[3] >> 4) & 3;
2493 if (afc == 0) /* reserved value */
2495 has_adaptation = afc & 2;
2496 has_payload = afc & 1;
2497 is_discontinuity = has_adaptation &&
2498 packet[4] != 0 && /* with length > 0 */
2499 (packet[5] & 0x80); /* and discontinuity indicated */
2501 /* continuity check (currently not used) */
2502 cc = (packet[3] & 0xf);
2503 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
2504 cc_ok = pid == 0x1FFF || // null packet PID
2511 av_log(ts->stream, AV_LOG_DEBUG,
2512 "Continuity check failed for pid %d expected %d got %d\n",
2513 pid, expected_cc, cc);
2514 if (tss->type == MPEGTS_PES) {
2515 PESContext *pc = tss->u.pes_filter.opaque;
2516 pc->flags |= AV_PKT_FLAG_CORRUPT;
2520 if (packet[1] & 0x80) {
2521 av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
2522 if (tss->type == MPEGTS_PES) {
2523 PESContext *pc = tss->u.pes_filter.opaque;
2524 pc->flags |= AV_PKT_FLAG_CORRUPT;
2529 if (has_adaptation) {
2532 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
2533 tss->last_pcr = pcr_h * 300 + pcr_l;
2534 /* skip adaptation field */
2537 /* if past the end of packet, ignore */
2538 p_end = packet + TS_PACKET_SIZE;
2539 if (p >= p_end || !has_payload)
2542 pos = avio_tell(ts->stream->pb);
2544 av_assert0(pos >= TS_PACKET_SIZE);
2545 ts->pos47_full = pos - TS_PACKET_SIZE;
2548 if (tss->type == MPEGTS_SECTION) {
2550 /* pointer field present */
2552 if (len > p_end - p)
2555 /* write remaining section bytes */
2556 write_section_data(ts, tss,
2558 /* check whether filter has been closed */
2564 write_section_data(ts, tss,
2569 write_section_data(ts, tss,
2574 // stop find_stream_info from waiting for more streams
2575 // when all programs have received a PMT
2576 if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
2578 for (i = 0; i < ts->nb_prg; i++) {
2579 if (!ts->prg[i].pmt_found)
2582 if (i == ts->nb_prg && ts->nb_prg > 0) {
2584 for (i = 0; i < ts->stream->nb_streams; i++) {
2585 AVStream *st = ts->stream->streams[i];
2586 if (st->codecpar->codec_type >= 0)
2587 types |= 1<<st->codecpar->codec_type;
2589 if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
2590 av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
2591 ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
2598 // Note: The position here points actually behind the current packet.
2599 if (tss->type == MPEGTS_PES) {
2600 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
2601 pos - ts->raw_packet_size)) < 0)
2609 static void reanalyze(MpegTSContext *ts) {
2610 AVIOContext *pb = ts->stream->pb;
2611 int64_t pos = avio_tell(pb);
2614 pos -= ts->pos47_full;
2615 if (pos == TS_PACKET_SIZE) {
2616 ts->size_stat[0] ++;
2617 } else if (pos == TS_DVHS_PACKET_SIZE) {
2618 ts->size_stat[1] ++;
2619 } else if (pos == TS_FEC_PACKET_SIZE) {
2620 ts->size_stat[2] ++;
2623 ts->size_stat_count ++;
2624 if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
2626 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
2627 newsize = TS_PACKET_SIZE;
2628 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
2629 newsize = TS_DVHS_PACKET_SIZE;
2630 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
2631 newsize = TS_FEC_PACKET_SIZE;
2633 if (newsize && newsize != ts->raw_packet_size) {
2634 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
2635 ts->raw_packet_size = newsize;
2637 ts->size_stat_count = 0;
2638 memset(ts->size_stat, 0, sizeof(ts->size_stat));
2642 /* XXX: try to find a better synchro over several packets (use
2643 * get_packet_size() ?) */
2644 static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
2646 MpegTSContext *ts = s->priv_data;
2647 AVIOContext *pb = s->pb;
2649 uint64_t pos = avio_tell(pb);
2651 avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
2653 //Special case for files like 01c56b0dc1.ts
2654 if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
2655 avio_seek(pb, 12, SEEK_CUR);
2659 for (i = 0; i < ts->resync_size; i++) {
2664 avio_seek(pb, -1, SEEK_CUR);
2665 reanalyze(s->priv_data);
2669 av_log(s, AV_LOG_ERROR,
2670 "max resync size reached, could not find sync byte\n");
2672 return AVERROR_INVALIDDATA;
2675 /* return AVERROR_something if error or EOF. Return 0 if OK. */
2676 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
2677 const uint8_t **data)
2679 AVIOContext *pb = s->pb;
2683 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2684 if (len != TS_PACKET_SIZE)
2685 return len < 0 ? len : AVERROR_EOF;
2686 /* check packet sync byte */
2687 if ((*data)[0] != 0x47) {
2688 /* find a new packet start */
2690 if (mpegts_resync(s, raw_packet_size, *data) < 0)
2691 return AVERROR(EAGAIN);
2701 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2703 AVIOContext *pb = s->pb;
2704 int skip = raw_packet_size - TS_PACKET_SIZE;
2706 avio_skip(pb, skip);
2709 static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
2711 AVFormatContext *s = ts->stream;
2712 uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
2713 const uint8_t *data;
2717 if (avio_tell(s->pb) != ts->last_pos) {
2719 av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
2720 /* seek detected, flush pes buffer */
2721 for (i = 0; i < NB_PID_MAX; i++) {
2723 if (ts->pids[i]->type == MPEGTS_PES) {
2724 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2725 av_buffer_unref(&pes->buffer);
2726 pes->data_index = 0;
2727 pes->state = MPEGTS_SKIP; /* skip until pes header */
2728 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
2729 ts->pids[i]->u.section_filter.last_ver = -1;
2731 ts->pids[i]->last_cc = -1;
2732 ts->pids[i]->last_pcr = -1;
2739 memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2742 if (nb_packets != 0 && packet_num >= nb_packets ||
2743 ts->stop_parse > 1) {
2744 ret = AVERROR(EAGAIN);
2747 if (ts->stop_parse > 0)
2750 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2753 ret = handle_packet(ts, data);
2754 finished_reading_packet(s, ts->raw_packet_size);
2758 ts->last_pos = avio_tell(s->pb);
2762 static int mpegts_probe(AVProbeData *p)
2764 const int size = p->buf_size;
2768 int check_count = size / TS_FEC_PACKET_SIZE;
2769 #define CHECK_COUNT 10
2770 #define CHECK_BLOCK 100
2775 for (i = 0; i<check_count; i+=CHECK_BLOCK) {
2776 int left = FFMIN(check_count - i, CHECK_BLOCK);
2777 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
2778 int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
2779 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
2780 score = FFMAX3(score, dvhs_score, fec_score);
2782 maxscore = FFMAX(maxscore, score);
2785 sumscore = sumscore * CHECK_COUNT / check_count;
2786 maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
2788 ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2790 if (check_count > CHECK_COUNT && sumscore > 6) {
2791 return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2792 } else if (check_count >= CHECK_COUNT && sumscore > 6) {
2793 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2794 } else if (check_count >= CHECK_COUNT && maxscore > 6) {
2795 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2796 } else if (sumscore > 6) {
2803 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2804 * (-1) if not available */
2805 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
2807 int afc, len, flags;
2811 afc = (packet[3] >> 4) & 3;
2813 return AVERROR_INVALIDDATA;
2818 return AVERROR_INVALIDDATA;
2821 if (!(flags & 0x10))
2822 return AVERROR_INVALIDDATA;
2824 return AVERROR_INVALIDDATA;
2826 *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
2827 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2831 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2833 /* NOTE: We attempt to seek on non-seekable files as well, as the
2834 * probe buffer usually is big enough. Only warn if the seek failed
2835 * on files where the seek should work. */
2836 if (avio_seek(pb, pos, SEEK_SET) < 0)
2837 av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2840 static int mpegts_read_header(AVFormatContext *s)
2842 MpegTSContext *ts = s->priv_data;
2843 AVIOContext *pb = s->pb;
2844 uint8_t buf[8 * 1024] = {0};
2846 int64_t pos, probesize = s->probesize;
2848 s->internal->prefer_codec_framerate = 1;
2850 if (ffio_ensure_seekback(pb, probesize) < 0)
2851 av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
2853 /* read the first 8192 bytes to get packet size */
2854 pos = avio_tell(pb);
2855 len = avio_read(pb, buf, sizeof(buf));
2856 ts->raw_packet_size = get_packet_size(buf, len);
2857 if (ts->raw_packet_size <= 0) {
2858 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2859 ts->raw_packet_size = TS_PACKET_SIZE;
2864 if (s->iformat == &ff_mpegts_demuxer) {
2867 /* first do a scan to get all the services */
2868 seek_back(s, pb, pos);
2870 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2872 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2874 handle_packets(ts, probesize / ts->raw_packet_size);
2875 /* if could not find service, enable auto_guess */
2879 av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
2881 s->ctx_flags |= AVFMTCTX_NOHEADER;
2884 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2885 int64_t pcrs[2], pcr_h;
2886 int packet_count[2];
2887 uint8_t packet[TS_PACKET_SIZE];
2888 const uint8_t *data;
2890 /* only read packets */
2892 st = avformat_new_stream(s, NULL);
2894 return AVERROR(ENOMEM);
2895 avpriv_set_pts_info(st, 60, 1, 27000000);
2896 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2897 st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
2899 /* we iterate until we find two PCRs to estimate the bitrate */
2904 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2907 pid = AV_RB16(data + 1) & 0x1fff;
2908 if ((pcr_pid == -1 || pcr_pid == pid) &&
2909 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2910 finished_reading_packet(s, ts->raw_packet_size);
2912 packet_count[nb_pcrs] = nb_packets;
2913 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2916 if (pcrs[1] - pcrs[0] > 0) {
2917 /* the difference needs to be positive to make sense for bitrate computation */
2920 av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
2922 packet_count[0] = packet_count[1];
2927 finished_reading_packet(s, ts->raw_packet_size);
2932 /* NOTE1: the bitrate is computed without the FEC */
2933 /* NOTE2: it is only the bitrate of the start of the stream */
2934 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2935 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2936 s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
2937 st->codecpar->bit_rate = s->bit_rate;
2938 st->start_time = ts->cur_pcr;
2939 av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
2940 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2943 seek_back(s, pb, pos);
2947 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2949 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
2951 MpegTSContext *ts = s->priv_data;
2953 int64_t pcr_h, next_pcr_h, pos;
2954 int pcr_l, next_pcr_l;
2955 uint8_t pcr_buf[12];
2956 const uint8_t *data;
2958 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2959 return AVERROR(ENOMEM);
2960 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2961 pkt->pos = avio_tell(s->pb);
2963 av_packet_unref(pkt);
2966 if (data != pkt->data)
2967 memcpy(pkt->data, data, ts->raw_packet_size);
2968 finished_reading_packet(s, ts->raw_packet_size);
2969 if (ts->mpeg2ts_compute_pcr) {
2970 /* compute exact PCR for each packet */
2971 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2972 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2973 pos = avio_tell(s->pb);
2974 for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
2975 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2976 avio_read(s->pb, pcr_buf, 12);
2977 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2978 /* XXX: not precise enough */
2980 ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2985 avio_seek(s->pb, pos, SEEK_SET);
2986 /* no next PCR found: we use previous increment */
2987 ts->cur_pcr = pcr_h * 300 + pcr_l;
2989 pkt->pts = ts->cur_pcr;
2990 pkt->duration = ts->pcr_incr;
2991 ts->cur_pcr += ts->pcr_incr;
2993 pkt->stream_index = 0;
2997 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
2999 MpegTSContext *ts = s->priv_data;
3004 ret = handle_packets(ts, 0);
3006 av_packet_unref(ts->pkt);
3007 /* flush pes data left */
3008 for (i = 0; i < NB_PID_MAX; i++)
3009 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
3010 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
3011 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
3012 ret = new_pes_packet(pes, pkt);
3015 pes->state = MPEGTS_SKIP;
3022 if (!ret && pkt->size < 0)
3023 ret = AVERROR_INVALIDDATA;
3027 static void mpegts_free(MpegTSContext *ts)
3033 for (i = 0; i < NB_PID_MAX; i++)
3035 mpegts_close_filter(ts, ts->pids[i]);
3038 static int mpegts_read_close(AVFormatContext *s)
3040 MpegTSContext *ts = s->priv_data;
3045 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
3046 int64_t *ppos, int64_t pos_limit)
3048 MpegTSContext *ts = s->priv_data;
3049 int64_t pos, timestamp;
3050 uint8_t buf[TS_PACKET_SIZE];
3051 int pcr_l, pcr_pid =
3052 ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
3053 int pos47 = ts->pos47_full % ts->raw_packet_size;
3055 ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
3056 ts->raw_packet_size + pos47;
3057 while(pos < pos_limit) {
3058 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3059 return AV_NOPTS_VALUE;
3060 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
3061 return AV_NOPTS_VALUE;
3062 if (buf[0] != 0x47) {
3063 if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
3064 return AV_NOPTS_VALUE;
3065 pos = avio_tell(s->pb);
3068 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
3069 parse_pcr(×tamp, &pcr_l, buf) == 0) {
3073 pos += ts->raw_packet_size;
3076 return AV_NOPTS_VALUE;
3079 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
3080 int64_t *ppos, int64_t pos_limit)
3082 MpegTSContext *ts = s->priv_data;
3084 int pos47 = ts->pos47_full % ts->raw_packet_size;
3085 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
3086 ff_read_frame_flush(s);
3087 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3088 return AV_NOPTS_VALUE;
3089 while(pos < pos_limit) {
3092 av_init_packet(&pkt);
3093 ret = av_read_frame(s, &pkt);
3095 return AV_NOPTS_VALUE;
3096 if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
3097 ff_reduce_index(s, pkt.stream_index);
3098 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
3099 if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
3100 int64_t dts = pkt.dts;
3102 av_packet_unref(&pkt);
3107 av_packet_unref(&pkt);
3110 return AV_NOPTS_VALUE;
3113 /**************************************************************/
3114 /* parsing functions - called from other demuxers such as RTP */
3116 MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
3120 ts = av_mallocz(sizeof(MpegTSContext));
3123 /* no stream case, currently used by RTP */
3124 ts->raw_packet_size = TS_PACKET_SIZE;
3127 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
3128 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
3133 /* return the consumed length if a packet was output, or -1 if no
3134 * packet is output */
3135 int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
3136 const uint8_t *buf, int len)
3144 if (len < TS_PACKET_SIZE)
3145 return AVERROR_INVALIDDATA;
3146 if (buf[0] != 0x47) {
3150 handle_packet(ts, buf);
3151 buf += TS_PACKET_SIZE;
3152 len -= TS_PACKET_SIZE;
3153 if (ts->stop_parse == 1)
3160 void avpriv_mpegts_parse_close(MpegTSContext *ts)
3166 AVInputFormat ff_mpegts_demuxer = {
3168 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
3169 .priv_data_size = sizeof(MpegTSContext),
3170 .read_probe = mpegts_probe,
3171 .read_header = mpegts_read_header,
3172 .read_packet = mpegts_read_packet,
3173 .read_close = mpegts_read_close,
3174 .read_timestamp = mpegts_get_dts,
3175 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3176 .priv_class = &mpegts_class,
3179 AVInputFormat ff_mpegtsraw_demuxer = {
3180 .name = "mpegtsraw",
3181 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
3182 .priv_data_size = sizeof(MpegTSContext),
3183 .read_header = mpegts_read_header,
3184 .read_packet = mpegts_raw_read_packet,
3185 .read_close = mpegts_read_close,
3186 .read_timestamp = mpegts_get_dts,
3187 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3188 .priv_class = &mpegtsraw_class,