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"
23 #include "libavutil/intreadwrite.h"
31 /* 1.0 second at 24Mbit/s */
32 #define MAX_SCAN_PACKETS 32000
34 /* maximum size in which we look for synchronisation if
35 synchronisation is lost */
36 #define MAX_RESYNC_SIZE 4096
37 #define REGISTRATION_DESCRIPTOR 5
39 typedef struct PESContext PESContext;
41 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
42 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
44 enum MpegTSFilterType {
49 typedef struct MpegTSFilter MpegTSFilter;
51 typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
53 typedef struct MpegTSPESFilter {
58 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
60 typedef void SetServiceCallback(void *opaque, int ret);
62 typedef struct MpegTSSectionFilter {
66 unsigned int check_crc:1;
67 unsigned int end_of_section_reached:1;
68 SectionCallback *section_cb;
70 } MpegTSSectionFilter;
74 int last_cc; /* last cc code (-1 if first packet) */
75 enum MpegTSFilterType type;
77 MpegTSPESFilter pes_filter;
78 MpegTSSectionFilter section_filter;
82 #define MAX_PIDS_PER_PROGRAM 64
84 unsigned int id; //program id/service id
86 unsigned int pids[MAX_PIDS_PER_PROGRAM];
89 struct MpegTSContext {
91 AVFormatContext *stream;
92 /** raw packet size, including FEC if present */
97 /** if true, all pids are analyzed to find streams */
100 /** compute exact PCR for each transport stream packet */
101 int mpeg2ts_compute_pcr;
103 int64_t cur_pcr; /**< used to estimate the exact PCR */
104 int pcr_incr; /**< used to estimate the exact PCR */
106 /* data needed to handle file based ts */
107 /** stop parsing loop */
109 /** packet containing Audio/Video data */
112 /******************************************/
113 /* private mpegts data */
115 /** structure to keep track of Program->pids mapping */
120 /** filters for various streams specified by PMT + for the PAT and PMT */
121 MpegTSFilter *pids[NB_PID_MAX];
124 /* TS stream handling */
128 MPEGTS_PESHEADER_FILL,
133 /* enough for PES header + length */
134 #define PES_START_SIZE 9
135 #define MAX_PES_HEADER_SIZE (9 + 255)
139 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
142 AVFormatContext *stream;
144 enum MpegTSState state;
145 /* used to get the format */
150 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
151 uint8_t header[MAX_PES_HEADER_SIZE];
154 extern AVInputFormat mpegts_demuxer;
156 static void clear_program(MpegTSContext *ts, unsigned int programid)
160 for(i=0; i<ts->nb_prg; i++)
161 if(ts->prg[i].id == programid)
162 ts->prg[i].nb_pids = 0;
165 static void clear_programs(MpegTSContext *ts)
171 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
174 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
178 p = &ts->prg[ts->nb_prg];
184 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
187 struct Program *p = NULL;
188 for(i=0; i<ts->nb_prg; i++) {
189 if(ts->prg[i].id == programid) {
197 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
199 p->pids[p->nb_pids++] = pid;
203 * \brief discard_pid() decides if the pid is to be discarded according
204 * to caller's programs selection
205 * \param ts : - TS context
207 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
210 static int discard_pid(MpegTSContext *ts, unsigned int pid)
213 int used = 0, discarded = 0;
215 for(i=0; i<ts->nb_prg; i++) {
217 for(j=0; j<p->nb_pids; j++) {
218 if(p->pids[j] != pid)
220 //is program with id p->id set to be discarded?
221 for(k=0; k<ts->stream->nb_programs; k++) {
222 if(ts->stream->programs[k]->id == p->id) {
223 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
232 return !used && discarded;
236 * Assembles PES packets out of TS packets, and then calls the "section_cb"
237 * function when they are complete.
239 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
240 const uint8_t *buf, int buf_size, int is_start)
242 MpegTSSectionFilter *tss = &tss1->u.section_filter;
246 memcpy(tss->section_buf, buf, buf_size);
247 tss->section_index = buf_size;
248 tss->section_h_size = -1;
249 tss->end_of_section_reached = 0;
251 if (tss->end_of_section_reached)
253 len = 4096 - tss->section_index;
256 memcpy(tss->section_buf + tss->section_index, buf, len);
257 tss->section_index += len;
260 /* compute section length if possible */
261 if (tss->section_h_size == -1 && tss->section_index >= 3) {
262 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
265 tss->section_h_size = len;
268 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
269 tss->end_of_section_reached = 1;
270 if (!tss->check_crc ||
271 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
272 tss->section_buf, tss->section_h_size) == 0)
273 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
277 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
278 SectionCallback *section_cb, void *opaque,
282 MpegTSFilter *filter;
283 MpegTSSectionFilter *sec;
286 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
288 if (pid >= NB_PID_MAX || ts->pids[pid])
290 filter = av_mallocz(sizeof(MpegTSFilter));
293 ts->pids[pid] = filter;
294 filter->type = MPEGTS_SECTION;
296 filter->last_cc = -1;
297 sec = &filter->u.section_filter;
298 sec->section_cb = section_cb;
299 sec->opaque = opaque;
300 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
301 sec->check_crc = check_crc;
302 if (!sec->section_buf) {
309 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
313 MpegTSFilter *filter;
314 MpegTSPESFilter *pes;
316 if (pid >= NB_PID_MAX || ts->pids[pid])
318 filter = av_mallocz(sizeof(MpegTSFilter));
321 ts->pids[pid] = filter;
322 filter->type = MPEGTS_PES;
324 filter->last_cc = -1;
325 pes = &filter->u.pes_filter;
326 pes->pes_cb = pes_cb;
327 pes->opaque = opaque;
331 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
336 if (filter->type == MPEGTS_SECTION)
337 av_freep(&filter->u.section_filter.section_buf);
338 else if (filter->type == MPEGTS_PES) {
339 /* referenced private data will be freed later in
340 * av_close_input_stream */
341 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
342 av_freep(&filter->u.pes_filter.opaque);
347 ts->pids[pid] = NULL;
350 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
351 int stat[packet_size];
356 memset(stat, 0, packet_size*sizeof(int));
358 for(x=i=0; i<size-3; i++){
359 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
361 if(stat[x] > best_score){
368 if(x == packet_size) x= 0;
374 /* autodetect fec presence. Must have at least 1024 bytes */
375 static int get_packet_size(const uint8_t *buf, int size)
377 int score, fec_score, dvhs_score;
379 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
382 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
383 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
384 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
385 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
387 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
388 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
389 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
393 typedef struct SectionHeader {
398 uint8_t last_sec_num;
401 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
414 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
420 if ((p + 1) >= p_end)
428 /* read and allocate a DVB string preceeded by its length */
429 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
436 len = get8(&p, p_end);
439 if ((p + len) > p_end)
441 str = av_malloc(len + 1);
451 static int parse_section_header(SectionHeader *h,
452 const uint8_t **pp, const uint8_t *p_end)
456 val = get8(pp, p_end);
461 val = get16(pp, p_end);
465 val = get8(pp, p_end);
468 h->version = (val >> 1) & 0x1f;
469 val = get8(pp, p_end);
473 val = get8(pp, p_end);
476 h->last_sec_num = val;
481 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
483 MpegTSContext *ts = filter->u.section_filter.opaque;
484 SectionHeader h1, *h = &h1;
487 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
488 int program_info_length, pcr_pid, pid, stream_type;
489 int desc_list_len, desc_len, desc_tag;
490 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
491 char language[4] = {0}; /* initialize to kill warnings */
492 int has_hdmv_descr = 0;
493 int has_dirac_descr = 0;
496 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
497 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
499 p_end = section + section_len - 4;
501 if (parse_section_header(h, &p, p_end) < 0)
504 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
505 h->id, h->sec_num, h->last_sec_num);
507 if (h->tid != PMT_TID)
510 clear_program(ts, h->id);
511 pcr_pid = get16(&p, p_end) & 0x1fff;
514 add_pid_to_pmt(ts, h->id, pcr_pid);
516 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
518 program_info_length = get16(&p, p_end) & 0xfff;
519 if (program_info_length < 0)
521 while(program_info_length >= 2) {
523 tag = get8(&p, p_end);
524 len = get8(&p, p_end);
525 if(len > program_info_length - 2)
526 //something else is broken, exit the program_descriptors_loop
528 program_info_length -= len + 2;
529 if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
531 bytes[0] = get8(&p, p_end);
532 bytes[1] = get8(&p, p_end);
533 bytes[2] = get8(&p, p_end);
534 bytes[3] = get8(&p, p_end);
536 if(bytes[0] == 'H' && bytes[1] == 'D' &&
537 bytes[2] == 'M' && bytes[3] == 'V')
542 p += program_info_length;
548 stream_type = get8(&p, p_end);
551 pid = get16(&p, p_end) & 0x1fff;
554 desc_list_len = get16(&p, p_end) & 0xfff;
555 if (desc_list_len < 0)
557 desc_list_end = p + desc_list_len;
558 if (desc_list_end >= p_end)
561 desc_tag = get8(&p, desc_list_end);
564 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
565 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
566 /*assume DVB AC-3 Audio*/
567 stream_type = STREAM_TYPE_AUDIO_AC3;
568 } else if(desc_tag == 0x7B) {
570 stream_type = STREAM_TYPE_AUDIO_DTS;
573 desc_len = get8(&p, desc_list_end);
574 desc_end = p + desc_len;
575 if (desc_end > desc_list_end)
578 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
582 case DVB_SUBT_DESCID:
583 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
584 stream_type = STREAM_TYPE_SUBTITLE_DVB;
586 language[0] = get8(&p, desc_end);
587 language[1] = get8(&p, desc_end);
588 language[2] = get8(&p, desc_end);
591 comp_page = get16(&p, desc_end);
592 anc_page = get16(&p, desc_end);
595 case 0x0a: /* ISO 639 language descriptor */
596 language[0] = get8(&p, desc_end);
597 language[1] = get8(&p, desc_end);
598 language[2] = get8(&p, desc_end);
601 case REGISTRATION_DESCRIPTOR: /*MPEG-2 Registration descriptor */
604 bytes[0] = get8(&p, desc_end);
605 bytes[1] = get8(&p, desc_end);
606 bytes[2] = get8(&p, desc_end);
607 bytes[3] = get8(&p, desc_end);
608 if(bytes[0] == 'd' && bytes[1] == 'r' &&
609 bytes[2] == 'a' && bytes[3] == 'c')
621 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
625 /* now create ffmpeg stream */
626 switch(stream_type) {
627 case STREAM_TYPE_AUDIO_MPEG1:
628 case STREAM_TYPE_AUDIO_MPEG2:
629 case STREAM_TYPE_VIDEO_MPEG1:
630 case STREAM_TYPE_VIDEO_MPEG2:
631 case STREAM_TYPE_VIDEO_MPEG4:
632 case STREAM_TYPE_VIDEO_H264:
633 case STREAM_TYPE_VIDEO_VC1:
634 case STREAM_TYPE_VIDEO_DIRAC:
635 case STREAM_TYPE_AUDIO_AAC:
636 case STREAM_TYPE_AUDIO_AC3:
637 case STREAM_TYPE_AUDIO_DTS:
638 case STREAM_TYPE_AUDIO_HDMV_DTS:
639 case STREAM_TYPE_SUBTITLE_DVB:
640 if((stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
641 || (stream_type == STREAM_TYPE_VIDEO_DIRAC && !has_dirac_descr))
643 if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
644 pes= ts->pids[pid]->u.pes_filter.opaque;
647 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
648 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
650 st = new_pes_av_stream(pes, 0);
652 add_pid_to_pmt(ts, h->id, pid);
654 av_program_add_stream_index(ts->stream, h->id, st->index);
657 /* we ignore the other streams */
662 if (language[0] != 0) {
663 av_metadata_set(&st->metadata, "language", language);
666 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
667 st->codec->sub_id = (anc_page << 16) | comp_page;
671 /* all parameters are there */
673 mpegts_close_filter(ts, filter);
676 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
678 MpegTSContext *ts = filter->u.section_filter.opaque;
679 SectionHeader h1, *h = &h1;
680 const uint8_t *p, *p_end;
684 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
685 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
687 p_end = section + section_len - 4;
689 if (parse_section_header(h, &p, p_end) < 0)
691 if (h->tid != PAT_TID)
696 sid = get16(&p, p_end);
699 pmt_pid = get16(&p, p_end) & 0x1fff;
703 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
708 av_new_program(ts->stream, sid);
710 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
711 add_pat_entry(ts, sid);
712 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
713 add_pid_to_pmt(ts, sid, pmt_pid);
719 mpegts_close_filter(ts, filter);
722 static void mpegts_set_service(MpegTSContext *ts)
724 mpegts_open_section_filter(ts, PAT_PID,
728 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
730 MpegTSContext *ts = filter->u.section_filter.opaque;
731 SectionHeader h1, *h = &h1;
732 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
733 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
734 char *name, *provider_name;
737 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
738 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
741 p_end = section + section_len - 4;
743 if (parse_section_header(h, &p, p_end) < 0)
745 if (h->tid != SDT_TID)
747 onid = get16(&p, p_end);
750 val = get8(&p, p_end);
754 sid = get16(&p, p_end);
757 val = get8(&p, p_end);
760 desc_list_len = get16(&p, p_end) & 0xfff;
761 if (desc_list_len < 0)
763 desc_list_end = p + desc_list_len;
764 if (desc_list_end > p_end)
767 desc_tag = get8(&p, desc_list_end);
770 desc_len = get8(&p, desc_list_end);
771 desc_end = p + desc_len;
772 if (desc_end > desc_list_end)
775 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
780 service_type = get8(&p, p_end);
781 if (service_type < 0)
783 provider_name = getstr8(&p, p_end);
786 name = getstr8(&p, p_end);
788 AVProgram *program = av_new_program(ts->stream, sid);
790 av_metadata_set(&program->metadata, "name", name);
791 av_metadata_set(&program->metadata, "provider_name", provider_name);
795 av_free(provider_name);
806 /* scan services in a transport stream by looking at the SDT */
807 static void mpegts_scan_sdt(MpegTSContext *ts)
809 mpegts_open_section_filter(ts, SDT_PID,
813 static int64_t get_pts(const uint8_t *p)
815 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
816 pts |= (AV_RB16(p + 1) >> 1) << 15;
817 pts |= AV_RB16(p + 3) >> 1;
821 /* return non zero if a packet could be constructed */
822 static void mpegts_push_data(MpegTSFilter *filter,
823 const uint8_t *buf, int buf_size, int is_start,
826 PESContext *pes = filter->u.pes_filter.opaque;
827 MpegTSContext *ts = pes->ts;
835 pes->state = MPEGTS_HEADER;
837 pes->ts_packet_pos = pos;
840 while (buf_size > 0) {
843 len = PES_START_SIZE - pes->data_index;
846 memcpy(pes->header + pes->data_index, p, len);
847 pes->data_index += len;
850 if (pes->data_index == PES_START_SIZE) {
851 /* we got all the PES or section header. We can now
854 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
856 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
857 pes->header[2] == 0x01) {
858 /* it must be an mpeg2 PES stream */
859 code = pes->header[3] | 0x100;
861 !((code >= 0x1c0 && code <= 0x1df) ||
862 (code >= 0x1e0 && code <= 0x1ef) ||
863 (code == 0x1bd) || (code == 0x1fd)))
865 pes->state = MPEGTS_PESHEADER_FILL;
866 pes->total_size = AV_RB16(pes->header + 4);
867 /* NOTE: a zero total size means the PES size is
870 pes->total_size += 6;
871 pes->pes_header_size = pes->header[8] + 9;
873 /* otherwise, it should be a table */
876 pes->state = MPEGTS_SKIP;
881 /**********************************************/
882 /* PES packing parsing */
883 case MPEGTS_PESHEADER_FILL:
884 len = pes->pes_header_size - pes->data_index;
887 memcpy(pes->header + pes->data_index, p, len);
888 pes->data_index += len;
891 if (pes->data_index == pes->pes_header_size) {
895 flags = pes->header[7];
897 pes->pts = AV_NOPTS_VALUE;
898 pes->dts = AV_NOPTS_VALUE;
899 if ((flags & 0xc0) == 0x80) {
900 pes->dts = pes->pts = get_pts(r);
902 } else if ((flags & 0xc0) == 0xc0) {
903 pes->pts = get_pts(r);
905 pes->dts = get_pts(r);
908 /* we got the full header. We parse it and get the payload */
909 pes->state = MPEGTS_PAYLOAD;
913 if (pes->total_size) {
914 len = pes->total_size - pes->data_index;
921 AVPacket *pkt = ts->pkt;
922 if (pes->st && av_new_packet(pkt, len) == 0) {
923 memcpy(pkt->data, p, len);
924 pkt->stream_index = pes->st->index;
927 /* store position of first TS packet of this PES packet */
928 pkt->pos = pes->ts_packet_pos;
929 /* reset pts values */
930 pes->pts = AV_NOPTS_VALUE;
931 pes->dts = AV_NOPTS_VALUE;
945 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
948 enum CodecID codec_id;
949 enum CodecType codec_type;
951 switch(pes->stream_type){
952 case STREAM_TYPE_AUDIO_MPEG1:
953 case STREAM_TYPE_AUDIO_MPEG2:
954 codec_type = CODEC_TYPE_AUDIO;
955 codec_id = CODEC_ID_MP3;
957 case STREAM_TYPE_VIDEO_MPEG1:
958 case STREAM_TYPE_VIDEO_MPEG2:
959 codec_type = CODEC_TYPE_VIDEO;
960 codec_id = CODEC_ID_MPEG2VIDEO;
962 case STREAM_TYPE_VIDEO_MPEG4:
963 codec_type = CODEC_TYPE_VIDEO;
964 codec_id = CODEC_ID_MPEG4;
966 case STREAM_TYPE_VIDEO_H264:
967 codec_type = CODEC_TYPE_VIDEO;
968 codec_id = CODEC_ID_H264;
970 case STREAM_TYPE_VIDEO_VC1:
971 codec_type = CODEC_TYPE_VIDEO;
972 codec_id = CODEC_ID_VC1;
974 case STREAM_TYPE_VIDEO_DIRAC:
975 codec_type = CODEC_TYPE_VIDEO;
976 codec_id = CODEC_ID_DIRAC;
978 case STREAM_TYPE_AUDIO_AAC:
979 codec_type = CODEC_TYPE_AUDIO;
980 codec_id = CODEC_ID_AAC;
982 case STREAM_TYPE_AUDIO_AC3:
983 codec_type = CODEC_TYPE_AUDIO;
984 codec_id = CODEC_ID_AC3;
986 case STREAM_TYPE_AUDIO_DTS:
987 case STREAM_TYPE_AUDIO_HDMV_DTS:
988 codec_type = CODEC_TYPE_AUDIO;
989 codec_id = CODEC_ID_DTS;
991 case STREAM_TYPE_SUBTITLE_DVB:
992 codec_type = CODEC_TYPE_SUBTITLE;
993 codec_id = CODEC_ID_DVB_SUBTITLE;
996 if (code >= 0x1c0 && code <= 0x1df) {
997 codec_type = CODEC_TYPE_AUDIO;
998 codec_id = CODEC_ID_MP2;
999 } else if (code == 0x1bd) {
1000 codec_type = CODEC_TYPE_AUDIO;
1001 codec_id = CODEC_ID_AC3;
1003 codec_type = CODEC_TYPE_VIDEO;
1004 codec_id = CODEC_ID_PROBE;
1008 st = av_new_stream(pes->stream, pes->pid);
1010 av_set_pts_info(st, 33, 1, 90000);
1011 st->priv_data = pes;
1012 st->codec->codec_type = codec_type;
1013 st->codec->codec_id = codec_id;
1014 st->need_parsing = AVSTREAM_PARSE_FULL;
1021 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1026 /* if no pid found, then add a pid context */
1027 pes = av_mallocz(sizeof(PESContext));
1031 pes->stream = ts->stream;
1033 pes->pcr_pid = pcr_pid;
1034 pes->stream_type = stream_type;
1035 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1043 /* handle one TS packet */
1044 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1046 AVFormatContext *s = ts->stream;
1048 int len, pid, cc, cc_ok, afc, is_start;
1049 const uint8_t *p, *p_end;
1052 pid = AV_RB16(packet + 1) & 0x1fff;
1053 if(pid && discard_pid(ts, pid))
1055 is_start = packet[1] & 0x40;
1056 tss = ts->pids[pid];
1057 if (ts->auto_guess && tss == NULL && is_start) {
1058 add_pes_stream(ts, pid, -1, 0);
1059 tss = ts->pids[pid];
1064 /* continuity check (currently not used) */
1065 cc = (packet[3] & 0xf);
1066 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1069 /* skip adaptation field */
1070 afc = (packet[3] >> 4) & 3;
1072 if (afc == 0) /* reserved value */
1074 if (afc == 2) /* adaptation field only */
1077 /* skip adapation field */
1080 /* if past the end of packet, ignore */
1081 p_end = packet + TS_PACKET_SIZE;
1085 pos = url_ftell(ts->stream->pb);
1086 ts->pos47= pos % ts->raw_packet_size;
1088 if (tss->type == MPEGTS_SECTION) {
1090 /* pointer field present */
1092 if (p + len > p_end)
1095 /* write remaining section bytes */
1096 write_section_data(s, tss,
1098 /* check whether filter has been closed */
1104 write_section_data(s, tss,
1109 write_section_data(s, tss,
1114 // Note: The position here points actually behind the current packet.
1115 tss->u.pes_filter.pes_cb(tss,
1116 p, p_end - p, is_start, pos - ts->raw_packet_size);
1120 /* XXX: try to find a better synchro over several packets (use
1121 get_packet_size() ?) */
1122 static int mpegts_resync(ByteIOContext *pb)
1126 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1131 url_fseek(pb, -1, SEEK_CUR);
1139 /* return -1 if error or EOF. Return 0 if OK. */
1140 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1145 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1146 if (len != TS_PACKET_SIZE)
1147 return AVERROR(EIO);
1148 /* check paquet sync byte */
1149 if (buf[0] != 0x47) {
1150 /* find a new packet start */
1151 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1152 if (mpegts_resync(pb) < 0)
1153 return AVERROR_INVALIDDATA;
1157 skip = raw_packet_size - TS_PACKET_SIZE;
1159 url_fskip(pb, skip);
1166 static int handle_packets(MpegTSContext *ts, int nb_packets)
1168 AVFormatContext *s = ts->stream;
1169 ByteIOContext *pb = s->pb;
1170 uint8_t packet[TS_PACKET_SIZE];
1171 int packet_num, ret;
1176 if (ts->stop_parse>0)
1179 if (nb_packets != 0 && packet_num >= nb_packets)
1181 ret = read_packet(pb, packet, ts->raw_packet_size);
1184 handle_packet(ts, packet);
1189 static int mpegts_probe(AVProbeData *p)
1192 const int size= p->buf_size;
1193 int score, fec_score, dvhs_score;
1194 int check_count= size / TS_FEC_PACKET_SIZE;
1195 #define CHECK_COUNT 10
1197 if (check_count < CHECK_COUNT)
1200 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1201 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1202 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1203 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1205 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1206 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1207 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1208 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1211 /* only use the extension for safer guess */
1212 if (match_ext(p->filename, "ts"))
1213 return AVPROBE_SCORE_MAX;
1219 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1220 (-1) if not available */
1221 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1222 const uint8_t *packet)
1224 int afc, len, flags;
1228 afc = (packet[3] >> 4) & 3;
1238 if (!(flags & 0x10))
1243 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1244 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1248 static int mpegts_read_header(AVFormatContext *s,
1249 AVFormatParameters *ap)
1251 MpegTSContext *ts = s->priv_data;
1252 ByteIOContext *pb = s->pb;
1253 uint8_t buf[5*1024];
1258 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1259 if(ap->mpeg2ts_raw){
1260 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1265 /* read the first 1024 bytes to get packet size */
1266 pos = url_ftell(pb);
1267 len = get_buffer(pb, buf, sizeof(buf));
1268 if (len != sizeof(buf))
1270 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1271 if (ts->raw_packet_size <= 0)
1276 if (s->iformat == &mpegts_demuxer) {
1279 /* first do a scaning to get all the services */
1280 url_fseek(pb, pos, SEEK_SET);
1281 mpegts_scan_sdt(ts);
1283 mpegts_set_service(ts);
1285 handle_packets(ts, s->probesize);
1286 /* if could not find service, enable auto_guess */
1291 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1293 s->ctx_flags |= AVFMTCTX_NOHEADER;
1296 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1297 int64_t pcrs[2], pcr_h;
1298 int packet_count[2];
1299 uint8_t packet[TS_PACKET_SIZE];
1301 /* only read packets */
1303 st = av_new_stream(s, 0);
1306 av_set_pts_info(st, 60, 1, 27000000);
1307 st->codec->codec_type = CODEC_TYPE_DATA;
1308 st->codec->codec_id = CODEC_ID_MPEG2TS;
1310 /* we iterate until we find two PCRs to estimate the bitrate */
1315 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1318 pid = AV_RB16(packet + 1) & 0x1fff;
1319 if ((pcr_pid == -1 || pcr_pid == pid) &&
1320 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1322 packet_count[nb_pcrs] = nb_packets;
1323 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1331 /* NOTE1: the bitrate is computed without the FEC */
1332 /* NOTE2: it is only the bitrate of the start of the stream */
1333 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1334 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1335 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1336 st->codec->bit_rate = s->bit_rate;
1337 st->start_time = ts->cur_pcr;
1339 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1340 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1344 url_fseek(pb, pos, SEEK_SET);
1350 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1352 static int mpegts_raw_read_packet(AVFormatContext *s,
1355 MpegTSContext *ts = s->priv_data;
1357 int64_t pcr_h, next_pcr_h, pos;
1358 int pcr_l, next_pcr_l;
1359 uint8_t pcr_buf[12];
1361 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1362 return AVERROR(ENOMEM);
1363 pkt->pos= url_ftell(s->pb);
1364 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1366 av_free_packet(pkt);
1369 if (ts->mpeg2ts_compute_pcr) {
1370 /* compute exact PCR for each packet */
1371 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1372 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1373 pos = url_ftell(s->pb);
1374 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1375 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1376 get_buffer(s->pb, pcr_buf, 12);
1377 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1378 /* XXX: not precise enough */
1379 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1384 url_fseek(s->pb, pos, SEEK_SET);
1385 /* no next PCR found: we use previous increment */
1386 ts->cur_pcr = pcr_h * 300 + pcr_l;
1388 pkt->pts = ts->cur_pcr;
1389 pkt->duration = ts->pcr_incr;
1390 ts->cur_pcr += ts->pcr_incr;
1392 pkt->stream_index = 0;
1396 static int mpegts_read_packet(AVFormatContext *s,
1399 MpegTSContext *ts = s->priv_data;
1402 return handle_packets(ts, 0);
1405 static int mpegts_read_close(AVFormatContext *s)
1407 MpegTSContext *ts = s->priv_data;
1412 for(i=0;i<NB_PID_MAX;i++)
1413 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1418 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1419 int64_t *ppos, int64_t pos_limit)
1421 MpegTSContext *ts = s->priv_data;
1422 int64_t pos, timestamp;
1423 uint8_t buf[TS_PACKET_SIZE];
1424 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1425 const int find_next= 1;
1426 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1429 url_fseek(s->pb, pos, SEEK_SET);
1430 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1431 return AV_NOPTS_VALUE;
1432 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1433 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1436 pos += ts->raw_packet_size;
1440 pos -= ts->raw_packet_size;
1442 return AV_NOPTS_VALUE;
1443 url_fseek(s->pb, pos, SEEK_SET);
1444 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1445 return AV_NOPTS_VALUE;
1446 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1447 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1457 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1458 MpegTSContext *ts = s->priv_data;
1459 uint8_t buf[TS_PACKET_SIZE];
1462 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1465 pos= url_ftell(s->pb);
1468 url_fseek(s->pb, pos, SEEK_SET);
1469 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1471 // pid = AV_RB16(buf + 1) & 0x1fff;
1472 if(buf[1] & 0x40) break;
1473 pos += ts->raw_packet_size;
1475 url_fseek(s->pb, pos, SEEK_SET);
1480 /**************************************************************/
1481 /* parsing functions - called from other demuxers such as RTP */
1483 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1487 ts = av_mallocz(sizeof(MpegTSContext));
1490 /* no stream case, currently used by RTP */
1491 ts->raw_packet_size = TS_PACKET_SIZE;
1497 /* return the consumed length if a packet was output, or -1 if no
1499 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1500 const uint8_t *buf, int len)
1508 if (ts->stop_parse>0)
1510 if (len < TS_PACKET_SIZE)
1512 if (buf[0] != 0x47) {
1516 handle_packet(ts, buf);
1517 buf += TS_PACKET_SIZE;
1518 len -= TS_PACKET_SIZE;
1524 void mpegts_parse_close(MpegTSContext *ts)
1528 for(i=0;i<NB_PID_MAX;i++)
1529 av_free(ts->pids[i]);
1533 AVInputFormat mpegts_demuxer = {
1535 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1536 sizeof(MpegTSContext),
1543 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1546 AVInputFormat mpegtsraw_demuxer = {
1548 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1549 sizeof(MpegTSContext),
1552 mpegts_raw_read_packet,
1556 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,