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
25 #include "libavutil/crc.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavcodec/bytestream.h"
33 /* 1.0 second at 24Mbit/s */
34 #define MAX_SCAN_PACKETS 32000
36 /* maximum size in which we look for synchronisation if
37 synchronisation is lost */
38 #define MAX_RESYNC_SIZE 4096
40 #define MAX_PES_PAYLOAD 200*1024
42 typedef struct PESContext PESContext;
44 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
46 enum MpegTSFilterType {
51 typedef struct MpegTSFilter MpegTSFilter;
53 typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
55 typedef struct MpegTSPESFilter {
60 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
62 typedef void SetServiceCallback(void *opaque, int ret);
64 typedef struct MpegTSSectionFilter {
68 unsigned int check_crc:1;
69 unsigned int end_of_section_reached:1;
70 SectionCallback *section_cb;
72 } MpegTSSectionFilter;
76 int last_cc; /* last cc code (-1 if first packet) */
77 enum MpegTSFilterType type;
79 MpegTSPESFilter pes_filter;
80 MpegTSSectionFilter section_filter;
84 #define MAX_PIDS_PER_PROGRAM 64
86 unsigned int id; //program id/service id
88 unsigned int pids[MAX_PIDS_PER_PROGRAM];
91 struct MpegTSContext {
93 AVFormatContext *stream;
94 /** raw packet size, including FEC if present */
99 /** if true, all pids are analyzed to find streams */
102 /** compute exact PCR for each transport stream packet */
103 int mpeg2ts_compute_pcr;
105 int64_t cur_pcr; /**< used to estimate the exact PCR */
106 int pcr_incr; /**< used to estimate the exact PCR */
108 /* data needed to handle file based ts */
109 /** stop parsing loop */
111 /** packet containing Audio/Video data */
113 /** to detect seek */
116 /******************************************/
117 /* private mpegts data */
119 /** structure to keep track of Program->pids mapping */
124 /** filters for various streams specified by PMT + for the PAT and PMT */
125 MpegTSFilter *pids[NB_PID_MAX];
128 /* TS stream handling */
133 MPEGTS_PESHEADER_FILL,
138 /* enough for PES header + length */
139 #define PES_START_SIZE 6
140 #define PES_HEADER_SIZE 9
141 #define MAX_PES_HEADER_SIZE (9 + 255)
145 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
148 AVFormatContext *stream;
150 enum MpegTSState state;
151 /* used to get the format */
156 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
157 uint8_t header[MAX_PES_HEADER_SIZE];
161 extern AVInputFormat mpegts_demuxer;
163 static void clear_program(MpegTSContext *ts, unsigned int programid)
167 for(i=0; i<ts->nb_prg; i++)
168 if(ts->prg[i].id == programid)
169 ts->prg[i].nb_pids = 0;
172 static void clear_programs(MpegTSContext *ts)
178 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
181 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
185 p = &ts->prg[ts->nb_prg];
191 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
194 struct Program *p = NULL;
195 for(i=0; i<ts->nb_prg; i++) {
196 if(ts->prg[i].id == programid) {
204 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
206 p->pids[p->nb_pids++] = pid;
210 * \brief discard_pid() decides if the pid is to be discarded according
211 * to caller's programs selection
212 * \param ts : - TS context
214 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
217 static int discard_pid(MpegTSContext *ts, unsigned int pid)
220 int used = 0, discarded = 0;
222 for(i=0; i<ts->nb_prg; i++) {
224 for(j=0; j<p->nb_pids; j++) {
225 if(p->pids[j] != pid)
227 //is program with id p->id set to be discarded?
228 for(k=0; k<ts->stream->nb_programs; k++) {
229 if(ts->stream->programs[k]->id == p->id) {
230 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
239 return !used && discarded;
243 * Assembles PES packets out of TS packets, and then calls the "section_cb"
244 * function when they are complete.
246 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
247 const uint8_t *buf, int buf_size, int is_start)
249 MpegTSSectionFilter *tss = &tss1->u.section_filter;
253 memcpy(tss->section_buf, buf, buf_size);
254 tss->section_index = buf_size;
255 tss->section_h_size = -1;
256 tss->end_of_section_reached = 0;
258 if (tss->end_of_section_reached)
260 len = 4096 - tss->section_index;
263 memcpy(tss->section_buf + tss->section_index, buf, len);
264 tss->section_index += len;
267 /* compute section length if possible */
268 if (tss->section_h_size == -1 && tss->section_index >= 3) {
269 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
272 tss->section_h_size = len;
275 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
276 tss->end_of_section_reached = 1;
277 if (!tss->check_crc ||
278 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
279 tss->section_buf, tss->section_h_size) == 0)
280 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
284 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
285 SectionCallback *section_cb, void *opaque,
289 MpegTSFilter *filter;
290 MpegTSSectionFilter *sec;
292 dprintf(ts->stream, "Filter: pid=0x%x\n", pid);
294 if (pid >= NB_PID_MAX || ts->pids[pid])
296 filter = av_mallocz(sizeof(MpegTSFilter));
299 ts->pids[pid] = filter;
300 filter->type = MPEGTS_SECTION;
302 filter->last_cc = -1;
303 sec = &filter->u.section_filter;
304 sec->section_cb = section_cb;
305 sec->opaque = opaque;
306 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
307 sec->check_crc = check_crc;
308 if (!sec->section_buf) {
315 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
319 MpegTSFilter *filter;
320 MpegTSPESFilter *pes;
322 if (pid >= NB_PID_MAX || ts->pids[pid])
324 filter = av_mallocz(sizeof(MpegTSFilter));
327 ts->pids[pid] = filter;
328 filter->type = MPEGTS_PES;
330 filter->last_cc = -1;
331 pes = &filter->u.pes_filter;
332 pes->pes_cb = pes_cb;
333 pes->opaque = opaque;
337 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
342 if (filter->type == MPEGTS_SECTION)
343 av_freep(&filter->u.section_filter.section_buf);
344 else if (filter->type == MPEGTS_PES) {
345 PESContext *pes = filter->u.pes_filter.opaque;
346 av_freep(&pes->buffer);
347 /* referenced private data will be freed later in
348 * av_close_input_stream */
349 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
350 av_freep(&filter->u.pes_filter.opaque);
355 ts->pids[pid] = NULL;
358 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
359 int stat[TS_MAX_PACKET_SIZE];
364 memset(stat, 0, packet_size*sizeof(int));
366 for(x=i=0; i<size-3; i++){
367 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
369 if(stat[x] > best_score){
376 if(x == packet_size) x= 0;
382 /* autodetect fec presence. Must have at least 1024 bytes */
383 static int get_packet_size(const uint8_t *buf, int size)
385 int score, fec_score, dvhs_score;
387 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
390 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
391 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
392 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
393 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
395 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
396 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
397 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
401 typedef struct SectionHeader {
406 uint8_t last_sec_num;
409 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
422 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
428 if ((p + 1) >= p_end)
436 /* read and allocate a DVB string preceeded by its length */
437 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
444 len = get8(&p, p_end);
447 if ((p + len) > p_end)
449 str = av_malloc(len + 1);
459 static int parse_section_header(SectionHeader *h,
460 const uint8_t **pp, const uint8_t *p_end)
464 val = get8(pp, p_end);
469 val = get16(pp, p_end);
473 val = get8(pp, p_end);
476 h->version = (val >> 1) & 0x1f;
477 val = get8(pp, p_end);
481 val = get8(pp, p_end);
484 h->last_sec_num = val;
489 uint32_t stream_type;
490 enum CodecType codec_type;
491 enum CodecID codec_id;
494 static const StreamType ISO_types[] = {
495 { 0x01, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
496 { 0x02, CODEC_TYPE_VIDEO, CODEC_ID_MPEG2VIDEO },
497 { 0x03, CODEC_TYPE_AUDIO, CODEC_ID_MP3 },
498 { 0x04, CODEC_TYPE_AUDIO, CODEC_ID_MP3 },
499 { 0x0f, CODEC_TYPE_AUDIO, CODEC_ID_AAC },
500 { 0x10, CODEC_TYPE_VIDEO, CODEC_ID_MPEG4 },
501 { 0x1b, CODEC_TYPE_VIDEO, CODEC_ID_H264 },
502 { 0xd1, CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
503 { 0xea, CODEC_TYPE_VIDEO, CODEC_ID_VC1 },
507 static const StreamType HDMV_types[] = {
508 { 0x80, CODEC_TYPE_AUDIO, CODEC_ID_PCM_BLURAY },
509 { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
510 { 0x82, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
511 { 0x90, CODEC_TYPE_SUBTITLE, CODEC_ID_HDMV_PGS_SUBTITLE },
516 static const StreamType MISC_types[] = {
517 { 0x81, CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
518 { 0x8a, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
522 static const StreamType REGD_types[] = {
523 { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO, CODEC_ID_DIRAC },
524 { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO, CODEC_ID_AC3 },
528 /* descriptor present */
529 static const StreamType DESC_types[] = {
530 { 0x6a, CODEC_TYPE_AUDIO, CODEC_ID_AC3 }, /* AC-3 descriptor */
531 { 0x7a, CODEC_TYPE_AUDIO, CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
532 { 0x7b, CODEC_TYPE_AUDIO, CODEC_ID_DTS },
533 { 0x59, CODEC_TYPE_SUBTITLE, CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
537 static void mpegts_find_stream_type(AVStream *st,
538 uint32_t stream_type, const StreamType *types)
540 for (; types->stream_type; types++) {
541 if (stream_type == types->stream_type) {
542 st->codec->codec_type = types->codec_type;
543 st->codec->codec_id = types->codec_id;
549 static AVStream *new_pes_av_stream(PESContext *pes, uint32_t prog_reg_desc, uint32_t code)
551 AVStream *st = av_new_stream(pes->stream, pes->pid);
556 av_set_pts_info(st, 33, 1, 90000);
558 st->codec->codec_type = CODEC_TYPE_DATA;
559 st->codec->codec_id = CODEC_ID_NONE;
560 st->need_parsing = AVSTREAM_PARSE_FULL;
563 dprintf(pes->stream, "stream_type=%x pid=%x prog_reg_desc=%.4s\n",
564 pes->stream_type, pes->pid, (char*)&prog_reg_desc);
566 st->codec->codec_tag = pes->stream_type;
568 mpegts_find_stream_type(st, pes->stream_type, ISO_types);
569 if (prog_reg_desc == AV_RL32("HDMV") &&
570 st->codec->codec_id == CODEC_ID_NONE)
571 mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
572 if (st->codec->codec_id == CODEC_ID_NONE)
573 mpegts_find_stream_type(st, pes->stream_type, MISC_types);
575 /* stream was not present in PMT, guess based on PES start code */
576 if (st->codec->codec_id == CODEC_ID_NONE) {
577 if (code >= 0x1c0 && code <= 0x1df) {
578 st->codec->codec_type = CODEC_TYPE_AUDIO;
579 st->codec->codec_id = CODEC_ID_MP2;
580 } else if (code == 0x1bd) {
581 st->codec->codec_type = CODEC_TYPE_AUDIO;
582 st->codec->codec_id = CODEC_ID_AC3;
589 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
591 MpegTSContext *ts = filter->u.section_filter.opaque;
592 SectionHeader h1, *h = &h1;
595 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
596 int program_info_length, pcr_pid, pid, stream_type;
597 int desc_list_len, desc_len, desc_tag;
598 int comp_page, anc_page;
600 uint32_t prog_reg_desc = 0; /* registration descriptor */
603 dprintf(ts->stream, "PMT: len %i\n", section_len);
604 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
607 p_end = section + section_len - 4;
609 if (parse_section_header(h, &p, p_end) < 0)
612 dprintf(ts->stream, "sid=0x%x sec_num=%d/%d\n",
613 h->id, h->sec_num, h->last_sec_num);
615 if (h->tid != PMT_TID)
618 clear_program(ts, h->id);
619 pcr_pid = get16(&p, p_end) & 0x1fff;
622 add_pid_to_pmt(ts, h->id, pcr_pid);
624 dprintf(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
626 program_info_length = get16(&p, p_end) & 0xfff;
627 if (program_info_length < 0)
629 while(program_info_length >= 2) {
631 tag = get8(&p, p_end);
632 len = get8(&p, p_end);
633 if(len > program_info_length - 2)
634 //something else is broken, exit the program_descriptors_loop
636 program_info_length -= len + 2;
637 if(tag == 0x05 && len >= 4) { // registration descriptor
638 prog_reg_desc = bytestream_get_le32(&p);
643 p += program_info_length;
647 // stop parsing after pmt, we found header
648 if (!ts->stream->nb_streams)
653 stream_type = get8(&p, p_end);
656 pid = get16(&p, p_end) & 0x1fff;
660 /* now create ffmpeg stream */
661 if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
662 pes = ts->pids[pid]->u.pes_filter.opaque;
665 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
666 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
668 st = new_pes_av_stream(pes, prog_reg_desc, 0);
674 add_pid_to_pmt(ts, h->id, pid);
676 av_program_add_stream_index(ts->stream, h->id, st->index);
678 desc_list_len = get16(&p, p_end) & 0xfff;
679 if (desc_list_len < 0)
681 desc_list_end = p + desc_list_len;
682 if (desc_list_end > p_end)
685 desc_tag = get8(&p, desc_list_end);
688 desc_len = get8(&p, desc_list_end);
691 desc_end = p + desc_len;
692 if (desc_end > desc_list_end)
695 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
698 if (st->codec->codec_id == CODEC_ID_NONE &&
699 stream_type == STREAM_TYPE_PRIVATE_DATA)
700 mpegts_find_stream_type(st, desc_tag, DESC_types);
703 case 0x59: /* subtitling descriptor */
704 language[0] = get8(&p, desc_end);
705 language[1] = get8(&p, desc_end);
706 language[2] = get8(&p, desc_end);
709 comp_page = get16(&p, desc_end);
710 anc_page = get16(&p, desc_end);
711 st->codec->sub_id = (anc_page << 16) | comp_page;
712 av_metadata_set(&st->metadata, "language", language);
714 case 0x0a: /* ISO 639 language descriptor */
715 language[0] = get8(&p, desc_end);
716 language[1] = get8(&p, desc_end);
717 language[2] = get8(&p, desc_end);
719 av_metadata_set(&st->metadata, "language", language);
721 case 0x05: /* registration descriptor */
722 st->codec->codec_tag = bytestream_get_le32(&p);
723 dprintf(ts->stream, "reg_desc=%.4s\n", (char*)&st->codec->codec_tag);
724 if (st->codec->codec_id == CODEC_ID_NONE &&
725 stream_type == STREAM_TYPE_PRIVATE_DATA)
726 mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types);
735 /* all parameters are there */
736 mpegts_close_filter(ts, filter);
739 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
741 MpegTSContext *ts = filter->u.section_filter.opaque;
742 SectionHeader h1, *h = &h1;
743 const uint8_t *p, *p_end;
747 dprintf(ts->stream, "PAT:\n");
748 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
750 p_end = section + section_len - 4;
752 if (parse_section_header(h, &p, p_end) < 0)
754 if (h->tid != PAT_TID)
759 sid = get16(&p, p_end);
762 pmt_pid = get16(&p, p_end) & 0x1fff;
766 dprintf(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
771 av_new_program(ts->stream, sid);
772 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
773 add_pat_entry(ts, sid);
774 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
775 add_pid_to_pmt(ts, sid, pmt_pid);
780 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
782 MpegTSContext *ts = filter->u.section_filter.opaque;
783 SectionHeader h1, *h = &h1;
784 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
785 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
786 char *name, *provider_name;
789 dprintf(ts->stream, "SDT:\n");
790 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
793 p_end = section + section_len - 4;
795 if (parse_section_header(h, &p, p_end) < 0)
797 if (h->tid != SDT_TID)
799 onid = get16(&p, p_end);
802 val = get8(&p, p_end);
806 sid = get16(&p, p_end);
809 val = get8(&p, p_end);
812 desc_list_len = get16(&p, p_end) & 0xfff;
813 if (desc_list_len < 0)
815 desc_list_end = p + desc_list_len;
816 if (desc_list_end > p_end)
819 desc_tag = get8(&p, desc_list_end);
822 desc_len = get8(&p, desc_list_end);
823 desc_end = p + desc_len;
824 if (desc_end > desc_list_end)
827 dprintf(ts->stream, "tag: 0x%02x len=%d\n",
832 service_type = get8(&p, p_end);
833 if (service_type < 0)
835 provider_name = getstr8(&p, p_end);
838 name = getstr8(&p, p_end);
840 AVProgram *program = av_new_program(ts->stream, sid);
842 av_metadata_set(&program->metadata, "name", name);
843 av_metadata_set(&program->metadata, "provider_name", provider_name);
847 av_free(provider_name);
858 static int64_t get_pts(const uint8_t *p)
860 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
861 pts |= (AV_RB16(p + 1) >> 1) << 15;
862 pts |= AV_RB16(p + 3) >> 1;
866 static void new_pes_packet(PESContext *pes, AVPacket *pkt)
870 pkt->destruct = av_destruct_packet;
871 pkt->data = pes->buffer;
872 pkt->size = pes->data_index;
873 memset(pkt->data+pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
875 pkt->stream_index = pes->st->index;
878 /* store position of first TS packet of this PES packet */
879 pkt->pos = pes->ts_packet_pos;
881 /* reset pts values */
882 pes->pts = AV_NOPTS_VALUE;
883 pes->dts = AV_NOPTS_VALUE;
888 /* return non zero if a packet could be constructed */
889 static int mpegts_push_data(MpegTSFilter *filter,
890 const uint8_t *buf, int buf_size, int is_start,
893 PESContext *pes = filter->u.pes_filter.opaque;
894 MpegTSContext *ts = pes->ts;
902 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
903 new_pes_packet(pes, ts->pkt);
906 pes->state = MPEGTS_HEADER;
908 pes->ts_packet_pos = pos;
911 while (buf_size > 0) {
914 len = PES_START_SIZE - pes->data_index;
917 memcpy(pes->header + pes->data_index, p, len);
918 pes->data_index += len;
921 if (pes->data_index == PES_START_SIZE) {
922 /* we got all the PES or section header. We can now
925 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
927 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
928 pes->header[2] == 0x01) {
929 /* it must be an mpeg2 PES stream */
930 code = pes->header[3] | 0x100;
931 dprintf(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
933 if ((!pes->st && pes->stream->nb_streams == MAX_STREAMS) ||
934 (pes->st && pes->st->discard == AVDISCARD_ALL) ||
935 code == 0x1be) /* padding_stream */
938 /* stream not present in PMT */
940 pes->st = new_pes_av_stream(pes, 0, code);
942 return AVERROR(ENOMEM);
944 pes->total_size = AV_RB16(pes->header + 4);
945 /* NOTE: a zero total size means the PES size is
947 if (!pes->total_size)
948 pes->total_size = MAX_PES_PAYLOAD;
950 /* allocate pes buffer */
951 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
953 return AVERROR(ENOMEM);
955 if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
956 code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
957 code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
958 code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
959 pes->state = MPEGTS_PESHEADER;
960 if (pes->st->codec->codec_id == CODEC_ID_NONE) {
961 dprintf(pes->stream, "pid=%x stream_type=%x probing\n",
962 pes->pid, pes->stream_type);
963 pes->st->codec->codec_id = CODEC_ID_PROBE;
966 pes->state = MPEGTS_PAYLOAD;
970 /* otherwise, it should be a table */
973 pes->state = MPEGTS_SKIP;
978 /**********************************************/
979 /* PES packing parsing */
980 case MPEGTS_PESHEADER:
981 len = PES_HEADER_SIZE - pes->data_index;
986 memcpy(pes->header + pes->data_index, p, len);
987 pes->data_index += len;
990 if (pes->data_index == PES_HEADER_SIZE) {
991 pes->pes_header_size = pes->header[8] + 9;
992 pes->state = MPEGTS_PESHEADER_FILL;
995 case MPEGTS_PESHEADER_FILL:
996 len = pes->pes_header_size - pes->data_index;
1001 memcpy(pes->header + pes->data_index, p, len);
1002 pes->data_index += len;
1005 if (pes->data_index == pes->pes_header_size) {
1009 flags = pes->header[7];
1010 r = pes->header + 9;
1011 pes->pts = AV_NOPTS_VALUE;
1012 pes->dts = AV_NOPTS_VALUE;
1013 if ((flags & 0xc0) == 0x80) {
1014 pes->dts = pes->pts = get_pts(r);
1016 } else if ((flags & 0xc0) == 0xc0) {
1017 pes->pts = get_pts(r);
1019 pes->dts = get_pts(r);
1023 /* we got the full header. We parse it and get the payload */
1024 pes->state = MPEGTS_PAYLOAD;
1025 pes->data_index = 0;
1028 case MPEGTS_PAYLOAD:
1030 if (pes->data_index+buf_size > pes->total_size) {
1031 new_pes_packet(pes, ts->pkt);
1032 pes->total_size = MAX_PES_PAYLOAD;
1033 pes->buffer = av_malloc(pes->total_size+FF_INPUT_BUFFER_PADDING_SIZE);
1035 return AVERROR(ENOMEM);
1038 memcpy(pes->buffer+pes->data_index, p, buf_size);
1039 pes->data_index += buf_size;
1052 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1057 /* if no pid found, then add a pid context */
1058 pes = av_mallocz(sizeof(PESContext));
1062 pes->stream = ts->stream;
1064 pes->pcr_pid = pcr_pid;
1065 pes->stream_type = stream_type;
1066 pes->state = MPEGTS_SKIP;
1067 pes->pts = AV_NOPTS_VALUE;
1068 pes->dts = AV_NOPTS_VALUE;
1069 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1077 /* handle one TS packet */
1078 static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
1080 AVFormatContext *s = ts->stream;
1082 int len, pid, cc, cc_ok, afc, is_start;
1083 const uint8_t *p, *p_end;
1086 pid = AV_RB16(packet + 1) & 0x1fff;
1087 if(pid && discard_pid(ts, pid))
1089 is_start = packet[1] & 0x40;
1090 tss = ts->pids[pid];
1091 if (ts->auto_guess && tss == NULL && is_start) {
1092 add_pes_stream(ts, pid, -1, 0);
1093 tss = ts->pids[pid];
1098 /* continuity check (currently not used) */
1099 cc = (packet[3] & 0xf);
1100 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1103 /* skip adaptation field */
1104 afc = (packet[3] >> 4) & 3;
1106 if (afc == 0) /* reserved value */
1108 if (afc == 2) /* adaptation field only */
1111 /* skip adapation field */
1114 /* if past the end of packet, ignore */
1115 p_end = packet + TS_PACKET_SIZE;
1119 pos = url_ftell(ts->stream->pb);
1120 ts->pos47= pos % ts->raw_packet_size;
1122 if (tss->type == MPEGTS_SECTION) {
1124 /* pointer field present */
1126 if (p + len > p_end)
1129 /* write remaining section bytes */
1130 write_section_data(s, tss,
1132 /* check whether filter has been closed */
1138 write_section_data(s, tss,
1143 write_section_data(s, tss,
1149 // Note: The position here points actually behind the current packet.
1150 if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
1151 pos - ts->raw_packet_size)) < 0)
1158 /* XXX: try to find a better synchro over several packets (use
1159 get_packet_size() ?) */
1160 static int mpegts_resync(ByteIOContext *pb)
1164 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1169 url_fseek(pb, -1, SEEK_CUR);
1177 /* return -1 if error or EOF. Return 0 if OK. */
1178 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1183 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1184 if (len != TS_PACKET_SIZE)
1185 return AVERROR(EIO);
1186 /* check paquet sync byte */
1187 if (buf[0] != 0x47) {
1188 /* find a new packet start */
1189 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1190 if (mpegts_resync(pb) < 0)
1191 return AVERROR_INVALIDDATA;
1195 skip = raw_packet_size - TS_PACKET_SIZE;
1197 url_fskip(pb, skip);
1204 static int handle_packets(MpegTSContext *ts, int nb_packets)
1206 AVFormatContext *s = ts->stream;
1207 ByteIOContext *pb = s->pb;
1208 uint8_t packet[TS_PACKET_SIZE];
1209 int packet_num, ret;
1214 if (ts->stop_parse>0)
1217 if (nb_packets != 0 && packet_num >= nb_packets)
1219 ret = read_packet(pb, packet, ts->raw_packet_size);
1222 ret = handle_packet(ts, packet);
1229 static int mpegts_probe(AVProbeData *p)
1232 const int size= p->buf_size;
1233 int score, fec_score, dvhs_score;
1234 int check_count= size / TS_FEC_PACKET_SIZE;
1235 #define CHECK_COUNT 10
1237 if (check_count < CHECK_COUNT)
1240 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1241 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1242 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1243 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1245 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1246 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1247 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1248 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1251 /* only use the extension for safer guess */
1252 if (match_ext(p->filename, "ts"))
1253 return AVPROBE_SCORE_MAX;
1259 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1260 (-1) if not available */
1261 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1262 const uint8_t *packet)
1264 int afc, len, flags;
1268 afc = (packet[3] >> 4) & 3;
1278 if (!(flags & 0x10))
1283 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1284 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1288 static int mpegts_read_header(AVFormatContext *s,
1289 AVFormatParameters *ap)
1291 MpegTSContext *ts = s->priv_data;
1292 ByteIOContext *pb = s->pb;
1293 uint8_t buf[5*1024];
1298 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1299 if(ap->mpeg2ts_raw){
1300 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1305 /* read the first 1024 bytes to get packet size */
1306 pos = url_ftell(pb);
1307 len = get_buffer(pb, buf, sizeof(buf));
1308 if (len != sizeof(buf))
1310 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1311 if (ts->raw_packet_size <= 0)
1316 if (s->iformat == &mpegts_demuxer) {
1319 /* first do a scaning to get all the services */
1320 url_fseek(pb, pos, SEEK_SET);
1322 mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
1324 mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
1326 handle_packets(ts, s->probesize);
1327 /* if could not find service, enable auto_guess */
1331 dprintf(ts->stream, "tuning done\n");
1333 s->ctx_flags |= AVFMTCTX_NOHEADER;
1336 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1337 int64_t pcrs[2], pcr_h;
1338 int packet_count[2];
1339 uint8_t packet[TS_PACKET_SIZE];
1341 /* only read packets */
1343 st = av_new_stream(s, 0);
1346 av_set_pts_info(st, 60, 1, 27000000);
1347 st->codec->codec_type = CODEC_TYPE_DATA;
1348 st->codec->codec_id = CODEC_ID_MPEG2TS;
1350 /* we iterate until we find two PCRs to estimate the bitrate */
1355 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1358 pid = AV_RB16(packet + 1) & 0x1fff;
1359 if ((pcr_pid == -1 || pcr_pid == pid) &&
1360 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1362 packet_count[nb_pcrs] = nb_packets;
1363 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1371 /* NOTE1: the bitrate is computed without the FEC */
1372 /* NOTE2: it is only the bitrate of the start of the stream */
1373 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1374 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1375 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1376 st->codec->bit_rate = s->bit_rate;
1377 st->start_time = ts->cur_pcr;
1379 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1380 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1384 url_fseek(pb, pos, SEEK_SET);
1390 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1392 static int mpegts_raw_read_packet(AVFormatContext *s,
1395 MpegTSContext *ts = s->priv_data;
1397 int64_t pcr_h, next_pcr_h, pos;
1398 int pcr_l, next_pcr_l;
1399 uint8_t pcr_buf[12];
1401 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1402 return AVERROR(ENOMEM);
1403 pkt->pos= url_ftell(s->pb);
1404 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1406 av_free_packet(pkt);
1409 if (ts->mpeg2ts_compute_pcr) {
1410 /* compute exact PCR for each packet */
1411 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1412 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1413 pos = url_ftell(s->pb);
1414 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1415 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1416 get_buffer(s->pb, pcr_buf, 12);
1417 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1418 /* XXX: not precise enough */
1419 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1424 url_fseek(s->pb, pos, SEEK_SET);
1425 /* no next PCR found: we use previous increment */
1426 ts->cur_pcr = pcr_h * 300 + pcr_l;
1428 pkt->pts = ts->cur_pcr;
1429 pkt->duration = ts->pcr_incr;
1430 ts->cur_pcr += ts->pcr_incr;
1432 pkt->stream_index = 0;
1436 static int mpegts_read_packet(AVFormatContext *s,
1439 MpegTSContext *ts = s->priv_data;
1442 if (url_ftell(s->pb) != ts->last_pos) {
1443 /* seek detected, flush pes buffer */
1444 for (i = 0; i < NB_PID_MAX; i++) {
1445 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1446 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1447 av_freep(&pes->buffer);
1448 pes->data_index = 0;
1449 pes->state = MPEGTS_SKIP; /* skip until pes header */
1455 ret = handle_packets(ts, 0);
1457 /* flush pes data left */
1458 for (i = 0; i < NB_PID_MAX; i++) {
1459 if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
1460 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
1461 if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
1462 new_pes_packet(pes, pkt);
1470 ts->last_pos = url_ftell(s->pb);
1475 static int mpegts_read_close(AVFormatContext *s)
1477 MpegTSContext *ts = s->priv_data;
1482 for(i=0;i<NB_PID_MAX;i++)
1483 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1488 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1489 int64_t *ppos, int64_t pos_limit)
1491 MpegTSContext *ts = s->priv_data;
1492 int64_t pos, timestamp;
1493 uint8_t buf[TS_PACKET_SIZE];
1494 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1495 const int find_next= 1;
1496 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1499 url_fseek(s->pb, pos, SEEK_SET);
1500 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1501 return AV_NOPTS_VALUE;
1502 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1503 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1506 pos += ts->raw_packet_size;
1510 pos -= ts->raw_packet_size;
1512 return AV_NOPTS_VALUE;
1513 url_fseek(s->pb, pos, SEEK_SET);
1514 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1515 return AV_NOPTS_VALUE;
1516 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1517 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1527 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags);
1529 static int read_seek2(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t target_ts, int64_t max_ts, int flags)
1533 int64_t ts_ret, ts_adj;
1534 int stream_index_gen_search;
1536 AVParserState *backup;
1538 backup = ff_store_parser_state(s);
1540 // detect direction of seeking for search purposes
1541 flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ? AVSEEK_FLAG_BACKWARD : 0;
1543 if (flags & AVSEEK_FLAG_BYTE) {
1544 /* use position directly, we will search starting from it */
1547 /* search for some position with good timestamp match */
1548 if(stream_index < 0){
1549 stream_index_gen_search = av_find_default_stream_index(s);
1550 if (stream_index_gen_search < 0) {
1551 ff_restore_parser_state(s, backup);
1555 st = s->streams[stream_index_gen_search];
1556 /* timestamp for default must be expressed in AV_TIME_BASE units */
1557 ts_adj = av_rescale(target_ts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1560 stream_index_gen_search = stream_index;
1562 pos = av_gen_search(s, stream_index_gen_search, ts_adj,
1566 flags, &ts_ret, mpegts_get_pcr);
1568 ff_restore_parser_state(s, backup);
1573 /* search for actual matching keyframe/starting position for all streams */
1574 if (ff_gen_syncpoint_search(s, stream_index, pos, min_ts, target_ts, max_ts, flags) < 0) {
1575 ff_restore_parser_state(s, backup);
1579 ff_free_parser_state(s, backup);
1583 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1586 if (flags & AVSEEK_FLAG_BACKWARD) {
1587 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1589 // for compatibility reasons, seek to best-fitting timestamp
1590 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags & ~AVSEEK_FLAG_BACKWARD);
1593 ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
1595 // for compatibility reasons, seek to best-fitting timestamp
1596 ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
1602 /**************************************************************/
1603 /* parsing functions - called from other demuxers such as RTP */
1605 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1609 ts = av_mallocz(sizeof(MpegTSContext));
1612 /* no stream case, currently used by RTP */
1613 ts->raw_packet_size = TS_PACKET_SIZE;
1619 /* return the consumed length if a packet was output, or -1 if no
1621 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1622 const uint8_t *buf, int len)
1630 if (ts->stop_parse>0)
1632 if (len < TS_PACKET_SIZE)
1634 if (buf[0] != 0x47) {
1638 handle_packet(ts, buf);
1639 buf += TS_PACKET_SIZE;
1640 len -= TS_PACKET_SIZE;
1646 void mpegts_parse_close(MpegTSContext *ts)
1650 for(i=0;i<NB_PID_MAX;i++)
1651 av_free(ts->pids[i]);
1655 AVInputFormat mpegts_demuxer = {
1657 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1658 sizeof(MpegTSContext),
1665 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1666 .read_seek2 = read_seek2,
1669 AVInputFormat mpegtsraw_demuxer = {
1671 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1672 sizeof(MpegTSContext),
1675 mpegts_raw_read_packet,
1679 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1680 .read_seek2 = read_seek2,