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"
35 /* 1.0 second at 24Mbit/s */
36 #define MAX_SCAN_PACKETS 32000
38 /* maximum size in which we look for synchronisation if
39 synchronisation is lost */
40 #define MAX_RESYNC_SIZE 65536
42 #define MAX_PES_PAYLOAD 200*1024
44 enum MpegTSFilterType {
49 typedef struct MpegTSFilter MpegTSFilter;
51 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
53 typedef struct MpegTSPESFilter {
58 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
60 typedef void SetServiceCallback(void *opaque, int ret);
62 typedef struct MpegTSSectionFilter {
66 unsigned int check_crc:1;
67 unsigned int end_of_section_reached:1;
68 SectionCallback *section_cb;
70 } MpegTSSectionFilter;
74 int last_cc; /* last cc code (-1 if first packet) */
75 enum MpegTSFilterType type;
77 MpegTSPESFilter pes_filter;
78 MpegTSSectionFilter section_filter;
82 #define MAX_PIDS_PER_PROGRAM 64
84 unsigned int id; //program id/service id
86 unsigned int pids[MAX_PIDS_PER_PROGRAM];
89 struct MpegTSContext {
91 AVFormatContext *stream;
92 /** raw packet size, including FEC if present */
97 /** if true, all pids are analyzed to find streams */
100 /** compute exact PCR for each transport stream packet */
101 int mpeg2ts_compute_pcr;
103 int64_t cur_pcr; /**< used to estimate the exact PCR */
104 int pcr_incr; /**< used to estimate the exact PCR */
106 /* data needed to handle file based ts */
107 /** stop parsing loop */
109 /** packet containing Audio/Video data */
111 /** to detect seek */
114 /******************************************/
115 /* private mpegts data */
117 /** structure to keep track of Program->pids mapping */
122 /** filters for various streams specified by PMT + for the PAT and PMT */
123 MpegTSFilter *pids[NB_PID_MAX];
126 /* TS stream handling */
131 MPEGTS_PESHEADER_FILL,
136 /* enough for PES header + length */
137 #define PES_START_SIZE 6
138 #define PES_HEADER_SIZE 9
139 #define MAX_PES_HEADER_SIZE (9 + 255)
141 typedef struct PESContext {
143 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
146 AVFormatContext *stream;
148 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
149 enum MpegTSState state;
150 /* used to get the format */
154 int extended_stream_id;
156 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
157 uint8_t header[MAX_PES_HEADER_SIZE];
161 extern AVInputFormat mpegts_demuxer;
163 static void clear_program(MpegTSContext *ts, unsigned int programid)
167 for(i=0; i<ts->nb_prg; i++)
168 if(ts->prg[i].id == programid)
169 ts->prg[i].nb_pids = 0;
172 static void clear_programs(MpegTSContext *ts)
178 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
181 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
185 p = &ts->prg[ts->nb_prg];
191 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
194 struct Program *p = NULL;
195 for(i=0; i<ts->nb_prg; i++) {
196 if(ts->prg[i].id == programid) {
204 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
206 p->pids[p->nb_pids++] = pid;
210 * \brief discard_pid() decides if the pid is to be discarded according
211 * to caller's programs selection
212 * \param ts : - TS context
214 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
217 static int discard_pid(MpegTSContext *ts, unsigned int pid)
220 int used = 0, discarded = 0;
222 for(i=0; i<ts->nb_prg; i++) {
224 for(j=0; j<p->nb_pids; j++) {
225 if(p->pids[j] != pid)
227 //is program with id p->id set to be discarded?
228 for(k=0; k<ts->stream->nb_programs; k++) {
229 if(ts->stream->programs[k]->id == p->id) {
230 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
239 return !used && discarded;
243 * Assemble PES packets out of TS packets, and then call the "section_cb"
244 * function when they are complete.
246 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
247 const uint8_t *buf, int buf_size, int is_start)
249 MpegTSSectionFilter *tss = &tss1->u.section_filter;
253 memcpy(tss->section_buf, buf, buf_size);
254 tss->section_index = buf_size;
255 tss->section_h_size = -1;
256 tss->end_of_section_reached = 0;
258 if (tss->end_of_section_reached)
260 len = 4096 - tss->section_index;
263 memcpy(tss->section_buf + tss->section_index, buf, len);
264 tss->section_index += len;
267 /* compute section length if possible */
268 if (tss->section_h_size == -1 && tss->section_index >= 3) {
269 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
272 tss->section_h_size = len;
275 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
276 tss->end_of_section_reached = 1;
277 if (!tss->check_crc ||
278 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
279 tss->section_buf, tss->section_h_size) == 0)
280 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
284 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
285 SectionCallback *section_cb, void *opaque,
289 MpegTSFilter *filter;
290 MpegTSSectionFilter *sec;
292 dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
294 if (pid >= NB_PID_MAX || ts->pids[pid])
296 filter = av_mallocz(sizeof(MpegTSFilter));
299 ts->pids[pid] = filter;
300 filter->type = MPEGTS_SECTION;
302 filter->last_cc = -1;
303 sec = &filter->u.section_filter;
304 sec->section_cb = section_cb;
305 sec->opaque = opaque;
306 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
307 sec->check_crc = check_crc;
308 if (!sec->section_buf) {
315 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
319 MpegTSFilter *filter;
320 MpegTSPESFilter *pes;
322 if (pid >= NB_PID_MAX || ts->pids[pid])
324 filter = av_mallocz(sizeof(MpegTSFilter));
327 ts->pids[pid] = filter;
328 filter->type = MPEGTS_PES;
330 filter->last_cc = -1;
331 pes = &filter->u.pes_filter;
332 pes->pes_cb = pes_cb;
333 pes->opaque = opaque;
337 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
342 if (filter->type == MPEGTS_SECTION)
343 av_freep(&filter->u.section_filter.section_buf);
344 else if (filter->type == MPEGTS_PES) {
345 PESContext *pes = filter->u.pes_filter.opaque;
346 av_freep(&pes->buffer);
347 /* referenced private data will be freed later in
348 * av_close_input_stream */
349 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
350 av_freep(&filter->u.pes_filter.opaque);
355 ts->pids[pid] = NULL;
358 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
359 int stat[TS_MAX_PACKET_SIZE];
364 memset(stat, 0, packet_size*sizeof(int));
366 for(x=i=0; i<size-3; i++){
367 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
369 if(stat[x] > best_score){
376 if(x == packet_size) x= 0;
382 /* autodetect fec presence. Must have at least 1024 bytes */
383 static int get_packet_size(const uint8_t *buf, int size)
385 int score, fec_score, dvhs_score;
387 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
390 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
391 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
392 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
393 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
395 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
396 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
397 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
401 typedef struct SectionHeader {
406 uint8_t last_sec_num;
409 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
422 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
428 if ((p + 1) >= p_end)
436 /* read and allocate a DVB string preceeded by its length */
437 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
444 len = get8(&p, p_end);
447 if ((p + len) > p_end)
449 str = av_malloc(len + 1);
459 static int parse_section_header(SectionHeader *h,
460 const uint8_t **pp, const uint8_t *p_end)
464 val = get8(pp, p_end);
469 val = get16(pp, p_end);
473 val = get8(pp, p_end);
476 h->version = (val >> 1) & 0x1f;
477 val = get8(pp, p_end);
481 val = get8(pp, p_end);
484 h->last_sec_num = val;
489 uint32_t stream_type;
490 enum AVMediaType codec_type;
491 enum CodecID codec_id;
494 static const StreamType ISO_types[] = {
495 { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
496 { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
497 { 0x03, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
498 { 0x04, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
499 { 0x0f, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC },
500 { 0x10, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4 },
501 { 0x11, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC_LATM }, /* LATM syntax */
502 { 0x1b, AVMEDIA_TYPE_VIDEO, CODEC_ID_H264 },
503 { 0xd1, AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
504 { 0xea, AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
508 static const StreamType HDMV_types[] = {
509 { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
510 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
511 { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
512 { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
513 { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
514 { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
519 static const StreamType MISC_types[] = {
520 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
521 { 0x8a, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
525 static const StreamType REGD_types[] = {
526 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
527 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
531 /* descriptor present */
532 static const StreamType DESC_types[] = {
533 { 0x6a, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
534 { 0x7a, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
535 { 0x7b, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
536 { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
537 { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
541 static void mpegts_find_stream_type(AVStream *st,
542 uint32_t stream_type, const StreamType *types)
544 for (; types->stream_type; types++) {
545 if (stream_type == types->stream_type) {
546 st->codec->codec_type = types->codec_type;
547 st->codec->codec_id = types->codec_id;
553 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
554 uint32_t stream_type, uint32_t prog_reg_desc)
556 av_set_pts_info(st, 33, 1, 90000);
558 st->codec->codec_type = AVMEDIA_TYPE_DATA;
559 st->codec->codec_id = CODEC_ID_NONE;
560 st->need_parsing = AVSTREAM_PARSE_FULL;
562 pes->stream_type = stream_type;
564 av_log(pes->stream, AV_LOG_DEBUG,
565 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
566 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
568 st->codec->codec_tag = pes->stream_type;
570 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
571 if (prog_reg_desc == AV_RL32("HDMV") &&
572 st->codec->codec_id == CODEC_ID_NONE) {
573 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
574 if (pes->stream_type == 0x83) {
575 // HDMV TrueHD streams also contain an AC3 coded version of the
576 // audio track - add a second stream for this
578 // priv_data cannot be shared between streams
579 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
581 return AVERROR(ENOMEM);
582 memcpy(sub_pes, pes, sizeof(*sub_pes));
584 sub_st = av_new_stream(pes->stream, pes->pid);
587 return AVERROR(ENOMEM);
590 av_set_pts_info(sub_st, 33, 1, 90000);
591 sub_st->priv_data = sub_pes;
592 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
593 sub_st->codec->codec_id = CODEC_ID_AC3;
594 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
595 sub_pes->sub_st = pes->sub_st = sub_st;
598 if (st->codec->codec_id == CODEC_ID_NONE)
599 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
604 static int64_t get_pts(const uint8_t *p)
606 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
607 pts |= (AV_RB16(p + 1) >> 1) << 15;
608 pts |= AV_RB16(p + 3) >> 1;
612 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
616 pkt->destruct = av_destruct_packet;
617 pkt->data = pes->buffer;
618 pkt->size = pes->data_index;
619 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
621 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
622 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
623 pkt->stream_index = pes->sub_st->index;
625 pkt->stream_index = pes->st->index;
628 /* store position of first TS packet of this PES packet */
629 pkt->pos = pes->ts_packet_pos;
631 /* reset pts values */
632 pes->pts = AV_NOPTS_VALUE;
633 pes->dts = AV_NOPTS_VALUE;
638 /* return non zero if a packet could be constructed */
639 static int mpegts_push_data(MpegTSFilter *filter,
640 const uint8_t *buf, int buf_size, int is_start,
643 PESContext *pes = filter->u.pes_filter.opaque;
644 MpegTSContext *ts = pes->ts;
652 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
653 new_pes_packet(pes, ts->pkt);
656 pes->state = MPEGTS_HEADER;
658 pes->ts_packet_pos = pos;
661 while (buf_size > 0) {
664 len = PES_START_SIZE - pes->data_index;
667 memcpy(pes->header + pes->data_index, p, len);
668 pes->data_index += len;
671 if (pes->data_index == PES_START_SIZE) {
672 /* we got all the PES or section header. We can now
675 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
677 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
678 pes->header[2] == 0x01) {
679 /* it must be an mpeg2 PES stream */
680 code = pes->header[3] | 0x100;
681 dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
683 if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
684 code == 0x1be) /* padding_stream */
687 #if FF_API_MAX_STREAMS
688 if (!pes->st && pes->stream->nb_streams == MAX_STREAMS)
692 /* stream not present in PMT */
694 pes->st = av_new_stream(ts->stream, pes->pid);
696 return AVERROR(ENOMEM);
697 mpegts_set_stream_info(pes->st, pes, 0, 0);
700 pes->total_size = AV_RB16(pes->header + 4);
701 /* NOTE: a zero total size means the PES size is
703 if (!pes->total_size)
704 pes->total_size = MAX_PES_PAYLOAD;
706 /* allocate pes buffer */
707 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
709 return AVERROR(ENOMEM);
711 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
712 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
713 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
714 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
715 pes->state = MPEGTS_PESHEADER;
716 if (pes->st->codec->codec_id == CODEC_ID_NONE) {
717 dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
718 pes->pid, pes->stream_type);
719 pes->st->codec->codec_id = CODEC_ID_PROBE;
722 pes->state = MPEGTS_PAYLOAD;
726 /* otherwise, it should be a table */
729 pes->state = MPEGTS_SKIP;
734 /**********************************************/
735 /* PES packing parsing */
736 case MPEGTS_PESHEADER:
737 len = PES_HEADER_SIZE - pes->data_index;
742 memcpy(pes->header + pes->data_index, p, len);
743 pes->data_index += len;
746 if (pes->data_index == PES_HEADER_SIZE) {
747 pes->pes_header_size = pes->header[8] + 9;
748 pes->state = MPEGTS_PESHEADER_FILL;
751 case MPEGTS_PESHEADER_FILL:
752 len = pes->pes_header_size - pes->data_index;
757 memcpy(pes->header + pes->data_index, p, len);
758 pes->data_index += len;
761 if (pes->data_index == pes->pes_header_size) {
763 unsigned int flags, pes_ext, skip;
765 flags = pes->header[7];
767 pes->pts = AV_NOPTS_VALUE;
768 pes->dts = AV_NOPTS_VALUE;
769 if ((flags & 0xc0) == 0x80) {
770 pes->dts = pes->pts = get_pts(r);
772 } else if ((flags & 0xc0) == 0xc0) {
773 pes->pts = get_pts(r);
775 pes->dts = get_pts(r);
778 pes->extended_stream_id = -1;
779 if (flags & 0x01) { /* PES extension */
781 /* Skip PES private data, program packet sequence counter and P-STD buffer */
782 skip = (pes_ext >> 4) & 0xb;
785 if ((pes_ext & 0x41) == 0x01 &&
786 (r + 2) <= (pes->header + pes->pes_header_size)) {
787 /* PES extension 2 */
788 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
789 pes->extended_stream_id = r[1];
793 /* we got the full header. We parse it and get the payload */
794 pes->state = MPEGTS_PAYLOAD;
799 if (buf_size > 0 && pes->buffer) {
800 if (pes->data_index+buf_size > pes->total_size) {
801 new_pes_packet(pes, ts->pkt);
802 pes->total_size = MAX_PES_PAYLOAD;
803 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
805 return AVERROR(ENOMEM);
808 memcpy(pes->buffer+pes->data_index, p, buf_size);
809 pes->data_index += buf_size;
812 /* emit complete packets with known packet size
813 * decreases demuxer delay for infrequent packets like subtitles from
814 * a couple of seconds to milliseconds for properly muxed files.
815 * total_size is the number of bytes following pes_packet_length
816 * in the pes header, i.e. not counting the first 6 bytes */
817 if (pes->total_size < MAX_PES_PAYLOAD &&
818 pes->pes_header_size + pes->data_index == pes->total_size + 6) {
820 new_pes_packet(pes, ts->pkt);
832 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
837 /* if no pid found, then add a pid context */
838 pes = av_mallocz(sizeof(PESContext));
842 pes->stream = ts->stream;
844 pes->pcr_pid = pcr_pid;
845 pes->state = MPEGTS_SKIP;
846 pes->pts = AV_NOPTS_VALUE;
847 pes->dts = AV_NOPTS_VALUE;
848 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
856 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
857 int *es_id, uint8_t **dec_config_descr,
858 int *dec_config_descr_size)
864 init_put_byte(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
866 len = ff_mp4_read_descr(s, &pb, &tag);
867 if (tag == MP4IODescrTag) {
874 len = ff_mp4_read_descr(s, &pb, &tag);
875 if (tag == MP4ESDescrTag) {
876 *es_id = get_be16(&pb); /* ES_ID */
877 dprintf(s, "ES_ID %#x\n", *es_id);
878 get_byte(&pb); /* priority */
879 len = ff_mp4_read_descr(s, &pb, &tag);
880 if (tag == MP4DecConfigDescrTag) {
881 *dec_config_descr = av_malloc(len);
882 if (!*dec_config_descr)
883 return AVERROR(ENOMEM);
884 *dec_config_descr_size = len;
885 get_buffer(&pb, *dec_config_descr, len);
892 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
894 MpegTSContext *ts = filter->u.section_filter.opaque;
895 SectionHeader h1, *h = &h1;
898 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
899 int program_info_length, pcr_pid, pid, stream_type;
900 int desc_list_len, desc_len, desc_tag;
902 uint32_t prog_reg_desc = 0; /* registration descriptor */
903 uint8_t *mp4_dec_config_descr = NULL;
904 int mp4_dec_config_descr_len = 0;
908 dprintf(ts->stream, "PMT: len %i\n", section_len);
909 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
912 p_end = section + section_len - 4;
914 if (parse_section_header(h, &p, p_end) < 0)
917 dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
918 h->id, h->sec_num, h->last_sec_num);
920 if (h->tid != PMT_TID)
923 clear_program(ts, h->id);
924 pcr_pid = get16(&p, p_end) & 0x1fff;
927 add_pid_to_pmt(ts, h->id, pcr_pid);
929 dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
931 program_info_length = get16(&p, p_end) & 0xfff;
932 if (program_info_length < 0)
934 while(program_info_length >= 2) {
936 tag = get8(&p, p_end);
937 len = get8(&p, p_end);
939 dprintf(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
941 if(len > program_info_length - 2)
942 //something else is broken, exit the program_descriptors_loop
944 program_info_length -= len + 2;
945 if (tag == 0x1d) { // IOD descriptor
946 get8(&p, p_end); // scope
947 get8(&p, p_end); // label
949 mp4_read_iods(ts->stream, p, len, &mp4_es_id,
950 &mp4_dec_config_descr, &mp4_dec_config_descr_len);
951 } else if (tag == 0x05 && len >= 4) { // registration descriptor
952 prog_reg_desc = bytestream_get_le32(&p);
957 p += program_info_length;
961 // stop parsing after pmt, we found header
962 if (!ts->stream->nb_streams)
967 stream_type = get8(&p, p_end);
970 pid = get16(&p, p_end) & 0x1fff;
974 /* now create ffmpeg stream */
975 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
976 pes = ts->pids[pid]->u.pes_filter.opaque;
978 pes->st = av_new_stream(pes->stream, pes->pid);
981 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
982 pes = add_pes_stream(ts, pid, pcr_pid);
984 st = av_new_stream(pes->stream, pes->pid);
990 if (!pes->stream_type)
991 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
993 add_pid_to_pmt(ts, h->id, pid);
995 ff_program_add_stream_index(ts->stream, h->id, st->index);
997 desc_list_len = get16(&p, p_end) & 0xfff;
998 if (desc_list_len < 0)
1000 desc_list_end = p + desc_list_len;
1001 if (desc_list_end > p_end)
1004 desc_tag = get8(&p, desc_list_end);
1007 desc_len = get8(&p, desc_list_end);
1010 desc_end = p + desc_len;
1011 if (desc_end > desc_list_end)
1014 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
1015 desc_tag, desc_len);
1017 if (st->codec->codec_id == CODEC_ID_NONE &&
1018 stream_type == STREAM_TYPE_PRIVATE_DATA)
1019 mpegts_find_stream_type(st, desc_tag, DESC_types);
1022 case 0x1F: /* FMC descriptor */
1023 get16(&p, desc_end);
1024 if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
1025 mp4_dec_config_descr_len && mp4_es_id == pid) {
1027 init_put_byte(&pb, mp4_dec_config_descr,
1028 mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1029 ff_mp4_read_dec_config_descr(ts->stream, st, &pb);
1030 if (st->codec->codec_id == CODEC_ID_AAC &&
1031 st->codec->extradata_size > 0)
1032 st->need_parsing = 0;
1035 case 0x56: /* DVB teletext descriptor */
1036 language[0] = get8(&p, desc_end);
1037 language[1] = get8(&p, desc_end);
1038 language[2] = get8(&p, desc_end);
1040 av_metadata_set2(&st->metadata, "language", language, 0);
1042 case 0x59: /* subtitling descriptor */
1043 language[0] = get8(&p, desc_end);
1044 language[1] = get8(&p, desc_end);
1045 language[2] = get8(&p, desc_end);
1048 if (st->codec->extradata) {
1049 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, p, 4))
1050 av_log_ask_for_sample(ts->stream, "DVB sub with multiple IDs\n");
1052 st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
1053 if (st->codec->extradata) {
1054 st->codec->extradata_size = 4;
1055 memcpy(st->codec->extradata, p, 4);
1059 av_metadata_set2(&st->metadata, "language", language, 0);
1061 case 0x0a: /* ISO 639 language descriptor */
1062 language[0] = get8(&p, desc_end);
1063 language[1] = get8(&p, desc_end);
1064 language[2] = get8(&p, desc_end);
1066 av_metadata_set2(&st->metadata, "language", language, 0);
1068 case 0x05: /* registration descriptor */
1069 st->codec->codec_tag = bytestream_get_le32(&p);
1070 dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1071 if (st->codec->codec_id == CODEC_ID_NONE &&
1072 stream_type == STREAM_TYPE_PRIVATE_DATA)
1073 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1080 if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1081 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1082 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1089 av_free(mp4_dec_config_descr);
1092 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1094 MpegTSContext *ts = filter->u.section_filter.opaque;
1095 SectionHeader h1, *h = &h1;
1096 const uint8_t *p, *p_end;
1100 dprintf(ts->stream, "PAT:\n");
1101 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1103 p_end = section + section_len - 4;
1105 if (parse_section_header(h, &p, p_end) < 0)
1107 if (h->tid != PAT_TID)
1112 sid = get16(&p, p_end);
1115 pmt_pid = get16(&p, p_end) & 0x1fff;
1119 dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1121 if (sid == 0x0000) {
1124 av_new_program(ts->stream, sid);
1125 if (ts->pids[pmt_pid])
1126 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1127 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1128 add_pat_entry(ts, sid);
1129 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1130 add_pid_to_pmt(ts, sid, pmt_pid);
1135 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1137 MpegTSContext *ts = filter->u.section_filter.opaque;
1138 SectionHeader h1, *h = &h1;
1139 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1140 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1141 char *name, *provider_name;
1144 dprintf(ts->stream, "SDT:\n");
1145 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
1148 p_end = section + section_len - 4;
1150 if (parse_section_header(h, &p, p_end) < 0)
1152 if (h->tid != SDT_TID)
1154 onid = get16(&p, p_end);
1157 val = get8(&p, p_end);
1161 sid = get16(&p, p_end);
1164 val = get8(&p, p_end);
1167 desc_list_len = get16(&p, p_end) & 0xfff;
1168 if (desc_list_len < 0)
1170 desc_list_end = p + desc_list_len;
1171 if (desc_list_end > p_end)
1174 desc_tag = get8(&p, desc_list_end);
1177 desc_len = get8(&p, desc_list_end);
1178 desc_end = p + desc_len;
1179 if (desc_end > desc_list_end)
1182 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
1183 desc_tag, desc_len);
1187 service_type = get8(&p, p_end);
1188 if (service_type < 0)
1190 provider_name = getstr8(&p, p_end);
1193 name = getstr8(&p, p_end);
1195 AVProgram *program = av_new_program(ts->stream, sid);
1197 av_metadata_set2(&program->metadata, "name", name, 0);
1198 av_metadata_set2(&program->metadata, "provider_name", provider_name, 0);
1202 av_free(provider_name);
1213 /* handle one TS packet */
1214 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1216 AVFormatContext *s = ts->stream;
1218 int len, pid, cc, cc_ok, afc, is_start;
1219 const uint8_t *p, *p_end;
1222 pid = AV_RB16(packet + 1) & 0x1fff;
1223 if(pid && discard_pid(ts, pid))
1225 is_start = packet[1] & 0x40;
1226 tss = ts->pids[pid];
1227 if (ts->auto_guess && tss == NULL && is_start) {
1228 add_pes_stream(ts, pid, -1);
1229 tss = ts->pids[pid];
1234 /* continuity check (currently not used) */
1235 cc = (packet[3] & 0xf);
1236 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1239 /* skip adaptation field */
1240 afc = (packet[3] >> 4) & 3;
1242 if (afc == 0) /* reserved value */
1244 if (afc == 2) /* adaptation field only */
1247 /* skip adapation field */
1250 /* if past the end of packet, ignore */
1251 p_end = packet + TS_PACKET_SIZE;
1255 pos = url_ftell(ts->stream->pb);
1256 ts->pos47= pos % ts->raw_packet_size;
1258 if (tss->type == MPEGTS_SECTION) {
1260 /* pointer field present */
1262 if (p + len > p_end)
1265 /* write remaining section bytes */
1266 write_section_data(s, tss,
1268 /* check whether filter has been closed */
1274 write_section_data(s, tss,
1279 write_section_data(s, tss,
1285 // Note: The position here points actually behind the current packet.
1286 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1287 pos - ts->raw_packet_size)) < 0)
1294 /* XXX: try to find a better synchro over several packets (use
1295 get_packet_size() ?) */
1296 static int mpegts_resync(AVFormatContext *s)
1298 ByteIOContext *pb = s->pb;
1301 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1306 url_fseek(pb, -1, SEEK_CUR);
1310 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1315 /* return -1 if error or EOF. Return 0 if OK. */
1316 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1318 ByteIOContext *pb = s->pb;
1322 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1323 if (len != TS_PACKET_SIZE)
1324 return AVERROR(EIO);
1325 /* check paquet sync byte */
1326 if (buf[0] != 0x47) {
1327 /* find a new packet start */
1328 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1329 if (mpegts_resync(s) < 0)
1330 return AVERROR(EAGAIN);
1334 skip = raw_packet_size - TS_PACKET_SIZE;
1336 url_fskip(pb, skip);
1343 static int handle_packets(MpegTSContext *ts, int nb_packets)
1345 AVFormatContext *s = ts->stream;
1346 uint8_t packet[TS_PACKET_SIZE];
1347 int packet_num, ret;
1352 if (ts->stop_parse>0)
1355 if (nb_packets != 0 && packet_num >= nb_packets)
1357 ret = read_packet(s, packet, ts->raw_packet_size);
1360 ret = handle_packet(ts, packet);
1367 static int mpegts_probe(AVProbeData *p)
1370 const int size= p->buf_size;
1371 int score, fec_score, dvhs_score;
1372 int check_count= size / TS_FEC_PACKET_SIZE;
1373 #define CHECK_COUNT 10
1375 if (check_count < CHECK_COUNT)
1378 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1379 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1380 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1381 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1383 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1384 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1385 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1386 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1389 /* only use the extension for safer guess */
1390 if (av_match_ext(p->filename, "ts"))
1391 return AVPROBE_SCORE_MAX;
1397 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1398 (-1) if not available */
1399 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1400 const uint8_t *packet)
1402 int afc, len, flags;
1406 afc = (packet[3] >> 4) & 3;
1416 if (!(flags & 0x10))
1421 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1422 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1426 static int mpegts_read_header(AVFormatContext *s,
1427 AVFormatParameters *ap)
1429 MpegTSContext *ts = s->priv_data;
1430 ByteIOContext *pb = s->pb;
1431 uint8_t buf[5*1024];
1436 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1437 if(ap->mpeg2ts_raw){
1438 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1443 /* read the first 1024 bytes to get packet size */
1444 pos = url_ftell(pb);
1445 len = get_buffer(pb, buf, sizeof(buf));
1446 if (len != sizeof(buf))
1448 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1449 if (ts->raw_packet_size <= 0)
1454 if (s->iformat == &mpegts_demuxer) {
1457 /* first do a scaning to get all the services */
1458 if (url_fseek(pb, pos, SEEK_SET) < 0)
1459 av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1461 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1463 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1465 handle_packets(ts, s->probesize / ts->raw_packet_size);
1466 /* if could not find service, enable auto_guess */
1470 dprintf(ts->stream, "tuning done\n");
1472 s->ctx_flags |= AVFMTCTX_NOHEADER;
1475 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1476 int64_t pcrs[2], pcr_h;
1477 int packet_count[2];
1478 uint8_t packet[TS_PACKET_SIZE];
1480 /* only read packets */
1482 st = av_new_stream(s, 0);
1485 av_set_pts_info(st, 60, 1, 27000000);
1486 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1487 st->codec->codec_id = CODEC_ID_MPEG2TS;
1489 /* we iterate until we find two PCRs to estimate the bitrate */
1494 ret = read_packet(s, packet, ts->raw_packet_size);
1497 pid = AV_RB16(packet + 1) & 0x1fff;
1498 if ((pcr_pid == -1 || pcr_pid == pid) &&
1499 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1501 packet_count[nb_pcrs] = nb_packets;
1502 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1510 /* NOTE1: the bitrate is computed without the FEC */
1511 /* NOTE2: it is only the bitrate of the start of the stream */
1512 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1513 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1514 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1515 st->codec->bit_rate = s->bit_rate;
1516 st->start_time = ts->cur_pcr;
1518 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1519 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1523 url_fseek(pb, pos, SEEK_SET);
1529 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1531 static int mpegts_raw_read_packet(AVFormatContext *s,
1534 MpegTSContext *ts = s->priv_data;
1536 int64_t pcr_h, next_pcr_h, pos;
1537 int pcr_l, next_pcr_l;
1538 uint8_t pcr_buf[12];
1540 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1541 return AVERROR(ENOMEM);
1542 pkt->pos= url_ftell(s->pb);
1543 ret = read_packet(s, pkt->data, ts->raw_packet_size);
1545 av_free_packet(pkt);
1548 if (ts->mpeg2ts_compute_pcr) {
1549 /* compute exact PCR for each packet */
1550 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1551 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1552 pos = url_ftell(s->pb);
1553 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1554 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1555 get_buffer(s->pb, pcr_buf, 12);
1556 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1557 /* XXX: not precise enough */
1558 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1563 url_fseek(s->pb, pos, SEEK_SET);
1564 /* no next PCR found: we use previous increment */
1565 ts->cur_pcr = pcr_h * 300 + pcr_l;
1567 pkt->pts = ts->cur_pcr;
1568 pkt->duration = ts->pcr_incr;
1569 ts->cur_pcr += ts->pcr_incr;
1571 pkt->stream_index = 0;
1575 static int mpegts_read_packet(AVFormatContext *s,
1578 MpegTSContext *ts = s->priv_data;
1581 if (url_ftell(s->pb) != ts->last_pos) {
1582 /* seek detected, flush pes buffer */
1583 for (i = 0; i < NB_PID_MAX; i++) {
1584 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1585 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1586 av_freep(&pes->buffer);
1587 pes->data_index = 0;
1588 pes->state = MPEGTS_SKIP; /* skip until pes header */
1594 ret = handle_packets(ts, 0);
1596 /* flush pes data left */
1597 for (i = 0; i < NB_PID_MAX; i++) {
1598 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1599 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1600 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1601 new_pes_packet(pes, pkt);
1602 pes->state = MPEGTS_SKIP;
1610 ts->last_pos = url_ftell(s->pb);
1615 static int mpegts_read_close(AVFormatContext *s)
1617 MpegTSContext *ts = s->priv_data;
1622 for(i=0;i<NB_PID_MAX;i++)
1623 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1628 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1629 int64_t *ppos, int64_t pos_limit)
1631 MpegTSContext *ts = s->priv_data;
1632 int64_t pos, timestamp;
1633 uint8_t buf[TS_PACKET_SIZE];
1634 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1635 const int find_next= 1;
1636 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1639 url_fseek(s->pb, pos, SEEK_SET);
1640 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1641 return AV_NOPTS_VALUE;
1642 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1643 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1646 pos += ts->raw_packet_size;
1650 pos -= ts->raw_packet_size;
1652 return AV_NOPTS_VALUE;
1653 url_fseek(s->pb, pos, SEEK_SET);
1654 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1655 return AV_NOPTS_VALUE;
1656 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1657 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1667 #ifdef USE_SYNCPOINT_SEARCH
1669 static int read_seek2(AVFormatContext *s,
1678 int64_t ts_ret, ts_adj;
1679 int stream_index_gen_search;
1681 AVParserState *backup;
1683 backup = ff_store_parser_state(s);
1685 // detect direction of seeking for search purposes
1686 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
1687 AVSEEK_FLAG_BACKWARD : 0;
1689 if (flags & AVSEEK_FLAG_BYTE) {
1690 // use position directly, we will search starting from it
1693 // search for some position with good timestamp match
1694 if (stream_index < 0) {
1695 stream_index_gen_search = av_find_default_stream_index(s);
1696 if (stream_index_gen_search < 0) {
1697 ff_restore_parser_state(s, backup);
1701 st = s->streams[stream_index_gen_search];
1702 // timestamp for default must be expressed in AV_TIME_BASE units
1703 ts_adj = av_rescale(target_ts,
1705 AV_TIME_BASE * (int64_t)st->time_base.num);
1708 stream_index_gen_search = stream_index;
1710 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1714 flags, &ts_ret, mpegts_get_pcr);
1716 ff_restore_parser_state(s, backup);
1721 // search for actual matching keyframe/starting position for all streams
1722 if (ff_gen_syncpoint_search(s, stream_index, pos,
1723 min_ts, target_ts, max_ts,
1725 ff_restore_parser_state(s, backup);
1729 ff_free_parser_state(s, backup);
1733 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1736 if (flags & AVSEEK_FLAG_BACKWARD) {
1737 flags &= ~AVSEEK_FLAG_BACKWARD;
1738 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
1740 // for compatibility reasons, seek to the best-fitting timestamp
1741 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1743 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1745 // for compatibility reasons, seek to the best-fitting timestamp
1746 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1753 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1754 MpegTSContext *ts = s->priv_data;
1755 uint8_t buf[TS_PACKET_SIZE];
1758 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1761 pos= url_ftell(s->pb);
1764 url_fseek(s->pb, pos, SEEK_SET);
1765 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1767 // pid = AV_RB16(buf + 1) & 0x1fff;
1768 if(buf[1] & 0x40) break;
1769 pos += ts->raw_packet_size;
1771 url_fseek(s->pb, pos, SEEK_SET);
1778 /**************************************************************/
1779 /* parsing functions - called from other demuxers such as RTP */
1781 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
1785 ts = av_mallocz(sizeof(MpegTSContext));
1788 /* no stream case, currently used by RTP */
1789 ts->raw_packet_size = TS_PACKET_SIZE;
1795 /* return the consumed length if a packet was output, or -1 if no
1797 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1798 const uint8_t *buf, int len)
1806 if (ts->stop_parse>0)
1808 if (len < TS_PACKET_SIZE)
1810 if (buf[0] != 0x47) {
1814 handle_packet(ts, buf);
1815 buf += TS_PACKET_SIZE;
1816 len -= TS_PACKET_SIZE;
1822 void ff_mpegts_parse_close(MpegTSContext *ts)
1826 for(i=0;i<NB_PID_MAX;i++)
1827 av_free(ts->pids[i]);
1831 AVInputFormat mpegts_demuxer = {
1833 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1834 sizeof(MpegTSContext),
1841 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1842 #ifdef USE_SYNCPOINT_SEARCH
1843 .read_seek2 = read_seek2,
1847 AVInputFormat mpegtsraw_demuxer = {
1849 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1850 sizeof(MpegTSContext),
1853 mpegts_raw_read_packet,
1857 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1858 #ifdef USE_SYNCPOINT_SEARCH
1859 .read_seek2 = read_seek2,