2 * MPEG2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard.
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/crc.h"
30 /* 1.0 second at 24Mbit/s */
31 #define MAX_SCAN_PACKETS 32000
33 /* maximum size in which we look for synchronisation if
34 synchronisation is lost */
35 #define MAX_RESYNC_SIZE 4096
36 #define REGISTRATION_DESCRIPTOR 5
38 typedef struct PESContext PESContext;
40 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
41 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
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 {
65 unsigned int check_crc:1;
66 unsigned 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 */
96 /** if true, all pids are analyzed to find streams */
99 /** compute exact PCR for each transport stream packet */
100 int mpeg2ts_compute_pcr;
102 int64_t cur_pcr; /**< used to estimate the exact PCR */
103 int pcr_incr; /**< used to estimate the exact PCR */
105 /* data needed to handle file based ts */
106 /** stop parsing loop */
108 /** packet containing Audio/Video data */
111 /******************************************/
112 /* private mpegts data */
114 /** structure to keep track of Program->pids mapping */
119 /** filters for various streams specified by PMT + for the PAT and PMT */
120 MpegTSFilter *pids[NB_PID_MAX];
123 /* TS stream handling */
127 MPEGTS_PESHEADER_FILL,
132 /* enough for PES header + length */
133 #define PES_START_SIZE 9
134 #define MAX_PES_HEADER_SIZE (9 + 255)
138 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
141 AVFormatContext *stream;
143 enum MpegTSState state;
144 /* used to get the format */
149 uint8_t header[MAX_PES_HEADER_SIZE];
152 extern AVInputFormat mpegts_demuxer;
154 static void clear_program(MpegTSContext *ts, unsigned int programid)
158 for(i=0; i<ts->nb_prg; i++)
159 if(ts->prg[i].id == programid)
160 ts->prg[i].nb_pids = 0;
163 static void clear_programs(MpegTSContext *ts)
169 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
172 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(Program_t));
176 p = &ts->prg[ts->nb_prg];
182 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
186 for(i=0; i<ts->nb_prg; i++) {
187 if(ts->prg[i].id == programid) {
195 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
197 p->pids[p->nb_pids++] = pid;
201 * \brief discard_pid() decides if the pid is to be discarded according
202 * to caller's programs selection
203 * \param ts : - TS context
205 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
208 static int discard_pid(MpegTSContext *ts, unsigned int pid)
211 int used = 0, discarded = 0;
213 for(i=0; i<ts->nb_prg; i++) {
215 for(j=0; j<p->nb_pids; j++) {
216 if(p->pids[j] != pid)
218 //is program with id p->id set to be discarded?
219 for(k=0; k<ts->stream->nb_programs; k++) {
220 if(ts->stream->programs[k]->id == p->id) {
221 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
230 return !used && discarded;
234 * Assembles PES packets out of TS packets, and then calls the "section_cb"
235 * function when they are complete.
237 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
238 const uint8_t *buf, int buf_size, int is_start)
240 MpegTSSectionFilter *tss = &tss1->u.section_filter;
244 memcpy(tss->section_buf, buf, buf_size);
245 tss->section_index = buf_size;
246 tss->section_h_size = -1;
247 tss->end_of_section_reached = 0;
249 if (tss->end_of_section_reached)
251 len = 4096 - tss->section_index;
254 memcpy(tss->section_buf + tss->section_index, buf, len);
255 tss->section_index += len;
258 /* compute section length if possible */
259 if (tss->section_h_size == -1 && tss->section_index >= 3) {
260 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
263 tss->section_h_size = len;
266 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
267 tss->end_of_section_reached = 1;
268 if (!tss->check_crc ||
269 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
270 tss->section_buf, tss->section_h_size) == 0)
271 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
275 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
276 SectionCallback *section_cb, void *opaque,
280 MpegTSFilter *filter;
281 MpegTSSectionFilter *sec;
284 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
286 if (pid >= NB_PID_MAX || ts->pids[pid])
288 filter = av_mallocz(sizeof(MpegTSFilter));
291 ts->pids[pid] = filter;
292 filter->type = MPEGTS_SECTION;
294 filter->last_cc = -1;
295 sec = &filter->u.section_filter;
296 sec->section_cb = section_cb;
297 sec->opaque = opaque;
298 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
299 sec->check_crc = check_crc;
300 if (!sec->section_buf) {
307 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
311 MpegTSFilter *filter;
312 MpegTSPESFilter *pes;
314 if (pid >= NB_PID_MAX || ts->pids[pid])
316 filter = av_mallocz(sizeof(MpegTSFilter));
319 ts->pids[pid] = filter;
320 filter->type = MPEGTS_PES;
322 filter->last_cc = -1;
323 pes = &filter->u.pes_filter;
324 pes->pes_cb = pes_cb;
325 pes->opaque = opaque;
329 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
334 if (filter->type == MPEGTS_SECTION)
335 av_freep(&filter->u.section_filter.section_buf);
338 ts->pids[pid] = NULL;
341 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
342 int stat[packet_size];
347 memset(stat, 0, packet_size*sizeof(int));
349 for(x=i=0; i<size-3; i++){
350 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
352 if(stat[x] > best_score){
359 if(x == packet_size) x= 0;
365 /* autodetect fec presence. Must have at least 1024 bytes */
366 static int get_packet_size(const uint8_t *buf, int size)
368 int score, fec_score, dvhs_score;
370 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
373 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
374 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
375 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
376 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
378 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
379 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
380 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
384 typedef struct SectionHeader {
389 uint8_t last_sec_num;
392 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
405 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
411 if ((p + 1) >= p_end)
419 /* read and allocate a DVB string preceeded by its length */
420 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
427 len = get8(&p, p_end);
430 if ((p + len) > p_end)
432 str = av_malloc(len + 1);
442 static int parse_section_header(SectionHeader *h,
443 const uint8_t **pp, const uint8_t *p_end)
447 val = get8(pp, p_end);
452 val = get16(pp, p_end);
456 val = get8(pp, p_end);
459 h->version = (val >> 1) & 0x1f;
460 val = get8(pp, p_end);
464 val = get8(pp, p_end);
467 h->last_sec_num = val;
472 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
474 MpegTSContext *ts = filter->u.section_filter.opaque;
475 SectionHeader h1, *h = &h1;
478 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
479 int program_info_length, pcr_pid, pid, stream_type;
480 int desc_list_len, desc_len, desc_tag;
481 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
482 char language[4] = {0}; /* initialize to kill warnings */
483 int has_hdmv_descr = 0;
484 int has_dirac_descr = 0;
487 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
488 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
490 p_end = section + section_len - 4;
492 if (parse_section_header(h, &p, p_end) < 0)
495 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
496 h->id, h->sec_num, h->last_sec_num);
498 if (h->tid != PMT_TID)
501 clear_program(ts, h->id);
502 pcr_pid = get16(&p, p_end) & 0x1fff;
505 add_pid_to_pmt(ts, h->id, pcr_pid);
507 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
509 program_info_length = get16(&p, p_end) & 0xfff;
510 if (program_info_length < 0)
512 while(program_info_length >= 2) {
514 tag = get8(&p, p_end);
515 len = get8(&p, p_end);
516 if(len > program_info_length - 2)
517 //something else is broken, exit the program_descriptors_loop
519 program_info_length -= len + 2;
520 if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
522 bytes[0] = get8(&p, p_end);
523 bytes[1] = get8(&p, p_end);
524 bytes[2] = get8(&p, p_end);
525 bytes[3] = get8(&p, p_end);
527 if(bytes[0] == 'H' && bytes[1] == 'D' &&
528 bytes[2] == 'M' && bytes[3] == 'V')
533 p += program_info_length;
539 stream_type = get8(&p, p_end);
542 pid = get16(&p, p_end) & 0x1fff;
545 desc_list_len = get16(&p, p_end) & 0xfff;
546 if (desc_list_len < 0)
548 desc_list_end = p + desc_list_len;
549 if (desc_list_end > p_end)
552 desc_tag = get8(&p, desc_list_end);
555 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
556 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
557 /*assume DVB AC-3 Audio*/
558 stream_type = STREAM_TYPE_AUDIO_AC3;
559 } else if(desc_tag == 0x7B) {
561 stream_type = STREAM_TYPE_AUDIO_DTS;
564 desc_len = get8(&p, desc_list_end);
565 desc_end = p + desc_len;
566 if (desc_end > desc_list_end)
569 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
573 case DVB_SUBT_DESCID:
574 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
575 stream_type = STREAM_TYPE_SUBTITLE_DVB;
577 language[0] = get8(&p, desc_end);
578 language[1] = get8(&p, desc_end);
579 language[2] = get8(&p, desc_end);
582 comp_page = get16(&p, desc_end);
583 anc_page = get16(&p, desc_end);
586 case 0x0a: /* ISO 639 language descriptor */
587 language[0] = get8(&p, desc_end);
588 language[1] = get8(&p, desc_end);
589 language[2] = get8(&p, desc_end);
592 case REGISTRATION_DESCRIPTOR: /*MPEG-2 Registration descriptor */
595 bytes[0] = get8(&p, desc_end);
596 bytes[1] = get8(&p, desc_end);
597 bytes[2] = get8(&p, desc_end);
598 bytes[3] = get8(&p, desc_end);
599 if(bytes[0] == 'd' && bytes[1] == 'r' &&
600 bytes[2] == 'a' && bytes[3] == 'c')
612 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
616 /* now create ffmpeg stream */
617 switch(stream_type) {
618 case STREAM_TYPE_AUDIO_MPEG1:
619 case STREAM_TYPE_AUDIO_MPEG2:
620 case STREAM_TYPE_VIDEO_MPEG1:
621 case STREAM_TYPE_VIDEO_MPEG2:
622 case STREAM_TYPE_VIDEO_MPEG4:
623 case STREAM_TYPE_VIDEO_H264:
624 case STREAM_TYPE_VIDEO_VC1:
625 case STREAM_TYPE_VIDEO_DIRAC:
626 case STREAM_TYPE_AUDIO_AAC:
627 case STREAM_TYPE_AUDIO_AC3:
628 case STREAM_TYPE_AUDIO_DTS:
629 case STREAM_TYPE_AUDIO_HDMV_DTS:
630 case STREAM_TYPE_SUBTITLE_DVB:
631 if((stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
632 || (stream_type == STREAM_TYPE_VIDEO_DIRAC && !has_dirac_descr))
634 if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
635 pes= ts->pids[pid]->u.pes_filter.opaque;
638 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
639 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
641 st = new_pes_av_stream(pes, 0);
643 add_pid_to_pmt(ts, h->id, pid);
645 av_program_add_stream_index(ts->stream, h->id, st->index);
648 /* we ignore the other streams */
653 if (language[0] != 0) {
654 memcpy(st->language, language, 4);
657 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
658 st->codec->sub_id = (anc_page << 16) | comp_page;
662 /* all parameters are there */
664 mpegts_close_filter(ts, filter);
667 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
669 MpegTSContext *ts = filter->u.section_filter.opaque;
670 SectionHeader h1, *h = &h1;
671 const uint8_t *p, *p_end;
675 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
676 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
678 p_end = section + section_len - 4;
680 if (parse_section_header(h, &p, p_end) < 0)
682 if (h->tid != PAT_TID)
687 sid = get16(&p, p_end);
690 pmt_pid = get16(&p, p_end) & 0x1fff;
694 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
699 av_new_program(ts->stream, sid);
701 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
702 add_pat_entry(ts, sid);
703 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
704 add_pid_to_pmt(ts, sid, pmt_pid);
710 mpegts_close_filter(ts, filter);
713 static void mpegts_set_service(MpegTSContext *ts)
715 mpegts_open_section_filter(ts, PAT_PID,
719 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
721 MpegTSContext *ts = filter->u.section_filter.opaque;
722 SectionHeader h1, *h = &h1;
723 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
724 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
725 char *name, *provider_name;
728 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
729 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
732 p_end = section + section_len - 4;
734 if (parse_section_header(h, &p, p_end) < 0)
736 if (h->tid != SDT_TID)
738 onid = get16(&p, p_end);
741 val = get8(&p, p_end);
745 sid = get16(&p, p_end);
748 val = get8(&p, p_end);
751 desc_list_len = get16(&p, p_end) & 0xfff;
752 if (desc_list_len < 0)
754 desc_list_end = p + desc_list_len;
755 if (desc_list_end > p_end)
758 desc_tag = get8(&p, desc_list_end);
761 desc_len = get8(&p, desc_list_end);
762 desc_end = p + desc_len;
763 if (desc_end > desc_list_end)
766 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
771 service_type = get8(&p, p_end);
772 if (service_type < 0)
774 provider_name = getstr8(&p, p_end);
777 name = getstr8(&p, p_end);
779 AVProgram *program = av_new_program(ts->stream, sid);
781 av_set_program_name(program, provider_name, name);
784 av_free(provider_name);
795 /* scan services in a transport stream by looking at the SDT */
796 static void mpegts_scan_sdt(MpegTSContext *ts)
798 mpegts_open_section_filter(ts, SDT_PID,
802 static int64_t get_pts(const uint8_t *p)
804 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
805 pts |= (AV_RB16(p + 1) >> 1) << 15;
806 pts |= AV_RB16(p + 3) >> 1;
810 /* return non zero if a packet could be constructed */
811 static void mpegts_push_data(MpegTSFilter *filter,
812 const uint8_t *buf, int buf_size, int is_start)
814 PESContext *pes = filter->u.pes_filter.opaque;
815 MpegTSContext *ts = pes->ts;
823 pes->state = MPEGTS_HEADER;
827 while (buf_size > 0) {
830 len = PES_START_SIZE - pes->data_index;
833 memcpy(pes->header + pes->data_index, p, len);
834 pes->data_index += len;
837 if (pes->data_index == PES_START_SIZE) {
838 /* we got all the PES or section header. We can now
841 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
843 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
844 pes->header[2] == 0x01) {
845 /* it must be an mpeg2 PES stream */
846 code = pes->header[3] | 0x100;
847 if (!((code >= 0x1c0 && code <= 0x1df) ||
848 (code >= 0x1e0 && code <= 0x1ef) ||
849 (code == 0x1bd) || (code == 0x1fd)))
852 /* allocate stream */
853 new_pes_av_stream(pes, code);
855 pes->state = MPEGTS_PESHEADER_FILL;
856 pes->total_size = AV_RB16(pes->header + 4);
857 /* NOTE: a zero total size means the PES size is
860 pes->total_size += 6;
861 pes->pes_header_size = pes->header[8] + 9;
863 /* otherwise, it should be a table */
866 pes->state = MPEGTS_SKIP;
871 /**********************************************/
872 /* PES packing parsing */
873 case MPEGTS_PESHEADER_FILL:
874 len = pes->pes_header_size - pes->data_index;
877 memcpy(pes->header + pes->data_index, p, len);
878 pes->data_index += len;
881 if (pes->data_index == pes->pes_header_size) {
885 flags = pes->header[7];
887 pes->pts = AV_NOPTS_VALUE;
888 pes->dts = AV_NOPTS_VALUE;
889 if ((flags & 0xc0) == 0x80) {
890 pes->pts = get_pts(r);
892 } else if ((flags & 0xc0) == 0xc0) {
893 pes->pts = get_pts(r);
895 pes->dts = get_pts(r);
898 /* we got the full header. We parse it and get the payload */
899 pes->state = MPEGTS_PAYLOAD;
903 if (pes->total_size) {
904 len = pes->total_size - pes->data_index;
911 AVPacket *pkt = ts->pkt;
912 if (pes->st && av_new_packet(pkt, len) == 0) {
913 memcpy(pkt->data, p, len);
914 pkt->stream_index = pes->st->index;
917 /* reset pts values */
918 pes->pts = AV_NOPTS_VALUE;
919 pes->dts = AV_NOPTS_VALUE;
933 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
936 enum CodecID codec_id;
937 enum CodecType codec_type;
939 switch(pes->stream_type){
940 case STREAM_TYPE_AUDIO_MPEG1:
941 case STREAM_TYPE_AUDIO_MPEG2:
942 codec_type = CODEC_TYPE_AUDIO;
943 codec_id = CODEC_ID_MP3;
945 case STREAM_TYPE_VIDEO_MPEG1:
946 case STREAM_TYPE_VIDEO_MPEG2:
947 codec_type = CODEC_TYPE_VIDEO;
948 codec_id = CODEC_ID_MPEG2VIDEO;
950 case STREAM_TYPE_VIDEO_MPEG4:
951 codec_type = CODEC_TYPE_VIDEO;
952 codec_id = CODEC_ID_MPEG4;
954 case STREAM_TYPE_VIDEO_H264:
955 codec_type = CODEC_TYPE_VIDEO;
956 codec_id = CODEC_ID_H264;
958 case STREAM_TYPE_VIDEO_VC1:
959 codec_type = CODEC_TYPE_VIDEO;
960 codec_id = CODEC_ID_VC1;
962 case STREAM_TYPE_VIDEO_DIRAC:
963 codec_type = CODEC_TYPE_VIDEO;
964 codec_id = CODEC_ID_DIRAC;
966 case STREAM_TYPE_AUDIO_AAC:
967 codec_type = CODEC_TYPE_AUDIO;
968 codec_id = CODEC_ID_AAC;
970 case STREAM_TYPE_AUDIO_AC3:
971 codec_type = CODEC_TYPE_AUDIO;
972 codec_id = CODEC_ID_AC3;
974 case STREAM_TYPE_AUDIO_DTS:
975 case STREAM_TYPE_AUDIO_HDMV_DTS:
976 codec_type = CODEC_TYPE_AUDIO;
977 codec_id = CODEC_ID_DTS;
979 case STREAM_TYPE_SUBTITLE_DVB:
980 codec_type = CODEC_TYPE_SUBTITLE;
981 codec_id = CODEC_ID_DVB_SUBTITLE;
984 if (code >= 0x1c0 && code <= 0x1df) {
985 codec_type = CODEC_TYPE_AUDIO;
986 codec_id = CODEC_ID_MP2;
987 } else if (code == 0x1bd) {
988 codec_type = CODEC_TYPE_AUDIO;
989 codec_id = CODEC_ID_AC3;
991 codec_type = CODEC_TYPE_VIDEO;
992 codec_id = CODEC_ID_PROBE;
996 st = av_new_stream(pes->stream, pes->pid);
998 av_set_pts_info(st, 33, 1, 90000);
1000 st->codec->codec_type = codec_type;
1001 st->codec->codec_id = codec_id;
1002 st->need_parsing = AVSTREAM_PARSE_FULL;
1009 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1014 /* if no pid found, then add a pid context */
1015 pes = av_mallocz(sizeof(PESContext));
1019 pes->stream = ts->stream;
1021 pes->pcr_pid = pcr_pid;
1022 pes->stream_type = stream_type;
1023 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1031 /* handle one TS packet */
1032 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1034 AVFormatContext *s = ts->stream;
1036 int len, pid, cc, cc_ok, afc, is_start;
1037 const uint8_t *p, *p_end;
1039 pid = AV_RB16(packet + 1) & 0x1fff;
1040 if(pid && discard_pid(ts, pid))
1042 is_start = packet[1] & 0x40;
1043 tss = ts->pids[pid];
1044 if (ts->auto_guess && tss == NULL && is_start) {
1045 add_pes_stream(ts, pid, -1, 0);
1046 tss = ts->pids[pid];
1051 /* continuity check (currently not used) */
1052 cc = (packet[3] & 0xf);
1053 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1056 /* skip adaptation field */
1057 afc = (packet[3] >> 4) & 3;
1059 if (afc == 0) /* reserved value */
1061 if (afc == 2) /* adaptation field only */
1064 /* skip adapation field */
1067 /* if past the end of packet, ignore */
1068 p_end = packet + TS_PACKET_SIZE;
1072 ts->pos47= url_ftell(ts->stream->pb) % ts->raw_packet_size;
1074 if (tss->type == MPEGTS_SECTION) {
1076 /* pointer field present */
1078 if (p + len > p_end)
1081 /* write remaining section bytes */
1082 write_section_data(s, tss,
1084 /* check whether filter has been closed */
1090 write_section_data(s, tss,
1095 write_section_data(s, tss,
1100 tss->u.pes_filter.pes_cb(tss,
1101 p, p_end - p, is_start);
1105 /* XXX: try to find a better synchro over several packets (use
1106 get_packet_size() ?) */
1107 static int mpegts_resync(ByteIOContext *pb)
1111 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1116 url_fseek(pb, -1, SEEK_CUR);
1124 /* return -1 if error or EOF. Return 0 if OK. */
1125 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1130 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1131 if (len != TS_PACKET_SIZE)
1132 return AVERROR(EIO);
1133 /* check paquet sync byte */
1134 if (buf[0] != 0x47) {
1135 /* find a new packet start */
1136 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1137 if (mpegts_resync(pb) < 0)
1138 return AVERROR_INVALIDDATA;
1142 skip = raw_packet_size - TS_PACKET_SIZE;
1144 url_fskip(pb, skip);
1151 static int handle_packets(MpegTSContext *ts, int nb_packets)
1153 AVFormatContext *s = ts->stream;
1154 ByteIOContext *pb = s->pb;
1155 uint8_t packet[TS_PACKET_SIZE];
1156 int packet_num, ret;
1161 if (ts->stop_parse>0)
1164 if (nb_packets != 0 && packet_num >= nb_packets)
1166 ret = read_packet(pb, packet, ts->raw_packet_size);
1169 handle_packet(ts, packet);
1174 static int mpegts_probe(AVProbeData *p)
1177 const int size= p->buf_size;
1178 int score, fec_score, dvhs_score;
1179 #define CHECK_COUNT 10
1181 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1184 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1185 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1186 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1187 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1189 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1190 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1191 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1192 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1195 /* only use the extension for safer guess */
1196 if (match_ext(p->filename, "ts"))
1197 return AVPROBE_SCORE_MAX;
1203 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1204 (-1) if not available */
1205 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1206 const uint8_t *packet)
1208 int afc, len, flags;
1212 afc = (packet[3] >> 4) & 3;
1222 if (!(flags & 0x10))
1227 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1228 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1232 static int mpegts_read_header(AVFormatContext *s,
1233 AVFormatParameters *ap)
1235 MpegTSContext *ts = s->priv_data;
1236 ByteIOContext *pb = s->pb;
1242 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1243 if(ap->mpeg2ts_raw){
1244 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1249 /* read the first 1024 bytes to get packet size */
1250 pos = url_ftell(pb);
1251 len = get_buffer(pb, buf, sizeof(buf));
1252 if (len != sizeof(buf))
1254 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1255 if (ts->raw_packet_size <= 0)
1260 if (s->iformat == &mpegts_demuxer) {
1263 /* first do a scaning to get all the services */
1264 url_fseek(pb, pos, SEEK_SET);
1265 mpegts_scan_sdt(ts);
1267 mpegts_set_service(ts);
1269 handle_packets(ts, s->probesize);
1270 /* if could not find service, enable auto_guess */
1275 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1277 s->ctx_flags |= AVFMTCTX_NOHEADER;
1280 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1281 int64_t pcrs[2], pcr_h;
1282 int packet_count[2];
1283 uint8_t packet[TS_PACKET_SIZE];
1285 /* only read packets */
1287 st = av_new_stream(s, 0);
1290 av_set_pts_info(st, 60, 1, 27000000);
1291 st->codec->codec_type = CODEC_TYPE_DATA;
1292 st->codec->codec_id = CODEC_ID_MPEG2TS;
1294 /* we iterate until we find two PCRs to estimate the bitrate */
1299 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1302 pid = AV_RB16(packet + 1) & 0x1fff;
1303 if ((pcr_pid == -1 || pcr_pid == pid) &&
1304 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1306 packet_count[nb_pcrs] = nb_packets;
1307 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1315 /* NOTE1: the bitrate is computed without the FEC */
1316 /* NOTE2: it is only the bitrate of the start of the stream */
1317 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1318 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1319 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1320 st->codec->bit_rate = s->bit_rate;
1321 st->start_time = ts->cur_pcr;
1323 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1324 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1328 url_fseek(pb, pos, SEEK_SET);
1334 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1336 static int mpegts_raw_read_packet(AVFormatContext *s,
1339 MpegTSContext *ts = s->priv_data;
1341 int64_t pcr_h, next_pcr_h, pos;
1342 int pcr_l, next_pcr_l;
1343 uint8_t pcr_buf[12];
1345 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1346 return AVERROR(ENOMEM);
1347 pkt->pos= url_ftell(s->pb);
1348 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1350 av_free_packet(pkt);
1353 if (ts->mpeg2ts_compute_pcr) {
1354 /* compute exact PCR for each packet */
1355 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1356 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1357 pos = url_ftell(s->pb);
1358 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1359 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1360 get_buffer(s->pb, pcr_buf, 12);
1361 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1362 /* XXX: not precise enough */
1363 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1368 url_fseek(s->pb, pos, SEEK_SET);
1369 /* no next PCR found: we use previous increment */
1370 ts->cur_pcr = pcr_h * 300 + pcr_l;
1372 pkt->pts = ts->cur_pcr;
1373 pkt->duration = ts->pcr_incr;
1374 ts->cur_pcr += ts->pcr_incr;
1376 pkt->stream_index = 0;
1380 static int mpegts_read_packet(AVFormatContext *s,
1383 MpegTSContext *ts = s->priv_data;
1386 return handle_packets(ts, 0);
1389 static int mpegts_read_close(AVFormatContext *s)
1391 MpegTSContext *ts = s->priv_data;
1396 for(i=0;i<NB_PID_MAX;i++)
1397 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1402 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1403 int64_t *ppos, int64_t pos_limit)
1405 MpegTSContext *ts = s->priv_data;
1406 int64_t pos, timestamp;
1407 uint8_t buf[TS_PACKET_SIZE];
1408 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1409 const int find_next= 1;
1410 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1413 url_fseek(s->pb, pos, SEEK_SET);
1414 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1415 return AV_NOPTS_VALUE;
1416 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1417 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1420 pos += ts->raw_packet_size;
1424 pos -= ts->raw_packet_size;
1426 return AV_NOPTS_VALUE;
1427 url_fseek(s->pb, pos, SEEK_SET);
1428 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1429 return AV_NOPTS_VALUE;
1430 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1431 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1441 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1442 MpegTSContext *ts = s->priv_data;
1443 uint8_t buf[TS_PACKET_SIZE];
1446 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1449 pos= url_ftell(s->pb);
1452 url_fseek(s->pb, pos, SEEK_SET);
1453 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1455 // pid = AV_RB16(buf + 1) & 0x1fff;
1456 if(buf[1] & 0x40) break;
1457 pos += ts->raw_packet_size;
1459 url_fseek(s->pb, pos, SEEK_SET);
1464 /**************************************************************/
1465 /* parsing functions - called from other demuxers such as RTP */
1467 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1471 ts = av_mallocz(sizeof(MpegTSContext));
1474 /* no stream case, currently used by RTP */
1475 ts->raw_packet_size = TS_PACKET_SIZE;
1481 /* return the consumed length if a packet was output, or -1 if no
1483 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1484 const uint8_t *buf, int len)
1492 if (ts->stop_parse>0)
1494 if (len < TS_PACKET_SIZE)
1496 if (buf[0] != 0x47) {
1500 handle_packet(ts, buf);
1501 buf += TS_PACKET_SIZE;
1502 len -= TS_PACKET_SIZE;
1508 void mpegts_parse_close(MpegTSContext *ts)
1512 for(i=0;i<NB_PID_MAX;i++)
1513 av_free(ts->pids[i]);
1517 AVInputFormat mpegts_demuxer = {
1519 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1520 sizeof(MpegTSContext),
1527 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1530 AVInputFormat mpegtsraw_demuxer = {
1532 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1533 sizeof(MpegTSContext),
1536 mpegts_raw_read_packet,
1540 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,