2 * MPEG2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard.
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 /* 1.0 second at 24Mbit/s */
29 #define MAX_SCAN_PACKETS 32000
31 /* maximum size in which we look for synchronisation if
32 synchronisation is lost */
33 #define MAX_RESYNC_SIZE 4096
35 typedef struct PESContext PESContext;
37 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
38 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
40 enum MpegTSFilterType {
45 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
47 typedef struct MpegTSPESFilter {
52 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
54 typedef void SetServiceCallback(void *opaque, int ret);
56 typedef struct MpegTSSectionFilter {
61 int end_of_section_reached:1;
62 SectionCallback *section_cb;
64 } MpegTSSectionFilter;
66 typedef struct MpegTSFilter {
68 int last_cc; /* last cc code (-1 if first packet) */
69 enum MpegTSFilterType type;
71 MpegTSPESFilter pes_filter;
72 MpegTSSectionFilter section_filter;
76 typedef struct MpegTSService {
78 int sid; /**< MPEG Program Number of stream */
79 char *provider_name; /**< DVB Network name, "" if not DVB stream */
80 char *name; /**< DVB Service name, "MPEG Program [sid]" if not DVB stream*/
83 struct MpegTSContext {
85 AVFormatContext *stream;
86 /** raw packet size, including FEC if present */
88 /** if true, all pids are analyzed to find streams */
92 /** force raw MPEG2 transport stream output, if possible */
94 /** compute exact PCR for each transport stream packet */
95 int mpeg2ts_compute_pcr;
97 int64_t cur_pcr; /**< used to estimate the exact PCR */
98 int pcr_incr; /**< used to estimate the exact PCR */
99 int pcr_pid; /**< used to estimate the exact PCR */
101 /* data needed to handle file based ts */
102 /** stop parsing loop */
104 /** packet containing Audio/Video data */
107 /******************************************/
108 /* private mpegts data */
110 MpegTSFilter *sdt_filter;
111 /** number of PMTs in the last PAT seen */
113 /** list of PMTs in the last PAT seen */
114 MpegTSService **services;
116 /* set service context (XXX: allocated it ?) */
117 SetServiceCallback *set_service_cb;
118 void *set_service_opaque;
119 /** filter for the PAT */
120 MpegTSFilter *pat_filter;
121 /** filter for the PMT for the MPEG program number specified by req_sid */
122 MpegTSFilter *pmt_filter;
123 /** MPEG program number of stream we want to decode */
126 /** filters for various streams specified by PMT + for the PAT and PMT */
127 MpegTSFilter *pids[NB_PID_MAX];
131 * Assembles PES packets out of TS packets, and then calls the "section_cb"
132 * function when they are complete.
134 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
135 const uint8_t *buf, int buf_size, int is_start)
137 MpegTSSectionFilter *tss = &tss1->u.section_filter;
141 memcpy(tss->section_buf, buf, buf_size);
142 tss->section_index = buf_size;
143 tss->section_h_size = -1;
144 tss->end_of_section_reached = 0;
146 if (tss->end_of_section_reached)
148 len = 4096 - tss->section_index;
151 memcpy(tss->section_buf + tss->section_index, buf, len);
152 tss->section_index += len;
155 /* compute section length if possible */
156 if (tss->section_h_size == -1 && tss->section_index >= 3) {
157 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
160 tss->section_h_size = len;
163 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
164 tss->end_of_section_reached = 1;
165 if (!tss->check_crc ||
166 av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
167 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
171 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
172 SectionCallback *section_cb, void *opaque,
176 MpegTSFilter *filter;
177 MpegTSSectionFilter *sec;
180 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
182 if (pid >= NB_PID_MAX || ts->pids[pid])
184 filter = av_mallocz(sizeof(MpegTSFilter));
187 ts->pids[pid] = filter;
188 filter->type = MPEGTS_SECTION;
190 filter->last_cc = -1;
191 sec = &filter->u.section_filter;
192 sec->section_cb = section_cb;
193 sec->opaque = opaque;
194 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
195 sec->check_crc = check_crc;
196 if (!sec->section_buf) {
203 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
207 MpegTSFilter *filter;
208 MpegTSPESFilter *pes;
210 if (pid >= NB_PID_MAX || ts->pids[pid])
212 filter = av_mallocz(sizeof(MpegTSFilter));
215 ts->pids[pid] = filter;
216 filter->type = MPEGTS_PES;
218 filter->last_cc = -1;
219 pes = &filter->u.pes_filter;
220 pes->pes_cb = pes_cb;
221 pes->opaque = opaque;
225 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
230 if (filter->type == MPEGTS_SECTION)
231 av_freep(&filter->u.section_filter.section_buf);
232 else if (filter->type == MPEGTS_PES)
233 av_freep(&filter->u.pes_filter.opaque);
236 ts->pids[pid] = NULL;
239 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
240 int stat[packet_size];
245 memset(stat, 0, packet_size*sizeof(int));
247 for(x=i=0; i<size; i++){
250 if(stat[x] > best_score){
257 if(x == packet_size) x= 0;
263 /* autodetect fec presence. Must have at least 1024 bytes */
264 static int get_packet_size(const uint8_t *buf, int size)
266 int score, fec_score, dvhs_score;
268 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
271 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
272 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
273 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
274 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
276 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
277 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
278 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
282 typedef struct SectionHeader {
287 uint8_t last_sec_num;
290 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
303 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
309 if ((p + 1) >= p_end)
311 c = (p[0] << 8) | p[1];
317 /* read and allocate a DVB string preceeded by its length */
318 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
325 len = get8(&p, p_end);
328 if ((p + len) > p_end)
330 str = av_malloc(len + 1);
340 static int parse_section_header(SectionHeader *h,
341 const uint8_t **pp, const uint8_t *p_end)
345 val = get8(pp, p_end);
350 val = get16(pp, p_end);
354 val = get8(pp, p_end);
357 h->version = (val >> 1) & 0x1f;
358 val = get8(pp, p_end);
362 val = get8(pp, p_end);
365 h->last_sec_num = val;
369 static MpegTSService *new_service(MpegTSContext *ts, int sid,
370 char *provider_name, char *name)
372 MpegTSService *service;
375 av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
376 "sid=0x%04x provider='%s' name='%s'\n",
377 sid, provider_name, name);
380 service = av_mallocz(sizeof(MpegTSService));
384 service->provider_name = provider_name;
385 service->name = name;
386 dynarray_add(&ts->services, &ts->nb_services, service);
390 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
392 MpegTSContext *ts = opaque;
393 SectionHeader h1, *h = &h1;
396 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
397 int program_info_length, pcr_pid, pid, stream_type;
398 int desc_list_len, desc_len, desc_tag;
399 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
403 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
404 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
406 p_end = section + section_len - 4;
408 if (parse_section_header(h, &p, p_end) < 0)
411 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
412 h->id, h->sec_num, h->last_sec_num);
414 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
417 pcr_pid = get16(&p, p_end) & 0x1fff;
420 ts->pcr_pid = pcr_pid;
422 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
424 program_info_length = get16(&p, p_end) & 0xfff;
425 if (program_info_length < 0)
427 p += program_info_length;
433 stream_type = get8(&p, p_end);
436 pid = get16(&p, p_end) & 0x1fff;
439 desc_list_len = get16(&p, p_end) & 0xfff;
440 if (desc_list_len < 0)
442 desc_list_end = p + desc_list_len;
443 if (desc_list_end > p_end)
446 desc_tag = get8(&p, desc_list_end);
449 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
450 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
451 /*assume DVB AC-3 Audio*/
452 stream_type = STREAM_TYPE_AUDIO_AC3;
453 } else if(desc_tag == 0x7B) {
455 stream_type = STREAM_TYPE_AUDIO_DTS;
458 desc_len = get8(&p, desc_list_end);
459 desc_end = p + desc_len;
460 if (desc_end > desc_list_end)
463 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
467 case DVB_SUBT_DESCID:
468 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
469 stream_type = STREAM_TYPE_SUBTITLE_DVB;
471 language[0] = get8(&p, desc_end);
472 language[1] = get8(&p, desc_end);
473 language[2] = get8(&p, desc_end);
476 comp_page = get16(&p, desc_end);
477 anc_page = get16(&p, desc_end);
480 case 0x0a: /* ISO 639 language descriptor */
481 language[0] = get8(&p, desc_end);
482 language[1] = get8(&p, desc_end);
483 language[2] = get8(&p, desc_end);
494 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
498 /* now create ffmpeg stream */
499 switch(stream_type) {
500 case STREAM_TYPE_AUDIO_MPEG1:
501 case STREAM_TYPE_AUDIO_MPEG2:
502 case STREAM_TYPE_VIDEO_MPEG1:
503 case STREAM_TYPE_VIDEO_MPEG2:
504 case STREAM_TYPE_VIDEO_MPEG4:
505 case STREAM_TYPE_VIDEO_H264:
506 case STREAM_TYPE_VIDEO_VC1:
507 case STREAM_TYPE_AUDIO_AAC:
508 case STREAM_TYPE_AUDIO_AC3:
509 case STREAM_TYPE_AUDIO_DTS:
510 case STREAM_TYPE_SUBTITLE_DVB:
511 pes = add_pes_stream(ts, pid, stream_type);
513 st = new_pes_av_stream(pes, 0);
516 /* we ignore the other streams */
521 if (language[0] != 0) {
522 st->language[0] = language[0];
523 st->language[1] = language[1];
524 st->language[2] = language[2];
525 st->language[3] = language[3];
528 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
529 st->codec->sub_id = (anc_page << 16) | comp_page;
533 /* all parameters are there */
534 ts->set_service_cb(ts->set_service_opaque, 0);
535 mpegts_close_filter(ts, ts->pmt_filter);
536 ts->pmt_filter = NULL;
539 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
541 MpegTSContext *ts = opaque;
542 SectionHeader h1, *h = &h1;
543 const uint8_t *p, *p_end;
547 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
548 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
550 p_end = section + section_len - 4;
552 if (parse_section_header(h, &p, p_end) < 0)
554 if (h->tid != PAT_TID)
558 sid = get16(&p, p_end);
561 pmt_pid = get16(&p, p_end) & 0x1fff;
565 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
570 if (ts->req_sid == sid) {
571 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
578 ts->set_service_cb(ts->set_service_opaque, -1);
581 mpegts_close_filter(ts, ts->pat_filter);
582 ts->pat_filter = NULL;
585 /* add all services found in the PAT */
586 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
588 MpegTSContext *ts = opaque;
589 SectionHeader h1, *h = &h1;
590 const uint8_t *p, *p_end;
592 char *provider_name, *name;
596 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
597 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
599 p_end = section + section_len - 4;
601 if (parse_section_header(h, &p, p_end) < 0)
603 if (h->tid != PAT_TID)
607 sid = get16(&p, p_end);
610 pmt_pid = get16(&p, p_end) & 0x1fff;
614 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
619 /* add the service with a dummy name */
620 snprintf(buf, sizeof(buf), "Service %x\n", sid);
621 name = av_strdup(buf);
622 provider_name = av_strdup("");
623 if (name && provider_name) {
624 new_service(ts, sid, provider_name, name);
627 av_freep(&provider_name);
634 mpegts_close_filter(ts, ts->pat_filter);
635 ts->pat_filter = NULL;
638 static void mpegts_set_service(MpegTSContext *ts, int sid,
639 SetServiceCallback *set_service_cb, void *opaque)
641 ts->set_service_cb = set_service_cb;
642 ts->set_service_opaque = opaque;
644 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
648 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
650 MpegTSContext *ts = opaque;
651 SectionHeader h1, *h = &h1;
652 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
653 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
654 char *name, *provider_name;
657 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
658 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
661 p_end = section + section_len - 4;
663 if (parse_section_header(h, &p, p_end) < 0)
665 if (h->tid != SDT_TID)
667 onid = get16(&p, p_end);
670 val = get8(&p, p_end);
674 sid = get16(&p, p_end);
677 val = get8(&p, p_end);
680 desc_list_len = get16(&p, p_end) & 0xfff;
681 if (desc_list_len < 0)
683 desc_list_end = p + desc_list_len;
684 if (desc_list_end > p_end)
687 desc_tag = get8(&p, desc_list_end);
690 desc_len = get8(&p, desc_list_end);
691 desc_end = p + desc_len;
692 if (desc_end > desc_list_end)
695 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
700 service_type = get8(&p, p_end);
701 if (service_type < 0)
703 provider_name = getstr8(&p, p_end);
706 name = getstr8(&p, p_end);
709 new_service(ts, sid, provider_name, name);
721 mpegts_close_filter(ts, ts->sdt_filter);
722 ts->sdt_filter = NULL;
725 /* scan services in a transport stream by looking at the SDT */
726 static void mpegts_scan_sdt(MpegTSContext *ts)
728 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
732 /* scan services in a transport stream by looking at the PAT (better
734 static void mpegts_scan_pat(MpegTSContext *ts)
736 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
740 /* TS stream handling */
744 MPEGTS_PESHEADER_FILL,
749 /* enough for PES header + length */
750 #define PES_START_SIZE 9
751 #define MAX_PES_HEADER_SIZE (9 + 255)
757 AVFormatContext *stream;
759 enum MpegTSState state;
760 /* used to get the format */
765 uint8_t header[MAX_PES_HEADER_SIZE];
768 static int64_t get_pts(const uint8_t *p)
773 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
774 val = (p[1] << 8) | p[2];
775 pts |= (int64_t)(val >> 1) << 15;
776 val = (p[3] << 8) | p[4];
777 pts |= (int64_t)(val >> 1);
781 /* return non zero if a packet could be constructed */
782 static void mpegts_push_data(void *opaque,
783 const uint8_t *buf, int buf_size, int is_start)
785 PESContext *pes = opaque;
786 MpegTSContext *ts = pes->ts;
791 pes->state = MPEGTS_HEADER;
795 while (buf_size > 0) {
798 len = PES_START_SIZE - pes->data_index;
801 memcpy(pes->header + pes->data_index, p, len);
802 pes->data_index += len;
805 if (pes->data_index == PES_START_SIZE) {
806 /* we got all the PES or section header. We can now
809 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
811 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
812 pes->header[2] == 0x01) {
813 /* it must be an mpeg2 PES stream */
814 code = pes->header[3] | 0x100;
815 if (!((code >= 0x1c0 && code <= 0x1df) ||
816 (code >= 0x1e0 && code <= 0x1ef) ||
817 (code == 0x1bd) || (code == 0x1fd)))
820 /* allocate stream */
821 new_pes_av_stream(pes, code);
823 pes->state = MPEGTS_PESHEADER_FILL;
824 pes->total_size = (pes->header[4] << 8) | pes->header[5];
825 /* NOTE: a zero total size means the PES size is
828 pes->total_size += 6;
829 pes->pes_header_size = pes->header[8] + 9;
831 /* otherwise, it should be a table */
834 pes->state = MPEGTS_SKIP;
839 /**********************************************/
840 /* PES packing parsing */
841 case MPEGTS_PESHEADER_FILL:
842 len = pes->pes_header_size - pes->data_index;
845 memcpy(pes->header + pes->data_index, p, len);
846 pes->data_index += len;
849 if (pes->data_index == pes->pes_header_size) {
853 flags = pes->header[7];
855 pes->pts = AV_NOPTS_VALUE;
856 pes->dts = AV_NOPTS_VALUE;
857 if ((flags & 0xc0) == 0x80) {
858 pes->pts = get_pts(r);
860 } else if ((flags & 0xc0) == 0xc0) {
861 pes->pts = get_pts(r);
863 pes->dts = get_pts(r);
866 /* we got the full header. We parse it and get the payload */
867 pes->state = MPEGTS_PAYLOAD;
871 if (pes->total_size) {
872 len = pes->total_size - pes->data_index;
879 AVPacket *pkt = ts->pkt;
880 if (pes->st && av_new_packet(pkt, len) == 0) {
881 memcpy(pkt->data, p, len);
882 pkt->stream_index = pes->st->index;
885 /* reset pts values */
886 pes->pts = AV_NOPTS_VALUE;
887 pes->dts = AV_NOPTS_VALUE;
901 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
904 int codec_type, codec_id;
906 switch(pes->stream_type){
907 case STREAM_TYPE_AUDIO_MPEG1:
908 case STREAM_TYPE_AUDIO_MPEG2:
909 codec_type = CODEC_TYPE_AUDIO;
910 codec_id = CODEC_ID_MP3;
912 case STREAM_TYPE_VIDEO_MPEG1:
913 case STREAM_TYPE_VIDEO_MPEG2:
914 codec_type = CODEC_TYPE_VIDEO;
915 codec_id = CODEC_ID_MPEG2VIDEO;
917 case STREAM_TYPE_VIDEO_MPEG4:
918 codec_type = CODEC_TYPE_VIDEO;
919 codec_id = CODEC_ID_MPEG4;
921 case STREAM_TYPE_VIDEO_H264:
922 codec_type = CODEC_TYPE_VIDEO;
923 codec_id = CODEC_ID_H264;
925 case STREAM_TYPE_VIDEO_VC1:
926 codec_type = CODEC_TYPE_VIDEO;
927 codec_id = CODEC_ID_VC1;
929 case STREAM_TYPE_AUDIO_AAC:
930 codec_type = CODEC_TYPE_AUDIO;
931 codec_id = CODEC_ID_AAC;
933 case STREAM_TYPE_AUDIO_AC3:
934 codec_type = CODEC_TYPE_AUDIO;
935 codec_id = CODEC_ID_AC3;
937 case STREAM_TYPE_AUDIO_DTS:
938 codec_type = CODEC_TYPE_AUDIO;
939 codec_id = CODEC_ID_DTS;
941 case STREAM_TYPE_SUBTITLE_DVB:
942 codec_type = CODEC_TYPE_SUBTITLE;
943 codec_id = CODEC_ID_DVB_SUBTITLE;
946 if (code >= 0x1c0 && code <= 0x1df) {
947 codec_type = CODEC_TYPE_AUDIO;
948 codec_id = CODEC_ID_MP2;
949 } else if (code == 0x1bd) {
950 codec_type = CODEC_TYPE_AUDIO;
951 codec_id = CODEC_ID_AC3;
953 codec_type = CODEC_TYPE_VIDEO;
954 codec_id = CODEC_ID_MPEG1VIDEO;
958 st = av_new_stream(pes->stream, pes->pid);
960 av_set_pts_info(st, 33, 1, 90000);
962 st->codec->codec_type = codec_type;
963 st->codec->codec_id = codec_id;
964 st->need_parsing = 1;
971 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
976 /* if no pid found, then add a pid context */
977 pes = av_mallocz(sizeof(PESContext));
981 pes->stream = ts->stream;
983 pes->stream_type = stream_type;
984 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
992 /* handle one TS packet */
993 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
995 AVFormatContext *s = ts->stream;
997 int len, pid, cc, cc_ok, afc, is_start;
998 const uint8_t *p, *p_end;
1000 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1001 is_start = packet[1] & 0x40;
1002 tss = ts->pids[pid];
1003 if (ts->auto_guess && tss == NULL && is_start) {
1004 add_pes_stream(ts, pid, 0);
1005 tss = ts->pids[pid];
1010 /* continuity check (currently not used) */
1011 cc = (packet[3] & 0xf);
1012 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1015 /* skip adaptation field */
1016 afc = (packet[3] >> 4) & 3;
1018 if (afc == 0) /* reserved value */
1020 if (afc == 2) /* adaptation field only */
1023 /* skip adapation field */
1026 /* if past the end of packet, ignore */
1027 p_end = packet + TS_PACKET_SIZE;
1031 if (tss->type == MPEGTS_SECTION) {
1033 /* pointer field present */
1035 if (p + len > p_end)
1038 /* write remaining section bytes */
1039 write_section_data(s, tss,
1041 /* check whether filter has been closed */
1047 write_section_data(s, tss,
1052 write_section_data(s, tss,
1057 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
1058 p, p_end - p, is_start);
1062 /* XXX: try to find a better synchro over several packets (use
1063 get_packet_size() ?) */
1064 static int mpegts_resync(ByteIOContext *pb)
1068 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1073 url_fseek(pb, -1, SEEK_CUR);
1081 /* return -1 if error or EOF. Return 0 if OK. */
1082 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1087 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1088 if (len != TS_PACKET_SIZE)
1090 /* check paquet sync byte */
1091 if (buf[0] != 0x47) {
1092 /* find a new packet start */
1093 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1094 if (mpegts_resync(pb) < 0)
1095 return AVERROR_INVALIDDATA;
1099 skip = raw_packet_size - TS_PACKET_SIZE;
1101 url_fskip(pb, skip);
1108 static int handle_packets(MpegTSContext *ts, int nb_packets)
1110 AVFormatContext *s = ts->stream;
1111 ByteIOContext *pb = &s->pb;
1112 uint8_t packet[TS_PACKET_SIZE];
1113 int packet_num, ret;
1121 if (nb_packets != 0 && packet_num >= nb_packets)
1123 ret = read_packet(pb, packet, ts->raw_packet_size);
1126 handle_packet(ts, packet);
1131 static int mpegts_probe(AVProbeData *p)
1134 const int size= p->buf_size;
1135 int score, fec_score, dvhs_score;
1136 #define CHECK_COUNT 10
1138 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1141 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1142 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1143 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1144 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1146 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1147 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1148 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1149 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1152 /* only use the extension for safer guess */
1153 if (match_ext(p->filename, "ts"))
1154 return AVPROBE_SCORE_MAX;
1160 static void set_service_cb(void *opaque, int ret)
1162 MpegTSContext *ts = opaque;
1163 ts->set_service_ret = ret;
1167 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1168 (-1) if not available */
1169 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1170 const uint8_t *packet)
1172 int afc, len, flags;
1176 afc = (packet[3] >> 4) & 3;
1186 if (!(flags & 0x10))
1190 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1191 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1192 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1196 static int mpegts_read_header(AVFormatContext *s,
1197 AVFormatParameters *ap)
1199 MpegTSContext *ts = s->priv_data;
1200 ByteIOContext *pb = &s->pb;
1204 MpegTSService *service;
1207 ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1208 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1211 /* read the first 1024 bytes to get packet size */
1212 pos = url_ftell(pb);
1213 len = get_buffer(pb, buf, sizeof(buf));
1214 if (len != sizeof(buf))
1216 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1217 if (ts->raw_packet_size <= 0)
1223 if (!ts->mpeg2ts_raw) {
1226 if (!ts->auto_guess) {
1227 ts->set_service_ret = -1;
1229 /* first do a scaning to get all the services */
1230 url_fseek(pb, pos, SEEK_SET);
1231 mpegts_scan_sdt(ts);
1233 handle_packets(ts, s->probesize);
1235 if (ts->nb_services <= 0) {
1236 /* no SDT found, we try to look at the PAT */
1238 /* First remove the SDT filters from each PID */
1240 for (i=0; i < NB_PID_MAX; i++) {
1242 mpegts_close_filter(ts, ts->pids[i]);
1244 url_fseek(pb, pos, SEEK_SET);
1245 mpegts_scan_pat(ts);
1247 handle_packets(ts, s->probesize);
1250 if (ts->nb_services <= 0) {
1251 /* raw transport stream */
1253 s->ctx_flags |= AVFMTCTX_NOHEADER;
1257 /* tune to first service found */
1258 for(i=0; i<ts->nb_services && ts->set_service_ret; i++){
1259 service = ts->services[i];
1262 av_log(ts->stream, AV_LOG_DEBUG, "tuning to '%s'\n", service->name);
1265 /* now find the info for the first service if we found any,
1266 otherwise try to filter all PATs */
1268 url_fseek(pb, pos, SEEK_SET);
1269 mpegts_set_service(ts, sid, set_service_cb, ts);
1271 handle_packets(ts, s->probesize);
1273 /* if could not find service, exit */
1275 if (ts->set_service_ret != 0) {
1279 //let's retry with auto_guess set
1281 goto goto_auto_guess;
1286 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1289 s->ctx_flags |= AVFMTCTX_NOHEADER;
1292 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1293 int64_t pcrs[2], pcr_h;
1294 int packet_count[2];
1295 uint8_t packet[TS_PACKET_SIZE];
1297 /* only read packets */
1300 st = av_new_stream(s, 0);
1303 av_set_pts_info(st, 60, 1, 27000000);
1304 st->codec->codec_type = CODEC_TYPE_DATA;
1305 st->codec->codec_id = CODEC_ID_MPEG2TS;
1307 /* we iterate until we find two PCRs to estimate the bitrate */
1312 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1315 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1316 if ((pcr_pid == -1 || pcr_pid == pid) &&
1317 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1319 packet_count[nb_pcrs] = nb_packets;
1320 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1327 ts->pcr_pid = pcr_pid;
1329 /* NOTE1: the bitrate is computed without the FEC */
1330 /* NOTE2: it is only the bitrate of the start of the stream */
1331 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1332 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1333 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1334 st->codec->bit_rate = s->bit_rate;
1335 st->start_time = ts->cur_pcr;
1337 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1338 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1342 url_fseek(pb, pos, SEEK_SET);
1348 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1350 static int mpegts_raw_read_packet(AVFormatContext *s,
1353 MpegTSContext *ts = s->priv_data;
1355 int64_t pcr_h, next_pcr_h, pos;
1356 int pcr_l, next_pcr_l;
1357 uint8_t pcr_buf[12];
1359 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1360 return AVERROR(ENOMEM);
1361 pkt->pos= url_ftell(&s->pb);
1362 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1364 av_free_packet(pkt);
1367 if (ts->mpeg2ts_compute_pcr) {
1368 /* compute exact PCR for each packet */
1369 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1370 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1371 pos = url_ftell(&s->pb);
1372 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1373 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1374 get_buffer(&s->pb, pcr_buf, 12);
1375 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1376 /* XXX: not precise enough */
1377 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1382 url_fseek(&s->pb, pos, SEEK_SET);
1383 /* no next PCR found: we use previous increment */
1384 ts->cur_pcr = pcr_h * 300 + pcr_l;
1386 pkt->pts = ts->cur_pcr;
1387 pkt->duration = ts->pcr_incr;
1388 ts->cur_pcr += ts->pcr_incr;
1390 pkt->stream_index = 0;
1394 static int mpegts_read_packet(AVFormatContext *s,
1397 MpegTSContext *ts = s->priv_data;
1399 if (!ts->mpeg2ts_raw) {
1401 return handle_packets(ts, 0);
1403 return mpegts_raw_read_packet(s, pkt);
1407 static int mpegts_read_close(AVFormatContext *s)
1409 MpegTSContext *ts = s->priv_data;
1411 for(i=0;i<NB_PID_MAX;i++)
1412 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1414 for(i = 0; i < ts->nb_services; i++){
1415 av_free(ts->services[i]->provider_name);
1416 av_free(ts->services[i]->name);
1417 av_free(ts->services[i]);
1419 av_freep(&ts->services);
1424 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1425 int64_t *ppos, int64_t pos_limit)
1427 MpegTSContext *ts = s->priv_data;
1428 int64_t pos, timestamp;
1429 uint8_t buf[TS_PACKET_SIZE];
1431 const int find_next= 1;
1432 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
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 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1439 if (pid == ts->pcr_pid &&
1440 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1443 pos += ts->raw_packet_size;
1447 pos -= ts->raw_packet_size;
1449 return AV_NOPTS_VALUE;
1450 url_fseek(&s->pb, pos, SEEK_SET);
1451 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1452 return AV_NOPTS_VALUE;
1453 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1454 if (pid == ts->pcr_pid &&
1455 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1465 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1466 MpegTSContext *ts = s->priv_data;
1467 uint8_t buf[TS_PACKET_SIZE];
1470 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1473 pos= url_ftell(&s->pb);
1476 url_fseek(&s->pb, pos, SEEK_SET);
1477 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1479 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1480 if(buf[1] & 0x40) break;
1481 pos += ts->raw_packet_size;
1483 url_fseek(&s->pb, pos, SEEK_SET);
1488 /**************************************************************/
1489 /* parsing functions - called from other demuxers such as RTP */
1491 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1495 ts = av_mallocz(sizeof(MpegTSContext));
1498 /* no stream case, currently used by RTP */
1499 ts->raw_packet_size = TS_PACKET_SIZE;
1505 /* return the consumed length if a packet was output, or -1 if no
1507 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1508 const uint8_t *buf, int len)
1518 if (len < TS_PACKET_SIZE)
1520 if (buf[0] != 0x47) {
1524 handle_packet(ts, buf);
1525 buf += TS_PACKET_SIZE;
1526 len -= TS_PACKET_SIZE;
1532 void mpegts_parse_close(MpegTSContext *ts)
1536 for(i=0;i<NB_PID_MAX;i++)
1537 av_free(ts->pids[i]);
1541 AVInputFormat mpegts_demuxer = {
1543 "MPEG2 transport stream format",
1544 sizeof(MpegTSContext),
1551 .flags = AVFMT_SHOW_IDS,