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"
24 #include "libavcodec/bytestream.h"
32 /* 1.0 second at 24Mbit/s */
33 #define MAX_SCAN_PACKETS 32000
35 /* maximum size in which we look for synchronisation if
36 synchronisation is lost */
37 #define MAX_RESYNC_SIZE 4096
38 #define REGISTRATION_DESCRIPTOR 5
40 typedef struct PESContext PESContext;
42 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type);
43 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
45 enum MpegTSFilterType {
50 typedef struct MpegTSFilter MpegTSFilter;
52 typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
54 typedef struct MpegTSPESFilter {
59 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
61 typedef void SetServiceCallback(void *opaque, int ret);
63 typedef struct MpegTSSectionFilter {
67 unsigned int check_crc:1;
68 unsigned int end_of_section_reached:1;
69 SectionCallback *section_cb;
71 } MpegTSSectionFilter;
75 int last_cc; /* last cc code (-1 if first packet) */
76 enum MpegTSFilterType type;
78 MpegTSPESFilter pes_filter;
79 MpegTSSectionFilter section_filter;
83 #define MAX_PIDS_PER_PROGRAM 64
85 unsigned int id; //program id/service id
87 unsigned int pids[MAX_PIDS_PER_PROGRAM];
90 struct MpegTSContext {
92 AVFormatContext *stream;
93 /** raw packet size, including FEC if present */
98 /** if true, all pids are analyzed to find streams */
101 /** compute exact PCR for each transport stream packet */
102 int mpeg2ts_compute_pcr;
104 int64_t cur_pcr; /**< used to estimate the exact PCR */
105 int pcr_incr; /**< used to estimate the exact PCR */
107 /* data needed to handle file based ts */
108 /** stop parsing loop */
110 /** packet containing Audio/Video data */
113 /******************************************/
114 /* private mpegts data */
116 /** structure to keep track of Program->pids mapping */
121 /** filters for various streams specified by PMT + for the PAT and PMT */
122 MpegTSFilter *pids[NB_PID_MAX];
125 /* TS stream handling */
129 MPEGTS_PESHEADER_FILL,
134 /* enough for PES header + length */
135 #define PES_START_SIZE 9
136 #define MAX_PES_HEADER_SIZE (9 + 255)
140 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
143 AVFormatContext *stream;
145 enum MpegTSState state;
146 /* used to get the format */
151 int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
152 uint8_t header[MAX_PES_HEADER_SIZE];
155 extern AVInputFormat mpegts_demuxer;
157 static void clear_program(MpegTSContext *ts, unsigned int programid)
161 for(i=0; i<ts->nb_prg; i++)
162 if(ts->prg[i].id == programid)
163 ts->prg[i].nb_pids = 0;
166 static void clear_programs(MpegTSContext *ts)
172 static void add_pat_entry(MpegTSContext *ts, unsigned int programid)
175 void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
179 p = &ts->prg[ts->nb_prg];
185 static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
188 struct Program *p = NULL;
189 for(i=0; i<ts->nb_prg; i++) {
190 if(ts->prg[i].id == programid) {
198 if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
200 p->pids[p->nb_pids++] = pid;
204 * \brief discard_pid() decides if the pid is to be discarded according
205 * to caller's programs selection
206 * \param ts : - TS context
208 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
211 static int discard_pid(MpegTSContext *ts, unsigned int pid)
214 int used = 0, discarded = 0;
216 for(i=0; i<ts->nb_prg; i++) {
218 for(j=0; j<p->nb_pids; j++) {
219 if(p->pids[j] != pid)
221 //is program with id p->id set to be discarded?
222 for(k=0; k<ts->stream->nb_programs; k++) {
223 if(ts->stream->programs[k]->id == p->id) {
224 if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
233 return !used && discarded;
237 * Assembles PES packets out of TS packets, and then calls the "section_cb"
238 * function when they are complete.
240 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
241 const uint8_t *buf, int buf_size, int is_start)
243 MpegTSSectionFilter *tss = &tss1->u.section_filter;
247 memcpy(tss->section_buf, buf, buf_size);
248 tss->section_index = buf_size;
249 tss->section_h_size = -1;
250 tss->end_of_section_reached = 0;
252 if (tss->end_of_section_reached)
254 len = 4096 - tss->section_index;
257 memcpy(tss->section_buf + tss->section_index, buf, len);
258 tss->section_index += len;
261 /* compute section length if possible */
262 if (tss->section_h_size == -1 && tss->section_index >= 3) {
263 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
266 tss->section_h_size = len;
269 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
270 tss->end_of_section_reached = 1;
271 if (!tss->check_crc ||
272 av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
273 tss->section_buf, tss->section_h_size) == 0)
274 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
278 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
279 SectionCallback *section_cb, void *opaque,
283 MpegTSFilter *filter;
284 MpegTSSectionFilter *sec;
287 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
289 if (pid >= NB_PID_MAX || ts->pids[pid])
291 filter = av_mallocz(sizeof(MpegTSFilter));
294 ts->pids[pid] = filter;
295 filter->type = MPEGTS_SECTION;
297 filter->last_cc = -1;
298 sec = &filter->u.section_filter;
299 sec->section_cb = section_cb;
300 sec->opaque = opaque;
301 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
302 sec->check_crc = check_crc;
303 if (!sec->section_buf) {
310 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
314 MpegTSFilter *filter;
315 MpegTSPESFilter *pes;
317 if (pid >= NB_PID_MAX || ts->pids[pid])
319 filter = av_mallocz(sizeof(MpegTSFilter));
322 ts->pids[pid] = filter;
323 filter->type = MPEGTS_PES;
325 filter->last_cc = -1;
326 pes = &filter->u.pes_filter;
327 pes->pes_cb = pes_cb;
328 pes->opaque = opaque;
332 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
337 if (filter->type == MPEGTS_SECTION)
338 av_freep(&filter->u.section_filter.section_buf);
339 else if (filter->type == MPEGTS_PES) {
340 /* referenced private data will be freed later in
341 * av_close_input_stream */
342 if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
343 av_freep(&filter->u.pes_filter.opaque);
348 ts->pids[pid] = NULL;
351 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
352 int stat[packet_size];
357 memset(stat, 0, packet_size*sizeof(int));
359 for(x=i=0; i<size-3; i++){
360 if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && (buf[i+3] & 0x30)){
362 if(stat[x] > best_score){
369 if(x == packet_size) x= 0;
375 /* autodetect fec presence. Must have at least 1024 bytes */
376 static int get_packet_size(const uint8_t *buf, int size)
378 int score, fec_score, dvhs_score;
380 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
383 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
384 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
385 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
386 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
388 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
389 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
390 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
394 typedef struct SectionHeader {
399 uint8_t last_sec_num;
402 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
415 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
421 if ((p + 1) >= p_end)
429 /* read and allocate a DVB string preceeded by its length */
430 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
437 len = get8(&p, p_end);
440 if ((p + len) > p_end)
442 str = av_malloc(len + 1);
452 static int parse_section_header(SectionHeader *h,
453 const uint8_t **pp, const uint8_t *p_end)
457 val = get8(pp, p_end);
462 val = get16(pp, p_end);
466 val = get8(pp, p_end);
469 h->version = (val >> 1) & 0x1f;
470 val = get8(pp, p_end);
474 val = get8(pp, p_end);
477 h->last_sec_num = val;
482 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
484 MpegTSContext *ts = filter->u.section_filter.opaque;
485 SectionHeader h1, *h = &h1;
488 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
489 int program_info_length, pcr_pid, pid, stream_type;
490 int desc_list_len, desc_len, desc_tag;
491 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
492 char language[4] = {0}; /* initialize to kill warnings */
493 int has_hdmv_descr = 0;
494 int has_dirac_descr = 0;
495 uint32_t reg_desc = 0; /* registration descriptor */
498 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
499 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
501 p_end = section + section_len - 4;
503 if (parse_section_header(h, &p, p_end) < 0)
506 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
507 h->id, h->sec_num, h->last_sec_num);
509 if (h->tid != PMT_TID)
512 clear_program(ts, h->id);
513 pcr_pid = get16(&p, p_end) & 0x1fff;
516 add_pid_to_pmt(ts, h->id, pcr_pid);
518 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
520 program_info_length = get16(&p, p_end) & 0xfff;
521 if (program_info_length < 0)
523 while(program_info_length >= 2) {
525 tag = get8(&p, p_end);
526 len = get8(&p, p_end);
527 if(len > program_info_length - 2)
528 //something else is broken, exit the program_descriptors_loop
530 program_info_length -= len + 2;
531 if(tag == REGISTRATION_DESCRIPTOR && len >= 4) {
532 reg_desc = bytestream_get_le32(&p);
534 if(reg_desc == AV_RL32("HDMV"))
539 p += program_info_length;
545 stream_type = get8(&p, p_end);
548 pid = get16(&p, p_end) & 0x1fff;
551 desc_list_len = get16(&p, p_end) & 0xfff;
552 if (desc_list_len < 0)
554 desc_list_end = p + desc_list_len;
555 if (desc_list_end > p_end)
558 desc_tag = get8(&p, desc_list_end);
561 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
562 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
563 /*assume DVB AC-3 Audio*/
564 stream_type = STREAM_TYPE_AUDIO_AC3;
565 } else if(desc_tag == 0x7B) {
567 stream_type = STREAM_TYPE_AUDIO_DTS;
570 desc_len = get8(&p, desc_list_end);
573 desc_end = p + desc_len;
574 if (desc_end > desc_list_end)
577 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
581 case DVB_SUBT_DESCID:
582 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
583 stream_type = STREAM_TYPE_SUBTITLE_DVB;
585 language[0] = get8(&p, desc_end);
586 language[1] = get8(&p, desc_end);
587 language[2] = get8(&p, desc_end);
590 comp_page = get16(&p, desc_end);
591 anc_page = get16(&p, desc_end);
594 case 0x0a: /* ISO 639 language descriptor */
595 language[0] = get8(&p, desc_end);
596 language[1] = get8(&p, desc_end);
597 language[2] = get8(&p, desc_end);
600 case REGISTRATION_DESCRIPTOR: /*MPEG-2 Registration descriptor */
601 reg_desc = bytestream_get_le32(&p);
602 if(reg_desc == AV_RL32("drac"))
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 av_metadata_set(&st->metadata, "language", language);
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_metadata_set(&program->metadata, "name", name);
783 av_metadata_set(&program->metadata, "provider_name", provider_name);
787 av_free(provider_name);
798 /* scan services in a transport stream by looking at the SDT */
799 static void mpegts_scan_sdt(MpegTSContext *ts)
801 mpegts_open_section_filter(ts, SDT_PID,
805 static int64_t get_pts(const uint8_t *p)
807 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
808 pts |= (AV_RB16(p + 1) >> 1) << 15;
809 pts |= AV_RB16(p + 3) >> 1;
813 /* return non zero if a packet could be constructed */
814 static void mpegts_push_data(MpegTSFilter *filter,
815 const uint8_t *buf, int buf_size, int is_start,
818 PESContext *pes = filter->u.pes_filter.opaque;
819 MpegTSContext *ts = pes->ts;
827 pes->state = MPEGTS_HEADER;
829 pes->ts_packet_pos = pos;
832 while (buf_size > 0) {
835 len = PES_START_SIZE - pes->data_index;
838 memcpy(pes->header + pes->data_index, p, len);
839 pes->data_index += len;
842 if (pes->data_index == PES_START_SIZE) {
843 /* we got all the PES or section header. We can now
846 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
848 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
849 pes->header[2] == 0x01) {
850 /* it must be an mpeg2 PES stream */
851 code = pes->header[3] | 0x100;
853 !((code >= 0x1c0 && code <= 0x1df) ||
854 (code >= 0x1e0 && code <= 0x1ef) ||
855 (code == 0x1bd) || (code == 0x1fd)))
857 pes->state = MPEGTS_PESHEADER_FILL;
858 pes->total_size = AV_RB16(pes->header + 4);
859 /* NOTE: a zero total size means the PES size is
862 pes->total_size += 6;
863 pes->pes_header_size = pes->header[8] + 9;
865 /* otherwise, it should be a table */
868 pes->state = MPEGTS_SKIP;
873 /**********************************************/
874 /* PES packing parsing */
875 case MPEGTS_PESHEADER_FILL:
876 len = pes->pes_header_size - pes->data_index;
879 memcpy(pes->header + pes->data_index, p, len);
880 pes->data_index += len;
883 if (pes->data_index == pes->pes_header_size) {
887 flags = pes->header[7];
889 pes->pts = AV_NOPTS_VALUE;
890 pes->dts = AV_NOPTS_VALUE;
891 if ((flags & 0xc0) == 0x80) {
892 pes->dts = pes->pts = get_pts(r);
894 } else if ((flags & 0xc0) == 0xc0) {
895 pes->pts = get_pts(r);
897 pes->dts = get_pts(r);
900 /* we got the full header. We parse it and get the payload */
901 pes->state = MPEGTS_PAYLOAD;
905 if (pes->total_size) {
906 len = pes->total_size - pes->data_index;
913 AVPacket *pkt = ts->pkt;
914 if (pes->st && av_new_packet(pkt, len) == 0) {
915 memcpy(pkt->data, p, len);
916 pkt->stream_index = pes->st->index;
919 /* store position of first TS packet of this PES packet */
920 pkt->pos = pes->ts_packet_pos;
921 /* reset pts values */
922 pes->pts = AV_NOPTS_VALUE;
923 pes->dts = AV_NOPTS_VALUE;
937 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
940 enum CodecID codec_id;
941 enum CodecType codec_type;
943 switch(pes->stream_type){
944 case STREAM_TYPE_AUDIO_MPEG1:
945 case STREAM_TYPE_AUDIO_MPEG2:
946 codec_type = CODEC_TYPE_AUDIO;
947 codec_id = CODEC_ID_MP3;
949 case STREAM_TYPE_VIDEO_MPEG1:
950 case STREAM_TYPE_VIDEO_MPEG2:
951 codec_type = CODEC_TYPE_VIDEO;
952 codec_id = CODEC_ID_MPEG2VIDEO;
954 case STREAM_TYPE_VIDEO_MPEG4:
955 codec_type = CODEC_TYPE_VIDEO;
956 codec_id = CODEC_ID_MPEG4;
958 case STREAM_TYPE_VIDEO_H264:
959 codec_type = CODEC_TYPE_VIDEO;
960 codec_id = CODEC_ID_H264;
962 case STREAM_TYPE_VIDEO_VC1:
963 codec_type = CODEC_TYPE_VIDEO;
964 codec_id = CODEC_ID_VC1;
966 case STREAM_TYPE_VIDEO_DIRAC:
967 codec_type = CODEC_TYPE_VIDEO;
968 codec_id = CODEC_ID_DIRAC;
970 case STREAM_TYPE_AUDIO_AAC:
971 codec_type = CODEC_TYPE_AUDIO;
972 codec_id = CODEC_ID_AAC;
974 case STREAM_TYPE_AUDIO_AC3:
975 codec_type = CODEC_TYPE_AUDIO;
976 codec_id = CODEC_ID_AC3;
978 case STREAM_TYPE_AUDIO_DTS:
979 case STREAM_TYPE_AUDIO_HDMV_DTS:
980 codec_type = CODEC_TYPE_AUDIO;
981 codec_id = CODEC_ID_DTS;
983 case STREAM_TYPE_SUBTITLE_DVB:
984 codec_type = CODEC_TYPE_SUBTITLE;
985 codec_id = CODEC_ID_DVB_SUBTITLE;
988 if (code >= 0x1c0 && code <= 0x1df) {
989 codec_type = CODEC_TYPE_AUDIO;
990 codec_id = CODEC_ID_MP2;
991 } else if (code == 0x1bd) {
992 codec_type = CODEC_TYPE_AUDIO;
993 codec_id = CODEC_ID_AC3;
995 codec_type = CODEC_TYPE_VIDEO;
996 codec_id = CODEC_ID_PROBE;
1000 st = av_new_stream(pes->stream, pes->pid);
1002 av_set_pts_info(st, 33, 1, 90000);
1003 st->priv_data = pes;
1004 st->codec->codec_type = codec_type;
1005 st->codec->codec_id = codec_id;
1006 st->need_parsing = AVSTREAM_PARSE_FULL;
1013 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
1018 /* if no pid found, then add a pid context */
1019 pes = av_mallocz(sizeof(PESContext));
1023 pes->stream = ts->stream;
1025 pes->pcr_pid = pcr_pid;
1026 pes->stream_type = stream_type;
1027 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
1035 /* handle one TS packet */
1036 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
1038 AVFormatContext *s = ts->stream;
1040 int len, pid, cc, cc_ok, afc, is_start;
1041 const uint8_t *p, *p_end;
1044 pid = AV_RB16(packet + 1) & 0x1fff;
1045 if(pid && discard_pid(ts, pid))
1047 is_start = packet[1] & 0x40;
1048 tss = ts->pids[pid];
1049 if (ts->auto_guess && tss == NULL && is_start) {
1050 add_pes_stream(ts, pid, -1, 0);
1051 tss = ts->pids[pid];
1056 /* continuity check (currently not used) */
1057 cc = (packet[3] & 0xf);
1058 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1061 /* skip adaptation field */
1062 afc = (packet[3] >> 4) & 3;
1064 if (afc == 0) /* reserved value */
1066 if (afc == 2) /* adaptation field only */
1069 /* skip adapation field */
1072 /* if past the end of packet, ignore */
1073 p_end = packet + TS_PACKET_SIZE;
1077 pos = url_ftell(ts->stream->pb);
1078 ts->pos47= pos % ts->raw_packet_size;
1080 if (tss->type == MPEGTS_SECTION) {
1082 /* pointer field present */
1084 if (p + len > p_end)
1087 /* write remaining section bytes */
1088 write_section_data(s, tss,
1090 /* check whether filter has been closed */
1096 write_section_data(s, tss,
1101 write_section_data(s, tss,
1106 // Note: The position here points actually behind the current packet.
1107 tss->u.pes_filter.pes_cb(tss,
1108 p, p_end - p, is_start, pos - ts->raw_packet_size);
1112 /* XXX: try to find a better synchro over several packets (use
1113 get_packet_size() ?) */
1114 static int mpegts_resync(ByteIOContext *pb)
1118 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1123 url_fseek(pb, -1, SEEK_CUR);
1131 /* return -1 if error or EOF. Return 0 if OK. */
1132 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1137 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1138 if (len != TS_PACKET_SIZE)
1139 return AVERROR(EIO);
1140 /* check paquet sync byte */
1141 if (buf[0] != 0x47) {
1142 /* find a new packet start */
1143 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1144 if (mpegts_resync(pb) < 0)
1145 return AVERROR_INVALIDDATA;
1149 skip = raw_packet_size - TS_PACKET_SIZE;
1151 url_fskip(pb, skip);
1158 static int handle_packets(MpegTSContext *ts, int nb_packets)
1160 AVFormatContext *s = ts->stream;
1161 ByteIOContext *pb = s->pb;
1162 uint8_t packet[TS_PACKET_SIZE];
1163 int packet_num, ret;
1168 if (ts->stop_parse>0)
1171 if (nb_packets != 0 && packet_num >= nb_packets)
1173 ret = read_packet(pb, packet, ts->raw_packet_size);
1176 handle_packet(ts, packet);
1181 static int mpegts_probe(AVProbeData *p)
1184 const int size= p->buf_size;
1185 int score, fec_score, dvhs_score;
1186 int check_count= size / TS_FEC_PACKET_SIZE;
1187 #define CHECK_COUNT 10
1189 if (check_count < CHECK_COUNT)
1192 score = analyze(p->buf, TS_PACKET_SIZE *check_count, TS_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1193 dvhs_score= analyze(p->buf, TS_DVHS_PACKET_SIZE*check_count, TS_DVHS_PACKET_SIZE, NULL)*CHECK_COUNT/check_count;
1194 fec_score = analyze(p->buf, TS_FEC_PACKET_SIZE *check_count, TS_FEC_PACKET_SIZE , NULL)*CHECK_COUNT/check_count;
1195 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1197 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1198 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1199 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1200 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1203 /* only use the extension for safer guess */
1204 if (match_ext(p->filename, "ts"))
1205 return AVPROBE_SCORE_MAX;
1211 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1212 (-1) if not available */
1213 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1214 const uint8_t *packet)
1216 int afc, len, flags;
1220 afc = (packet[3] >> 4) & 3;
1230 if (!(flags & 0x10))
1235 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1236 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1240 static int mpegts_read_header(AVFormatContext *s,
1241 AVFormatParameters *ap)
1243 MpegTSContext *ts = s->priv_data;
1244 ByteIOContext *pb = s->pb;
1245 uint8_t buf[5*1024];
1250 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1251 if(ap->mpeg2ts_raw){
1252 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1257 /* read the first 1024 bytes to get packet size */
1258 pos = url_ftell(pb);
1259 len = get_buffer(pb, buf, sizeof(buf));
1260 if (len != sizeof(buf))
1262 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1263 if (ts->raw_packet_size <= 0)
1268 if (s->iformat == &mpegts_demuxer) {
1271 /* first do a scaning to get all the services */
1272 url_fseek(pb, pos, SEEK_SET);
1273 mpegts_scan_sdt(ts);
1275 mpegts_set_service(ts);
1277 handle_packets(ts, s->probesize);
1278 /* if could not find service, enable auto_guess */
1283 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1285 s->ctx_flags |= AVFMTCTX_NOHEADER;
1288 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1289 int64_t pcrs[2], pcr_h;
1290 int packet_count[2];
1291 uint8_t packet[TS_PACKET_SIZE];
1293 /* only read packets */
1295 st = av_new_stream(s, 0);
1298 av_set_pts_info(st, 60, 1, 27000000);
1299 st->codec->codec_type = CODEC_TYPE_DATA;
1300 st->codec->codec_id = CODEC_ID_MPEG2TS;
1302 /* we iterate until we find two PCRs to estimate the bitrate */
1307 ret = read_packet(s->pb, packet, ts->raw_packet_size);
1310 pid = AV_RB16(packet + 1) & 0x1fff;
1311 if ((pcr_pid == -1 || pcr_pid == pid) &&
1312 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1314 packet_count[nb_pcrs] = nb_packets;
1315 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1323 /* NOTE1: the bitrate is computed without the FEC */
1324 /* NOTE2: it is only the bitrate of the start of the stream */
1325 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1326 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1327 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1328 st->codec->bit_rate = s->bit_rate;
1329 st->start_time = ts->cur_pcr;
1331 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1332 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1336 url_fseek(pb, pos, SEEK_SET);
1342 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1344 static int mpegts_raw_read_packet(AVFormatContext *s,
1347 MpegTSContext *ts = s->priv_data;
1349 int64_t pcr_h, next_pcr_h, pos;
1350 int pcr_l, next_pcr_l;
1351 uint8_t pcr_buf[12];
1353 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1354 return AVERROR(ENOMEM);
1355 pkt->pos= url_ftell(s->pb);
1356 ret = read_packet(s->pb, pkt->data, ts->raw_packet_size);
1358 av_free_packet(pkt);
1361 if (ts->mpeg2ts_compute_pcr) {
1362 /* compute exact PCR for each packet */
1363 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1364 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1365 pos = url_ftell(s->pb);
1366 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1367 url_fseek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1368 get_buffer(s->pb, pcr_buf, 12);
1369 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1370 /* XXX: not precise enough */
1371 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1376 url_fseek(s->pb, pos, SEEK_SET);
1377 /* no next PCR found: we use previous increment */
1378 ts->cur_pcr = pcr_h * 300 + pcr_l;
1380 pkt->pts = ts->cur_pcr;
1381 pkt->duration = ts->pcr_incr;
1382 ts->cur_pcr += ts->pcr_incr;
1384 pkt->stream_index = 0;
1388 static int mpegts_read_packet(AVFormatContext *s,
1391 MpegTSContext *ts = s->priv_data;
1394 return handle_packets(ts, 0);
1397 static int mpegts_read_close(AVFormatContext *s)
1399 MpegTSContext *ts = s->priv_data;
1404 for(i=0;i<NB_PID_MAX;i++)
1405 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1410 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1411 int64_t *ppos, int64_t pos_limit)
1413 MpegTSContext *ts = s->priv_data;
1414 int64_t pos, timestamp;
1415 uint8_t buf[TS_PACKET_SIZE];
1416 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1417 const int find_next= 1;
1418 pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
1421 url_fseek(s->pb, pos, SEEK_SET);
1422 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1423 return AV_NOPTS_VALUE;
1424 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1425 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1428 pos += ts->raw_packet_size;
1432 pos -= ts->raw_packet_size;
1434 return AV_NOPTS_VALUE;
1435 url_fseek(s->pb, pos, SEEK_SET);
1436 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1437 return AV_NOPTS_VALUE;
1438 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1439 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1449 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1450 MpegTSContext *ts = s->priv_data;
1451 uint8_t buf[TS_PACKET_SIZE];
1454 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1457 pos= url_ftell(s->pb);
1460 url_fseek(s->pb, pos, SEEK_SET);
1461 if (get_buffer(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1463 // pid = AV_RB16(buf + 1) & 0x1fff;
1464 if(buf[1] & 0x40) break;
1465 pos += ts->raw_packet_size;
1467 url_fseek(s->pb, pos, SEEK_SET);
1472 /**************************************************************/
1473 /* parsing functions - called from other demuxers such as RTP */
1475 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1479 ts = av_mallocz(sizeof(MpegTSContext));
1482 /* no stream case, currently used by RTP */
1483 ts->raw_packet_size = TS_PACKET_SIZE;
1489 /* return the consumed length if a packet was output, or -1 if no
1491 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1492 const uint8_t *buf, int len)
1500 if (ts->stop_parse>0)
1502 if (len < TS_PACKET_SIZE)
1504 if (buf[0] != 0x47) {
1508 handle_packet(ts, buf);
1509 buf += TS_PACKET_SIZE;
1510 len -= TS_PACKET_SIZE;
1516 void mpegts_parse_close(MpegTSContext *ts)
1520 for(i=0;i<NB_PID_MAX;i++)
1521 av_free(ts->pids[i]);
1525 AVInputFormat mpegts_demuxer = {
1527 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1528 sizeof(MpegTSContext),
1535 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
1538 AVInputFormat mpegtsraw_demuxer = {
1540 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1541 sizeof(MpegTSContext),
1544 mpegts_raw_read_packet,
1548 .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,