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 //#define USE_SYNCPOINT_SEARCH
24 #include "libavutil/crc.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/log.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/mathematics.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/avassert.h"
31 #include "libavcodec/bytestream.h"
35 #include "avio_internal.h"
40 /* maximum size in which we look for synchronisation if
41 synchronisation is lost */
42 #define MAX_RESYNC_SIZE 65536
44 #define MAX_PES_PAYLOAD 200*1024
46 enum MpegTSFilterType {
51 typedef struct MpegTSFilter MpegTSFilter;
53 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
55 typedef struct MpegTSPESFilter {
60 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
62 typedef void SetServiceCallback(void *opaque, int ret);
64 typedef struct MpegTSSectionFilter {
68 unsigned int check_crc:1;
69 unsigned int end_of_section_reached:1;
70 SectionCallback *section_cb;
72 } MpegTSSectionFilter;
76 int last_cc; /* last cc code (-1 if first packet) */
77 enum MpegTSFilterType type;
79 MpegTSPESFilter pes_filter;
80 MpegTSSectionFilter section_filter;
84 #define MAX_PIDS_PER_PROGRAM 64
86 unsigned int id; //program id/service id
88 unsigned int pids[MAX_PIDS_PER_PROGRAM];
91 struct MpegTSContext {
94 AVFormatContext *stream;
95 /** raw packet size, including FEC if present */
100 /** if true, all pids are analyzed to find streams */
103 /** compute exact PCR for each transport stream packet */
104 int mpeg2ts_compute_pcr;
106 int64_t cur_pcr; /**< used to estimate the exact PCR */
107 int pcr_incr; /**< used to estimate the exact PCR */
109 /* data needed to handle file based ts */
110 /** stop parsing loop */
112 /** packet containing Audio/Video data */
114 /** to detect seek */
117 /******************************************/
118 /* private mpegts data */
120 /** structure to keep track of Program->pids mapping */
125 /** filters for various streams specified by PMT + for the PAT and PMT */
126 MpegTSFilter *pids[NB_PID_MAX];
129 static const AVOption options[] = {
130 {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
131 {.dbl = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
135 static const AVClass mpegtsraw_class = {
136 .class_name = "mpegtsraw demuxer",
137 .item_name = av_default_item_name,
139 .version = LIBAVUTIL_VERSION_INT,
142 /* TS stream handling */
147 MPEGTS_PESHEADER_FILL,
152 /* enough for PES header + length */
153 #define PES_START_SIZE 6
154 #define PES_HEADER_SIZE 9
155 #define MAX_PES_HEADER_SIZE (9 + 255)
157 typedef struct PESContext {
159 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
162 AVFormatContext *stream;
164 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
165 enum MpegTSState state;
166 /* used to get the format */
168 int flags; /**< copied to the AVPacket flags */
171 int extended_stream_id;
173 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
174 uint8_t header[MAX_PES_HEADER_SIZE];
178 extern AVInputFormat ff_mpegts_demuxer;
180 static void clear_program(MpegTSContext *ts, unsigned int programid)
184 for(i=0; i<ts->nb_prg; i++)
185 if(ts->prg[i].id == programid)
186 ts->prg[i].nb_pids = 0;
189 static void clear_programs(MpegTSContext *ts)
195 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
198 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
202 p = &ts->prg[ts->nb_prg];
208 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
211 struct Program *p = NULL;
212 for(i=0; i<ts->nb_prg; i++) {
213 if(ts->prg[i].id == programid) {
221 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
223 p->pids[p->nb_pids++] = pid;
226 static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
229 for(i=0; i<s->nb_programs; i++) {
230 if(s->programs[i]->id == programid) {
231 s->programs[i]->pcr_pid = pid;
238 * @brief discard_pid() decides if the pid is to be discarded according
239 * to caller's programs selection
240 * @param ts : - TS context
242 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
245 static int discard_pid(MpegTSContext *ts, unsigned int pid)
248 int used = 0, discarded = 0;
250 for(i=0; i<ts->nb_prg; i++) {
252 for(j=0; j<p->nb_pids; j++) {
253 if(p->pids[j] != pid)
255 //is program with id p->id set to be discarded?
256 for(k=0; k<ts->stream->nb_programs; k++) {
257 if(ts->stream->programs[k]->id == p->id) {
258 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
267 return !used && discarded;
271 * Assemble PES packets out of TS packets, and then call the "section_cb"
272 * function when they are complete.
274 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
275 const uint8_t *buf, int buf_size, int is_start)
277 MpegTSSectionFilter *tss = &tss1->u.section_filter;
281 memcpy(tss->section_buf, buf, buf_size);
282 tss->section_index = buf_size;
283 tss->section_h_size = -1;
284 tss->end_of_section_reached = 0;
286 if (tss->end_of_section_reached)
288 len = 4096 - tss->section_index;
291 memcpy(tss->section_buf + tss->section_index, buf, len);
292 tss->section_index += len;
295 /* compute section length if possible */
296 if (tss->section_h_size == -1 && tss->section_index >= 3) {
297 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
300 tss->section_h_size = len;
303 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
304 tss->end_of_section_reached = 1;
305 if (!tss->check_crc ||
306 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
307 tss->section_buf, tss->section_h_size) == 0)
308 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
312 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
313 SectionCallback *section_cb, void *opaque,
317 MpegTSFilter *filter;
318 MpegTSSectionFilter *sec;
320 av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
322 if (pid >= NB_PID_MAX || ts->pids[pid])
324 filter = av_mallocz(sizeof(MpegTSFilter));
327 ts->pids[pid] = filter;
328 filter->type = MPEGTS_SECTION;
330 filter->last_cc = -1;
331 sec = &filter->u.section_filter;
332 sec->section_cb = section_cb;
333 sec->opaque = opaque;
334 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
335 sec->check_crc = check_crc;
336 if (!sec->section_buf) {
343 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
347 MpegTSFilter *filter;
348 MpegTSPESFilter *pes;
350 if (pid >= NB_PID_MAX || ts->pids[pid])
352 filter = av_mallocz(sizeof(MpegTSFilter));
355 ts->pids[pid] = filter;
356 filter->type = MPEGTS_PES;
358 filter->last_cc = -1;
359 pes = &filter->u.pes_filter;
360 pes->pes_cb = pes_cb;
361 pes->opaque = opaque;
365 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
370 if (filter->type == MPEGTS_SECTION)
371 av_freep(&filter->u.section_filter.section_buf);
372 else if (filter->type == MPEGTS_PES) {
373 PESContext *pes = filter->u.pes_filter.opaque;
374 av_freep(&pes->buffer);
375 /* referenced private data will be freed later in
376 * av_close_input_stream */
377 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
378 av_freep(&filter->u.pes_filter.opaque);
383 ts->pids[pid] = NULL;
386 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
387 int stat[TS_MAX_PACKET_SIZE];
392 memset(stat, 0, packet_size*sizeof(int));
394 for(x=i=0; i<size-3; i++){
395 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
397 if(stat[x] > best_score){
404 if(x == packet_size) x= 0;
410 /* autodetect fec presence. Must have at least 1024 bytes */
411 static int get_packet_size(const uint8_t *buf, int size)
413 int score, fec_score, dvhs_score;
415 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
418 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
419 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
420 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
421 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
423 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
424 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
425 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
429 typedef struct SectionHeader {
434 uint8_t last_sec_num;
437 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
450 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
456 if ((p + 1) >= p_end)
464 /* read and allocate a DVB string preceeded by its length */
465 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
472 len = get8(&p, p_end);
475 if ((p + len) > p_end)
477 str = av_malloc(len + 1);
487 static int parse_section_header(SectionHeader *h,
488 const uint8_t **pp, const uint8_t *p_end)
492 val = get8(pp, p_end);
497 val = get16(pp, p_end);
501 val = get8(pp, p_end);
504 h->version = (val >> 1) & 0x1f;
505 val = get8(pp, p_end);
509 val = get8(pp, p_end);
512 h->last_sec_num = val;
517 uint32_t stream_type;
518 enum AVMediaType codec_type;
519 enum CodecID codec_id;
522 static const StreamType ISO_types[] = {
523 { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
524 { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
525 { 0x03, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
526 { 0x04, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
527 { 0x0f, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC },
528 { 0x10, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4 },
529 /* Makito encoder sets stream type 0x11 for AAC,
530 * so auto-detect LOAS/LATM instead of hardcoding it. */
531 // { 0x11, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC_LATM }, /* LATM syntax */
532 { 0x1b, AVMEDIA_TYPE_VIDEO, CODEC_ID_H264 },
533 { 0xd1, AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
534 { 0xea, AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
538 static const StreamType HDMV_types[] = {
539 { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
540 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
541 { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
542 { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
543 { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
544 { 0x85, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS }, /* DTS HD */
545 { 0x86, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS }, /* DTS HD MASTER*/
546 { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
551 static const StreamType MISC_types[] = {
552 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
553 { 0x8a, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
557 static const StreamType REGD_types[] = {
558 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
559 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
560 { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, CODEC_ID_S302M },
561 { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
562 { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
563 { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
564 { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
568 /* descriptor present */
569 static const StreamType DESC_types[] = {
570 { 0x6a, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
571 { 0x7a, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
572 { 0x7b, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
573 { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
574 { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
578 static void mpegts_find_stream_type(AVStream *st,
579 uint32_t stream_type, const StreamType *types)
581 for (; types->stream_type; types++) {
582 if (stream_type == types->stream_type) {
583 st->codec->codec_type = types->codec_type;
584 st->codec->codec_id = types->codec_id;
585 st->request_probe = 0;
591 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
592 uint32_t stream_type, uint32_t prog_reg_desc)
594 int old_codec_type= st->codec->codec_type;
595 int old_codec_id = st->codec->codec_id;
596 av_set_pts_info(st, 33, 1, 90000);
598 st->codec->codec_type = AVMEDIA_TYPE_DATA;
599 st->codec->codec_id = CODEC_ID_NONE;
600 st->need_parsing = AVSTREAM_PARSE_FULL;
602 pes->stream_type = stream_type;
604 av_log(pes->stream, AV_LOG_DEBUG,
605 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
606 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
608 st->codec->codec_tag = pes->stream_type;
610 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
611 if (prog_reg_desc == AV_RL32("HDMV") &&
612 st->codec->codec_id == CODEC_ID_NONE) {
613 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
614 if (pes->stream_type == 0x83) {
615 // HDMV TrueHD streams also contain an AC3 coded version of the
616 // audio track - add a second stream for this
618 // priv_data cannot be shared between streams
619 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
621 return AVERROR(ENOMEM);
622 memcpy(sub_pes, pes, sizeof(*sub_pes));
624 sub_st = avformat_new_stream(pes->stream, NULL);
627 return AVERROR(ENOMEM);
630 sub_st->id = pes->pid;
631 av_set_pts_info(sub_st, 33, 1, 90000);
632 sub_st->priv_data = sub_pes;
633 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
634 sub_st->codec->codec_id = CODEC_ID_AC3;
635 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
636 sub_pes->sub_st = pes->sub_st = sub_st;
639 if (st->codec->codec_id == CODEC_ID_NONE)
640 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
641 if (st->codec->codec_id == CODEC_ID_NONE){
642 st->codec->codec_id = old_codec_id;
643 st->codec->codec_type= old_codec_type;
649 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
653 pkt->destruct = av_destruct_packet;
654 pkt->data = pes->buffer;
655 pkt->size = pes->data_index;
657 if(pes->total_size != MAX_PES_PAYLOAD &&
658 pes->pes_header_size + pes->data_index != pes->total_size + 6) {
659 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
660 pes->flags |= AV_PKT_FLAG_CORRUPT;
662 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
664 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
665 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
666 pkt->stream_index = pes->sub_st->index;
668 pkt->stream_index = pes->st->index;
671 /* store position of first TS packet of this PES packet */
672 pkt->pos = pes->ts_packet_pos;
673 pkt->flags = pes->flags;
675 /* reset pts values */
676 pes->pts = AV_NOPTS_VALUE;
677 pes->dts = AV_NOPTS_VALUE;
683 /* return non zero if a packet could be constructed */
684 static int mpegts_push_data(MpegTSFilter *filter,
685 const uint8_t *buf, int buf_size, int is_start,
688 PESContext *pes = filter->u.pes_filter.opaque;
689 MpegTSContext *ts = pes->ts;
697 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
698 new_pes_packet(pes, ts->pkt);
701 pes->state = MPEGTS_HEADER;
703 pes->ts_packet_pos = pos;
706 while (buf_size > 0) {
709 len = PES_START_SIZE - pes->data_index;
712 memcpy(pes->header + pes->data_index, p, len);
713 pes->data_index += len;
716 if (pes->data_index == PES_START_SIZE) {
717 /* we got all the PES or section header. We can now
719 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
720 pes->header[2] == 0x01) {
721 /* it must be an mpeg2 PES stream */
722 code = pes->header[3] | 0x100;
723 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
725 if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
726 code == 0x1be) /* padding_stream */
729 /* stream not present in PMT */
731 pes->st = avformat_new_stream(ts->stream, NULL);
733 return AVERROR(ENOMEM);
734 pes->st->id = pes->pid;
735 mpegts_set_stream_info(pes->st, pes, 0, 0);
738 pes->total_size = AV_RB16(pes->header + 4);
739 /* NOTE: a zero total size means the PES size is
741 if (!pes->total_size)
742 pes->total_size = MAX_PES_PAYLOAD;
744 /* allocate pes buffer */
745 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
747 return AVERROR(ENOMEM);
749 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
750 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
751 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
752 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
753 pes->state = MPEGTS_PESHEADER;
754 if (pes->st->codec->codec_id == CODEC_ID_NONE && !pes->st->request_probe) {
755 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
756 pes->pid, pes->stream_type);
757 pes->st->request_probe= 1;
760 pes->state = MPEGTS_PAYLOAD;
764 /* otherwise, it should be a table */
767 pes->state = MPEGTS_SKIP;
772 /**********************************************/
773 /* PES packing parsing */
774 case MPEGTS_PESHEADER:
775 len = PES_HEADER_SIZE - pes->data_index;
780 memcpy(pes->header + pes->data_index, p, len);
781 pes->data_index += len;
784 if (pes->data_index == PES_HEADER_SIZE) {
785 pes->pes_header_size = pes->header[8] + 9;
786 pes->state = MPEGTS_PESHEADER_FILL;
789 case MPEGTS_PESHEADER_FILL:
790 len = pes->pes_header_size - pes->data_index;
795 memcpy(pes->header + pes->data_index, p, len);
796 pes->data_index += len;
799 if (pes->data_index == pes->pes_header_size) {
801 unsigned int flags, pes_ext, skip;
803 flags = pes->header[7];
805 pes->pts = AV_NOPTS_VALUE;
806 pes->dts = AV_NOPTS_VALUE;
807 if ((flags & 0xc0) == 0x80) {
808 pes->dts = pes->pts = ff_parse_pes_pts(r);
810 } else if ((flags & 0xc0) == 0xc0) {
811 pes->pts = ff_parse_pes_pts(r);
813 pes->dts = ff_parse_pes_pts(r);
816 pes->extended_stream_id = -1;
817 if (flags & 0x01) { /* PES extension */
819 /* Skip PES private data, program packet sequence counter and P-STD buffer */
820 skip = (pes_ext >> 4) & 0xb;
823 if ((pes_ext & 0x41) == 0x01 &&
824 (r + 2) <= (pes->header + pes->pes_header_size)) {
825 /* PES extension 2 */
826 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
827 pes->extended_stream_id = r[1];
831 /* we got the full header. We parse it and get the payload */
832 pes->state = MPEGTS_PAYLOAD;
837 if (buf_size > 0 && pes->buffer) {
838 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
839 new_pes_packet(pes, ts->pkt);
840 pes->total_size = MAX_PES_PAYLOAD;
841 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
843 return AVERROR(ENOMEM);
845 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
846 // pes packet size is < ts size packet and pes data is padded with 0xff
847 // not sure if this is legal in ts but see issue #2392
848 buf_size = pes->total_size;
850 memcpy(pes->buffer+pes->data_index, p, buf_size);
851 pes->data_index += buf_size;
854 /* emit complete packets with known packet size
855 * decreases demuxer delay for infrequent packets like subtitles from
856 * a couple of seconds to milliseconds for properly muxed files.
857 * total_size is the number of bytes following pes_packet_length
858 * in the pes header, i.e. not counting the first 6 bytes */
859 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
860 pes->pes_header_size + pes->data_index == pes->total_size + 6) {
862 new_pes_packet(pes, ts->pkt);
874 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
879 /* if no pid found, then add a pid context */
880 pes = av_mallocz(sizeof(PESContext));
884 pes->stream = ts->stream;
886 pes->pcr_pid = pcr_pid;
887 pes->state = MPEGTS_SKIP;
888 pes->pts = AV_NOPTS_VALUE;
889 pes->dts = AV_NOPTS_VALUE;
890 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
898 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
899 int *es_id, uint8_t **dec_config_descr,
900 int *dec_config_descr_size)
906 ffio_init_context(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
908 len = ff_mp4_read_descr(s, &pb, &tag);
909 if (tag == MP4IODescrTag) {
910 avio_rb16(&pb); // ID
916 len = ff_mp4_read_descr(s, &pb, &tag);
917 if (tag == MP4ESDescrTag) {
918 ff_mp4_parse_es_descr(&pb, es_id);
919 av_dlog(s, "ES_ID %#x\n", *es_id);
920 len = ff_mp4_read_descr(s, &pb, &tag);
921 if (tag == MP4DecConfigDescrTag) {
922 *dec_config_descr = av_malloc(len);
923 if (!*dec_config_descr)
924 return AVERROR(ENOMEM);
925 *dec_config_descr_size = len;
926 avio_read(&pb, *dec_config_descr, len);
933 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
934 const uint8_t **pp, const uint8_t *desc_list_end,
935 int mp4_dec_config_descr_len, int mp4_es_id, int pid,
936 uint8_t *mp4_dec_config_descr)
938 const uint8_t *desc_end;
939 int desc_len, desc_tag;
943 desc_tag = get8(pp, desc_list_end);
946 desc_len = get8(pp, desc_list_end);
949 desc_end = *pp + desc_len;
950 if (desc_end > desc_list_end)
953 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
955 if (st->codec->codec_id == CODEC_ID_NONE &&
956 stream_type == STREAM_TYPE_PRIVATE_DATA)
957 mpegts_find_stream_type(st, desc_tag, DESC_types);
960 case 0x1F: /* FMC descriptor */
962 if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
963 mp4_dec_config_descr_len && mp4_es_id == pid) {
965 ffio_init_context(&pb, mp4_dec_config_descr,
966 mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
967 ff_mp4_read_dec_config_descr(fc, st, &pb);
968 if (st->codec->codec_id == CODEC_ID_AAC &&
969 st->codec->extradata_size > 0)
970 st->need_parsing = 0;
973 case 0x56: /* DVB teletext descriptor */
974 language[0] = get8(pp, desc_end);
975 language[1] = get8(pp, desc_end);
976 language[2] = get8(pp, desc_end);
978 av_dict_set(&st->metadata, "language", language, 0);
980 case 0x59: /* subtitling descriptor */
981 language[0] = get8(pp, desc_end);
982 language[1] = get8(pp, desc_end);
983 language[2] = get8(pp, desc_end);
985 /* hearing impaired subtitles detection */
986 switch(get8(pp, desc_end)) {
987 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
988 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
989 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
990 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
991 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
992 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
993 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
996 if (st->codec->extradata) {
997 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
998 av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
1000 st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
1001 if (st->codec->extradata) {
1002 st->codec->extradata_size = 4;
1003 memcpy(st->codec->extradata, *pp, 4);
1007 av_dict_set(&st->metadata, "language", language, 0);
1009 case 0x0a: /* ISO 639 language descriptor */
1010 for (i = 0; i + 4 <= desc_len; i += 4) {
1011 language[i + 0] = get8(pp, desc_end);
1012 language[i + 1] = get8(pp, desc_end);
1013 language[i + 2] = get8(pp, desc_end);
1014 language[i + 3] = ',';
1015 switch (get8(pp, desc_end)) {
1016 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1017 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1018 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1022 language[i - 1] = 0;
1023 av_dict_set(&st->metadata, "language", language, 0);
1026 case 0x05: /* registration descriptor */
1027 st->codec->codec_tag = bytestream_get_le32(pp);
1028 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1029 if (st->codec->codec_id == CODEC_ID_NONE &&
1030 stream_type == STREAM_TYPE_PRIVATE_DATA)
1031 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1033 case 0x52: /* stream identifier descriptor */
1034 st->stream_identifier = 1 + get8(pp, desc_end);
1043 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1045 MpegTSContext *ts = filter->u.section_filter.opaque;
1046 SectionHeader h1, *h = &h1;
1049 const uint8_t *p, *p_end, *desc_list_end;
1050 int program_info_length, pcr_pid, pid, stream_type;
1052 uint32_t prog_reg_desc = 0; /* registration descriptor */
1053 uint8_t *mp4_dec_config_descr = NULL;
1054 int mp4_dec_config_descr_len = 0;
1057 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1058 hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
1060 p_end = section + section_len - 4;
1062 if (parse_section_header(h, &p, p_end) < 0)
1065 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1066 h->id, h->sec_num, h->last_sec_num);
1068 if (h->tid != PMT_TID)
1071 clear_program(ts, h->id);
1072 pcr_pid = get16(&p, p_end) & 0x1fff;
1075 add_pid_to_pmt(ts, h->id, pcr_pid);
1076 set_pcr_pid(ts->stream, h->id, pcr_pid);
1078 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1080 program_info_length = get16(&p, p_end) & 0xfff;
1081 if (program_info_length < 0)
1083 while(program_info_length >= 2) {
1085 tag = get8(&p, p_end);
1086 len = get8(&p, p_end);
1088 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1090 if(len > program_info_length - 2)
1091 //something else is broken, exit the program_descriptors_loop
1093 program_info_length -= len + 2;
1094 if (tag == 0x1d) { // IOD descriptor
1095 get8(&p, p_end); // scope
1096 get8(&p, p_end); // label
1098 mp4_read_iods(ts->stream, p, len, &mp4_es_id,
1099 &mp4_dec_config_descr, &mp4_dec_config_descr_len);
1100 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1101 prog_reg_desc = bytestream_get_le32(&p);
1106 p += program_info_length;
1110 // stop parsing after pmt, we found header
1111 if (!ts->stream->nb_streams)
1116 stream_type = get8(&p, p_end);
1117 if (stream_type < 0)
1119 pid = get16(&p, p_end) & 0x1fff;
1123 /* now create ffmpeg stream */
1124 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1125 pes = ts->pids[pid]->u.pes_filter.opaque;
1127 pes->st = avformat_new_stream(pes->stream, NULL);
1128 pes->st->id = pes->pid;
1132 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1133 pes = add_pes_stream(ts, pid, pcr_pid);
1135 st = avformat_new_stream(pes->stream, NULL);
1143 if (!pes->stream_type)
1144 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1146 add_pid_to_pmt(ts, h->id, pid);
1148 ff_program_add_stream_index(ts->stream, h->id, st->index);
1150 desc_list_len = get16(&p, p_end) & 0xfff;
1151 if (desc_list_len < 0)
1153 desc_list_end = p + desc_list_len;
1154 if (desc_list_end > p_end)
1157 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1158 mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
1161 if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1162 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1163 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1170 av_free(mp4_dec_config_descr);
1173 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1175 MpegTSContext *ts = filter->u.section_filter.opaque;
1176 SectionHeader h1, *h = &h1;
1177 const uint8_t *p, *p_end;
1181 av_dlog(ts->stream, "PAT:\n");
1182 hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
1184 p_end = section + section_len - 4;
1186 if (parse_section_header(h, &p, p_end) < 0)
1188 if (h->tid != PAT_TID)
1191 ts->stream->ts_id = h->id;
1195 sid = get16(&p, p_end);
1198 pmt_pid = get16(&p, p_end) & 0x1fff;
1202 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1204 if (sid == 0x0000) {
1207 program = av_new_program(ts->stream, sid);
1208 program->program_num = sid;
1209 program->pmt_pid = pmt_pid;
1210 if (ts->pids[pmt_pid])
1211 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1212 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1213 add_pat_entry(ts, sid);
1214 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1215 add_pid_to_pmt(ts, sid, pmt_pid);
1220 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1222 MpegTSContext *ts = filter->u.section_filter.opaque;
1223 SectionHeader h1, *h = &h1;
1224 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1225 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1226 char *name, *provider_name;
1228 av_dlog(ts->stream, "SDT:\n");
1229 hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
1231 p_end = section + section_len - 4;
1233 if (parse_section_header(h, &p, p_end) < 0)
1235 if (h->tid != SDT_TID)
1237 onid = get16(&p, p_end);
1240 val = get8(&p, p_end);
1244 sid = get16(&p, p_end);
1247 val = get8(&p, p_end);
1250 desc_list_len = get16(&p, p_end) & 0xfff;
1251 if (desc_list_len < 0)
1253 desc_list_end = p + desc_list_len;
1254 if (desc_list_end > p_end)
1257 desc_tag = get8(&p, desc_list_end);
1260 desc_len = get8(&p, desc_list_end);
1261 desc_end = p + desc_len;
1262 if (desc_end > desc_list_end)
1265 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1266 desc_tag, desc_len);
1270 service_type = get8(&p, p_end);
1271 if (service_type < 0)
1273 provider_name = getstr8(&p, p_end);
1276 name = getstr8(&p, p_end);
1278 AVProgram *program = av_new_program(ts->stream, sid);
1280 av_dict_set(&program->metadata, "service_name", name, 0);
1281 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1285 av_free(provider_name);
1296 /* handle one TS packet */
1297 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1299 AVFormatContext *s = ts->stream;
1301 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1302 has_adaptation, has_payload;
1303 const uint8_t *p, *p_end;
1306 pid = AV_RB16(packet + 1) & 0x1fff;
1307 if(pid && discard_pid(ts, pid))
1309 is_start = packet[1] & 0x40;
1310 tss = ts->pids[pid];
1311 if (ts->auto_guess && tss == NULL && is_start) {
1312 add_pes_stream(ts, pid, -1);
1313 tss = ts->pids[pid];
1318 afc = (packet[3] >> 4) & 3;
1319 if (afc == 0) /* reserved value */
1321 has_adaptation = afc & 2;
1322 has_payload = afc & 1;
1323 is_discontinuity = has_adaptation
1324 && packet[4] != 0 /* with length > 0 */
1325 && (packet[5] & 0x80); /* and discontinuity indicated */
1327 /* continuity check (currently not used) */
1328 cc = (packet[3] & 0xf);
1329 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1330 cc_ok = pid == 0x1FFF // null packet PID
1333 || expected_cc == cc;
1337 av_log(ts->stream, AV_LOG_DEBUG,
1338 "Continuity check failed for pid %d expected %d got %d\n",
1339 pid, expected_cc, cc);
1340 if(tss->type == MPEGTS_PES) {
1341 PESContext *pc = tss->u.pes_filter.opaque;
1342 pc->flags |= AV_PKT_FLAG_CORRUPT;
1349 if (has_adaptation) {
1350 /* skip adapation field */
1353 /* if past the end of packet, ignore */
1354 p_end = packet + TS_PACKET_SIZE;
1358 pos = avio_tell(ts->stream->pb);
1359 ts->pos47= pos % ts->raw_packet_size;
1361 if (tss->type == MPEGTS_SECTION) {
1363 /* pointer field present */
1365 if (p + len > p_end)
1368 /* write remaining section bytes */
1369 write_section_data(s, tss,
1371 /* check whether filter has been closed */
1377 write_section_data(s, tss,
1382 write_section_data(s, tss,
1388 // Note: The position here points actually behind the current packet.
1389 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1390 pos - ts->raw_packet_size)) < 0)
1397 /* XXX: try to find a better synchro over several packets (use
1398 get_packet_size() ?) */
1399 static int mpegts_resync(AVFormatContext *s)
1401 AVIOContext *pb = s->pb;
1404 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1409 avio_seek(pb, -1, SEEK_CUR);
1413 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1418 /* return -1 if error or EOF. Return 0 if OK. */
1419 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1421 AVIOContext *pb = s->pb;
1425 len = avio_read(pb, buf, TS_PACKET_SIZE);
1426 if (len != TS_PACKET_SIZE)
1427 return len < 0 ? len : AVERROR_EOF;
1428 /* check paquet sync byte */
1429 if (buf[0] != 0x47) {
1430 /* find a new packet start */
1431 avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1432 if (mpegts_resync(s) < 0)
1433 return AVERROR(EAGAIN);
1437 skip = raw_packet_size - TS_PACKET_SIZE;
1439 avio_skip(pb, skip);
1446 static int handle_packets(MpegTSContext *ts, int nb_packets)
1448 AVFormatContext *s = ts->stream;
1449 uint8_t packet[TS_PACKET_SIZE];
1450 int packet_num, ret = 0;
1452 if (avio_tell(s->pb) != ts->last_pos) {
1454 av_dlog(ts->stream, "Skipping after seek\n");
1455 /* seek detected, flush pes buffer */
1456 for (i = 0; i < NB_PID_MAX; i++) {
1458 if (ts->pids[i]->type == MPEGTS_PES) {
1459 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1460 av_freep(&pes->buffer);
1461 pes->data_index = 0;
1462 pes->state = MPEGTS_SKIP; /* skip until pes header */
1464 ts->pids[i]->last_cc = -1;
1473 if (nb_packets != 0 && packet_num >= nb_packets ||
1474 ts->stop_parse > 1) {
1475 ret = AVERROR(EAGAIN);
1478 if (ts->stop_parse > 0)
1481 ret = read_packet(s, packet, ts->raw_packet_size);
1484 ret = handle_packet(ts, packet);
1488 ts->last_pos = avio_tell(s->pb);
1492 static int mpegts_probe(AVProbeData *p)
1495 const int size= p->buf_size;
1496 int score, fec_score, dvhs_score;
1497 int check_count= size / TS_FEC_PACKET_SIZE;
1498 #define CHECK_COUNT 10
1500 if (check_count < CHECK_COUNT)
1503 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1504 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1505 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1506 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1508 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1509 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1510 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1511 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1514 /* only use the extension for safer guess */
1515 if (av_match_ext(p->filename, "ts"))
1516 return AVPROBE_SCORE_MAX;
1522 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1523 (-1) if not available */
1524 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1525 const uint8_t *packet)
1527 int afc, len, flags;
1531 afc = (packet[3] >> 4) & 3;
1541 if (!(flags & 0x10))
1546 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1547 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1551 static int mpegts_read_header(AVFormatContext *s,
1552 AVFormatParameters *ap)
1554 MpegTSContext *ts = s->priv_data;
1555 AVIOContext *pb = s->pb;
1556 uint8_t buf[8*1024];
1560 /* read the first 8192 bytes to get packet size */
1561 pos = avio_tell(pb);
1562 len = avio_read(pb, buf, sizeof(buf));
1563 if (len != sizeof(buf))
1565 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1566 if (ts->raw_packet_size <= 0) {
1567 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
1568 ts->raw_packet_size = TS_PACKET_SIZE;
1573 if (s->iformat == &ff_mpegts_demuxer) {
1576 /* first do a scaning to get all the services */
1577 /* NOTE: We attempt to seek on non-seekable files as well, as the
1578 * probe buffer usually is big enough. Only warn if the seek failed
1579 * on files where the seek should work. */
1580 if (avio_seek(pb, pos, SEEK_SET) < 0)
1581 av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
1583 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1585 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1587 handle_packets(ts, s->probesize / ts->raw_packet_size);
1588 /* if could not find service, enable auto_guess */
1592 av_dlog(ts->stream, "tuning done\n");
1594 s->ctx_flags |= AVFMTCTX_NOHEADER;
1597 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1598 int64_t pcrs[2], pcr_h;
1599 int packet_count[2];
1600 uint8_t packet[TS_PACKET_SIZE];
1602 /* only read packets */
1604 st = avformat_new_stream(s, NULL);
1607 av_set_pts_info(st, 60, 1, 27000000);
1608 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1609 st->codec->codec_id = CODEC_ID_MPEG2TS;
1611 /* we iterate until we find two PCRs to estimate the bitrate */
1616 ret = read_packet(s, packet, ts->raw_packet_size);
1619 pid = AV_RB16(packet + 1) & 0x1fff;
1620 if ((pcr_pid == -1 || pcr_pid == pid) &&
1621 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1623 packet_count[nb_pcrs] = nb_packets;
1624 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1632 /* NOTE1: the bitrate is computed without the FEC */
1633 /* NOTE2: it is only the bitrate of the start of the stream */
1634 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1635 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1636 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1637 st->codec->bit_rate = s->bit_rate;
1638 st->start_time = ts->cur_pcr;
1639 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
1640 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1643 avio_seek(pb, pos, SEEK_SET);
1649 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1651 static int mpegts_raw_read_packet(AVFormatContext *s,
1654 MpegTSContext *ts = s->priv_data;
1656 int64_t pcr_h, next_pcr_h, pos;
1657 int pcr_l, next_pcr_l;
1658 uint8_t pcr_buf[12];
1660 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1661 return AVERROR(ENOMEM);
1662 pkt->pos= avio_tell(s->pb);
1663 ret = read_packet(s, pkt->data, ts->raw_packet_size);
1665 av_free_packet(pkt);
1668 if (ts->mpeg2ts_compute_pcr) {
1669 /* compute exact PCR for each packet */
1670 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1671 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1672 pos = avio_tell(s->pb);
1673 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1674 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1675 avio_read(s->pb, pcr_buf, 12);
1676 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1677 /* XXX: not precise enough */
1678 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1683 avio_seek(s->pb, pos, SEEK_SET);
1684 /* no next PCR found: we use previous increment */
1685 ts->cur_pcr = pcr_h * 300 + pcr_l;
1687 pkt->pts = ts->cur_pcr;
1688 pkt->duration = ts->pcr_incr;
1689 ts->cur_pcr += ts->pcr_incr;
1691 pkt->stream_index = 0;
1695 static int mpegts_read_packet(AVFormatContext *s,
1698 MpegTSContext *ts = s->priv_data;
1702 ret = handle_packets(ts, 0);
1704 /* flush pes data left */
1705 for (i = 0; i < NB_PID_MAX; i++) {
1706 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1707 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1708 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1709 new_pes_packet(pes, pkt);
1710 pes->state = MPEGTS_SKIP;
1721 static int mpegts_read_close(AVFormatContext *s)
1723 MpegTSContext *ts = s->priv_data;
1728 for(i=0;i<NB_PID_MAX;i++)
1729 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1734 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1735 int64_t *ppos, int64_t pos_limit)
1737 MpegTSContext *ts = s->priv_data;
1738 int64_t pos, timestamp;
1739 uint8_t buf[TS_PACKET_SIZE];
1740 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1741 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1742 while(pos < pos_limit) {
1743 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1744 return AV_NOPTS_VALUE;
1745 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1746 return AV_NOPTS_VALUE;
1747 if (buf[0] != 0x47) {
1748 if (mpegts_resync(s) < 0)
1749 return AV_NOPTS_VALUE;
1750 pos = url_ftell(s->pb);
1753 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1754 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1758 pos += ts->raw_packet_size;
1761 return AV_NOPTS_VALUE;
1764 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
1765 int64_t *ppos, int64_t pos_limit)
1767 MpegTSContext *ts = s->priv_data;
1768 int64_t pos, timestamp;
1769 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1770 ff_read_frame_flush(s);
1771 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1772 return AV_NOPTS_VALUE;
1773 while(pos < pos_limit) {
1776 av_init_packet(&pkt);
1777 ret= av_read_frame(s, &pkt);
1779 return AV_NOPTS_VALUE;
1780 av_free_packet(&pkt);
1781 if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
1782 ff_reduce_index(s, pkt.stream_index);
1783 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
1784 if(pkt.stream_index == stream_index){
1792 return AV_NOPTS_VALUE;
1795 #ifdef USE_SYNCPOINT_SEARCH
1797 static int read_seek2(AVFormatContext *s,
1806 int64_t ts_ret, ts_adj;
1807 int stream_index_gen_search;
1809 AVParserState *backup;
1811 backup = ff_store_parser_state(s);
1813 // detect direction of seeking for search purposes
1814 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
1815 AVSEEK_FLAG_BACKWARD : 0;
1817 if (flags & AVSEEK_FLAG_BYTE) {
1818 // use position directly, we will search starting from it
1821 // search for some position with good timestamp match
1822 if (stream_index < 0) {
1823 stream_index_gen_search = av_find_default_stream_index(s);
1824 if (stream_index_gen_search < 0) {
1825 ff_restore_parser_state(s, backup);
1829 st = s->streams[stream_index_gen_search];
1830 // timestamp for default must be expressed in AV_TIME_BASE units
1831 ts_adj = av_rescale(target_ts,
1833 AV_TIME_BASE * (int64_t)st->time_base.num);
1836 stream_index_gen_search = stream_index;
1838 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1842 flags, &ts_ret, mpegts_get_pcr);
1844 ff_restore_parser_state(s, backup);
1849 // search for actual matching keyframe/starting position for all streams
1850 if (ff_gen_syncpoint_search(s, stream_index, pos,
1851 min_ts, target_ts, max_ts,
1853 ff_restore_parser_state(s, backup);
1857 ff_free_parser_state(s, backup);
1861 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1864 if (flags & AVSEEK_FLAG_BACKWARD) {
1865 flags &= ~AVSEEK_FLAG_BACKWARD;
1866 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
1868 // for compatibility reasons, seek to the best-fitting timestamp
1869 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1871 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1873 // for compatibility reasons, seek to the best-fitting timestamp
1874 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1881 /**************************************************************/
1882 /* parsing functions - called from other demuxers such as RTP */
1884 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
1888 ts = av_mallocz(sizeof(MpegTSContext));
1891 /* no stream case, currently used by RTP */
1892 ts->raw_packet_size = TS_PACKET_SIZE;
1895 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1896 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1901 /* return the consumed length if a packet was output, or -1 if no
1903 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1904 const uint8_t *buf, int len)
1912 if (len < TS_PACKET_SIZE)
1914 if (buf[0] != 0x47) {
1918 handle_packet(ts, buf);
1919 buf += TS_PACKET_SIZE;
1920 len -= TS_PACKET_SIZE;
1921 if (ts->stop_parse == 1)
1928 void ff_mpegts_parse_close(MpegTSContext *ts)
1932 for(i=0;i<NB_PID_MAX;i++)
1933 av_free(ts->pids[i]);
1937 AVInputFormat ff_mpegts_demuxer = {
1939 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1940 .priv_data_size = sizeof(MpegTSContext),
1941 .read_probe = mpegts_probe,
1942 .read_header = mpegts_read_header,
1943 .read_packet = mpegts_read_packet,
1944 .read_close = mpegts_read_close,
1945 .read_timestamp = mpegts_get_dts,
1946 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1947 #ifdef USE_SYNCPOINT_SEARCH
1948 .read_seek2 = read_seek2,
1952 AVInputFormat ff_mpegtsraw_demuxer = {
1953 .name = "mpegtsraw",
1954 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1955 .priv_data_size = sizeof(MpegTSContext),
1956 .read_header = mpegts_read_header,
1957 .read_packet = mpegts_raw_read_packet,
1958 .read_close = mpegts_read_close,
1959 .read_timestamp = mpegts_get_dts,
1960 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1961 #ifdef USE_SYNCPOINT_SEARCH
1962 .read_seek2 = read_seek2,
1964 .priv_class = &mpegtsraw_class,