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);
958 case 0x05: /* registration descriptor */
959 st->codec->codec_tag = bytestream_get_le32(pp);
960 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
961 if (st->codec->codec_id == CODEC_ID_NONE &&
962 stream_type == STREAM_TYPE_PRIVATE_DATA)
963 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
972 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
974 MpegTSContext *ts = filter->u.section_filter.opaque;
975 SectionHeader h1, *h = &h1;
978 const uint8_t *p, *p_end, *desc_list_end;
979 int program_info_length, pcr_pid, pid, stream_type;
981 uint32_t prog_reg_desc = 0; /* registration descriptor */
982 uint8_t *mp4_dec_config_descr = NULL;
983 int mp4_dec_config_descr_len = 0;
987 av_dlog(ts->stream, "PMT: len %i\n", section_len);
988 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
991 p_end = section + section_len - 4;
993 if (parse_section_header(h, &p, p_end) < 0)
996 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
997 h->id, h->sec_num, h->last_sec_num);
999 if (h->tid != PMT_TID)
1002 clear_program(ts, h->id);
1003 pcr_pid = get16(&p, p_end) & 0x1fff;
1006 add_pid_to_pmt(ts, h->id, pcr_pid);
1008 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1010 program_info_length = get16(&p, p_end) & 0xfff;
1011 if (program_info_length < 0)
1013 while(program_info_length >= 2) {
1015 tag = get8(&p, p_end);
1016 len = get8(&p, p_end);
1018 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1020 if(len > program_info_length - 2)
1021 //something else is broken, exit the program_descriptors_loop
1023 program_info_length -= len + 2;
1024 if (tag == 0x1d) { // IOD descriptor
1025 get8(&p, p_end); // scope
1026 get8(&p, p_end); // label
1028 mp4_read_iods(ts->stream, p, len, &mp4_es_id,
1029 &mp4_dec_config_descr, &mp4_dec_config_descr_len);
1030 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1031 prog_reg_desc = bytestream_get_le32(&p);
1036 p += program_info_length;
1040 // stop parsing after pmt, we found header
1041 if (!ts->stream->nb_streams)
1046 stream_type = get8(&p, p_end);
1047 if (stream_type < 0)
1049 pid = get16(&p, p_end) & 0x1fff;
1053 /* now create ffmpeg stream */
1054 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1055 pes = ts->pids[pid]->u.pes_filter.opaque;
1057 pes->st = av_new_stream(pes->stream, pes->pid);
1060 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1061 pes = add_pes_stream(ts, pid, pcr_pid);
1063 st = av_new_stream(pes->stream, pes->pid);
1069 if (!pes->stream_type)
1070 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1072 add_pid_to_pmt(ts, h->id, pid);
1074 ff_program_add_stream_index(ts->stream, h->id, st->index);
1076 desc_list_len = get16(&p, p_end) & 0xfff;
1077 if (desc_list_len < 0)
1079 desc_list_end = p + desc_list_len;
1080 if (desc_list_end > p_end)
1083 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1084 mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
1087 if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1088 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1089 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1096 av_free(mp4_dec_config_descr);
1099 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1101 MpegTSContext *ts = filter->u.section_filter.opaque;
1102 SectionHeader h1, *h = &h1;
1103 const uint8_t *p, *p_end;
1107 av_dlog(ts->stream, "PAT:\n");
1108 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1110 p_end = section + section_len - 4;
1112 if (parse_section_header(h, &p, p_end) < 0)
1114 if (h->tid != PAT_TID)
1119 sid = get16(&p, p_end);
1122 pmt_pid = get16(&p, p_end) & 0x1fff;
1126 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1128 if (sid == 0x0000) {
1131 av_new_program(ts->stream, sid);
1132 if (ts->pids[pmt_pid])
1133 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1134 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1135 add_pat_entry(ts, sid);
1136 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1137 add_pid_to_pmt(ts, sid, pmt_pid);
1142 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1144 MpegTSContext *ts = filter->u.section_filter.opaque;
1145 SectionHeader h1, *h = &h1;
1146 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1147 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1148 char *name, *provider_name;
1151 av_dlog(ts->stream, "SDT:\n");
1152 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1155 p_end = section + section_len - 4;
1157 if (parse_section_header(h, &p, p_end) < 0)
1159 if (h->tid != SDT_TID)
1161 onid = get16(&p, p_end);
1164 val = get8(&p, p_end);
1168 sid = get16(&p, p_end);
1171 val = get8(&p, p_end);
1174 desc_list_len = get16(&p, p_end) & 0xfff;
1175 if (desc_list_len < 0)
1177 desc_list_end = p + desc_list_len;
1178 if (desc_list_end > p_end)
1181 desc_tag = get8(&p, desc_list_end);
1184 desc_len = get8(&p, desc_list_end);
1185 desc_end = p + desc_len;
1186 if (desc_end > desc_list_end)
1189 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1190 desc_tag, desc_len);
1194 service_type = get8(&p, p_end);
1195 if (service_type < 0)
1197 provider_name = getstr8(&p, p_end);
1200 name = getstr8(&p, p_end);
1202 AVProgram *program = av_new_program(ts->stream, sid);
1204 av_metadata_set2(&program->metadata, "service_name", name, 0);
1205 av_metadata_set2(&program->metadata, "service_provider", provider_name, 0);
1209 av_free(provider_name);
1220 /* handle one TS packet */
1221 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1223 AVFormatContext *s = ts->stream;
1225 int len, pid, cc, cc_ok, afc, is_start;
1226 const uint8_t *p, *p_end;
1229 pid = AV_RB16(packet + 1) & 0x1fff;
1230 if(pid && discard_pid(ts, pid))
1232 is_start = packet[1] & 0x40;
1233 tss = ts->pids[pid];
1234 if (ts->auto_guess && tss == NULL && is_start) {
1235 add_pes_stream(ts, pid, -1);
1236 tss = ts->pids[pid];
1241 /* continuity check (currently not used) */
1242 cc = (packet[3] & 0xf);
1243 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1246 /* skip adaptation field */
1247 afc = (packet[3] >> 4) & 3;
1249 if (afc == 0) /* reserved value */
1251 if (afc == 2) /* adaptation field only */
1254 /* skip adapation field */
1257 /* if past the end of packet, ignore */
1258 p_end = packet + TS_PACKET_SIZE;
1262 pos = url_ftell(ts->stream->pb);
1263 ts->pos47= pos % ts->raw_packet_size;
1265 if (tss->type == MPEGTS_SECTION) {
1267 /* pointer field present */
1269 if (p + len > p_end)
1272 /* write remaining section bytes */
1273 write_section_data(s, tss,
1275 /* check whether filter has been closed */
1281 write_section_data(s, tss,
1286 write_section_data(s, tss,
1292 // Note: The position here points actually behind the current packet.
1293 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1294 pos - ts->raw_packet_size)) < 0)
1301 /* XXX: try to find a better synchro over several packets (use
1302 get_packet_size() ?) */
1303 static int mpegts_resync(AVFormatContext *s)
1305 ByteIOContext *pb = s->pb;
1308 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1313 url_fseek(pb, -1, SEEK_CUR);
1317 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1322 /* return -1 if error or EOF. Return 0 if OK. */
1323 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1325 ByteIOContext *pb = s->pb;
1329 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1330 if (len != TS_PACKET_SIZE)
1331 return AVERROR(EIO);
1332 /* check paquet sync byte */
1333 if (buf[0] != 0x47) {
1334 /* find a new packet start */
1335 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1336 if (mpegts_resync(s) < 0)
1337 return AVERROR(EAGAIN);
1341 skip = raw_packet_size - TS_PACKET_SIZE;
1343 url_fskip(pb, skip);
1350 static int handle_packets(MpegTSContext *ts, int nb_packets)
1352 AVFormatContext *s = ts->stream;
1353 uint8_t packet[TS_PACKET_SIZE];
1354 int packet_num, ret;
1359 if (ts->stop_parse>0)
1362 if (nb_packets != 0 && packet_num >= nb_packets)
1364 ret = read_packet(s, packet, ts->raw_packet_size);
1367 ret = handle_packet(ts, packet);
1374 static int mpegts_probe(AVProbeData *p)
1377 const int size= p->buf_size;
1378 int score, fec_score, dvhs_score;
1379 int check_count= size / TS_FEC_PACKET_SIZE;
1380 #define CHECK_COUNT 10
1382 if (check_count < CHECK_COUNT)
1385 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1386 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1387 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1388 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1390 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1391 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1392 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1393 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1396 /* only use the extension for safer guess */
1397 if (av_match_ext(p->filename, "ts"))
1398 return AVPROBE_SCORE_MAX;
1404 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1405 (-1) if not available */
1406 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1407 const uint8_t *packet)
1409 int afc, len, flags;
1413 afc = (packet[3] >> 4) & 3;
1423 if (!(flags & 0x10))
1428 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1429 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1433 static int mpegts_read_header(AVFormatContext *s,
1434 AVFormatParameters *ap)
1436 MpegTSContext *ts = s->priv_data;
1437 ByteIOContext *pb = s->pb;
1438 uint8_t buf[5*1024];
1443 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1444 if(ap->mpeg2ts_raw){
1445 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1450 /* read the first 1024 bytes to get packet size */
1451 pos = url_ftell(pb);
1452 len = get_buffer(pb, buf, sizeof(buf));
1453 if (len != sizeof(buf))
1455 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1456 if (ts->raw_packet_size <= 0)
1461 if (s->iformat == &ff_mpegts_demuxer) {
1464 /* first do a scaning to get all the services */
1465 if (url_fseek(pb, pos, SEEK_SET) < 0)
1466 av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1468 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1470 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1472 handle_packets(ts, s->probesize / ts->raw_packet_size);
1473 /* if could not find service, enable auto_guess */
1477 av_dlog(ts->stream, "tuning done\n");
1479 s->ctx_flags |= AVFMTCTX_NOHEADER;
1482 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1483 int64_t pcrs[2], pcr_h;
1484 int packet_count[2];
1485 uint8_t packet[TS_PACKET_SIZE];
1487 /* only read packets */
1489 st = av_new_stream(s, 0);
1492 av_set_pts_info(st, 60, 1, 27000000);
1493 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1494 st->codec->codec_id = CODEC_ID_MPEG2TS;
1496 /* we iterate until we find two PCRs to estimate the bitrate */
1501 ret = read_packet(s, packet, ts->raw_packet_size);
1504 pid = AV_RB16(packet + 1) & 0x1fff;
1505 if ((pcr_pid == -1 || pcr_pid == pid) &&
1506 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1508 packet_count[nb_pcrs] = nb_packets;
1509 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1517 /* NOTE1: the bitrate is computed without the FEC */
1518 /* NOTE2: it is only the bitrate of the start of the stream */
1519 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1520 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1521 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1522 st->codec->bit_rate = s->bit_rate;
1523 st->start_time = ts->cur_pcr;
1525 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1526 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1530 url_fseek(pb, pos, SEEK_SET);
1536 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1538 static int mpegts_raw_read_packet(AVFormatContext *s,
1541 MpegTSContext *ts = s->priv_data;
1543 int64_t pcr_h, next_pcr_h, pos;
1544 int pcr_l, next_pcr_l;
1545 uint8_t pcr_buf[12];
1547 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1548 return AVERROR(ENOMEM);
1549 pkt->pos= url_ftell(s->pb);
1550 ret = read_packet(s, pkt->data, ts->raw_packet_size);
1552 av_free_packet(pkt);
1555 if (ts->mpeg2ts_compute_pcr) {
1556 /* compute exact PCR for each packet */
1557 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1558 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1559 pos = url_ftell(s->pb);
1560 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1561 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1562 get_buffer(s->pb, pcr_buf, 12);
1563 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1564 /* XXX: not precise enough */
1565 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1570 url_fseek(s->pb, pos, SEEK_SET);
1571 /* no next PCR found: we use previous increment */
1572 ts->cur_pcr = pcr_h * 300 + pcr_l;
1574 pkt->pts = ts->cur_pcr;
1575 pkt->duration = ts->pcr_incr;
1576 ts->cur_pcr += ts->pcr_incr;
1578 pkt->stream_index = 0;
1582 static int mpegts_read_packet(AVFormatContext *s,
1585 MpegTSContext *ts = s->priv_data;
1588 if (url_ftell(s->pb) != ts->last_pos) {
1589 /* seek detected, flush pes buffer */
1590 for (i = 0; i < NB_PID_MAX; i++) {
1591 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1592 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1593 av_freep(&pes->buffer);
1594 pes->data_index = 0;
1595 pes->state = MPEGTS_SKIP; /* skip until pes header */
1601 ret = handle_packets(ts, 0);
1603 /* flush pes data left */
1604 for (i = 0; i < NB_PID_MAX; i++) {
1605 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1606 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1607 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1608 new_pes_packet(pes, pkt);
1609 pes->state = MPEGTS_SKIP;
1617 ts->last_pos = url_ftell(s->pb);
1622 static int mpegts_read_close(AVFormatContext *s)
1624 MpegTSContext *ts = s->priv_data;
1629 for(i=0;i<NB_PID_MAX;i++)
1630 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1635 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1636 int64_t *ppos, int64_t pos_limit)
1638 MpegTSContext *ts = s->priv_data;
1639 int64_t pos, timestamp;
1640 uint8_t buf[TS_PACKET_SIZE];
1641 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1642 const int find_next= 1;
1643 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1646 url_fseek(s->pb, pos, SEEK_SET);
1647 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1648 return AV_NOPTS_VALUE;
1649 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1650 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1653 pos += ts->raw_packet_size;
1657 pos -= ts->raw_packet_size;
1659 return AV_NOPTS_VALUE;
1660 url_fseek(s->pb, pos, SEEK_SET);
1661 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1662 return AV_NOPTS_VALUE;
1663 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1664 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1674 #ifdef USE_SYNCPOINT_SEARCH
1676 static int read_seek2(AVFormatContext *s,
1685 int64_t ts_ret, ts_adj;
1686 int stream_index_gen_search;
1688 AVParserState *backup;
1690 backup = ff_store_parser_state(s);
1692 // detect direction of seeking for search purposes
1693 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
1694 AVSEEK_FLAG_BACKWARD : 0;
1696 if (flags & AVSEEK_FLAG_BYTE) {
1697 // use position directly, we will search starting from it
1700 // search for some position with good timestamp match
1701 if (stream_index < 0) {
1702 stream_index_gen_search = av_find_default_stream_index(s);
1703 if (stream_index_gen_search < 0) {
1704 ff_restore_parser_state(s, backup);
1708 st = s->streams[stream_index_gen_search];
1709 // timestamp for default must be expressed in AV_TIME_BASE units
1710 ts_adj = av_rescale(target_ts,
1712 AV_TIME_BASE * (int64_t)st->time_base.num);
1715 stream_index_gen_search = stream_index;
1717 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1721 flags, &ts_ret, mpegts_get_pcr);
1723 ff_restore_parser_state(s, backup);
1728 // search for actual matching keyframe/starting position for all streams
1729 if (ff_gen_syncpoint_search(s, stream_index, pos,
1730 min_ts, target_ts, max_ts,
1732 ff_restore_parser_state(s, backup);
1736 ff_free_parser_state(s, backup);
1740 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1743 if (flags & AVSEEK_FLAG_BACKWARD) {
1744 flags &= ~AVSEEK_FLAG_BACKWARD;
1745 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
1747 // for compatibility reasons, seek to the best-fitting timestamp
1748 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1750 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, 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);
1760 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1761 MpegTSContext *ts = s->priv_data;
1762 uint8_t buf[TS_PACKET_SIZE];
1765 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1768 pos= url_ftell(s->pb);
1771 url_fseek(s->pb, pos, SEEK_SET);
1772 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1774 // pid = AV_RB16(buf + 1) & 0x1fff;
1775 if(buf[1] & 0x40) break;
1776 pos += ts->raw_packet_size;
1778 url_fseek(s->pb, pos, SEEK_SET);
1785 /**************************************************************/
1786 /* parsing functions - called from other demuxers such as RTP */
1788 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
1792 ts = av_mallocz(sizeof(MpegTSContext));
1795 /* no stream case, currently used by RTP */
1796 ts->raw_packet_size = TS_PACKET_SIZE;
1802 /* return the consumed length if a packet was output, or -1 if no
1804 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1805 const uint8_t *buf, int len)
1813 if (ts->stop_parse>0)
1815 if (len < TS_PACKET_SIZE)
1817 if (buf[0] != 0x47) {
1821 handle_packet(ts, buf);
1822 buf += TS_PACKET_SIZE;
1823 len -= TS_PACKET_SIZE;
1829 void ff_mpegts_parse_close(MpegTSContext *ts)
1833 for(i=0;i<NB_PID_MAX;i++)
1834 av_free(ts->pids[i]);
1838 AVInputFormat ff_mpegts_demuxer = {
1840 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1841 sizeof(MpegTSContext),
1848 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1849 #ifdef USE_SYNCPOINT_SEARCH
1850 .read_seek2 = read_seek2,
1854 AVInputFormat ff_mpegtsraw_demuxer = {
1856 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1857 sizeof(MpegTSContext),
1860 mpegts_raw_read_packet,
1864 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1865 #ifdef USE_SYNCPOINT_SEARCH
1866 .read_seek2 = read_seek2,