2 * MPEG2 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 synchronisation if
42 * synchronisation 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) */
94 enum MpegTSFilterType type;
96 MpegTSPESFilter pes_filter;
97 MpegTSSectionFilter section_filter;
101 #define MAX_PIDS_PER_PROGRAM 64
103 unsigned int id; // program id/service id
104 unsigned int nb_pids;
105 unsigned int pids[MAX_PIDS_PER_PROGRAM];
107 /** have we found pmt for this program */
111 struct MpegTSContext {
112 const AVClass *class;
114 AVFormatContext *stream;
115 /** raw packet size, including FEC if present */
120 #define SIZE_STAT_THRESHOLD 10
124 /** if true, all pids are analyzed to find streams */
127 /** compute exact PCR for each transport stream packet */
128 int mpeg2ts_compute_pcr;
130 /** fix dvb teletext pts */
131 int fix_teletext_pts;
133 int64_t cur_pcr; /**< used to estimate the exact PCR */
134 int pcr_incr; /**< used to estimate the exact PCR */
136 /* data needed to handle file based ts */
137 /** stop parsing loop */
139 /** packet containing Audio/Video data */
141 /** to detect seek */
151 /******************************************/
152 /* private mpegts data */
154 /** structure to keep track of Program->pids mapping */
158 int8_t crc_validity[NB_PID_MAX];
159 /** filters for various streams specified by PMT + for the PAT and PMT */
160 MpegTSFilter *pids[NB_PID_MAX];
164 #define MPEGTS_OPTIONS \
165 { "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 }
167 static const AVOption options[] = {
169 {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
170 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
171 {"ts_packetsize", "output option carrying the raw packet size", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
172 {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
173 {"scan_all_pmts", "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
174 { .i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM },
175 {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
176 {.i64 = 0}, 0, 1, 0 },
177 {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
178 {.i64 = 0}, 0, 1, 0 },
182 static const AVClass mpegts_class = {
183 .class_name = "mpegts demuxer",
184 .item_name = av_default_item_name,
186 .version = LIBAVUTIL_VERSION_INT,
189 static const AVOption raw_options[] = {
191 { "compute_pcr", "compute exact PCR for each transport stream packet",
192 offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
193 { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
194 { "ts_packetsize", "output option carrying the raw packet size",
195 offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
197 AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
201 static const AVClass mpegtsraw_class = {
202 .class_name = "mpegtsraw demuxer",
203 .item_name = av_default_item_name,
204 .option = raw_options,
205 .version = LIBAVUTIL_VERSION_INT,
208 /* TS stream handling */
213 MPEGTS_PESHEADER_FILL,
218 /* enough for PES header + length */
219 #define PES_START_SIZE 6
220 #define PES_HEADER_SIZE 9
221 #define MAX_PES_HEADER_SIZE (9 + 255)
223 typedef struct PESContext {
225 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
228 AVFormatContext *stream;
230 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
231 enum MpegTSState state;
232 /* used to get the format */
234 int flags; /**< copied to the AVPacket flags */
237 int extended_stream_id;
240 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
241 uint8_t header[MAX_PES_HEADER_SIZE];
246 extern AVInputFormat ff_mpegts_demuxer;
248 static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
251 for (i = 0; i < ts->nb_prg; i++) {
252 if (ts->prg[i].id == programid) {
259 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
261 AVProgram *prg = NULL;
264 for (i = 0; i < ts->stream->nb_programs; i++)
265 if (ts->stream->programs[i]->id == programid) {
266 prg = ts->stream->programs[i];
271 prg->nb_stream_indexes = 0;
274 static void clear_program(MpegTSContext *ts, unsigned int programid)
278 clear_avprogram(ts, programid);
279 for (i = 0; i < ts->nb_prg; i++)
280 if (ts->prg[i].id == programid) {
281 ts->prg[i].nb_pids = 0;
282 ts->prg[i].pmt_found = 0;
286 static void clear_programs(MpegTSContext *ts)
292 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
295 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
299 p = &ts->prg[ts->nb_prg];
306 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
309 struct Program *p = get_program(ts, programid);
314 if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
317 for (i = 0; i < p->nb_pids; i++)
318 if (p->pids[i] == pid)
321 p->pids[p->nb_pids++] = pid;
324 static void set_pmt_found(MpegTSContext *ts, unsigned int programid)
326 struct Program *p = get_program(ts, programid);
333 static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
336 for (i = 0; i < s->nb_programs; i++) {
337 if (s->programs[i]->id == programid) {
338 s->programs[i]->pcr_pid = pid;
345 * @brief discard_pid() decides if the pid is to be discarded according
346 * to caller's programs selection
347 * @param ts : - TS context
349 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
352 static int discard_pid(MpegTSContext *ts, unsigned int pid)
355 int used = 0, discarded = 0;
358 /* If none of the programs have .discard=AVDISCARD_ALL then there's
359 * no way we have to discard this packet */
360 for (k = 0; k < ts->stream->nb_programs; k++)
361 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
363 if (k == ts->stream->nb_programs)
366 for (i = 0; i < ts->nb_prg; i++) {
368 for (j = 0; j < p->nb_pids; j++) {
369 if (p->pids[j] != pid)
371 // is program with id p->id set to be discarded?
372 for (k = 0; k < ts->stream->nb_programs; k++) {
373 if (ts->stream->programs[k]->id == p->id) {
374 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
383 return !used && discarded;
387 * Assemble PES packets out of TS packets, and then call the "section_cb"
388 * function when they are complete.
390 static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
391 const uint8_t *buf, int buf_size, int is_start)
393 MpegTSSectionFilter *tss = &tss1->u.section_filter;
397 memcpy(tss->section_buf, buf, buf_size);
398 tss->section_index = buf_size;
399 tss->section_h_size = -1;
400 tss->end_of_section_reached = 0;
402 if (tss->end_of_section_reached)
404 len = 4096 - tss->section_index;
407 memcpy(tss->section_buf + tss->section_index, buf, len);
408 tss->section_index += len;
411 /* compute section length if possible */
412 if (tss->section_h_size == -1 && tss->section_index >= 3) {
413 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
416 tss->section_h_size = len;
419 if (tss->section_h_size != -1 &&
420 tss->section_index >= tss->section_h_size) {
422 tss->end_of_section_reached = 1;
424 if (tss->check_crc) {
425 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
426 if (tss->section_h_size >= 4)
427 tss->crc = AV_RB32(tss->section_buf + tss->section_h_size - 4);
430 ts->crc_validity[ tss1->pid ] = 100;
431 }else if (ts->crc_validity[ tss1->pid ] > -10) {
432 ts->crc_validity[ tss1->pid ]--;
437 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
444 static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
445 enum MpegTSFilterType type)
447 MpegTSFilter *filter;
449 av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x\n", pid);
451 if (pid >= NB_PID_MAX || ts->pids[pid])
453 filter = av_mallocz(sizeof(MpegTSFilter));
456 ts->pids[pid] = filter;
461 filter->last_cc = -1;
462 filter->last_pcr= -1;
467 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
469 SectionCallback *section_cb,
473 MpegTSFilter *filter;
474 MpegTSSectionFilter *sec;
476 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION)))
478 sec = &filter->u.section_filter;
479 sec->section_cb = section_cb;
480 sec->opaque = opaque;
481 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
482 sec->check_crc = check_crc;
485 if (!sec->section_buf) {
492 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
496 MpegTSFilter *filter;
497 MpegTSPESFilter *pes;
499 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
502 pes = &filter->u.pes_filter;
503 pes->pes_cb = pes_cb;
504 pes->opaque = opaque;
508 static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
510 return mpegts_open_filter(ts, pid, MPEGTS_PCR);
513 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
518 if (filter->type == MPEGTS_SECTION)
519 av_freep(&filter->u.section_filter.section_buf);
520 else if (filter->type == MPEGTS_PES) {
521 PESContext *pes = filter->u.pes_filter.opaque;
522 av_buffer_unref(&pes->buffer);
523 /* referenced private data will be freed later in
524 * avformat_close_input */
525 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
526 av_freep(&filter->u.pes_filter.opaque);
531 ts->pids[pid] = NULL;
534 static int analyze(const uint8_t *buf, int size, int packet_size,
537 int stat[TS_MAX_PACKET_SIZE];
542 memset(stat, 0, packet_size * sizeof(*stat));
544 for (i = 0; i < size - 3; i++) {
545 if (buf[i] == 0x47 &&
546 (!probe || (buf[i + 3] & 0x30))) {
547 int x = i % packet_size;
550 if (stat[x] > best_score) {
551 best_score = stat[x];
556 return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
559 /* autodetect fec presence. Must have at least 1024 bytes */
560 static int get_packet_size(const uint8_t *buf, int size)
562 int score, fec_score, dvhs_score;
564 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
565 return AVERROR_INVALIDDATA;
567 score = analyze(buf, size, TS_PACKET_SIZE, 0);
568 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, 0);
569 fec_score = analyze(buf, size, TS_FEC_PACKET_SIZE, 0);
570 av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
571 score, dvhs_score, fec_score);
573 if (score > fec_score && score > dvhs_score)
574 return TS_PACKET_SIZE;
575 else if (dvhs_score > score && dvhs_score > fec_score)
576 return TS_DVHS_PACKET_SIZE;
577 else if (score < fec_score && dvhs_score < fec_score)
578 return TS_FEC_PACKET_SIZE;
580 return AVERROR_INVALIDDATA;
583 typedef struct SectionHeader {
588 uint8_t last_sec_num;
591 static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
593 if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
596 tssf->last_ver = h->version;
597 tssf->last_crc = tssf->crc;
602 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
609 return AVERROR_INVALIDDATA;
615 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
622 return AVERROR_INVALIDDATA;
629 /* read and allocate a DVB string preceded by its length */
630 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
637 len = get8(&p, p_end);
642 str = av_malloc(len + 1);
652 static int parse_section_header(SectionHeader *h,
653 const uint8_t **pp, const uint8_t *p_end)
657 val = get8(pp, p_end);
662 val = get16(pp, p_end);
666 val = get8(pp, p_end);
669 h->version = (val >> 1) & 0x1f;
670 val = get8(pp, p_end);
674 val = get8(pp, p_end);
677 h->last_sec_num = val;
681 typedef struct StreamType {
682 uint32_t stream_type;
683 enum AVMediaType codec_type;
684 enum AVCodecID codec_id;
687 static const StreamType ISO_types[] = {
688 { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
689 { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
690 { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
691 { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
692 { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
693 { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
694 /* Makito encoder sets stream type 0x11 for AAC,
695 * so auto-detect LOAS/LATM instead of hardcoding it. */
696 #if !CONFIG_LOAS_DEMUXER
697 { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
699 { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
700 { 0x20, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
701 { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000 },
702 { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
703 { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
704 { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
705 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
709 static const StreamType HDMV_types[] = {
710 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
711 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
712 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
713 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
714 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
715 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
716 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
717 { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
718 { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
719 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
720 { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
725 static const StreamType MISC_types[] = {
726 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
727 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
731 static const StreamType REGD_types[] = {
732 { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
733 { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
734 { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
735 { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
736 { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
737 { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
738 { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
739 { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
740 { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
741 { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
742 { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS },
746 static const StreamType METADATA_types[] = {
747 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
748 { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
752 /* descriptor present */
753 static const StreamType DESC_types[] = {
754 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
755 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
756 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
757 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
758 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
762 static void mpegts_find_stream_type(AVStream *st,
763 uint32_t stream_type,
764 const StreamType *types)
766 for (; types->stream_type; types++)
767 if (stream_type == types->stream_type) {
768 if (st->codecpar->codec_type != types->codec_type ||
769 st->codecpar->codec_id != types->codec_id) {
770 st->codecpar->codec_type = types->codec_type;
771 st->codecpar->codec_id = types->codec_id;
772 st->internal->need_context_update = 1;
774 st->request_probe = 0;
779 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
780 uint32_t stream_type, uint32_t prog_reg_desc)
782 int old_codec_type = st->codecpar->codec_type;
783 int old_codec_id = st->codecpar->codec_id;
784 int old_codec_tag = st->codecpar->codec_tag;
786 if (avcodec_is_open(st->internal->avctx)) {
787 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, internal codec is open\n");
791 avpriv_set_pts_info(st, 33, 1, 90000);
793 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
794 st->codecpar->codec_id = AV_CODEC_ID_NONE;
795 st->need_parsing = AVSTREAM_PARSE_FULL;
797 pes->stream_type = stream_type;
799 av_log(pes->stream, AV_LOG_DEBUG,
800 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
801 st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
803 st->codecpar->codec_tag = pes->stream_type;
805 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
806 if (pes->stream_type == 4)
807 st->request_probe = 50;
808 if ((prog_reg_desc == AV_RL32("HDMV") ||
809 prog_reg_desc == AV_RL32("HDPR")) &&
810 st->codecpar->codec_id == AV_CODEC_ID_NONE) {
811 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
812 if (pes->stream_type == 0x83) {
813 // HDMV TrueHD streams also contain an AC3 coded version of the
814 // audio track - add a second stream for this
816 // priv_data cannot be shared between streams
817 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
819 return AVERROR(ENOMEM);
820 memcpy(sub_pes, pes, sizeof(*sub_pes));
822 sub_st = avformat_new_stream(pes->stream, NULL);
825 return AVERROR(ENOMEM);
828 sub_st->id = pes->pid;
829 avpriv_set_pts_info(sub_st, 33, 1, 90000);
830 sub_st->priv_data = sub_pes;
831 sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
832 sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
833 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
834 sub_pes->sub_st = pes->sub_st = sub_st;
837 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
838 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
839 if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
840 st->codecpar->codec_id = old_codec_id;
841 st->codecpar->codec_type = old_codec_type;
843 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
844 (st->request_probe > 0 && st->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
845 st->probe_packets > 0 &&
846 stream_type == STREAM_TYPE_PRIVATE_DATA) {
847 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
848 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
849 st->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
852 /* queue a context update if properties changed */
853 if (old_codec_type != st->codecpar->codec_type ||
854 old_codec_id != st->codecpar->codec_id ||
855 old_codec_tag != st->codecpar->codec_tag)
856 st->internal->need_context_update = 1;
861 static void reset_pes_packet_state(PESContext *pes)
863 pes->pts = AV_NOPTS_VALUE;
864 pes->dts = AV_NOPTS_VALUE;
867 av_buffer_unref(&pes->buffer);
870 static int new_pes_packet(PESContext *pes, AVPacket *pkt)
876 pkt->buf = pes->buffer;
877 pkt->data = pes->buffer->data;
878 pkt->size = pes->data_index;
880 if (pes->total_size != MAX_PES_PAYLOAD &&
881 pes->pes_header_size + pes->data_index != pes->total_size +
883 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
884 pes->flags |= AV_PKT_FLAG_CORRUPT;
886 memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
888 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
889 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
890 pkt->stream_index = pes->sub_st->index;
892 pkt->stream_index = pes->st->index;
895 /* store position of first TS packet of this PES packet */
896 pkt->pos = pes->ts_packet_pos;
897 pkt->flags = pes->flags;
900 reset_pes_packet_state(pes);
902 sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
904 return AVERROR(ENOMEM);
905 *sd = pes->stream_id;
910 static uint64_t get_ts64(GetBitContext *gb, int bits)
912 if (get_bits_left(gb) < bits)
913 return AV_NOPTS_VALUE;
914 return get_bits64(gb, bits);
917 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
918 const uint8_t *buf, int buf_size)
921 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
922 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
923 int dts_flag = -1, cts_flag = -1;
924 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
925 uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
926 int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
928 memcpy(buf_padded, buf, buf_padded_size);
930 init_get_bits(&gb, buf_padded, buf_padded_size * 8);
932 if (sl->use_au_start)
933 au_start_flag = get_bits1(&gb);
935 au_end_flag = get_bits1(&gb);
936 if (!sl->use_au_start && !sl->use_au_end)
937 au_start_flag = au_end_flag = 1;
939 ocr_flag = get_bits1(&gb);
941 idle_flag = get_bits1(&gb);
943 padding_flag = get_bits1(&gb);
945 padding_bits = get_bits(&gb, 3);
947 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
948 if (sl->packet_seq_num_len)
949 skip_bits_long(&gb, sl->packet_seq_num_len);
950 if (sl->degr_prior_len)
952 skip_bits(&gb, sl->degr_prior_len);
954 skip_bits_long(&gb, sl->ocr_len);
956 if (sl->use_rand_acc_pt)
958 if (sl->au_seq_num_len > 0)
959 skip_bits_long(&gb, sl->au_seq_num_len);
960 if (sl->use_timestamps) {
961 dts_flag = get_bits1(&gb);
962 cts_flag = get_bits1(&gb);
965 if (sl->inst_bitrate_len)
966 inst_bitrate_flag = get_bits1(&gb);
968 dts = get_ts64(&gb, sl->timestamp_len);
970 cts = get_ts64(&gb, sl->timestamp_len);
972 skip_bits_long(&gb, sl->au_len);
973 if (inst_bitrate_flag)
974 skip_bits_long(&gb, sl->inst_bitrate_len);
977 if (dts != AV_NOPTS_VALUE)
979 if (cts != AV_NOPTS_VALUE)
982 if (sl->timestamp_len && sl->timestamp_res)
983 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
985 return (get_bits_count(&gb) + 7) >> 3;
988 /* return non zero if a packet could be constructed */
989 static int mpegts_push_data(MpegTSFilter *filter,
990 const uint8_t *buf, int buf_size, int is_start,
993 PESContext *pes = filter->u.pes_filter.opaque;
994 MpegTSContext *ts = pes->ts;
1002 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1003 ret = new_pes_packet(pes, ts->pkt);
1008 reset_pes_packet_state(pes);
1010 pes->state = MPEGTS_HEADER;
1011 pes->ts_packet_pos = pos;
1014 while (buf_size > 0) {
1015 switch (pes->state) {
1017 len = PES_START_SIZE - pes->data_index;
1020 memcpy(pes->header + pes->data_index, p, len);
1021 pes->data_index += len;
1024 if (pes->data_index == PES_START_SIZE) {
1025 /* we got all the PES or section header. We can now
1027 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
1028 pes->header[2] == 0x01) {
1029 /* it must be an mpeg2 PES stream */
1030 code = pes->header[3] | 0x100;
1031 av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
1033 pes->stream_id = pes->header[3];
1035 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
1037 pes->sub_st->discard == AVDISCARD_ALL)) ||
1038 code == 0x1be) /* padding_stream */
1041 /* stream not present in PMT */
1043 if (ts->skip_changes)
1046 pes->st = avformat_new_stream(ts->stream, NULL);
1048 return AVERROR(ENOMEM);
1049 pes->st->id = pes->pid;
1050 mpegts_set_stream_info(pes->st, pes, 0, 0);
1053 pes->total_size = AV_RB16(pes->header + 4);
1054 /* NOTE: a zero total size means the PES size is
1056 if (!pes->total_size)
1057 pes->total_size = MAX_PES_PAYLOAD;
1059 /* allocate pes buffer */
1060 pes->buffer = av_buffer_alloc(pes->total_size +
1061 AV_INPUT_BUFFER_PADDING_SIZE);
1063 return AVERROR(ENOMEM);
1065 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
1066 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
1067 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
1068 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
1069 pes->state = MPEGTS_PESHEADER;
1070 if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
1071 av_log(pes->stream, AV_LOG_TRACE,
1072 "pid=%x stream_type=%x probing\n",
1075 pes->st->request_probe = 1;
1078 pes->pes_header_size = 6;
1079 pes->state = MPEGTS_PAYLOAD;
1080 pes->data_index = 0;
1083 /* otherwise, it should be a table */
1086 pes->state = MPEGTS_SKIP;
1091 /**********************************************/
1092 /* PES packing parsing */
1093 case MPEGTS_PESHEADER:
1094 len = PES_HEADER_SIZE - pes->data_index;
1096 return AVERROR_INVALIDDATA;
1099 memcpy(pes->header + pes->data_index, p, len);
1100 pes->data_index += len;
1103 if (pes->data_index == PES_HEADER_SIZE) {
1104 pes->pes_header_size = pes->header[8] + 9;
1105 pes->state = MPEGTS_PESHEADER_FILL;
1108 case MPEGTS_PESHEADER_FILL:
1109 len = pes->pes_header_size - pes->data_index;
1111 return AVERROR_INVALIDDATA;
1114 memcpy(pes->header + pes->data_index, p, len);
1115 pes->data_index += len;
1118 if (pes->data_index == pes->pes_header_size) {
1120 unsigned int flags, pes_ext, skip;
1122 flags = pes->header[7];
1123 r = pes->header + 9;
1124 pes->pts = AV_NOPTS_VALUE;
1125 pes->dts = AV_NOPTS_VALUE;
1126 if ((flags & 0xc0) == 0x80) {
1127 pes->dts = pes->pts = ff_parse_pes_pts(r);
1129 } else if ((flags & 0xc0) == 0xc0) {
1130 pes->pts = ff_parse_pes_pts(r);
1132 pes->dts = ff_parse_pes_pts(r);
1135 pes->extended_stream_id = -1;
1136 if (flags & 0x01) { /* PES extension */
1138 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1139 skip = (pes_ext >> 4) & 0xb;
1142 if ((pes_ext & 0x41) == 0x01 &&
1143 (r + 2) <= (pes->header + pes->pes_header_size)) {
1144 /* PES extension 2 */
1145 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1146 pes->extended_stream_id = r[1];
1150 /* we got the full header. We parse it and get the payload */
1151 pes->state = MPEGTS_PAYLOAD;
1152 pes->data_index = 0;
1153 if (pes->stream_type == 0x12 && buf_size > 0) {
1154 int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
1156 pes->pes_header_size += sl_header_bytes;
1157 p += sl_header_bytes;
1158 buf_size -= sl_header_bytes;
1160 if (pes->stream_type == 0x15 && buf_size >= 5) {
1161 /* skip metadata access unit header */
1162 pes->pes_header_size += 5;
1166 if ( pes->ts->fix_teletext_pts
1167 && ( pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
1168 || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1170 AVProgram *p = NULL;
1171 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1172 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1173 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1175 AVStream *st = NULL;
1176 if (f->type == MPEGTS_PES) {
1177 PESContext *pcrpes = f->u.pes_filter.opaque;
1180 } else if (f->type == MPEGTS_PCR) {
1182 for (i = 0; i < p->nb_stream_indexes; i++) {
1183 AVStream *pst = pes->stream->streams[p->stream_index[i]];
1184 if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1188 if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
1189 // teletext packets do not always have correct timestamps,
1190 // the standard says they should be handled after 40.6 ms at most,
1191 // and the pcr error to this packet should be no more than 100 ms.
1192 // TODO: we should interpolate the PCR, not just use the last one
1193 int64_t pcr = f->last_pcr / 300;
1194 pes->st->pts_wrap_reference = st->pts_wrap_reference;
1195 pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
1196 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1197 pes->pts = pes->dts = pcr;
1198 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1199 pes->dts > pcr + 3654 + 9000) {
1200 pes->pts = pes->dts = pcr + 3654 + 9000;
1201 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1202 pes->dts > pcr + 10*90000) { //10sec
1203 pes->pts = pes->dts = pcr + 3654 + 9000;
1213 case MPEGTS_PAYLOAD:
1215 if (pes->data_index > 0 &&
1216 pes->data_index + buf_size > pes->total_size) {
1217 ret = new_pes_packet(pes, ts->pkt);
1220 pes->total_size = MAX_PES_PAYLOAD;
1221 pes->buffer = av_buffer_alloc(pes->total_size +
1222 AV_INPUT_BUFFER_PADDING_SIZE);
1224 return AVERROR(ENOMEM);
1226 } else if (pes->data_index == 0 &&
1227 buf_size > pes->total_size) {
1228 // pes packet size is < ts size packet and pes data is padded with 0xff
1229 // not sure if this is legal in ts but see issue #2392
1230 buf_size = pes->total_size;
1232 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1233 pes->data_index += buf_size;
1234 /* emit complete packets with known packet size
1235 * decreases demuxer delay for infrequent packets like subtitles from
1236 * a couple of seconds to milliseconds for properly muxed files.
1237 * total_size is the number of bytes following pes_packet_length
1238 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1239 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1240 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1242 ret = new_pes_packet(pes, ts->pkt);
1258 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1263 /* if no pid found, then add a pid context */
1264 pes = av_mallocz(sizeof(PESContext));
1268 pes->stream = ts->stream;
1270 pes->pcr_pid = pcr_pid;
1271 pes->state = MPEGTS_SKIP;
1272 pes->pts = AV_NOPTS_VALUE;
1273 pes->dts = AV_NOPTS_VALUE;
1274 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1283 typedef struct MP4DescrParseContext {
1287 Mp4Descr *active_descr;
1289 int max_descr_count;
1291 int predefined_SLConfigDescriptor_seen;
1292 } MP4DescrParseContext;
1294 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
1295 const uint8_t *buf, unsigned size,
1296 Mp4Descr *descr, int max_descr_count)
1299 if (size > (1 << 30))
1300 return AVERROR_INVALIDDATA;
1302 if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
1303 NULL, NULL, NULL, NULL)) < 0)
1310 d->active_descr = NULL;
1311 d->max_descr_count = max_descr_count;
1316 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1318 int64_t new_off = avio_tell(pb);
1319 (*len) -= new_off - *off;
1323 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1326 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1329 int ret = parse_mp4_descr(d, off, len, 0);
1332 update_offsets(&d->pb, &off, &len);
1337 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1339 avio_rb16(&d->pb); // ID
1345 update_offsets(&d->pb, &off, &len);
1346 return parse_mp4_descr_arr(d, off, len);
1349 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1354 id_flags = avio_rb16(&d->pb);
1355 if (!(id_flags & 0x0020)) { // URL_Flag
1356 update_offsets(&d->pb, &off, &len);
1357 return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1363 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1368 if (d->descr_count >= d->max_descr_count)
1369 return AVERROR_INVALIDDATA;
1370 ff_mp4_parse_es_descr(&d->pb, &es_id);
1371 d->active_descr = d->descr + (d->descr_count++);
1373 d->active_descr->es_id = es_id;
1374 update_offsets(&d->pb, &off, &len);
1375 if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
1377 update_offsets(&d->pb, &off, &len);
1379 ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
1380 d->active_descr = NULL;
1384 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
1387 Mp4Descr *descr = d->active_descr;
1389 return AVERROR_INVALIDDATA;
1390 d->active_descr->dec_config_descr = av_malloc(len);
1391 if (!descr->dec_config_descr)
1392 return AVERROR(ENOMEM);
1393 descr->dec_config_descr_len = len;
1394 avio_read(&d->pb, descr->dec_config_descr, len);
1398 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1400 Mp4Descr *descr = d->active_descr;
1403 return AVERROR_INVALIDDATA;
1405 predefined = avio_r8(&d->pb);
1408 int flags = avio_r8(&d->pb);
1409 descr->sl.use_au_start = !!(flags & 0x80);
1410 descr->sl.use_au_end = !!(flags & 0x40);
1411 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1412 descr->sl.use_padding = !!(flags & 0x08);
1413 descr->sl.use_timestamps = !!(flags & 0x04);
1414 descr->sl.use_idle = !!(flags & 0x02);
1415 descr->sl.timestamp_res = avio_rb32(&d->pb);
1417 descr->sl.timestamp_len = avio_r8(&d->pb);
1418 if (descr->sl.timestamp_len > 64) {
1419 avpriv_request_sample(NULL, "timestamp_len > 64");
1420 descr->sl.timestamp_len = 64;
1421 return AVERROR_PATCHWELCOME;
1423 descr->sl.ocr_len = avio_r8(&d->pb);
1424 descr->sl.au_len = avio_r8(&d->pb);
1425 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1426 lengths = avio_rb16(&d->pb);
1427 descr->sl.degr_prior_len = lengths >> 12;
1428 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1429 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1430 } else if (!d->predefined_SLConfigDescriptor_seen){
1431 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1432 d->predefined_SLConfigDescriptor_seen = 1;
1437 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1441 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1444 update_offsets(&d->pb, &off, &len);
1445 if (len < 0 || len1 > len || len1 <= 0) {
1446 av_log(d->s, AV_LOG_ERROR,
1447 "Tag %x length violation new length %d bytes remaining %d\n",
1449 return AVERROR_INVALIDDATA;
1452 if (d->level++ >= MAX_LEVEL) {
1453 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1454 ret = AVERROR_INVALIDDATA;
1458 if (target_tag && tag != target_tag) {
1459 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1461 ret = AVERROR_INVALIDDATA;
1467 ret = parse_MP4IODescrTag(d, off, len1);
1470 ret = parse_MP4ODescrTag(d, off, len1);
1473 ret = parse_MP4ESDescrTag(d, off, len1);
1475 case MP4DecConfigDescrTag:
1476 ret = parse_MP4DecConfigDescrTag(d, off, len1);
1479 ret = parse_MP4SLDescrTag(d, off, len1);
1486 avio_seek(&d->pb, off + len1, SEEK_SET);
1490 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1491 Mp4Descr *descr, int *descr_count, int max_descr_count)
1493 MP4DescrParseContext d;
1496 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1500 ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1502 *descr_count = d.descr_count;
1506 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1507 Mp4Descr *descr, int *descr_count, int max_descr_count)
1509 MP4DescrParseContext d;
1512 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1516 ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1518 *descr_count = d.descr_count;
1522 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1525 MpegTSContext *ts = filter->u.section_filter.opaque;
1526 MpegTSSectionFilter *tssf = &filter->u.section_filter;
1528 const uint8_t *p, *p_end;
1530 int mp4_descr_count = 0;
1531 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1533 AVFormatContext *s = ts->stream;
1535 p_end = section + section_len - 4;
1537 if (parse_section_header(&h, &p, p_end) < 0)
1539 if (h.tid != M4OD_TID)
1541 if (skip_identical(&h, tssf))
1544 mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1545 MAX_MP4_DESCR_COUNT);
1547 for (pid = 0; pid < NB_PID_MAX; pid++) {
1550 for (i = 0; i < mp4_descr_count; i++) {
1553 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1555 if (ts->pids[pid]->type != MPEGTS_PES) {
1556 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1559 pes = ts->pids[pid]->u.pes_filter.opaque;
1564 pes->sl = mp4_descr[i].sl;
1566 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1567 mp4_descr[i].dec_config_descr_len, 0,
1568 NULL, NULL, NULL, NULL);
1569 ff_mp4_read_dec_config_descr(s, st, &pb);
1570 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1571 st->codecpar->extradata_size > 0)
1572 st->need_parsing = 0;
1573 if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
1574 st->codecpar->extradata_size > 0)
1575 st->need_parsing = 0;
1577 st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
1578 st->internal->need_context_update = 1;
1581 for (i = 0; i < mp4_descr_count; i++)
1582 av_free(mp4_descr[i].dec_config_descr);
1585 static const uint8_t opus_coupled_stream_cnt[9] = {
1586 1, 0, 1, 1, 2, 2, 2, 3, 3
1589 static const uint8_t opus_stream_cnt[9] = {
1590 1, 1, 1, 2, 2, 3, 4, 4, 5,
1593 static const uint8_t opus_channel_map[8][8] = {
1601 { 0,6,1,2,3,4,5,7 },
1604 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1605 const uint8_t **pp, const uint8_t *desc_list_end,
1606 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1609 const uint8_t *desc_end;
1610 int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
1614 desc_tag = get8(pp, desc_list_end);
1616 return AVERROR_INVALIDDATA;
1617 desc_len = get8(pp, desc_list_end);
1619 return AVERROR_INVALIDDATA;
1620 desc_end = *pp + desc_len;
1621 if (desc_end > desc_list_end)
1622 return AVERROR_INVALIDDATA;
1624 av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1626 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
1627 stream_type == STREAM_TYPE_PRIVATE_DATA)
1628 mpegts_find_stream_type(st, desc_tag, DESC_types);
1631 case 0x1E: /* SL descriptor */
1632 desc_es_id = get16(pp, desc_end);
1635 if (ts && ts->pids[pid])
1636 ts->pids[pid]->es_id = desc_es_id;
1637 for (i = 0; i < mp4_descr_count; i++)
1638 if (mp4_descr[i].dec_config_descr_len &&
1639 mp4_descr[i].es_id == desc_es_id) {
1641 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1642 mp4_descr[i].dec_config_descr_len, 0,
1643 NULL, NULL, NULL, NULL);
1644 ff_mp4_read_dec_config_descr(fc, st, &pb);
1645 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1646 st->codecpar->extradata_size > 0) {
1647 st->need_parsing = 0;
1648 st->internal->need_context_update = 1;
1650 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1651 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1654 case 0x1F: /* FMC descriptor */
1655 if (get16(pp, desc_end) < 0)
1657 if (mp4_descr_count > 0 &&
1658 (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
1659 (st->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
1660 st->request_probe > 0) &&
1661 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1663 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1664 mp4_descr->dec_config_descr_len, 0,
1665 NULL, NULL, NULL, NULL);
1666 ff_mp4_read_dec_config_descr(fc, st, &pb);
1667 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1668 st->codecpar->extradata_size > 0) {
1669 st->request_probe = st->need_parsing = 0;
1670 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1671 st->internal->need_context_update = 1;
1675 case 0x56: /* DVB teletext descriptor */
1677 uint8_t *extradata = NULL;
1678 int language_count = desc_len / 5;
1680 if (desc_len > 0 && desc_len % 5 != 0)
1681 return AVERROR_INVALIDDATA;
1683 if (language_count > 0) {
1684 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1685 av_assert0(language_count <= sizeof(language) / 4);
1687 if (st->codecpar->extradata == NULL) {
1688 if (ff_alloc_extradata(st->codecpar, language_count * 2)) {
1689 return AVERROR(ENOMEM);
1693 if (st->codecpar->extradata_size < language_count * 2)
1694 return AVERROR_INVALIDDATA;
1696 extradata = st->codecpar->extradata;
1698 for (i = 0; i < language_count; i++) {
1699 language[i * 4 + 0] = get8(pp, desc_end);
1700 language[i * 4 + 1] = get8(pp, desc_end);
1701 language[i * 4 + 2] = get8(pp, desc_end);
1702 language[i * 4 + 3] = ',';
1704 memcpy(extradata, *pp, 2);
1710 language[i * 4 - 1] = 0;
1711 av_dict_set(&st->metadata, "language", language, 0);
1712 st->internal->need_context_update = 1;
1716 case 0x59: /* subtitling descriptor */
1718 /* 8 bytes per DVB subtitle substream data:
1719 * ISO_639_language_code (3 bytes),
1720 * subtitling_type (1 byte),
1721 * composition_page_id (2 bytes),
1722 * ancillary_page_id (2 bytes) */
1723 int language_count = desc_len / 8;
1725 if (desc_len > 0 && desc_len % 8 != 0)
1726 return AVERROR_INVALIDDATA;
1728 if (language_count > 1) {
1729 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
1732 if (language_count > 0) {
1735 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1736 av_assert0(language_count <= sizeof(language) / 4);
1738 if (st->codecpar->extradata == NULL) {
1739 if (ff_alloc_extradata(st->codecpar, language_count * 5)) {
1740 return AVERROR(ENOMEM);
1744 if (st->codecpar->extradata_size < language_count * 5)
1745 return AVERROR_INVALIDDATA;
1747 extradata = st->codecpar->extradata;
1749 for (i = 0; i < language_count; i++) {
1750 language[i * 4 + 0] = get8(pp, desc_end);
1751 language[i * 4 + 1] = get8(pp, desc_end);
1752 language[i * 4 + 2] = get8(pp, desc_end);
1753 language[i * 4 + 3] = ',';
1755 /* hearing impaired subtitles detection using subtitling_type */
1757 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1758 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1759 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1760 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1761 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1762 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1763 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1767 extradata[4] = get8(pp, desc_end); /* subtitling_type */
1768 memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
1774 language[i * 4 - 1] = 0;
1775 av_dict_set(&st->metadata, "language", language, 0);
1776 st->internal->need_context_update = 1;
1780 case 0x0a: /* ISO 639 language descriptor */
1781 for (i = 0; i + 4 <= desc_len; i += 4) {
1782 language[i + 0] = get8(pp, desc_end);
1783 language[i + 1] = get8(pp, desc_end);
1784 language[i + 2] = get8(pp, desc_end);
1785 language[i + 3] = ',';
1786 switch (get8(pp, desc_end)) {
1788 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
1791 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1794 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1798 if (i && language[0]) {
1799 language[i - 1] = 0;
1800 av_dict_set(&st->metadata, "language", language, 0);
1803 case 0x05: /* registration descriptor */
1804 st->codecpar->codec_tag = bytestream_get_le32(pp);
1805 av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
1806 if (st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0)
1807 mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
1809 case 0x52: /* stream identifier descriptor */
1810 st->stream_identifier = 1 + get8(pp, desc_end);
1812 case 0x26: /* metadata descriptor */
1813 if (get16(pp, desc_end) == 0xFFFF)
1815 if (get8(pp, desc_end) == 0xFF) {
1816 st->codecpar->codec_tag = bytestream_get_le32(pp);
1817 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
1818 mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
1821 case 0x7f: /* DVB extension descriptor */
1822 ext_desc_tag = get8(pp, desc_end);
1823 if (ext_desc_tag < 0)
1824 return AVERROR_INVALIDDATA;
1825 if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
1826 ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
1827 if (!st->codecpar->extradata) {
1828 st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
1829 AV_INPUT_BUFFER_PADDING_SIZE);
1830 if (!st->codecpar->extradata)
1831 return AVERROR(ENOMEM);
1833 st->codecpar->extradata_size = sizeof(opus_default_extradata);
1834 memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
1836 channel_config_code = get8(pp, desc_end);
1837 if (channel_config_code < 0)
1838 return AVERROR_INVALIDDATA;
1839 if (channel_config_code <= 0x8) {
1840 st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
1841 st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
1842 st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
1843 st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
1844 memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
1846 avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
1848 st->need_parsing = AVSTREAM_PARSE_FULL;
1849 st->internal->need_context_update = 1;
1860 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1862 MpegTSContext *ts = filter->u.section_filter.opaque;
1863 MpegTSSectionFilter *tssf = &filter->u.section_filter;
1864 SectionHeader h1, *h = &h1;
1867 const uint8_t *p, *p_end, *desc_list_end;
1868 int program_info_length, pcr_pid, pid, stream_type;
1870 uint32_t prog_reg_desc = 0; /* registration descriptor */
1872 int mp4_descr_count = 0;
1873 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1876 av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
1877 hex_dump_debug(ts->stream, section, section_len);
1879 p_end = section + section_len - 4;
1881 if (parse_section_header(h, &p, p_end) < 0)
1883 if (skip_identical(h, tssf))
1886 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d\n",
1887 h->id, h->sec_num, h->last_sec_num, h->version);
1889 if (h->tid != PMT_TID)
1891 if (!ts->scan_all_pmts && ts->skip_changes)
1894 if (!ts->skip_clear)
1895 clear_program(ts, h->id);
1897 pcr_pid = get16(&p, p_end);
1901 add_pid_to_pmt(ts, h->id, pcr_pid);
1902 set_pcr_pid(ts->stream, h->id, pcr_pid);
1904 av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
1906 program_info_length = get16(&p, p_end);
1907 if (program_info_length < 0)
1909 program_info_length &= 0xfff;
1910 while (program_info_length >= 2) {
1912 tag = get8(&p, p_end);
1913 len = get8(&p, p_end);
1915 av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
1917 if (len > program_info_length - 2)
1918 // something else is broken, exit the program_descriptors_loop
1920 program_info_length -= len + 2;
1921 if (tag == 0x1d) { // IOD descriptor
1922 get8(&p, p_end); // scope
1923 get8(&p, p_end); // label
1925 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1926 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1927 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1928 prog_reg_desc = bytestream_get_le32(&p);
1933 p += program_info_length;
1937 // stop parsing after pmt, we found header
1938 if (!ts->stream->nb_streams)
1941 set_pmt_found(ts, h->id);
1947 stream_type = get8(&p, p_end);
1948 if (stream_type < 0)
1950 pid = get16(&p, p_end);
1954 if (pid == ts->current_pid)
1957 /* now create stream */
1958 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1959 pes = ts->pids[pid]->u.pes_filter.opaque;
1961 pes->st = avformat_new_stream(pes->stream, NULL);
1964 pes->st->id = pes->pid;
1967 } else if (stream_type != 0x13) {
1969 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
1970 pes = add_pes_stream(ts, pid, pcr_pid);
1972 st = avformat_new_stream(pes->stream, NULL);
1978 int idx = ff_find_stream_index(ts->stream, pid);
1980 st = ts->stream->streams[idx];
1982 st = avformat_new_stream(ts->stream, NULL);
1986 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
1993 if (pes && !pes->stream_type)
1994 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1996 add_pid_to_pmt(ts, h->id, pid);
1998 av_program_add_stream_index(ts->stream, h->id, st->index);
2000 desc_list_len = get16(&p, p_end);
2001 if (desc_list_len < 0)
2003 desc_list_len &= 0xfff;
2004 desc_list_end = p + desc_list_len;
2005 if (desc_list_end > p_end)
2008 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
2009 desc_list_end, mp4_descr,
2010 mp4_descr_count, pid, ts) < 0)
2013 if (pes && prog_reg_desc == AV_RL32("HDMV") &&
2014 stream_type == 0x83 && pes->sub_st) {
2015 av_program_add_stream_index(ts->stream, h->id,
2016 pes->sub_st->index);
2017 pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
2023 if (!ts->pids[pcr_pid])
2024 mpegts_open_pcr_filter(ts, pcr_pid);
2027 for (i = 0; i < mp4_descr_count; i++)
2028 av_free(mp4_descr[i].dec_config_descr);
2031 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2033 MpegTSContext *ts = filter->u.section_filter.opaque;
2034 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2035 SectionHeader h1, *h = &h1;
2036 const uint8_t *p, *p_end;
2040 av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
2041 hex_dump_debug(ts->stream, section, section_len);
2043 p_end = section + section_len - 4;
2045 if (parse_section_header(h, &p, p_end) < 0)
2047 if (h->tid != PAT_TID)
2049 if (ts->skip_changes)
2052 if (skip_identical(h, tssf))
2054 ts->stream->ts_id = h->id;
2058 sid = get16(&p, p_end);
2061 pmt_pid = get16(&p, p_end);
2066 if (pmt_pid == ts->current_pid)
2069 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
2071 if (sid == 0x0000) {
2074 MpegTSFilter *fil = ts->pids[pmt_pid];
2075 program = av_new_program(ts->stream, sid);
2077 program->program_num = sid;
2078 program->pmt_pid = pmt_pid;
2081 if ( fil->type != MPEGTS_SECTION
2082 || fil->pid != pmt_pid
2083 || fil->u.section_filter.section_cb != pmt_cb)
2084 mpegts_close_filter(ts, ts->pids[pmt_pid]);
2086 if (!ts->pids[pmt_pid])
2087 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
2088 add_pat_entry(ts, sid);
2089 add_pid_to_pmt(ts, sid, 0); // add pat pid to program
2090 add_pid_to_pmt(ts, sid, pmt_pid);
2096 for (j=0; j<ts->stream->nb_programs; j++) {
2097 for (i = 0; i < ts->nb_prg; i++)
2098 if (ts->prg[i].id == ts->stream->programs[j]->id)
2100 if (i==ts->nb_prg && !ts->skip_clear)
2101 clear_avprogram(ts, ts->stream->programs[j]->id);
2106 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2108 MpegTSContext *ts = filter->u.section_filter.opaque;
2109 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2110 SectionHeader h1, *h = &h1;
2111 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
2112 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
2113 char *name, *provider_name;
2115 av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
2116 hex_dump_debug(ts->stream, section, section_len);
2118 p_end = section + section_len - 4;
2120 if (parse_section_header(h, &p, p_end) < 0)
2122 if (h->tid != SDT_TID)
2124 if (ts->skip_changes)
2126 if (skip_identical(h, tssf))
2129 onid = get16(&p, p_end);
2132 val = get8(&p, p_end);
2136 sid = get16(&p, p_end);
2139 val = get8(&p, p_end);
2142 desc_list_len = get16(&p, p_end);
2143 if (desc_list_len < 0)
2145 desc_list_len &= 0xfff;
2146 desc_list_end = p + desc_list_len;
2147 if (desc_list_end > p_end)
2150 desc_tag = get8(&p, desc_list_end);
2153 desc_len = get8(&p, desc_list_end);
2154 desc_end = p + desc_len;
2155 if (desc_len < 0 || desc_end > desc_list_end)
2158 av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
2159 desc_tag, desc_len);
2163 service_type = get8(&p, p_end);
2164 if (service_type < 0)
2166 provider_name = getstr8(&p, p_end);
2169 name = getstr8(&p, p_end);
2171 AVProgram *program = av_new_program(ts->stream, sid);
2173 av_dict_set(&program->metadata, "service_name", name, 0);
2174 av_dict_set(&program->metadata, "service_provider",
2179 av_free(provider_name);
2190 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2191 const uint8_t *packet);
2193 /* handle one TS packet */
2194 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
2197 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
2198 has_adaptation, has_payload;
2199 const uint8_t *p, *p_end;
2202 pid = AV_RB16(packet + 1) & 0x1fff;
2203 if (pid && discard_pid(ts, pid))
2205 is_start = packet[1] & 0x40;
2206 tss = ts->pids[pid];
2207 if (ts->auto_guess && !tss && is_start) {
2208 add_pes_stream(ts, pid, -1);
2209 tss = ts->pids[pid];
2213 ts->current_pid = pid;
2215 afc = (packet[3] >> 4) & 3;
2216 if (afc == 0) /* reserved value */
2218 has_adaptation = afc & 2;
2219 has_payload = afc & 1;
2220 is_discontinuity = has_adaptation &&
2221 packet[4] != 0 && /* with length > 0 */
2222 (packet[5] & 0x80); /* and discontinuity indicated */
2224 /* continuity check (currently not used) */
2225 cc = (packet[3] & 0xf);
2226 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
2227 cc_ok = pid == 0x1FFF || // null packet PID
2234 av_log(ts->stream, AV_LOG_DEBUG,
2235 "Continuity check failed for pid %d expected %d got %d\n",
2236 pid, expected_cc, cc);
2237 if (tss->type == MPEGTS_PES) {
2238 PESContext *pc = tss->u.pes_filter.opaque;
2239 pc->flags |= AV_PKT_FLAG_CORRUPT;
2244 if (has_adaptation) {
2247 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
2248 tss->last_pcr = pcr_h * 300 + pcr_l;
2249 /* skip adaptation field */
2252 /* if past the end of packet, ignore */
2253 p_end = packet + TS_PACKET_SIZE;
2254 if (p >= p_end || !has_payload)
2257 pos = avio_tell(ts->stream->pb);
2259 av_assert0(pos >= TS_PACKET_SIZE);
2260 ts->pos47_full = pos - TS_PACKET_SIZE;
2263 if (tss->type == MPEGTS_SECTION) {
2265 /* pointer field present */
2267 if (len > p_end - p)
2270 /* write remaining section bytes */
2271 write_section_data(ts, tss,
2273 /* check whether filter has been closed */
2279 write_section_data(ts, tss,
2284 write_section_data(ts, tss,
2289 // stop find_stream_info from waiting for more streams
2290 // when all programs have received a PMT
2291 if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
2293 for (i = 0; i < ts->nb_prg; i++) {
2294 if (!ts->prg[i].pmt_found)
2297 if (i == ts->nb_prg && ts->nb_prg > 0) {
2299 for (i = 0; i < ts->stream->nb_streams; i++) {
2300 AVStream *st = ts->stream->streams[i];
2301 types |= 1<<st->codecpar->codec_type;
2303 if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
2304 av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
2305 ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
2312 // Note: The position here points actually behind the current packet.
2313 if (tss->type == MPEGTS_PES) {
2314 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
2315 pos - ts->raw_packet_size)) < 0)
2323 static void reanalyze(MpegTSContext *ts) {
2324 AVIOContext *pb = ts->stream->pb;
2325 int64_t pos = avio_tell(pb);
2328 pos -= ts->pos47_full;
2329 if (pos == TS_PACKET_SIZE) {
2330 ts->size_stat[0] ++;
2331 } else if (pos == TS_DVHS_PACKET_SIZE) {
2332 ts->size_stat[1] ++;
2333 } else if (pos == TS_FEC_PACKET_SIZE) {
2334 ts->size_stat[2] ++;
2337 ts->size_stat_count ++;
2338 if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
2340 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
2341 newsize = TS_PACKET_SIZE;
2342 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
2343 newsize = TS_DVHS_PACKET_SIZE;
2344 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
2345 newsize = TS_FEC_PACKET_SIZE;
2347 if (newsize && newsize != ts->raw_packet_size) {
2348 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
2349 ts->raw_packet_size = newsize;
2351 ts->size_stat_count = 0;
2352 memset(ts->size_stat, 0, sizeof(ts->size_stat));
2356 /* XXX: try to find a better synchro over several packets (use
2357 * get_packet_size() ?) */
2358 static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
2360 MpegTSContext *ts = s->priv_data;
2361 AVIOContext *pb = s->pb;
2363 uint64_t pos = avio_tell(pb);
2365 avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
2367 //Special case for files like 01c56b0dc1.ts
2368 if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
2369 avio_seek(pb, 12, SEEK_CUR);
2373 for (i = 0; i < ts->resync_size; i++) {
2378 avio_seek(pb, -1, SEEK_CUR);
2379 reanalyze(s->priv_data);
2383 av_log(s, AV_LOG_ERROR,
2384 "max resync size reached, could not find sync byte\n");
2386 return AVERROR_INVALIDDATA;
2389 /* return AVERROR_something if error or EOF. Return 0 if OK. */
2390 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
2391 const uint8_t **data)
2393 AVIOContext *pb = s->pb;
2397 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2398 if (len != TS_PACKET_SIZE)
2399 return len < 0 ? len : AVERROR_EOF;
2400 /* check packet sync byte */
2401 if ((*data)[0] != 0x47) {
2402 /* find a new packet start */
2404 if (mpegts_resync(s, raw_packet_size, *data) < 0)
2405 return AVERROR(EAGAIN);
2415 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2417 AVIOContext *pb = s->pb;
2418 int skip = raw_packet_size - TS_PACKET_SIZE;
2420 avio_skip(pb, skip);
2423 static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
2425 AVFormatContext *s = ts->stream;
2426 uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
2427 const uint8_t *data;
2431 if (avio_tell(s->pb) != ts->last_pos) {
2433 av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
2434 /* seek detected, flush pes buffer */
2435 for (i = 0; i < NB_PID_MAX; i++) {
2437 if (ts->pids[i]->type == MPEGTS_PES) {
2438 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2439 av_buffer_unref(&pes->buffer);
2440 pes->data_index = 0;
2441 pes->state = MPEGTS_SKIP; /* skip until pes header */
2442 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
2443 ts->pids[i]->u.section_filter.last_ver = -1;
2445 ts->pids[i]->last_cc = -1;
2446 ts->pids[i]->last_pcr = -1;
2453 memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2456 if (nb_packets != 0 && packet_num >= nb_packets ||
2457 ts->stop_parse > 1) {
2458 ret = AVERROR(EAGAIN);
2461 if (ts->stop_parse > 0)
2464 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2467 ret = handle_packet(ts, data);
2468 finished_reading_packet(s, ts->raw_packet_size);
2472 ts->last_pos = avio_tell(s->pb);
2476 static int mpegts_probe(AVProbeData *p)
2478 const int size = p->buf_size;
2482 int check_count = size / TS_FEC_PACKET_SIZE;
2483 #define CHECK_COUNT 10
2484 #define CHECK_BLOCK 100
2489 for (i = 0; i<check_count; i+=CHECK_BLOCK) {
2490 int left = FFMIN(check_count - i, CHECK_BLOCK);
2491 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
2492 int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
2493 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
2494 score = FFMAX3(score, dvhs_score, fec_score);
2496 maxscore = FFMAX(maxscore, score);
2499 sumscore = sumscore * CHECK_COUNT / check_count;
2500 maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
2502 ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2504 if (check_count >= CHECK_COUNT && sumscore > 6) {
2505 return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2506 } else if (check_count >= CHECK_COUNT && maxscore > 6) {
2507 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2508 } else if (sumscore > 6) {
2515 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2516 * (-1) if not available */
2517 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
2519 int afc, len, flags;
2523 afc = (packet[3] >> 4) & 3;
2525 return AVERROR_INVALIDDATA;
2530 return AVERROR_INVALIDDATA;
2533 if (!(flags & 0x10))
2534 return AVERROR_INVALIDDATA;
2536 return AVERROR_INVALIDDATA;
2538 *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
2539 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2543 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2545 /* NOTE: We attempt to seek on non-seekable files as well, as the
2546 * probe buffer usually is big enough. Only warn if the seek failed
2547 * on files where the seek should work. */
2548 if (avio_seek(pb, pos, SEEK_SET) < 0)
2549 av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2552 static int mpegts_read_header(AVFormatContext *s)
2554 MpegTSContext *ts = s->priv_data;
2555 AVIOContext *pb = s->pb;
2556 uint8_t buf[8 * 1024] = {0};
2558 int64_t pos, probesize = s->probesize;
2560 if (ffio_ensure_seekback(pb, probesize) < 0)
2561 av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
2563 /* read the first 8192 bytes to get packet size */
2564 pos = avio_tell(pb);
2565 len = avio_read(pb, buf, sizeof(buf));
2566 ts->raw_packet_size = get_packet_size(buf, len);
2567 if (ts->raw_packet_size <= 0) {
2568 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2569 ts->raw_packet_size = TS_PACKET_SIZE;
2574 if (s->iformat == &ff_mpegts_demuxer) {
2577 /* first do a scan to get all the services */
2578 seek_back(s, pb, pos);
2580 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2582 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2584 handle_packets(ts, probesize / ts->raw_packet_size);
2585 /* if could not find service, enable auto_guess */
2589 av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
2591 s->ctx_flags |= AVFMTCTX_NOHEADER;
2594 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2595 int64_t pcrs[2], pcr_h;
2596 int packet_count[2];
2597 uint8_t packet[TS_PACKET_SIZE];
2598 const uint8_t *data;
2600 /* only read packets */
2602 st = avformat_new_stream(s, NULL);
2604 return AVERROR(ENOMEM);
2605 avpriv_set_pts_info(st, 60, 1, 27000000);
2606 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2607 st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
2609 /* we iterate until we find two PCRs to estimate the bitrate */
2614 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2617 pid = AV_RB16(data + 1) & 0x1fff;
2618 if ((pcr_pid == -1 || pcr_pid == pid) &&
2619 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2620 finished_reading_packet(s, ts->raw_packet_size);
2622 packet_count[nb_pcrs] = nb_packets;
2623 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2628 finished_reading_packet(s, ts->raw_packet_size);
2633 /* NOTE1: the bitrate is computed without the FEC */
2634 /* NOTE2: it is only the bitrate of the start of the stream */
2635 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2636 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2637 s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
2638 st->codecpar->bit_rate = s->bit_rate;
2639 st->start_time = ts->cur_pcr;
2640 av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
2641 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2644 seek_back(s, pb, pos);
2648 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2650 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
2652 MpegTSContext *ts = s->priv_data;
2654 int64_t pcr_h, next_pcr_h, pos;
2655 int pcr_l, next_pcr_l;
2656 uint8_t pcr_buf[12];
2657 const uint8_t *data;
2659 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2660 return AVERROR(ENOMEM);
2661 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2662 pkt->pos = avio_tell(s->pb);
2664 av_packet_unref(pkt);
2667 if (data != pkt->data)
2668 memcpy(pkt->data, data, ts->raw_packet_size);
2669 finished_reading_packet(s, ts->raw_packet_size);
2670 if (ts->mpeg2ts_compute_pcr) {
2671 /* compute exact PCR for each packet */
2672 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2673 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2674 pos = avio_tell(s->pb);
2675 for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
2676 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2677 avio_read(s->pb, pcr_buf, 12);
2678 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2679 /* XXX: not precise enough */
2681 ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2686 avio_seek(s->pb, pos, SEEK_SET);
2687 /* no next PCR found: we use previous increment */
2688 ts->cur_pcr = pcr_h * 300 + pcr_l;
2690 pkt->pts = ts->cur_pcr;
2691 pkt->duration = ts->pcr_incr;
2692 ts->cur_pcr += ts->pcr_incr;
2694 pkt->stream_index = 0;
2698 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
2700 MpegTSContext *ts = s->priv_data;
2705 ret = handle_packets(ts, 0);
2707 av_packet_unref(ts->pkt);
2708 /* flush pes data left */
2709 for (i = 0; i < NB_PID_MAX; i++)
2710 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2711 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2712 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2713 ret = new_pes_packet(pes, pkt);
2716 pes->state = MPEGTS_SKIP;
2723 if (!ret && pkt->size < 0)
2724 ret = AVERROR_INVALIDDATA;
2728 static void mpegts_free(MpegTSContext *ts)
2734 for (i = 0; i < NB_PID_MAX; i++)
2736 mpegts_close_filter(ts, ts->pids[i]);
2739 static int mpegts_read_close(AVFormatContext *s)
2741 MpegTSContext *ts = s->priv_data;
2746 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2747 int64_t *ppos, int64_t pos_limit)
2749 MpegTSContext *ts = s->priv_data;
2750 int64_t pos, timestamp;
2751 uint8_t buf[TS_PACKET_SIZE];
2752 int pcr_l, pcr_pid =
2753 ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
2754 int pos47 = ts->pos47_full % ts->raw_packet_size;
2756 ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
2757 ts->raw_packet_size + pos47;
2758 while(pos < pos_limit) {
2759 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2760 return AV_NOPTS_VALUE;
2761 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2762 return AV_NOPTS_VALUE;
2763 if (buf[0] != 0x47) {
2764 if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
2765 return AV_NOPTS_VALUE;
2766 pos = avio_tell(s->pb);
2769 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2770 parse_pcr(×tamp, &pcr_l, buf) == 0) {
2774 pos += ts->raw_packet_size;
2777 return AV_NOPTS_VALUE;
2780 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2781 int64_t *ppos, int64_t pos_limit)
2783 MpegTSContext *ts = s->priv_data;
2785 int pos47 = ts->pos47_full % ts->raw_packet_size;
2786 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2787 ff_read_frame_flush(s);
2788 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2789 return AV_NOPTS_VALUE;
2790 while(pos < pos_limit) {
2793 av_init_packet(&pkt);
2794 ret = av_read_frame(s, &pkt);
2796 return AV_NOPTS_VALUE;
2797 if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
2798 ff_reduce_index(s, pkt.stream_index);
2799 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2800 if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
2801 int64_t dts = pkt.dts;
2803 av_packet_unref(&pkt);
2808 av_packet_unref(&pkt);
2811 return AV_NOPTS_VALUE;
2814 /**************************************************************/
2815 /* parsing functions - called from other demuxers such as RTP */
2817 MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
2821 ts = av_mallocz(sizeof(MpegTSContext));
2824 /* no stream case, currently used by RTP */
2825 ts->raw_packet_size = TS_PACKET_SIZE;
2828 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2829 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2834 /* return the consumed length if a packet was output, or -1 if no
2835 * packet is output */
2836 int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2837 const uint8_t *buf, int len)
2845 if (len < TS_PACKET_SIZE)
2846 return AVERROR_INVALIDDATA;
2847 if (buf[0] != 0x47) {
2851 handle_packet(ts, buf);
2852 buf += TS_PACKET_SIZE;
2853 len -= TS_PACKET_SIZE;
2854 if (ts->stop_parse == 1)
2861 void avpriv_mpegts_parse_close(MpegTSContext *ts)
2867 AVInputFormat ff_mpegts_demuxer = {
2869 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2870 .priv_data_size = sizeof(MpegTSContext),
2871 .read_probe = mpegts_probe,
2872 .read_header = mpegts_read_header,
2873 .read_packet = mpegts_read_packet,
2874 .read_close = mpegts_read_close,
2875 .read_timestamp = mpegts_get_dts,
2876 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2877 .priv_class = &mpegts_class,
2880 AVInputFormat ff_mpegtsraw_demuxer = {
2881 .name = "mpegtsraw",
2882 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2883 .priv_data_size = sizeof(MpegTSContext),
2884 .read_header = mpegts_read_header,
2885 .read_packet = mpegts_raw_read_packet,
2886 .read_close = mpegts_read_close,
2887 .read_timestamp = mpegts_get_dts,
2888 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2889 .priv_class = &mpegtsraw_class,