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
34 #define REGISTRATION_DESCRIPTOR 5
36 typedef struct PESContext PESContext;
38 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
39 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
40 extern void av_set_program_name(AVProgram *program, char *provider_name, char *name);
41 extern void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx);
43 enum MpegTSFilterType {
48 typedef struct MpegTSFilter MpegTSFilter;
50 typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start);
52 typedef struct MpegTSPESFilter {
57 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
59 typedef void SetServiceCallback(void *opaque, int ret);
61 typedef struct MpegTSSectionFilter {
66 int end_of_section_reached:1;
67 SectionCallback *section_cb;
69 } MpegTSSectionFilter;
73 int last_cc; /* last cc code (-1 if first packet) */
74 enum MpegTSFilterType type;
76 MpegTSPESFilter pes_filter;
77 MpegTSSectionFilter section_filter;
81 #define MAX_PIDS_PER_PROGRAM 64
83 unsigned int id; //program id/service id
85 unsigned int pids[MAX_PIDS_PER_PROGRAM];
88 struct MpegTSContext {
90 AVFormatContext *stream;
91 /** raw packet size, including FEC if present */
93 /** if true, all pids are analyzed to find streams */
96 /** compute exact PCR for each transport stream packet */
97 int mpeg2ts_compute_pcr;
99 int64_t cur_pcr; /**< used to estimate the exact PCR */
100 int pcr_incr; /**< used to estimate the exact PCR */
102 /* data needed to handle file based ts */
103 /** stop parsing loop */
105 /** packet containing Audio/Video data */
108 /******************************************/
109 /* private mpegts data */
111 /** structure to keep track of Program->pids mapping */
116 /** filters for various streams specified by PMT + for the PAT and PMT */
117 MpegTSFilter *pids[NB_PID_MAX];
120 /* TS stream handling */
124 MPEGTS_PESHEADER_FILL,
129 /* enough for PES header + length */
130 #define PES_START_SIZE 9
131 #define MAX_PES_HEADER_SIZE (9 + 255)
135 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
138 AVFormatContext *stream;
140 enum MpegTSState state;
141 /* used to get the format */
146 uint8_t header[MAX_PES_HEADER_SIZE];
149 extern AVInputFormat mpegts_demuxer;
151 static void clear_program(MpegTSContext *ts, unsigned int programid)
155 for(i=0; i<ts->nb_prg; i++)
156 if(ts->prg[i].id == programid)
157 ts->prg[i].nb_pids = 0;
160 static void clear_programs(MpegTSContext *ts)
166 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
169 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(Program_t));
173 p = &ts->prg[ts->nb_prg];
179 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
183 for(i=0; i<ts->nb_prg; i++) {
184 if(ts->prg[i].id == programid) {
192 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
194 p->pids[p->nb_pids++] = pid;
198 * \brief discard_pid() decides if the pid is to be discarded according
199 * to caller's programs selection
200 * \param ts : - TS context
202 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
205 static int discard_pid(MpegTSContext *ts, unsigned int pid)
208 int used = 0, discarded = 0;
210 for(i=0; i<ts->nb_prg; i++) {
212 for(j=0; j<p->nb_pids; j++) {
213 if(p->pids[j] != pid)
215 //is program with id p->id set to be discarded?
216 for(k=0; k<ts->stream->nb_programs; k++) {
217 if(ts->stream->programs[k]->id == p->id) {
218 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
227 return (!used && discarded);
231 * Assembles PES packets out of TS packets, and then calls the "section_cb"
232 * function when they are complete.
234 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
235 const uint8_t *buf, int buf_size, int is_start)
237 MpegTSSectionFilter *tss = &tss1->u.section_filter;
241 memcpy(tss->section_buf, buf, buf_size);
242 tss->section_index = buf_size;
243 tss->section_h_size = -1;
244 tss->end_of_section_reached = 0;
246 if (tss->end_of_section_reached)
248 len = 4096 - tss->section_index;
251 memcpy(tss->section_buf + tss->section_index, buf, len);
252 tss->section_index += len;
255 /* compute section length if possible */
256 if (tss->section_h_size == -1 && tss->section_index >= 3) {
257 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
260 tss->section_h_size = len;
263 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
264 tss->end_of_section_reached = 1;
265 if (!tss->check_crc ||
266 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
267 tss->section_buf, tss->section_h_size) == 0)
268 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
272 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
273 SectionCallback *section_cb, void *opaque,
277 MpegTSFilter *filter;
278 MpegTSSectionFilter *sec;
281 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
283 if (pid >= NB_PID_MAX || ts->pids[pid])
285 filter = av_mallocz(sizeof(MpegTSFilter));
288 ts->pids[pid] = filter;
289 filter->type = MPEGTS_SECTION;
291 filter->last_cc = -1;
292 sec = &filter->u.section_filter;
293 sec->section_cb = section_cb;
294 sec->opaque = opaque;
295 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
296 sec->check_crc = check_crc;
297 if (!sec->section_buf) {
304 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
308 MpegTSFilter *filter;
309 MpegTSPESFilter *pes;
311 if (pid >= NB_PID_MAX || ts->pids[pid])
313 filter = av_mallocz(sizeof(MpegTSFilter));
316 ts->pids[pid] = filter;
317 filter->type = MPEGTS_PES;
319 filter->last_cc = -1;
320 pes = &filter->u.pes_filter;
321 pes->pes_cb = pes_cb;
322 pes->opaque = opaque;
326 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
331 if (filter->type == MPEGTS_SECTION)
332 av_freep(&filter->u.section_filter.section_buf);
333 else if (filter->type == MPEGTS_PES)
334 av_freep(&filter->u.pes_filter.opaque);
337 ts->pids[pid] = NULL;
340 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
341 int stat[packet_size];
346 memset(stat, 0, packet_size*sizeof(int));
348 for(x=i=0; i<size; i++){
351 if(stat[x] > best_score){
358 if(x == packet_size) x= 0;
364 /* autodetect fec presence. Must have at least 1024 bytes */
365 static int get_packet_size(const uint8_t *buf, int size)
367 int score, fec_score, dvhs_score;
369 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
372 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
373 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
374 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
375 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
377 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
378 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
379 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
383 typedef struct SectionHeader {
388 uint8_t last_sec_num;
391 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
404 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
410 if ((p + 1) >= p_end)
418 /* read and allocate a DVB string preceeded by its length */
419 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
426 len = get8(&p, p_end);
429 if ((p + len) > p_end)
431 str = av_malloc(len + 1);
441 static int parse_section_header(SectionHeader *h,
442 const uint8_t **pp, const uint8_t *p_end)
446 val = get8(pp, p_end);
451 val = get16(pp, p_end);
455 val = get8(pp, p_end);
458 h->version = (val >> 1) & 0x1f;
459 val = get8(pp, p_end);
463 val = get8(pp, p_end);
466 h->last_sec_num = val;
471 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
473 MpegTSContext *ts = filter->u.section_filter.opaque;
474 SectionHeader h1, *h = &h1;
477 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
478 int program_info_length, pcr_pid, pid, stream_type;
479 int desc_list_len, desc_len, desc_tag;
480 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
481 char language[4] = {0}; /* initialize to kill warnings */
482 int has_hdmv_descr = 0;
485 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
486 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
488 p_end = section + section_len - 4;
490 if (parse_section_header(h, &p, p_end) < 0)
493 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
494 h->id, h->sec_num, h->last_sec_num);
496 if (h->tid != PMT_TID)
499 clear_program(ts, h->id);
500 pcr_pid = get16(&p, p_end) & 0x1fff;
503 add_pid_to_pmt(ts, h->id, pcr_pid);
505 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
507 program_info_length = get16(&p, p_end) & 0xfff;
508 if (program_info_length < 0)
510 while(program_info_length >= 2) {
512 tag = get8(&p, p_end);
513 len = get8(&p, p_end);
514 if(len > program_info_length - 2)
515 //something else is broken, exit the program_descriptors_loop
517 program_info_length -= len + 2;
518 if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
520 bytes[0] = get8(&p, p_end);
521 bytes[1] = get8(&p, p_end);
522 bytes[2] = get8(&p, p_end);
523 bytes[3] = get8(&p, p_end);
525 if(bytes[0] == 'H' && bytes[1] == 'D' &&
526 bytes[2] == 'M' && bytes[3] == 'V')
531 p += program_info_length;
537 stream_type = get8(&p, p_end);
540 pid = get16(&p, p_end) & 0x1fff;
543 desc_list_len = get16(&p, p_end) & 0xfff;
544 if (desc_list_len < 0)
546 desc_list_end = p + desc_list_len;
547 if (desc_list_end > p_end)
550 desc_tag = get8(&p, desc_list_end);
553 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
554 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
555 /*assume DVB AC-3 Audio*/
556 stream_type = STREAM_TYPE_AUDIO_AC3;
557 } else if(desc_tag == 0x7B) {
559 stream_type = STREAM_TYPE_AUDIO_DTS;
562 desc_len = get8(&p, desc_list_end);
563 desc_end = p + desc_len;
564 if (desc_end > desc_list_end)
567 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
571 case DVB_SUBT_DESCID:
572 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
573 stream_type = STREAM_TYPE_SUBTITLE_DVB;
575 language[0] = get8(&p, desc_end);
576 language[1] = get8(&p, desc_end);
577 language[2] = get8(&p, desc_end);
580 comp_page = get16(&p, desc_end);
581 anc_page = get16(&p, desc_end);
584 case 0x0a: /* ISO 639 language descriptor */
585 language[0] = get8(&p, desc_end);
586 language[1] = get8(&p, desc_end);
587 language[2] = get8(&p, desc_end);
598 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
602 /* now create ffmpeg stream */
603 switch(stream_type) {
604 case STREAM_TYPE_AUDIO_MPEG1:
605 case STREAM_TYPE_AUDIO_MPEG2:
606 case STREAM_TYPE_VIDEO_MPEG1:
607 case STREAM_TYPE_VIDEO_MPEG2:
608 case STREAM_TYPE_VIDEO_MPEG4:
609 case STREAM_TYPE_VIDEO_H264:
610 case STREAM_TYPE_VIDEO_VC1:
611 case STREAM_TYPE_AUDIO_AAC:
612 case STREAM_TYPE_AUDIO_AC3:
613 case STREAM_TYPE_AUDIO_DTS:
614 case STREAM_TYPE_AUDIO_HDMV_DTS:
615 case STREAM_TYPE_SUBTITLE_DVB:
616 if(stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
618 if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
619 pes= ts->pids[pid]->u.pes_filter.opaque;
622 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
623 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
625 st = new_pes_av_stream(pes, 0);
627 add_pid_to_pmt(ts, h->id, pid);
629 av_program_add_stream_index(ts->stream, h->id, st->index);
632 /* we ignore the other streams */
637 if (language[0] != 0) {
638 memcpy(st->language, language, 4);
641 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
642 st->codec->sub_id = (anc_page << 16) | comp_page;
646 /* all parameters are there */
648 mpegts_close_filter(ts, filter);
651 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
653 MpegTSContext *ts = filter->u.section_filter.opaque;
654 SectionHeader h1, *h = &h1;
655 const uint8_t *p, *p_end;
659 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
660 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
662 p_end = section + section_len - 4;
664 if (parse_section_header(h, &p, p_end) < 0)
666 if (h->tid != PAT_TID)
671 sid = get16(&p, p_end);
674 pmt_pid = get16(&p, p_end) & 0x1fff;
678 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
683 av_new_program(ts->stream, sid);
685 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
686 add_pat_entry(ts, sid);
687 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
688 add_pid_to_pmt(ts, sid, pmt_pid);
694 mpegts_close_filter(ts, filter);
697 static void mpegts_set_service(MpegTSContext *ts)
699 mpegts_open_section_filter(ts, PAT_PID,
703 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
705 MpegTSContext *ts = filter->u.section_filter.opaque;
706 SectionHeader h1, *h = &h1;
707 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
708 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
709 char *name, *provider_name;
712 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
713 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
716 p_end = section + section_len - 4;
718 if (parse_section_header(h, &p, p_end) < 0)
720 if (h->tid != SDT_TID)
722 onid = get16(&p, p_end);
725 val = get8(&p, p_end);
729 sid = get16(&p, p_end);
732 val = get8(&p, p_end);
735 desc_list_len = get16(&p, p_end) & 0xfff;
736 if (desc_list_len < 0)
738 desc_list_end = p + desc_list_len;
739 if (desc_list_end > p_end)
742 desc_tag = get8(&p, desc_list_end);
745 desc_len = get8(&p, desc_list_end);
746 desc_end = p + desc_len;
747 if (desc_end > desc_list_end)
750 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
755 service_type = get8(&p, p_end);
756 if (service_type < 0)
758 provider_name = getstr8(&p, p_end);
761 name = getstr8(&p, p_end);
763 AVProgram *program = av_new_program(ts->stream, sid);
765 av_set_program_name(program, provider_name, name);
777 /* scan services in a transport stream by looking at the SDT */
778 static void mpegts_scan_sdt(MpegTSContext *ts)
780 mpegts_open_section_filter(ts, SDT_PID,
784 static int64_t get_pts(const uint8_t *p)
786 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
787 pts |= (AV_RB16(p + 1) >> 1) << 15;
788 pts |= AV_RB16(p + 3) >> 1;
792 /* return non zero if a packet could be constructed */
793 static void mpegts_push_data(MpegTSFilter *filter,
794 const uint8_t *buf, int buf_size, int is_start)
796 PESContext *pes = filter->u.pes_filter.opaque;
797 MpegTSContext *ts = pes->ts;
805 pes->state = MPEGTS_HEADER;
809 while (buf_size > 0) {
812 len = PES_START_SIZE - pes->data_index;
815 memcpy(pes->header + pes->data_index, p, len);
816 pes->data_index += len;
819 if (pes->data_index == PES_START_SIZE) {
820 /* we got all the PES or section header. We can now
823 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
825 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
826 pes->header[2] == 0x01) {
827 /* it must be an mpeg2 PES stream */
828 code = pes->header[3] | 0x100;
829 if (!((code >= 0x1c0 && code <= 0x1df) ||
830 (code >= 0x1e0 && code <= 0x1ef) ||
831 (code == 0x1bd) || (code == 0x1fd)))
834 /* allocate stream */
835 new_pes_av_stream(pes, code);
837 pes->state = MPEGTS_PESHEADER_FILL;
838 pes->total_size = AV_RB16(pes->header + 4);
839 /* NOTE: a zero total size means the PES size is
842 pes->total_size += 6;
843 pes->pes_header_size = pes->header[8] + 9;
845 /* otherwise, it should be a table */
848 pes->state = MPEGTS_SKIP;
853 /**********************************************/
854 /* PES packing parsing */
855 case MPEGTS_PESHEADER_FILL:
856 len = pes->pes_header_size - pes->data_index;
859 memcpy(pes->header + pes->data_index, p, len);
860 pes->data_index += len;
863 if (pes->data_index == pes->pes_header_size) {
867 flags = pes->header[7];
869 pes->pts = AV_NOPTS_VALUE;
870 pes->dts = AV_NOPTS_VALUE;
871 if ((flags & 0xc0) == 0x80) {
872 pes->pts = get_pts(r);
874 } else if ((flags & 0xc0) == 0xc0) {
875 pes->pts = get_pts(r);
877 pes->dts = get_pts(r);
880 /* we got the full header. We parse it and get the payload */
881 pes->state = MPEGTS_PAYLOAD;
885 if (pes->total_size) {
886 len = pes->total_size - pes->data_index;
893 AVPacket *pkt = ts->pkt;
894 if (pes->st && av_new_packet(pkt, len) == 0) {
895 memcpy(pkt->data, p, len);
896 pkt->stream_index = pes->st->index;
899 /* reset pts values */
900 pes->pts = AV_NOPTS_VALUE;
901 pes->dts = AV_NOPTS_VALUE;
915 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
918 int codec_type, codec_id;
920 switch(pes->stream_type){
921 case STREAM_TYPE_AUDIO_MPEG1:
922 case STREAM_TYPE_AUDIO_MPEG2:
923 codec_type = CODEC_TYPE_AUDIO;
924 codec_id = CODEC_ID_MP3;
926 case STREAM_TYPE_VIDEO_MPEG1:
927 case STREAM_TYPE_VIDEO_MPEG2:
928 codec_type = CODEC_TYPE_VIDEO;
929 codec_id = CODEC_ID_MPEG2VIDEO;
931 case STREAM_TYPE_VIDEO_MPEG4:
932 codec_type = CODEC_TYPE_VIDEO;
933 codec_id = CODEC_ID_MPEG4;
935 case STREAM_TYPE_VIDEO_H264:
936 codec_type = CODEC_TYPE_VIDEO;
937 codec_id = CODEC_ID_H264;
939 case STREAM_TYPE_VIDEO_VC1:
940 codec_type = CODEC_TYPE_VIDEO;
941 codec_id = CODEC_ID_VC1;
943 case STREAM_TYPE_AUDIO_AAC:
944 codec_type = CODEC_TYPE_AUDIO;
945 codec_id = CODEC_ID_AAC;
947 case STREAM_TYPE_AUDIO_AC3:
948 codec_type = CODEC_TYPE_AUDIO;
949 codec_id = CODEC_ID_AC3;
951 case STREAM_TYPE_AUDIO_DTS:
952 case STREAM_TYPE_AUDIO_HDMV_DTS:
953 codec_type = CODEC_TYPE_AUDIO;
954 codec_id = CODEC_ID_DTS;
956 case STREAM_TYPE_SUBTITLE_DVB:
957 codec_type = CODEC_TYPE_SUBTITLE;
958 codec_id = CODEC_ID_DVB_SUBTITLE;
961 if (code >= 0x1c0 && code <= 0x1df) {
962 codec_type = CODEC_TYPE_AUDIO;
963 codec_id = CODEC_ID_MP2;
964 } else if (code == 0x1bd) {
965 codec_type = CODEC_TYPE_AUDIO;
966 codec_id = CODEC_ID_AC3;
968 codec_type = CODEC_TYPE_VIDEO;
969 codec_id = CODEC_ID_MPEG1VIDEO;
973 st = av_new_stream(pes->stream, pes->pid);
975 av_set_pts_info(st, 33, 1, 90000);
977 st->codec->codec_type = codec_type;
978 st->codec->codec_id = codec_id;
979 st->need_parsing = AVSTREAM_PARSE_FULL;
986 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
991 /* if no pid found, then add a pid context */
992 pes = av_mallocz(sizeof(PESContext));
996 pes->stream = ts->stream;
998 pes->pcr_pid = pcr_pid;
999 pes->stream_type = stream_type;
1000 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1008 /* handle one TS packet */
1009 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1011 AVFormatContext *s = ts->stream;
1013 int len, pid, cc, cc_ok, afc, is_start;
1014 const uint8_t *p, *p_end;
1016 pid = AV_RB16(packet + 1) & 0x1fff;
1017 if(pid && discard_pid(ts, pid))
1019 is_start = packet[1] & 0x40;
1020 tss = ts->pids[pid];
1021 if (ts->auto_guess && tss == NULL && is_start) {
1022 add_pes_stream(ts, pid, -1, 0);
1023 tss = ts->pids[pid];
1028 /* continuity check (currently not used) */
1029 cc = (packet[3] & 0xf);
1030 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1033 /* skip adaptation field */
1034 afc = (packet[3] >> 4) & 3;
1036 if (afc == 0) /* reserved value */
1038 if (afc == 2) /* adaptation field only */
1041 /* skip adapation field */
1044 /* if past the end of packet, ignore */
1045 p_end = packet + TS_PACKET_SIZE;
1049 if (tss->type == MPEGTS_SECTION) {
1051 /* pointer field present */
1053 if (p + len > p_end)
1056 /* write remaining section bytes */
1057 write_section_data(s, tss,
1059 /* check whether filter has been closed */
1065 write_section_data(s, tss,
1070 write_section_data(s, tss,
1075 tss->u.pes_filter.pes_cb(tss,
1076 p, p_end - p, is_start);
1080 /* XXX: try to find a better synchro over several packets (use
1081 get_packet_size() ?) */
1082 static int mpegts_resync(ByteIOContext *pb)
1086 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1091 url_fseek(pb, -1, SEEK_CUR);
1099 /* return -1 if error or EOF. Return 0 if OK. */
1100 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1105 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1106 if (len != TS_PACKET_SIZE)
1107 return AVERROR(EIO);
1108 /* check paquet sync byte */
1109 if (buf[0] != 0x47) {
1110 /* find a new packet start */
1111 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1112 if (mpegts_resync(pb) < 0)
1113 return AVERROR_INVALIDDATA;
1117 skip = raw_packet_size - TS_PACKET_SIZE;
1119 url_fskip(pb, skip);
1126 static int handle_packets(MpegTSContext *ts, int nb_packets)
1128 AVFormatContext *s = ts->stream;
1129 ByteIOContext *pb = s->pb;
1130 uint8_t packet[TS_PACKET_SIZE];
1131 int packet_num, ret;
1136 if (ts->stop_parse>0)
1139 if (nb_packets != 0 && packet_num >= nb_packets)
1141 ret = read_packet(pb, packet, ts->raw_packet_size);
1144 handle_packet(ts, packet);
1149 static int mpegts_probe(AVProbeData *p)
1152 const int size= p->buf_size;
1153 int score, fec_score, dvhs_score;
1154 #define CHECK_COUNT 10
1156 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1159 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1160 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1161 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1162 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1164 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1165 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1166 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1167 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1170 /* only use the extension for safer guess */
1171 if (match_ext(p->filename, "ts"))
1172 return AVPROBE_SCORE_MAX;
1178 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1179 (-1) if not available */
1180 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1181 const uint8_t *packet)
1183 int afc, len, flags;
1187 afc = (packet[3] >> 4) & 3;
1197 if (!(flags & 0x10))
1202 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1203 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1207 static int mpegts_read_header(AVFormatContext *s,
1208 AVFormatParameters *ap)
1210 MpegTSContext *ts = s->priv_data;
1211 ByteIOContext *pb = s->pb;
1217 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1218 if(ap->mpeg2ts_raw){
1219 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1224 /* read the first 1024 bytes to get packet size */
1225 pos = url_ftell(pb);
1226 len = get_buffer(pb, buf, sizeof(buf));
1227 if (len != sizeof(buf))
1229 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1230 if (ts->raw_packet_size <= 0)
1235 if (s->iformat == &mpegts_demuxer) {
1238 /* first do a scaning to get all the services */
1239 url_fseek(pb, pos, SEEK_SET);
1240 mpegts_scan_sdt(ts);
1242 mpegts_set_service(ts);
1244 handle_packets(ts, s->probesize);
1245 /* if could not find service, enable auto_guess */
1250 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1252 s->ctx_flags |= AVFMTCTX_NOHEADER;
1255 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1256 int64_t pcrs[2], pcr_h;
1257 int packet_count[2];
1258 uint8_t packet[TS_PACKET_SIZE];
1260 /* only read packets */
1262 st = av_new_stream(s, 0);
1265 av_set_pts_info(st, 60, 1, 27000000);
1266 st->codec->codec_type = CODEC_TYPE_DATA;
1267 st->codec->codec_id = CODEC_ID_MPEG2TS;
1269 /* we iterate until we find two PCRs to estimate the bitrate */
1274 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1277 pid = AV_RB16(packet + 1) & 0x1fff;
1278 if ((pcr_pid == -1 || pcr_pid == pid) &&
1279 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1281 packet_count[nb_pcrs] = nb_packets;
1282 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1290 /* NOTE1: the bitrate is computed without the FEC */
1291 /* NOTE2: it is only the bitrate of the start of the stream */
1292 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1293 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1294 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1295 st->codec->bit_rate = s->bit_rate;
1296 st->start_time = ts->cur_pcr;
1298 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1299 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1303 url_fseek(pb, pos, SEEK_SET);
1309 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1311 static int mpegts_raw_read_packet(AVFormatContext *s,
1314 MpegTSContext *ts = s->priv_data;
1316 int64_t pcr_h, next_pcr_h, pos;
1317 int pcr_l, next_pcr_l;
1318 uint8_t pcr_buf[12];
1320 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1321 return AVERROR(ENOMEM);
1322 pkt->pos= url_ftell(s->pb);
1323 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1325 av_free_packet(pkt);
1328 if (ts->mpeg2ts_compute_pcr) {
1329 /* compute exact PCR for each packet */
1330 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1331 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1332 pos = url_ftell(s->pb);
1333 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1334 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1335 get_buffer(s->pb, pcr_buf, 12);
1336 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1337 /* XXX: not precise enough */
1338 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1343 url_fseek(s->pb, pos, SEEK_SET);
1344 /* no next PCR found: we use previous increment */
1345 ts->cur_pcr = pcr_h * 300 + pcr_l;
1347 pkt->pts = ts->cur_pcr;
1348 pkt->duration = ts->pcr_incr;
1349 ts->cur_pcr += ts->pcr_incr;
1351 pkt->stream_index = 0;
1355 static int mpegts_read_packet(AVFormatContext *s,
1358 MpegTSContext *ts = s->priv_data;
1361 return handle_packets(ts, 0);
1364 static int mpegts_read_close(AVFormatContext *s)
1366 MpegTSContext *ts = s->priv_data;
1368 for(i=0;i<NB_PID_MAX;i++)
1369 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1374 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1375 int64_t *ppos, int64_t pos_limit)
1377 MpegTSContext *ts = s->priv_data;
1378 int64_t pos, timestamp;
1379 uint8_t buf[TS_PACKET_SIZE];
1380 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1381 const int find_next= 1;
1382 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1385 url_fseek(s->pb, pos, SEEK_SET);
1386 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1387 return AV_NOPTS_VALUE;
1388 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1389 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1392 pos += ts->raw_packet_size;
1396 pos -= ts->raw_packet_size;
1398 return AV_NOPTS_VALUE;
1399 url_fseek(s->pb, pos, SEEK_SET);
1400 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1401 return AV_NOPTS_VALUE;
1402 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1403 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1413 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1414 MpegTSContext *ts = s->priv_data;
1415 uint8_t buf[TS_PACKET_SIZE];
1418 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1421 pos= url_ftell(s->pb);
1424 url_fseek(s->pb, pos, SEEK_SET);
1425 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1427 // pid = AV_RB16(buf + 1) & 0x1fff;
1428 if(buf[1] & 0x40) break;
1429 pos += ts->raw_packet_size;
1431 url_fseek(s->pb, pos, SEEK_SET);
1436 /**************************************************************/
1437 /* parsing functions - called from other demuxers such as RTP */
1439 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1443 ts = av_mallocz(sizeof(MpegTSContext));
1446 /* no stream case, currently used by RTP */
1447 ts->raw_packet_size = TS_PACKET_SIZE;
1453 /* return the consumed length if a packet was output, or -1 if no
1455 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1456 const uint8_t *buf, int len)
1464 if (ts->stop_parse>0)
1466 if (len < TS_PACKET_SIZE)
1468 if (buf[0] != 0x47) {
1472 handle_packet(ts, buf);
1473 buf += TS_PACKET_SIZE;
1474 len -= TS_PACKET_SIZE;
1480 void mpegts_parse_close(MpegTSContext *ts)
1484 for(i=0;i<NB_PID_MAX;i++)
1485 av_free(ts->pids[i]);
1489 AVInputFormat mpegts_demuxer = {
1491 "MPEG2 transport stream format",
1492 sizeof(MpegTSContext),
1499 .flags = AVFMT_SHOW_IDS,
1502 AVInputFormat mpegtsraw_demuxer = {
1504 "MPEG2 raw transport stream format",
1505 sizeof(MpegTSContext),
1508 mpegts_raw_read_packet,
1512 .flags = AVFMT_SHOW_IDS,