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->dts = pes->pts = ff_parse_pes_pts(r);
977 } else if ((flags & 0xc0) == 0xc0) {
978 pes->pts = ff_parse_pes_pts(r);
980 pes->dts = ff_parse_pes_pts(r);
983 pes->extended_stream_id = -1;
984 if (flags & 0x01) { /* PES extension */
986 /* Skip PES private data, program packet sequence counter and P-STD buffer */
987 skip = (pes_ext >> 4) & 0xb;
990 if ((pes_ext & 0x41) == 0x01 &&
991 (r + 2) <= (pes->header + pes->pes_header_size)) {
992 /* PES extension 2 */
993 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
994 pes->extended_stream_id = r[1];
998 /* we got the full header. We parse it and get the payload */
999 pes->state = MPEGTS_PAYLOAD;
1000 pes->data_index = 0;
1001 if (pes->stream_type == 0x12 && buf_size > 0) {
1002 int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
1003 pes->pes_header_size += sl_header_bytes;
1004 p += sl_header_bytes;
1005 buf_size -= sl_header_bytes;
1007 if (pes->stream_type == 0x15 && buf_size >= 5) {
1008 /* skip metadata access unit header */
1009 pes->pes_header_size += 5;
1013 if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1014 AVProgram *p = NULL;
1015 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1016 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1017 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1018 if (f && f->type == MPEGTS_PES) {
1019 PESContext *pcrpes = f->u.pes_filter.opaque;
1020 if (pcrpes && pcrpes->last_pcr != -1 && pcrpes->st && pcrpes->st->discard != AVDISCARD_ALL) {
1021 // teletext packets do not always have correct timestamps,
1022 // the standard says they should be handled after 40.6 ms at most,
1023 // and the pcr error to this packet should be no more than 100 ms.
1024 // TODO: we should interpolate the PCR, not just use the last one
1025 int64_t pcr = pcrpes->last_pcr / 300;
1026 pes->st->pts_wrap_reference = pcrpes->st->pts_wrap_reference;
1027 pes->st->pts_wrap_behavior = pcrpes->st->pts_wrap_behavior;
1028 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1029 pes->pts = pes->dts = pcr;
1030 } else if (pes->dts > pcr + 3654 + 9000) {
1031 pes->pts = pes->dts = pcr + 3654 + 9000;
1041 case MPEGTS_PAYLOAD:
1042 if (buf_size > 0 && pes->buffer) {
1043 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
1044 new_pes_packet(pes, ts->pkt);
1045 pes->total_size = MAX_PES_PAYLOAD;
1046 pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
1048 return AVERROR(ENOMEM);
1050 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
1051 // pes packet size is < ts size packet and pes data is padded with 0xff
1052 // not sure if this is legal in ts but see issue #2392
1053 buf_size = pes->total_size;
1055 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1056 pes->data_index += buf_size;
1059 /* emit complete packets with known packet size
1060 * decreases demuxer delay for infrequent packets like subtitles from
1061 * a couple of seconds to milliseconds for properly muxed files.
1062 * total_size is the number of bytes following pes_packet_length
1063 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1064 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1065 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1067 new_pes_packet(pes, ts->pkt);
1079 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1084 /* if no pid found, then add a pid context */
1085 pes = av_mallocz(sizeof(PESContext));
1089 pes->stream = ts->stream;
1091 pes->pcr_pid = pcr_pid;
1092 pes->state = MPEGTS_SKIP;
1093 pes->pts = AV_NOPTS_VALUE;
1094 pes->dts = AV_NOPTS_VALUE;
1096 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1109 Mp4Descr *active_descr;
1111 int max_descr_count;
1113 } MP4DescrParseContext;
1115 static int init_MP4DescrParseContext(
1116 MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
1117 unsigned size, Mp4Descr *descr, int max_descr_count)
1121 return AVERROR_INVALIDDATA;
1123 if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
1124 NULL, NULL, NULL, NULL)) < 0)
1131 d->active_descr = NULL;
1132 d->max_descr_count = max_descr_count;
1137 static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
1138 int64_t new_off = avio_tell(pb);
1139 (*len) -= new_off - *off;
1143 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1146 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1149 if (parse_mp4_descr(d, off, len, 0) < 0)
1151 update_offsets(&d->pb, &off, &len);
1156 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1158 avio_rb16(&d->pb); // ID
1164 update_offsets(&d->pb, &off, &len);
1165 return parse_mp4_descr_arr(d, off, len);
1168 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1173 id_flags = avio_rb16(&d->pb);
1174 if (!(id_flags & 0x0020)) { //URL_Flag
1175 update_offsets(&d->pb, &off, &len);
1176 return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1182 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1185 if (d->descr_count >= d->max_descr_count)
1187 ff_mp4_parse_es_descr(&d->pb, &es_id);
1188 d->active_descr = d->descr + (d->descr_count++);
1190 d->active_descr->es_id = es_id;
1191 update_offsets(&d->pb, &off, &len);
1192 parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1193 update_offsets(&d->pb, &off, &len);
1195 parse_mp4_descr(d, off, len, MP4SLDescrTag);
1196 d->active_descr = NULL;
1200 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1202 Mp4Descr *descr = d->active_descr;
1205 d->active_descr->dec_config_descr = av_malloc(len);
1206 if (!descr->dec_config_descr)
1207 return AVERROR(ENOMEM);
1208 descr->dec_config_descr_len = len;
1209 avio_read(&d->pb, descr->dec_config_descr, len);
1213 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1215 Mp4Descr *descr = d->active_descr;
1220 predefined = avio_r8(&d->pb);
1223 int flags = avio_r8(&d->pb);
1224 descr->sl.use_au_start = !!(flags & 0x80);
1225 descr->sl.use_au_end = !!(flags & 0x40);
1226 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1227 descr->sl.use_padding = !!(flags & 0x08);
1228 descr->sl.use_timestamps = !!(flags & 0x04);
1229 descr->sl.use_idle = !!(flags & 0x02);
1230 descr->sl.timestamp_res = avio_rb32(&d->pb);
1232 descr->sl.timestamp_len = avio_r8(&d->pb);
1233 descr->sl.ocr_len = avio_r8(&d->pb);
1234 descr->sl.au_len = avio_r8(&d->pb);
1235 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1236 lengths = avio_rb16(&d->pb);
1237 descr->sl.degr_prior_len = lengths >> 12;
1238 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1239 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1241 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1246 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1249 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1250 update_offsets(&d->pb, &off, &len);
1251 if (len < 0 || len1 > len || len1 <= 0) {
1252 av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1256 if (d->level++ >= MAX_LEVEL) {
1257 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1261 if (target_tag && tag != target_tag) {
1262 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1268 parse_MP4IODescrTag(d, off, len1);
1271 parse_MP4ODescrTag(d, off, len1);
1274 parse_MP4ESDescrTag(d, off, len1);
1276 case MP4DecConfigDescrTag:
1277 parse_MP4DecConfigDescrTag(d, off, len1);
1280 parse_MP4SLDescrTag(d, off, len1);
1286 avio_seek(&d->pb, off + len1, SEEK_SET);
1290 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1291 Mp4Descr *descr, int *descr_count, int max_descr_count)
1293 MP4DescrParseContext d;
1294 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1297 parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1299 *descr_count = d.descr_count;
1303 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1304 Mp4Descr *descr, int *descr_count, int max_descr_count)
1306 MP4DescrParseContext d;
1307 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1310 parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1312 *descr_count = d.descr_count;
1316 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1318 MpegTSContext *ts = filter->u.section_filter.opaque;
1320 const uint8_t *p, *p_end;
1322 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1323 int mp4_descr_count = 0;
1325 AVFormatContext *s = ts->stream;
1327 p_end = section + section_len - 4;
1329 if (parse_section_header(&h, &p, p_end) < 0)
1331 if (h.tid != M4OD_TID)
1334 mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1336 for (pid = 0; pid < NB_PID_MAX; pid++) {
1339 for (i = 0; i < mp4_descr_count; i++) {
1342 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1344 if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1345 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1348 pes = ts->pids[pid]->u.pes_filter.opaque;
1354 pes->sl = mp4_descr[i].sl;
1356 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1357 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1358 ff_mp4_read_dec_config_descr(s, st, &pb);
1359 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1360 st->codec->extradata_size > 0)
1361 st->need_parsing = 0;
1362 if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1363 st->codec->extradata_size > 0)
1364 st->need_parsing = 0;
1366 if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1367 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1368 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1369 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1370 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1371 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1372 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1376 for (i = 0; i < mp4_descr_count; i++)
1377 av_free(mp4_descr[i].dec_config_descr);
1380 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1381 const uint8_t **pp, const uint8_t *desc_list_end,
1382 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1385 const uint8_t *desc_end;
1386 int desc_len, desc_tag, desc_es_id;
1390 desc_tag = get8(pp, desc_list_end);
1393 desc_len = get8(pp, desc_list_end);
1396 desc_end = *pp + desc_len;
1397 if (desc_end > desc_list_end)
1400 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1402 if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1403 stream_type == STREAM_TYPE_PRIVATE_DATA)
1404 mpegts_find_stream_type(st, desc_tag, DESC_types);
1407 case 0x1E: /* SL descriptor */
1408 desc_es_id = get16(pp, desc_end);
1409 if (ts && ts->pids[pid])
1410 ts->pids[pid]->es_id = desc_es_id;
1411 for (i = 0; i < mp4_descr_count; i++)
1412 if (mp4_descr[i].dec_config_descr_len &&
1413 mp4_descr[i].es_id == desc_es_id) {
1415 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1416 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1417 ff_mp4_read_dec_config_descr(fc, st, &pb);
1418 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1419 st->codec->extradata_size > 0)
1420 st->need_parsing = 0;
1421 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1422 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1425 case 0x1F: /* FMC descriptor */
1426 get16(pp, desc_end);
1427 if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
1428 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1430 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1431 mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1432 ff_mp4_read_dec_config_descr(fc, st, &pb);
1433 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1434 st->codec->extradata_size > 0){
1435 st->request_probe= st->need_parsing = 0;
1436 st->codec->codec_type= AVMEDIA_TYPE_AUDIO;
1440 case 0x56: /* DVB teletext descriptor */
1441 language[0] = get8(pp, desc_end);
1442 language[1] = get8(pp, desc_end);
1443 language[2] = get8(pp, desc_end);
1445 av_dict_set(&st->metadata, "language", language, 0);
1447 case 0x59: /* subtitling descriptor */
1448 language[0] = get8(pp, desc_end);
1449 language[1] = get8(pp, desc_end);
1450 language[2] = get8(pp, desc_end);
1452 /* hearing impaired subtitles detection */
1453 switch(get8(pp, desc_end)) {
1454 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1455 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1456 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1457 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1458 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1459 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1460 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1463 if (st->codec->extradata) {
1464 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1465 avpriv_request_sample(fc, "DVB sub with multiple IDs");
1467 if (!ff_alloc_extradata(st->codec, 4)) {
1468 memcpy(st->codec->extradata, *pp, 4);
1472 av_dict_set(&st->metadata, "language", language, 0);
1474 case 0x0a: /* ISO 639 language descriptor */
1475 for (i = 0; i + 4 <= desc_len; i += 4) {
1476 language[i + 0] = get8(pp, desc_end);
1477 language[i + 1] = get8(pp, desc_end);
1478 language[i + 2] = get8(pp, desc_end);
1479 language[i + 3] = ',';
1480 switch (get8(pp, desc_end)) {
1481 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1482 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1483 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1487 language[i - 1] = 0;
1488 av_dict_set(&st->metadata, "language", language, 0);
1491 case 0x05: /* registration descriptor */
1492 st->codec->codec_tag = bytestream_get_le32(pp);
1493 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1494 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1495 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1497 case 0x52: /* stream identifier descriptor */
1498 st->stream_identifier = 1 + get8(pp, desc_end);
1500 case 0x26: /* metadata descriptor */
1501 if (get16(pp, desc_end) == 0xFFFF)
1503 if (get8(pp, desc_end) == 0xFF) {
1504 st->codec->codec_tag = bytestream_get_le32(pp);
1505 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1506 mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
1516 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1518 MpegTSContext *ts = filter->u.section_filter.opaque;
1519 SectionHeader h1, *h = &h1;
1522 const uint8_t *p, *p_end, *desc_list_end;
1523 int program_info_length, pcr_pid, pid, stream_type;
1525 uint32_t prog_reg_desc = 0; /* registration descriptor */
1527 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1528 int mp4_descr_count = 0;
1531 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1532 hex_dump_debug(ts->stream, section, section_len);
1534 p_end = section + section_len - 4;
1536 if (parse_section_header(h, &p, p_end) < 0)
1539 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1540 h->id, h->sec_num, h->last_sec_num);
1542 if (h->tid != PMT_TID)
1545 clear_program(ts, h->id);
1546 pcr_pid = get16(&p, p_end);
1550 add_pid_to_pmt(ts, h->id, pcr_pid);
1551 set_pcr_pid(ts->stream, h->id, pcr_pid);
1553 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1555 program_info_length = get16(&p, p_end);
1556 if (program_info_length < 0)
1558 program_info_length &= 0xfff;
1559 while(program_info_length >= 2) {
1561 tag = get8(&p, p_end);
1562 len = get8(&p, p_end);
1564 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1566 if(len > program_info_length - 2)
1567 //something else is broken, exit the program_descriptors_loop
1569 program_info_length -= len + 2;
1570 if (tag == 0x1d) { // IOD descriptor
1571 get8(&p, p_end); // scope
1572 get8(&p, p_end); // label
1574 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1575 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1576 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1577 prog_reg_desc = bytestream_get_le32(&p);
1582 p += program_info_length;
1586 // stop parsing after pmt, we found header
1587 if (!ts->stream->nb_streams)
1593 stream_type = get8(&p, p_end);
1594 if (stream_type < 0)
1596 pid = get16(&p, p_end);
1600 if (pid == ts->current_pid)
1603 /* now create stream */
1604 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1605 pes = ts->pids[pid]->u.pes_filter.opaque;
1607 pes->st = avformat_new_stream(pes->stream, NULL);
1610 pes->st->id = pes->pid;
1613 } else if (stream_type != 0x13) {
1614 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1615 pes = add_pes_stream(ts, pid, pcr_pid);
1617 st = avformat_new_stream(pes->stream, NULL);
1623 int idx = ff_find_stream_index(ts->stream, pid);
1625 st = ts->stream->streams[idx];
1627 st = avformat_new_stream(ts->stream, NULL);
1631 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1638 if (pes && !pes->stream_type)
1639 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1641 add_pid_to_pmt(ts, h->id, pid);
1643 ff_program_add_stream_index(ts->stream, h->id, st->index);
1645 desc_list_len = get16(&p, p_end);
1646 if (desc_list_len < 0)
1648 desc_list_len &= 0xfff;
1649 desc_list_end = p + desc_list_len;
1650 if (desc_list_end > p_end)
1653 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1654 mp4_descr, mp4_descr_count, pid, ts) < 0)
1657 if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1658 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1659 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1666 for (i = 0; i < mp4_descr_count; i++)
1667 av_free(mp4_descr[i].dec_config_descr);
1670 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1672 MpegTSContext *ts = filter->u.section_filter.opaque;
1673 SectionHeader h1, *h = &h1;
1674 const uint8_t *p, *p_end;
1678 av_dlog(ts->stream, "PAT:\n");
1679 hex_dump_debug(ts->stream, section, section_len);
1681 p_end = section + section_len - 4;
1683 if (parse_section_header(h, &p, p_end) < 0)
1685 if (h->tid != PAT_TID)
1688 ts->stream->ts_id = h->id;
1692 sid = get16(&p, p_end);
1695 pmt_pid = get16(&p, p_end);
1700 if (pmt_pid == ts->current_pid)
1703 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1705 if (sid == 0x0000) {
1708 MpegTSFilter *fil = ts->pids[pmt_pid];
1709 program = av_new_program(ts->stream, sid);
1710 program->program_num = sid;
1711 program->pmt_pid = pmt_pid;
1713 if ( fil->type != MPEGTS_SECTION
1714 || fil->pid != pmt_pid
1715 || fil->u.section_filter.section_cb != pmt_cb)
1716 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1718 if (!ts->pids[pmt_pid])
1719 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1720 add_pat_entry(ts, sid);
1721 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1722 add_pid_to_pmt(ts, sid, pmt_pid);
1728 for (j=0; j<ts->stream->nb_programs; j++) {
1729 for (i=0; i<ts->nb_prg; i++)
1730 if (ts->prg[i].id == ts->stream->programs[j]->id)
1733 clear_avprogram(ts, ts->stream->programs[j]->id);
1738 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1740 MpegTSContext *ts = filter->u.section_filter.opaque;
1741 SectionHeader h1, *h = &h1;
1742 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1743 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1744 char *name, *provider_name;
1746 av_dlog(ts->stream, "SDT:\n");
1747 hex_dump_debug(ts->stream, section, section_len);
1749 p_end = section + section_len - 4;
1751 if (parse_section_header(h, &p, p_end) < 0)
1753 if (h->tid != SDT_TID)
1755 onid = get16(&p, p_end);
1758 val = get8(&p, p_end);
1762 sid = get16(&p, p_end);
1765 val = get8(&p, p_end);
1768 desc_list_len = get16(&p, p_end);
1769 if (desc_list_len < 0)
1771 desc_list_len &= 0xfff;
1772 desc_list_end = p + desc_list_len;
1773 if (desc_list_end > p_end)
1776 desc_tag = get8(&p, desc_list_end);
1779 desc_len = get8(&p, desc_list_end);
1780 desc_end = p + desc_len;
1781 if (desc_end > desc_list_end)
1784 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1785 desc_tag, desc_len);
1789 service_type = get8(&p, p_end);
1790 if (service_type < 0)
1792 provider_name = getstr8(&p, p_end);
1795 name = getstr8(&p, p_end);
1797 AVProgram *program = av_new_program(ts->stream, sid);
1799 av_dict_set(&program->metadata, "service_name", name, 0);
1800 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1804 av_free(provider_name);
1815 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1816 const uint8_t *packet);
1818 /* handle one TS packet */
1819 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1821 AVFormatContext *s = ts->stream;
1823 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1824 has_adaptation, has_payload;
1825 const uint8_t *p, *p_end;
1828 pid = AV_RB16(packet + 1) & 0x1fff;
1829 if(pid && discard_pid(ts, pid))
1831 is_start = packet[1] & 0x40;
1832 tss = ts->pids[pid];
1833 if (ts->auto_guess && tss == NULL && is_start) {
1834 add_pes_stream(ts, pid, -1);
1835 tss = ts->pids[pid];
1839 ts->current_pid = pid;
1841 afc = (packet[3] >> 4) & 3;
1842 if (afc == 0) /* reserved value */
1844 has_adaptation = afc & 2;
1845 has_payload = afc & 1;
1846 is_discontinuity = has_adaptation
1847 && packet[4] != 0 /* with length > 0 */
1848 && (packet[5] & 0x80); /* and discontinuity indicated */
1850 /* continuity check (currently not used) */
1851 cc = (packet[3] & 0xf);
1852 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1853 cc_ok = pid == 0x1FFF // null packet PID
1856 || expected_cc == cc;
1860 av_log(ts->stream, AV_LOG_DEBUG,
1861 "Continuity check failed for pid %d expected %d got %d\n",
1862 pid, expected_cc, cc);
1863 if(tss->type == MPEGTS_PES) {
1864 PESContext *pc = tss->u.pes_filter.opaque;
1865 pc->flags |= AV_PKT_FLAG_CORRUPT;
1872 if (has_adaptation) {
1873 /* skip adaptation field */
1876 /* if past the end of packet, ignore */
1877 p_end = packet + TS_PACKET_SIZE;
1881 pos = avio_tell(ts->stream->pb);
1883 av_assert0(pos >= TS_PACKET_SIZE);
1884 ts->pos47_full = pos - TS_PACKET_SIZE;
1887 if (tss->type == MPEGTS_SECTION) {
1889 /* pointer field present */
1891 if (p + len > p_end)
1894 /* write remaining section bytes */
1895 write_section_data(s, tss,
1897 /* check whether filter has been closed */
1903 write_section_data(s, tss,
1908 write_section_data(s, tss,
1917 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
1918 pcr = pcr_h * 300 + pcr_l;
1919 // Note: The position here points actually behind the current packet.
1920 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1921 pos - ts->raw_packet_size, pcr)) < 0)
1928 static void reanalyze(MpegTSContext *ts) {
1929 AVIOContext *pb = ts->stream->pb;
1930 int64_t pos = avio_tell(pb);
1933 pos -= ts->pos47_full;
1934 if (pos == TS_PACKET_SIZE) {
1935 ts->size_stat[0] ++;
1936 } else if (pos == TS_DVHS_PACKET_SIZE) {
1937 ts->size_stat[1] ++;
1938 } else if (pos == TS_FEC_PACKET_SIZE) {
1939 ts->size_stat[2] ++;
1942 ts->size_stat_count ++;
1943 if(ts->size_stat_count > SIZE_STAT_THRESHOLD) {
1945 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
1946 newsize = TS_PACKET_SIZE;
1947 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
1948 newsize = TS_DVHS_PACKET_SIZE;
1949 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
1950 newsize = TS_FEC_PACKET_SIZE;
1952 if (newsize && newsize != ts->raw_packet_size) {
1953 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
1954 ts->raw_packet_size = newsize;
1956 ts->size_stat_count = 0;
1957 memset(ts->size_stat, 0, sizeof(ts->size_stat));
1961 /* XXX: try to find a better synchro over several packets (use
1962 get_packet_size() ?) */
1963 static int mpegts_resync(AVFormatContext *s)
1965 AVIOContext *pb = s->pb;
1968 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1973 avio_seek(pb, -1, SEEK_CUR);
1974 reanalyze(s->priv_data);
1978 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1983 /* return -1 if error or EOF. Return 0 if OK. */
1984 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data)
1986 AVIOContext *pb = s->pb;
1990 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
1991 if (len != TS_PACKET_SIZE)
1992 return len < 0 ? len : AVERROR_EOF;
1993 /* check packet sync byte */
1994 if ((*data)[0] != 0x47) {
1995 /* find a new packet start */
1996 uint64_t pos = avio_tell(pb);
1997 avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
1999 if (mpegts_resync(s) < 0)
2000 return AVERROR(EAGAIN);
2010 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2012 AVIOContext *pb = s->pb;
2013 int skip = raw_packet_size - TS_PACKET_SIZE;
2015 avio_skip(pb, skip);
2018 static int handle_packets(MpegTSContext *ts, int nb_packets)
2020 AVFormatContext *s = ts->stream;
2021 uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
2022 const uint8_t *data;
2023 int packet_num, ret = 0;
2025 if (avio_tell(s->pb) != ts->last_pos) {
2027 av_dlog(ts->stream, "Skipping after seek\n");
2028 /* seek detected, flush pes buffer */
2029 for (i = 0; i < NB_PID_MAX; i++) {
2031 if (ts->pids[i]->type == MPEGTS_PES) {
2032 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2033 av_buffer_unref(&pes->buffer);
2034 pes->data_index = 0;
2035 pes->state = MPEGTS_SKIP; /* skip until pes header */
2038 ts->pids[i]->last_cc = -1;
2045 memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2048 if (nb_packets != 0 && packet_num >= nb_packets ||
2049 ts->stop_parse > 1) {
2050 ret = AVERROR(EAGAIN);
2053 if (ts->stop_parse > 0)
2056 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2059 ret = handle_packet(ts, data);
2060 finished_reading_packet(s, ts->raw_packet_size);
2064 ts->last_pos = avio_tell(s->pb);
2068 static int mpegts_probe(AVProbeData *p)
2070 const int size= p->buf_size;
2074 int check_count= size / TS_FEC_PACKET_SIZE;
2075 #define CHECK_COUNT 10
2076 #define CHECK_BLOCK 100
2078 if (check_count < CHECK_COUNT)
2081 for (i=0; i<check_count; i+=CHECK_BLOCK){
2082 int left = FFMIN(check_count - i, CHECK_BLOCK);
2083 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
2084 int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
2085 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
2086 score = FFMAX3(score, dvhs_score, fec_score);
2088 maxscore = FFMAX(maxscore, score);
2091 sumscore = sumscore*CHECK_COUNT/check_count;
2092 maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
2094 av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2096 if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2097 else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2101 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2102 (-1) if not available */
2103 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2104 const uint8_t *packet)
2106 int afc, len, flags;
2110 afc = (packet[3] >> 4) & 3;
2120 if (!(flags & 0x10))
2125 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
2126 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2130 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2132 /* NOTE: We attempt to seek on non-seekable files as well, as the
2133 * probe buffer usually is big enough. Only warn if the seek failed
2134 * on files where the seek should work. */
2135 if (avio_seek(pb, pos, SEEK_SET) < 0)
2136 av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2139 static int mpegts_read_header(AVFormatContext *s)
2141 MpegTSContext *ts = s->priv_data;
2142 AVIOContext *pb = s->pb;
2143 uint8_t buf[8*1024]={0};
2147 ffio_ensure_seekback(pb, s->probesize);
2149 /* read the first 8192 bytes to get packet size */
2150 pos = avio_tell(pb);
2151 len = avio_read(pb, buf, sizeof(buf));
2152 ts->raw_packet_size = get_packet_size(buf, len);
2153 if (ts->raw_packet_size <= 0) {
2154 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2155 ts->raw_packet_size = TS_PACKET_SIZE;
2160 if (s->iformat == &ff_mpegts_demuxer) {
2163 /* first do a scan to get all the services */
2164 seek_back(s, pb, pos);
2166 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2168 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2170 handle_packets(ts, s->probesize / ts->raw_packet_size);
2171 /* if could not find service, enable auto_guess */
2175 av_dlog(ts->stream, "tuning done\n");
2177 s->ctx_flags |= AVFMTCTX_NOHEADER;
2180 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2181 int64_t pcrs[2], pcr_h;
2182 int packet_count[2];
2183 uint8_t packet[TS_PACKET_SIZE];
2184 const uint8_t *data;
2186 /* only read packets */
2188 st = avformat_new_stream(s, NULL);
2191 avpriv_set_pts_info(st, 60, 1, 27000000);
2192 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2193 st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
2195 /* we iterate until we find two PCRs to estimate the bitrate */
2200 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2203 pid = AV_RB16(data + 1) & 0x1fff;
2204 if ((pcr_pid == -1 || pcr_pid == pid) &&
2205 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2206 finished_reading_packet(s, ts->raw_packet_size);
2208 packet_count[nb_pcrs] = nb_packets;
2209 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2214 finished_reading_packet(s, ts->raw_packet_size);
2219 /* NOTE1: the bitrate is computed without the FEC */
2220 /* NOTE2: it is only the bitrate of the start of the stream */
2221 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2222 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2223 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2224 st->codec->bit_rate = s->bit_rate;
2225 st->start_time = ts->cur_pcr;
2226 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2227 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2230 seek_back(s, pb, pos);
2236 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2238 static int mpegts_raw_read_packet(AVFormatContext *s,
2241 MpegTSContext *ts = s->priv_data;
2243 int64_t pcr_h, next_pcr_h, pos;
2244 int pcr_l, next_pcr_l;
2245 uint8_t pcr_buf[12];
2246 const uint8_t *data;
2248 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2249 return AVERROR(ENOMEM);
2250 pkt->pos= avio_tell(s->pb);
2251 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2253 av_free_packet(pkt);
2256 if (data != pkt->data)
2257 memcpy(pkt->data, data, ts->raw_packet_size);
2258 finished_reading_packet(s, ts->raw_packet_size);
2259 if (ts->mpeg2ts_compute_pcr) {
2260 /* compute exact PCR for each packet */
2261 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2262 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2263 pos = avio_tell(s->pb);
2264 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2265 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2266 avio_read(s->pb, pcr_buf, 12);
2267 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2268 /* XXX: not precise enough */
2269 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2274 avio_seek(s->pb, pos, SEEK_SET);
2275 /* no next PCR found: we use previous increment */
2276 ts->cur_pcr = pcr_h * 300 + pcr_l;
2278 pkt->pts = ts->cur_pcr;
2279 pkt->duration = ts->pcr_incr;
2280 ts->cur_pcr += ts->pcr_incr;
2282 pkt->stream_index = 0;
2286 static int mpegts_read_packet(AVFormatContext *s,
2289 MpegTSContext *ts = s->priv_data;
2294 ret = handle_packets(ts, 0);
2296 av_free_packet(ts->pkt);
2297 /* flush pes data left */
2298 for (i = 0; i < NB_PID_MAX; i++) {
2299 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2300 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2301 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2302 new_pes_packet(pes, pkt);
2303 pes->state = MPEGTS_SKIP;
2311 if (!ret && pkt->size < 0)
2312 ret = AVERROR(EINTR);
2316 static void mpegts_free(MpegTSContext *ts)
2322 for(i=0;i<NB_PID_MAX;i++)
2323 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2326 static int mpegts_read_close(AVFormatContext *s)
2328 MpegTSContext *ts = s->priv_data;
2333 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2334 int64_t *ppos, int64_t pos_limit)
2336 MpegTSContext *ts = s->priv_data;
2337 int64_t pos, timestamp;
2338 uint8_t buf[TS_PACKET_SIZE];
2339 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2340 int pos47 = ts->pos47_full % ts->raw_packet_size;
2341 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2342 while(pos < pos_limit) {
2343 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2344 return AV_NOPTS_VALUE;
2345 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2346 return AV_NOPTS_VALUE;
2347 if (buf[0] != 0x47) {
2348 avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
2349 if (mpegts_resync(s) < 0)
2350 return AV_NOPTS_VALUE;
2351 pos = avio_tell(s->pb);
2354 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2355 parse_pcr(×tamp, &pcr_l, buf) == 0) {
2359 pos += ts->raw_packet_size;
2362 return AV_NOPTS_VALUE;
2365 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2366 int64_t *ppos, int64_t pos_limit)
2368 MpegTSContext *ts = s->priv_data;
2370 int pos47 = ts->pos47_full % ts->raw_packet_size;
2371 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2372 ff_read_frame_flush(s);
2373 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2374 return AV_NOPTS_VALUE;
2375 while(pos < pos_limit) {
2378 av_init_packet(&pkt);
2379 ret= av_read_frame(s, &pkt);
2381 return AV_NOPTS_VALUE;
2382 av_free_packet(&pkt);
2383 if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
2384 ff_reduce_index(s, pkt.stream_index);
2385 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2386 if(pkt.stream_index == stream_index && pkt.pos >= *ppos){
2394 return AV_NOPTS_VALUE;
2397 /**************************************************************/
2398 /* parsing functions - called from other demuxers such as RTP */
2400 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2404 ts = av_mallocz(sizeof(MpegTSContext));
2407 /* no stream case, currently used by RTP */
2408 ts->raw_packet_size = TS_PACKET_SIZE;
2411 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2412 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2417 /* return the consumed length if a packet was output, or -1 if no
2419 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2420 const uint8_t *buf, int len)
2428 if (len < TS_PACKET_SIZE)
2430 if (buf[0] != 0x47) {
2434 handle_packet(ts, buf);
2435 buf += TS_PACKET_SIZE;
2436 len -= TS_PACKET_SIZE;
2437 if (ts->stop_parse == 1)
2444 void ff_mpegts_parse_close(MpegTSContext *ts)
2450 AVInputFormat ff_mpegts_demuxer = {
2452 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2453 .priv_data_size = sizeof(MpegTSContext),
2454 .read_probe = mpegts_probe,
2455 .read_header = mpegts_read_header,
2456 .read_packet = mpegts_read_packet,
2457 .read_close = mpegts_read_close,
2458 .read_timestamp = mpegts_get_dts,
2459 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2460 .priv_class = &mpegts_class,
2463 AVInputFormat ff_mpegtsraw_demuxer = {
2464 .name = "mpegtsraw",
2465 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2466 .priv_data_size = sizeof(MpegTSContext),
2467 .read_header = mpegts_read_header,
2468 .read_packet = mpegts_raw_read_packet,
2469 .read_close = mpegts_read_close,
2470 .read_timestamp = mpegts_get_dts,
2471 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2472 .priv_class = &mpegtsraw_class,