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 #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 "libavcodec/bytestream.h"
30 #include "libavcodec/get_bits.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 #define MAX_MP4_DESCR_COUNT 16
47 enum MpegTSFilterType {
52 typedef struct MpegTSFilter MpegTSFilter;
54 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
56 typedef struct MpegTSPESFilter {
61 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
63 typedef void SetServiceCallback(void *opaque, int ret);
65 typedef struct MpegTSSectionFilter {
69 unsigned int check_crc:1;
70 unsigned int end_of_section_reached:1;
71 SectionCallback *section_cb;
73 } MpegTSSectionFilter;
78 int last_cc; /* last cc code (-1 if first packet) */
79 enum MpegTSFilterType type;
81 MpegTSPESFilter pes_filter;
82 MpegTSSectionFilter section_filter;
86 #define MAX_PIDS_PER_PROGRAM 64
88 unsigned int id; //program id/service id
90 unsigned int pids[MAX_PIDS_PER_PROGRAM];
93 struct MpegTSContext {
96 AVFormatContext *stream;
97 /** raw packet size, including FEC if present */
102 /** if true, all pids are analyzed to find streams */
105 /** compute exact PCR for each transport stream packet */
106 int mpeg2ts_compute_pcr;
108 int64_t cur_pcr; /**< used to estimate the exact PCR */
109 int pcr_incr; /**< used to estimate the exact PCR */
111 /* data needed to handle file based ts */
112 /** stop parsing loop */
114 /** packet containing Audio/Video data */
116 /** to detect seek */
119 /******************************************/
120 /* private mpegts data */
122 /** structure to keep track of Program->pids mapping */
127 /** filters for various streams specified by PMT + for the PAT and PMT */
128 MpegTSFilter *pids[NB_PID_MAX];
131 static const AVOption options[] = {
132 {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
133 {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
137 static const AVClass mpegtsraw_class = {
138 .class_name = "mpegtsraw demuxer",
139 .item_name = av_default_item_name,
141 .version = LIBAVUTIL_VERSION_INT,
144 /* TS stream handling */
149 MPEGTS_PESHEADER_FILL,
154 /* enough for PES header + length */
155 #define PES_START_SIZE 6
156 #define PES_HEADER_SIZE 9
157 #define MAX_PES_HEADER_SIZE (9 + 255)
159 typedef struct PESContext {
161 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
164 AVFormatContext *stream;
166 AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
167 enum MpegTSState state;
168 /* used to get the format */
170 int flags; /**< copied to the AVPacket flags */
173 int extended_stream_id;
175 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
176 uint8_t header[MAX_PES_HEADER_SIZE];
181 extern AVInputFormat ff_mpegts_demuxer;
183 static void clear_program(MpegTSContext *ts, unsigned int programid)
187 for(i=0; i<ts->nb_prg; i++)
188 if(ts->prg[i].id == programid)
189 ts->prg[i].nb_pids = 0;
192 static void clear_programs(MpegTSContext *ts)
198 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
201 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
205 p = &ts->prg[ts->nb_prg];
211 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
214 struct Program *p = NULL;
215 for(i=0; i<ts->nb_prg; i++) {
216 if(ts->prg[i].id == programid) {
224 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
226 p->pids[p->nb_pids++] = pid;
230 * @brief discard_pid() decides if the pid is to be discarded according
231 * to caller's programs selection
232 * @param ts : - TS context
234 * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
237 static int discard_pid(MpegTSContext *ts, unsigned int pid)
240 int used = 0, discarded = 0;
242 for(i=0; i<ts->nb_prg; i++) {
244 for(j=0; j<p->nb_pids; j++) {
245 if(p->pids[j] != pid)
247 //is program with id p->id set to be discarded?
248 for(k=0; k<ts->stream->nb_programs; k++) {
249 if(ts->stream->programs[k]->id == p->id) {
250 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
259 return !used && discarded;
263 * Assemble PES packets out of TS packets, and then call the "section_cb"
264 * function when they are complete.
266 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
267 const uint8_t *buf, int buf_size, int is_start)
269 MpegTSSectionFilter *tss = &tss1->u.section_filter;
273 memcpy(tss->section_buf, buf, buf_size);
274 tss->section_index = buf_size;
275 tss->section_h_size = -1;
276 tss->end_of_section_reached = 0;
278 if (tss->end_of_section_reached)
280 len = 4096 - tss->section_index;
283 memcpy(tss->section_buf + tss->section_index, buf, len);
284 tss->section_index += len;
287 /* compute section length if possible */
288 if (tss->section_h_size == -1 && tss->section_index >= 3) {
289 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
292 tss->section_h_size = len;
295 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
296 tss->end_of_section_reached = 1;
297 if (!tss->check_crc ||
298 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
299 tss->section_buf, tss->section_h_size) == 0)
300 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
304 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
305 SectionCallback *section_cb, void *opaque,
309 MpegTSFilter *filter;
310 MpegTSSectionFilter *sec;
312 av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
314 if (pid >= NB_PID_MAX || ts->pids[pid])
316 filter = av_mallocz(sizeof(MpegTSFilter));
319 ts->pids[pid] = filter;
320 filter->type = MPEGTS_SECTION;
323 filter->last_cc = -1;
324 sec = &filter->u.section_filter;
325 sec->section_cb = section_cb;
326 sec->opaque = opaque;
327 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
328 sec->check_crc = check_crc;
329 if (!sec->section_buf) {
336 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
340 MpegTSFilter *filter;
341 MpegTSPESFilter *pes;
343 if (pid >= NB_PID_MAX || ts->pids[pid])
345 filter = av_mallocz(sizeof(MpegTSFilter));
348 ts->pids[pid] = filter;
349 filter->type = MPEGTS_PES;
352 filter->last_cc = -1;
353 pes = &filter->u.pes_filter;
354 pes->pes_cb = pes_cb;
355 pes->opaque = opaque;
359 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
364 if (filter->type == MPEGTS_SECTION)
365 av_freep(&filter->u.section_filter.section_buf);
366 else if (filter->type == MPEGTS_PES) {
367 PESContext *pes = filter->u.pes_filter.opaque;
368 av_buffer_unref(&pes->buffer);
369 /* referenced private data will be freed later in
370 * avformat_close_input */
371 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
372 av_freep(&filter->u.pes_filter.opaque);
377 ts->pids[pid] = NULL;
380 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
381 int stat[TS_MAX_PACKET_SIZE];
386 memset(stat, 0, packet_size*sizeof(int));
388 for(x=i=0; i<size-3; i++){
389 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
391 if(stat[x] > best_score){
398 if(x == packet_size) x= 0;
404 /* autodetect fec presence. Must have at least 1024 bytes */
405 static int get_packet_size(const uint8_t *buf, int size)
407 int score, fec_score, dvhs_score;
409 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
412 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
413 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
414 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
415 av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
416 score, dvhs_score, fec_score);
418 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
419 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
420 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
424 typedef struct SectionHeader {
429 uint8_t last_sec_num;
432 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
445 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
451 if ((p + 1) >= p_end)
459 /* read and allocate a DVB string preceded by its length */
460 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
467 len = get8(&p, p_end);
470 if ((p + len) > p_end)
472 str = av_malloc(len + 1);
482 static int parse_section_header(SectionHeader *h,
483 const uint8_t **pp, const uint8_t *p_end)
487 val = get8(pp, p_end);
492 val = get16(pp, p_end);
496 val = get8(pp, p_end);
499 h->version = (val >> 1) & 0x1f;
500 val = get8(pp, p_end);
504 val = get8(pp, p_end);
507 h->last_sec_num = val;
512 uint32_t stream_type;
513 enum AVMediaType codec_type;
514 enum AVCodecID codec_id;
517 static const StreamType ISO_types[] = {
518 { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
519 { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
520 { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
521 { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
522 { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
523 { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
524 { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
525 { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
526 { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS },
527 { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
528 { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
532 static const StreamType HDMV_types[] = {
533 { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
534 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
535 { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
536 { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
537 { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
538 { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
539 { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
540 { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
545 static const StreamType MISC_types[] = {
546 { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
547 { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
551 static const StreamType REGD_types[] = {
552 { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
553 { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
554 { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
555 { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
556 { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
557 { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
558 { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
562 /* descriptor present */
563 static const StreamType DESC_types[] = {
564 { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
565 { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
566 { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
567 { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
568 { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
572 static void mpegts_find_stream_type(AVStream *st,
573 uint32_t stream_type, const StreamType *types)
575 for (; types->stream_type; types++) {
576 if (stream_type == types->stream_type) {
577 st->codec->codec_type = types->codec_type;
578 st->codec->codec_id = types->codec_id;
584 static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
585 uint32_t stream_type, uint32_t prog_reg_desc)
587 avpriv_set_pts_info(st, 33, 1, 90000);
589 st->codec->codec_type = AVMEDIA_TYPE_DATA;
590 st->codec->codec_id = AV_CODEC_ID_NONE;
591 st->need_parsing = AVSTREAM_PARSE_FULL;
593 pes->stream_type = stream_type;
595 av_log(pes->stream, AV_LOG_DEBUG,
596 "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
597 st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
599 st->codec->codec_tag = pes->stream_type;
601 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
602 if (prog_reg_desc == AV_RL32("HDMV") &&
603 st->codec->codec_id == AV_CODEC_ID_NONE) {
604 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
605 if (pes->stream_type == 0x83) {
606 // HDMV TrueHD streams also contain an AC3 coded version of the
607 // audio track - add a second stream for this
609 // priv_data cannot be shared between streams
610 PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
612 return AVERROR(ENOMEM);
613 memcpy(sub_pes, pes, sizeof(*sub_pes));
615 sub_st = avformat_new_stream(pes->stream, NULL);
618 return AVERROR(ENOMEM);
621 sub_st->id = pes->pid;
622 avpriv_set_pts_info(sub_st, 33, 1, 90000);
623 sub_st->priv_data = sub_pes;
624 sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
625 sub_st->codec->codec_id = AV_CODEC_ID_AC3;
626 sub_st->need_parsing = AVSTREAM_PARSE_FULL;
627 sub_pes->sub_st = pes->sub_st = sub_st;
630 if (st->codec->codec_id == AV_CODEC_ID_NONE)
631 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
636 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
640 pkt->buf = pes->buffer;
641 pkt->data = pes->buffer->data;
642 pkt->size = pes->data_index;
644 if(pes->total_size != MAX_PES_PAYLOAD &&
645 pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
646 av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
647 pes->flags |= AV_PKT_FLAG_CORRUPT;
649 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
651 // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
652 if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
653 pkt->stream_index = pes->sub_st->index;
655 pkt->stream_index = pes->st->index;
658 /* store position of first TS packet of this PES packet */
659 pkt->pos = pes->ts_packet_pos;
660 pkt->flags = pes->flags;
662 /* reset pts values */
663 pes->pts = AV_NOPTS_VALUE;
664 pes->dts = AV_NOPTS_VALUE;
670 static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
673 int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
674 int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
675 int dts_flag = -1, cts_flag = -1;
676 int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
677 init_get_bits(&gb, buf, buf_size*8);
679 if (sl->use_au_start)
680 au_start_flag = get_bits1(&gb);
682 au_end_flag = get_bits1(&gb);
683 if (!sl->use_au_start && !sl->use_au_end)
684 au_start_flag = au_end_flag = 1;
686 ocr_flag = get_bits1(&gb);
688 idle_flag = get_bits1(&gb);
690 padding_flag = get_bits1(&gb);
692 padding_bits = get_bits(&gb, 3);
694 if (!idle_flag && (!padding_flag || padding_bits != 0)) {
695 if (sl->packet_seq_num_len)
696 skip_bits_long(&gb, sl->packet_seq_num_len);
697 if (sl->degr_prior_len)
699 skip_bits(&gb, sl->degr_prior_len);
701 skip_bits_long(&gb, sl->ocr_len);
703 if (sl->use_rand_acc_pt)
705 if (sl->au_seq_num_len > 0)
706 skip_bits_long(&gb, sl->au_seq_num_len);
707 if (sl->use_timestamps) {
708 dts_flag = get_bits1(&gb);
709 cts_flag = get_bits1(&gb);
712 if (sl->inst_bitrate_len)
713 inst_bitrate_flag = get_bits1(&gb);
715 dts = get_bits64(&gb, sl->timestamp_len);
717 cts = get_bits64(&gb, sl->timestamp_len);
719 skip_bits_long(&gb, sl->au_len);
720 if (inst_bitrate_flag)
721 skip_bits_long(&gb, sl->inst_bitrate_len);
724 if (dts != AV_NOPTS_VALUE)
726 if (cts != AV_NOPTS_VALUE)
729 if (sl->timestamp_len && sl->timestamp_res)
730 avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
732 return (get_bits_count(&gb) + 7) >> 3;
735 /* return non zero if a packet could be constructed */
736 static int mpegts_push_data(MpegTSFilter *filter,
737 const uint8_t *buf, int buf_size, int is_start,
740 PESContext *pes = filter->u.pes_filter.opaque;
741 MpegTSContext *ts = pes->ts;
749 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
750 new_pes_packet(pes, ts->pkt);
753 pes->state = MPEGTS_HEADER;
755 pes->ts_packet_pos = pos;
758 while (buf_size > 0) {
761 len = PES_START_SIZE - pes->data_index;
764 memcpy(pes->header + pes->data_index, p, len);
765 pes->data_index += len;
768 if (pes->data_index == PES_START_SIZE) {
769 /* we got all the PES or section header. We can now
771 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
772 pes->header[2] == 0x01) {
773 /* it must be an mpeg2 PES stream */
774 code = pes->header[3] | 0x100;
775 av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
777 if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
778 (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
779 code == 0x1be) /* padding_stream */
782 /* stream not present in PMT */
784 pes->st = avformat_new_stream(ts->stream, NULL);
786 return AVERROR(ENOMEM);
787 pes->st->id = pes->pid;
788 mpegts_set_stream_info(pes->st, pes, 0, 0);
791 pes->total_size = AV_RB16(pes->header + 4);
792 /* NOTE: a zero total size means the PES size is
794 if (!pes->total_size)
795 pes->total_size = MAX_PES_PAYLOAD;
797 /* allocate pes buffer */
798 pes->buffer = av_buffer_alloc(pes->total_size +
799 FF_INPUT_BUFFER_PADDING_SIZE);
801 return AVERROR(ENOMEM);
803 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
804 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
805 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
806 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
807 pes->state = MPEGTS_PESHEADER;
808 if (pes->st->codec->codec_id == AV_CODEC_ID_NONE) {
809 av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
810 pes->pid, pes->stream_type);
811 pes->st->codec->codec_id = AV_CODEC_ID_PROBE;
814 pes->state = MPEGTS_PAYLOAD;
818 /* otherwise, it should be a table */
821 pes->state = MPEGTS_SKIP;
826 /**********************************************/
827 /* PES packing parsing */
828 case MPEGTS_PESHEADER:
829 len = PES_HEADER_SIZE - pes->data_index;
834 memcpy(pes->header + pes->data_index, p, len);
835 pes->data_index += len;
838 if (pes->data_index == PES_HEADER_SIZE) {
839 pes->pes_header_size = pes->header[8] + 9;
840 pes->state = MPEGTS_PESHEADER_FILL;
843 case MPEGTS_PESHEADER_FILL:
844 len = pes->pes_header_size - pes->data_index;
849 memcpy(pes->header + pes->data_index, p, len);
850 pes->data_index += len;
853 if (pes->data_index == pes->pes_header_size) {
855 unsigned int flags, pes_ext, skip;
857 flags = pes->header[7];
859 pes->pts = AV_NOPTS_VALUE;
860 pes->dts = AV_NOPTS_VALUE;
861 if ((flags & 0xc0) == 0x80) {
862 pes->dts = pes->pts = ff_parse_pes_pts(r);
864 } else if ((flags & 0xc0) == 0xc0) {
865 pes->pts = ff_parse_pes_pts(r);
867 pes->dts = ff_parse_pes_pts(r);
870 pes->extended_stream_id = -1;
871 if (flags & 0x01) { /* PES extension */
873 /* Skip PES private data, program packet sequence counter and P-STD buffer */
874 skip = (pes_ext >> 4) & 0xb;
877 if ((pes_ext & 0x41) == 0x01 &&
878 (r + 2) <= (pes->header + pes->pes_header_size)) {
879 /* PES extension 2 */
880 if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
881 pes->extended_stream_id = r[1];
885 /* we got the full header. We parse it and get the payload */
886 pes->state = MPEGTS_PAYLOAD;
888 if (pes->stream_type == 0x12 && buf_size > 0) {
889 int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
890 pes->pes_header_size += sl_header_bytes;
891 p += sl_header_bytes;
892 buf_size -= sl_header_bytes;
897 if (buf_size > 0 && pes->buffer) {
898 if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
899 new_pes_packet(pes, ts->pkt);
900 pes->total_size = MAX_PES_PAYLOAD;
901 pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE);
903 return AVERROR(ENOMEM);
905 } else if (pes->data_index == 0 && buf_size > pes->total_size) {
906 // pes packet size is < ts size packet and pes data is padded with 0xff
907 // not sure if this is legal in ts but see issue #2392
908 buf_size = pes->total_size;
910 memcpy(pes->buffer->data + pes->data_index, p, buf_size);
911 pes->data_index += buf_size;
914 /* emit complete packets with known packet size
915 * decreases demuxer delay for infrequent packets like subtitles from
916 * a couple of seconds to milliseconds for properly muxed files.
917 * total_size is the number of bytes following pes_packet_length
918 * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
919 if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
920 pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
922 new_pes_packet(pes, ts->pkt);
934 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
939 /* if no pid found, then add a pid context */
940 pes = av_mallocz(sizeof(PESContext));
944 pes->stream = ts->stream;
946 pes->pcr_pid = pcr_pid;
947 pes->state = MPEGTS_SKIP;
948 pes->pts = AV_NOPTS_VALUE;
949 pes->dts = AV_NOPTS_VALUE;
950 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
963 Mp4Descr *active_descr;
967 } MP4DescrParseContext;
969 static int init_MP4DescrParseContext(
970 MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
971 unsigned size, Mp4Descr *descr, int max_descr_count)
975 return AVERROR_INVALIDDATA;
977 if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
978 NULL, NULL, NULL, NULL)) < 0)
985 d->active_descr = NULL;
986 d->max_descr_count = max_descr_count;
991 static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
992 int64_t new_off = avio_tell(pb);
993 (*len) -= new_off - *off;
997 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1000 static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
1003 if (parse_mp4_descr(d, off, len, 0) < 0)
1005 update_offsets(&d->pb, &off, &len);
1010 static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1012 avio_rb16(&d->pb); // ID
1018 update_offsets(&d->pb, &off, &len);
1019 return parse_mp4_descr_arr(d, off, len);
1022 static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
1027 id_flags = avio_rb16(&d->pb);
1028 if (!(id_flags & 0x0020)) { //URL_Flag
1029 update_offsets(&d->pb, &off, &len);
1030 return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
1036 static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1039 if (d->descr_count >= d->max_descr_count)
1041 ff_mp4_parse_es_descr(&d->pb, &es_id);
1042 d->active_descr = d->descr + (d->descr_count++);
1044 d->active_descr->es_id = es_id;
1045 update_offsets(&d->pb, &off, &len);
1046 parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
1047 update_offsets(&d->pb, &off, &len);
1049 parse_mp4_descr(d, off, len, MP4SLDescrTag);
1050 d->active_descr = NULL;
1054 static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1056 Mp4Descr *descr = d->active_descr;
1059 d->active_descr->dec_config_descr = av_malloc(len);
1060 if (!descr->dec_config_descr)
1061 return AVERROR(ENOMEM);
1062 descr->dec_config_descr_len = len;
1063 avio_read(&d->pb, descr->dec_config_descr, len);
1067 static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
1069 Mp4Descr *descr = d->active_descr;
1074 predefined = avio_r8(&d->pb);
1077 int flags = avio_r8(&d->pb);
1078 descr->sl.use_au_start = !!(flags & 0x80);
1079 descr->sl.use_au_end = !!(flags & 0x40);
1080 descr->sl.use_rand_acc_pt = !!(flags & 0x20);
1081 descr->sl.use_padding = !!(flags & 0x08);
1082 descr->sl.use_timestamps = !!(flags & 0x04);
1083 descr->sl.use_idle = !!(flags & 0x02);
1084 descr->sl.timestamp_res = avio_rb32(&d->pb);
1086 descr->sl.timestamp_len = avio_r8(&d->pb);
1087 descr->sl.ocr_len = avio_r8(&d->pb);
1088 descr->sl.au_len = avio_r8(&d->pb);
1089 descr->sl.inst_bitrate_len = avio_r8(&d->pb);
1090 lengths = avio_rb16(&d->pb);
1091 descr->sl.degr_prior_len = lengths >> 12;
1092 descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
1093 descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
1095 avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
1100 static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
1103 int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
1104 update_offsets(&d->pb, &off, &len);
1105 if (len < 0 || len1 > len || len1 <= 0) {
1106 av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
1110 if (d->level++ >= MAX_LEVEL) {
1111 av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
1115 if (target_tag && tag != target_tag) {
1116 av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
1122 parse_MP4IODescrTag(d, off, len1);
1125 parse_MP4ODescrTag(d, off, len1);
1128 parse_MP4ESDescrTag(d, off, len1);
1130 case MP4DecConfigDescrTag:
1131 parse_MP4DecConfigDescrTag(d, off, len1);
1134 parse_MP4SLDescrTag(d, off, len1);
1140 avio_seek(&d->pb, off + len1, SEEK_SET);
1144 static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
1145 Mp4Descr *descr, int *descr_count, int max_descr_count)
1147 MP4DescrParseContext d;
1148 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1151 parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
1153 *descr_count = d.descr_count;
1157 static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
1158 Mp4Descr *descr, int *descr_count, int max_descr_count)
1160 MP4DescrParseContext d;
1161 if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
1164 parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
1166 *descr_count = d.descr_count;
1170 static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1172 MpegTSContext *ts = filter->u.section_filter.opaque;
1174 const uint8_t *p, *p_end;
1176 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1177 int mp4_descr_count = 0;
1179 AVFormatContext *s = ts->stream;
1181 p_end = section + section_len - 4;
1183 if (parse_section_header(&h, &p, p_end) < 0)
1185 if (h.tid != M4OD_TID)
1188 mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1190 for (pid = 0; pid < NB_PID_MAX; pid++) {
1193 for (i = 0; i < mp4_descr_count; i++) {
1196 if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
1198 if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
1199 av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
1202 pes = ts->pids[pid]->u.pes_filter.opaque;
1208 pes->sl = mp4_descr[i].sl;
1210 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1211 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1212 ff_mp4_read_dec_config_descr(s, st, &pb);
1213 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1214 st->codec->extradata_size > 0)
1215 st->need_parsing = 0;
1216 if (st->codec->codec_id == AV_CODEC_ID_H264 &&
1217 st->codec->extradata_size > 0)
1218 st->need_parsing = 0;
1220 if (st->codec->codec_id <= AV_CODEC_ID_NONE) {
1221 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
1222 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1223 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
1224 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1225 } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
1226 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1230 for (i = 0; i < mp4_descr_count; i++)
1231 av_free(mp4_descr[i].dec_config_descr);
1234 int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
1235 const uint8_t **pp, const uint8_t *desc_list_end,
1236 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
1239 const uint8_t *desc_end;
1240 int desc_len, desc_tag, desc_es_id;
1244 desc_tag = get8(pp, desc_list_end);
1247 desc_len = get8(pp, desc_list_end);
1250 desc_end = *pp + desc_len;
1251 if (desc_end > desc_list_end)
1254 av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
1256 if (st->codec->codec_id == AV_CODEC_ID_NONE &&
1257 stream_type == STREAM_TYPE_PRIVATE_DATA)
1258 mpegts_find_stream_type(st, desc_tag, DESC_types);
1261 case 0x1E: /* SL descriptor */
1262 desc_es_id = get16(pp, desc_end);
1263 if (ts && ts->pids[pid])
1264 ts->pids[pid]->es_id = desc_es_id;
1265 for (i = 0; i < mp4_descr_count; i++)
1266 if (mp4_descr[i].dec_config_descr_len &&
1267 mp4_descr[i].es_id == desc_es_id) {
1269 ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
1270 mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1271 ff_mp4_read_dec_config_descr(fc, st, &pb);
1272 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1273 st->codec->extradata_size > 0)
1274 st->need_parsing = 0;
1275 if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
1276 mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
1279 case 0x1F: /* FMC descriptor */
1280 get16(pp, desc_end);
1281 if (mp4_descr_count > 0 && st->codec->codec_id == AV_CODEC_ID_AAC_LATM &&
1282 mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
1284 ffio_init_context(&pb, mp4_descr->dec_config_descr,
1285 mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
1286 ff_mp4_read_dec_config_descr(fc, st, &pb);
1287 if (st->codec->codec_id == AV_CODEC_ID_AAC &&
1288 st->codec->extradata_size > 0)
1289 st->need_parsing = 0;
1292 case 0x56: /* DVB teletext descriptor */
1293 language[0] = get8(pp, desc_end);
1294 language[1] = get8(pp, desc_end);
1295 language[2] = get8(pp, desc_end);
1297 av_dict_set(&st->metadata, "language", language, 0);
1299 case 0x59: /* subtitling descriptor */
1300 language[0] = get8(pp, desc_end);
1301 language[1] = get8(pp, desc_end);
1302 language[2] = get8(pp, desc_end);
1304 /* hearing impaired subtitles detection */
1305 switch(get8(pp, desc_end)) {
1306 case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
1307 case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
1308 case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
1309 case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
1310 case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
1311 case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
1312 st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
1315 if (st->codec->extradata) {
1316 if (st->codec->extradata_size == 4 && memcmp(st->codec->extradata, *pp, 4))
1317 avpriv_request_sample(fc, "DVB sub with multiple IDs");
1319 st->codec->extradata = av_malloc(4 + FF_INPUT_BUFFER_PADDING_SIZE);
1320 if (st->codec->extradata) {
1321 st->codec->extradata_size = 4;
1322 memcpy(st->codec->extradata, *pp, 4);
1326 av_dict_set(&st->metadata, "language", language, 0);
1328 case 0x0a: /* ISO 639 language descriptor */
1329 for (i = 0; i + 4 <= desc_len; i += 4) {
1330 language[i + 0] = get8(pp, desc_end);
1331 language[i + 1] = get8(pp, desc_end);
1332 language[i + 2] = get8(pp, desc_end);
1333 language[i + 3] = ',';
1334 switch (get8(pp, desc_end)) {
1335 case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
1336 case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
1337 case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
1341 language[i - 1] = 0;
1342 av_dict_set(&st->metadata, "language", language, 0);
1345 case 0x05: /* registration descriptor */
1346 st->codec->codec_tag = bytestream_get_le32(pp);
1347 av_dlog(fc, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
1348 if (st->codec->codec_id == AV_CODEC_ID_NONE)
1349 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
1358 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1360 MpegTSContext *ts = filter->u.section_filter.opaque;
1361 SectionHeader h1, *h = &h1;
1364 const uint8_t *p, *p_end, *desc_list_end;
1365 int program_info_length, pcr_pid, pid, stream_type;
1367 uint32_t prog_reg_desc = 0; /* registration descriptor */
1369 Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
1370 int mp4_descr_count = 0;
1373 av_dlog(ts->stream, "PMT: len %i\n", section_len);
1374 hex_dump_debug(ts->stream, section, section_len);
1376 p_end = section + section_len - 4;
1378 if (parse_section_header(h, &p, p_end) < 0)
1381 av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
1382 h->id, h->sec_num, h->last_sec_num);
1384 if (h->tid != PMT_TID)
1387 clear_program(ts, h->id);
1388 pcr_pid = get16(&p, p_end);
1392 add_pid_to_pmt(ts, h->id, pcr_pid);
1394 av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
1396 program_info_length = get16(&p, p_end);
1397 if (program_info_length < 0)
1399 program_info_length &= 0xfff;
1400 while(program_info_length >= 2) {
1402 tag = get8(&p, p_end);
1403 len = get8(&p, p_end);
1405 av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
1407 if(len > program_info_length - 2)
1408 //something else is broken, exit the program_descriptors_loop
1410 program_info_length -= len + 2;
1411 if (tag == 0x1d) { // IOD descriptor
1412 get8(&p, p_end); // scope
1413 get8(&p, p_end); // label
1415 mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
1416 &mp4_descr_count, MAX_MP4_DESCR_COUNT);
1417 } else if (tag == 0x05 && len >= 4) { // registration descriptor
1418 prog_reg_desc = bytestream_get_le32(&p);
1423 p += program_info_length;
1427 // stop parsing after pmt, we found header
1428 if (!ts->stream->nb_streams)
1434 stream_type = get8(&p, p_end);
1435 if (stream_type < 0)
1437 pid = get16(&p, p_end);
1442 /* now create stream */
1443 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
1444 pes = ts->pids[pid]->u.pes_filter.opaque;
1446 pes->st = avformat_new_stream(pes->stream, NULL);
1447 pes->st->id = pes->pid;
1450 } else if (stream_type != 0x13) {
1451 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
1452 pes = add_pes_stream(ts, pid, pcr_pid);
1454 st = avformat_new_stream(pes->stream, NULL);
1458 int idx = ff_find_stream_index(ts->stream, pid);
1460 st = ts->stream->streams[idx];
1462 st = avformat_new_stream(ts->stream, NULL);
1464 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1471 if (pes && !pes->stream_type)
1472 mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc);
1474 add_pid_to_pmt(ts, h->id, pid);
1476 ff_program_add_stream_index(ts->stream, h->id, st->index);
1478 desc_list_len = get16(&p, p_end);
1479 if (desc_list_len < 0)
1481 desc_list_len &= 0xfff;
1482 desc_list_end = p + desc_list_len;
1483 if (desc_list_end > p_end)
1486 if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end,
1487 mp4_descr, mp4_descr_count, pid, ts) < 0)
1490 if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) {
1491 ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index);
1492 pes->sub_st->codec->codec_tag = st->codec->codec_tag;
1499 for (i = 0; i < mp4_descr_count; i++)
1500 av_free(mp4_descr[i].dec_config_descr);
1503 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1505 MpegTSContext *ts = filter->u.section_filter.opaque;
1506 SectionHeader h1, *h = &h1;
1507 const uint8_t *p, *p_end;
1510 av_dlog(ts->stream, "PAT:\n");
1511 hex_dump_debug(ts->stream, section, section_len);
1513 p_end = section + section_len - 4;
1515 if (parse_section_header(h, &p, p_end) < 0)
1517 if (h->tid != PAT_TID)
1522 sid = get16(&p, p_end);
1525 pmt_pid = get16(&p, p_end);
1530 av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
1532 if (sid == 0x0000) {
1535 av_new_program(ts->stream, sid);
1536 if (ts->pids[pmt_pid])
1537 mpegts_close_filter(ts, ts->pids[pmt_pid]);
1538 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
1539 add_pat_entry(ts, sid);
1540 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
1541 add_pid_to_pmt(ts, sid, pmt_pid);
1546 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
1548 MpegTSContext *ts = filter->u.section_filter.opaque;
1549 SectionHeader h1, *h = &h1;
1550 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
1551 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
1552 char *name, *provider_name;
1554 av_dlog(ts->stream, "SDT:\n");
1555 hex_dump_debug(ts->stream, section, section_len);
1557 p_end = section + section_len - 4;
1559 if (parse_section_header(h, &p, p_end) < 0)
1561 if (h->tid != SDT_TID)
1563 onid = get16(&p, p_end);
1566 val = get8(&p, p_end);
1570 sid = get16(&p, p_end);
1573 val = get8(&p, p_end);
1576 desc_list_len = get16(&p, p_end);
1577 if (desc_list_len < 0)
1579 desc_list_len &= 0xfff;
1580 desc_list_end = p + desc_list_len;
1581 if (desc_list_end > p_end)
1584 desc_tag = get8(&p, desc_list_end);
1587 desc_len = get8(&p, desc_list_end);
1588 desc_end = p + desc_len;
1589 if (desc_end > desc_list_end)
1592 av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
1593 desc_tag, desc_len);
1597 service_type = get8(&p, p_end);
1598 if (service_type < 0)
1600 provider_name = getstr8(&p, p_end);
1603 name = getstr8(&p, p_end);
1605 AVProgram *program = av_new_program(ts->stream, sid);
1607 av_dict_set(&program->metadata, "service_name", name, 0);
1608 av_dict_set(&program->metadata, "service_provider", provider_name, 0);
1612 av_free(provider_name);
1623 /* handle one TS packet */
1624 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1626 AVFormatContext *s = ts->stream;
1628 int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
1629 has_adaptation, has_payload;
1630 const uint8_t *p, *p_end;
1633 pid = AV_RB16(packet + 1) & 0x1fff;
1634 if(pid && discard_pid(ts, pid))
1636 is_start = packet[1] & 0x40;
1637 tss = ts->pids[pid];
1638 if (ts->auto_guess && tss == NULL && is_start) {
1639 add_pes_stream(ts, pid, -1);
1640 tss = ts->pids[pid];
1645 afc = (packet[3] >> 4) & 3;
1646 if (afc == 0) /* reserved value */
1648 has_adaptation = afc & 2;
1649 has_payload = afc & 1;
1650 is_discontinuity = has_adaptation
1651 && packet[4] != 0 /* with length > 0 */
1652 && (packet[5] & 0x80); /* and discontinuity indicated */
1654 /* continuity check (currently not used) */
1655 cc = (packet[3] & 0xf);
1656 expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
1657 cc_ok = pid == 0x1FFF // null packet PID
1660 || expected_cc == cc;
1664 av_log(ts->stream, AV_LOG_WARNING,
1665 "Continuity check failed for pid %d expected %d got %d\n",
1666 pid, expected_cc, cc);
1667 if(tss->type == MPEGTS_PES) {
1668 PESContext *pc = tss->u.pes_filter.opaque;
1669 pc->flags |= AV_PKT_FLAG_CORRUPT;
1676 if (has_adaptation) {
1677 /* skip adaptation field */
1680 /* if past the end of packet, ignore */
1681 p_end = packet + TS_PACKET_SIZE;
1685 pos = avio_tell(ts->stream->pb);
1686 ts->pos47= pos % ts->raw_packet_size;
1688 if (tss->type == MPEGTS_SECTION) {
1690 /* pointer field present */
1692 if (p + len > p_end)
1695 /* write remaining section bytes */
1696 write_section_data(s, tss,
1698 /* check whether filter has been closed */
1704 write_section_data(s, tss,
1709 write_section_data(s, tss,
1715 // Note: The position here points actually behind the current packet.
1716 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1717 pos - ts->raw_packet_size)) < 0)
1724 /* XXX: try to find a better synchro over several packets (use
1725 get_packet_size() ?) */
1726 static int mpegts_resync(AVFormatContext *s)
1728 AVIOContext *pb = s->pb;
1731 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1733 if (pb->eof_reached)
1736 avio_seek(pb, -1, SEEK_CUR);
1740 av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
1745 /* return -1 if error or EOF. Return 0 if OK. */
1746 static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
1748 AVIOContext *pb = s->pb;
1752 len = avio_read(pb, buf, TS_PACKET_SIZE);
1753 if (len != TS_PACKET_SIZE)
1754 return len < 0 ? len : AVERROR_EOF;
1755 /* check packet sync byte */
1756 if (buf[0] != 0x47) {
1757 /* find a new packet start */
1758 avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1759 if (mpegts_resync(s) < 0)
1760 return AVERROR(EAGAIN);
1764 skip = raw_packet_size - TS_PACKET_SIZE;
1766 avio_skip(pb, skip);
1773 static int handle_packets(MpegTSContext *ts, int nb_packets)
1775 AVFormatContext *s = ts->stream;
1776 uint8_t packet[TS_PACKET_SIZE+FF_INPUT_BUFFER_PADDING_SIZE];
1777 int packet_num, ret = 0;
1779 if (avio_tell(s->pb) != ts->last_pos) {
1781 av_dlog(ts->stream, "Skipping after seek\n");
1782 /* seek detected, flush pes buffer */
1783 for (i = 0; i < NB_PID_MAX; i++) {
1785 if (ts->pids[i]->type == MPEGTS_PES) {
1786 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1787 av_buffer_unref(&pes->buffer);
1788 pes->data_index = 0;
1789 pes->state = MPEGTS_SKIP; /* skip until pes header */
1791 ts->pids[i]->last_cc = -1;
1798 memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1800 if (ts->stop_parse>0)
1803 if (nb_packets != 0 && packet_num >= nb_packets)
1805 ret = read_packet(s, packet, ts->raw_packet_size);
1808 ret = handle_packet(ts, packet);
1812 ts->last_pos = avio_tell(s->pb);
1816 static int mpegts_probe(AVProbeData *p)
1818 const int size= p->buf_size;
1819 int score, fec_score, dvhs_score;
1820 int check_count= size / TS_FEC_PACKET_SIZE;
1821 #define CHECK_COUNT 10
1823 if (check_count < CHECK_COUNT)
1826 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1827 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1828 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1829 av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n",
1830 score, dvhs_score, fec_score);
1832 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1833 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1834 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1835 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1839 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1840 (-1) if not available */
1841 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1842 const uint8_t *packet)
1844 int afc, len, flags;
1848 afc = (packet[3] >> 4) & 3;
1858 if (!(flags & 0x10))
1863 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1864 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1868 static int mpegts_read_header(AVFormatContext *s)
1870 MpegTSContext *ts = s->priv_data;
1871 AVIOContext *pb = s->pb;
1872 uint8_t buf[5*1024];
1876 /* read the first 1024 bytes to get packet size */
1877 pos = avio_tell(pb);
1878 len = avio_read(pb, buf, sizeof(buf));
1879 if (len != sizeof(buf))
1881 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1882 if (ts->raw_packet_size <= 0)
1887 if (s->iformat == &ff_mpegts_demuxer) {
1890 /* first do a scan to get all the services */
1891 if (avio_seek(pb, pos, SEEK_SET) < 0 && pb->seekable)
1892 av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");
1894 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1896 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1898 handle_packets(ts, s->probesize / ts->raw_packet_size);
1899 /* if could not find service, enable auto_guess */
1903 av_dlog(ts->stream, "tuning done\n");
1905 s->ctx_flags |= AVFMTCTX_NOHEADER;
1908 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1909 int64_t pcrs[2], pcr_h;
1910 int packet_count[2];
1911 uint8_t packet[TS_PACKET_SIZE];
1913 /* only read packets */
1915 st = avformat_new_stream(s, NULL);
1918 avpriv_set_pts_info(st, 60, 1, 27000000);
1919 st->codec->codec_type = AVMEDIA_TYPE_DATA;
1920 st->codec->codec_id = AV_CODEC_ID_MPEG2TS;
1922 /* we iterate until we find two PCRs to estimate the bitrate */
1927 ret = read_packet(s, packet, ts->raw_packet_size);
1930 pid = AV_RB16(packet + 1) & 0x1fff;
1931 if ((pcr_pid == -1 || pcr_pid == pid) &&
1932 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1934 packet_count[nb_pcrs] = nb_packets;
1935 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1943 /* NOTE1: the bitrate is computed without the FEC */
1944 /* NOTE2: it is only the bitrate of the start of the stream */
1945 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1946 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1947 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1948 st->codec->bit_rate = s->bit_rate;
1949 st->start_time = ts->cur_pcr;
1950 av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
1951 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1954 avio_seek(pb, pos, SEEK_SET);
1960 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1962 static int mpegts_raw_read_packet(AVFormatContext *s,
1965 MpegTSContext *ts = s->priv_data;
1967 int64_t pcr_h, next_pcr_h, pos;
1968 int pcr_l, next_pcr_l;
1969 uint8_t pcr_buf[12];
1971 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1972 return AVERROR(ENOMEM);
1973 pkt->pos= avio_tell(s->pb);
1974 ret = read_packet(s, pkt->data, ts->raw_packet_size);
1976 av_free_packet(pkt);
1979 if (ts->mpeg2ts_compute_pcr) {
1980 /* compute exact PCR for each packet */
1981 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1982 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1983 pos = avio_tell(s->pb);
1984 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1985 avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1986 avio_read(s->pb, pcr_buf, 12);
1987 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1988 /* XXX: not precise enough */
1989 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1994 avio_seek(s->pb, pos, SEEK_SET);
1995 /* no next PCR found: we use previous increment */
1996 ts->cur_pcr = pcr_h * 300 + pcr_l;
1998 pkt->pts = ts->cur_pcr;
1999 pkt->duration = ts->pcr_incr;
2000 ts->cur_pcr += ts->pcr_incr;
2002 pkt->stream_index = 0;
2006 static int mpegts_read_packet(AVFormatContext *s,
2009 MpegTSContext *ts = s->priv_data;
2014 ret = handle_packets(ts, 0);
2016 /* flush pes data left */
2017 for (i = 0; i < NB_PID_MAX; i++) {
2018 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
2019 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
2020 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
2021 new_pes_packet(pes, pkt);
2022 pes->state = MPEGTS_SKIP;
2030 if (!ret && pkt->size < 0)
2031 ret = AVERROR(EINTR);
2035 static void mpegts_free(MpegTSContext *ts)
2041 for(i=0;i<NB_PID_MAX;i++)
2042 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
2045 static int mpegts_read_close(AVFormatContext *s)
2047 MpegTSContext *ts = s->priv_data;
2052 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
2053 int64_t *ppos, int64_t pos_limit)
2055 MpegTSContext *ts = s->priv_data;
2056 int64_t pos, timestamp;
2057 uint8_t buf[TS_PACKET_SIZE];
2058 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
2059 const int find_next= 1;
2060 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
2063 avio_seek(s->pb, pos, SEEK_SET);
2064 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2065 return AV_NOPTS_VALUE;
2066 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2067 parse_pcr(×tamp, &pcr_l, buf) == 0) {
2070 pos += ts->raw_packet_size;
2074 pos -= ts->raw_packet_size;
2076 return AV_NOPTS_VALUE;
2077 avio_seek(s->pb, pos, SEEK_SET);
2078 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2079 return AV_NOPTS_VALUE;
2080 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
2081 parse_pcr(×tamp, &pcr_l, buf) == 0) {
2091 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
2092 MpegTSContext *ts = s->priv_data;
2093 uint8_t buf[TS_PACKET_SIZE];
2096 if (ff_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
2099 pos= avio_tell(s->pb);
2102 avio_seek(s->pb, pos, SEEK_SET);
2103 if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
2105 // pid = AV_RB16(buf + 1) & 0x1fff;
2106 if(buf[1] & 0x40) break;
2107 pos += ts->raw_packet_size;
2109 avio_seek(s->pb, pos, SEEK_SET);
2114 /**************************************************************/
2115 /* parsing functions - called from other demuxers such as RTP */
2117 MpegTSContext *ff_mpegts_parse_open(AVFormatContext *s)
2121 ts = av_mallocz(sizeof(MpegTSContext));
2124 /* no stream case, currently used by RTP */
2125 ts->raw_packet_size = TS_PACKET_SIZE;
2131 /* return the consumed length if a packet was output, or -1 if no
2133 int ff_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
2134 const uint8_t *buf, int len)
2142 if (ts->stop_parse>0)
2144 if (len < TS_PACKET_SIZE)
2146 if (buf[0] != 0x47) {
2150 handle_packet(ts, buf);
2151 buf += TS_PACKET_SIZE;
2152 len -= TS_PACKET_SIZE;
2158 void ff_mpegts_parse_close(MpegTSContext *ts)
2164 AVInputFormat ff_mpegts_demuxer = {
2166 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
2167 .priv_data_size = sizeof(MpegTSContext),
2168 .read_probe = mpegts_probe,
2169 .read_header = mpegts_read_header,
2170 .read_packet = mpegts_read_packet,
2171 .read_close = mpegts_read_close,
2172 .read_seek = read_seek,
2173 .read_timestamp = mpegts_get_pcr,
2174 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2177 AVInputFormat ff_mpegtsraw_demuxer = {
2178 .name = "mpegtsraw",
2179 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
2180 .priv_data_size = sizeof(MpegTSContext),
2181 .read_header = mpegts_read_header,
2182 .read_packet = mpegts_raw_read_packet,
2183 .read_close = mpegts_read_close,
2184 .read_seek = read_seek,
2185 .read_timestamp = mpegts_get_pcr,
2186 .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
2187 .priv_class = &mpegtsraw_class,