2 * MPEG-2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/buffer.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/internal.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/log.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/mathematics.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/avassert.h"
31 #include "libavcodec/bytestream.h"
32 #include "libavcodec/get_bits.h"
33 #include "libavcodec/opus.h"
37 #include "avio_internal.h"
44 /* maximum size in which we look for synchronization if
45 * synchronization is lost */
46 #define MAX_RESYNC_SIZE 65536
48 #define MAX_PES_PAYLOAD 200 * 1024
50 #define MAX_MP4_DESCR_COUNT 16
52 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \
54 if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
55 (modulus) = (dividend) % (divisor); \
56 (prev_dividend) = (dividend); \
59 enum MpegTSFilterType {
65 typedef struct MpegTSFilter MpegTSFilter;
67 typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len,
68 int is_start, int64_t pos);
70 typedef struct MpegTSPESFilter {
75 typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len);
77 typedef void SetServiceCallback (void *opaque, int ret);
79 typedef struct MpegTSSectionFilter {
86 unsigned int check_crc : 1;
87 unsigned int end_of_section_reached : 1;
88 SectionCallback *section_cb;
90 } MpegTSSectionFilter;
95 int last_cc; /* last cc code (-1 if first packet) */
98 enum MpegTSFilterType type;
100 MpegTSPESFilter pes_filter;
101 MpegTSSectionFilter section_filter;
105 #define MAX_PIDS_PER_PROGRAM 64
107 unsigned int id; // program id/service id
108 unsigned int nb_pids;
109 unsigned int pids[MAX_PIDS_PER_PROGRAM];
111 /** have we found pmt for this program */
115 struct MpegTSContext {
116 const AVClass *class;
118 AVFormatContext *stream;
119 /** raw packet size, including FEC if present */
124 #define SIZE_STAT_THRESHOLD 10
128 /** if true, all pids are analyzed to find streams */
131 /** compute exact PCR for each transport stream packet */
132 int mpeg2ts_compute_pcr;
134 /** fix dvb teletext pts */
135 int fix_teletext_pts;
137 int64_t cur_pcr; /**< used to estimate the exact PCR */
138 int pcr_incr; /**< used to estimate the exact PCR */
140 /* data needed to handle file based ts */
141 /** stop parsing loop */
143 /** packet containing Audio/Video data */
145 /** to detect seek */
150 int skip_unknown_pmt;
155 int merge_pmt_versions;
157 /******************************************/
158 /* private mpegts data */
160 /** structure to keep track of Program->pids mapping */
164 int8_t crc_validity[NB_PID_MAX];
165 /** filters for various streams specified by PMT + for the PAT and PMT */
166 MpegTSFilter *pids[NB_PID_MAX];
170 #define MPEGTS_OPTIONS \
171 { "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 }
173 static const AVOption options[] = {
175 {"fix_teletext_pts", "try to fix pts values of dvb teletext streams", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_BOOL,
176 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
177 {"ts_packetsize", "output option carrying the raw packet size", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
178 {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
179 {"scan_all_pmts", "scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_BOOL,
180 {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM },
181 {"skip_unknown_pmt", "skip PMTs for programs not advertised in the PAT", offsetof(MpegTSContext, skip_unknown_pmt), AV_OPT_TYPE_BOOL,
182 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
183 {"merge_pmt_versions", "re-use streams when PMT's version/pids change", offsetof(MpegTSContext, merge_pmt_versions), AV_OPT_TYPE_BOOL,
184 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
185 {"skip_changes", "skip changing / adding streams / programs", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_BOOL,
186 {.i64 = 0}, 0, 1, 0 },
187 {"skip_clear", "skip clearing programs", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_BOOL,
188 {.i64 = 0}, 0, 1, 0 },
192 static const AVClass mpegts_class = {
193 .class_name = "mpegts demuxer",
194 .item_name = av_default_item_name,
196 .version = LIBAVUTIL_VERSION_INT,
199 static const AVOption raw_options[] = {
201 { "compute_pcr", "compute exact PCR for each transport stream packet",
202 offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_BOOL,
203 { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
204 { "ts_packetsize", "output option carrying the raw packet size",
205 offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT,
207 AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
211 static const AVClass mpegtsraw_class = {
212 .class_name = "mpegtsraw demuxer",
213 .item_name = av_default_item_name,
214 .option = raw_options,
215 .version = LIBAVUTIL_VERSION_INT,
218 /* TS stream handling */
223 MPEGTS_PESHEADER_FILL,
228 /* enough for PES header + length */
229 #define PES_START_SIZE 6
230 #define PES_HEADER_SIZE 9
231 #define MAX_PES_HEADER_SIZE (9 + 255)
233 typedef struct PESContext {
235 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
238 AVFormatContext *stream;
240 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
241 enum MpegTSState state;
242 /* used to get the format */
244 int flags; /**< copied to the AVPacket flags */
247 int extended_stream_id;
250 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
251 uint8_t header[MAX_PES_HEADER_SIZE];
257 extern AVInputFormat ff_mpegts_demuxer;
259 static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
262 for (i = 0; i < ts->nb_prg; i++) {
263 if (ts->prg[i].id == programid) {
270 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
272 AVProgram *prg = NULL;
275 for (i = 0; i < ts->stream->nb_programs; i++)
276 if (ts->stream->programs[i]->id == programid) {
277 prg = ts->stream->programs[i];
282 prg->nb_stream_indexes = 0;
285 static void clear_program(MpegTSContext *ts, unsigned int programid)
289 clear_avprogram(ts, programid);
290 for (i = 0; i < ts->nb_prg; i++)
291 if (ts->prg[i].id == programid) {
292 ts->prg[i].nb_pids = 0;
293 ts->prg[i].pmt_found = 0;
297 static void clear_programs(MpegTSContext *ts)
303 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
306 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
310 p = &ts->prg[ts->nb_prg];
317 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid,
320 struct Program *p = get_program(ts, programid);
325 if (p->nb_pids >= MAX_PIDS_PER_PROGRAM)
328 for (i = 0; i < p->nb_pids; i++)
329 if (p->pids[i] == pid)
332 p->pids[p->nb_pids++] = pid;
335 static void set_pmt_found(MpegTSContext *ts, unsigned int programid)
337 struct Program *p = get_program(ts, programid);
344 static void update_av_program_info(AVFormatContext *s, unsigned int programid,
345 unsigned int pid, int version)
348 for (i = 0; i < s->nb_programs; i++) {
349 AVProgram *program = s->programs[i];
350 if (program->id == programid) {
351 int old_pcr_pid = program->pcr_pid,
352 old_version = program->pmt_version;
353 program->pcr_pid = pid;
354 program->pmt_version = version;
356 if (old_version != -1 && old_version != version) {
357 av_log(s, AV_LOG_VERBOSE,
358 "detected PMT change (program=%d, version=%d/%d, pcr_pid=0x%x/0x%x)\n",
359 programid, old_version, version, old_pcr_pid, pid);
367 * @brief discard_pid() decides if the pid is to be discarded according
368 * to caller's programs selection
369 * @param ts : - TS context
371 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
374 static int discard_pid(MpegTSContext *ts, unsigned int pid)
377 int used = 0, discarded = 0;
380 /* If none of the programs have .discard=AVDISCARD_ALL then there's
381 * no way we have to discard this packet */
382 for (k = 0; k < ts->stream->nb_programs; k++)
383 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
385 if (k == ts->stream->nb_programs)
388 for (i = 0; i < ts->nb_prg; i++) {
390 for (j = 0; j < p->nb_pids; j++) {
391 if (p->pids[j] != pid)
393 // is program with id p->id set to be discarded?
394 for (k = 0; k < ts->stream->nb_programs; k++) {
395 if (ts->stream->programs[k]->id == p->id) {
396 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
405 return !used && discarded;
409 * Assemble PES packets out of TS packets, and then call the "section_cb"
410 * function when they are complete.
412 static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1,
413 const uint8_t *buf, int buf_size, int is_start)
415 MpegTSSectionFilter *tss = &tss1->u.section_filter;
416 uint8_t *cur_section_buf = NULL;
420 memcpy(tss->section_buf, buf, buf_size);
421 tss->section_index = buf_size;
422 tss->section_h_size = -1;
423 tss->end_of_section_reached = 0;
425 if (tss->end_of_section_reached)
427 len = MAX_SECTION_SIZE - tss->section_index;
430 memcpy(tss->section_buf + tss->section_index, buf, len);
431 tss->section_index += len;
435 cur_section_buf = tss->section_buf;
436 while (cur_section_buf - tss->section_buf < MAX_SECTION_SIZE && cur_section_buf[0] != 0xff) {
437 /* compute section length if possible */
438 if (tss->section_h_size == -1 && tss->section_index - offset >= 3) {
439 len = (AV_RB16(cur_section_buf + 1) & 0xfff) + 3;
440 if (len > MAX_SECTION_SIZE)
442 tss->section_h_size = len;
445 if (tss->section_h_size != -1 &&
446 tss->section_index >= offset + tss->section_h_size) {
448 tss->end_of_section_reached = 1;
450 if (tss->check_crc) {
451 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, cur_section_buf, tss->section_h_size);
452 if (tss->section_h_size >= 4)
453 tss->crc = AV_RB32(cur_section_buf + tss->section_h_size - 4);
456 ts->crc_validity[ tss1->pid ] = 100;
457 }else if (ts->crc_validity[ tss1->pid ] > -10) {
458 ts->crc_validity[ tss1->pid ]--;
463 tss->section_cb(tss1, cur_section_buf, tss->section_h_size);
468 cur_section_buf += tss->section_h_size;
469 offset += tss->section_h_size;
470 tss->section_h_size = -1;
472 tss->section_h_size = -1;
473 tss->end_of_section_reached = 0;
479 static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid,
480 enum MpegTSFilterType type)
482 MpegTSFilter *filter;
484 av_log(ts->stream, AV_LOG_TRACE, "Filter: pid=0x%x type=%d\n", pid, type);
486 if (pid >= NB_PID_MAX || ts->pids[pid])
488 filter = av_mallocz(sizeof(MpegTSFilter));
491 ts->pids[pid] = filter;
496 filter->last_cc = -1;
497 filter->last_pcr= -1;
502 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts,
504 SectionCallback *section_cb,
508 MpegTSFilter *filter;
509 MpegTSSectionFilter *sec;
511 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION)))
513 sec = &filter->u.section_filter;
514 sec->section_cb = section_cb;
515 sec->opaque = opaque;
516 sec->section_buf = av_mallocz(MAX_SECTION_SIZE);
517 sec->check_crc = check_crc;
520 if (!sec->section_buf) {
527 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
531 MpegTSFilter *filter;
532 MpegTSPESFilter *pes;
534 if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES)))
537 pes = &filter->u.pes_filter;
538 pes->pes_cb = pes_cb;
539 pes->opaque = opaque;
543 static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid)
545 return mpegts_open_filter(ts, pid, MPEGTS_PCR);
548 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
553 if (filter->type == MPEGTS_SECTION)
554 av_freep(&filter->u.section_filter.section_buf);
555 else if (filter->type == MPEGTS_PES) {
556 PESContext *pes = filter->u.pes_filter.opaque;
557 av_buffer_unref(&pes->buffer);
558 /* referenced private data will be freed later in
559 * avformat_close_input (pes->st->priv_data == pes) */
560 if (!pes->st || pes->merged_st) {
561 av_freep(&filter->u.pes_filter.opaque);
566 ts->pids[pid] = NULL;
569 static int analyze(const uint8_t *buf, int size, int packet_size,
572 int stat[TS_MAX_PACKET_SIZE];
577 memset(stat, 0, packet_size * sizeof(*stat));
579 for (i = 0; i < size - 3; i++) {
580 if (buf[i] == 0x47) {
581 int pid = AV_RB16(buf+1) & 0x1FFF;
582 int asc = buf[i + 3] & 0x30;
583 if (!probe || pid == 0x1FFF || asc) {
584 int x = i % packet_size;
587 if (stat[x] > best_score) {
588 best_score = stat[x];
594 return best_score - FFMAX(stat_all - 10*best_score, 0)/10;
597 /* autodetect fec presence. Must have at least 1024 bytes */
598 static int get_packet_size(const uint8_t *buf, int size)
600 int score, fec_score, dvhs_score;
602 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
603 return AVERROR_INVALIDDATA;
605 score = analyze(buf, size, TS_PACKET_SIZE, 0);
606 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, 0);
607 fec_score = analyze(buf, size, TS_FEC_PACKET_SIZE, 0);
608 av_log(NULL, AV_LOG_TRACE, "score: %d, dvhs_score: %d, fec_score: %d \n",
609 score, dvhs_score, fec_score);
611 if (score > fec_score && score > dvhs_score)
612 return TS_PACKET_SIZE;
613 else if (dvhs_score > score && dvhs_score > fec_score)
614 return TS_DVHS_PACKET_SIZE;
615 else if (score < fec_score && dvhs_score < fec_score)
616 return TS_FEC_PACKET_SIZE;
618 return AVERROR_INVALIDDATA;
621 typedef struct SectionHeader {
626 uint8_t last_sec_num;
629 static int skip_identical(const SectionHeader *h, MpegTSSectionFilter *tssf)
631 if (h->version == tssf->last_ver && tssf->last_crc == tssf->crc)
634 tssf->last_ver = h->version;
635 tssf->last_crc = tssf->crc;
640 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
647 return AVERROR_INVALIDDATA;
653 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
660 return AVERROR_INVALIDDATA;
667 /* read and allocate a DVB string preceded by its length */
668 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
675 len = get8(&p, p_end);
682 const char *encodings[] = {
683 "ISO6937", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7",
684 "ISO-8859-8", "ISO-8859-9", "ISO-8859-10", "ISO-8859-11",
685 "", "ISO-8859-13", "ISO-8859-14", "ISO-8859-15", "", "", "", "",
686 "", "UCS-2BE", "KSC_5601", "GB2312", "UCS-2BE", "UTF-8", "", "",
687 "", "", "", "", "", "", "", ""
691 size_t inlen = len, outlen = inlen * 6 + 1;
692 if (len >= 3 && p[0] == 0x10 && !p[1] && p[2] && p[2] <= 0xf && p[2] != 0xc) {
694 snprintf(iso8859, sizeof(iso8859), "ISO-8859-%d", p[2]);
697 cd = iconv_open("UTF-8", iso8859);
698 } else if (p[0] < 0x20) {
701 cd = iconv_open("UTF-8", encodings[*p]);
704 cd = iconv_open("UTF-8", encodings[0]);
706 if (cd == (iconv_t)-1)
708 str = out = av_malloc(outlen);
713 if (iconv(cd, &in, &inlen, &out, &outlen) == -1) {
725 str = av_malloc(len + 1);
735 static int parse_section_header(SectionHeader *h,
736 const uint8_t **pp, const uint8_t *p_end)
740 val = get8(pp, p_end);
745 val = get16(pp, p_end);
749 val = get8(pp, p_end);
752 h->version = (val >> 1) & 0x1f;
753 val = get8(pp, p_end);
757 val = get8(pp, p_end);
760 h->last_sec_num = val;
764 typedef struct StreamType {
765 uint32_t stream_type;
766 enum AVMediaType codec_type;
767 enum AVCodecID codec_id;
770 static const StreamType ISO_types[] = {
771 { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
772 { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
773 { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
774 { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
775 { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
776 { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
777 /* Makito encoder sets stream type 0x11 for AAC,
778 * so auto-detect LOAS/LATM instead of hardcoding it. */
779 #if !CONFIG_LOAS_DEMUXER
780 { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
782 { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
783 { 0x1c, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
784 { 0x20, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
785 { 0x21, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_JPEG2000 },
786 { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
787 { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
788 { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
789 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
793 static const StreamType HDMV_types[] = {
794 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
795 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
796 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
797 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
798 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
799 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
800 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
801 { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
802 { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
803 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
804 { 0x92, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_TEXT_SUBTITLE },
809 static const StreamType SCTE_types[] = {
810 { 0x86, AVMEDIA_TYPE_DATA, AV_CODEC_ID_SCTE_35 },
815 static const StreamType MISC_types[] = {
816 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
817 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
821 static const StreamType REGD_types[] = {
822 { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
823 { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
824 { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
825 { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
826 { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
827 { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
828 { MKTAG('E', 'A', 'C', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
829 { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
830 { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
831 { MKTAG('I', 'D', '3', ' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
832 { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
833 { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS },
837 static const StreamType METADATA_types[] = {
838 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
839 { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 },
843 /* descriptor present */
844 static const StreamType DESC_types[] = {
845 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
846 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
847 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
848 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
849 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
853 static void mpegts_find_stream_type(AVStream *st,
854 uint32_t stream_type,
855 const StreamType *types)
857 for (; types->stream_type; types++)
858 if (stream_type == types->stream_type) {
859 if (st->codecpar->codec_type != types->codec_type ||
860 st->codecpar->codec_id != types->codec_id) {
861 st->codecpar->codec_type = types->codec_type;
862 st->codecpar->codec_id = types->codec_id;
863 st->internal->need_context_update = 1;
865 st->request_probe = 0;
870 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
871 uint32_t stream_type, uint32_t prog_reg_desc)
873 int old_codec_type = st->codecpar->codec_type;
874 int old_codec_id = st->codecpar->codec_id;
875 int old_codec_tag = st->codecpar->codec_tag;
877 if (avcodec_is_open(st->internal->avctx)) {
878 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, internal codec is open\n");
882 avpriv_set_pts_info(st, 33, 1, 90000);
884 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
885 st->codecpar->codec_id = AV_CODEC_ID_NONE;
886 st->need_parsing = AVSTREAM_PARSE_FULL;
888 pes->stream_type = stream_type;
890 av_log(pes->stream, AV_LOG_DEBUG,
891 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
892 st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc);
894 st->codecpar->codec_tag = pes->stream_type;
896 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
897 if (pes->stream_type == 4 || pes->stream_type == 0x0f)
898 st->request_probe = 50;
899 if ((prog_reg_desc == AV_RL32("HDMV") ||
900 prog_reg_desc == AV_RL32("HDPR")) &&
901 st->codecpar->codec_id == AV_CODEC_ID_NONE) {
902 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
903 if (pes->stream_type == 0x83) {
904 // HDMV TrueHD streams also contain an AC3 coded version of the
905 // audio track - add a second stream for this
907 // priv_data cannot be shared between streams
908 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
910 return AVERROR(ENOMEM);
911 memcpy(sub_pes, pes, sizeof(*sub_pes));
913 sub_st = avformat_new_stream(pes->stream, NULL);
916 return AVERROR(ENOMEM);
919 sub_st->id = pes->pid;
920 avpriv_set_pts_info(sub_st, 33, 1, 90000);
921 sub_st->priv_data = sub_pes;
922 sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
923 sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
924 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
925 sub_pes->sub_st = pes->sub_st = sub_st;
928 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
929 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
930 if (st->codecpar->codec_id == AV_CODEC_ID_NONE) {
931 st->codecpar->codec_id = old_codec_id;
932 st->codecpar->codec_type = old_codec_type;
934 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE ||
935 (st->request_probe > 0 && st->request_probe < AVPROBE_SCORE_STREAM_RETRY / 5)) &&
936 st->probe_packets > 0 &&
937 stream_type == STREAM_TYPE_PRIVATE_DATA) {
938 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
939 st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
940 st->request_probe = AVPROBE_SCORE_STREAM_RETRY / 5;
943 /* queue a context update if properties changed */
944 if (old_codec_type != st->codecpar->codec_type ||
945 old_codec_id != st->codecpar->codec_id ||
946 old_codec_tag != st->codecpar->codec_tag)
947 st->internal->need_context_update = 1;
952 static void reset_pes_packet_state(PESContext *pes)
954 pes->pts = AV_NOPTS_VALUE;
955 pes->dts = AV_NOPTS_VALUE;
958 av_buffer_unref(&pes->buffer);
961 static void new_data_packet(const uint8_t *buffer, int len, AVPacket *pkt)
964 pkt->data = (uint8_t *)buffer;
968 static int new_pes_packet(PESContext *pes, AVPacket *pkt)
974 pkt->buf = pes->buffer;
975 pkt->data = pes->buffer->data;
976 pkt->size = pes->data_index;
978 if (pes->total_size != MAX_PES_PAYLOAD &&
979 pes->pes_header_size + pes->data_index != pes->total_size +
981 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
982 pes->flags |= AV_PKT_FLAG_CORRUPT;
984 memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
986 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
987 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
988 pkt->stream_index = pes->sub_st->index;
990 pkt->stream_index = pes->st->index;
993 /* store position of first TS packet of this PES packet */
994 pkt->pos = pes->ts_packet_pos;
995 pkt->flags = pes->flags;
998 reset_pes_packet_state(pes);
1000 sd = av_packet_new_side_data(pkt, AV_PKT_DATA_MPEGTS_STREAM_ID, 1);
1002 return AVERROR(ENOMEM);
1003 *sd = pes->stream_id;
1008 static uint64_t get_ts64(GetBitContext *gb, int bits)
1010 if (get_bits_left(gb) < bits)
1011 return AV_NOPTS_VALUE;
1012 return get_bits64(gb, bits);
1015 static int read_sl_header(PESContext *pes, SLConfigDescr *sl,
1016 const uint8_t *buf, int buf_size)
1019 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
1020 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
1021 int dts_flag = -1, cts_flag = -1;
1022 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
1023 uint8_t buf_padded[128 + AV_INPUT_BUFFER_PADDING_SIZE];
1024 int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - AV_INPUT_BUFFER_PADDING_SIZE);
1026 memcpy(buf_padded, buf, buf_padded_size);
1028 init_get_bits(&gb, buf_padded, buf_padded_size * 8);
1030 if (sl->use_au_start)
1031 au_start_flag = get_bits1(&gb);
1033 au_end_flag = get_bits1(&gb);
1034 if (!sl->use_au_start && !sl->use_au_end)
1035 au_start_flag = au_end_flag = 1;
1036 if (sl->ocr_len > 0)
1037 ocr_flag = get_bits1(&gb);
1039 idle_flag = get_bits1(&gb);
1040 if (sl->use_padding)
1041 padding_flag = get_bits1(&gb);
1043 padding_bits = get_bits(&gb, 3);
1045 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
1046 if (sl->packet_seq_num_len)
1047 skip_bits_long(&gb, sl->packet_seq_num_len);
1048 if (sl->degr_prior_len)
1050 skip_bits(&gb, sl->degr_prior_len);
1052 skip_bits_long(&gb, sl->ocr_len);
1053 if (au_start_flag) {
1054 if (sl->use_rand_acc_pt)
1056 if (sl->au_seq_num_len > 0)
1057 skip_bits_long(&gb, sl->au_seq_num_len);
1058 if (sl->use_timestamps) {
1059 dts_flag = get_bits1(&gb);
1060 cts_flag = get_bits1(&gb);
1063 if (sl->inst_bitrate_len)
1064 inst_bitrate_flag = get_bits1(&gb);
1066 dts = get_ts64(&gb, sl->timestamp_len);
1068 cts = get_ts64(&gb, sl->timestamp_len);
1070 skip_bits_long(&gb, sl->au_len);
1071 if (inst_bitrate_flag)
1072 skip_bits_long(&gb, sl->inst_bitrate_len);
1075 if (dts != AV_NOPTS_VALUE)
1077 if (cts != AV_NOPTS_VALUE)
1080 if (sl->timestamp_len && sl->timestamp_res)
1081 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
1083 return (get_bits_count(&gb) + 7) >> 3;
1086 /* return non zero if a packet could be constructed */
1087 static int mpegts_push_data(MpegTSFilter *filter,
1088 const uint8_t *buf, int buf_size, int is_start,
1091 PESContext *pes = filter->u.pes_filter.opaque;
1092 MpegTSContext *ts = pes->ts;
1100 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1101 ret = new_pes_packet(pes, ts->pkt);
1106 reset_pes_packet_state(pes);
1108 pes->state = MPEGTS_HEADER;
1109 pes->ts_packet_pos = pos;
1112 while (buf_size > 0) {
1113 switch (pes->state) {
1115 len = PES_START_SIZE - pes->data_index;
1118 memcpy(pes->header + pes->data_index, p, len);
1119 pes->data_index += len;
1122 if (pes->data_index == PES_START_SIZE) {
1123 /* we got all the PES or section header. We can now
1125 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
1126 pes->header[2] == 0x01) {
1127 /* it must be an MPEG-2 PES stream */
1128 code = pes->header[3] | 0x100;
1129 av_log(pes->stream, AV_LOG_TRACE, "pid=%x pes_code=%#x\n", pes->pid,
1131 pes->stream_id = pes->header[3];
1133 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
1135 pes->sub_st->discard == AVDISCARD_ALL)) ||
1136 code == 0x1be) /* padding_stream */
1139 /* stream not present in PMT */
1141 if (ts->skip_changes)
1143 if (ts->merge_pmt_versions)
1144 goto skip; /* wait for PMT to merge new stream */
1146 pes->st = avformat_new_stream(ts->stream, NULL);
1148 return AVERROR(ENOMEM);
1149 pes->st->id = pes->pid;
1150 mpegts_set_stream_info(pes->st, pes, 0, 0);
1153 pes->total_size = AV_RB16(pes->header + 4);
1154 /* NOTE: a zero total size means the PES size is
1156 if (!pes->total_size)
1157 pes->total_size = MAX_PES_PAYLOAD;
1159 /* allocate pes buffer */
1160 pes->buffer = av_buffer_alloc(pes->total_size +
1161 AV_INPUT_BUFFER_PADDING_SIZE);
1163 return AVERROR(ENOMEM);
1165 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
1166 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
1167 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
1168 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
1169 pes->state = MPEGTS_PESHEADER;
1170 if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
1171 av_log(pes->stream, AV_LOG_TRACE,
1172 "pid=%x stream_type=%x probing\n",
1175 pes->st->request_probe = 1;
1178 pes->pes_header_size = 6;
1179 pes->state = MPEGTS_PAYLOAD;
1180 pes->data_index = 0;
1183 /* otherwise, it should be a table */
1186 pes->state = MPEGTS_SKIP;
1191 /**********************************************/
1192 /* PES packing parsing */
1193 case MPEGTS_PESHEADER:
1194 len = PES_HEADER_SIZE - pes->data_index;
1196 return AVERROR_INVALIDDATA;
1199 memcpy(pes->header + pes->data_index, p, len);
1200 pes->data_index += len;
1203 if (pes->data_index == PES_HEADER_SIZE) {
1204 pes->pes_header_size = pes->header[8] + 9;
1205 pes->state = MPEGTS_PESHEADER_FILL;
1208 case MPEGTS_PESHEADER_FILL:
1209 len = pes->pes_header_size - pes->data_index;
1211 return AVERROR_INVALIDDATA;
1214 memcpy(pes->header + pes->data_index, p, len);
1215 pes->data_index += len;
1218 if (pes->data_index == pes->pes_header_size) {
1220 unsigned int flags, pes_ext, skip;
1222 flags = pes->header[7];
1223 r = pes->header + 9;
1224 pes->pts = AV_NOPTS_VALUE;
1225 pes->dts = AV_NOPTS_VALUE;
1226 if ((flags & 0xc0) == 0x80) {
1227 pes->dts = pes->pts = ff_parse_pes_pts(r);
1229 } else if ((flags & 0xc0) == 0xc0) {
1230 pes->pts = ff_parse_pes_pts(r);
1232 pes->dts = ff_parse_pes_pts(r);
1235 pes->extended_stream_id = -1;
1236 if (flags & 0x01) { /* PES extension */
1238 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1239 skip = (pes_ext >> 4) & 0xb;
1242 if ((pes_ext & 0x41) == 0x01 &&
1243 (r + 2) <= (pes->header + pes->pes_header_size)) {
1244 /* PES extension 2 */
1245 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1246 pes->extended_stream_id = r[1];
1250 /* we got the full header. We parse it and get the payload */
1251 pes->state = MPEGTS_PAYLOAD;
1252 pes->data_index = 0;
1253 if (pes->stream_type == 0x12 && buf_size > 0) {
1254 int sl_header_bytes = read_sl_header(pes, &pes->sl, p,
1256 pes->pes_header_size += sl_header_bytes;
1257 p += sl_header_bytes;
1258 buf_size -= sl_header_bytes;
1260 if (pes->stream_type == 0x15 && buf_size >= 5) {
1261 /* skip metadata access unit header */
1262 pes->pes_header_size += 5;
1266 if ( pes->ts->fix_teletext_pts
1267 && ( pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT
1268 || pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1270 AVProgram *p = NULL;
1272 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1273 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1274 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1276 AVStream *st = NULL;
1277 if (f->type == MPEGTS_PES) {
1278 PESContext *pcrpes = f->u.pes_filter.opaque;
1281 } else if (f->type == MPEGTS_PCR) {
1283 for (i = 0; i < p->nb_stream_indexes; i++) {
1284 AVStream *pst = pes->stream->streams[p->stream_index[i]];
1285 if (pst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1289 if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) {
1290 // teletext packets do not always have correct timestamps,
1291 // the standard says they should be handled after 40.6 ms at most,
1292 // and the pcr error to this packet should be no more than 100 ms.
1293 // TODO: we should interpolate the PCR, not just use the last one
1294 int64_t pcr = f->last_pcr / 300;
1296 pes->st->pts_wrap_reference = st->pts_wrap_reference;
1297 pes->st->pts_wrap_behavior = st->pts_wrap_behavior;
1298 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1299 pes->pts = pes->dts = pcr;
1300 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_TELETEXT &&
1301 pes->dts > pcr + 3654 + 9000) {
1302 pes->pts = pes->dts = pcr + 3654 + 9000;
1303 } else if (pes->st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1304 pes->dts > pcr + 10*90000) { //10sec
1305 pes->pts = pes->dts = pcr + 3654 + 9000;
1314 av_log(pes->stream, AV_LOG_VERBOSE,
1315 "Forcing DTS/PTS to be unset for a "
1316 "non-trustworthy PES packet for PID %d as "
1317 "PCR hasn't been received yet.\n",
1319 pes->dts = pes->pts = AV_NOPTS_VALUE;
1324 case MPEGTS_PAYLOAD:
1326 if (pes->data_index > 0 &&
1327 pes->data_index + buf_size > pes->total_size) {
1328 ret = new_pes_packet(pes, ts->pkt);
1331 pes->total_size = MAX_PES_PAYLOAD;
1332 pes->buffer = av_buffer_alloc(pes->total_size +
1333 AV_INPUT_BUFFER_PADDING_SIZE);
1335 return AVERROR(ENOMEM);
1337 } else if (pes->data_index == 0 &&
1338 buf_size > pes->total_size) {
1339 // pes packet size is < ts size packet and pes data is padded with 0xff
1340 // not sure if this is legal in ts but see issue #2392
1341 buf_size = pes->total_size;
1343 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1344 pes->data_index += buf_size;
1345 /* emit complete packets with known packet size
1346 * decreases demuxer delay for infrequent packets like subtitles from
1347 * a couple of seconds to milliseconds for properly muxed files.
1348 * total_size is the number of bytes following pes_packet_length
1349 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1350 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1351 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1353 ret = new_pes_packet(pes, ts->pkt);
1369 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1374 /* if no pid found, then add a pid context */
1375 pes = av_mallocz(sizeof(PESContext));
1379 pes->stream = ts->stream;
1381 pes->pcr_pid = pcr_pid;
1382 pes->state = MPEGTS_SKIP;
1383 pes->pts = AV_NOPTS_VALUE;
1384 pes->dts = AV_NOPTS_VALUE;
1385 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1394 typedef struct MP4DescrParseContext {
1398 Mp4Descr *active_descr;
1400 int max_descr_count;
1402 int predefined_SLConfigDescriptor_seen;
1403 } MP4DescrParseContext;
1405 static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s,
1406 const uint8_t *buf, unsigned size,
1407 Mp4Descr *descr, int max_descr_count)
1410 if (size > (1 << 30))
1411 return AVERROR_INVALIDDATA;
1413 if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0,
1414 NULL, NULL, NULL, NULL)) < 0)
1421 d->active_descr = NULL;
1422 d->max_descr_count = max_descr_count;
1427 static void update_offsets(AVIOContext *pb, int64_t *off, int *len)
1429 int64_t new_off = avio_tell(pb);
1430 (*len) -= new_off - *off;
1434 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1437 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1440 int ret = parse_mp4_descr(d, off, len, 0);
1443 update_offsets(&d->pb, &off, &len);
1448 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1450 avio_rb16(&d->pb); // ID
1456 update_offsets(&d->pb, &off, &len);
1457 return parse_mp4_descr_arr(d, off, len);
1460 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1465 id_flags = avio_rb16(&d->pb);
1466 if (!(id_flags & 0x0020)) { // URL_Flag
1467 update_offsets(&d->pb, &off, &len);
1468 return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[]
1474 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1479 if (d->descr_count >= d->max_descr_count)
1480 return AVERROR_INVALIDDATA;
1481 ff_mp4_parse_es_descr(&d->pb, &es_id);
1482 d->active_descr = d->descr + (d->descr_count++);
1484 d->active_descr->es_id = es_id;
1485 update_offsets(&d->pb, &off, &len);
1486 if ((ret = parse_mp4_descr(d, off, len, MP4DecConfigDescrTag)) < 0)
1488 update_offsets(&d->pb, &off, &len);
1490 ret = parse_mp4_descr(d, off, len, MP4SLDescrTag);
1491 d->active_descr = NULL;
1495 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off,
1498 Mp4Descr *descr = d->active_descr;
1500 return AVERROR_INVALIDDATA;
1501 d->active_descr->dec_config_descr = av_malloc(len);
1502 if (!descr->dec_config_descr)
1503 return AVERROR(ENOMEM);
1504 descr->dec_config_descr_len = len;
1505 avio_read(&d->pb, descr->dec_config_descr, len);
1509 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1511 Mp4Descr *descr = d->active_descr;
1514 return AVERROR_INVALIDDATA;
1516 #define R8_CHECK_CLIP_MAX(dst, maxv) do { \
1517 descr->sl.dst = avio_r8(&d->pb); \
1518 if (descr->sl.dst > maxv) { \
1519 descr->sl.dst = maxv; \
1520 return AVERROR_INVALIDDATA; \
1524 predefined = avio_r8(&d->pb);
1527 int flags = avio_r8(&d->pb);
1528 descr->sl.use_au_start = !!(flags & 0x80);
1529 descr->sl.use_au_end = !!(flags & 0x40);
1530 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1531 descr->sl.use_padding = !!(flags & 0x08);
1532 descr->sl.use_timestamps = !!(flags & 0x04);
1533 descr->sl.use_idle = !!(flags & 0x02);
1534 descr->sl.timestamp_res = avio_rb32(&d->pb);
1536 R8_CHECK_CLIP_MAX(timestamp_len, 63);
1537 R8_CHECK_CLIP_MAX(ocr_len, 63);
1538 R8_CHECK_CLIP_MAX(au_len, 31);
1539 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1540 lengths = avio_rb16(&d->pb);
1541 descr->sl.degr_prior_len = lengths >> 12;
1542 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1543 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1544 } else if (!d->predefined_SLConfigDescriptor_seen){
1545 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1546 d->predefined_SLConfigDescriptor_seen = 1;
1551 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1555 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1558 update_offsets(&d->pb, &off, &len);
1559 if (len < 0 || len1 > len || len1 <= 0) {
1560 av_log(d->s, AV_LOG_ERROR,
1561 "Tag %x length violation new length %d bytes remaining %d\n",
1563 return AVERROR_INVALIDDATA;
1566 if (d->level++ >= MAX_LEVEL) {
1567 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1568 ret = AVERROR_INVALIDDATA;
1572 if (target_tag && tag != target_tag) {
1573 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag,
1575 ret = AVERROR_INVALIDDATA;
1581 ret = parse_MP4IODescrTag(d, off, len1);
1584 ret = parse_MP4ODescrTag(d, off, len1);
1587 ret = parse_MP4ESDescrTag(d, off, len1);
1589 case MP4DecConfigDescrTag:
1590 ret = parse_MP4DecConfigDescrTag(d, off, len1);
1593 ret = parse_MP4SLDescrTag(d, off, len1);
1600 avio_seek(&d->pb, off + len1, SEEK_SET);
1604 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1605 Mp4Descr *descr, int *descr_count, int max_descr_count)
1607 MP4DescrParseContext d;
1610 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1614 ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1616 *descr_count = d.descr_count;
1620 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1621 Mp4Descr *descr, int *descr_count, int max_descr_count)
1623 MP4DescrParseContext d;
1626 ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count);
1630 ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1632 *descr_count = d.descr_count;
1636 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,
1639 MpegTSContext *ts = filter->u.section_filter.opaque;
1640 MpegTSSectionFilter *tssf = &filter->u.section_filter;
1642 const uint8_t *p, *p_end;
1644 int mp4_descr_count = 0;
1645 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
1647 AVFormatContext *s = ts->stream;
1649 p_end = section + section_len - 4;
1651 if (parse_section_header(&h, &p, p_end) < 0)
1653 if (h.tid != M4OD_TID)
1655 if (skip_identical(&h, tssf))
1658 mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,
1659 MAX_MP4_DESCR_COUNT);
1661 for (pid = 0; pid < NB_PID_MAX; pid++) {
1664 for (i = 0; i < mp4_descr_count; i++) {
1667 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1669 if (ts->pids[pid]->type != MPEGTS_PES) {
1670 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1673 pes = ts->pids[pid]->u.pes_filter.opaque;
1678 pes->sl = mp4_descr[i].sl;
1680 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1681 mp4_descr[i].dec_config_descr_len, 0,
1682 NULL, NULL, NULL, NULL);
1683 ff_mp4_read_dec_config_descr(s, st, &pb);
1684 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1685 st->codecpar->extradata_size > 0)
1686 st->need_parsing = 0;
1687 if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
1688 st->codecpar->extradata_size > 0)
1689 st->need_parsing = 0;
1691 st->codecpar->codec_type = avcodec_get_type(st->codecpar->codec_id);
1692 st->internal->need_context_update = 1;
1695 for (i = 0; i < mp4_descr_count; i++)
1696 av_free(mp4_descr[i].dec_config_descr);
1699 static void scte_data_cb(MpegTSFilter *filter, const uint8_t *section,
1702 AVProgram *prg = NULL;
1703 MpegTSContext *ts = filter->u.section_filter.opaque;
1705 int idx = ff_find_stream_index(ts->stream, filter->pid);
1709 new_data_packet(section, section_len, ts->pkt);
1710 ts->pkt->stream_index = idx;
1711 prg = av_find_program_from_stream(ts->stream, NULL, idx);
1712 if (prg && prg->pcr_pid != -1 && prg->discard != AVDISCARD_ALL) {
1713 MpegTSFilter *f = ts->pids[prg->pcr_pid];
1714 if (f && f->last_pcr != -1)
1715 ts->pkt->pts = ts->pkt->dts = f->last_pcr/300;
1721 static const uint8_t opus_coupled_stream_cnt[9] = {
1722 1, 0, 1, 1, 2, 2, 2, 3, 3
1725 static const uint8_t opus_stream_cnt[9] = {
1726 1, 1, 1, 2, 2, 3, 4, 4, 5,
1729 static const uint8_t opus_channel_map[8][8] = {
1737 { 0,6,1,2,3,4,5,7 },
1740 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1741 const uint8_t **pp, const uint8_t *desc_list_end,
1742 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1745 const uint8_t *desc_end;
1746 int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code;
1750 desc_tag = get8(pp, desc_list_end);
1752 return AVERROR_INVALIDDATA;
1753 desc_len = get8(pp, desc_list_end);
1755 return AVERROR_INVALIDDATA;
1756 desc_end = *pp + desc_len;
1757 if (desc_end > desc_list_end)
1758 return AVERROR_INVALIDDATA;
1760 av_log(fc, AV_LOG_TRACE, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1762 if ((st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) &&
1763 stream_type == STREAM_TYPE_PRIVATE_DATA)
1764 mpegts_find_stream_type(st, desc_tag, DESC_types);
1767 case 0x02: /* video stream descriptor */
1768 if (get8(pp, desc_end) & 0x1) {
1769 st->disposition |= AV_DISPOSITION_STILL_IMAGE;
1772 case 0x1E: /* SL descriptor */
1773 desc_es_id = get16(pp, desc_end);
1776 if (ts && ts->pids[pid])
1777 ts->pids[pid]->es_id = desc_es_id;
1778 for (i = 0; i < mp4_descr_count; i++)
1779 if (mp4_descr[i].dec_config_descr_len &&
1780 mp4_descr[i].es_id == desc_es_id) {
1782 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1783 mp4_descr[i].dec_config_descr_len, 0,
1784 NULL, NULL, NULL, NULL);
1785 ff_mp4_read_dec_config_descr(fc, st, &pb);
1786 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1787 st->codecpar->extradata_size > 0) {
1788 st->need_parsing = 0;
1789 st->internal->need_context_update = 1;
1791 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1792 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1795 case 0x1F: /* FMC descriptor */
1796 if (get16(pp, desc_end) < 0)
1798 if (mp4_descr_count > 0 &&
1799 (st->codecpar->codec_id == AV_CODEC_ID_AAC_LATM ||
1800 (st->request_probe == 0 && st->codecpar->codec_id == AV_CODEC_ID_NONE) ||
1801 st->request_probe > 0) &&
1802 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1804 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1805 mp4_descr->dec_config_descr_len, 0,
1806 NULL, NULL, NULL, NULL);
1807 ff_mp4_read_dec_config_descr(fc, st, &pb);
1808 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
1809 st->codecpar->extradata_size > 0) {
1810 st->request_probe = st->need_parsing = 0;
1811 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1812 st->internal->need_context_update = 1;
1816 case 0x56: /* DVB teletext descriptor */
1818 uint8_t *extradata = NULL;
1819 int language_count = desc_len / 5;
1821 if (desc_len > 0 && desc_len % 5 != 0)
1822 return AVERROR_INVALIDDATA;
1824 if (language_count > 0) {
1825 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1826 av_assert0(language_count <= sizeof(language) / 4);
1828 if (st->codecpar->extradata == NULL) {
1829 if (ff_alloc_extradata(st->codecpar, language_count * 2)) {
1830 return AVERROR(ENOMEM);
1834 if (st->codecpar->extradata_size < language_count * 2)
1835 return AVERROR_INVALIDDATA;
1837 extradata = st->codecpar->extradata;
1839 for (i = 0; i < language_count; i++) {
1840 language[i * 4 + 0] = get8(pp, desc_end);
1841 language[i * 4 + 1] = get8(pp, desc_end);
1842 language[i * 4 + 2] = get8(pp, desc_end);
1843 language[i * 4 + 3] = ',';
1845 memcpy(extradata, *pp, 2);
1851 language[i * 4 - 1] = 0;
1852 av_dict_set(&st->metadata, "language", language, 0);
1853 st->internal->need_context_update = 1;
1857 case 0x59: /* subtitling descriptor */
1859 /* 8 bytes per DVB subtitle substream data:
1860 * ISO_639_language_code (3 bytes),
1861 * subtitling_type (1 byte),
1862 * composition_page_id (2 bytes),
1863 * ancillary_page_id (2 bytes) */
1864 int language_count = desc_len / 8;
1866 if (desc_len > 0 && desc_len % 8 != 0)
1867 return AVERROR_INVALIDDATA;
1869 if (language_count > 1) {
1870 avpriv_request_sample(fc, "DVB subtitles with multiple languages");
1873 if (language_count > 0) {
1876 /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */
1877 av_assert0(language_count <= sizeof(language) / 4);
1879 if (st->codecpar->extradata == NULL) {
1880 if (ff_alloc_extradata(st->codecpar, language_count * 5)) {
1881 return AVERROR(ENOMEM);
1885 if (st->codecpar->extradata_size < language_count * 5)
1886 return AVERROR_INVALIDDATA;
1888 extradata = st->codecpar->extradata;
1890 for (i = 0; i < language_count; i++) {
1891 language[i * 4 + 0] = get8(pp, desc_end);
1892 language[i * 4 + 1] = get8(pp, desc_end);
1893 language[i * 4 + 2] = get8(pp, desc_end);
1894 language[i * 4 + 3] = ',';
1896 /* hearing impaired subtitles detection using subtitling_type */
1898 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1899 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1900 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1901 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1902 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1903 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1904 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1908 extradata[4] = get8(pp, desc_end); /* subtitling_type */
1909 memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */
1915 language[i * 4 - 1] = 0;
1916 av_dict_set(&st->metadata, "language", language, 0);
1917 st->internal->need_context_update = 1;
1921 case 0x0a: /* ISO 639 language descriptor */
1922 for (i = 0; i + 4 <= desc_len; i += 4) {
1923 language[i + 0] = get8(pp, desc_end);
1924 language[i + 1] = get8(pp, desc_end);
1925 language[i + 2] = get8(pp, desc_end);
1926 language[i + 3] = ',';
1927 switch (get8(pp, desc_end)) {
1929 st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS;
1932 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1935 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
1936 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
1940 if (i && language[0]) {
1941 language[i - 1] = 0;
1942 /* don't overwrite language, as it may already have been set by
1943 * another, more specific descriptor (e.g. supplementary audio) */
1944 av_dict_set(&st->metadata, "language", language, AV_DICT_DONT_OVERWRITE);
1947 case 0x05: /* registration descriptor */
1948 st->codecpar->codec_tag = bytestream_get_le32(pp);
1949 av_log(fc, AV_LOG_TRACE, "reg_desc=%.4s\n", (char *)&st->codecpar->codec_tag);
1950 if (st->codecpar->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) {
1951 mpegts_find_stream_type(st, st->codecpar->codec_tag, REGD_types);
1952 if (st->codecpar->codec_tag == MKTAG('B', 'S', 'S', 'D'))
1953 st->request_probe = 50;
1956 case 0x52: /* stream identifier descriptor */
1957 st->stream_identifier = 1 + get8(pp, desc_end);
1959 case 0x26: /* metadata descriptor */
1960 if (get16(pp, desc_end) == 0xFFFF)
1962 if (get8(pp, desc_end) == 0xFF) {
1963 st->codecpar->codec_tag = bytestream_get_le32(pp);
1964 if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
1965 mpegts_find_stream_type(st, st->codecpar->codec_tag, METADATA_types);
1968 case 0x7f: /* DVB extension descriptor */
1969 ext_desc_tag = get8(pp, desc_end);
1970 if (ext_desc_tag < 0)
1971 return AVERROR_INVALIDDATA;
1972 if (st->codecpar->codec_id == AV_CODEC_ID_OPUS &&
1973 ext_desc_tag == 0x80) { /* User defined (provisional Opus) */
1974 if (!st->codecpar->extradata) {
1975 st->codecpar->extradata = av_mallocz(sizeof(opus_default_extradata) +
1976 AV_INPUT_BUFFER_PADDING_SIZE);
1977 if (!st->codecpar->extradata)
1978 return AVERROR(ENOMEM);
1980 st->codecpar->extradata_size = sizeof(opus_default_extradata);
1981 memcpy(st->codecpar->extradata, opus_default_extradata, sizeof(opus_default_extradata));
1983 channel_config_code = get8(pp, desc_end);
1984 if (channel_config_code < 0)
1985 return AVERROR_INVALIDDATA;
1986 if (channel_config_code <= 0x8) {
1987 st->codecpar->extradata[9] = channels = channel_config_code ? channel_config_code : 2;
1988 st->codecpar->extradata[18] = channel_config_code ? (channels > 2) : /* Dual Mono */ 255;
1989 st->codecpar->extradata[19] = opus_stream_cnt[channel_config_code];
1990 st->codecpar->extradata[20] = opus_coupled_stream_cnt[channel_config_code];
1991 memcpy(&st->codecpar->extradata[21], opus_channel_map[channels - 1], channels);
1993 avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8");
1995 st->need_parsing = AVSTREAM_PARSE_FULL;
1996 st->internal->need_context_update = 1;
1999 if (ext_desc_tag == 0x06) { /* supplementary audio descriptor */
2003 return AVERROR_INVALIDDATA;
2004 flags = get8(pp, desc_end);
2006 if ((flags & 0x80) == 0) /* mix_type */
2007 st->disposition |= AV_DISPOSITION_DEPENDENT;
2009 switch ((flags >> 2) & 0x1F) { /* editorial_classification */
2011 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2012 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2015 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
2018 st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
2022 if (flags & 0x01) { /* language_code_present */
2024 return AVERROR_INVALIDDATA;
2025 language[0] = get8(pp, desc_end);
2026 language[1] = get8(pp, desc_end);
2027 language[2] = get8(pp, desc_end);
2030 /* This language always has to override a possible
2031 * ISO 639 language descriptor language */
2033 av_dict_set(&st->metadata, "language", language, 0);
2037 case 0x6a: /* ac-3_descriptor */
2039 int component_type_flag = get8(pp, desc_end) & (1 << 7);
2040 if (component_type_flag) {
2041 int component_type = get8(pp, desc_end);
2042 int service_type_mask = 0x38; // 0b00111000
2043 int service_type = ((component_type & service_type_mask) >> 3);
2044 if (service_type == 0x02 /* 0b010 */) {
2045 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2046 av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2051 case 0x7a: /* enhanced_ac-3_descriptor */
2053 int component_type_flag = get8(pp, desc_end) & (1 << 7);
2054 if (component_type_flag) {
2055 int component_type = get8(pp, desc_end);
2056 int service_type_mask = 0x38; // 0b00111000
2057 int service_type = ((component_type & service_type_mask) >> 3);
2058 if (service_type == 0x02 /* 0b010 */) {
2059 st->disposition |= AV_DISPOSITION_DESCRIPTIONS;
2060 av_log(ts ? ts->stream : fc, AV_LOG_DEBUG, "New track disposition for id %u: %u\n", st->id, st->disposition);
2065 case 0xfd: /* ARIB data coding type descriptor */
2066 // STD-B24, fascicle 3, chapter 4 defines private_stream_1
2068 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
2069 // This structure is defined in STD-B10, part 1, listing 5.4 and
2071 // Listing of data_component_ids is in STD-B10, part 2, Annex J.
2072 // Component tag limits are documented in TR-B14, fascicle 2,
2073 // Vol. 3, Section 2, 4.2.8.1
2074 int actual_component_tag = st->stream_identifier - 1;
2075 int picked_profile = FF_PROFILE_UNKNOWN;
2076 int data_component_id = get16(pp, desc_end);
2077 if (data_component_id < 0)
2078 return AVERROR_INVALIDDATA;
2080 switch (data_component_id) {
2082 // [0x30..0x37] are component tags utilized for
2083 // non-mobile captioning service ("profile A").
2084 if (actual_component_tag >= 0x30 &&
2085 actual_component_tag <= 0x37) {
2086 picked_profile = FF_PROFILE_ARIB_PROFILE_A;
2090 // component tag 0x87 signifies a mobile/partial reception
2091 // (1seg) captioning service ("profile C").
2092 if (actual_component_tag == 0x87) {
2093 picked_profile = FF_PROFILE_ARIB_PROFILE_C;
2100 if (picked_profile == FF_PROFILE_UNKNOWN)
2103 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2104 st->codecpar->codec_id = AV_CODEC_ID_ARIB_CAPTION;
2105 st->codecpar->profile = picked_profile;
2106 st->request_probe = 0;
2116 static AVStream *find_matching_stream(MpegTSContext *ts, int pid,
2117 int stream_identifier, int pmt_stream_idx)
2119 AVFormatContext *s = ts->stream;
2121 AVStream *found = NULL;
2123 for (i = 0; i < s->nb_streams; i++) {
2124 AVStream *st = s->streams[i];
2125 if (stream_identifier != -1) { /* match based on "stream identifier descriptor" if present */
2126 if (st->stream_identifier == stream_identifier+1) {
2130 } else if (st->pmt_stream_idx == pmt_stream_idx) { /* match based on position within the PMT */
2137 av_log(ts->stream, AV_LOG_VERBOSE,
2138 "re-using existing %s stream %d (pid=0x%x) for new pid=0x%x\n",
2139 av_get_media_type_string(found->codecpar->codec_type),
2146 static int parse_stream_identifier_desc(const uint8_t *p, const uint8_t *p_end)
2148 const uint8_t **pp = &p;
2149 const uint8_t *desc_list_end;
2150 const uint8_t *desc_end;
2152 int desc_len, desc_tag;
2154 desc_list_len = get16(pp, p_end);
2155 if (desc_list_len < 0)
2157 desc_list_len &= 0xfff;
2158 desc_list_end = p + desc_list_len;
2159 if (desc_list_end > p_end)
2163 desc_tag = get8(pp, desc_list_end);
2166 desc_len = get8(pp, desc_list_end);
2169 desc_end = *pp + desc_len;
2170 if (desc_end > desc_list_end)
2173 if (desc_tag == 0x52) {
2174 return get8(pp, desc_end);
2182 static int is_pes_stream(int stream_type, uint32_t prog_reg_desc)
2184 return !(stream_type == 0x13 ||
2185 (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) );
2188 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2190 MpegTSContext *ts = filter->u.section_filter.opaque;
2191 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2192 SectionHeader h1, *h = &h1;
2195 const uint8_t *p, *p_end, *desc_list_end;
2196 int program_info_length, pcr_pid, pid, stream_type;
2198 uint32_t prog_reg_desc = 0; /* registration descriptor */
2199 int stream_identifier = -1;
2201 int mp4_descr_count = 0;
2202 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };
2205 av_log(ts->stream, AV_LOG_TRACE, "PMT: len %i\n", section_len);
2206 hex_dump_debug(ts->stream, section, section_len);
2208 p_end = section + section_len - 4;
2210 if (parse_section_header(h, &p, p_end) < 0)
2212 if (h->tid != PMT_TID)
2214 if (skip_identical(h, tssf))
2217 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x sec_num=%d/%d version=%d tid=%d\n",
2218 h->id, h->sec_num, h->last_sec_num, h->version, h->tid);
2220 if (!ts->scan_all_pmts && ts->skip_changes)
2223 if (ts->skip_unknown_pmt && !get_program(ts, h->id))
2225 if (!ts->skip_clear)
2226 clear_program(ts, h->id);
2228 pcr_pid = get16(&p, p_end);
2232 add_pid_to_pmt(ts, h->id, pcr_pid);
2233 update_av_program_info(ts->stream, h->id, pcr_pid, h->version);
2235 av_log(ts->stream, AV_LOG_TRACE, "pcr_pid=0x%x\n", pcr_pid);
2237 program_info_length = get16(&p, p_end);
2238 if (program_info_length < 0)
2240 program_info_length &= 0xfff;
2241 while (program_info_length >= 2) {
2243 tag = get8(&p, p_end);
2244 len = get8(&p, p_end);
2246 av_log(ts->stream, AV_LOG_TRACE, "program tag: 0x%02x len=%d\n", tag, len);
2248 if (len > program_info_length - 2)
2249 // something else is broken, exit the program_descriptors_loop
2251 program_info_length -= len + 2;
2252 if (tag == 0x1d) { // IOD descriptor
2253 get8(&p, p_end); // scope
2254 get8(&p, p_end); // label
2256 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
2257 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
2258 } else if (tag == 0x05 && len >= 4) { // registration descriptor
2259 prog_reg_desc = bytestream_get_le32(&p);
2264 p += program_info_length;
2268 // stop parsing after pmt, we found header
2269 if (!ts->stream->nb_streams)
2272 set_pmt_found(ts, h->id);
2275 for (i = 0; ; i++) {
2278 stream_type = get8(&p, p_end);
2279 if (stream_type < 0)
2281 pid = get16(&p, p_end);
2285 if (pid == ts->current_pid)
2288 if (ts->merge_pmt_versions)
2289 stream_identifier = parse_stream_identifier_desc(p, p_end);
2291 /* now create stream */
2292 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
2293 pes = ts->pids[pid]->u.pes_filter.opaque;
2294 if (ts->merge_pmt_versions && !pes->st) {
2295 st = find_matching_stream(ts, pid, stream_identifier, i);
2298 pes->stream_type = stream_type;
2303 pes->st = avformat_new_stream(pes->stream, NULL);
2306 pes->st->id = pes->pid;
2307 pes->st->program_num = h->id;
2308 pes->st->pmt_version = h->version;
2309 pes->st->pmt_stream_idx = i;
2312 } else if (is_pes_stream(stream_type, prog_reg_desc)) {
2314 mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably
2315 pes = add_pes_stream(ts, pid, pcr_pid);
2316 if (ts->merge_pmt_versions && pes && !pes->st) {
2317 st = find_matching_stream(ts, pid, stream_identifier, i);
2320 pes->stream_type = stream_type;
2324 if (pes && !pes->st) {
2325 st = avformat_new_stream(pes->stream, NULL);
2329 st->program_num = h->id;
2330 st->pmt_version = h->version;
2331 st->pmt_stream_idx = i;
2334 int idx = ff_find_stream_index(ts->stream, pid);
2336 st = ts->stream->streams[idx];
2338 if (ts->merge_pmt_versions && !st) {
2339 st = find_matching_stream(ts, pid, stream_identifier, i);
2342 st = avformat_new_stream(ts->stream, NULL);
2346 st->program_num = h->id;
2347 st->pmt_version = h->version;
2348 st->pmt_stream_idx = i;
2349 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2350 if (stream_type == 0x86 && prog_reg_desc == AV_RL32("CUEI")) {
2351 mpegts_find_stream_type(st, stream_type, SCTE_types);
2352 mpegts_open_section_filter(ts, pid, scte_data_cb, ts, 1);
2360 if (pes && !pes->stream_type)
2361 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
2363 add_pid_to_pmt(ts, h->id, pid);
2365 av_program_add_stream_index(ts->stream, h->id, st->index);
2367 desc_list_len = get16(&p, p_end);
2368 if (desc_list_len < 0)
2370 desc_list_len &= 0xfff;
2371 desc_list_end = p + desc_list_len;
2372 if (desc_list_end > p_end)
2375 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
2376 desc_list_end, mp4_descr,
2377 mp4_descr_count, pid, ts) < 0)
2380 if (pes && prog_reg_desc == AV_RL32("HDMV") &&
2381 stream_type == 0x83 && pes->sub_st) {
2382 av_program_add_stream_index(ts->stream, h->id,
2383 pes->sub_st->index);
2384 pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
2390 if (!ts->pids[pcr_pid])
2391 mpegts_open_pcr_filter(ts, pcr_pid);
2394 for (i = 0; i < mp4_descr_count; i++)
2395 av_free(mp4_descr[i].dec_config_descr);
2398 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2400 MpegTSContext *ts = filter->u.section_filter.opaque;
2401 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2402 SectionHeader h1, *h = &h1;
2403 const uint8_t *p, *p_end;
2407 av_log(ts->stream, AV_LOG_TRACE, "PAT:\n");
2408 hex_dump_debug(ts->stream, section, section_len);
2410 p_end = section + section_len - 4;
2412 if (parse_section_header(h, &p, p_end) < 0)
2414 if (h->tid != PAT_TID)
2416 if (ts->skip_changes)
2419 if (skip_identical(h, tssf))
2421 ts->stream->ts_id = h->id;
2425 sid = get16(&p, p_end);
2428 pmt_pid = get16(&p, p_end);
2433 if (pmt_pid == ts->current_pid)
2436 av_log(ts->stream, AV_LOG_TRACE, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
2438 if (sid == 0x0000) {
2441 MpegTSFilter *fil = ts->pids[pmt_pid];
2442 program = av_new_program(ts->stream, sid);
2444 program->program_num = sid;
2445 program->pmt_pid = pmt_pid;
2448 if ( fil->type != MPEGTS_SECTION
2449 || fil->pid != pmt_pid
2450 || fil->u.section_filter.section_cb != pmt_cb)
2451 mpegts_close_filter(ts, ts->pids[pmt_pid]);
2453 if (!ts->pids[pmt_pid])
2454 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
2455 add_pat_entry(ts, sid);
2456 add_pid_to_pmt(ts, sid, 0); // add pat pid to program
2457 add_pid_to_pmt(ts, sid, pmt_pid);
2463 for (j=0; j<ts->stream->nb_programs; j++) {
2464 for (i = 0; i < ts->nb_prg; i++)
2465 if (ts->prg[i].id == ts->stream->programs[j]->id)
2467 if (i==ts->nb_prg && !ts->skip_clear)
2468 clear_avprogram(ts, ts->stream->programs[j]->id);
2473 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
2475 MpegTSContext *ts = filter->u.section_filter.opaque;
2476 MpegTSSectionFilter *tssf = &filter->u.section_filter;
2477 SectionHeader h1, *h = &h1;
2478 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
2479 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
2480 char *name, *provider_name;
2482 av_log(ts->stream, AV_LOG_TRACE, "SDT:\n");
2483 hex_dump_debug(ts->stream, section, section_len);
2485 p_end = section + section_len - 4;
2487 if (parse_section_header(h, &p, p_end) < 0)
2489 if (h->tid != SDT_TID)
2491 if (ts->skip_changes)
2493 if (skip_identical(h, tssf))
2496 onid = get16(&p, p_end);
2499 val = get8(&p, p_end);
2503 sid = get16(&p, p_end);
2506 val = get8(&p, p_end);
2509 desc_list_len = get16(&p, p_end);
2510 if (desc_list_len < 0)
2512 desc_list_len &= 0xfff;
2513 desc_list_end = p + desc_list_len;
2514 if (desc_list_end > p_end)
2517 desc_tag = get8(&p, desc_list_end);
2520 desc_len = get8(&p, desc_list_end);
2521 desc_end = p + desc_len;
2522 if (desc_len < 0 || desc_end > desc_list_end)
2525 av_log(ts->stream, AV_LOG_TRACE, "tag: 0x%02x len=%d\n",
2526 desc_tag, desc_len);
2530 service_type = get8(&p, p_end);
2531 if (service_type < 0)
2533 provider_name = getstr8(&p, p_end);
2536 name = getstr8(&p, p_end);
2538 AVProgram *program = av_new_program(ts->stream, sid);
2540 av_dict_set(&program->metadata, "service_name", name, 0);
2541 av_dict_set(&program->metadata, "service_provider",
2546 av_free(provider_name);
2557 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2558 const uint8_t *packet);
2560 /* handle one TS packet */
2561 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
2564 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
2565 has_adaptation, has_payload;
2566 const uint8_t *p, *p_end;
2569 pid = AV_RB16(packet + 1) & 0x1fff;
2570 is_start = packet[1] & 0x40;
2571 tss = ts->pids[pid];
2572 if (ts->auto_guess && !tss && is_start) {
2573 add_pes_stream(ts, pid, -1);
2574 tss = ts->pids[pid];
2579 tss->discard = discard_pid(ts, pid);
2582 ts->current_pid = pid;
2584 afc = (packet[3] >> 4) & 3;
2585 if (afc == 0) /* reserved value */
2587 has_adaptation = afc & 2;
2588 has_payload = afc & 1;
2589 is_discontinuity = has_adaptation &&
2590 packet[4] != 0 && /* with length > 0 */
2591 (packet[5] & 0x80); /* and discontinuity indicated */
2593 /* continuity check (currently not used) */
2594 cc = (packet[3] & 0xf);
2595 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
2596 cc_ok = pid == 0x1FFF || // null packet PID
2603 av_log(ts->stream, AV_LOG_DEBUG,
2604 "Continuity check failed for pid %d expected %d got %d\n",
2605 pid, expected_cc, cc);
2606 if (tss->type == MPEGTS_PES) {
2607 PESContext *pc = tss->u.pes_filter.opaque;
2608 pc->flags |= AV_PKT_FLAG_CORRUPT;
2612 if (packet[1] & 0x80) {
2613 av_log(ts->stream, AV_LOG_DEBUG, "Packet had TEI flag set; marking as corrupt\n");
2614 if (tss->type == MPEGTS_PES) {
2615 PESContext *pc = tss->u.pes_filter.opaque;
2616 pc->flags |= AV_PKT_FLAG_CORRUPT;
2621 if (has_adaptation) {
2624 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
2625 tss->last_pcr = pcr_h * 300 + pcr_l;
2626 /* skip adaptation field */
2629 /* if past the end of packet, ignore */
2630 p_end = packet + TS_PACKET_SIZE;
2631 if (p >= p_end || !has_payload)
2634 pos = avio_tell(ts->stream->pb);
2636 av_assert0(pos >= TS_PACKET_SIZE);
2637 ts->pos47_full = pos - TS_PACKET_SIZE;
2640 if (tss->type == MPEGTS_SECTION) {
2642 /* pointer field present */
2644 if (len > p_end - p)
2647 /* write remaining section bytes */
2648 write_section_data(ts, tss,
2650 /* check whether filter has been closed */
2656 write_section_data(ts, tss,
2661 write_section_data(ts, tss,
2666 // stop find_stream_info from waiting for more streams
2667 // when all programs have received a PMT
2668 if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) {
2670 for (i = 0; i < ts->nb_prg; i++) {
2671 if (!ts->prg[i].pmt_found)
2674 if (i == ts->nb_prg && ts->nb_prg > 0) {
2676 for (i = 0; i < ts->stream->nb_streams; i++) {
2677 AVStream *st = ts->stream->streams[i];
2678 if (st->codecpar->codec_type >= 0)
2679 types |= 1<<st->codecpar->codec_type;
2681 if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) {
2682 av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
2683 ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
2690 // Note: The position here points actually behind the current packet.
2691 if (tss->type == MPEGTS_PES) {
2692 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
2693 pos - ts->raw_packet_size)) < 0)
2701 static void reanalyze(MpegTSContext *ts) {
2702 AVIOContext *pb = ts->stream->pb;
2703 int64_t pos = avio_tell(pb);
2706 pos -= ts->pos47_full;
2707 if (pos == TS_PACKET_SIZE) {
2708 ts->size_stat[0] ++;
2709 } else if (pos == TS_DVHS_PACKET_SIZE) {
2710 ts->size_stat[1] ++;
2711 } else if (pos == TS_FEC_PACKET_SIZE) {
2712 ts->size_stat[2] ++;
2715 ts->size_stat_count ++;
2716 if (ts->size_stat_count > SIZE_STAT_THRESHOLD) {
2718 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
2719 newsize = TS_PACKET_SIZE;
2720 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
2721 newsize = TS_DVHS_PACKET_SIZE;
2722 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
2723 newsize = TS_FEC_PACKET_SIZE;
2725 if (newsize && newsize != ts->raw_packet_size) {
2726 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
2727 ts->raw_packet_size = newsize;
2729 ts->size_stat_count = 0;
2730 memset(ts->size_stat, 0, sizeof(ts->size_stat));
2734 /* XXX: try to find a better synchro over several packets (use
2735 * get_packet_size() ?) */
2736 static int mpegts_resync(AVFormatContext *s, int seekback, const uint8_t *current_packet)
2738 MpegTSContext *ts = s->priv_data;
2739 AVIOContext *pb = s->pb;
2741 uint64_t pos = avio_tell(pb);
2743 avio_seek(pb, -FFMIN(seekback, pos), SEEK_CUR);
2745 //Special case for files like 01c56b0dc1.ts
2746 if (current_packet[0] == 0x80 && current_packet[12] == 0x47) {
2747 avio_seek(pb, 12, SEEK_CUR);
2751 for (i = 0; i < ts->resync_size; i++) {
2756 avio_seek(pb, -1, SEEK_CUR);
2757 reanalyze(s->priv_data);
2761 av_log(s, AV_LOG_ERROR,
2762 "max resync size reached, could not find sync byte\n");
2764 return AVERROR_INVALIDDATA;
2767 /* return AVERROR_something if error or EOF. Return 0 if OK. */
2768 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size,
2769 const uint8_t **data)
2771 AVIOContext *pb = s->pb;
2775 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2776 if (len != TS_PACKET_SIZE)
2777 return len < 0 ? len : AVERROR_EOF;
2778 /* check packet sync byte */
2779 if ((*data)[0] != 0x47) {
2780 /* find a new packet start */
2782 if (mpegts_resync(s, raw_packet_size, *data) < 0)
2783 return AVERROR(EAGAIN);
2793 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2795 AVIOContext *pb = s->pb;
2796 int skip = raw_packet_size - TS_PACKET_SIZE;
2798 avio_skip(pb, skip);
2801 static int handle_packets(MpegTSContext *ts, int64_t nb_packets)
2803 AVFormatContext *s = ts->stream;
2804 uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
2805 const uint8_t *data;
2809 if (avio_tell(s->pb) != ts->last_pos) {
2811 av_log(ts->stream, AV_LOG_TRACE, "Skipping after seek\n");
2812 /* seek detected, flush pes buffer */
2813 for (i = 0; i < NB_PID_MAX; i++) {
2815 if (ts->pids[i]->type == MPEGTS_PES) {
2816 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2817 av_buffer_unref(&pes->buffer);
2818 pes->data_index = 0;
2819 pes->state = MPEGTS_SKIP; /* skip until pes header */
2820 } else if (ts->pids[i]->type == MPEGTS_SECTION) {
2821 ts->pids[i]->u.section_filter.last_ver = -1;
2823 ts->pids[i]->last_cc = -1;
2824 ts->pids[i]->last_pcr = -1;
2831 memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2834 if (nb_packets != 0 && packet_num >= nb_packets ||
2835 ts->stop_parse > 1) {
2836 ret = AVERROR(EAGAIN);
2839 if (ts->stop_parse > 0)
2842 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2845 ret = handle_packet(ts, data);
2846 finished_reading_packet(s, ts->raw_packet_size);
2850 ts->last_pos = avio_tell(s->pb);
2854 static int mpegts_probe(AVProbeData *p)
2856 const int size = p->buf_size;
2860 int check_count = size / TS_FEC_PACKET_SIZE;
2861 #define CHECK_COUNT 10
2862 #define CHECK_BLOCK 100
2867 for (i = 0; i<check_count; i+=CHECK_BLOCK) {
2868 int left = FFMIN(check_count - i, CHECK_BLOCK);
2869 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , 1);
2870 int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, 1);
2871 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , 1);
2872 score = FFMAX3(score, dvhs_score, fec_score);
2874 maxscore = FFMAX(maxscore, score);
2877 sumscore = sumscore * CHECK_COUNT / check_count;
2878 maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK;
2880 ff_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2882 if (check_count > CHECK_COUNT && sumscore > 6) {
2883 return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2884 } else if (check_count >= CHECK_COUNT && sumscore > 6) {
2885 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2886 } else if (check_count >= CHECK_COUNT && maxscore > 6) {
2887 return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2888 } else if (sumscore > 6) {
2895 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2896 * (-1) if not available */
2897 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet)
2899 int afc, len, flags;
2903 afc = (packet[3] >> 4) & 3;
2905 return AVERROR_INVALIDDATA;
2910 return AVERROR_INVALIDDATA;
2913 if (!(flags & 0x10))
2914 return AVERROR_INVALIDDATA;
2916 return AVERROR_INVALIDDATA;
2918 *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7);
2919 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2923 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2925 /* NOTE: We attempt to seek on non-seekable files as well, as the
2926 * probe buffer usually is big enough. Only warn if the seek failed
2927 * on files where the seek should work. */
2928 if (avio_seek(pb, pos, SEEK_SET) < 0)
2929 av_log(s, (pb->seekable & AVIO_SEEKABLE_NORMAL) ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2932 static int mpegts_read_header(AVFormatContext *s)
2934 MpegTSContext *ts = s->priv_data;
2935 AVIOContext *pb = s->pb;
2936 uint8_t buf[8 * 1024] = {0};
2938 int64_t pos, probesize = s->probesize;
2940 s->internal->prefer_codec_framerate = 1;
2942 if (ffio_ensure_seekback(pb, probesize) < 0)
2943 av_log(s, AV_LOG_WARNING, "Failed to allocate buffers for seekback\n");
2945 /* read the first 8192 bytes to get packet size */
2946 pos = avio_tell(pb);
2947 len = avio_read(pb, buf, sizeof(buf));
2948 ts->raw_packet_size = get_packet_size(buf, len);
2949 if (ts->raw_packet_size <= 0) {
2950 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2951 ts->raw_packet_size = TS_PACKET_SIZE;
2956 if (s->iformat == &ff_mpegts_demuxer) {
2959 /* first do a scan to get all the services */
2960 seek_back(s, pb, pos);
2962 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2964 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2966 handle_packets(ts, probesize / ts->raw_packet_size);
2967 /* if could not find service, enable auto_guess */
2971 av_log(ts->stream, AV_LOG_TRACE, "tuning done\n");
2973 s->ctx_flags |= AVFMTCTX_NOHEADER;
2976 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2977 int64_t pcrs[2], pcr_h;
2978 int packet_count[2];
2979 uint8_t packet[TS_PACKET_SIZE];
2980 const uint8_t *data;
2982 /* only read packets */
2984 st = avformat_new_stream(s, NULL);
2986 return AVERROR(ENOMEM);
2987 avpriv_set_pts_info(st, 60, 1, 27000000);
2988 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2989 st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
2991 /* we iterate until we find two PCRs to estimate the bitrate */
2996 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2999 pid = AV_RB16(data + 1) & 0x1fff;
3000 if ((pcr_pid == -1 || pcr_pid == pid) &&
3001 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
3002 finished_reading_packet(s, ts->raw_packet_size);
3004 packet_count[nb_pcrs] = nb_packets;
3005 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
3008 if (pcrs[1] - pcrs[0] > 0) {
3009 /* the difference needs to be positive to make sense for bitrate computation */
3012 av_log(ts->stream, AV_LOG_WARNING, "invalid pcr pair %"PRId64" >= %"PRId64"\n", pcrs[0], pcrs[1]);
3014 packet_count[0] = packet_count[1];
3019 finished_reading_packet(s, ts->raw_packet_size);
3024 /* NOTE1: the bitrate is computed without the FEC */
3025 /* NOTE2: it is only the bitrate of the start of the stream */
3026 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
3027 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
3028 s->bit_rate = TS_PACKET_SIZE * 8 * 27000000LL / ts->pcr_incr;
3029 st->codecpar->bit_rate = s->bit_rate;
3030 st->start_time = ts->cur_pcr;
3031 av_log(ts->stream, AV_LOG_TRACE, "start=%0.3f pcr=%0.3f incr=%d\n",
3032 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
3035 seek_back(s, pb, pos);
3039 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
3041 static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt)
3043 MpegTSContext *ts = s->priv_data;
3045 int64_t pcr_h, next_pcr_h, pos;
3046 int pcr_l, next_pcr_l;
3047 uint8_t pcr_buf[12];
3048 const uint8_t *data;
3050 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
3051 return AVERROR(ENOMEM);
3052 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
3053 pkt->pos = avio_tell(s->pb);
3055 av_packet_unref(pkt);
3058 if (data != pkt->data)
3059 memcpy(pkt->data, data, ts->raw_packet_size);
3060 finished_reading_packet(s, ts->raw_packet_size);
3061 if (ts->mpeg2ts_compute_pcr) {
3062 /* compute exact PCR for each packet */
3063 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
3064 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
3065 pos = avio_tell(s->pb);
3066 for (i = 0; i < MAX_PACKET_READAHEAD; i++) {
3067 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
3068 avio_read(s->pb, pcr_buf, 12);
3069 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
3070 /* XXX: not precise enough */
3072 ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
3077 avio_seek(s->pb, pos, SEEK_SET);
3078 /* no next PCR found: we use previous increment */
3079 ts->cur_pcr = pcr_h * 300 + pcr_l;
3081 pkt->pts = ts->cur_pcr;
3082 pkt->duration = ts->pcr_incr;
3083 ts->cur_pcr += ts->pcr_incr;
3085 pkt->stream_index = 0;
3089 static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt)
3091 MpegTSContext *ts = s->priv_data;
3096 ret = handle_packets(ts, 0);
3098 av_packet_unref(ts->pkt);
3099 /* flush pes data left */
3100 for (i = 0; i < NB_PID_MAX; i++)
3101 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
3102 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
3103 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
3104 ret = new_pes_packet(pes, pkt);
3107 pes->state = MPEGTS_SKIP;
3114 if (!ret && pkt->size < 0)
3115 ret = AVERROR_INVALIDDATA;
3119 static void mpegts_free(MpegTSContext *ts)
3125 for (i = 0; i < NB_PID_MAX; i++)
3127 mpegts_close_filter(ts, ts->pids[i]);
3130 static int mpegts_read_close(AVFormatContext *s)
3132 MpegTSContext *ts = s->priv_data;
3137 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
3138 int64_t *ppos, int64_t pos_limit)
3140 MpegTSContext *ts = s->priv_data;
3141 int64_t pos, timestamp;
3142 uint8_t buf[TS_PACKET_SIZE];
3143 int pcr_l, pcr_pid =
3144 ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid;
3145 int pos47 = ts->pos47_full % ts->raw_packet_size;
3147 ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) *
3148 ts->raw_packet_size + pos47;
3149 while(pos < pos_limit) {
3150 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3151 return AV_NOPTS_VALUE;
3152 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
3153 return AV_NOPTS_VALUE;
3154 if (buf[0] != 0x47) {
3155 if (mpegts_resync(s, TS_PACKET_SIZE, buf) < 0)
3156 return AV_NOPTS_VALUE;
3157 pos = avio_tell(s->pb);
3160 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
3161 parse_pcr(×tamp, &pcr_l, buf) == 0) {
3165 pos += ts->raw_packet_size;
3168 return AV_NOPTS_VALUE;
3171 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
3172 int64_t *ppos, int64_t pos_limit)
3174 MpegTSContext *ts = s->priv_data;
3176 int pos47 = ts->pos47_full % ts->raw_packet_size;
3177 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
3178 ff_read_frame_flush(s);
3179 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
3180 return AV_NOPTS_VALUE;
3181 while(pos < pos_limit) {
3184 av_init_packet(&pkt);
3185 ret = av_read_frame(s, &pkt);
3187 return AV_NOPTS_VALUE;
3188 if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) {
3189 ff_reduce_index(s, pkt.stream_index);
3190 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
3191 if (pkt.stream_index == stream_index && pkt.pos >= *ppos) {
3192 int64_t dts = pkt.dts;
3194 av_packet_unref(&pkt);
3199 av_packet_unref(&pkt);
3202 return AV_NOPTS_VALUE;
3205 /**************************************************************/
3206 /* parsing functions - called from other demuxers such as RTP */
3208 MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
3212 ts = av_mallocz(sizeof(MpegTSContext));
3215 /* no stream case, currently used by RTP */
3216 ts->raw_packet_size = TS_PACKET_SIZE;
3219 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
3220 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
3225 /* return the consumed length if a packet was output, or -1 if no
3226 * packet is output */
3227 int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
3228 const uint8_t *buf, int len)
3236 if (len < TS_PACKET_SIZE)
3237 return AVERROR_INVALIDDATA;
3238 if (buf[0] != 0x47) {
3242 handle_packet(ts, buf);
3243 buf += TS_PACKET_SIZE;
3244 len -= TS_PACKET_SIZE;
3245 if (ts->stop_parse == 1)
3252 void avpriv_mpegts_parse_close(MpegTSContext *ts)
3258 AVInputFormat ff_mpegts_demuxer = {
3260 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
3261 .priv_data_size = sizeof(MpegTSContext),
3262 .read_probe = mpegts_probe,
3263 .read_header = mpegts_read_header,
3264 .read_packet = mpegts_read_packet,
3265 .read_close = mpegts_read_close,
3266 .read_timestamp = mpegts_get_dts,
3267 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3268 .priv_class = &mpegts_class,
3271 AVInputFormat ff_mpegtsraw_demuxer = {
3272 .name = "mpegtsraw",
3273 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
3274 .priv_data_size = sizeof(MpegTSContext),
3275 .read_header = mpegts_read_header,
3276 .read_packet = mpegts_raw_read_packet,
3277 .read_close = mpegts_read_close,
3278 .read_timestamp = mpegts_get_dts,
3279 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
3280 .priv_class = &mpegtsraw_class,