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);
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 uint8_t header[MAX_PES_HEADER_SIZE];
153 extern AVInputFormat mpegts_demuxer;
155 static void clear_program(MpegTSContext *ts, unsigned int programid)
159 for(i=0; i<ts->nb_prg; i++)
160 if(ts->prg[i].id == programid)
161 ts->prg[i].nb_pids = 0;
164 static void clear_programs(MpegTSContext *ts)
170 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
173 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
177 p = &ts->prg[ts->nb_prg];
183 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
186 struct Program *p = NULL;
187 for(i=0; i<ts->nb_prg; i++) {
188 if(ts->prg[i].id == programid) {
196 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
198 p->pids[p->nb_pids++] = pid;
202 * \brief discard_pid() decides if the pid is to be discarded according
203 * to caller's programs selection
204 * \param ts : - TS context
206 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
209 static int discard_pid(MpegTSContext *ts, unsigned int pid)
212 int used = 0, discarded = 0;
214 for(i=0; i<ts->nb_prg; i++) {
216 for(j=0; j<p->nb_pids; j++) {
217 if(p->pids[j] != pid)
219 //is program with id p->id set to be discarded?
220 for(k=0; k<ts->stream->nb_programs; k++) {
221 if(ts->stream->programs[k]->id == p->id) {
222 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
231 return !used && discarded;
235 * Assembles PES packets out of TS packets, and then calls the "section_cb"
236 * function when they are complete.
238 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
239 const uint8_t *buf, int buf_size, int is_start)
241 MpegTSSectionFilter *tss = &tss1->u.section_filter;
245 memcpy(tss->section_buf, buf, buf_size);
246 tss->section_index = buf_size;
247 tss->section_h_size = -1;
248 tss->end_of_section_reached = 0;
250 if (tss->end_of_section_reached)
252 len = 4096 - tss->section_index;
255 memcpy(tss->section_buf + tss->section_index, buf, len);
256 tss->section_index += len;
259 /* compute section length if possible */
260 if (tss->section_h_size == -1 && tss->section_index >= 3) {
261 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
264 tss->section_h_size = len;
267 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
268 tss->end_of_section_reached = 1;
269 if (!tss->check_crc ||
270 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
271 tss->section_buf, tss->section_h_size) == 0)
272 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
276 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
277 SectionCallback *section_cb, void *opaque,
281 MpegTSFilter *filter;
282 MpegTSSectionFilter *sec;
285 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
287 if (pid >= NB_PID_MAX || ts->pids[pid])
289 filter = av_mallocz(sizeof(MpegTSFilter));
292 ts->pids[pid] = filter;
293 filter->type = MPEGTS_SECTION;
295 filter->last_cc = -1;
296 sec = &filter->u.section_filter;
297 sec->section_cb = section_cb;
298 sec->opaque = opaque;
299 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
300 sec->check_crc = check_crc;
301 if (!sec->section_buf) {
308 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
312 MpegTSFilter *filter;
313 MpegTSPESFilter *pes;
315 if (pid >= NB_PID_MAX || ts->pids[pid])
317 filter = av_mallocz(sizeof(MpegTSFilter));
320 ts->pids[pid] = filter;
321 filter->type = MPEGTS_PES;
323 filter->last_cc = -1;
324 pes = &filter->u.pes_filter;
325 pes->pes_cb = pes_cb;
326 pes->opaque = opaque;
330 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
335 if (filter->type == MPEGTS_SECTION)
336 av_freep(&filter->u.section_filter.section_buf);
339 ts->pids[pid] = NULL;
342 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
343 int stat[packet_size];
348 memset(stat, 0, packet_size*sizeof(int));
350 for(x=i=0; i<size-3; i++){
351 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
353 if(stat[x] > best_score){
360 if(x == packet_size) x= 0;
366 /* autodetect fec presence. Must have at least 1024 bytes */
367 static int get_packet_size(const uint8_t *buf, int size)
369 int score, fec_score, dvhs_score;
371 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
374 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
375 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
376 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
377 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
379 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
380 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
381 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
385 typedef struct SectionHeader {
390 uint8_t last_sec_num;
393 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
406 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
412 if ((p + 1) >= p_end)
420 /* read and allocate a DVB string preceeded by its length */
421 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
428 len = get8(&p, p_end);
431 if ((p + len) > p_end)
433 str = av_malloc(len + 1);
443 static int parse_section_header(SectionHeader *h,
444 const uint8_t **pp, const uint8_t *p_end)
448 val = get8(pp, p_end);
453 val = get16(pp, p_end);
457 val = get8(pp, p_end);
460 h->version = (val >> 1) & 0x1f;
461 val = get8(pp, p_end);
465 val = get8(pp, p_end);
468 h->last_sec_num = val;
473 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
475 MpegTSContext *ts = filter->u.section_filter.opaque;
476 SectionHeader h1, *h = &h1;
479 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
480 int program_info_length, pcr_pid, pid, stream_type;
481 int desc_list_len, desc_len, desc_tag;
482 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
483 char language[4] = {0}; /* initialize to kill warnings */
484 int has_hdmv_descr = 0;
485 int has_dirac_descr = 0;
488 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
489 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
491 p_end = section + section_len - 4;
493 if (parse_section_header(h, &p, p_end) < 0)
496 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
497 h->id, h->sec_num, h->last_sec_num);
499 if (h->tid != PMT_TID)
502 clear_program(ts, h->id);
503 pcr_pid = get16(&p, p_end) & 0x1fff;
506 add_pid_to_pmt(ts, h->id, pcr_pid);
508 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
510 program_info_length = get16(&p, p_end) & 0xfff;
511 if (program_info_length < 0)
513 while(program_info_length >= 2) {
515 tag = get8(&p, p_end);
516 len = get8(&p, p_end);
517 if(len > program_info_length - 2)
518 //something else is broken, exit the program_descriptors_loop
520 program_info_length -= len + 2;
521 if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
523 bytes[0] = get8(&p, p_end);
524 bytes[1] = get8(&p, p_end);
525 bytes[2] = get8(&p, p_end);
526 bytes[3] = get8(&p, p_end);
528 if(bytes[0] == 'H' && bytes[1] == 'D' &&
529 bytes[2] == 'M' && bytes[3] == 'V')
534 p += program_info_length;
540 stream_type = get8(&p, p_end);
543 pid = get16(&p, p_end) & 0x1fff;
546 desc_list_len = get16(&p, p_end) & 0xfff;
547 if (desc_list_len < 0)
549 desc_list_end = p + desc_list_len;
550 if (desc_list_end > p_end)
553 desc_tag = get8(&p, desc_list_end);
556 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
557 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
558 /*assume DVB AC-3 Audio*/
559 stream_type = STREAM_TYPE_AUDIO_AC3;
560 } else if(desc_tag == 0x7B) {
562 stream_type = STREAM_TYPE_AUDIO_DTS;
565 desc_len = get8(&p, desc_list_end);
566 desc_end = p + desc_len;
567 if (desc_end > desc_list_end)
570 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
574 case DVB_SUBT_DESCID:
575 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
576 stream_type = STREAM_TYPE_SUBTITLE_DVB;
578 language[0] = get8(&p, desc_end);
579 language[1] = get8(&p, desc_end);
580 language[2] = get8(&p, desc_end);
583 comp_page = get16(&p, desc_end);
584 anc_page = get16(&p, desc_end);
587 case 0x0a: /* ISO 639 language descriptor */
588 language[0] = get8(&p, desc_end);
589 language[1] = get8(&p, desc_end);
590 language[2] = get8(&p, desc_end);
593 case REGISTRATION_DESCRIPTOR: /*MPEG-2 Registration descriptor */
596 bytes[0] = get8(&p, desc_end);
597 bytes[1] = get8(&p, desc_end);
598 bytes[2] = get8(&p, desc_end);
599 bytes[3] = get8(&p, desc_end);
600 if(bytes[0] == 'd' && bytes[1] == 'r' &&
601 bytes[2] == 'a' && bytes[3] == 'c')
613 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
617 /* now create ffmpeg stream */
618 switch(stream_type) {
619 case STREAM_TYPE_AUDIO_MPEG1:
620 case STREAM_TYPE_AUDIO_MPEG2:
621 case STREAM_TYPE_VIDEO_MPEG1:
622 case STREAM_TYPE_VIDEO_MPEG2:
623 case STREAM_TYPE_VIDEO_MPEG4:
624 case STREAM_TYPE_VIDEO_H264:
625 case STREAM_TYPE_VIDEO_VC1:
626 case STREAM_TYPE_VIDEO_DIRAC:
627 case STREAM_TYPE_AUDIO_AAC:
628 case STREAM_TYPE_AUDIO_AC3:
629 case STREAM_TYPE_AUDIO_DTS:
630 case STREAM_TYPE_AUDIO_HDMV_DTS:
631 case STREAM_TYPE_SUBTITLE_DVB:
632 if((stream_type == STREAM_TYPE_AUDIO_HDMV_DTS && !has_hdmv_descr)
633 || (stream_type == STREAM_TYPE_VIDEO_DIRAC && !has_dirac_descr))
635 if(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES){
636 pes= ts->pids[pid]->u.pes_filter.opaque;
639 if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); //wrongly added sdt filter probably
640 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
642 st = new_pes_av_stream(pes, 0);
644 add_pid_to_pmt(ts, h->id, pid);
646 av_program_add_stream_index(ts->stream, h->id, st->index);
649 /* we ignore the other streams */
654 if (language[0] != 0) {
655 memcpy(st->language, language, 4);
658 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
659 st->codec->sub_id = (anc_page << 16) | comp_page;
663 /* all parameters are there */
665 mpegts_close_filter(ts, filter);
668 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
670 MpegTSContext *ts = filter->u.section_filter.opaque;
671 SectionHeader h1, *h = &h1;
672 const uint8_t *p, *p_end;
676 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
677 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
679 p_end = section + section_len - 4;
681 if (parse_section_header(h, &p, p_end) < 0)
683 if (h->tid != PAT_TID)
688 sid = get16(&p, p_end);
691 pmt_pid = get16(&p, p_end) & 0x1fff;
695 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
700 av_new_program(ts->stream, sid);
702 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
703 add_pat_entry(ts, sid);
704 add_pid_to_pmt(ts, sid, 0); //add pat pid to program
705 add_pid_to_pmt(ts, sid, pmt_pid);
711 mpegts_close_filter(ts, filter);
714 static void mpegts_set_service(MpegTSContext *ts)
716 mpegts_open_section_filter(ts, PAT_PID,
720 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
722 MpegTSContext *ts = filter->u.section_filter.opaque;
723 SectionHeader h1, *h = &h1;
724 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
725 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
726 char *name, *provider_name;
729 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
730 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
733 p_end = section + section_len - 4;
735 if (parse_section_header(h, &p, p_end) < 0)
737 if (h->tid != SDT_TID)
739 onid = get16(&p, p_end);
742 val = get8(&p, p_end);
746 sid = get16(&p, p_end);
749 val = get8(&p, p_end);
752 desc_list_len = get16(&p, p_end) & 0xfff;
753 if (desc_list_len < 0)
755 desc_list_end = p + desc_list_len;
756 if (desc_list_end > p_end)
759 desc_tag = get8(&p, desc_list_end);
762 desc_len = get8(&p, desc_list_end);
763 desc_end = p + desc_len;
764 if (desc_end > desc_list_end)
767 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
772 service_type = get8(&p, p_end);
773 if (service_type < 0)
775 provider_name = getstr8(&p, p_end);
778 name = getstr8(&p, p_end);
780 AVProgram *program = av_new_program(ts->stream, sid);
782 av_set_program_name(program, provider_name, name);
785 av_free(provider_name);
796 /* scan services in a transport stream by looking at the SDT */
797 static void mpegts_scan_sdt(MpegTSContext *ts)
799 mpegts_open_section_filter(ts, SDT_PID,
803 static int64_t get_pts(const uint8_t *p)
805 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
806 pts |= (AV_RB16(p + 1) >> 1) << 15;
807 pts |= AV_RB16(p + 3) >> 1;
811 /* return non zero if a packet could be constructed */
812 static void mpegts_push_data(MpegTSFilter *filter,
813 const uint8_t *buf, int buf_size, int is_start)
815 PESContext *pes = filter->u.pes_filter.opaque;
816 MpegTSContext *ts = pes->ts;
824 pes->state = MPEGTS_HEADER;
828 while (buf_size > 0) {
831 len = PES_START_SIZE - pes->data_index;
834 memcpy(pes->header + pes->data_index, p, len);
835 pes->data_index += len;
838 if (pes->data_index == PES_START_SIZE) {
839 /* we got all the PES or section header. We can now
842 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
844 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
845 pes->header[2] == 0x01) {
846 /* it must be an mpeg2 PES stream */
847 code = pes->header[3] | 0x100;
848 if (!((code >= 0x1c0 && code <= 0x1df) ||
849 (code >= 0x1e0 && code <= 0x1ef) ||
850 (code == 0x1bd) || (code == 0x1fd)))
853 /* allocate stream */
854 new_pes_av_stream(pes, code);
856 pes->state = MPEGTS_PESHEADER_FILL;
857 pes->total_size = AV_RB16(pes->header + 4);
858 /* NOTE: a zero total size means the PES size is
861 pes->total_size += 6;
862 pes->pes_header_size = pes->header[8] + 9;
864 /* otherwise, it should be a table */
867 pes->state = MPEGTS_SKIP;
872 /**********************************************/
873 /* PES packing parsing */
874 case MPEGTS_PESHEADER_FILL:
875 len = pes->pes_header_size - pes->data_index;
878 memcpy(pes->header + pes->data_index, p, len);
879 pes->data_index += len;
882 if (pes->data_index == pes->pes_header_size) {
886 flags = pes->header[7];
888 pes->pts = AV_NOPTS_VALUE;
889 pes->dts = AV_NOPTS_VALUE;
890 if ((flags & 0xc0) == 0x80) {
891 pes->pts = get_pts(r);
893 } else if ((flags & 0xc0) == 0xc0) {
894 pes->pts = get_pts(r);
896 pes->dts = get_pts(r);
899 /* we got the full header. We parse it and get the payload */
900 pes->state = MPEGTS_PAYLOAD;
904 if (pes->total_size) {
905 len = pes->total_size - pes->data_index;
912 AVPacket *pkt = ts->pkt;
913 if (pes->st && av_new_packet(pkt, len) == 0) {
914 memcpy(pkt->data, p, len);
915 pkt->stream_index = pes->st->index;
918 /* reset pts values */
919 pes->pts = AV_NOPTS_VALUE;
920 pes->dts = AV_NOPTS_VALUE;
934 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
937 enum CodecID codec_id;
938 enum CodecType codec_type;
940 switch(pes->stream_type){
941 case STREAM_TYPE_AUDIO_MPEG1:
942 case STREAM_TYPE_AUDIO_MPEG2:
943 codec_type = CODEC_TYPE_AUDIO;
944 codec_id = CODEC_ID_MP3;
946 case STREAM_TYPE_VIDEO_MPEG1:
947 case STREAM_TYPE_VIDEO_MPEG2:
948 codec_type = CODEC_TYPE_VIDEO;
949 codec_id = CODEC_ID_MPEG2VIDEO;
951 case STREAM_TYPE_VIDEO_MPEG4:
952 codec_type = CODEC_TYPE_VIDEO;
953 codec_id = CODEC_ID_MPEG4;
955 case STREAM_TYPE_VIDEO_H264:
956 codec_type = CODEC_TYPE_VIDEO;
957 codec_id = CODEC_ID_H264;
959 case STREAM_TYPE_VIDEO_VC1:
960 codec_type = CODEC_TYPE_VIDEO;
961 codec_id = CODEC_ID_VC1;
963 case STREAM_TYPE_VIDEO_DIRAC:
964 codec_type = CODEC_TYPE_VIDEO;
965 codec_id = CODEC_ID_DIRAC;
967 case STREAM_TYPE_AUDIO_AAC:
968 codec_type = CODEC_TYPE_AUDIO;
969 codec_id = CODEC_ID_AAC;
971 case STREAM_TYPE_AUDIO_AC3:
972 codec_type = CODEC_TYPE_AUDIO;
973 codec_id = CODEC_ID_AC3;
975 case STREAM_TYPE_AUDIO_DTS:
976 case STREAM_TYPE_AUDIO_HDMV_DTS:
977 codec_type = CODEC_TYPE_AUDIO;
978 codec_id = CODEC_ID_DTS;
980 case STREAM_TYPE_SUBTITLE_DVB:
981 codec_type = CODEC_TYPE_SUBTITLE;
982 codec_id = CODEC_ID_DVB_SUBTITLE;
985 if (code >= 0x1c0 && code <= 0x1df) {
986 codec_type = CODEC_TYPE_AUDIO;
987 codec_id = CODEC_ID_MP2;
988 } else if (code == 0x1bd) {
989 codec_type = CODEC_TYPE_AUDIO;
990 codec_id = CODEC_ID_AC3;
992 codec_type = CODEC_TYPE_VIDEO;
993 codec_id = CODEC_ID_PROBE;
997 st = av_new_stream(pes->stream, pes->pid);
999 av_set_pts_info(st, 33, 1, 90000);
1000 st->priv_data = pes;
1001 st->codec->codec_type = codec_type;
1002 st->codec->codec_id = codec_id;
1003 st->need_parsing = AVSTREAM_PARSE_FULL;
1010 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1015 /* if no pid found, then add a pid context */
1016 pes = av_mallocz(sizeof(PESContext));
1020 pes->stream = ts->stream;
1022 pes->pcr_pid = pcr_pid;
1023 pes->stream_type = stream_type;
1024 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1032 /* handle one TS packet */
1033 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1035 AVFormatContext *s = ts->stream;
1037 int len, pid, cc, cc_ok, afc, is_start;
1038 const uint8_t *p, *p_end;
1040 pid = AV_RB16(packet + 1) & 0x1fff;
1041 if(pid && discard_pid(ts, pid))
1043 is_start = packet[1] & 0x40;
1044 tss = ts->pids[pid];
1045 if (ts->auto_guess && tss == NULL && is_start) {
1046 add_pes_stream(ts, pid, -1, 0);
1047 tss = ts->pids[pid];
1052 /* continuity check (currently not used) */
1053 cc = (packet[3] & 0xf);
1054 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1057 /* skip adaptation field */
1058 afc = (packet[3] >> 4) & 3;
1060 if (afc == 0) /* reserved value */
1062 if (afc == 2) /* adaptation field only */
1065 /* skip adapation field */
1068 /* if past the end of packet, ignore */
1069 p_end = packet + TS_PACKET_SIZE;
1073 ts->pos47= url_ftell(ts->stream->pb) % ts->raw_packet_size;
1075 if (tss->type == MPEGTS_SECTION) {
1077 /* pointer field present */
1079 if (p + len > p_end)
1082 /* write remaining section bytes */
1083 write_section_data(s, tss,
1085 /* check whether filter has been closed */
1091 write_section_data(s, tss,
1096 write_section_data(s, tss,
1101 tss->u.pes_filter.pes_cb(tss,
1102 p, p_end - p, is_start);
1106 /* XXX: try to find a better synchro over several packets (use
1107 get_packet_size() ?) */
1108 static int mpegts_resync(ByteIOContext *pb)
1112 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1117 url_fseek(pb, -1, SEEK_CUR);
1125 /* return -1 if error or EOF. Return 0 if OK. */
1126 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1131 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1132 if (len != TS_PACKET_SIZE)
1133 return AVERROR(EIO);
1134 /* check paquet sync byte */
1135 if (buf[0] != 0x47) {
1136 /* find a new packet start */
1137 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1138 if (mpegts_resync(pb) < 0)
1139 return AVERROR_INVALIDDATA;
1143 skip = raw_packet_size - TS_PACKET_SIZE;
1145 url_fskip(pb, skip);
1152 static int handle_packets(MpegTSContext *ts, int nb_packets)
1154 AVFormatContext *s = ts->stream;
1155 ByteIOContext *pb = s->pb;
1156 uint8_t packet[TS_PACKET_SIZE];
1157 int packet_num, ret;
1162 if (ts->stop_parse>0)
1165 if (nb_packets != 0 && packet_num >= nb_packets)
1167 ret = read_packet(pb, packet, ts->raw_packet_size);
1170 handle_packet(ts, packet);
1175 static int mpegts_probe(AVProbeData *p)
1178 const int size= p->buf_size;
1179 int score, fec_score, dvhs_score;
1180 #define CHECK_COUNT 10
1182 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1185 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1186 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1187 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1188 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1190 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1191 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1192 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1193 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1196 /* only use the extension for safer guess */
1197 if (match_ext(p->filename, "ts"))
1198 return AVPROBE_SCORE_MAX;
1204 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1205 (-1) if not available */
1206 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1207 const uint8_t *packet)
1209 int afc, len, flags;
1213 afc = (packet[3] >> 4) & 3;
1223 if (!(flags & 0x10))
1228 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1229 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1233 static int mpegts_read_header(AVFormatContext *s,
1234 AVFormatParameters *ap)
1236 MpegTSContext *ts = s->priv_data;
1237 ByteIOContext *pb = s->pb;
1243 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1244 if(ap->mpeg2ts_raw){
1245 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1250 /* read the first 1024 bytes to get packet size */
1251 pos = url_ftell(pb);
1252 len = get_buffer(pb, buf, sizeof(buf));
1253 if (len != sizeof(buf))
1255 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1256 if (ts->raw_packet_size <= 0)
1261 if (s->iformat == &mpegts_demuxer) {
1264 /* first do a scaning to get all the services */
1265 url_fseek(pb, pos, SEEK_SET);
1266 mpegts_scan_sdt(ts);
1268 mpegts_set_service(ts);
1270 handle_packets(ts, s->probesize);
1271 /* if could not find service, enable auto_guess */
1276 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1278 s->ctx_flags |= AVFMTCTX_NOHEADER;
1281 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1282 int64_t pcrs[2], pcr_h;
1283 int packet_count[2];
1284 uint8_t packet[TS_PACKET_SIZE];
1286 /* only read packets */
1288 st = av_new_stream(s, 0);
1291 av_set_pts_info(st, 60, 1, 27000000);
1292 st->codec->codec_type = CODEC_TYPE_DATA;
1293 st->codec->codec_id = CODEC_ID_MPEG2TS;
1295 /* we iterate until we find two PCRs to estimate the bitrate */
1300 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1303 pid = AV_RB16(packet + 1) & 0x1fff;
1304 if ((pcr_pid == -1 || pcr_pid == pid) &&
1305 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1307 packet_count[nb_pcrs] = nb_packets;
1308 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1316 /* NOTE1: the bitrate is computed without the FEC */
1317 /* NOTE2: it is only the bitrate of the start of the stream */
1318 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1319 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1320 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1321 st->codec->bit_rate = s->bit_rate;
1322 st->start_time = ts->cur_pcr;
1324 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1325 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1329 url_fseek(pb, pos, SEEK_SET);
1335 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1337 static int mpegts_raw_read_packet(AVFormatContext *s,
1340 MpegTSContext *ts = s->priv_data;
1342 int64_t pcr_h, next_pcr_h, pos;
1343 int pcr_l, next_pcr_l;
1344 uint8_t pcr_buf[12];
1346 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1347 return AVERROR(ENOMEM);
1348 pkt->pos= url_ftell(s->pb);
1349 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1351 av_free_packet(pkt);
1354 if (ts->mpeg2ts_compute_pcr) {
1355 /* compute exact PCR for each packet */
1356 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1357 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1358 pos = url_ftell(s->pb);
1359 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1360 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1361 get_buffer(s->pb, pcr_buf, 12);
1362 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1363 /* XXX: not precise enough */
1364 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1369 url_fseek(s->pb, pos, SEEK_SET);
1370 /* no next PCR found: we use previous increment */
1371 ts->cur_pcr = pcr_h * 300 + pcr_l;
1373 pkt->pts = ts->cur_pcr;
1374 pkt->duration = ts->pcr_incr;
1375 ts->cur_pcr += ts->pcr_incr;
1377 pkt->stream_index = 0;
1381 static int mpegts_read_packet(AVFormatContext *s,
1384 MpegTSContext *ts = s->priv_data;
1387 return handle_packets(ts, 0);
1390 static int mpegts_read_close(AVFormatContext *s)
1392 MpegTSContext *ts = s->priv_data;
1397 for(i=0;i<NB_PID_MAX;i++)
1398 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1403 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1404 int64_t *ppos, int64_t pos_limit)
1406 MpegTSContext *ts = s->priv_data;
1407 int64_t pos, timestamp;
1408 uint8_t buf[TS_PACKET_SIZE];
1409 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1410 const int find_next= 1;
1411 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1414 url_fseek(s->pb, pos, SEEK_SET);
1415 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1416 return AV_NOPTS_VALUE;
1417 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1418 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1421 pos += ts->raw_packet_size;
1425 pos -= ts->raw_packet_size;
1427 return AV_NOPTS_VALUE;
1428 url_fseek(s->pb, pos, SEEK_SET);
1429 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1430 return AV_NOPTS_VALUE;
1431 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1432 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1442 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1443 MpegTSContext *ts = s->priv_data;
1444 uint8_t buf[TS_PACKET_SIZE];
1447 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1450 pos= url_ftell(s->pb);
1453 url_fseek(s->pb, pos, SEEK_SET);
1454 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1456 // pid = AV_RB16(buf + 1) & 0x1fff;
1457 if(buf[1] & 0x40) break;
1458 pos += ts->raw_packet_size;
1460 url_fseek(s->pb, pos, SEEK_SET);
1465 /**************************************************************/
1466 /* parsing functions - called from other demuxers such as RTP */
1468 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1472 ts = av_mallocz(sizeof(MpegTSContext));
1475 /* no stream case, currently used by RTP */
1476 ts->raw_packet_size = TS_PACKET_SIZE;
1482 /* return the consumed length if a packet was output, or -1 if no
1484 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1485 const uint8_t *buf, int len)
1493 if (ts->stop_parse>0)
1495 if (len < TS_PACKET_SIZE)
1497 if (buf[0] != 0x47) {
1501 handle_packet(ts, buf);
1502 buf += TS_PACKET_SIZE;
1503 len -= TS_PACKET_SIZE;
1509 void mpegts_parse_close(MpegTSContext *ts)
1513 for(i=0;i<NB_PID_MAX;i++)
1514 av_free(ts->pids[i]);
1518 AVInputFormat mpegts_demuxer = {
1520 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1521 sizeof(MpegTSContext),
1528 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1531 AVInputFormat mpegtsraw_demuxer = {
1533 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1534 sizeof(MpegTSContext),
1537 mpegts_raw_read_packet,
1541 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,