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/intreadwrite.h"
25 #include "libavutil/log.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/mathematics.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/avassert.h"
30 #include "libavcodec/bytestream.h"
31 #include "libavcodec/get_bits.h"
32 #include "libavcodec/mathops.h"
36 #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 enum MpegTSFilterType {
54 typedef struct MpegTSFilter MpegTSFilter;
56 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos, int64_t cur_pcr);
58 typedef struct MpegTSPESFilter {
63 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
65 typedef void SetServiceCallback(void *opaque, int ret);
67 typedef struct MpegTSSectionFilter {
71 unsigned int check_crc:1;
72 unsigned int end_of_section_reached:1;
73 SectionCallback *section_cb;
75 } MpegTSSectionFilter;
80 int last_cc; /* last cc code (-1 if first packet) */
81 enum MpegTSFilterType type;
83 MpegTSPESFilter pes_filter;
84 MpegTSSectionFilter section_filter;
88 #define MAX_PIDS_PER_PROGRAM 64
90 unsigned int id; //program id/service id
92 unsigned int pids[MAX_PIDS_PER_PROGRAM];
95 struct MpegTSContext {
98 AVFormatContext *stream;
99 /** raw packet size, including FEC if present */
104 #define SIZE_STAT_THRESHOLD 10
108 /** if true, all pids are analyzed to find streams */
111 /** compute exact PCR for each transport stream packet */
112 int mpeg2ts_compute_pcr;
114 /** fix dvb teletext pts */
115 int fix_teletext_pts;
117 int64_t cur_pcr; /**< used to estimate the exact PCR */
118 int pcr_incr; /**< used to estimate the exact PCR */
120 /* data needed to handle file based ts */
121 /** stop parsing loop */
123 /** packet containing Audio/Video data */
125 /** to detect seek */
128 /******************************************/
129 /* private mpegts data */
131 /** structure to keep track of Program->pids mapping */
135 int8_t crc_validity[NB_PID_MAX];
137 /** filters for various streams specified by PMT + for the PAT and PMT */
138 MpegTSFilter *pids[NB_PID_MAX];
142 static const AVOption mpegtsraw_options[] = {
143 {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
144 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
148 static const AVClass mpegtsraw_class = {
149 .class_name = "mpegtsraw demuxer",
150 .item_name = av_default_item_name,
151 .option = mpegtsraw_options,
152 .version = LIBAVUTIL_VERSION_INT,
155 static const AVOption mpegts_options[] = {
156 {"fix_teletext_pts", "Try to fix pts values of dvb teletext streams.", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_INT,
157 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
161 static const AVClass mpegts_class = {
162 .class_name = "mpegts demuxer",
163 .item_name = av_default_item_name,
164 .option = mpegts_options,
165 .version = LIBAVUTIL_VERSION_INT,
168 /* TS stream handling */
173 MPEGTS_PESHEADER_FILL,
178 /* enough for PES header + length */
179 #define PES_START_SIZE 6
180 #define PES_HEADER_SIZE 9
181 #define MAX_PES_HEADER_SIZE (9 + 255)
183 typedef struct PESContext {
185 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
188 AVFormatContext *stream;
190 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
191 enum MpegTSState state;
192 /* used to get the format */
194 int flags; /**< copied to the AVPacket flags */
197 int extended_stream_id;
199 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
200 uint8_t header[MAX_PES_HEADER_SIZE];
206 extern AVInputFormat ff_mpegts_demuxer;
208 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
210 AVProgram *prg = NULL;
212 for(i=0; i<ts->stream->nb_programs; i++)
213 if(ts->stream->programs[i]->id == programid){
214 prg = ts->stream->programs[i];
219 prg->nb_stream_indexes = 0;
222 static void clear_program(MpegTSContext *ts, unsigned int programid)
226 clear_avprogram(ts, programid);
227 for(i=0; i<ts->nb_prg; i++)
228 if(ts->prg[i].id == programid)
229 ts->prg[i].nb_pids = 0;
232 static void clear_programs(MpegTSContext *ts)
238 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
241 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
245 p = &ts->prg[ts->nb_prg];
251 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
254 struct Program *p = NULL;
255 for(i=0; i<ts->nb_prg; i++) {
256 if(ts->prg[i].id == programid) {
264 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
266 p->pids[p->nb_pids++] = pid;
269 static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
272 for(i=0; i<s->nb_programs; i++) {
273 if(s->programs[i]->id == programid) {
274 s->programs[i]->pcr_pid = pid;
281 * @brief discard_pid() decides if the pid is to be discarded according
282 * to caller's programs selection
283 * @param ts : - TS context
285 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
288 static int discard_pid(MpegTSContext *ts, unsigned int pid)
291 int used = 0, discarded = 0;
294 /* If none of the programs have .discard=AVDISCARD_ALL then there's
295 * no way we have to discard this packet
297 for (k = 0; k < ts->stream->nb_programs; k++) {
298 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
301 if (k == ts->stream->nb_programs)
304 for(i=0; i<ts->nb_prg; i++) {
306 for(j=0; j<p->nb_pids; j++) {
307 if(p->pids[j] != pid)
309 //is program with id p->id set to be discarded?
310 for(k=0; k<ts->stream->nb_programs; k++) {
311 if(ts->stream->programs[k]->id == p->id) {
312 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
321 return !used && discarded;
325 * Assemble PES packets out of TS packets, and then call the "section_cb"
326 * function when they are complete.
328 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
329 const uint8_t *buf, int buf_size, int is_start)
331 MpegTSContext *ts = s->priv_data;
332 MpegTSSectionFilter *tss = &tss1->u.section_filter;
336 memcpy(tss->section_buf, buf, buf_size);
337 tss->section_index = buf_size;
338 tss->section_h_size = -1;
339 tss->end_of_section_reached = 0;
341 if (tss->end_of_section_reached)
343 len = 4096 - tss->section_index;
346 memcpy(tss->section_buf + tss->section_index, buf, len);
347 tss->section_index += len;
350 /* compute section length if possible */
351 if (tss->section_h_size == -1 && tss->section_index >= 3) {
352 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
355 tss->section_h_size = len;
358 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
360 tss->end_of_section_reached = 1;
363 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
365 ts->crc_validity[ tss1->pid ] = 100;
366 }else if(ts->crc_validity[ tss1->pid ] > -10){
367 ts->crc_validity[ tss1->pid ]--;
372 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
376 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
377 SectionCallback *section_cb, void *opaque,
381 MpegTSFilter *filter;
382 MpegTSSectionFilter *sec;
384 av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
386 if (pid >= NB_PID_MAX || ts->pids[pid])
388 filter = av_mallocz(sizeof(MpegTSFilter));
391 ts->pids[pid] = filter;
392 filter->type = MPEGTS_SECTION;
395 filter->last_cc = -1;
396 sec = &filter->u.section_filter;
397 sec->section_cb = section_cb;
398 sec->opaque = opaque;
399 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
400 sec->check_crc = check_crc;
401 if (!sec->section_buf) {
408 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
412 MpegTSFilter *filter;
413 MpegTSPESFilter *pes;
415 if (pid >= NB_PID_MAX || ts->pids[pid])
417 filter = av_mallocz(sizeof(MpegTSFilter));
420 ts->pids[pid] = filter;
421 filter->type = MPEGTS_PES;
424 filter->last_cc = -1;
425 pes = &filter->u.pes_filter;
426 pes->pes_cb = pes_cb;
427 pes->opaque = opaque;
431 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
436 if (filter->type == MPEGTS_SECTION)
437 av_freep(&filter->u.section_filter.section_buf);
438 else if (filter->type == MPEGTS_PES) {
439 PESContext *pes = filter->u.pes_filter.opaque;
440 av_buffer_unref(&pes->buffer);
441 /* referenced private data will be freed later in
442 * avformat_close_input */
443 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
444 av_freep(&filter->u.pes_filter.opaque);
449 ts->pids[pid] = NULL;
452 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
453 int stat[TS_MAX_PACKET_SIZE];
457 memset(stat, 0, packet_size*sizeof(*stat));
459 for(i=0; i<size-3; i++){
460 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && buf[i+3] != 0x47){
461 int x = i % packet_size;
463 if(stat[x] > best_score){
473 /* autodetect fec presence. Must have at least 1024 bytes */
474 static int get_packet_size(const uint8_t *buf, int size)
476 int score, fec_score, dvhs_score;
478 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
481 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
482 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
483 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
484 av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
485 score, dvhs_score, fec_score);
487 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
488 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
489 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
493 typedef struct SectionHeader {
498 uint8_t last_sec_num;
501 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
514 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
520 if ((p + 1) >= p_end)
528 /* read and allocate a DVB string preceded by its length */
529 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
536 len = get8(&p, p_end);
539 if ((p + len) > p_end)
541 str = av_malloc(len + 1);
551 static int parse_section_header(SectionHeader *h,
552 const uint8_t **pp, const uint8_t *p_end)
556 val = get8(pp, p_end);
561 val = get16(pp, p_end);
565 val = get8(pp, p_end);
568 h->version = (val >> 1) & 0x1f;
569 val = get8(pp, p_end);
573 val = get8(pp, p_end);
576 h->last_sec_num = val;
581 uint32_t stream_type;
582 enum AVMediaType codec_type;
583 enum AVCodecID codec_id;
586 static const StreamType ISO_types[] = {
587 { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
588 { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
589 { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
590 { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
591 { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
592 { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
593 /* Makito encoder sets stream type 0x11 for AAC,
594 * so auto-detect LOAS/LATM instead of hardcoding it. */
595 #if !CONFIG_LOAS_DEMUXER
596 { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
598 { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
599 { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
600 { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
601 { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
602 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
606 static const StreamType HDMV_types[] = {
607 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
608 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
609 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
610 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
611 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
612 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
613 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
614 { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
615 { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
616 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
621 static const StreamType MISC_types[] = {
622 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
623 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
627 static const StreamType REGD_types[] = {
628 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
629 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
630 { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
631 { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
632 { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
633 { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
634 { MKTAG('H','E','V','C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
635 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
636 { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
640 static const StreamType METADATA_types[] = {
641 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
645 /* descriptor present */
646 static const StreamType DESC_types[] = {
647 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
648 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
649 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
650 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
651 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
655 static void mpegts_find_stream_type(AVStream *st,
656 uint32_t stream_type, const StreamType *types)
658 if (avcodec_is_open(st->codec)) {
659 av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
663 for (; types->stream_type; types++) {
664 if (stream_type == types->stream_type) {
665 st->codec->codec_type = types->codec_type;
666 st->codec->codec_id = types->codec_id;
667 st->request_probe = 0;
673 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
674 uint32_t stream_type, uint32_t prog_reg_desc)
676 int old_codec_type= st->codec->codec_type;
677 int old_codec_id = st->codec->codec_id;
679 if (avcodec_is_open(st->codec)) {
680 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
684 avpriv_set_pts_info(st, 33, 1, 90000);
686 st->codec->codec_type = AVMEDIA_TYPE_DATA;
687 st->codec->codec_id = AV_CODEC_ID_NONE;
688 st->need_parsing = AVSTREAM_PARSE_FULL;
690 pes->stream_type = stream_type;
692 av_log(pes->stream, AV_LOG_DEBUG,
693 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
694 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
696 st->codec->codec_tag = pes->stream_type;
698 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
699 if ((prog_reg_desc == AV_RL32("HDMV") ||
700 prog_reg_desc == AV_RL32("HDPR")) &&
701 st->codec->codec_id == AV_CODEC_ID_NONE) {
702 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
703 if (pes->stream_type == 0x83) {
704 // HDMV TrueHD streams also contain an AC3 coded version of the
705 // audio track - add a second stream for this
707 // priv_data cannot be shared between streams
708 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
710 return AVERROR(ENOMEM);
711 memcpy(sub_pes, pes, sizeof(*sub_pes));
713 sub_st = avformat_new_stream(pes->stream, NULL);
716 return AVERROR(ENOMEM);
719 sub_st->id = pes->pid;
720 avpriv_set_pts_info(sub_st, 33, 1, 90000);
721 sub_st->priv_data = sub_pes;
722 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
723 sub_st->codec->codec_id = AV_CODEC_ID_AC3;
724 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
725 sub_pes->sub_st = pes->sub_st = sub_st;
728 if (st->codec->codec_id == AV_CODEC_ID_NONE)
729 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
730 if (st->codec->codec_id == AV_CODEC_ID_NONE){
731 st->codec->codec_id = old_codec_id;
732 st->codec->codec_type= old_codec_type;
738 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
742 pkt->buf = pes->buffer;
743 pkt->data = pes->buffer->data;
744 pkt->size = pes->data_index;
746 if(pes->total_size != MAX_PES_PAYLOAD &&
747 pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
748 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
749 pes->flags |= AV_PKT_FLAG_CORRUPT;
751 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
753 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
754 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
755 pkt->stream_index = pes->sub_st->index;
757 pkt->stream_index = pes->st->index;
760 /* store position of first TS packet of this PES packet */
761 pkt->pos = pes->ts_packet_pos;
762 pkt->flags = pes->flags;
764 /* reset pts values */
765 pes->pts = AV_NOPTS_VALUE;
766 pes->dts = AV_NOPTS_VALUE;
772 static uint64_t get_ts64(GetBitContext *gb, int bits)
774 if (get_bits_left(gb) < bits)
775 return AV_NOPTS_VALUE;
776 return get_bits64(gb, bits);
779 static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
782 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
783 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
784 int dts_flag = -1, cts_flag = -1;
785 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
787 init_get_bits(&gb, buf, buf_size*8);
789 if (sl->use_au_start)
790 au_start_flag = get_bits1(&gb);
792 au_end_flag = get_bits1(&gb);
793 if (!sl->use_au_start && !sl->use_au_end)
794 au_start_flag = au_end_flag = 1;
796 ocr_flag = get_bits1(&gb);
798 idle_flag = get_bits1(&gb);
800 padding_flag = get_bits1(&gb);
802 padding_bits = get_bits(&gb, 3);
804 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
805 if (sl->packet_seq_num_len)
806 skip_bits_long(&gb, sl->packet_seq_num_len);
807 if (sl->degr_prior_len)
809 skip_bits(&gb, sl->degr_prior_len);
811 skip_bits_long(&gb, sl->ocr_len);
813 if (sl->use_rand_acc_pt)
815 if (sl->au_seq_num_len > 0)
816 skip_bits_long(&gb, sl->au_seq_num_len);
817 if (sl->use_timestamps) {
818 dts_flag = get_bits1(&gb);
819 cts_flag = get_bits1(&gb);
822 if (sl->inst_bitrate_len)
823 inst_bitrate_flag = get_bits1(&gb);
825 dts = get_ts64(&gb, sl->timestamp_len);
827 cts = get_ts64(&gb, sl->timestamp_len);
829 skip_bits_long(&gb, sl->au_len);
830 if (inst_bitrate_flag)
831 skip_bits_long(&gb, sl->inst_bitrate_len);
834 if (dts != AV_NOPTS_VALUE)
836 if (cts != AV_NOPTS_VALUE)
839 if (sl->timestamp_len && sl->timestamp_res)
840 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
842 return (get_bits_count(&gb) + 7) >> 3;
845 /* return non zero if a packet could be constructed */
846 static int mpegts_push_data(MpegTSFilter *filter,
847 const uint8_t *buf, int buf_size, int is_start,
848 int64_t pos, int64_t pcr)
850 PESContext *pes = filter->u.pes_filter.opaque;
851 MpegTSContext *ts = pes->ts;
862 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
863 new_pes_packet(pes, ts->pkt);
866 pes->state = MPEGTS_HEADER;
868 pes->ts_packet_pos = pos;
871 while (buf_size > 0) {
874 len = PES_START_SIZE - pes->data_index;
877 memcpy(pes->header + pes->data_index, p, len);
878 pes->data_index += len;
881 if (pes->data_index == PES_START_SIZE) {
882 /* we got all the PES or section header. We can now
884 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
885 pes->header[2] == 0x01) {
886 /* it must be an mpeg2 PES stream */
887 code = pes->header[3] | 0x100;
888 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
890 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
891 (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
892 code == 0x1be) /* padding_stream */
895 /* stream not present in PMT */
897 pes->st = avformat_new_stream(ts->stream, NULL);
899 return AVERROR(ENOMEM);
900 pes->st->id = pes->pid;
901 mpegts_set_stream_info(pes->st, pes, 0, 0);
904 pes->total_size = AV_RB16(pes->header + 4);
905 /* NOTE: a zero total size means the PES size is
907 if (!pes->total_size)
908 pes->total_size = MAX_PES_PAYLOAD;
910 /* allocate pes buffer */
911 pes->buffer = av_buffer_alloc(pes->total_size +
912 FF_INPUT_BUFFER_PADDING_SIZE);
914 return AVERROR(ENOMEM);
916 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
917 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
918 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
919 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
920 pes->state = MPEGTS_PESHEADER;
921 if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
922 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
923 pes->pid, pes->stream_type);
924 pes->st->request_probe= 1;
927 pes->state = MPEGTS_PAYLOAD;
931 /* otherwise, it should be a table */
934 pes->state = MPEGTS_SKIP;
939 /**********************************************/
940 /* PES packing parsing */
941 case MPEGTS_PESHEADER:
942 len = PES_HEADER_SIZE - pes->data_index;
947 memcpy(pes->header + pes->data_index, p, len);
948 pes->data_index += len;
951 if (pes->data_index == PES_HEADER_SIZE) {
952 pes->pes_header_size = pes->header[8] + 9;
953 pes->state = MPEGTS_PESHEADER_FILL;
956 case MPEGTS_PESHEADER_FILL:
957 len = pes->pes_header_size - pes->data_index;
962 memcpy(pes->header + pes->data_index, p, len);
963 pes->data_index += len;
966 if (pes->data_index == pes->pes_header_size) {
968 unsigned int flags, pes_ext, skip;
970 flags = pes->header[7];
972 pes->pts = AV_NOPTS_VALUE;
973 pes->dts = AV_NOPTS_VALUE;
974 if ((flags & 0xc0) == 0x80) {
975 pes->pts = ff_parse_pes_pts(r);
976 /* video pts is not monotonic, can't be used for dts */
977 if (pes->st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
980 } else if ((flags & 0xc0) == 0xc0) {
981 pes->pts = ff_parse_pes_pts(r);
983 pes->dts = ff_parse_pes_pts(r);
986 pes->extended_stream_id = -1;
987 if (flags & 0x01) { /* PES extension */
989 /* Skip PES private data, program packet sequence counter and P-STD buffer */
990 skip = (pes_ext >> 4) & 0xb;
993 if ((pes_ext & 0x41) == 0x01 &&
994 (r + 2) <= (pes->header + pes->pes_header_size)) {
995 /* PES extension 2 */
996 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
997 pes->extended_stream_id = r[1];
1001 /* we got the full header. We parse it and get the payload */
1002 pes->state = MPEGTS_PAYLOAD;
1003 pes->data_index = 0;
1004 if (pes->stream_type == 0x12 && buf_size > 0) {
1005 int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
1006 pes->pes_header_size += sl_header_bytes;
1007 p += sl_header_bytes;
1008 buf_size -= sl_header_bytes;
1010 if (pes->stream_type == 0x15 && buf_size >= 5) {
1011 /* skip metadata access unit header */
1012 pes->pes_header_size += 5;
1016 if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1017 AVProgram *p = NULL;
1018 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1019 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1020 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1021 if (f && f->type == MPEGTS_PES) {
1022 PESContext *pcrpes = f->u.pes_filter.opaque;
1023 if (pcrpes && pcrpes->last_pcr != -1 && pcrpes->st && pcrpes->st->discard != AVDISCARD_ALL) {
1024 // teletext packets do not always have correct timestamps,
1025 // the standard says they should be handled after 40.6 ms at most,
1026 // and the pcr error to this packet should be no more than 100 ms.
1027 // TODO: we should interpolate the PCR, not just use the last one
1028 int64_t pcr = pcrpes->last_pcr / 300;
1029 pes->st->pts_wrap_reference = pcrpes->st->pts_wrap_reference;
1030 pes->st->pts_wrap_behavior = pcrpes->st->pts_wrap_behavior;
1031 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1032 pes->pts = pes->dts = pcr;
1033 } else if (pes->dts > pcr + 3654 + 9000) {
1034 pes->pts = pes->dts = pcr + 3654 + 9000;
1044 case MPEGTS_PAYLOAD:
1045 if (buf_size > 0 && pes->buffer) {
1046 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
1047 new_pes_packet(pes, ts->pkt);
1048 pes->total_size = MAX_PES_PAYLOAD;
1049 pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
1051 return AVERROR(ENOMEM);
1053 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
1054 // pes packet size is < ts size packet and pes data is padded with 0xff
1055 // not sure if this is legal in ts but see issue #2392
1056 buf_size = pes->total_size;
1058 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1059 pes->data_index += buf_size;
1062 /* emit complete packets with known packet size
1063 * decreases demuxer delay for infrequent packets like subtitles from
1064 * a couple of seconds to milliseconds for properly muxed files.
1065 * total_size is the number of bytes following pes_packet_length
1066 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1067 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1068 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1070 new_pes_packet(pes, ts->pkt);
1082 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1087 /* if no pid found, then add a pid context */
1088 pes = av_mallocz(sizeof(PESContext));
1092 pes->stream = ts->stream;
1094 pes->pcr_pid = pcr_pid;
1095 pes->state = MPEGTS_SKIP;
1096 pes->pts = AV_NOPTS_VALUE;
1097 pes->dts = AV_NOPTS_VALUE;
1099 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1112 Mp4Descr *active_descr;
1114 int max_descr_count;
1116 } MP4DescrParseContext;
1118 static int init_MP4DescrParseContext(
1119 MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
1120 unsigned size, Mp4Descr *descr, int max_descr_count)
1124 return AVERROR_INVALIDDATA;
1126 if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
1127 NULL, NULL, NULL, NULL)) < 0)
1134 d->active_descr = NULL;
1135 d->max_descr_count = max_descr_count;
1140 static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
1141 int64_t new_off = avio_tell(pb);
1142 (*len) -= new_off - *off;
1146 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1149 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1152 if (parse_mp4_descr(d, off, len, 0) < 0)
1154 update_offsets(&d->pb, &off, &len);
1159 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1161 avio_rb16(&d->pb); // ID
1167 update_offsets(&d->pb, &off, &len);
1168 return parse_mp4_descr_arr(d, off, len);
1171 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1176 id_flags = avio_rb16(&d->pb);
1177 if (!(id_flags & 0x0020)) { //URL_Flag
1178 update_offsets(&d->pb, &off, &len);
1179 return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1185 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1188 if (d->descr_count >= d->max_descr_count)
1190 ff_mp4_parse_es_descr(&d->pb, &es_id);
1191 d->active_descr = d->descr + (d->descr_count++);
1193 d->active_descr->es_id = es_id;
1194 update_offsets(&d->pb, &off, &len);
1195 parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1196 update_offsets(&d->pb, &off, &len);
1198 parse_mp4_descr(d, off, len, MP4SLDescrTag);
1199 d->active_descr = NULL;
1203 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1205 Mp4Descr *descr = d->active_descr;
1208 d->active_descr->dec_config_descr = av_malloc(len);
1209 if (!descr->dec_config_descr)
1210 return AVERROR(ENOMEM);
1211 descr->dec_config_descr_len = len;
1212 avio_read(&d->pb, descr->dec_config_descr, len);
1216 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1218 Mp4Descr *descr = d->active_descr;
1223 predefined = avio_r8(&d->pb);
1226 int flags = avio_r8(&d->pb);
1227 descr->sl.use_au_start = !!(flags & 0x80);
1228 descr->sl.use_au_end = !!(flags & 0x40);
1229 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1230 descr->sl.use_padding = !!(flags & 0x08);
1231 descr->sl.use_timestamps = !!(flags & 0x04);
1232 descr->sl.use_idle = !!(flags & 0x02);
1233 descr->sl.timestamp_res = avio_rb32(&d->pb);
1235 descr->sl.timestamp_len = avio_r8(&d->pb);
1236 descr->sl.ocr_len = avio_r8(&d->pb);
1237 descr->sl.au_len = avio_r8(&d->pb);
1238 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1239 lengths = avio_rb16(&d->pb);
1240 descr->sl.degr_prior_len = lengths >> 12;
1241 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1242 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1244 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1249 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1252 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1253 update_offsets(&d->pb, &off, &len);
1254 if (len < 0 || len1 > len || len1 <= 0) {
1255 av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1259 if (d->level++ >= MAX_LEVEL) {
1260 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1264 if (target_tag && tag != target_tag) {
1265 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1271 parse_MP4IODescrTag(d, off, len1);
1274 parse_MP4ODescrTag(d, off, len1);
1277 parse_MP4ESDescrTag(d, off, len1);
1279 case MP4DecConfigDescrTag:
1280 parse_MP4DecConfigDescrTag(d, off, len1);
1283 parse_MP4SLDescrTag(d, off, len1);
1289 avio_seek(&d->pb, off + len1, SEEK_SET);
1293 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1294 Mp4Descr *descr, int *descr_count, int max_descr_count)
1296 MP4DescrParseContext d;
1297 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1300 parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1302 *descr_count = d.descr_count;
1306 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1307 Mp4Descr *descr, int *descr_count, int max_descr_count)
1309 MP4DescrParseContext d;
1310 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1313 parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1315 *descr_count = d.descr_count;
1319 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1321 MpegTSContext *ts = filter->u.section_filter.opaque;
1323 const uint8_t *p, *p_end;
1325 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1326 int mp4_descr_count = 0;
1328 AVFormatContext *s = ts->stream;
1330 p_end = section + section_len - 4;
1332 if (parse_section_header(&h, &p, p_end) < 0)
1334 if (h.tid != M4OD_TID)
1337 mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1339 for (pid = 0; pid < NB_PID_MAX; pid++) {
1342 for (i = 0; i < mp4_descr_count; i++) {
1345 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1347 if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1348 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1351 pes = ts->pids[pid]->u.pes_filter.opaque;
1357 pes->sl = mp4_descr[i].sl;
1359 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1360 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1361 ff_mp4_read_dec_config_descr(s, st, &pb);
1362 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1363 st->codec->extradata_size > 0)
1364 st->need_parsing = 0;
1365 if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1366 st->codec->extradata_size > 0)
1367 st->need_parsing = 0;
1369 if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1370 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1371 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1372 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1373 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1374 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1375 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1379 for (i = 0; i < mp4_descr_count; i++)
1380 av_free(mp4_descr[i].dec_config_descr);
1383 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1384 const uint8_t **pp, const uint8_t *desc_list_end,
1385 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1388 const uint8_t *desc_end;
1389 int desc_len, desc_tag, desc_es_id;
1393 desc_tag = get8(pp, desc_list_end);
1396 desc_len = get8(pp, desc_list_end);
1399 desc_end = *pp + desc_len;
1400 if (desc_end > desc_list_end)
1403 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1405 if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1406 stream_type == STREAM_TYPE_PRIVATE_DATA)
1407 mpegts_find_stream_type(st, desc_tag, DESC_types);
1410 case 0x1E: /* SL descriptor */
1411 desc_es_id = get16(pp, desc_end);
1412 if (ts && ts->pids[pid])
1413 ts->pids[pid]->es_id = desc_es_id;
1414 for (i = 0; i < mp4_descr_count; i++)
1415 if (mp4_descr[i].dec_config_descr_len &&
1416 mp4_descr[i].es_id == desc_es_id) {
1418 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1419 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1420 ff_mp4_read_dec_config_descr(fc, st, &pb);
1421 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1422 st->codec->extradata_size > 0)
1423 st->need_parsing = 0;
1424 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1425 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1428 case 0x1F: /* FMC descriptor */
1429 get16(pp, desc_end);
1430 if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
1431 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1433 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1434 mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1435 ff_mp4_read_dec_config_descr(fc, st, &pb);
1436 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1437 st->codec->extradata_size > 0){
1438 st->request_probe= st->need_parsing = 0;
1439 st->codec->codec_type= AVMEDIA_TYPE_AUDIO;
1443 case 0x56: /* DVB teletext descriptor */
1444 language[0] = get8(pp, desc_end);
1445 language[1] = get8(pp, desc_end);
1446 language[2] = get8(pp, desc_end);
1448 av_dict_set(&st->metadata, "language", language, 0);
1450 case 0x59: /* subtitling descriptor */
1451 language[0] = get8(pp, desc_end);
1452 language[1] = get8(pp, desc_end);
1453 language[2] = get8(pp, desc_end);
1455 /* hearing impaired subtitles detection */
1456 switch(get8(pp, desc_end)) {
1457 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1458 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1459 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1460 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1461 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1462 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1463 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1466 if (st->codec->extradata) {
1467 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1468 avpriv_request_sample(fc, "DVB sub with multiple IDs");
1470 if (!ff_alloc_extradata(st->codec, 4)) {
1471 memcpy(st->codec->extradata, *pp, 4);
1475 av_dict_set(&st->metadata, "language", language, 0);
1477 case 0x0a: /* ISO 639 language descriptor */
1478 for (i = 0; i + 4 <= desc_len; i += 4) {
1479 language[i + 0] = get8(pp, desc_end);
1480 language[i + 1] = get8(pp, desc_end);
1481 language[i + 2] = get8(pp, desc_end);
1482 language[i + 3] = ',';
1483 switch (get8(pp, desc_end)) {
1484 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1485 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1486 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1490 language[i - 1] = 0;
1491 av_dict_set(&st->metadata, "language", language, 0);
1494 case 0x05: /* registration descriptor */
1495 st->codec->codec_tag = bytestream_get_le32(pp);
1496 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1497 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1498 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1500 case 0x52: /* stream identifier descriptor */
1501 st->stream_identifier = 1 + get8(pp, desc_end);
1503 case 0x26: /* metadata descriptor */
1504 if (get16(pp, desc_end) == 0xFFFF)
1506 if (get8(pp, desc_end) == 0xFF) {
1507 st->codec->codec_tag = bytestream_get_le32(pp);
1508 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1509 mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
1519 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1521 MpegTSContext *ts = filter->u.section_filter.opaque;
1522 SectionHeader h1, *h = &h1;
1525 const uint8_t *p, *p_end, *desc_list_end;
1526 int program_info_length, pcr_pid, pid, stream_type;
1528 uint32_t prog_reg_desc = 0; /* registration descriptor */
1530 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1531 int mp4_descr_count = 0;
1534 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1535 hex_dump_debug(ts->stream, section, section_len);
1537 p_end = section + section_len - 4;
1539 if (parse_section_header(h, &p, p_end) < 0)
1542 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1543 h->id, h->sec_num, h->last_sec_num);
1545 if (h->tid != PMT_TID)
1548 clear_program(ts, h->id);
1549 pcr_pid = get16(&p, p_end);
1553 add_pid_to_pmt(ts, h->id, pcr_pid);
1554 set_pcr_pid(ts->stream, h->id, pcr_pid);
1556 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1558 program_info_length = get16(&p, p_end);
1559 if (program_info_length < 0)
1561 program_info_length &= 0xfff;
1562 while(program_info_length >= 2) {
1564 tag = get8(&p, p_end);
1565 len = get8(&p, p_end);
1567 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1569 if(len > program_info_length - 2)
1570 //something else is broken, exit the program_descriptors_loop
1572 program_info_length -= len + 2;
1573 if (tag == 0x1d) { // IOD descriptor
1574 get8(&p, p_end); // scope
1575 get8(&p, p_end); // label
1577 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1578 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1579 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1580 prog_reg_desc = bytestream_get_le32(&p);
1585 p += program_info_length;
1589 // stop parsing after pmt, we found header
1590 if (!ts->stream->nb_streams)
1596 stream_type = get8(&p, p_end);
1597 if (stream_type < 0)
1599 pid = get16(&p, p_end);
1603 if (pid == ts->current_pid)
1606 /* now create stream */
1607 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1608 pes = ts->pids[pid]->u.pes_filter.opaque;
1610 pes->st = avformat_new_stream(pes->stream, NULL);
1613 pes->st->id = pes->pid;
1616 } else if (stream_type != 0x13) {
1617 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1618 pes = add_pes_stream(ts, pid, pcr_pid);
1620 st = avformat_new_stream(pes->stream, NULL);
1626 int idx = ff_find_stream_index(ts->stream, pid);
1628 st = ts->stream->streams[idx];
1630 st = avformat_new_stream(ts->stream, NULL);
1634 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1641 if (pes && !pes->stream_type)
1642 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1644 add_pid_to_pmt(ts, h->id, pid);
1646 ff_program_add_stream_index(ts->stream, h->id, st->index);
1648 desc_list_len = get16(&p, p_end);
1649 if (desc_list_len < 0)
1651 desc_list_len &= 0xfff;
1652 desc_list_end = p + desc_list_len;
1653 if (desc_list_end > p_end)
1656 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1657 mp4_descr, mp4_descr_count, pid, ts) < 0)
1660 if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1661 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1662 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1669 for (i = 0; i < mp4_descr_count; i++)
1670 av_free(mp4_descr[i].dec_config_descr);
1673 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1675 MpegTSContext *ts = filter->u.section_filter.opaque;
1676 SectionHeader h1, *h = &h1;
1677 const uint8_t *p, *p_end;
1681 av_dlog(ts->stream, "PAT:\n");
1682 hex_dump_debug(ts->stream, section, section_len);
1684 p_end = section + section_len - 4;
1686 if (parse_section_header(h, &p, p_end) < 0)
1688 if (h->tid != PAT_TID)
1691 ts->stream->ts_id = h->id;
1695 sid = get16(&p, p_end);
1698 pmt_pid = get16(&p, p_end);
1703 if (pmt_pid == ts->current_pid)
1706 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1708 if (sid == 0x0000) {
1711 MpegTSFilter *fil = ts->pids[pmt_pid];
1712 program = av_new_program(ts->stream, sid);
1713 program->program_num = sid;
1714 program->pmt_pid = pmt_pid;
1716 if ( fil->type != MPEGTS_SECTION
1717 || fil->pid != pmt_pid
1718 || fil->u.section_filter.section_cb != pmt_cb)
1719 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1721 if (!ts->pids[pmt_pid])
1722 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1723 add_pat_entry(ts, sid);
1724 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1725 add_pid_to_pmt(ts, sid, pmt_pid);
1731 for (j=0; j<ts->stream->nb_programs; j++) {
1732 for (i=0; i<ts->nb_prg; i++)
1733 if (ts->prg[i].id == ts->stream->programs[j]->id)
1736 clear_avprogram(ts, ts->stream->programs[j]->id);
1741 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1743 MpegTSContext *ts = filter->u.section_filter.opaque;
1744 SectionHeader h1, *h = &h1;
1745 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1746 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1747 char *name, *provider_name;
1749 av_dlog(ts->stream, "SDT:\n");
1750 hex_dump_debug(ts->stream, section, section_len);
1752 p_end = section + section_len - 4;
1754 if (parse_section_header(h, &p, p_end) < 0)
1756 if (h->tid != SDT_TID)
1758 onid = get16(&p, p_end);
1761 val = get8(&p, p_end);
1765 sid = get16(&p, p_end);
1768 val = get8(&p, p_end);
1771 desc_list_len = get16(&p, p_end);
1772 if (desc_list_len < 0)
1774 desc_list_len &= 0xfff;
1775 desc_list_end = p + desc_list_len;
1776 if (desc_list_end > p_end)
1779 desc_tag = get8(&p, desc_list_end);
1782 desc_len = get8(&p, desc_list_end);
1783 desc_end = p + desc_len;
1784 if (desc_end > desc_list_end)
1787 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1788 desc_tag, desc_len);
1792 service_type = get8(&p, p_end);
1793 if (service_type < 0)
1795 provider_name = getstr8(&p, p_end);
1798 name = getstr8(&p, p_end);
1800 AVProgram *program = av_new_program(ts->stream, sid);
1802 av_dict_set(&program->metadata, "service_name", name, 0);
1803 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1807 av_free(provider_name);
1818 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1819 const uint8_t *packet);
1821 /* handle one TS packet */
1822 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1824 AVFormatContext *s = ts->stream;
1826 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1827 has_adaptation, has_payload;
1828 const uint8_t *p, *p_end;
1831 pid = AV_RB16(packet + 1) & 0x1fff;
1832 if(pid && discard_pid(ts, pid))
1834 is_start = packet[1] & 0x40;
1835 tss = ts->pids[pid];
1836 if (ts->auto_guess && tss == NULL && is_start) {
1837 add_pes_stream(ts, pid, -1);
1838 tss = ts->pids[pid];
1842 ts->current_pid = pid;
1844 afc = (packet[3] >> 4) & 3;
1845 if (afc == 0) /* reserved value */
1847 has_adaptation = afc & 2;
1848 has_payload = afc & 1;
1849 is_discontinuity = has_adaptation
1850 && packet[4] != 0 /* with length > 0 */
1851 && (packet[5] & 0x80); /* and discontinuity indicated */
1853 /* continuity check (currently not used) */
1854 cc = (packet[3] & 0xf);
1855 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1856 cc_ok = pid == 0x1FFF // null packet PID
1859 || expected_cc == cc;
1863 av_log(ts->stream, AV_LOG_DEBUG,
1864 "Continuity check failed for pid %d expected %d got %d\n",
1865 pid, expected_cc, cc);
1866 if(tss->type == MPEGTS_PES) {
1867 PESContext *pc = tss->u.pes_filter.opaque;
1868 pc->flags |= AV_PKT_FLAG_CORRUPT;
1875 if (has_adaptation) {
1876 /* skip adaptation field */
1879 /* if past the end of packet, ignore */
1880 p_end = packet + TS_PACKET_SIZE;
1884 pos = avio_tell(ts->stream->pb);
1886 av_assert0(pos >= TS_PACKET_SIZE);
1887 ts->pos47_full = pos - TS_PACKET_SIZE;
1890 if (tss->type == MPEGTS_SECTION) {
1892 /* pointer field present */
1894 if (p + len > p_end)
1897 /* write remaining section bytes */
1898 write_section_data(s, tss,
1900 /* check whether filter has been closed */
1906 write_section_data(s, tss,
1911 write_section_data(s, tss,
1920 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
1921 pcr = pcr_h * 300 + pcr_l;
1922 // Note: The position here points actually behind the current packet.
1923 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1924 pos - ts->raw_packet_size, pcr)) < 0)
1931 static void reanalyze(MpegTSContext *ts) {
1932 AVIOContext *pb = ts->stream->pb;
1933 int64_t pos = avio_tell(pb);
1936 pos -= ts->pos47_full;
1937 if (pos == TS_PACKET_SIZE) {
1938 ts->size_stat[0] ++;
1939 } else if (pos == TS_DVHS_PACKET_SIZE) {
1940 ts->size_stat[1] ++;
1941 } else if (pos == TS_FEC_PACKET_SIZE) {
1942 ts->size_stat[2] ++;
1945 ts->size_stat_count ++;
1946 if(ts->size_stat_count > SIZE_STAT_THRESHOLD) {
1948 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
1949 newsize = TS_PACKET_SIZE;
1950 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
1951 newsize = TS_DVHS_PACKET_SIZE;
1952 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
1953 newsize = TS_FEC_PACKET_SIZE;
1955 if (newsize && newsize != ts->raw_packet_size) {
1956 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
1957 ts->raw_packet_size = newsize;
1959 ts->size_stat_count = 0;
1960 memset(ts->size_stat, 0, sizeof(ts->size_stat));
1964 /* XXX: try to find a better synchro over several packets (use
1965 get_packet_size() ?) */
1966 static int mpegts_resync(AVFormatContext *s)
1968 AVIOContext *pb = s->pb;
1971 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1976 avio_seek(pb, -1, SEEK_CUR);
1977 reanalyze(s->priv_data);
1981 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1986 /* return -1 if error or EOF. Return 0 if OK. */
1987 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data)
1989 AVIOContext *pb = s->pb;
1993 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
1994 if (len != TS_PACKET_SIZE)
1995 return len < 0 ? len : AVERROR_EOF;
1996 /* check packet sync byte */
1997 if ((*data)[0] != 0x47) {
1998 /* find a new packet start */
1999 uint64_t pos = avio_tell(pb);
2000 avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
2002 if (mpegts_resync(s) < 0)
2003 return AVERROR(EAGAIN);
2013 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2015 AVIOContext *pb = s->pb;
2016 int skip = raw_packet_size - TS_PACKET_SIZE;
2018 avio_skip(pb, skip);
2021 static int handle_packets(MpegTSContext *ts, int nb_packets)
2023 AVFormatContext *s = ts->stream;
2024 uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
2025 const uint8_t *data;
2026 int packet_num, ret = 0;
2028 if (avio_tell(s->pb) != ts->last_pos) {
2030 av_dlog(ts->stream, "Skipping after seek\n");
2031 /* seek detected, flush pes buffer */
2032 for (i = 0; i < NB_PID_MAX; i++) {
2034 if (ts->pids[i]->type == MPEGTS_PES) {
2035 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2036 av_buffer_unref(&pes->buffer);
2037 pes->data_index = 0;
2038 pes->state = MPEGTS_SKIP; /* skip until pes header */
2041 ts->pids[i]->last_cc = -1;
2048 memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2051 if (nb_packets != 0 && packet_num >= nb_packets ||
2052 ts->stop_parse > 1) {
2053 ret = AVERROR(EAGAIN);
2056 if (ts->stop_parse > 0)
2059 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2062 ret = handle_packet(ts, data);
2063 finished_reading_packet(s, ts->raw_packet_size);
2067 ts->last_pos = avio_tell(s->pb);
2071 static int mpegts_probe(AVProbeData *p)
2073 const int size= p->buf_size;
2077 int check_count= size / TS_FEC_PACKET_SIZE;
2078 #define CHECK_COUNT 10
2079 #define CHECK_BLOCK 100
2081 if (check_count < CHECK_COUNT)
2084 for (i=0; i<check_count; i+=CHECK_BLOCK){
2085 int left = FFMIN(check_count - i, CHECK_BLOCK);
2086 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
2087 int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
2088 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
2089 score = FFMAX3(score, dvhs_score, fec_score);
2091 maxscore = FFMAX(maxscore, score);
2094 sumscore = sumscore*CHECK_COUNT/check_count;
2095 maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
2097 av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2099 if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2100 else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2104 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2105 (-1) if not available */
2106 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2107 const uint8_t *packet)
2109 int afc, len, flags;
2113 afc = (packet[3] >> 4) & 3;
2123 if (!(flags & 0x10))
2128 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
2129 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2133 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2135 /* NOTE: We attempt to seek on non-seekable files as well, as the
2136 * probe buffer usually is big enough. Only warn if the seek failed
2137 * on files where the seek should work. */
2138 if (avio_seek(pb, pos, SEEK_SET) < 0)
2139 av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2142 static int mpegts_read_header(AVFormatContext *s)
2144 MpegTSContext *ts = s->priv_data;
2145 AVIOContext *pb = s->pb;
2146 uint8_t buf[8*1024]={0};
2150 ffio_ensure_seekback(pb, s->probesize);
2152 /* read the first 8192 bytes to get packet size */
2153 pos = avio_tell(pb);
2154 len = avio_read(pb, buf, sizeof(buf));
2155 ts->raw_packet_size = get_packet_size(buf, len);
2156 if (ts->raw_packet_size <= 0) {
2157 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2158 ts->raw_packet_size = TS_PACKET_SIZE;
2163 if (s->iformat == &ff_mpegts_demuxer) {
2166 /* first do a scan to get all the services */
2167 seek_back(s, pb, pos);
2169 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2171 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2173 handle_packets(ts, s->probesize / ts->raw_packet_size);
2174 /* if could not find service, enable auto_guess */
2178 av_dlog(ts->stream, "tuning done\n");
2180 s->ctx_flags |= AVFMTCTX_NOHEADER;
2183 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2184 int64_t pcrs[2], pcr_h;
2185 int packet_count[2];
2186 uint8_t packet[TS_PACKET_SIZE];
2187 const uint8_t *data;
2189 /* only read packets */
2191 st = avformat_new_stream(s, NULL);
2194 avpriv_set_pts_info(st, 60, 1, 27000000);
2195 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2196 st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
2198 /* we iterate until we find two PCRs to estimate the bitrate */
2203 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2206 pid = AV_RB16(data + 1) & 0x1fff;
2207 if ((pcr_pid == -1 || pcr_pid == pid) &&
2208 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2209 finished_reading_packet(s, ts->raw_packet_size);
2211 packet_count[nb_pcrs] = nb_packets;
2212 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2217 finished_reading_packet(s, ts->raw_packet_size);
2222 /* NOTE1: the bitrate is computed without the FEC */
2223 /* NOTE2: it is only the bitrate of the start of the stream */
2224 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2225 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2226 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2227 st->codec->bit_rate = s->bit_rate;
2228 st->start_time = ts->cur_pcr;
2229 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2230 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2233 seek_back(s, pb, pos);
2239 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2241 static int mpegts_raw_read_packet(AVFormatContext *s,
2244 MpegTSContext *ts = s->priv_data;
2246 int64_t pcr_h, next_pcr_h, pos;
2247 int pcr_l, next_pcr_l;
2248 uint8_t pcr_buf[12];
2249 const uint8_t *data;
2251 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2252 return AVERROR(ENOMEM);
2253 pkt->pos= avio_tell(s->pb);
2254 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2256 av_free_packet(pkt);
2259 if (data != pkt->data)
2260 memcpy(pkt->data, data, ts->raw_packet_size);
2261 finished_reading_packet(s, ts->raw_packet_size);
2262 if (ts->mpeg2ts_compute_pcr) {
2263 /* compute exact PCR for each packet */
2264 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2265 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2266 pos = avio_tell(s->pb);
2267 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2268 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2269 avio_read(s->pb, pcr_buf, 12);
2270 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2271 /* XXX: not precise enough */
2272 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2277 avio_seek(s->pb, pos, SEEK_SET);
2278 /* no next PCR found: we use previous increment */
2279 ts->cur_pcr = pcr_h * 300 + pcr_l;
2281 pkt->pts = ts->cur_pcr;
2282 pkt->duration = ts->pcr_incr;
2283 ts->cur_pcr += ts->pcr_incr;
2285 pkt->stream_index = 0;
2289 static int mpegts_read_packet(AVFormatContext *s,
2292 MpegTSContext *ts = s->priv_data;
2297 ret = handle_packets(ts, 0);
2299 av_free_packet(ts->pkt);
2300 /* flush pes data left */
2301 for (i = 0; i < NB_PID_MAX; i++) {
2302 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2303 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2304 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2305 new_pes_packet(pes, pkt);
2306 pes->state = MPEGTS_SKIP;
2314 if (!ret && pkt->size < 0)
2315 ret = AVERROR(EINTR);
2319 static void mpegts_free(MpegTSContext *ts)
2325 for(i=0;i<NB_PID_MAX;i++)
2326 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2329 static int mpegts_read_close(AVFormatContext *s)
2331 MpegTSContext *ts = s->priv_data;
2336 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2337 int64_t *ppos, int64_t pos_limit)
2339 MpegTSContext *ts = s->priv_data;
2340 int64_t pos, timestamp;
2341 uint8_t buf[TS_PACKET_SIZE];
2342 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2343 int pos47 = ts->pos47_full % ts->raw_packet_size;
2344 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2345 while(pos < pos_limit) {
2346 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2347 return AV_NOPTS_VALUE;
2348 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2349 return AV_NOPTS_VALUE;
2350 if (buf[0] != 0x47) {
2351 avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
2352 if (mpegts_resync(s) < 0)
2353 return AV_NOPTS_VALUE;
2354 pos = avio_tell(s->pb);
2357 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2358 parse_pcr(×tamp, &pcr_l, buf) == 0) {
2362 pos += ts->raw_packet_size;
2365 return AV_NOPTS_VALUE;
2368 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2369 int64_t *ppos, int64_t pos_limit)
2371 MpegTSContext *ts = s->priv_data;
2373 int pos47 = ts->pos47_full % ts->raw_packet_size;
2374 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2375 ff_read_frame_flush(s);
2376 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2377 return AV_NOPTS_VALUE;
2378 while(pos < pos_limit) {
2381 av_init_packet(&pkt);
2382 ret= av_read_frame(s, &pkt);
2384 return AV_NOPTS_VALUE;
2385 av_free_packet(&pkt);
2386 if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
2387 ff_reduce_index(s, pkt.stream_index);
2388 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2389 if(pkt.stream_index == stream_index && pkt.pos >= *ppos){
2397 return AV_NOPTS_VALUE;
2400 /**************************************************************/
2401 /* parsing functions - called from other demuxers such as RTP */
2403 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2407 ts = av_mallocz(sizeof(MpegTSContext));
2410 /* no stream case, currently used by RTP */
2411 ts->raw_packet_size = TS_PACKET_SIZE;
2414 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2415 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2420 /* return the consumed length if a packet was output, or -1 if no
2422 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2423 const uint8_t *buf, int len)
2431 if (len < TS_PACKET_SIZE)
2433 if (buf[0] != 0x47) {
2437 handle_packet(ts, buf);
2438 buf += TS_PACKET_SIZE;
2439 len -= TS_PACKET_SIZE;
2440 if (ts->stop_parse == 1)
2447 void ff_mpegts_parse_close(MpegTSContext *ts)
2453 AVInputFormat ff_mpegts_demuxer = {
2455 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2456 .priv_data_size = sizeof(MpegTSContext),
2457 .read_probe = mpegts_probe,
2458 .read_header = mpegts_read_header,
2459 .read_packet = mpegts_read_packet,
2460 .read_close = mpegts_read_close,
2461 .read_timestamp = mpegts_get_dts,
2462 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2463 .priv_class = &mpegts_class,
2466 AVInputFormat ff_mpegtsraw_demuxer = {
2467 .name = "mpegtsraw",
2468 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2469 .priv_data_size = sizeof(MpegTSContext),
2470 .read_header = mpegts_read_header,
2471 .read_packet = mpegts_raw_read_packet,
2472 .read_close = mpegts_read_close,
2473 .read_timestamp = mpegts_get_dts,
2474 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2475 .priv_class = &mpegtsraw_class,