2 * MPEG2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/buffer.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/log.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/mathematics.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/avassert.h"
30 #include "libavcodec/bytestream.h"
31 #include "libavcodec/get_bits.h"
32 #include "libavcodec/mathops.h"
36 #include "avio_internal.h"
41 /* maximum size in which we look for synchronisation if
42 synchronisation is lost */
43 #define MAX_RESYNC_SIZE 65536
45 #define MAX_PES_PAYLOAD 200*1024
47 #define MAX_MP4_DESCR_COUNT 16
49 enum MpegTSFilterType {
54 typedef struct MpegTSFilter MpegTSFilter;
56 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos, int64_t cur_pcr);
58 typedef struct MpegTSPESFilter {
63 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
65 typedef void SetServiceCallback(void *opaque, int ret);
67 typedef struct MpegTSSectionFilter {
71 unsigned int check_crc:1;
72 unsigned int end_of_section_reached:1;
73 SectionCallback *section_cb;
75 } MpegTSSectionFilter;
80 int last_cc; /* last cc code (-1 if first packet) */
81 enum MpegTSFilterType type;
83 MpegTSPESFilter pes_filter;
84 MpegTSSectionFilter section_filter;
88 #define MAX_PIDS_PER_PROGRAM 64
90 unsigned int id; //program id/service id
92 unsigned int pids[MAX_PIDS_PER_PROGRAM];
94 /** have we found pmt for this program */
98 struct MpegTSContext {
101 AVFormatContext *stream;
102 /** raw packet size, including FEC if present */
107 #define SIZE_STAT_THRESHOLD 10
111 /** if true, all pids are analyzed to find streams */
114 /** compute exact PCR for each transport stream packet */
115 int mpeg2ts_compute_pcr;
117 /** fix dvb teletext pts */
118 int fix_teletext_pts;
120 int64_t cur_pcr; /**< used to estimate the exact PCR */
121 int pcr_incr; /**< used to estimate the exact PCR */
123 /* data needed to handle file based ts */
124 /** stop parsing loop */
126 /** packet containing Audio/Video data */
128 /** to detect seek */
131 /******************************************/
132 /* private mpegts data */
134 /** structure to keep track of Program->pids mapping */
138 int8_t crc_validity[NB_PID_MAX];
140 /** filters for various streams specified by PMT + for the PAT and PMT */
141 MpegTSFilter *pids[NB_PID_MAX];
145 static const AVOption mpegtsraw_options[] = {
146 {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
147 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
151 static const AVClass mpegtsraw_class = {
152 .class_name = "mpegtsraw demuxer",
153 .item_name = av_default_item_name,
154 .option = mpegtsraw_options,
155 .version = LIBAVUTIL_VERSION_INT,
158 static const AVOption mpegts_options[] = {
159 {"fix_teletext_pts", "Try to fix pts values of dvb teletext streams.", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_INT,
160 {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
164 static const AVClass mpegts_class = {
165 .class_name = "mpegts demuxer",
166 .item_name = av_default_item_name,
167 .option = mpegts_options,
168 .version = LIBAVUTIL_VERSION_INT,
171 /* TS stream handling */
176 MPEGTS_PESHEADER_FILL,
181 /* enough for PES header + length */
182 #define PES_START_SIZE 6
183 #define PES_HEADER_SIZE 9
184 #define MAX_PES_HEADER_SIZE (9 + 255)
186 typedef struct PESContext {
188 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
191 AVFormatContext *stream;
193 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
194 enum MpegTSState state;
195 /* used to get the format */
197 int flags; /**< copied to the AVPacket flags */
200 int extended_stream_id;
202 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
203 uint8_t header[MAX_PES_HEADER_SIZE];
209 extern AVInputFormat ff_mpegts_demuxer;
211 static struct Program * get_program(MpegTSContext *ts, unsigned int programid)
214 for(i=0; i<ts->nb_prg; i++) {
215 if(ts->prg[i].id == programid) {
222 static void clear_avprogram(MpegTSContext *ts, unsigned int programid)
224 AVProgram *prg = NULL;
226 for(i=0; i<ts->stream->nb_programs; i++)
227 if(ts->stream->programs[i]->id == programid){
228 prg = ts->stream->programs[i];
233 prg->nb_stream_indexes = 0;
236 static void clear_program(MpegTSContext *ts, unsigned int programid)
240 clear_avprogram(ts, programid);
241 for(i=0; i<ts->nb_prg; i++)
242 if(ts->prg[i].id == programid) {
243 ts->prg[i].nb_pids = 0;
244 ts->prg[i].pmt_found = 0;
248 static void clear_programs(MpegTSContext *ts)
254 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
257 if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) {
261 p = &ts->prg[ts->nb_prg];
268 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
270 struct Program *p = get_program(ts, programid);
274 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
276 p->pids[p->nb_pids++] = pid;
279 static void set_pmt_found(MpegTSContext *ts, unsigned int programid)
281 struct Program *p = get_program(ts, programid);
288 static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
291 for(i=0; i<s->nb_programs; i++) {
292 if(s->programs[i]->id == programid) {
293 s->programs[i]->pcr_pid = pid;
300 * @brief discard_pid() decides if the pid is to be discarded according
301 * to caller's programs selection
302 * @param ts : - TS context
304 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
307 static int discard_pid(MpegTSContext *ts, unsigned int pid)
310 int used = 0, discarded = 0;
313 /* If none of the programs have .discard=AVDISCARD_ALL then there's
314 * no way we have to discard this packet
316 for (k = 0; k < ts->stream->nb_programs; k++) {
317 if (ts->stream->programs[k]->discard == AVDISCARD_ALL)
320 if (k == ts->stream->nb_programs)
323 for(i=0; i<ts->nb_prg; i++) {
325 for(j=0; j<p->nb_pids; j++) {
326 if(p->pids[j] != pid)
328 //is program with id p->id set to be discarded?
329 for(k=0; k<ts->stream->nb_programs; k++) {
330 if(ts->stream->programs[k]->id == p->id) {
331 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
340 return !used && discarded;
344 * Assemble PES packets out of TS packets, and then call the "section_cb"
345 * function when they are complete.
347 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
348 const uint8_t *buf, int buf_size, int is_start)
350 MpegTSContext *ts = s->priv_data;
351 MpegTSSectionFilter *tss = &tss1->u.section_filter;
355 memcpy(tss->section_buf, buf, buf_size);
356 tss->section_index = buf_size;
357 tss->section_h_size = -1;
358 tss->end_of_section_reached = 0;
360 if (tss->end_of_section_reached)
362 len = 4096 - tss->section_index;
365 memcpy(tss->section_buf + tss->section_index, buf, len);
366 tss->section_index += len;
369 /* compute section length if possible */
370 if (tss->section_h_size == -1 && tss->section_index >= 3) {
371 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
374 tss->section_h_size = len;
377 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
379 tss->end_of_section_reached = 1;
382 crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size);
384 ts->crc_validity[ tss1->pid ] = 100;
385 }else if(ts->crc_validity[ tss1->pid ] > -10){
386 ts->crc_validity[ tss1->pid ]--;
391 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
395 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
396 SectionCallback *section_cb, void *opaque,
400 MpegTSFilter *filter;
401 MpegTSSectionFilter *sec;
403 av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
405 if (pid >= NB_PID_MAX || ts->pids[pid])
407 filter = av_mallocz(sizeof(MpegTSFilter));
410 ts->pids[pid] = filter;
411 filter->type = MPEGTS_SECTION;
414 filter->last_cc = -1;
415 sec = &filter->u.section_filter;
416 sec->section_cb = section_cb;
417 sec->opaque = opaque;
418 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
419 sec->check_crc = check_crc;
420 if (!sec->section_buf) {
427 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
431 MpegTSFilter *filter;
432 MpegTSPESFilter *pes;
434 if (pid >= NB_PID_MAX || ts->pids[pid])
436 filter = av_mallocz(sizeof(MpegTSFilter));
439 ts->pids[pid] = filter;
440 filter->type = MPEGTS_PES;
443 filter->last_cc = -1;
444 pes = &filter->u.pes_filter;
445 pes->pes_cb = pes_cb;
446 pes->opaque = opaque;
450 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
455 if (filter->type == MPEGTS_SECTION)
456 av_freep(&filter->u.section_filter.section_buf);
457 else if (filter->type == MPEGTS_PES) {
458 PESContext *pes = filter->u.pes_filter.opaque;
459 av_buffer_unref(&pes->buffer);
460 /* referenced private data will be freed later in
461 * avformat_close_input */
462 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
463 av_freep(&filter->u.pes_filter.opaque);
468 ts->pids[pid] = NULL;
471 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
472 int stat[TS_MAX_PACKET_SIZE];
476 memset(stat, 0, packet_size*sizeof(*stat));
478 for(i=0; i<size-3; i++){
479 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && buf[i+3] != 0x47){
480 int x = i % packet_size;
482 if(stat[x] > best_score){
492 /* autodetect fec presence. Must have at least 1024 bytes */
493 static int get_packet_size(const uint8_t *buf, int size)
495 int score, fec_score, dvhs_score;
497 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
500 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
501 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
502 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
503 av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
504 score, dvhs_score, fec_score);
506 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
507 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
508 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
512 typedef struct SectionHeader {
517 uint8_t last_sec_num;
520 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
533 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
539 if ((p + 1) >= p_end)
547 /* read and allocate a DVB string preceded by its length */
548 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
555 len = get8(&p, p_end);
558 if ((p + len) > p_end)
560 str = av_malloc(len + 1);
570 static int parse_section_header(SectionHeader *h,
571 const uint8_t **pp, const uint8_t *p_end)
575 val = get8(pp, p_end);
580 val = get16(pp, p_end);
584 val = get8(pp, p_end);
587 h->version = (val >> 1) & 0x1f;
588 val = get8(pp, p_end);
592 val = get8(pp, p_end);
595 h->last_sec_num = val;
600 uint32_t stream_type;
601 enum AVMediaType codec_type;
602 enum AVCodecID codec_id;
605 static const StreamType ISO_types[] = {
606 { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
607 { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
608 { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
609 { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
610 { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
611 { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
612 /* Makito encoder sets stream type 0x11 for AAC,
613 * so auto-detect LOAS/LATM instead of hardcoding it. */
614 #if !CONFIG_LOAS_DEMUXER
615 { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
617 { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
618 { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
619 { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
620 { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
621 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
625 static const StreamType HDMV_types[] = {
626 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
627 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
628 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
629 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
630 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
631 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
632 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
633 { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
634 { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
635 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
640 static const StreamType MISC_types[] = {
641 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
642 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
646 static const StreamType REGD_types[] = {
647 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
648 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
649 { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
650 { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
651 { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
652 { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
653 { MKTAG('H','E','V','C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
654 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
655 { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
659 static const StreamType METADATA_types[] = {
660 { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV },
664 /* descriptor present */
665 static const StreamType DESC_types[] = {
666 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
667 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
668 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
669 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
670 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
674 static void mpegts_find_stream_type(AVStream *st,
675 uint32_t stream_type, const StreamType *types)
677 if (avcodec_is_open(st->codec)) {
678 av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
682 for (; types->stream_type; types++) {
683 if (stream_type == types->stream_type) {
684 st->codec->codec_type = types->codec_type;
685 st->codec->codec_id = types->codec_id;
686 st->request_probe = 0;
692 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
693 uint32_t stream_type, uint32_t prog_reg_desc)
695 int old_codec_type= st->codec->codec_type;
696 int old_codec_id = st->codec->codec_id;
698 if (avcodec_is_open(st->codec)) {
699 av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n");
703 avpriv_set_pts_info(st, 33, 1, 90000);
705 st->codec->codec_type = AVMEDIA_TYPE_DATA;
706 st->codec->codec_id = AV_CODEC_ID_NONE;
707 st->need_parsing = AVSTREAM_PARSE_FULL;
709 pes->stream_type = stream_type;
711 av_log(pes->stream, AV_LOG_DEBUG,
712 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
713 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
715 st->codec->codec_tag = pes->stream_type;
717 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
718 if ((prog_reg_desc == AV_RL32("HDMV") ||
719 prog_reg_desc == AV_RL32("HDPR")) &&
720 st->codec->codec_id == AV_CODEC_ID_NONE) {
721 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
722 if (pes->stream_type == 0x83) {
723 // HDMV TrueHD streams also contain an AC3 coded version of the
724 // audio track - add a second stream for this
726 // priv_data cannot be shared between streams
727 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
729 return AVERROR(ENOMEM);
730 memcpy(sub_pes, pes, sizeof(*sub_pes));
732 sub_st = avformat_new_stream(pes->stream, NULL);
735 return AVERROR(ENOMEM);
738 sub_st->id = pes->pid;
739 avpriv_set_pts_info(sub_st, 33, 1, 90000);
740 sub_st->priv_data = sub_pes;
741 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
742 sub_st->codec->codec_id = AV_CODEC_ID_AC3;
743 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
744 sub_pes->sub_st = pes->sub_st = sub_st;
747 if (st->codec->codec_id == AV_CODEC_ID_NONE)
748 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
749 if (st->codec->codec_id == AV_CODEC_ID_NONE){
750 st->codec->codec_id = old_codec_id;
751 st->codec->codec_type= old_codec_type;
757 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
761 pkt->buf = pes->buffer;
762 pkt->data = pes->buffer->data;
763 pkt->size = pes->data_index;
765 if(pes->total_size != MAX_PES_PAYLOAD &&
766 pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
767 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
768 pes->flags |= AV_PKT_FLAG_CORRUPT;
770 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
772 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
773 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
774 pkt->stream_index = pes->sub_st->index;
776 pkt->stream_index = pes->st->index;
779 /* store position of first TS packet of this PES packet */
780 pkt->pos = pes->ts_packet_pos;
781 pkt->flags = pes->flags;
783 /* reset pts values */
784 pes->pts = AV_NOPTS_VALUE;
785 pes->dts = AV_NOPTS_VALUE;
791 static uint64_t get_ts64(GetBitContext *gb, int bits)
793 if (get_bits_left(gb) < bits)
794 return AV_NOPTS_VALUE;
795 return get_bits64(gb, bits);
798 static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
801 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
802 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
803 int dts_flag = -1, cts_flag = -1;
804 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
806 init_get_bits(&gb, buf, buf_size*8);
808 if (sl->use_au_start)
809 au_start_flag = get_bits1(&gb);
811 au_end_flag = get_bits1(&gb);
812 if (!sl->use_au_start && !sl->use_au_end)
813 au_start_flag = au_end_flag = 1;
815 ocr_flag = get_bits1(&gb);
817 idle_flag = get_bits1(&gb);
819 padding_flag = get_bits1(&gb);
821 padding_bits = get_bits(&gb, 3);
823 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
824 if (sl->packet_seq_num_len)
825 skip_bits_long(&gb, sl->packet_seq_num_len);
826 if (sl->degr_prior_len)
828 skip_bits(&gb, sl->degr_prior_len);
830 skip_bits_long(&gb, sl->ocr_len);
832 if (sl->use_rand_acc_pt)
834 if (sl->au_seq_num_len > 0)
835 skip_bits_long(&gb, sl->au_seq_num_len);
836 if (sl->use_timestamps) {
837 dts_flag = get_bits1(&gb);
838 cts_flag = get_bits1(&gb);
841 if (sl->inst_bitrate_len)
842 inst_bitrate_flag = get_bits1(&gb);
844 dts = get_ts64(&gb, sl->timestamp_len);
846 cts = get_ts64(&gb, sl->timestamp_len);
848 skip_bits_long(&gb, sl->au_len);
849 if (inst_bitrate_flag)
850 skip_bits_long(&gb, sl->inst_bitrate_len);
853 if (dts != AV_NOPTS_VALUE)
855 if (cts != AV_NOPTS_VALUE)
858 if (sl->timestamp_len && sl->timestamp_res)
859 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
861 return (get_bits_count(&gb) + 7) >> 3;
864 /* return non zero if a packet could be constructed */
865 static int mpegts_push_data(MpegTSFilter *filter,
866 const uint8_t *buf, int buf_size, int is_start,
867 int64_t pos, int64_t pcr)
869 PESContext *pes = filter->u.pes_filter.opaque;
870 MpegTSContext *ts = pes->ts;
881 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
882 new_pes_packet(pes, ts->pkt);
885 pes->state = MPEGTS_HEADER;
887 pes->ts_packet_pos = pos;
890 while (buf_size > 0) {
893 len = PES_START_SIZE - pes->data_index;
896 memcpy(pes->header + pes->data_index, p, len);
897 pes->data_index += len;
900 if (pes->data_index == PES_START_SIZE) {
901 /* we got all the PES or section header. We can now
903 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
904 pes->header[2] == 0x01) {
905 /* it must be an mpeg2 PES stream */
906 code = pes->header[3] | 0x100;
907 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
909 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
910 (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
911 code == 0x1be) /* padding_stream */
914 /* stream not present in PMT */
916 pes->st = avformat_new_stream(ts->stream, NULL);
918 return AVERROR(ENOMEM);
919 pes->st->id = pes->pid;
920 mpegts_set_stream_info(pes->st, pes, 0, 0);
923 pes->total_size = AV_RB16(pes->header + 4);
924 /* NOTE: a zero total size means the PES size is
926 if (!pes->total_size)
927 pes->total_size = MAX_PES_PAYLOAD;
929 /* allocate pes buffer */
930 pes->buffer = av_buffer_alloc(pes->total_size +
931 FF_INPUT_BUFFER_PADDING_SIZE);
933 return AVERROR(ENOMEM);
935 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
936 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
937 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
938 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
939 pes->state = MPEGTS_PESHEADER;
940 if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) {
941 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
942 pes->pid, pes->stream_type);
943 pes->st->request_probe= 1;
946 pes->state = MPEGTS_PAYLOAD;
950 /* otherwise, it should be a table */
953 pes->state = MPEGTS_SKIP;
958 /**********************************************/
959 /* PES packing parsing */
960 case MPEGTS_PESHEADER:
961 len = PES_HEADER_SIZE - pes->data_index;
966 memcpy(pes->header + pes->data_index, p, len);
967 pes->data_index += len;
970 if (pes->data_index == PES_HEADER_SIZE) {
971 pes->pes_header_size = pes->header[8] + 9;
972 pes->state = MPEGTS_PESHEADER_FILL;
975 case MPEGTS_PESHEADER_FILL:
976 len = pes->pes_header_size - pes->data_index;
981 memcpy(pes->header + pes->data_index, p, len);
982 pes->data_index += len;
985 if (pes->data_index == pes->pes_header_size) {
987 unsigned int flags, pes_ext, skip;
989 flags = pes->header[7];
991 pes->pts = AV_NOPTS_VALUE;
992 pes->dts = AV_NOPTS_VALUE;
993 if ((flags & 0xc0) == 0x80) {
994 pes->pts = ff_parse_pes_pts(r);
995 /* video pts is not monotonic, can't be used for dts */
996 if (pes->st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
999 } else if ((flags & 0xc0) == 0xc0) {
1000 pes->pts = ff_parse_pes_pts(r);
1002 pes->dts = ff_parse_pes_pts(r);
1005 pes->extended_stream_id = -1;
1006 if (flags & 0x01) { /* PES extension */
1008 /* Skip PES private data, program packet sequence counter and P-STD buffer */
1009 skip = (pes_ext >> 4) & 0xb;
1012 if ((pes_ext & 0x41) == 0x01 &&
1013 (r + 2) <= (pes->header + pes->pes_header_size)) {
1014 /* PES extension 2 */
1015 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
1016 pes->extended_stream_id = r[1];
1020 /* we got the full header. We parse it and get the payload */
1021 pes->state = MPEGTS_PAYLOAD;
1022 pes->data_index = 0;
1023 if (pes->stream_type == 0x12 && buf_size > 0) {
1024 int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
1025 pes->pes_header_size += sl_header_bytes;
1026 p += sl_header_bytes;
1027 buf_size -= sl_header_bytes;
1029 if (pes->stream_type == 0x15 && buf_size >= 5) {
1030 /* skip metadata access unit header */
1031 pes->pes_header_size += 5;
1035 if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {
1036 AVProgram *p = NULL;
1037 while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) {
1038 if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) {
1039 MpegTSFilter *f = pes->ts->pids[p->pcr_pid];
1040 if (f && f->type == MPEGTS_PES) {
1041 PESContext *pcrpes = f->u.pes_filter.opaque;
1042 if (pcrpes && pcrpes->last_pcr != -1 && pcrpes->st && pcrpes->st->discard != AVDISCARD_ALL) {
1043 // teletext packets do not always have correct timestamps,
1044 // the standard says they should be handled after 40.6 ms at most,
1045 // and the pcr error to this packet should be no more than 100 ms.
1046 // TODO: we should interpolate the PCR, not just use the last one
1047 int64_t pcr = pcrpes->last_pcr / 300;
1048 pes->st->pts_wrap_reference = pcrpes->st->pts_wrap_reference;
1049 pes->st->pts_wrap_behavior = pcrpes->st->pts_wrap_behavior;
1050 if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) {
1051 pes->pts = pes->dts = pcr;
1052 } else if (pes->dts > pcr + 3654 + 9000) {
1053 pes->pts = pes->dts = pcr + 3654 + 9000;
1063 case MPEGTS_PAYLOAD:
1064 if (buf_size > 0 && pes->buffer) {
1065 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
1066 new_pes_packet(pes, ts->pkt);
1067 pes->total_size = MAX_PES_PAYLOAD;
1068 pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
1070 return AVERROR(ENOMEM);
1072 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
1073 // pes packet size is < ts size packet and pes data is padded with 0xff
1074 // not sure if this is legal in ts but see issue #2392
1075 buf_size = pes->total_size;
1077 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
1078 pes->data_index += buf_size;
1081 /* emit complete packets with known packet size
1082 * decreases demuxer delay for infrequent packets like subtitles from
1083 * a couple of seconds to milliseconds for properly muxed files.
1084 * total_size is the number of bytes following pes_packet_length
1085 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
1086 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
1087 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
1089 new_pes_packet(pes, ts->pkt);
1101 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
1106 /* if no pid found, then add a pid context */
1107 pes = av_mallocz(sizeof(PESContext));
1111 pes->stream = ts->stream;
1113 pes->pcr_pid = pcr_pid;
1114 pes->state = MPEGTS_SKIP;
1115 pes->pts = AV_NOPTS_VALUE;
1116 pes->dts = AV_NOPTS_VALUE;
1118 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1131 Mp4Descr *active_descr;
1133 int max_descr_count;
1135 } MP4DescrParseContext;
1137 static int init_MP4DescrParseContext(
1138 MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
1139 unsigned size, Mp4Descr *descr, int max_descr_count)
1143 return AVERROR_INVALIDDATA;
1145 if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
1146 NULL, NULL, NULL, NULL)) < 0)
1153 d->active_descr = NULL;
1154 d->max_descr_count = max_descr_count;
1159 static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
1160 int64_t new_off = avio_tell(pb);
1161 (*len) -= new_off - *off;
1165 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1168 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1171 if (parse_mp4_descr(d, off, len, 0) < 0)
1173 update_offsets(&d->pb, &off, &len);
1178 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1180 avio_rb16(&d->pb); // ID
1186 update_offsets(&d->pb, &off, &len);
1187 return parse_mp4_descr_arr(d, off, len);
1190 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1195 id_flags = avio_rb16(&d->pb);
1196 if (!(id_flags & 0x0020)) { //URL_Flag
1197 update_offsets(&d->pb, &off, &len);
1198 return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1204 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1207 if (d->descr_count >= d->max_descr_count)
1209 ff_mp4_parse_es_descr(&d->pb, &es_id);
1210 d->active_descr = d->descr + (d->descr_count++);
1212 d->active_descr->es_id = es_id;
1213 update_offsets(&d->pb, &off, &len);
1214 parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1215 update_offsets(&d->pb, &off, &len);
1217 parse_mp4_descr(d, off, len, MP4SLDescrTag);
1218 d->active_descr = NULL;
1222 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1224 Mp4Descr *descr = d->active_descr;
1227 d->active_descr->dec_config_descr = av_malloc(len);
1228 if (!descr->dec_config_descr)
1229 return AVERROR(ENOMEM);
1230 descr->dec_config_descr_len = len;
1231 avio_read(&d->pb, descr->dec_config_descr, len);
1235 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1237 Mp4Descr *descr = d->active_descr;
1242 predefined = avio_r8(&d->pb);
1245 int flags = avio_r8(&d->pb);
1246 descr->sl.use_au_start = !!(flags & 0x80);
1247 descr->sl.use_au_end = !!(flags & 0x40);
1248 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1249 descr->sl.use_padding = !!(flags & 0x08);
1250 descr->sl.use_timestamps = !!(flags & 0x04);
1251 descr->sl.use_idle = !!(flags & 0x02);
1252 descr->sl.timestamp_res = avio_rb32(&d->pb);
1254 descr->sl.timestamp_len = avio_r8(&d->pb);
1255 descr->sl.ocr_len = avio_r8(&d->pb);
1256 descr->sl.au_len = avio_r8(&d->pb);
1257 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1258 lengths = avio_rb16(&d->pb);
1259 descr->sl.degr_prior_len = lengths >> 12;
1260 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1261 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1263 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1268 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1271 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1272 update_offsets(&d->pb, &off, &len);
1273 if (len < 0 || len1 > len || len1 <= 0) {
1274 av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1278 if (d->level++ >= MAX_LEVEL) {
1279 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1283 if (target_tag && tag != target_tag) {
1284 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1290 parse_MP4IODescrTag(d, off, len1);
1293 parse_MP4ODescrTag(d, off, len1);
1296 parse_MP4ESDescrTag(d, off, len1);
1298 case MP4DecConfigDescrTag:
1299 parse_MP4DecConfigDescrTag(d, off, len1);
1302 parse_MP4SLDescrTag(d, off, len1);
1308 avio_seek(&d->pb, off + len1, SEEK_SET);
1312 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1313 Mp4Descr *descr, int *descr_count, int max_descr_count)
1315 MP4DescrParseContext d;
1316 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1319 parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1321 *descr_count = d.descr_count;
1325 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1326 Mp4Descr *descr, int *descr_count, int max_descr_count)
1328 MP4DescrParseContext d;
1329 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1332 parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1334 *descr_count = d.descr_count;
1338 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1340 MpegTSContext *ts = filter->u.section_filter.opaque;
1342 const uint8_t *p, *p_end;
1344 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1345 int mp4_descr_count = 0;
1347 AVFormatContext *s = ts->stream;
1349 p_end = section + section_len - 4;
1351 if (parse_section_header(&h, &p, p_end) < 0)
1353 if (h.tid != M4OD_TID)
1356 mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1358 for (pid = 0; pid < NB_PID_MAX; pid++) {
1361 for (i = 0; i < mp4_descr_count; i++) {
1364 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1366 if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1367 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1370 pes = ts->pids[pid]->u.pes_filter.opaque;
1376 pes->sl = mp4_descr[i].sl;
1378 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1379 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1380 ff_mp4_read_dec_config_descr(s, st, &pb);
1381 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1382 st->codec->extradata_size > 0)
1383 st->need_parsing = 0;
1384 if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1385 st->codec->extradata_size > 0)
1386 st->need_parsing = 0;
1388 if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1389 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1390 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1391 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1392 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1393 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1394 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1398 for (i = 0; i < mp4_descr_count; i++)
1399 av_free(mp4_descr[i].dec_config_descr);
1402 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1403 const uint8_t **pp, const uint8_t *desc_list_end,
1404 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1407 const uint8_t *desc_end;
1408 int desc_len, desc_tag, desc_es_id;
1412 desc_tag = get8(pp, desc_list_end);
1415 desc_len = get8(pp, desc_list_end);
1418 desc_end = *pp + desc_len;
1419 if (desc_end > desc_list_end)
1422 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1424 if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1425 stream_type == STREAM_TYPE_PRIVATE_DATA)
1426 mpegts_find_stream_type(st, desc_tag, DESC_types);
1429 case 0x1E: /* SL descriptor */
1430 desc_es_id = get16(pp, desc_end);
1431 if (ts && ts->pids[pid])
1432 ts->pids[pid]->es_id = desc_es_id;
1433 for (i = 0; i < mp4_descr_count; i++)
1434 if (mp4_descr[i].dec_config_descr_len &&
1435 mp4_descr[i].es_id == desc_es_id) {
1437 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1438 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1439 ff_mp4_read_dec_config_descr(fc, st, &pb);
1440 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1441 st->codec->extradata_size > 0)
1442 st->need_parsing = 0;
1443 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1444 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1447 case 0x1F: /* FMC descriptor */
1448 get16(pp, desc_end);
1449 if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe>0) &&
1450 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1452 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1453 mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1454 ff_mp4_read_dec_config_descr(fc, st, &pb);
1455 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1456 st->codec->extradata_size > 0){
1457 st->request_probe= st->need_parsing = 0;
1458 st->codec->codec_type= AVMEDIA_TYPE_AUDIO;
1462 case 0x56: /* DVB teletext descriptor */
1463 language[0] = get8(pp, desc_end);
1464 language[1] = get8(pp, desc_end);
1465 language[2] = get8(pp, desc_end);
1467 av_dict_set(&st->metadata, "language", language, 0);
1469 case 0x59: /* subtitling descriptor */
1470 language[0] = get8(pp, desc_end);
1471 language[1] = get8(pp, desc_end);
1472 language[2] = get8(pp, desc_end);
1474 /* hearing impaired subtitles detection */
1475 switch(get8(pp, desc_end)) {
1476 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1477 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1478 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1479 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1480 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1481 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1482 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1485 if (st->codec->extradata) {
1486 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1487 avpriv_request_sample(fc, "DVB sub with multiple IDs");
1489 if (!ff_alloc_extradata(st->codec, 4)) {
1490 memcpy(st->codec->extradata, *pp, 4);
1494 av_dict_set(&st->metadata, "language", language, 0);
1496 case 0x0a: /* ISO 639 language descriptor */
1497 for (i = 0; i + 4 <= desc_len; i += 4) {
1498 language[i + 0] = get8(pp, desc_end);
1499 language[i + 1] = get8(pp, desc_end);
1500 language[i + 2] = get8(pp, desc_end);
1501 language[i + 3] = ',';
1502 switch (get8(pp, desc_end)) {
1503 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1504 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1505 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1509 language[i - 1] = 0;
1510 av_dict_set(&st->metadata, "language", language, 0);
1513 case 0x05: /* registration descriptor */
1514 st->codec->codec_tag = bytestream_get_le32(pp);
1515 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1516 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1517 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1519 case 0x52: /* stream identifier descriptor */
1520 st->stream_identifier = 1 + get8(pp, desc_end);
1522 case 0x26: /* metadata descriptor */
1523 if (get16(pp, desc_end) == 0xFFFF)
1525 if (get8(pp, desc_end) == 0xFF) {
1526 st->codec->codec_tag = bytestream_get_le32(pp);
1527 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1528 mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types);
1538 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1540 MpegTSContext *ts = filter->u.section_filter.opaque;
1541 SectionHeader h1, *h = &h1;
1544 const uint8_t *p, *p_end, *desc_list_end;
1545 int program_info_length, pcr_pid, pid, stream_type;
1547 uint32_t prog_reg_desc = 0; /* registration descriptor */
1549 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1550 int mp4_descr_count = 0;
1553 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1554 hex_dump_debug(ts->stream, section, section_len);
1556 p_end = section + section_len - 4;
1558 if (parse_section_header(h, &p, p_end) < 0)
1561 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1562 h->id, h->sec_num, h->last_sec_num);
1564 if (h->tid != PMT_TID)
1567 clear_program(ts, h->id);
1568 pcr_pid = get16(&p, p_end);
1572 add_pid_to_pmt(ts, h->id, pcr_pid);
1573 set_pcr_pid(ts->stream, h->id, pcr_pid);
1575 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1577 program_info_length = get16(&p, p_end);
1578 if (program_info_length < 0)
1580 program_info_length &= 0xfff;
1581 while(program_info_length >= 2) {
1583 tag = get8(&p, p_end);
1584 len = get8(&p, p_end);
1586 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1588 if(len > program_info_length - 2)
1589 //something else is broken, exit the program_descriptors_loop
1591 program_info_length -= len + 2;
1592 if (tag == 0x1d) { // IOD descriptor
1593 get8(&p, p_end); // scope
1594 get8(&p, p_end); // label
1596 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1597 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1598 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1599 prog_reg_desc = bytestream_get_le32(&p);
1604 p += program_info_length;
1608 // stop parsing after pmt, we found header
1609 if (!ts->stream->nb_streams)
1612 set_pmt_found(ts, h->id);
1617 stream_type = get8(&p, p_end);
1618 if (stream_type < 0)
1620 pid = get16(&p, p_end);
1624 if (pid == ts->current_pid)
1627 /* now create stream */
1628 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1629 pes = ts->pids[pid]->u.pes_filter.opaque;
1631 pes->st = avformat_new_stream(pes->stream, NULL);
1634 pes->st->id = pes->pid;
1637 } else if (stream_type != 0x13) {
1638 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1639 pes = add_pes_stream(ts, pid, pcr_pid);
1641 st = avformat_new_stream(pes->stream, NULL);
1647 int idx = ff_find_stream_index(ts->stream, pid);
1649 st = ts->stream->streams[idx];
1651 st = avformat_new_stream(ts->stream, NULL);
1655 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1662 if (pes && !pes->stream_type)
1663 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1665 add_pid_to_pmt(ts, h->id, pid);
1667 ff_program_add_stream_index(ts->stream, h->id, st->index);
1669 desc_list_len = get16(&p, p_end);
1670 if (desc_list_len < 0)
1672 desc_list_len &= 0xfff;
1673 desc_list_end = p + desc_list_len;
1674 if (desc_list_end > p_end)
1677 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1678 mp4_descr, mp4_descr_count, pid, ts) < 0)
1681 if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1682 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1683 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1690 for (i = 0; i < mp4_descr_count; i++)
1691 av_free(mp4_descr[i].dec_config_descr);
1694 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1696 MpegTSContext *ts = filter->u.section_filter.opaque;
1697 SectionHeader h1, *h = &h1;
1698 const uint8_t *p, *p_end;
1702 av_dlog(ts->stream, "PAT:\n");
1703 hex_dump_debug(ts->stream, section, section_len);
1705 p_end = section + section_len - 4;
1707 if (parse_section_header(h, &p, p_end) < 0)
1709 if (h->tid != PAT_TID)
1712 ts->stream->ts_id = h->id;
1716 sid = get16(&p, p_end);
1719 pmt_pid = get16(&p, p_end);
1724 if (pmt_pid == ts->current_pid)
1727 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1729 if (sid == 0x0000) {
1732 MpegTSFilter *fil = ts->pids[pmt_pid];
1733 program = av_new_program(ts->stream, sid);
1734 program->program_num = sid;
1735 program->pmt_pid = pmt_pid;
1737 if ( fil->type != MPEGTS_SECTION
1738 || fil->pid != pmt_pid
1739 || fil->u.section_filter.section_cb != pmt_cb)
1740 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1742 if (!ts->pids[pmt_pid])
1743 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1744 add_pat_entry(ts, sid);
1745 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1746 add_pid_to_pmt(ts, sid, pmt_pid);
1752 for (j=0; j<ts->stream->nb_programs; j++) {
1753 for (i=0; i<ts->nb_prg; i++)
1754 if (ts->prg[i].id == ts->stream->programs[j]->id)
1757 clear_avprogram(ts, ts->stream->programs[j]->id);
1762 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1764 MpegTSContext *ts = filter->u.section_filter.opaque;
1765 SectionHeader h1, *h = &h1;
1766 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1767 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1768 char *name, *provider_name;
1770 av_dlog(ts->stream, "SDT:\n");
1771 hex_dump_debug(ts->stream, section, section_len);
1773 p_end = section + section_len - 4;
1775 if (parse_section_header(h, &p, p_end) < 0)
1777 if (h->tid != SDT_TID)
1779 onid = get16(&p, p_end);
1782 val = get8(&p, p_end);
1786 sid = get16(&p, p_end);
1789 val = get8(&p, p_end);
1792 desc_list_len = get16(&p, p_end);
1793 if (desc_list_len < 0)
1795 desc_list_len &= 0xfff;
1796 desc_list_end = p + desc_list_len;
1797 if (desc_list_end > p_end)
1800 desc_tag = get8(&p, desc_list_end);
1803 desc_len = get8(&p, desc_list_end);
1804 desc_end = p + desc_len;
1805 if (desc_end > desc_list_end)
1808 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1809 desc_tag, desc_len);
1813 service_type = get8(&p, p_end);
1814 if (service_type < 0)
1816 provider_name = getstr8(&p, p_end);
1819 name = getstr8(&p, p_end);
1821 AVProgram *program = av_new_program(ts->stream, sid);
1823 av_dict_set(&program->metadata, "service_name", name, 0);
1824 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1828 av_free(provider_name);
1839 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1840 const uint8_t *packet);
1842 /* handle one TS packet */
1843 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1845 AVFormatContext *s = ts->stream;
1847 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1848 has_adaptation, has_payload;
1849 const uint8_t *p, *p_end;
1852 pid = AV_RB16(packet + 1) & 0x1fff;
1853 if(pid && discard_pid(ts, pid))
1855 is_start = packet[1] & 0x40;
1856 tss = ts->pids[pid];
1857 if (ts->auto_guess && tss == NULL && is_start) {
1858 add_pes_stream(ts, pid, -1);
1859 tss = ts->pids[pid];
1863 ts->current_pid = pid;
1865 afc = (packet[3] >> 4) & 3;
1866 if (afc == 0) /* reserved value */
1868 has_adaptation = afc & 2;
1869 has_payload = afc & 1;
1870 is_discontinuity = has_adaptation
1871 && packet[4] != 0 /* with length > 0 */
1872 && (packet[5] & 0x80); /* and discontinuity indicated */
1874 /* continuity check (currently not used) */
1875 cc = (packet[3] & 0xf);
1876 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1877 cc_ok = pid == 0x1FFF // null packet PID
1880 || expected_cc == cc;
1884 av_log(ts->stream, AV_LOG_DEBUG,
1885 "Continuity check failed for pid %d expected %d got %d\n",
1886 pid, expected_cc, cc);
1887 if(tss->type == MPEGTS_PES) {
1888 PESContext *pc = tss->u.pes_filter.opaque;
1889 pc->flags |= AV_PKT_FLAG_CORRUPT;
1896 if (has_adaptation) {
1897 /* skip adaptation field */
1900 /* if past the end of packet, ignore */
1901 p_end = packet + TS_PACKET_SIZE;
1905 pos = avio_tell(ts->stream->pb);
1907 av_assert0(pos >= TS_PACKET_SIZE);
1908 ts->pos47_full = pos - TS_PACKET_SIZE;
1911 if (tss->type == MPEGTS_SECTION) {
1913 /* pointer field present */
1915 if (p + len > p_end)
1918 /* write remaining section bytes */
1919 write_section_data(s, tss,
1921 /* check whether filter has been closed */
1927 write_section_data(s, tss,
1932 write_section_data(s, tss,
1937 // stop find_stream_info from waiting for more streams
1938 // when all programs have received a PMT
1939 if( ts->stream->ctx_flags & AVFMTCTX_NOHEADER) {
1941 for(i=0; i<ts->nb_prg; i++) {
1942 if (!ts->prg[i].pmt_found)
1945 if (i == ts->nb_prg && ts->nb_prg > 0) {
1946 av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n");
1947 ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER;
1956 if (parse_pcr(&pcr_h, &pcr_l, packet) == 0)
1957 pcr = pcr_h * 300 + pcr_l;
1958 // Note: The position here points actually behind the current packet.
1959 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1960 pos - ts->raw_packet_size, pcr)) < 0)
1967 static void reanalyze(MpegTSContext *ts) {
1968 AVIOContext *pb = ts->stream->pb;
1969 int64_t pos = avio_tell(pb);
1972 pos -= ts->pos47_full;
1973 if (pos == TS_PACKET_SIZE) {
1974 ts->size_stat[0] ++;
1975 } else if (pos == TS_DVHS_PACKET_SIZE) {
1976 ts->size_stat[1] ++;
1977 } else if (pos == TS_FEC_PACKET_SIZE) {
1978 ts->size_stat[2] ++;
1981 ts->size_stat_count ++;
1982 if(ts->size_stat_count > SIZE_STAT_THRESHOLD) {
1984 if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) {
1985 newsize = TS_PACKET_SIZE;
1986 } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) {
1987 newsize = TS_DVHS_PACKET_SIZE;
1988 } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) {
1989 newsize = TS_FEC_PACKET_SIZE;
1991 if (newsize && newsize != ts->raw_packet_size) {
1992 av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize);
1993 ts->raw_packet_size = newsize;
1995 ts->size_stat_count = 0;
1996 memset(ts->size_stat, 0, sizeof(ts->size_stat));
2000 /* XXX: try to find a better synchro over several packets (use
2001 get_packet_size() ?) */
2002 static int mpegts_resync(AVFormatContext *s)
2004 AVIOContext *pb = s->pb;
2007 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
2012 avio_seek(pb, -1, SEEK_CUR);
2013 reanalyze(s->priv_data);
2017 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
2022 /* return -1 if error or EOF. Return 0 if OK. */
2023 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data)
2025 AVIOContext *pb = s->pb;
2029 len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data);
2030 if (len != TS_PACKET_SIZE)
2031 return len < 0 ? len : AVERROR_EOF;
2032 /* check packet sync byte */
2033 if ((*data)[0] != 0x47) {
2034 /* find a new packet start */
2035 uint64_t pos = avio_tell(pb);
2036 avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR);
2038 if (mpegts_resync(s) < 0)
2039 return AVERROR(EAGAIN);
2049 static void finished_reading_packet(AVFormatContext *s, int raw_packet_size)
2051 AVIOContext *pb = s->pb;
2052 int skip = raw_packet_size - TS_PACKET_SIZE;
2054 avio_skip(pb, skip);
2057 static int handle_packets(MpegTSContext *ts, int nb_packets)
2059 AVFormatContext *s = ts->stream;
2060 uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
2061 const uint8_t *data;
2062 int packet_num, ret = 0;
2064 if (avio_tell(s->pb) != ts->last_pos) {
2066 av_dlog(ts->stream, "Skipping after seek\n");
2067 /* seek detected, flush pes buffer */
2068 for (i = 0; i < NB_PID_MAX; i++) {
2070 if (ts->pids[i]->type == MPEGTS_PES) {
2071 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2072 av_buffer_unref(&pes->buffer);
2073 pes->data_index = 0;
2074 pes->state = MPEGTS_SKIP; /* skip until pes header */
2077 ts->pids[i]->last_cc = -1;
2084 memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2087 if (nb_packets != 0 && packet_num >= nb_packets ||
2088 ts->stop_parse > 1) {
2089 ret = AVERROR(EAGAIN);
2092 if (ts->stop_parse > 0)
2095 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2098 ret = handle_packet(ts, data);
2099 finished_reading_packet(s, ts->raw_packet_size);
2103 ts->last_pos = avio_tell(s->pb);
2107 static int mpegts_probe(AVProbeData *p)
2109 const int size= p->buf_size;
2113 int check_count= size / TS_FEC_PACKET_SIZE;
2114 #define CHECK_COUNT 10
2115 #define CHECK_BLOCK 100
2117 if (check_count < CHECK_COUNT)
2120 for (i=0; i<check_count; i+=CHECK_BLOCK){
2121 int left = FFMIN(check_count - i, CHECK_BLOCK);
2122 int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
2123 int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
2124 int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
2125 score = FFMAX3(score, dvhs_score, fec_score);
2127 maxscore = FFMAX(maxscore, score);
2130 sumscore = sumscore*CHECK_COUNT/check_count;
2131 maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
2133 av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
2135 if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
2136 else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
2140 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
2141 (-1) if not available */
2142 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
2143 const uint8_t *packet)
2145 int afc, len, flags;
2149 afc = (packet[3] >> 4) & 3;
2159 if (!(flags & 0x10))
2164 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
2165 *ppcr_low = ((p[4] & 1) << 8) | p[5];
2169 static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) {
2171 /* NOTE: We attempt to seek on non-seekable files as well, as the
2172 * probe buffer usually is big enough. Only warn if the seek failed
2173 * on files where the seek should work. */
2174 if (avio_seek(pb, pos, SEEK_SET) < 0)
2175 av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
2178 static int mpegts_read_header(AVFormatContext *s)
2180 MpegTSContext *ts = s->priv_data;
2181 AVIOContext *pb = s->pb;
2182 uint8_t buf[8*1024]={0};
2186 ffio_ensure_seekback(pb, s->probesize);
2188 /* read the first 8192 bytes to get packet size */
2189 pos = avio_tell(pb);
2190 len = avio_read(pb, buf, sizeof(buf));
2191 ts->raw_packet_size = get_packet_size(buf, len);
2192 if (ts->raw_packet_size <= 0) {
2193 av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
2194 ts->raw_packet_size = TS_PACKET_SIZE;
2199 if (s->iformat == &ff_mpegts_demuxer) {
2202 /* first do a scan to get all the services */
2203 seek_back(s, pb, pos);
2205 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2207 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2209 handle_packets(ts, s->probesize / ts->raw_packet_size);
2210 /* if could not find service, enable auto_guess */
2214 av_dlog(ts->stream, "tuning done\n");
2216 s->ctx_flags |= AVFMTCTX_NOHEADER;
2219 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
2220 int64_t pcrs[2], pcr_h;
2221 int packet_count[2];
2222 uint8_t packet[TS_PACKET_SIZE];
2223 const uint8_t *data;
2225 /* only read packets */
2227 st = avformat_new_stream(s, NULL);
2230 avpriv_set_pts_info(st, 60, 1, 27000000);
2231 st->codec->codec_type = AVMEDIA_TYPE_DATA;
2232 st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
2234 /* we iterate until we find two PCRs to estimate the bitrate */
2239 ret = read_packet(s, packet, ts->raw_packet_size, &data);
2242 pid = AV_RB16(data + 1) & 0x1fff;
2243 if ((pcr_pid == -1 || pcr_pid == pid) &&
2244 parse_pcr(&pcr_h, &pcr_l, data) == 0) {
2245 finished_reading_packet(s, ts->raw_packet_size);
2247 packet_count[nb_pcrs] = nb_packets;
2248 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
2253 finished_reading_packet(s, ts->raw_packet_size);
2258 /* NOTE1: the bitrate is computed without the FEC */
2259 /* NOTE2: it is only the bitrate of the start of the stream */
2260 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
2261 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
2262 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
2263 st->codec->bit_rate = s->bit_rate;
2264 st->start_time = ts->cur_pcr;
2265 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
2266 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
2269 seek_back(s, pb, pos);
2275 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
2277 static int mpegts_raw_read_packet(AVFormatContext *s,
2280 MpegTSContext *ts = s->priv_data;
2282 int64_t pcr_h, next_pcr_h, pos;
2283 int pcr_l, next_pcr_l;
2284 uint8_t pcr_buf[12];
2285 const uint8_t *data;
2287 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
2288 return AVERROR(ENOMEM);
2289 pkt->pos= avio_tell(s->pb);
2290 ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);
2292 av_free_packet(pkt);
2295 if (data != pkt->data)
2296 memcpy(pkt->data, data, ts->raw_packet_size);
2297 finished_reading_packet(s, ts->raw_packet_size);
2298 if (ts->mpeg2ts_compute_pcr) {
2299 /* compute exact PCR for each packet */
2300 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
2301 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
2302 pos = avio_tell(s->pb);
2303 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
2304 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
2305 avio_read(s->pb, pcr_buf, 12);
2306 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
2307 /* XXX: not precise enough */
2308 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
2313 avio_seek(s->pb, pos, SEEK_SET);
2314 /* no next PCR found: we use previous increment */
2315 ts->cur_pcr = pcr_h * 300 + pcr_l;
2317 pkt->pts = ts->cur_pcr;
2318 pkt->duration = ts->pcr_incr;
2319 ts->cur_pcr += ts->pcr_incr;
2321 pkt->stream_index = 0;
2325 static int mpegts_read_packet(AVFormatContext *s,
2328 MpegTSContext *ts = s->priv_data;
2333 ret = handle_packets(ts, 0);
2335 av_free_packet(ts->pkt);
2336 /* flush pes data left */
2337 for (i = 0; i < NB_PID_MAX; i++) {
2338 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2339 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2340 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2341 new_pes_packet(pes, pkt);
2342 pes->state = MPEGTS_SKIP;
2350 if (!ret && pkt->size < 0)
2351 ret = AVERROR(EINTR);
2355 static void mpegts_free(MpegTSContext *ts)
2361 for(i=0;i<NB_PID_MAX;i++)
2362 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2365 static int mpegts_read_close(AVFormatContext *s)
2367 MpegTSContext *ts = s->priv_data;
2372 static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2373 int64_t *ppos, int64_t pos_limit)
2375 MpegTSContext *ts = s->priv_data;
2376 int64_t pos, timestamp;
2377 uint8_t buf[TS_PACKET_SIZE];
2378 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2379 int pos47 = ts->pos47_full % ts->raw_packet_size;
2380 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2381 while(pos < pos_limit) {
2382 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2383 return AV_NOPTS_VALUE;
2384 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2385 return AV_NOPTS_VALUE;
2386 if (buf[0] != 0x47) {
2387 avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR);
2388 if (mpegts_resync(s) < 0)
2389 return AV_NOPTS_VALUE;
2390 pos = avio_tell(s->pb);
2393 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2394 parse_pcr(×tamp, &pcr_l, buf) == 0) {
2398 pos += ts->raw_packet_size;
2401 return AV_NOPTS_VALUE;
2404 static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
2405 int64_t *ppos, int64_t pos_limit)
2407 MpegTSContext *ts = s->priv_data;
2409 int pos47 = ts->pos47_full % ts->raw_packet_size;
2410 pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47;
2411 ff_read_frame_flush(s);
2412 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
2413 return AV_NOPTS_VALUE;
2414 while(pos < pos_limit) {
2417 av_init_packet(&pkt);
2418 ret= av_read_frame(s, &pkt);
2420 return AV_NOPTS_VALUE;
2421 av_free_packet(&pkt);
2422 if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
2423 ff_reduce_index(s, pkt.stream_index);
2424 av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
2425 if(pkt.stream_index == stream_index && pkt.pos >= *ppos){
2433 return AV_NOPTS_VALUE;
2436 /**************************************************************/
2437 /* parsing functions - called from other demuxers such as RTP */
2439 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2443 ts = av_mallocz(sizeof(MpegTSContext));
2446 /* no stream case, currently used by RTP */
2447 ts->raw_packet_size = TS_PACKET_SIZE;
2450 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
2451 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
2456 /* return the consumed length if a packet was output, or -1 if no
2458 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2459 const uint8_t *buf, int len)
2467 if (len < TS_PACKET_SIZE)
2469 if (buf[0] != 0x47) {
2473 handle_packet(ts, buf);
2474 buf += TS_PACKET_SIZE;
2475 len -= TS_PACKET_SIZE;
2476 if (ts->stop_parse == 1)
2483 void ff_mpegts_parse_close(MpegTSContext *ts)
2489 AVInputFormat ff_mpegts_demuxer = {
2491 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2492 .priv_data_size = sizeof(MpegTSContext),
2493 .read_probe = mpegts_probe,
2494 .read_header = mpegts_read_header,
2495 .read_packet = mpegts_read_packet,
2496 .read_close = mpegts_read_close,
2497 .read_timestamp = mpegts_get_dts,
2498 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2499 .priv_class = &mpegts_class,
2502 AVInputFormat ff_mpegtsraw_demuxer = {
2503 .name = "mpegtsraw",
2504 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2505 .priv_data_size = sizeof(MpegTSContext),
2506 .read_header = mpegts_read_header,
2507 .read_packet = mpegts_raw_read_packet,
2508 .read_close = mpegts_read_close,
2509 .read_timestamp = mpegts_get_dts,
2510 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2511 .priv_class = &mpegtsraw_class,