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
24 //#define USE_SYNCPOINT_SEARCH
26 #include "libavutil/crc.h"
27 #include "libavutil/intreadwrite.h"
28 #include "libavcodec/bytestream.h"
36 /* maximum size in which we look for synchronisation if
37 synchronisation is lost */
38 #define MAX_RESYNC_SIZE 65536
40 #define MAX_PES_PAYLOAD 200*1024
42 enum MpegTSFilterType {
47 typedef struct MpegTSFilter MpegTSFilter;
49 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
51 typedef struct MpegTSPESFilter {
56 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
58 typedef void SetServiceCallback(void *opaque, int ret);
60 typedef struct MpegTSSectionFilter {
64 unsigned int check_crc:1;
65 unsigned int end_of_section_reached:1;
66 SectionCallback *section_cb;
68 } MpegTSSectionFilter;
72 int last_cc; /* last cc code (-1 if first packet) */
73 enum MpegTSFilterType type;
75 MpegTSPESFilter pes_filter;
76 MpegTSSectionFilter section_filter;
80 #define MAX_PIDS_PER_PROGRAM 64
82 unsigned int id; //program id/service id
84 unsigned int pids[MAX_PIDS_PER_PROGRAM];
87 struct MpegTSContext {
89 AVFormatContext *stream;
90 /** raw packet size, including FEC if present */
95 /** if true, all pids are analyzed to find streams */
98 /** compute exact PCR for each transport stream packet */
99 int mpeg2ts_compute_pcr;
101 int64_t cur_pcr; /**< used to estimate the exact PCR */
102 int pcr_incr; /**< used to estimate the exact PCR */
104 /* data needed to handle file based ts */
105 /** stop parsing loop */
107 /** packet containing Audio/Video data */
109 /** to detect seek */
112 /******************************************/
113 /* private mpegts data */
115 /** structure to keep track of Program->pids mapping */
120 /** filters for various streams specified by PMT + for the PAT and PMT */
121 MpegTSFilter *pids[NB_PID_MAX];
124 /* TS stream handling */
129 MPEGTS_PESHEADER_FILL,
134 /* enough for PES header + length */
135 #define PES_START_SIZE 6
136 #define PES_HEADER_SIZE 9
137 #define MAX_PES_HEADER_SIZE (9 + 255)
139 typedef struct PESContext {
141 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
144 AVFormatContext *stream;
146 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
147 enum MpegTSState state;
148 /* used to get the format */
152 int extended_stream_id;
154 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
155 uint8_t header[MAX_PES_HEADER_SIZE];
159 extern AVInputFormat ff_mpegts_demuxer;
161 static void clear_program(MpegTSContext *ts, unsigned int programid)
165 for(i=0; i<ts->nb_prg; i++)
166 if(ts->prg[i].id == programid)
167 ts->prg[i].nb_pids = 0;
170 static void clear_programs(MpegTSContext *ts)
176 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
179 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
183 p = &ts->prg[ts->nb_prg];
189 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
192 struct Program *p = NULL;
193 for(i=0; i<ts->nb_prg; i++) {
194 if(ts->prg[i].id == programid) {
202 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
204 p->pids[p->nb_pids++] = pid;
208 * \brief discard_pid() decides if the pid is to be discarded according
209 * to caller's programs selection
210 * \param ts : - TS context
212 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
215 static int discard_pid(MpegTSContext *ts, unsigned int pid)
218 int used = 0, discarded = 0;
220 for(i=0; i<ts->nb_prg; i++) {
222 for(j=0; j<p->nb_pids; j++) {
223 if(p->pids[j] != pid)
225 //is program with id p->id set to be discarded?
226 for(k=0; k<ts->stream->nb_programs; k++) {
227 if(ts->stream->programs[k]->id == p->id) {
228 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
237 return !used && discarded;
241 * Assemble PES packets out of TS packets, and then call the "section_cb"
242 * function when they are complete.
244 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
245 const uint8_t *buf, int buf_size, int is_start)
247 MpegTSSectionFilter *tss = &tss1->u.section_filter;
251 memcpy(tss->section_buf, buf, buf_size);
252 tss->section_index = buf_size;
253 tss->section_h_size = -1;
254 tss->end_of_section_reached = 0;
256 if (tss->end_of_section_reached)
258 len = 4096 - tss->section_index;
261 memcpy(tss->section_buf + tss->section_index, buf, len);
262 tss->section_index += len;
265 /* compute section length if possible */
266 if (tss->section_h_size == -1 && tss->section_index >= 3) {
267 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
270 tss->section_h_size = len;
273 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
274 tss->end_of_section_reached = 1;
275 if (!tss->check_crc ||
276 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
277 tss->section_buf, tss->section_h_size) == 0)
278 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
282 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
283 SectionCallback *section_cb, void *opaque,
287 MpegTSFilter *filter;
288 MpegTSSectionFilter *sec;
290 av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
292 if (pid >= NB_PID_MAX || ts->pids[pid])
294 filter = av_mallocz(sizeof(MpegTSFilter));
297 ts->pids[pid] = filter;
298 filter->type = MPEGTS_SECTION;
300 filter->last_cc = -1;
301 sec = &filter->u.section_filter;
302 sec->section_cb = section_cb;
303 sec->opaque = opaque;
304 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
305 sec->check_crc = check_crc;
306 if (!sec->section_buf) {
313 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
317 MpegTSFilter *filter;
318 MpegTSPESFilter *pes;
320 if (pid >= NB_PID_MAX || ts->pids[pid])
322 filter = av_mallocz(sizeof(MpegTSFilter));
325 ts->pids[pid] = filter;
326 filter->type = MPEGTS_PES;
328 filter->last_cc = -1;
329 pes = &filter->u.pes_filter;
330 pes->pes_cb = pes_cb;
331 pes->opaque = opaque;
335 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
340 if (filter->type == MPEGTS_SECTION)
341 av_freep(&filter->u.section_filter.section_buf);
342 else if (filter->type == MPEGTS_PES) {
343 PESContext *pes = filter->u.pes_filter.opaque;
344 av_freep(&pes->buffer);
345 /* referenced private data will be freed later in
346 * av_close_input_stream */
347 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
348 av_freep(&filter->u.pes_filter.opaque);
353 ts->pids[pid] = NULL;
356 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
357 int stat[TS_MAX_PACKET_SIZE];
362 memset(stat, 0, packet_size*sizeof(int));
364 for(x=i=0; i<size-3; i++){
365 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
367 if(stat[x] > best_score){
374 if(x == packet_size) x= 0;
380 /* autodetect fec presence. Must have at least 1024 bytes */
381 static int get_packet_size(const uint8_t *buf, int size)
383 int score, fec_score, dvhs_score;
385 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
388 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
389 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
390 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
391 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
393 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
394 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
395 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
399 typedef struct SectionHeader {
404 uint8_t last_sec_num;
407 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
420 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
426 if ((p + 1) >= p_end)
434 /* read and allocate a DVB string preceeded by its length */
435 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
442 len = get8(&p, p_end);
445 if ((p + len) > p_end)
447 str = av_malloc(len + 1);
457 static int parse_section_header(SectionHeader *h,
458 const uint8_t **pp, const uint8_t *p_end)
462 val = get8(pp, p_end);
467 val = get16(pp, p_end);
471 val = get8(pp, p_end);
474 h->version = (val >> 1) & 0x1f;
475 val = get8(pp, p_end);
479 val = get8(pp, p_end);
482 h->last_sec_num = val;
487 uint32_t stream_type;
488 enum AVMediaType codec_type;
489 enum CodecID codec_id;
492 static const StreamType ISO_types[] = {
493 { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
494 { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
495 { 0x03, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
496 { 0x04, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
497 { 0x0f, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC },
498 { 0x10, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4 },
499 { 0x11, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC_LATM }, /* LATM syntax */
500 { 0x1b, AVMEDIA_TYPE_VIDEO, CODEC_ID_H264 },
501 { 0xd1, AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
502 { 0xea, AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
506 static const StreamType HDMV_types[] = {
507 { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
508 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
509 { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
510 { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
511 { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
512 { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
517 static const StreamType MISC_types[] = {
518 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
519 { 0x8a, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
523 static const StreamType REGD_types[] = {
524 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
525 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
529 /* descriptor present */
530 static const StreamType DESC_types[] = {
531 { 0x6a, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
532 { 0x7a, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
533 { 0x7b, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
534 { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
535 { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
539 static void mpegts_find_stream_type(AVStream *st,
540 uint32_t stream_type, const StreamType *types)
542 for (; types->stream_type; types++) {
543 if (stream_type == types->stream_type) {
544 st->codec->codec_type = types->codec_type;
545 st->codec->codec_id = types->codec_id;
551 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
552 uint32_t stream_type, uint32_t prog_reg_desc)
554 av_set_pts_info(st, 33, 1, 90000);
556 st->codec->codec_type = AVMEDIA_TYPE_DATA;
557 st->codec->codec_id = CODEC_ID_NONE;
558 st->need_parsing = AVSTREAM_PARSE_FULL;
560 pes->stream_type = stream_type;
562 av_log(pes->stream, AV_LOG_DEBUG,
563 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
564 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
566 st->codec->codec_tag = pes->stream_type;
568 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
569 if (prog_reg_desc == AV_RL32("HDMV") &&
570 st->codec->codec_id == CODEC_ID_NONE) {
571 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
572 if (pes->stream_type == 0x83) {
573 // HDMV TrueHD streams also contain an AC3 coded version of the
574 // audio track - add a second stream for this
576 // priv_data cannot be shared between streams
577 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
579 return AVERROR(ENOMEM);
580 memcpy(sub_pes, pes, sizeof(*sub_pes));
582 sub_st = av_new_stream(pes->stream, pes->pid);
585 return AVERROR(ENOMEM);
588 av_set_pts_info(sub_st, 33, 1, 90000);
589 sub_st->priv_data = sub_pes;
590 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
591 sub_st->codec->codec_id = CODEC_ID_AC3;
592 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
593 sub_pes->sub_st = pes->sub_st = sub_st;
596 if (st->codec->codec_id == CODEC_ID_NONE)
597 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
602 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
606 pkt->destruct = av_destruct_packet;
607 pkt->data = pes->buffer;
608 pkt->size = pes->data_index;
609 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
611 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
612 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
613 pkt->stream_index = pes->sub_st->index;
615 pkt->stream_index = pes->st->index;
618 /* store position of first TS packet of this PES packet */
619 pkt->pos = pes->ts_packet_pos;
621 /* reset pts values */
622 pes->pts = AV_NOPTS_VALUE;
623 pes->dts = AV_NOPTS_VALUE;
628 /* return non zero if a packet could be constructed */
629 static int mpegts_push_data(MpegTSFilter *filter,
630 const uint8_t *buf, int buf_size, int is_start,
633 PESContext *pes = filter->u.pes_filter.opaque;
634 MpegTSContext *ts = pes->ts;
642 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
643 new_pes_packet(pes, ts->pkt);
646 pes->state = MPEGTS_HEADER;
648 pes->ts_packet_pos = pos;
651 while (buf_size > 0) {
654 len = PES_START_SIZE - pes->data_index;
657 memcpy(pes->header + pes->data_index, p, len);
658 pes->data_index += len;
661 if (pes->data_index == PES_START_SIZE) {
662 /* we got all the PES or section header. We can now
665 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
667 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
668 pes->header[2] == 0x01) {
669 /* it must be an mpeg2 PES stream */
670 code = pes->header[3] | 0x100;
671 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
673 if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
674 code == 0x1be) /* padding_stream */
677 #if FF_API_MAX_STREAMS
678 if (!pes->st && pes->stream->nb_streams == MAX_STREAMS)
682 /* stream not present in PMT */
684 pes->st = av_new_stream(ts->stream, pes->pid);
686 return AVERROR(ENOMEM);
687 mpegts_set_stream_info(pes->st, pes, 0, 0);
690 pes->total_size = AV_RB16(pes->header + 4);
691 /* NOTE: a zero total size means the PES size is
693 if (!pes->total_size)
694 pes->total_size = MAX_PES_PAYLOAD;
696 /* allocate pes buffer */
697 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
699 return AVERROR(ENOMEM);
701 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
702 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
703 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
704 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
705 pes->state = MPEGTS_PESHEADER;
706 if (pes->st->codec->codec_id == CODEC_ID_NONE) {
707 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
708 pes->pid, pes->stream_type);
709 pes->st->codec->codec_id = CODEC_ID_PROBE;
712 pes->state = MPEGTS_PAYLOAD;
716 /* otherwise, it should be a table */
719 pes->state = MPEGTS_SKIP;
724 /**********************************************/
725 /* PES packing parsing */
726 case MPEGTS_PESHEADER:
727 len = PES_HEADER_SIZE - pes->data_index;
732 memcpy(pes->header + pes->data_index, p, len);
733 pes->data_index += len;
736 if (pes->data_index == PES_HEADER_SIZE) {
737 pes->pes_header_size = pes->header[8] + 9;
738 pes->state = MPEGTS_PESHEADER_FILL;
741 case MPEGTS_PESHEADER_FILL:
742 len = pes->pes_header_size - pes->data_index;
747 memcpy(pes->header + pes->data_index, p, len);
748 pes->data_index += len;
751 if (pes->data_index == pes->pes_header_size) {
753 unsigned int flags, pes_ext, skip;
755 flags = pes->header[7];
757 pes->pts = AV_NOPTS_VALUE;
758 pes->dts = AV_NOPTS_VALUE;
759 if ((flags & 0xc0) == 0x80) {
760 pes->dts = pes->pts = ff_parse_pes_pts(r);
762 } else if ((flags & 0xc0) == 0xc0) {
763 pes->pts = ff_parse_pes_pts(r);
765 pes->dts = ff_parse_pes_pts(r);
768 pes->extended_stream_id = -1;
769 if (flags & 0x01) { /* PES extension */
771 /* Skip PES private data, program packet sequence counter and P-STD buffer */
772 skip = (pes_ext >> 4) & 0xb;
775 if ((pes_ext & 0x41) == 0x01 &&
776 (r + 2) <= (pes->header + pes->pes_header_size)) {
777 /* PES extension 2 */
778 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
779 pes->extended_stream_id = r[1];
783 /* we got the full header. We parse it and get the payload */
784 pes->state = MPEGTS_PAYLOAD;
789 if (buf_size > 0 && pes->buffer) {
790 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
791 new_pes_packet(pes, ts->pkt);
792 pes->total_size = MAX_PES_PAYLOAD;
793 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
795 return AVERROR(ENOMEM);
797 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
798 // pes packet size is < ts size packet and pes data is padded with 0xff
799 // not sure if this is legal in ts but see issue #2392
800 buf_size = pes->total_size;
802 memcpy(pes->buffer+pes->data_index, p, buf_size);
803 pes->data_index += buf_size;
806 /* emit complete packets with known packet size
807 * decreases demuxer delay for infrequent packets like subtitles from
808 * a couple of seconds to milliseconds for properly muxed files.
809 * total_size is the number of bytes following pes_packet_length
810 * in the pes header, i.e. not counting the first 6 bytes */
811 if (pes->total_size < MAX_PES_PAYLOAD &&
812 pes->pes_header_size + pes->data_index == pes->total_size + 6) {
814 new_pes_packet(pes, ts->pkt);
826 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
831 /* if no pid found, then add a pid context */
832 pes = av_mallocz(sizeof(PESContext));
836 pes->stream = ts->stream;
838 pes->pcr_pid = pcr_pid;
839 pes->state = MPEGTS_SKIP;
840 pes->pts = AV_NOPTS_VALUE;
841 pes->dts = AV_NOPTS_VALUE;
842 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
850 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
851 int *es_id, uint8_t **dec_config_descr,
852 int *dec_config_descr_size)
858 init_put_byte(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
860 len = ff_mp4_read_descr(s, &pb, &tag);
861 if (tag == MP4IODescrTag) {
868 len = ff_mp4_read_descr(s, &pb, &tag);
869 if (tag == MP4ESDescrTag) {
870 *es_id = get_be16(&pb); /* ES_ID */
871 av_dlog(s, "ES_ID %#x\n", *es_id);
872 get_byte(&pb); /* priority */
873 len = ff_mp4_read_descr(s, &pb, &tag);
874 if (tag == MP4DecConfigDescrTag) {
875 *dec_config_descr = av_malloc(len);
876 if (!*dec_config_descr)
877 return AVERROR(ENOMEM);
878 *dec_config_descr_size = len;
879 get_buffer(&pb, *dec_config_descr, len);
886 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
887 const uint8_t **pp, const uint8_t *desc_list_end,
888 int mp4_dec_config_descr_len, int mp4_es_id, int pid,
889 uint8_t *mp4_dec_config_descr)
891 const uint8_t *desc_end;
892 int desc_len, desc_tag;
895 desc_tag = get8(pp, desc_list_end);
898 desc_len = get8(pp, desc_list_end);
901 desc_end = *pp + desc_len;
902 if (desc_end > desc_list_end)
905 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
907 if (st->codec->codec_id == CODEC_ID_NONE &&
908 stream_type == STREAM_TYPE_PRIVATE_DATA)
909 mpegts_find_stream_type(st, desc_tag, DESC_types);
912 case 0x1F: /* FMC descriptor */
914 if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
915 mp4_dec_config_descr_len && mp4_es_id == pid) {
917 init_put_byte(&pb, mp4_dec_config_descr,
918 mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
919 ff_mp4_read_dec_config_descr(fc, st, &pb);
920 if (st->codec->codec_id == CODEC_ID_AAC &&
921 st->codec->extradata_size > 0)
922 st->need_parsing = 0;
925 case 0x56: /* DVB teletext descriptor */
926 language[0] = get8(pp, desc_end);
927 language[1] = get8(pp, desc_end);
928 language[2] = get8(pp, desc_end);
930 av_metadata_set2(&st->metadata, "language", language, 0);
932 case 0x59: /* subtitling descriptor */
933 language[0] = get8(pp, desc_end);
934 language[1] = get8(pp, desc_end);
935 language[2] = get8(pp, desc_end);
938 if (st->codec->extradata) {
939 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
940 av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
942 st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
943 if (st->codec->extradata) {
944 st->codec->extradata_size = 4;
945 memcpy(st->codec->extradata, *pp, 4);
949 av_metadata_set2(&st->metadata, "language", language, 0);
951 case 0x0a: /* ISO 639 language descriptor */
952 language[0] = get8(pp, desc_end);
953 language[1] = get8(pp, desc_end);
954 language[2] = get8(pp, desc_end);
956 av_metadata_set2(&st->metadata, "language", language, 0);
957 switch (get8(pp, desc_end)) {
958 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
959 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
960 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
963 case 0x05: /* registration descriptor */
964 st->codec->codec_tag = bytestream_get_le32(pp);
965 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
966 if (st->codec->codec_id == CODEC_ID_NONE &&
967 stream_type == STREAM_TYPE_PRIVATE_DATA)
968 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
977 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
979 MpegTSContext *ts = filter->u.section_filter.opaque;
980 SectionHeader h1, *h = &h1;
983 const uint8_t *p, *p_end, *desc_list_end;
984 int program_info_length, pcr_pid, pid, stream_type;
986 uint32_t prog_reg_desc = 0; /* registration descriptor */
987 uint8_t *mp4_dec_config_descr = NULL;
988 int mp4_dec_config_descr_len = 0;
992 av_dlog(ts->stream, "PMT: len %i\n", section_len);
993 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
996 p_end = section + section_len - 4;
998 if (parse_section_header(h, &p, p_end) < 0)
1001 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1002 h->id, h->sec_num, h->last_sec_num);
1004 if (h->tid != PMT_TID)
1007 clear_program(ts, h->id);
1008 pcr_pid = get16(&p, p_end) & 0x1fff;
1011 add_pid_to_pmt(ts, h->id, pcr_pid);
1013 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1015 program_info_length = get16(&p, p_end) & 0xfff;
1016 if (program_info_length < 0)
1018 while(program_info_length >= 2) {
1020 tag = get8(&p, p_end);
1021 len = get8(&p, p_end);
1023 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1025 if(len > program_info_length - 2)
1026 //something else is broken, exit the program_descriptors_loop
1028 program_info_length -= len + 2;
1029 if (tag == 0x1d) { // IOD descriptor
1030 get8(&p, p_end); // scope
1031 get8(&p, p_end); // label
1033 mp4_read_iods(ts->stream, p, len, &mp4_es_id,
1034 &mp4_dec_config_descr, &mp4_dec_config_descr_len);
1035 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1036 prog_reg_desc = bytestream_get_le32(&p);
1041 p += program_info_length;
1045 // stop parsing after pmt, we found header
1046 if (!ts->stream->nb_streams)
1051 stream_type = get8(&p, p_end);
1052 if (stream_type < 0)
1054 pid = get16(&p, p_end) & 0x1fff;
1058 /* now create ffmpeg stream */
1059 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1060 pes = ts->pids[pid]->u.pes_filter.opaque;
1062 pes->st = av_new_stream(pes->stream, pes->pid);
1065 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1066 pes = add_pes_stream(ts, pid, pcr_pid);
1068 st = av_new_stream(pes->stream, pes->pid);
1074 if (!pes->stream_type)
1075 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1077 add_pid_to_pmt(ts, h->id, pid);
1079 ff_program_add_stream_index(ts->stream, h->id, st->index);
1081 desc_list_len = get16(&p, p_end) & 0xfff;
1082 if (desc_list_len < 0)
1084 desc_list_end = p + desc_list_len;
1085 if (desc_list_end > p_end)
1088 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1089 mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
1092 if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1093 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1094 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1101 av_free(mp4_dec_config_descr);
1104 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1106 MpegTSContext *ts = filter->u.section_filter.opaque;
1107 SectionHeader h1, *h = &h1;
1108 const uint8_t *p, *p_end;
1112 av_dlog(ts->stream, "PAT:\n");
1113 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1115 p_end = section + section_len - 4;
1117 if (parse_section_header(h, &p, p_end) < 0)
1119 if (h->tid != PAT_TID)
1124 sid = get16(&p, p_end);
1127 pmt_pid = get16(&p, p_end) & 0x1fff;
1131 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1133 if (sid == 0x0000) {
1136 av_new_program(ts->stream, sid);
1137 if (ts->pids[pmt_pid])
1138 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1139 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1140 add_pat_entry(ts, sid);
1141 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1142 add_pid_to_pmt(ts, sid, pmt_pid);
1147 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1149 MpegTSContext *ts = filter->u.section_filter.opaque;
1150 SectionHeader h1, *h = &h1;
1151 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1152 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1153 char *name, *provider_name;
1156 av_dlog(ts->stream, "SDT:\n");
1157 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1160 p_end = section + section_len - 4;
1162 if (parse_section_header(h, &p, p_end) < 0)
1164 if (h->tid != SDT_TID)
1166 onid = get16(&p, p_end);
1169 val = get8(&p, p_end);
1173 sid = get16(&p, p_end);
1176 val = get8(&p, p_end);
1179 desc_list_len = get16(&p, p_end) & 0xfff;
1180 if (desc_list_len < 0)
1182 desc_list_end = p + desc_list_len;
1183 if (desc_list_end > p_end)
1186 desc_tag = get8(&p, desc_list_end);
1189 desc_len = get8(&p, desc_list_end);
1190 desc_end = p + desc_len;
1191 if (desc_end > desc_list_end)
1194 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1195 desc_tag, desc_len);
1199 service_type = get8(&p, p_end);
1200 if (service_type < 0)
1202 provider_name = getstr8(&p, p_end);
1205 name = getstr8(&p, p_end);
1207 AVProgram *program = av_new_program(ts->stream, sid);
1209 av_metadata_set2(&program->metadata, "service_name", name, 0);
1210 av_metadata_set2(&program->metadata, "service_provider", provider_name, 0);
1214 av_free(provider_name);
1225 /* handle one TS packet */
1226 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1228 AVFormatContext *s = ts->stream;
1230 int len, pid, cc, cc_ok, afc, is_start;
1231 const uint8_t *p, *p_end;
1234 pid = AV_RB16(packet + 1) & 0x1fff;
1235 if(pid && discard_pid(ts, pid))
1237 is_start = packet[1] & 0x40;
1238 tss = ts->pids[pid];
1239 if (ts->auto_guess && tss == NULL && is_start) {
1240 add_pes_stream(ts, pid, -1);
1241 tss = ts->pids[pid];
1246 /* continuity check (currently not used) */
1247 cc = (packet[3] & 0xf);
1248 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1251 /* skip adaptation field */
1252 afc = (packet[3] >> 4) & 3;
1254 if (afc == 0) /* reserved value */
1256 if (afc == 2) /* adaptation field only */
1259 /* skip adapation field */
1262 /* if past the end of packet, ignore */
1263 p_end = packet + TS_PACKET_SIZE;
1267 pos = url_ftell(ts->stream->pb);
1268 ts->pos47= pos % ts->raw_packet_size;
1270 if (tss->type == MPEGTS_SECTION) {
1272 /* pointer field present */
1274 if (p + len > p_end)
1277 /* write remaining section bytes */
1278 write_section_data(s, tss,
1280 /* check whether filter has been closed */
1286 write_section_data(s, tss,
1291 write_section_data(s, tss,
1297 // Note: The position here points actually behind the current packet.
1298 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1299 pos - ts->raw_packet_size)) < 0)
1306 /* XXX: try to find a better synchro over several packets (use
1307 get_packet_size() ?) */
1308 static int mpegts_resync(AVFormatContext *s)
1310 ByteIOContext *pb = s->pb;
1313 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1318 url_fseek(pb, -1, SEEK_CUR);
1322 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1327 /* return -1 if error or EOF. Return 0 if OK. */
1328 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1330 ByteIOContext *pb = s->pb;
1334 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1335 if (len != TS_PACKET_SIZE)
1336 return AVERROR(EIO);
1337 /* check paquet sync byte */
1338 if (buf[0] != 0x47) {
1339 /* find a new packet start */
1340 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1341 if (mpegts_resync(s) < 0)
1342 return AVERROR(EAGAIN);
1346 skip = raw_packet_size - TS_PACKET_SIZE;
1348 url_fskip(pb, skip);
1355 static int handle_packets(MpegTSContext *ts, int nb_packets)
1357 AVFormatContext *s = ts->stream;
1358 uint8_t packet[TS_PACKET_SIZE];
1359 int packet_num, ret;
1364 if (ts->stop_parse>0)
1367 if (nb_packets != 0 && packet_num >= nb_packets)
1369 ret = read_packet(s, packet, ts->raw_packet_size);
1372 ret = handle_packet(ts, packet);
1379 static int mpegts_probe(AVProbeData *p)
1382 const int size= p->buf_size;
1383 int score, fec_score, dvhs_score;
1384 int check_count= size / TS_FEC_PACKET_SIZE;
1385 #define CHECK_COUNT 10
1387 if (check_count < CHECK_COUNT)
1390 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1391 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1392 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1393 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1395 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1396 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1397 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1398 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1401 /* only use the extension for safer guess */
1402 if (av_match_ext(p->filename, "ts"))
1403 return AVPROBE_SCORE_MAX;
1409 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1410 (-1) if not available */
1411 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1412 const uint8_t *packet)
1414 int afc, len, flags;
1418 afc = (packet[3] >> 4) & 3;
1428 if (!(flags & 0x10))
1433 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1434 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1438 static int mpegts_read_header(AVFormatContext *s,
1439 AVFormatParameters *ap)
1441 MpegTSContext *ts = s->priv_data;
1442 ByteIOContext *pb = s->pb;
1443 uint8_t buf[5*1024];
1448 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1449 if(ap->mpeg2ts_raw){
1450 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1455 /* read the first 1024 bytes to get packet size */
1456 pos = url_ftell(pb);
1457 len = get_buffer(pb, buf, sizeof(buf));
1458 if (len != sizeof(buf))
1460 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1461 if (ts->raw_packet_size <= 0)
1466 if (s->iformat == &ff_mpegts_demuxer) {
1469 /* first do a scaning to get all the services */
1470 if (url_fseek(pb, pos, SEEK_SET) < 0)
1471 av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1473 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1475 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1477 handle_packets(ts, s->probesize / ts->raw_packet_size);
1478 /* if could not find service, enable auto_guess */
1482 av_dlog(ts->stream, "tuning done\n");
1484 s->ctx_flags |= AVFMTCTX_NOHEADER;
1487 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1488 int64_t pcrs[2], pcr_h;
1489 int packet_count[2];
1490 uint8_t packet[TS_PACKET_SIZE];
1492 /* only read packets */
1494 st = av_new_stream(s, 0);
1497 av_set_pts_info(st, 60, 1, 27000000);
1498 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1499 st->codec->codec_id = CODEC_ID_MPEG2TS;
1501 /* we iterate until we find two PCRs to estimate the bitrate */
1506 ret = read_packet(s, packet, ts->raw_packet_size);
1509 pid = AV_RB16(packet + 1) & 0x1fff;
1510 if ((pcr_pid == -1 || pcr_pid == pid) &&
1511 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1513 packet_count[nb_pcrs] = nb_packets;
1514 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1522 /* NOTE1: the bitrate is computed without the FEC */
1523 /* NOTE2: it is only the bitrate of the start of the stream */
1524 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1525 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1526 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1527 st->codec->bit_rate = s->bit_rate;
1528 st->start_time = ts->cur_pcr;
1530 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1531 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1535 url_fseek(pb, pos, SEEK_SET);
1541 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1543 static int mpegts_raw_read_packet(AVFormatContext *s,
1546 MpegTSContext *ts = s->priv_data;
1548 int64_t pcr_h, next_pcr_h, pos;
1549 int pcr_l, next_pcr_l;
1550 uint8_t pcr_buf[12];
1552 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1553 return AVERROR(ENOMEM);
1554 pkt->pos= url_ftell(s->pb);
1555 ret = read_packet(s, pkt->data, ts->raw_packet_size);
1557 av_free_packet(pkt);
1560 if (ts->mpeg2ts_compute_pcr) {
1561 /* compute exact PCR for each packet */
1562 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1563 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1564 pos = url_ftell(s->pb);
1565 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1566 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1567 get_buffer(s->pb, pcr_buf, 12);
1568 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1569 /* XXX: not precise enough */
1570 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1575 url_fseek(s->pb, pos, SEEK_SET);
1576 /* no next PCR found: we use previous increment */
1577 ts->cur_pcr = pcr_h * 300 + pcr_l;
1579 pkt->pts = ts->cur_pcr;
1580 pkt->duration = ts->pcr_incr;
1581 ts->cur_pcr += ts->pcr_incr;
1583 pkt->stream_index = 0;
1587 static int mpegts_read_packet(AVFormatContext *s,
1590 MpegTSContext *ts = s->priv_data;
1593 if (url_ftell(s->pb) != ts->last_pos) {
1594 /* seek detected, flush pes buffer */
1595 for (i = 0; i < NB_PID_MAX; i++) {
1596 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1597 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1598 av_freep(&pes->buffer);
1599 pes->data_index = 0;
1600 pes->state = MPEGTS_SKIP; /* skip until pes header */
1606 ret = handle_packets(ts, 0);
1608 /* flush pes data left */
1609 for (i = 0; i < NB_PID_MAX; i++) {
1610 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1611 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1612 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1613 new_pes_packet(pes, pkt);
1614 pes->state = MPEGTS_SKIP;
1622 ts->last_pos = url_ftell(s->pb);
1627 static int mpegts_read_close(AVFormatContext *s)
1629 MpegTSContext *ts = s->priv_data;
1634 for(i=0;i<NB_PID_MAX;i++)
1635 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1640 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1641 int64_t *ppos, int64_t pos_limit)
1643 MpegTSContext *ts = s->priv_data;
1644 int64_t pos, timestamp;
1645 uint8_t buf[TS_PACKET_SIZE];
1646 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1647 const int find_next= 1;
1648 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1651 url_fseek(s->pb, pos, SEEK_SET);
1652 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1653 return AV_NOPTS_VALUE;
1654 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1655 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1658 pos += ts->raw_packet_size;
1662 pos -= ts->raw_packet_size;
1664 return AV_NOPTS_VALUE;
1665 url_fseek(s->pb, pos, SEEK_SET);
1666 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1667 return AV_NOPTS_VALUE;
1668 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1669 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1679 #ifdef USE_SYNCPOINT_SEARCH
1681 static int read_seek2(AVFormatContext *s,
1690 int64_t ts_ret, ts_adj;
1691 int stream_index_gen_search;
1693 AVParserState *backup;
1695 backup = ff_store_parser_state(s);
1697 // detect direction of seeking for search purposes
1698 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
1699 AVSEEK_FLAG_BACKWARD : 0;
1701 if (flags & AVSEEK_FLAG_BYTE) {
1702 // use position directly, we will search starting from it
1705 // search for some position with good timestamp match
1706 if (stream_index < 0) {
1707 stream_index_gen_search = av_find_default_stream_index(s);
1708 if (stream_index_gen_search < 0) {
1709 ff_restore_parser_state(s, backup);
1713 st = s->streams[stream_index_gen_search];
1714 // timestamp for default must be expressed in AV_TIME_BASE units
1715 ts_adj = av_rescale(target_ts,
1717 AV_TIME_BASE * (int64_t)st->time_base.num);
1720 stream_index_gen_search = stream_index;
1722 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1726 flags, &ts_ret, mpegts_get_pcr);
1728 ff_restore_parser_state(s, backup);
1733 // search for actual matching keyframe/starting position for all streams
1734 if (ff_gen_syncpoint_search(s, stream_index, pos,
1735 min_ts, target_ts, max_ts,
1737 ff_restore_parser_state(s, backup);
1741 ff_free_parser_state(s, backup);
1745 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1748 if (flags & AVSEEK_FLAG_BACKWARD) {
1749 flags &= ~AVSEEK_FLAG_BACKWARD;
1750 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
1752 // for compatibility reasons, seek to the best-fitting timestamp
1753 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1755 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1757 // for compatibility reasons, seek to the best-fitting timestamp
1758 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1765 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1766 MpegTSContext *ts = s->priv_data;
1767 uint8_t buf[TS_PACKET_SIZE];
1770 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1773 pos= url_ftell(s->pb);
1776 url_fseek(s->pb, pos, SEEK_SET);
1777 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1779 // pid = AV_RB16(buf + 1) & 0x1fff;
1780 if(buf[1] & 0x40) break;
1781 pos += ts->raw_packet_size;
1783 url_fseek(s->pb, pos, SEEK_SET);
1790 /**************************************************************/
1791 /* parsing functions - called from other demuxers such as RTP */
1793 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
1797 ts = av_mallocz(sizeof(MpegTSContext));
1800 /* no stream case, currently used by RTP */
1801 ts->raw_packet_size = TS_PACKET_SIZE;
1807 /* return the consumed length if a packet was output, or -1 if no
1809 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1810 const uint8_t *buf, int len)
1818 if (ts->stop_parse>0)
1820 if (len < TS_PACKET_SIZE)
1822 if (buf[0] != 0x47) {
1826 handle_packet(ts, buf);
1827 buf += TS_PACKET_SIZE;
1828 len -= TS_PACKET_SIZE;
1834 void ff_mpegts_parse_close(MpegTSContext *ts)
1838 for(i=0;i<NB_PID_MAX;i++)
1839 av_free(ts->pids[i]);
1843 AVInputFormat ff_mpegts_demuxer = {
1845 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1846 sizeof(MpegTSContext),
1853 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1854 #ifdef USE_SYNCPOINT_SEARCH
1855 .read_seek2 = read_seek2,
1859 AVInputFormat ff_mpegtsraw_demuxer = {
1861 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1862 sizeof(MpegTSContext),
1865 mpegts_raw_read_packet,
1869 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1870 #ifdef USE_SYNCPOINT_SEARCH
1871 .read_seek2 = read_seek2,