2 * MPEG2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 //#define USE_SYNCPOINT_SEARCH
24 #include "libavutil/crc.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/log.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/mathematics.h"
29 #include "libavutil/opt.h"
30 #include "libavcodec/bytestream.h"
34 #include "avio_internal.h"
39 /* maximum size in which we look for synchronisation if
40 synchronisation is lost */
41 #define MAX_RESYNC_SIZE 65536
43 #define MAX_PES_PAYLOAD 200*1024
45 enum MpegTSFilterType {
50 typedef struct MpegTSFilter MpegTSFilter;
52 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
54 typedef struct MpegTSPESFilter {
59 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
61 typedef void SetServiceCallback(void *opaque, int ret);
63 typedef struct MpegTSSectionFilter {
67 unsigned int check_crc:1;
68 unsigned int end_of_section_reached:1;
69 SectionCallback *section_cb;
71 } MpegTSSectionFilter;
75 int last_cc; /* last cc code (-1 if first packet) */
76 enum MpegTSFilterType type;
78 MpegTSPESFilter pes_filter;
79 MpegTSSectionFilter section_filter;
83 #define MAX_PIDS_PER_PROGRAM 64
85 unsigned int id; //program id/service id
87 unsigned int pids[MAX_PIDS_PER_PROGRAM];
90 struct MpegTSContext {
93 AVFormatContext *stream;
94 /** raw packet size, including FEC if present */
99 /** if true, all pids are analyzed to find streams */
102 /** compute exact PCR for each transport stream packet */
103 int mpeg2ts_compute_pcr;
105 int64_t cur_pcr; /**< used to estimate the exact PCR */
106 int pcr_incr; /**< used to estimate the exact PCR */
108 /* data needed to handle file based ts */
109 /** stop parsing loop */
111 /** packet containing Audio/Video data */
113 /** to detect seek */
116 /******************************************/
117 /* private mpegts data */
119 /** structure to keep track of Program->pids mapping */
124 /** filters for various streams specified by PMT + for the PAT and PMT */
125 MpegTSFilter *pids[NB_PID_MAX];
128 static const AVOption options[] = {
129 {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), FF_OPT_TYPE_INT,
130 {.dbl = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
134 static const AVClass mpegtsraw_class = {
135 .class_name = "mpegtsraw demuxer",
136 .item_name = av_default_item_name,
138 .version = LIBAVUTIL_VERSION_INT,
141 /* TS stream handling */
146 MPEGTS_PESHEADER_FILL,
151 /* enough for PES header + length */
152 #define PES_START_SIZE 6
153 #define PES_HEADER_SIZE 9
154 #define MAX_PES_HEADER_SIZE (9 + 255)
156 typedef struct PESContext {
158 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
161 AVFormatContext *stream;
163 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
164 enum MpegTSState state;
165 /* used to get the format */
167 int flags; /**< copied to the AVPacket flags */
170 int extended_stream_id;
172 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
173 uint8_t header[MAX_PES_HEADER_SIZE];
177 extern AVInputFormat ff_mpegts_demuxer;
179 static void clear_program(MpegTSContext *ts, unsigned int programid)
183 for(i=0; i<ts->nb_prg; i++)
184 if(ts->prg[i].id == programid)
185 ts->prg[i].nb_pids = 0;
188 static void clear_programs(MpegTSContext *ts)
194 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
197 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
201 p = &ts->prg[ts->nb_prg];
207 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
210 struct Program *p = NULL;
211 for(i=0; i<ts->nb_prg; i++) {
212 if(ts->prg[i].id == programid) {
220 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
222 p->pids[p->nb_pids++] = pid;
226 * @brief discard_pid() decides if the pid is to be discarded according
227 * to caller's programs selection
228 * @param ts : - TS context
230 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
233 static int discard_pid(MpegTSContext *ts, unsigned int pid)
236 int used = 0, discarded = 0;
238 for(i=0; i<ts->nb_prg; i++) {
240 for(j=0; j<p->nb_pids; j++) {
241 if(p->pids[j] != pid)
243 //is program with id p->id set to be discarded?
244 for(k=0; k<ts->stream->nb_programs; k++) {
245 if(ts->stream->programs[k]->id == p->id) {
246 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
255 return !used && discarded;
259 * Assemble PES packets out of TS packets, and then call the "section_cb"
260 * function when they are complete.
262 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
263 const uint8_t *buf, int buf_size, int is_start)
265 MpegTSSectionFilter *tss = &tss1->u.section_filter;
269 memcpy(tss->section_buf, buf, buf_size);
270 tss->section_index = buf_size;
271 tss->section_h_size = -1;
272 tss->end_of_section_reached = 0;
274 if (tss->end_of_section_reached)
276 len = 4096 - tss->section_index;
279 memcpy(tss->section_buf + tss->section_index, buf, len);
280 tss->section_index += len;
283 /* compute section length if possible */
284 if (tss->section_h_size == -1 && tss->section_index >= 3) {
285 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
288 tss->section_h_size = len;
291 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
292 tss->end_of_section_reached = 1;
293 if (!tss->check_crc ||
294 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
295 tss->section_buf, tss->section_h_size) == 0)
296 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
300 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
301 SectionCallback *section_cb, void *opaque,
305 MpegTSFilter *filter;
306 MpegTSSectionFilter *sec;
308 av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
310 if (pid >= NB_PID_MAX || ts->pids[pid])
312 filter = av_mallocz(sizeof(MpegTSFilter));
315 ts->pids[pid] = filter;
316 filter->type = MPEGTS_SECTION;
318 filter->last_cc = -1;
319 sec = &filter->u.section_filter;
320 sec->section_cb = section_cb;
321 sec->opaque = opaque;
322 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
323 sec->check_crc = check_crc;
324 if (!sec->section_buf) {
331 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
335 MpegTSFilter *filter;
336 MpegTSPESFilter *pes;
338 if (pid >= NB_PID_MAX || ts->pids[pid])
340 filter = av_mallocz(sizeof(MpegTSFilter));
343 ts->pids[pid] = filter;
344 filter->type = MPEGTS_PES;
346 filter->last_cc = -1;
347 pes = &filter->u.pes_filter;
348 pes->pes_cb = pes_cb;
349 pes->opaque = opaque;
353 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
358 if (filter->type == MPEGTS_SECTION)
359 av_freep(&filter->u.section_filter.section_buf);
360 else if (filter->type == MPEGTS_PES) {
361 PESContext *pes = filter->u.pes_filter.opaque;
362 av_freep(&pes->buffer);
363 /* referenced private data will be freed later in
364 * av_close_input_stream */
365 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
366 av_freep(&filter->u.pes_filter.opaque);
371 ts->pids[pid] = NULL;
374 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
375 int stat[TS_MAX_PACKET_SIZE];
380 memset(stat, 0, packet_size*sizeof(int));
382 for(x=i=0; i<size-3; i++){
383 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
385 if(stat[x] > best_score){
392 if(x == packet_size) x= 0;
398 /* autodetect fec presence. Must have at least 1024 bytes */
399 static int get_packet_size(const uint8_t *buf, int size)
401 int score, fec_score, dvhs_score;
403 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
406 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
407 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
408 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
409 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
411 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
412 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
413 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
417 typedef struct SectionHeader {
422 uint8_t last_sec_num;
425 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
438 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
444 if ((p + 1) >= p_end)
452 /* read and allocate a DVB string preceeded by its length */
453 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
460 len = get8(&p, p_end);
463 if ((p + len) > p_end)
465 str = av_malloc(len + 1);
475 static int parse_section_header(SectionHeader *h,
476 const uint8_t **pp, const uint8_t *p_end)
480 val = get8(pp, p_end);
485 val = get16(pp, p_end);
489 val = get8(pp, p_end);
492 h->version = (val >> 1) & 0x1f;
493 val = get8(pp, p_end);
497 val = get8(pp, p_end);
500 h->last_sec_num = val;
505 uint32_t stream_type;
506 enum AVMediaType codec_type;
507 enum CodecID codec_id;
510 static const StreamType ISO_types[] = {
511 { 0x01, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
512 { 0x02, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
513 { 0x03, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
514 { 0x04, AVMEDIA_TYPE_AUDIO, CODEC_ID_MP3 },
515 { 0x0f, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC },
516 { 0x10, AVMEDIA_TYPE_VIDEO, CODEC_ID_MPEG4 },
517 { 0x11, AVMEDIA_TYPE_AUDIO, CODEC_ID_AAC_LATM }, /* LATM syntax */
518 { 0x1b, AVMEDIA_TYPE_VIDEO, CODEC_ID_H264 },
519 { 0xd1, AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
520 { 0xea, AVMEDIA_TYPE_VIDEO, CODEC_ID_VC1 },
524 static const StreamType HDMV_types[] = {
525 { 0x80, AVMEDIA_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
526 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
527 { 0x82, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
528 { 0x83, AVMEDIA_TYPE_AUDIO, CODEC_ID_TRUEHD },
529 { 0x84, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 },
530 { 0x90, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
535 static const StreamType MISC_types[] = {
536 { 0x81, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
537 { 0x8a, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
541 static const StreamType REGD_types[] = {
542 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, CODEC_ID_DIRAC },
543 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 },
544 { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, CODEC_ID_S302M },
548 /* descriptor present */
549 static const StreamType DESC_types[] = {
550 { 0x6a, AVMEDIA_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
551 { 0x7a, AVMEDIA_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
552 { 0x7b, AVMEDIA_TYPE_AUDIO, CODEC_ID_DTS },
553 { 0x56, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_TELETEXT },
554 { 0x59, AVMEDIA_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
558 static void mpegts_find_stream_type(AVStream *st,
559 uint32_t stream_type, const StreamType *types)
561 for (; types->stream_type; types++) {
562 if (stream_type == types->stream_type) {
563 st->codec->codec_type = types->codec_type;
564 st->codec->codec_id = types->codec_id;
570 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
571 uint32_t stream_type, uint32_t prog_reg_desc)
573 av_set_pts_info(st, 33, 1, 90000);
575 st->codec->codec_type = AVMEDIA_TYPE_DATA;
576 st->codec->codec_id = CODEC_ID_NONE;
577 st->need_parsing = AVSTREAM_PARSE_FULL;
579 pes->stream_type = stream_type;
581 av_log(pes->stream, AV_LOG_DEBUG,
582 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
583 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
585 st->codec->codec_tag = pes->stream_type;
587 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
588 if (prog_reg_desc == AV_RL32("HDMV") &&
589 st->codec->codec_id == CODEC_ID_NONE) {
590 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
591 if (pes->stream_type == 0x83) {
592 // HDMV TrueHD streams also contain an AC3 coded version of the
593 // audio track - add a second stream for this
595 // priv_data cannot be shared between streams
596 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
598 return AVERROR(ENOMEM);
599 memcpy(sub_pes, pes, sizeof(*sub_pes));
601 sub_st = av_new_stream(pes->stream, pes->pid);
604 return AVERROR(ENOMEM);
607 av_set_pts_info(sub_st, 33, 1, 90000);
608 sub_st->priv_data = sub_pes;
609 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
610 sub_st->codec->codec_id = CODEC_ID_AC3;
611 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
612 sub_pes->sub_st = pes->sub_st = sub_st;
615 if (st->codec->codec_id == CODEC_ID_NONE)
616 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
621 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
625 pkt->destruct = av_destruct_packet;
626 pkt->data = pes->buffer;
627 pkt->size = pes->data_index;
628 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
630 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
631 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
632 pkt->stream_index = pes->sub_st->index;
634 pkt->stream_index = pes->st->index;
637 /* store position of first TS packet of this PES packet */
638 pkt->pos = pes->ts_packet_pos;
639 pkt->flags = pes->flags;
641 /* reset pts values */
642 pes->pts = AV_NOPTS_VALUE;
643 pes->dts = AV_NOPTS_VALUE;
649 /* return non zero if a packet could be constructed */
650 static int mpegts_push_data(MpegTSFilter *filter,
651 const uint8_t *buf, int buf_size, int is_start,
654 PESContext *pes = filter->u.pes_filter.opaque;
655 MpegTSContext *ts = pes->ts;
663 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
664 new_pes_packet(pes, ts->pkt);
667 pes->state = MPEGTS_HEADER;
669 pes->ts_packet_pos = pos;
672 while (buf_size > 0) {
675 len = PES_START_SIZE - pes->data_index;
678 memcpy(pes->header + pes->data_index, p, len);
679 pes->data_index += len;
682 if (pes->data_index == PES_START_SIZE) {
683 /* we got all the PES or section header. We can now
685 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
686 pes->header[2] == 0x01) {
687 /* it must be an mpeg2 PES stream */
688 code = pes->header[3] | 0x100;
689 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
691 if ((pes->st && pes->st->discard == AVDISCARD_ALL) ||
692 code == 0x1be) /* padding_stream */
695 /* stream not present in PMT */
697 pes->st = av_new_stream(ts->stream, pes->pid);
699 return AVERROR(ENOMEM);
700 mpegts_set_stream_info(pes->st, pes, 0, 0);
703 pes->total_size = AV_RB16(pes->header + 4);
704 /* NOTE: a zero total size means the PES size is
706 if (!pes->total_size)
707 pes->total_size = MAX_PES_PAYLOAD;
709 /* allocate pes buffer */
710 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
712 return AVERROR(ENOMEM);
714 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
715 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
716 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
717 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
718 pes->state = MPEGTS_PESHEADER;
719 if (pes->st->codec->codec_id == CODEC_ID_NONE) {
720 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
721 pes->pid, pes->stream_type);
722 pes->st->codec->codec_id = CODEC_ID_PROBE;
725 pes->state = MPEGTS_PAYLOAD;
729 /* otherwise, it should be a table */
732 pes->state = MPEGTS_SKIP;
737 /**********************************************/
738 /* PES packing parsing */
739 case MPEGTS_PESHEADER:
740 len = PES_HEADER_SIZE - pes->data_index;
745 memcpy(pes->header + pes->data_index, p, len);
746 pes->data_index += len;
749 if (pes->data_index == PES_HEADER_SIZE) {
750 pes->pes_header_size = pes->header[8] + 9;
751 pes->state = MPEGTS_PESHEADER_FILL;
754 case MPEGTS_PESHEADER_FILL:
755 len = pes->pes_header_size - pes->data_index;
760 memcpy(pes->header + pes->data_index, p, len);
761 pes->data_index += len;
764 if (pes->data_index == pes->pes_header_size) {
766 unsigned int flags, pes_ext, skip;
768 flags = pes->header[7];
770 pes->pts = AV_NOPTS_VALUE;
771 pes->dts = AV_NOPTS_VALUE;
772 if ((flags & 0xc0) == 0x80) {
773 pes->dts = pes->pts = ff_parse_pes_pts(r);
775 } else if ((flags & 0xc0) == 0xc0) {
776 pes->pts = ff_parse_pes_pts(r);
778 pes->dts = ff_parse_pes_pts(r);
781 pes->extended_stream_id = -1;
782 if (flags & 0x01) { /* PES extension */
784 /* Skip PES private data, program packet sequence counter and P-STD buffer */
785 skip = (pes_ext >> 4) & 0xb;
788 if ((pes_ext & 0x41) == 0x01 &&
789 (r + 2) <= (pes->header + pes->pes_header_size)) {
790 /* PES extension 2 */
791 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
792 pes->extended_stream_id = r[1];
796 /* we got the full header. We parse it and get the payload */
797 pes->state = MPEGTS_PAYLOAD;
802 if (buf_size > 0 && pes->buffer) {
803 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
804 new_pes_packet(pes, ts->pkt);
805 pes->total_size = MAX_PES_PAYLOAD;
806 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
808 return AVERROR(ENOMEM);
810 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
811 // pes packet size is < ts size packet and pes data is padded with 0xff
812 // not sure if this is legal in ts but see issue #2392
813 buf_size = pes->total_size;
814 pes->flags |= AV_PKT_FLAG_CORRUPT;
816 memcpy(pes->buffer+pes->data_index, p, buf_size);
817 pes->data_index += buf_size;
820 /* emit complete packets with known packet size
821 * decreases demuxer delay for infrequent packets like subtitles from
822 * a couple of seconds to milliseconds for properly muxed files.
823 * total_size is the number of bytes following pes_packet_length
824 * in the pes header, i.e. not counting the first 6 bytes */
825 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
826 pes->pes_header_size + pes->data_index == pes->total_size + 6) {
828 new_pes_packet(pes, ts->pkt);
840 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
845 /* if no pid found, then add a pid context */
846 pes = av_mallocz(sizeof(PESContext));
850 pes->stream = ts->stream;
852 pes->pcr_pid = pcr_pid;
853 pes->state = MPEGTS_SKIP;
854 pes->pts = AV_NOPTS_VALUE;
855 pes->dts = AV_NOPTS_VALUE;
856 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
864 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
865 int *es_id, uint8_t **dec_config_descr,
866 int *dec_config_descr_size)
872 ffio_init_context(&pb, buf, size, 0, NULL, NULL, NULL, NULL);
874 len = ff_mp4_read_descr(s, &pb, &tag);
875 if (tag == MP4IODescrTag) {
876 avio_rb16(&pb); // ID
882 len = ff_mp4_read_descr(s, &pb, &tag);
883 if (tag == MP4ESDescrTag) {
884 *es_id = avio_rb16(&pb); /* ES_ID */
885 av_dlog(s, "ES_ID %#x\n", *es_id);
886 avio_r8(&pb); /* priority */
887 len = ff_mp4_read_descr(s, &pb, &tag);
888 if (tag == MP4DecConfigDescrTag) {
889 *dec_config_descr = av_malloc(len);
890 if (!*dec_config_descr)
891 return AVERROR(ENOMEM);
892 *dec_config_descr_size = len;
893 avio_read(&pb, *dec_config_descr, len);
900 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
901 const uint8_t **pp, const uint8_t *desc_list_end,
902 int mp4_dec_config_descr_len, int mp4_es_id, int pid,
903 uint8_t *mp4_dec_config_descr)
905 const uint8_t *desc_end;
906 int desc_len, desc_tag;
910 desc_tag = get8(pp, desc_list_end);
913 desc_len = get8(pp, desc_list_end);
916 desc_end = *pp + desc_len;
917 if (desc_end > desc_list_end)
920 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
922 if (st->codec->codec_id == CODEC_ID_NONE &&
923 stream_type == STREAM_TYPE_PRIVATE_DATA)
924 mpegts_find_stream_type(st, desc_tag, DESC_types);
927 case 0x1F: /* FMC descriptor */
929 if (st->codec->codec_id == CODEC_ID_AAC_LATM &&
930 mp4_dec_config_descr_len && mp4_es_id == pid) {
932 ffio_init_context(&pb, mp4_dec_config_descr,
933 mp4_dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
934 ff_mp4_read_dec_config_descr(fc, st, &pb);
935 if (st->codec->codec_id == CODEC_ID_AAC &&
936 st->codec->extradata_size > 0)
937 st->need_parsing = 0;
940 case 0x56: /* DVB teletext descriptor */
941 language[0] = get8(pp, desc_end);
942 language[1] = get8(pp, desc_end);
943 language[2] = get8(pp, desc_end);
945 av_dict_set(&st->metadata, "language", language, 0);
947 case 0x59: /* subtitling descriptor */
948 language[0] = get8(pp, desc_end);
949 language[1] = get8(pp, desc_end);
950 language[2] = get8(pp, desc_end);
952 /* hearing impaired subtitles detection */
953 switch(get8(pp, desc_end)) {
954 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
955 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
956 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
957 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
958 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
959 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
960 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
963 if (st->codec->extradata) {
964 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
965 av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
967 st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
968 if (st->codec->extradata) {
969 st->codec->extradata_size = 4;
970 memcpy(st->codec->extradata, *pp, 4);
974 av_dict_set(&st->metadata, "language", language, 0);
976 case 0x0a: /* ISO 639 language descriptor */
977 for (i = 0; i + 4 <= desc_len; i += 4) {
978 language[i + 0] = get8(pp, desc_end);
979 language[i + 1] = get8(pp, desc_end);
980 language[i + 2] = get8(pp, desc_end);
981 language[i + 3] = ',';
982 switch (get8(pp, desc_end)) {
983 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
984 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
985 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
990 av_dict_set(&st->metadata, "language", language, 0);
993 case 0x05: /* registration descriptor */
994 st->codec->codec_tag = bytestream_get_le32(pp);
995 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
996 if (st->codec->codec_id == CODEC_ID_NONE &&
997 stream_type == STREAM_TYPE_PRIVATE_DATA)
998 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1007 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1009 MpegTSContext *ts = filter->u.section_filter.opaque;
1010 SectionHeader h1, *h = &h1;
1013 const uint8_t *p, *p_end, *desc_list_end;
1014 int program_info_length, pcr_pid, pid, stream_type;
1016 uint32_t prog_reg_desc = 0; /* registration descriptor */
1017 uint8_t *mp4_dec_config_descr = NULL;
1018 int mp4_dec_config_descr_len = 0;
1021 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1022 hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
1024 p_end = section + section_len - 4;
1026 if (parse_section_header(h, &p, p_end) < 0)
1029 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1030 h->id, h->sec_num, h->last_sec_num);
1032 if (h->tid != PMT_TID)
1035 clear_program(ts, h->id);
1036 pcr_pid = get16(&p, p_end) & 0x1fff;
1039 add_pid_to_pmt(ts, h->id, pcr_pid);
1041 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1043 program_info_length = get16(&p, p_end) & 0xfff;
1044 if (program_info_length < 0)
1046 while(program_info_length >= 2) {
1048 tag = get8(&p, p_end);
1049 len = get8(&p, p_end);
1051 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1053 if(len > program_info_length - 2)
1054 //something else is broken, exit the program_descriptors_loop
1056 program_info_length -= len + 2;
1057 if (tag == 0x1d) { // IOD descriptor
1058 get8(&p, p_end); // scope
1059 get8(&p, p_end); // label
1061 mp4_read_iods(ts->stream, p, len, &mp4_es_id,
1062 &mp4_dec_config_descr, &mp4_dec_config_descr_len);
1063 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1064 prog_reg_desc = bytestream_get_le32(&p);
1069 p += program_info_length;
1073 // stop parsing after pmt, we found header
1074 if (!ts->stream->nb_streams)
1079 stream_type = get8(&p, p_end);
1080 if (stream_type < 0)
1082 pid = get16(&p, p_end) & 0x1fff;
1086 /* now create ffmpeg stream */
1087 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1088 pes = ts->pids[pid]->u.pes_filter.opaque;
1090 pes->st = av_new_stream(pes->stream, pes->pid);
1093 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1094 pes = add_pes_stream(ts, pid, pcr_pid);
1096 st = av_new_stream(pes->stream, pes->pid);
1102 if (!pes->stream_type)
1103 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1105 add_pid_to_pmt(ts, h->id, pid);
1107 ff_program_add_stream_index(ts->stream, h->id, st->index);
1109 desc_list_len = get16(&p, p_end) & 0xfff;
1110 if (desc_list_len < 0)
1112 desc_list_end = p + desc_list_len;
1113 if (desc_list_end > p_end)
1116 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1117 mp4_dec_config_descr_len, mp4_es_id, pid, mp4_dec_config_descr) < 0)
1120 if (prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1121 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1122 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1129 av_free(mp4_dec_config_descr);
1132 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1134 MpegTSContext *ts = filter->u.section_filter.opaque;
1135 SectionHeader h1, *h = &h1;
1136 const uint8_t *p, *p_end;
1139 av_dlog(ts->stream, "PAT:\n");
1140 hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
1142 p_end = section + section_len - 4;
1144 if (parse_section_header(h, &p, p_end) < 0)
1146 if (h->tid != PAT_TID)
1151 sid = get16(&p, p_end);
1154 pmt_pid = get16(&p, p_end) & 0x1fff;
1158 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1160 if (sid == 0x0000) {
1163 av_new_program(ts->stream, sid);
1164 if (ts->pids[pmt_pid])
1165 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1166 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1167 add_pat_entry(ts, sid);
1168 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1169 add_pid_to_pmt(ts, sid, pmt_pid);
1174 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1176 MpegTSContext *ts = filter->u.section_filter.opaque;
1177 SectionHeader h1, *h = &h1;
1178 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1179 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1180 char *name, *provider_name;
1182 av_dlog(ts->stream, "SDT:\n");
1183 hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
1185 p_end = section + section_len - 4;
1187 if (parse_section_header(h, &p, p_end) < 0)
1189 if (h->tid != SDT_TID)
1191 onid = get16(&p, p_end);
1194 val = get8(&p, p_end);
1198 sid = get16(&p, p_end);
1201 val = get8(&p, p_end);
1204 desc_list_len = get16(&p, p_end) & 0xfff;
1205 if (desc_list_len < 0)
1207 desc_list_end = p + desc_list_len;
1208 if (desc_list_end > p_end)
1211 desc_tag = get8(&p, desc_list_end);
1214 desc_len = get8(&p, desc_list_end);
1215 desc_end = p + desc_len;
1216 if (desc_end > desc_list_end)
1219 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1220 desc_tag, desc_len);
1224 service_type = get8(&p, p_end);
1225 if (service_type < 0)
1227 provider_name = getstr8(&p, p_end);
1230 name = getstr8(&p, p_end);
1232 AVProgram *program = av_new_program(ts->stream, sid);
1234 av_dict_set(&program->metadata, "service_name", name, 0);
1235 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1239 av_free(provider_name);
1250 /* handle one TS packet */
1251 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1253 AVFormatContext *s = ts->stream;
1255 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1256 has_adaptation, has_payload;
1257 const uint8_t *p, *p_end;
1260 pid = AV_RB16(packet + 1) & 0x1fff;
1261 if(pid && discard_pid(ts, pid))
1263 is_start = packet[1] & 0x40;
1264 tss = ts->pids[pid];
1265 if (ts->auto_guess && tss == NULL && is_start) {
1266 add_pes_stream(ts, pid, -1);
1267 tss = ts->pids[pid];
1272 afc = (packet[3] >> 4) & 3;
1273 if (afc == 0) /* reserved value */
1275 has_adaptation = afc & 2;
1276 has_payload = afc & 1;
1277 is_discontinuity = has_adaptation
1278 && packet[4] != 0 /* with length > 0 */
1279 && (packet[5] & 0x80); /* and discontinuity indicated */
1281 /* continuity check (currently not used) */
1282 cc = (packet[3] & 0xf);
1283 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1284 cc_ok = pid == 0x1FFF // null packet PID
1287 || expected_cc == cc;
1291 av_log(NULL, AV_LOG_WARNING, "Continuity Check Failed\n");
1292 if(tss->type == MPEGTS_PES) {
1293 PESContext *pc = tss->u.pes_filter.opaque;
1294 pc->flags |= AV_PKT_FLAG_CORRUPT;
1301 if (has_adaptation) {
1302 /* skip adapation field */
1305 /* if past the end of packet, ignore */
1306 p_end = packet + TS_PACKET_SIZE;
1310 pos = avio_tell(ts->stream->pb);
1311 ts->pos47= pos % ts->raw_packet_size;
1313 if (tss->type == MPEGTS_SECTION) {
1315 /* pointer field present */
1317 if (p + len > p_end)
1320 /* write remaining section bytes */
1321 write_section_data(s, tss,
1323 /* check whether filter has been closed */
1329 write_section_data(s, tss,
1334 write_section_data(s, tss,
1340 // Note: The position here points actually behind the current packet.
1341 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1342 pos - ts->raw_packet_size)) < 0)
1349 /* XXX: try to find a better synchro over several packets (use
1350 get_packet_size() ?) */
1351 static int mpegts_resync(AVFormatContext *s)
1353 AVIOContext *pb = s->pb;
1356 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1358 if (pb->eof_reached)
1361 avio_seek(pb, -1, SEEK_CUR);
1365 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1370 /* return -1 if error or EOF. Return 0 if OK. */
1371 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1373 AVIOContext *pb = s->pb;
1377 len = avio_read(pb, buf, TS_PACKET_SIZE);
1378 if (len != TS_PACKET_SIZE)
1379 return len < 0 ? len : AVERROR_EOF;
1380 /* check paquet sync byte */
1381 if (buf[0] != 0x47) {
1382 /* find a new packet start */
1383 avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1384 if (mpegts_resync(s) < 0)
1385 return AVERROR(EAGAIN);
1389 skip = raw_packet_size - TS_PACKET_SIZE;
1391 avio_skip(pb, skip);
1398 static int handle_packets(MpegTSContext *ts, int nb_packets)
1400 AVFormatContext *s = ts->stream;
1401 uint8_t packet[TS_PACKET_SIZE];
1402 int packet_num, ret = 0;
1404 if (avio_tell(s->pb) != ts->last_pos) {
1406 av_dlog("Skipping after seek\n");
1407 /* seek detected, flush pes buffer */
1408 for (i = 0; i < NB_PID_MAX; i++) {
1409 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1410 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1411 av_freep(&pes->buffer);
1412 ts->pids[i]->last_cc = -1;
1413 pes->data_index = 0;
1414 pes->state = MPEGTS_SKIP; /* skip until pes header */
1422 if (ts->stop_parse>0)
1425 if (nb_packets != 0 && packet_num >= nb_packets)
1427 ret = read_packet(s, packet, ts->raw_packet_size);
1430 ret = handle_packet(ts, packet);
1434 ts->last_pos = avio_tell(s->pb);
1438 static int mpegts_probe(AVProbeData *p)
1441 const int size= p->buf_size;
1442 int score, fec_score, dvhs_score;
1443 int check_count= size / TS_FEC_PACKET_SIZE;
1444 #define CHECK_COUNT 10
1446 if (check_count < CHECK_COUNT)
1449 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1450 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1451 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1452 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1454 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1455 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1456 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1457 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1460 /* only use the extension for safer guess */
1461 if (av_match_ext(p->filename, "ts"))
1462 return AVPROBE_SCORE_MAX;
1468 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1469 (-1) if not available */
1470 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1471 const uint8_t *packet)
1473 int afc, len, flags;
1477 afc = (packet[3] >> 4) & 3;
1487 if (!(flags & 0x10))
1492 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1493 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1497 static int mpegts_read_header(AVFormatContext *s,
1498 AVFormatParameters *ap)
1500 MpegTSContext *ts = s->priv_data;
1501 AVIOContext *pb = s->pb;
1502 uint8_t buf[5*1024];
1506 #if FF_API_FORMAT_PARAMETERS
1508 if (ap->mpeg2ts_compute_pcr)
1509 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1513 /* read the first 1024 bytes to get packet size */
1514 pos = avio_tell(pb);
1515 len = avio_read(pb, buf, sizeof(buf));
1516 if (len != sizeof(buf))
1518 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1519 if (ts->raw_packet_size <= 0)
1524 if (s->iformat == &ff_mpegts_demuxer) {
1527 /* first do a scaning to get all the services */
1528 if (pb->seekable && avio_seek(pb, pos, SEEK_SET) < 0)
1529 av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1531 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1533 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1535 handle_packets(ts, s->probesize / ts->raw_packet_size);
1536 /* if could not find service, enable auto_guess */
1540 av_dlog(ts->stream, "tuning done\n");
1542 s->ctx_flags |= AVFMTCTX_NOHEADER;
1545 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1546 int64_t pcrs[2], pcr_h;
1547 int packet_count[2];
1548 uint8_t packet[TS_PACKET_SIZE];
1550 /* only read packets */
1552 st = av_new_stream(s, 0);
1555 av_set_pts_info(st, 60, 1, 27000000);
1556 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1557 st->codec->codec_id = CODEC_ID_MPEG2TS;
1559 /* we iterate until we find two PCRs to estimate the bitrate */
1564 ret = read_packet(s, packet, ts->raw_packet_size);
1567 pid = AV_RB16(packet + 1) & 0x1fff;
1568 if ((pcr_pid == -1 || pcr_pid == pid) &&
1569 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1571 packet_count[nb_pcrs] = nb_packets;
1572 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1580 /* NOTE1: the bitrate is computed without the FEC */
1581 /* NOTE2: it is only the bitrate of the start of the stream */
1582 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1583 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1584 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1585 st->codec->bit_rate = s->bit_rate;
1586 st->start_time = ts->cur_pcr;
1587 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
1588 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1591 avio_seek(pb, pos, SEEK_SET);
1597 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1599 static int mpegts_raw_read_packet(AVFormatContext *s,
1602 MpegTSContext *ts = s->priv_data;
1604 int64_t pcr_h, next_pcr_h, pos;
1605 int pcr_l, next_pcr_l;
1606 uint8_t pcr_buf[12];
1608 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1609 return AVERROR(ENOMEM);
1610 pkt->pos= avio_tell(s->pb);
1611 ret = read_packet(s, pkt->data, ts->raw_packet_size);
1613 av_free_packet(pkt);
1616 if (ts->mpeg2ts_compute_pcr) {
1617 /* compute exact PCR for each packet */
1618 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1619 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1620 pos = avio_tell(s->pb);
1621 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1622 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1623 avio_read(s->pb, pcr_buf, 12);
1624 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1625 /* XXX: not precise enough */
1626 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1631 avio_seek(s->pb, pos, SEEK_SET);
1632 /* no next PCR found: we use previous increment */
1633 ts->cur_pcr = pcr_h * 300 + pcr_l;
1635 pkt->pts = ts->cur_pcr;
1636 pkt->duration = ts->pcr_incr;
1637 ts->cur_pcr += ts->pcr_incr;
1639 pkt->stream_index = 0;
1643 static int mpegts_read_packet(AVFormatContext *s,
1646 MpegTSContext *ts = s->priv_data;
1650 ret = handle_packets(ts, 0);
1652 /* flush pes data left */
1653 for (i = 0; i < NB_PID_MAX; i++) {
1654 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1655 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1656 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1657 new_pes_packet(pes, pkt);
1658 pes->state = MPEGTS_SKIP;
1669 static int mpegts_read_close(AVFormatContext *s)
1671 MpegTSContext *ts = s->priv_data;
1676 for(i=0;i<NB_PID_MAX;i++)
1677 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1682 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1683 int64_t *ppos, int64_t pos_limit)
1685 MpegTSContext *ts = s->priv_data;
1686 int64_t pos, timestamp;
1687 uint8_t buf[TS_PACKET_SIZE];
1688 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1689 const int find_next= 1;
1690 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1693 avio_seek(s->pb, pos, SEEK_SET);
1694 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1695 return AV_NOPTS_VALUE;
1696 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1697 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1700 pos += ts->raw_packet_size;
1704 pos -= ts->raw_packet_size;
1706 return AV_NOPTS_VALUE;
1707 avio_seek(s->pb, pos, SEEK_SET);
1708 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1709 return AV_NOPTS_VALUE;
1710 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1711 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1721 #ifdef USE_SYNCPOINT_SEARCH
1723 static int read_seek2(AVFormatContext *s,
1732 int64_t ts_ret, ts_adj;
1733 int stream_index_gen_search;
1735 AVParserState *backup;
1737 backup = ff_store_parser_state(s);
1739 // detect direction of seeking for search purposes
1740 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
1741 AVSEEK_FLAG_BACKWARD : 0;
1743 if (flags & AVSEEK_FLAG_BYTE) {
1744 // use position directly, we will search starting from it
1747 // search for some position with good timestamp match
1748 if (stream_index < 0) {
1749 stream_index_gen_search = av_find_default_stream_index(s);
1750 if (stream_index_gen_search < 0) {
1751 ff_restore_parser_state(s, backup);
1755 st = s->streams[stream_index_gen_search];
1756 // timestamp for default must be expressed in AV_TIME_BASE units
1757 ts_adj = av_rescale(target_ts,
1759 AV_TIME_BASE * (int64_t)st->time_base.num);
1762 stream_index_gen_search = stream_index;
1764 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1768 flags, &ts_ret, mpegts_get_pcr);
1770 ff_restore_parser_state(s, backup);
1775 // search for actual matching keyframe/starting position for all streams
1776 if (ff_gen_syncpoint_search(s, stream_index, pos,
1777 min_ts, target_ts, max_ts,
1779 ff_restore_parser_state(s, backup);
1783 ff_free_parser_state(s, backup);
1787 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1790 if (flags & AVSEEK_FLAG_BACKWARD) {
1791 flags &= ~AVSEEK_FLAG_BACKWARD;
1792 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
1794 // for compatibility reasons, seek to the best-fitting timestamp
1795 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1797 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1799 // for compatibility reasons, seek to the best-fitting timestamp
1800 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1807 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1808 MpegTSContext *ts = s->priv_data;
1809 uint8_t buf[TS_PACKET_SIZE];
1812 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1815 pos= avio_tell(s->pb);
1818 avio_seek(s->pb, pos, SEEK_SET);
1819 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1821 // pid = AV_RB16(buf + 1) & 0x1fff;
1822 if(buf[1] & 0x40) break;
1823 pos += ts->raw_packet_size;
1825 avio_seek(s->pb, pos, SEEK_SET);
1832 /**************************************************************/
1833 /* parsing functions - called from other demuxers such as RTP */
1835 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
1839 ts = av_mallocz(sizeof(MpegTSContext));
1842 /* no stream case, currently used by RTP */
1843 ts->raw_packet_size = TS_PACKET_SIZE;
1849 /* return the consumed length if a packet was output, or -1 if no
1851 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1852 const uint8_t *buf, int len)
1860 if (ts->stop_parse>0)
1862 if (len < TS_PACKET_SIZE)
1864 if (buf[0] != 0x47) {
1868 handle_packet(ts, buf);
1869 buf += TS_PACKET_SIZE;
1870 len -= TS_PACKET_SIZE;
1876 void ff_mpegts_parse_close(MpegTSContext *ts)
1880 for(i=0;i<NB_PID_MAX;i++)
1881 av_free(ts->pids[i]);
1885 AVInputFormat ff_mpegts_demuxer = {
1887 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1888 .priv_data_size = sizeof(MpegTSContext),
1889 .read_probe = mpegts_probe,
1890 .read_header = mpegts_read_header,
1891 .read_packet = mpegts_read_packet,
1892 .read_close = mpegts_read_close,
1893 .read_seek = read_seek,
1894 .read_timestamp = mpegts_get_pcr,
1895 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1896 #ifdef USE_SYNCPOINT_SEARCH
1897 .read_seek2 = read_seek2,
1901 AVInputFormat ff_mpegtsraw_demuxer = {
1902 .name = "mpegtsraw",
1903 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1904 .priv_data_size = sizeof(MpegTSContext),
1905 .read_header = mpegts_read_header,
1906 .read_packet = mpegts_raw_read_packet,
1907 .read_close = mpegts_read_close,
1908 .read_seek = read_seek,
1909 .read_timestamp = mpegts_get_pcr,
1910 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1911 #ifdef USE_SYNCPOINT_SEARCH
1912 .read_seek2 = read_seek2,
1914 .priv_class = &mpegtsraw_class,