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
28 /* 1.0 second at 24Mbit/s */
29 #define MAX_SCAN_PACKETS 32000
31 /* maximum size in which we look for synchronisation if
32 synchronisation is lost */
33 #define MAX_RESYNC_SIZE 4096
35 typedef struct PESContext PESContext;
37 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
38 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
39 extern void av_set_program_name(AVProgram *program, char *provider_name, char *name);
40 extern void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx);
42 enum MpegTSFilterType {
47 typedef struct MpegTSFilter MpegTSFilter;
49 typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start);
51 typedef struct MpegTSPESFilter {
56 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
58 typedef void SetServiceCallback(void *opaque, int ret);
60 typedef struct MpegTSSectionFilter {
65 int end_of_section_reached:1;
66 SectionCallback *section_cb;
68 } MpegTSSectionFilter;
72 int last_cc; /* last cc code (-1 if first packet) */
73 enum MpegTSFilterType type;
75 MpegTSPESFilter pes_filter;
76 MpegTSSectionFilter section_filter;
80 #define MAX_PIDS_PER_PROGRAM 64
82 unsigned int id; //program id/service id
84 unsigned int pids[MAX_PIDS_PER_PROGRAM];
87 struct MpegTSContext {
89 AVFormatContext *stream;
90 /** raw packet size, including FEC if present */
92 /** if true, all pids are analyzed to find streams */
95 /** compute exact PCR for each transport stream packet */
96 int mpeg2ts_compute_pcr;
98 int64_t cur_pcr; /**< used to estimate the exact PCR */
99 int pcr_incr; /**< used to estimate the exact PCR */
101 /* data needed to handle file based ts */
102 /** stop parsing loop */
104 /** packet containing Audio/Video data */
107 /******************************************/
108 /* private mpegts data */
110 /** structure to keep track of Program->pids mapping */
115 /** filters for various streams specified by PMT + for the PAT and PMT */
116 MpegTSFilter *pids[NB_PID_MAX];
119 /* TS stream handling */
123 MPEGTS_PESHEADER_FILL,
128 /* enough for PES header + length */
129 #define PES_START_SIZE 9
130 #define MAX_PES_HEADER_SIZE (9 + 255)
134 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
137 AVFormatContext *stream;
139 enum MpegTSState state;
140 /* used to get the format */
145 uint8_t header[MAX_PES_HEADER_SIZE];
148 extern AVInputFormat mpegts_demuxer;
150 static void clear_program(MpegTSContext *ts, unsigned int programid)
154 for(i=0; i<ts->nb_prg; i++)
155 if(ts->prg[i].id == programid)
156 ts->prg[i].nb_pids = 0;
159 static void clear_programs(MpegTSContext *ts)
165 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
168 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(Program_t));
172 p = &ts->prg[ts->nb_prg];
178 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
182 for(i=0; i<ts->nb_prg; i++) {
183 if(ts->prg[i].id == programid) {
191 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
193 p->pids[p->nb_pids++] = pid;
197 * \brief discard_pid() decides if the pid is to be discarded according
198 * to caller's programs selection
199 * \param ts : - TS context
201 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
204 static int discard_pid(MpegTSContext *ts, unsigned int pid)
207 int used = 0, discarded = 0;
209 for(i=0; i<ts->nb_prg; i++) {
211 for(j=0; j<p->nb_pids; j++) {
212 if(p->pids[j] != pid)
214 //is program with id p->id set to be discarded?
215 for(k=0; k<ts->stream->nb_programs; k++) {
216 if(ts->stream->programs[k]->id == p->id) {
217 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
226 return (!used && discarded);
230 * Assembles PES packets out of TS packets, and then calls the "section_cb"
231 * function when they are complete.
233 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
234 const uint8_t *buf, int buf_size, int is_start)
236 MpegTSSectionFilter *tss = &tss1->u.section_filter;
240 memcpy(tss->section_buf, buf, buf_size);
241 tss->section_index = buf_size;
242 tss->section_h_size = -1;
243 tss->end_of_section_reached = 0;
245 if (tss->end_of_section_reached)
247 len = 4096 - tss->section_index;
250 memcpy(tss->section_buf + tss->section_index, buf, len);
251 tss->section_index += len;
254 /* compute section length if possible */
255 if (tss->section_h_size == -1 && tss->section_index >= 3) {
256 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
259 tss->section_h_size = len;
262 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
263 tss->end_of_section_reached = 1;
264 if (!tss->check_crc ||
265 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
266 tss->section_buf, tss->section_h_size) == 0)
267 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
271 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
272 SectionCallback *section_cb, void *opaque,
276 MpegTSFilter *filter;
277 MpegTSSectionFilter *sec;
280 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
282 if (pid >= NB_PID_MAX || ts->pids[pid])
284 filter = av_mallocz(sizeof(MpegTSFilter));
287 ts->pids[pid] = filter;
288 filter->type = MPEGTS_SECTION;
290 filter->last_cc = -1;
291 sec = &filter->u.section_filter;
292 sec->section_cb = section_cb;
293 sec->opaque = opaque;
294 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
295 sec->check_crc = check_crc;
296 if (!sec->section_buf) {
303 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
307 MpegTSFilter *filter;
308 MpegTSPESFilter *pes;
310 if (pid >= NB_PID_MAX || ts->pids[pid])
312 filter = av_mallocz(sizeof(MpegTSFilter));
315 ts->pids[pid] = filter;
316 filter->type = MPEGTS_PES;
318 filter->last_cc = -1;
319 pes = &filter->u.pes_filter;
320 pes->pes_cb = pes_cb;
321 pes->opaque = opaque;
325 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
330 if (filter->type == MPEGTS_SECTION)
331 av_freep(&filter->u.section_filter.section_buf);
332 else if (filter->type == MPEGTS_PES)
333 av_freep(&filter->u.pes_filter.opaque);
336 ts->pids[pid] = NULL;
339 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
340 int stat[packet_size];
345 memset(stat, 0, packet_size*sizeof(int));
347 for(x=i=0; i<size; i++){
350 if(stat[x] > best_score){
357 if(x == packet_size) x= 0;
363 /* autodetect fec presence. Must have at least 1024 bytes */
364 static int get_packet_size(const uint8_t *buf, int size)
366 int score, fec_score, dvhs_score;
368 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
371 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
372 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
373 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
374 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
376 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
377 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
378 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
382 typedef struct SectionHeader {
387 uint8_t last_sec_num;
390 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
403 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
409 if ((p + 1) >= p_end)
417 /* read and allocate a DVB string preceeded by its length */
418 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
425 len = get8(&p, p_end);
428 if ((p + len) > p_end)
430 str = av_malloc(len + 1);
440 static int parse_section_header(SectionHeader *h,
441 const uint8_t **pp, const uint8_t *p_end)
445 val = get8(pp, p_end);
450 val = get16(pp, p_end);
454 val = get8(pp, p_end);
457 h->version = (val >> 1) & 0x1f;
458 val = get8(pp, p_end);
462 val = get8(pp, p_end);
465 h->last_sec_num = val;
470 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
472 MpegTSContext *ts = filter->u.section_filter.opaque;
473 SectionHeader h1, *h = &h1;
476 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
477 int program_info_length, pcr_pid, pid, stream_type;
478 int desc_list_len, desc_len, desc_tag;
479 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
480 char language[4] = {0}; /* initialize to kill warnings */
483 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
484 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
486 p_end = section + section_len - 4;
488 if (parse_section_header(h, &p, p_end) < 0)
491 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
492 h->id, h->sec_num, h->last_sec_num);
494 if (h->tid != PMT_TID)
497 clear_program(ts, h->id);
498 pcr_pid = get16(&p, p_end) & 0x1fff;
501 add_pid_to_pmt(ts, h->id, pcr_pid);
503 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
505 program_info_length = get16(&p, p_end) & 0xfff;
506 if (program_info_length < 0)
508 p += program_info_length;
514 stream_type = get8(&p, p_end);
517 pid = get16(&p, p_end) & 0x1fff;
520 desc_list_len = get16(&p, p_end) & 0xfff;
521 if (desc_list_len < 0)
523 desc_list_end = p + desc_list_len;
524 if (desc_list_end > p_end)
527 desc_tag = get8(&p, desc_list_end);
530 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
531 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
532 /*assume DVB AC-3 Audio*/
533 stream_type = STREAM_TYPE_AUDIO_AC3;
534 } else if(desc_tag == 0x7B) {
536 stream_type = STREAM_TYPE_AUDIO_DTS;
539 desc_len = get8(&p, desc_list_end);
540 desc_end = p + desc_len;
541 if (desc_end > desc_list_end)
544 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
548 case DVB_SUBT_DESCID:
549 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
550 stream_type = STREAM_TYPE_SUBTITLE_DVB;
552 language[0] = get8(&p, desc_end);
553 language[1] = get8(&p, desc_end);
554 language[2] = get8(&p, desc_end);
557 comp_page = get16(&p, desc_end);
558 anc_page = get16(&p, desc_end);
561 case 0x0a: /* ISO 639 language descriptor */
562 language[0] = get8(&p, desc_end);
563 language[1] = get8(&p, desc_end);
564 language[2] = get8(&p, desc_end);
575 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
579 /* now create ffmpeg stream */
580 switch(stream_type) {
581 case STREAM_TYPE_AUDIO_MPEG1:
582 case STREAM_TYPE_AUDIO_MPEG2:
583 case STREAM_TYPE_VIDEO_MPEG1:
584 case STREAM_TYPE_VIDEO_MPEG2:
585 case STREAM_TYPE_VIDEO_MPEG4:
586 case STREAM_TYPE_VIDEO_H264:
587 case STREAM_TYPE_VIDEO_VC1:
588 case STREAM_TYPE_AUDIO_AAC:
589 case STREAM_TYPE_AUDIO_AC3:
590 case STREAM_TYPE_AUDIO_DTS:
591 case STREAM_TYPE_SUBTITLE_DVB:
592 if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
593 pes= ts->pids[pid]->u.pes_filter.opaque;
596 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
597 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
599 st = new_pes_av_stream(pes, 0);
601 add_pid_to_pmt(ts, h->id, pid);
603 av_program_add_stream_index(ts->stream, h->id, st->index);
606 /* we ignore the other streams */
611 if (language[0] != 0) {
612 memcpy(st->language, language, 4);
615 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
616 st->codec->sub_id = (anc_page << 16) | comp_page;
620 /* all parameters are there */
622 mpegts_close_filter(ts, filter);
625 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
627 MpegTSContext *ts = filter->u.section_filter.opaque;
628 SectionHeader h1, *h = &h1;
629 const uint8_t *p, *p_end;
633 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
634 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
636 p_end = section + section_len - 4;
638 if (parse_section_header(h, &p, p_end) < 0)
640 if (h->tid != PAT_TID)
645 sid = get16(&p, p_end);
648 pmt_pid = get16(&p, p_end) & 0x1fff;
652 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
657 av_new_program(ts->stream, sid);
659 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
660 add_pat_entry(ts, sid);
661 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
662 add_pid_to_pmt(ts, sid, pmt_pid);
668 mpegts_close_filter(ts, filter);
671 static void mpegts_set_service(MpegTSContext *ts)
673 mpegts_open_section_filter(ts, PAT_PID,
677 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
679 MpegTSContext *ts = filter->u.section_filter.opaque;
680 SectionHeader h1, *h = &h1;
681 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
682 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
683 char *name, *provider_name;
686 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
687 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
690 p_end = section + section_len - 4;
692 if (parse_section_header(h, &p, p_end) < 0)
694 if (h->tid != SDT_TID)
696 onid = get16(&p, p_end);
699 val = get8(&p, p_end);
703 sid = get16(&p, p_end);
706 val = get8(&p, p_end);
709 desc_list_len = get16(&p, p_end) & 0xfff;
710 if (desc_list_len < 0)
712 desc_list_end = p + desc_list_len;
713 if (desc_list_end > p_end)
716 desc_tag = get8(&p, desc_list_end);
719 desc_len = get8(&p, desc_list_end);
720 desc_end = p + desc_len;
721 if (desc_end > desc_list_end)
724 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
729 service_type = get8(&p, p_end);
730 if (service_type < 0)
732 provider_name = getstr8(&p, p_end);
735 name = getstr8(&p, p_end);
737 AVProgram *program = av_new_program(ts->stream, sid);
739 av_set_program_name(program, provider_name, name);
751 /* scan services in a transport stream by looking at the SDT */
752 static void mpegts_scan_sdt(MpegTSContext *ts)
754 mpegts_open_section_filter(ts, SDT_PID,
758 static int64_t get_pts(const uint8_t *p)
760 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
761 pts |= (AV_RB16(p + 1) >> 1) << 15;
762 pts |= AV_RB16(p + 3) >> 1;
766 /* return non zero if a packet could be constructed */
767 static void mpegts_push_data(MpegTSFilter *filter,
768 const uint8_t *buf, int buf_size, int is_start)
770 PESContext *pes = filter->u.pes_filter.opaque;
771 MpegTSContext *ts = pes->ts;
779 pes->state = MPEGTS_HEADER;
783 while (buf_size > 0) {
786 len = PES_START_SIZE - pes->data_index;
789 memcpy(pes->header + pes->data_index, p, len);
790 pes->data_index += len;
793 if (pes->data_index == PES_START_SIZE) {
794 /* we got all the PES or section header. We can now
797 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
799 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
800 pes->header[2] == 0x01) {
801 /* it must be an mpeg2 PES stream */
802 code = pes->header[3] | 0x100;
803 if (!((code >= 0x1c0 && code <= 0x1df) ||
804 (code >= 0x1e0 && code <= 0x1ef) ||
805 (code == 0x1bd) || (code == 0x1fd)))
808 /* allocate stream */
809 new_pes_av_stream(pes, code);
811 pes->state = MPEGTS_PESHEADER_FILL;
812 pes->total_size = AV_RB16(pes->header + 4);
813 /* NOTE: a zero total size means the PES size is
816 pes->total_size += 6;
817 pes->pes_header_size = pes->header[8] + 9;
819 /* otherwise, it should be a table */
822 pes->state = MPEGTS_SKIP;
827 /**********************************************/
828 /* PES packing parsing */
829 case MPEGTS_PESHEADER_FILL:
830 len = pes->pes_header_size - pes->data_index;
833 memcpy(pes->header + pes->data_index, p, len);
834 pes->data_index += len;
837 if (pes->data_index == pes->pes_header_size) {
841 flags = pes->header[7];
843 pes->pts = AV_NOPTS_VALUE;
844 pes->dts = AV_NOPTS_VALUE;
845 if ((flags & 0xc0) == 0x80) {
846 pes->pts = get_pts(r);
848 } else if ((flags & 0xc0) == 0xc0) {
849 pes->pts = get_pts(r);
851 pes->dts = get_pts(r);
854 /* we got the full header. We parse it and get the payload */
855 pes->state = MPEGTS_PAYLOAD;
859 if (pes->total_size) {
860 len = pes->total_size - pes->data_index;
867 AVPacket *pkt = ts->pkt;
868 if (pes->st && av_new_packet(pkt, len) == 0) {
869 memcpy(pkt->data, p, len);
870 pkt->stream_index = pes->st->index;
873 /* reset pts values */
874 pes->pts = AV_NOPTS_VALUE;
875 pes->dts = AV_NOPTS_VALUE;
889 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
892 int codec_type, codec_id;
894 switch(pes->stream_type){
895 case STREAM_TYPE_AUDIO_MPEG1:
896 case STREAM_TYPE_AUDIO_MPEG2:
897 codec_type = CODEC_TYPE_AUDIO;
898 codec_id = CODEC_ID_MP3;
900 case STREAM_TYPE_VIDEO_MPEG1:
901 case STREAM_TYPE_VIDEO_MPEG2:
902 codec_type = CODEC_TYPE_VIDEO;
903 codec_id = CODEC_ID_MPEG2VIDEO;
905 case STREAM_TYPE_VIDEO_MPEG4:
906 codec_type = CODEC_TYPE_VIDEO;
907 codec_id = CODEC_ID_MPEG4;
909 case STREAM_TYPE_VIDEO_H264:
910 codec_type = CODEC_TYPE_VIDEO;
911 codec_id = CODEC_ID_H264;
913 case STREAM_TYPE_VIDEO_VC1:
914 codec_type = CODEC_TYPE_VIDEO;
915 codec_id = CODEC_ID_VC1;
917 case STREAM_TYPE_AUDIO_AAC:
918 codec_type = CODEC_TYPE_AUDIO;
919 codec_id = CODEC_ID_AAC;
921 case STREAM_TYPE_AUDIO_AC3:
922 codec_type = CODEC_TYPE_AUDIO;
923 codec_id = CODEC_ID_AC3;
925 case STREAM_TYPE_AUDIO_DTS:
926 codec_type = CODEC_TYPE_AUDIO;
927 codec_id = CODEC_ID_DTS;
929 case STREAM_TYPE_SUBTITLE_DVB:
930 codec_type = CODEC_TYPE_SUBTITLE;
931 codec_id = CODEC_ID_DVB_SUBTITLE;
934 if (code >= 0x1c0 && code <= 0x1df) {
935 codec_type = CODEC_TYPE_AUDIO;
936 codec_id = CODEC_ID_MP2;
937 } else if (code == 0x1bd) {
938 codec_type = CODEC_TYPE_AUDIO;
939 codec_id = CODEC_ID_AC3;
941 codec_type = CODEC_TYPE_VIDEO;
942 codec_id = CODEC_ID_MPEG1VIDEO;
946 st = av_new_stream(pes->stream, pes->pid);
948 av_set_pts_info(st, 33, 1, 90000);
950 st->codec->codec_type = codec_type;
951 st->codec->codec_id = codec_id;
952 st->need_parsing = AVSTREAM_PARSE_FULL;
959 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
964 /* if no pid found, then add a pid context */
965 pes = av_mallocz(sizeof(PESContext));
969 pes->stream = ts->stream;
971 pes->pcr_pid = pcr_pid;
972 pes->stream_type = stream_type;
973 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
981 /* handle one TS packet */
982 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
984 AVFormatContext *s = ts->stream;
986 int len, pid, cc, cc_ok, afc, is_start;
987 const uint8_t *p, *p_end;
989 pid = AV_RB16(packet + 1) & 0x1fff;
990 if(pid && discard_pid(ts, pid))
992 is_start = packet[1] & 0x40;
994 if (ts->auto_guess && tss == NULL && is_start) {
995 add_pes_stream(ts, pid, -1, 0);
1001 /* continuity check (currently not used) */
1002 cc = (packet[3] & 0xf);
1003 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1006 /* skip adaptation field */
1007 afc = (packet[3] >> 4) & 3;
1009 if (afc == 0) /* reserved value */
1011 if (afc == 2) /* adaptation field only */
1014 /* skip adapation field */
1017 /* if past the end of packet, ignore */
1018 p_end = packet + TS_PACKET_SIZE;
1022 if (tss->type == MPEGTS_SECTION) {
1024 /* pointer field present */
1026 if (p + len > p_end)
1029 /* write remaining section bytes */
1030 write_section_data(s, tss,
1032 /* check whether filter has been closed */
1038 write_section_data(s, tss,
1043 write_section_data(s, tss,
1048 tss->u.pes_filter.pes_cb(tss,
1049 p, p_end - p, is_start);
1053 /* XXX: try to find a better synchro over several packets (use
1054 get_packet_size() ?) */
1055 static int mpegts_resync(ByteIOContext *pb)
1059 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1064 url_fseek(pb, -1, SEEK_CUR);
1072 /* return -1 if error or EOF. Return 0 if OK. */
1073 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1078 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1079 if (len != TS_PACKET_SIZE)
1080 return AVERROR(EIO);
1081 /* check paquet sync byte */
1082 if (buf[0] != 0x47) {
1083 /* find a new packet start */
1084 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1085 if (mpegts_resync(pb) < 0)
1086 return AVERROR_INVALIDDATA;
1090 skip = raw_packet_size - TS_PACKET_SIZE;
1092 url_fskip(pb, skip);
1099 static int handle_packets(MpegTSContext *ts, int nb_packets)
1101 AVFormatContext *s = ts->stream;
1102 ByteIOContext *pb = s->pb;
1103 uint8_t packet[TS_PACKET_SIZE];
1104 int packet_num, ret;
1109 if (ts->stop_parse>0)
1112 if (nb_packets != 0 && packet_num >= nb_packets)
1114 ret = read_packet(pb, packet, ts->raw_packet_size);
1117 handle_packet(ts, packet);
1122 static int mpegts_probe(AVProbeData *p)
1125 const int size= p->buf_size;
1126 int score, fec_score, dvhs_score;
1127 #define CHECK_COUNT 10
1129 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1132 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1133 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1134 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1135 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1137 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1138 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1139 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1140 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1143 /* only use the extension for safer guess */
1144 if (match_ext(p->filename, "ts"))
1145 return AVPROBE_SCORE_MAX;
1151 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1152 (-1) if not available */
1153 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1154 const uint8_t *packet)
1156 int afc, len, flags;
1160 afc = (packet[3] >> 4) & 3;
1170 if (!(flags & 0x10))
1175 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1176 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1180 static int mpegts_read_header(AVFormatContext *s,
1181 AVFormatParameters *ap)
1183 MpegTSContext *ts = s->priv_data;
1184 ByteIOContext *pb = s->pb;
1190 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1191 if(ap->mpeg2ts_raw){
1192 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1197 /* read the first 1024 bytes to get packet size */
1198 pos = url_ftell(pb);
1199 len = get_buffer(pb, buf, sizeof(buf));
1200 if (len != sizeof(buf))
1202 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1203 if (ts->raw_packet_size <= 0)
1208 if (s->iformat == &mpegts_demuxer) {
1211 /* first do a scaning to get all the services */
1212 url_fseek(pb, pos, SEEK_SET);
1213 mpegts_scan_sdt(ts);
1215 mpegts_set_service(ts);
1217 handle_packets(ts, s->probesize);
1218 /* if could not find service, enable auto_guess */
1223 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1225 s->ctx_flags |= AVFMTCTX_NOHEADER;
1228 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1229 int64_t pcrs[2], pcr_h;
1230 int packet_count[2];
1231 uint8_t packet[TS_PACKET_SIZE];
1233 /* only read packets */
1235 st = av_new_stream(s, 0);
1238 av_set_pts_info(st, 60, 1, 27000000);
1239 st->codec->codec_type = CODEC_TYPE_DATA;
1240 st->codec->codec_id = CODEC_ID_MPEG2TS;
1242 /* we iterate until we find two PCRs to estimate the bitrate */
1247 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1250 pid = AV_RB16(packet + 1) & 0x1fff;
1251 if ((pcr_pid == -1 || pcr_pid == pid) &&
1252 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1254 packet_count[nb_pcrs] = nb_packets;
1255 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1263 /* NOTE1: the bitrate is computed without the FEC */
1264 /* NOTE2: it is only the bitrate of the start of the stream */
1265 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1266 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1267 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1268 st->codec->bit_rate = s->bit_rate;
1269 st->start_time = ts->cur_pcr;
1271 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1272 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1276 url_fseek(pb, pos, SEEK_SET);
1282 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1284 static int mpegts_raw_read_packet(AVFormatContext *s,
1287 MpegTSContext *ts = s->priv_data;
1289 int64_t pcr_h, next_pcr_h, pos;
1290 int pcr_l, next_pcr_l;
1291 uint8_t pcr_buf[12];
1293 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1294 return AVERROR(ENOMEM);
1295 pkt->pos= url_ftell(s->pb);
1296 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1298 av_free_packet(pkt);
1301 if (ts->mpeg2ts_compute_pcr) {
1302 /* compute exact PCR for each packet */
1303 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1304 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1305 pos = url_ftell(s->pb);
1306 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1307 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1308 get_buffer(s->pb, pcr_buf, 12);
1309 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1310 /* XXX: not precise enough */
1311 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1316 url_fseek(s->pb, pos, SEEK_SET);
1317 /* no next PCR found: we use previous increment */
1318 ts->cur_pcr = pcr_h * 300 + pcr_l;
1320 pkt->pts = ts->cur_pcr;
1321 pkt->duration = ts->pcr_incr;
1322 ts->cur_pcr += ts->pcr_incr;
1324 pkt->stream_index = 0;
1328 static int mpegts_read_packet(AVFormatContext *s,
1331 MpegTSContext *ts = s->priv_data;
1334 return handle_packets(ts, 0);
1337 static int mpegts_read_close(AVFormatContext *s)
1339 MpegTSContext *ts = s->priv_data;
1341 for(i=0;i<NB_PID_MAX;i++)
1342 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1347 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1348 int64_t *ppos, int64_t pos_limit)
1350 MpegTSContext *ts = s->priv_data;
1351 int64_t pos, timestamp;
1352 uint8_t buf[TS_PACKET_SIZE];
1353 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1354 const int find_next= 1;
1355 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1358 url_fseek(s->pb, pos, SEEK_SET);
1359 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1360 return AV_NOPTS_VALUE;
1361 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1362 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1365 pos += ts->raw_packet_size;
1369 pos -= ts->raw_packet_size;
1371 return AV_NOPTS_VALUE;
1372 url_fseek(s->pb, pos, SEEK_SET);
1373 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1374 return AV_NOPTS_VALUE;
1375 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1376 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1386 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1387 MpegTSContext *ts = s->priv_data;
1388 uint8_t buf[TS_PACKET_SIZE];
1391 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1394 pos= url_ftell(s->pb);
1397 url_fseek(s->pb, pos, SEEK_SET);
1398 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1400 // pid = AV_RB16(buf + 1) & 0x1fff;
1401 if(buf[1] & 0x40) break;
1402 pos += ts->raw_packet_size;
1404 url_fseek(s->pb, pos, SEEK_SET);
1409 /**************************************************************/
1410 /* parsing functions - called from other demuxers such as RTP */
1412 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1416 ts = av_mallocz(sizeof(MpegTSContext));
1419 /* no stream case, currently used by RTP */
1420 ts->raw_packet_size = TS_PACKET_SIZE;
1426 /* return the consumed length if a packet was output, or -1 if no
1428 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1429 const uint8_t *buf, int len)
1437 if (ts->stop_parse>0)
1439 if (len < TS_PACKET_SIZE)
1441 if (buf[0] != 0x47) {
1445 handle_packet(ts, buf);
1446 buf += TS_PACKET_SIZE;
1447 len -= TS_PACKET_SIZE;
1453 void mpegts_parse_close(MpegTSContext *ts)
1457 for(i=0;i<NB_PID_MAX;i++)
1458 av_free(ts->pids[i]);
1462 AVInputFormat mpegts_demuxer = {
1464 "MPEG2 transport stream format",
1465 sizeof(MpegTSContext),
1472 .flags = AVFMT_SHOW_IDS,
1475 AVInputFormat mpegtsraw_demuxer = {
1477 "MPEG2 raw transport stream format",
1478 sizeof(MpegTSContext),
1481 mpegts_raw_read_packet,
1485 .flags = AVFMT_SHOW_IDS,