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
24 #include "allformats.h"
29 /* 1.0 second at 24Mbit/s */
30 #define MAX_SCAN_PACKETS 32000
32 /* maximum size in which we look for synchronisation if
33 synchronisation is lost */
34 #define MAX_RESYNC_SIZE 4096
36 typedef struct PESContext PESContext;
38 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
39 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
41 enum MpegTSFilterType {
46 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
48 typedef struct MpegTSPESFilter {
53 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
55 typedef void SetServiceCallback(void *opaque, int ret);
57 typedef struct MpegTSSectionFilter {
62 int end_of_section_reached:1;
63 SectionCallback *section_cb;
65 } MpegTSSectionFilter;
67 typedef struct MpegTSFilter {
69 int last_cc; /* last cc code (-1 if first packet) */
70 enum MpegTSFilterType type;
72 MpegTSPESFilter pes_filter;
73 MpegTSSectionFilter section_filter;
77 typedef struct MpegTSService {
79 int sid; /**< MPEG Program Number of stream */
80 char *provider_name; /**< DVB Network name, "" if not DVB stream */
81 char *name; /**< DVB Service name, "MPEG Program [sid]" if not DVB stream*/
84 struct MpegTSContext {
86 AVFormatContext *stream;
87 /** raw packet size, including FEC if present */
89 /** if true, all pids are analyzed to find streams */
93 /** compute exact PCR for each transport stream packet */
94 int mpeg2ts_compute_pcr;
96 int64_t cur_pcr; /**< used to estimate the exact PCR */
97 int pcr_incr; /**< used to estimate the exact PCR */
98 int pcr_pid; /**< used to estimate the exact PCR */
100 /* data needed to handle file based ts */
101 /** stop parsing loop */
103 /** packet containing Audio/Video data */
106 /******************************************/
107 /* private mpegts data */
109 MpegTSFilter *sdt_filter;
110 /** number of PMTs in the last PAT seen */
112 /** list of PMTs in the last PAT seen */
113 MpegTSService **services;
115 /* set service context (XXX: allocated it ?) */
116 SetServiceCallback *set_service_cb;
117 void *set_service_opaque;
118 /** filter for the PAT */
119 MpegTSFilter *pat_filter;
120 /** filter for the PMT for the MPEG program number specified by req_sid */
121 MpegTSFilter *pmt_filter;
122 /** MPEG program number of stream we want to decode */
125 /** filters for various streams specified by PMT + for the PAT and PMT */
126 MpegTSFilter *pids[NB_PID_MAX];
130 * Assembles PES packets out of TS packets, and then calls the "section_cb"
131 * function when they are complete.
133 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
134 const uint8_t *buf, int buf_size, int is_start)
136 MpegTSSectionFilter *tss = &tss1->u.section_filter;
140 memcpy(tss->section_buf, buf, buf_size);
141 tss->section_index = buf_size;
142 tss->section_h_size = -1;
143 tss->end_of_section_reached = 0;
145 if (tss->end_of_section_reached)
147 len = 4096 - tss->section_index;
150 memcpy(tss->section_buf + tss->section_index, buf, len);
151 tss->section_index += len;
154 /* compute section length if possible */
155 if (tss->section_h_size == -1 && tss->section_index >= 3) {
156 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
159 tss->section_h_size = len;
162 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
163 tss->end_of_section_reached = 1;
164 if (!tss->check_crc ||
165 av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
166 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
170 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
171 SectionCallback *section_cb, void *opaque,
175 MpegTSFilter *filter;
176 MpegTSSectionFilter *sec;
179 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
181 if (pid >= NB_PID_MAX || ts->pids[pid])
183 filter = av_mallocz(sizeof(MpegTSFilter));
186 ts->pids[pid] = filter;
187 filter->type = MPEGTS_SECTION;
189 filter->last_cc = -1;
190 sec = &filter->u.section_filter;
191 sec->section_cb = section_cb;
192 sec->opaque = opaque;
193 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
194 sec->check_crc = check_crc;
195 if (!sec->section_buf) {
202 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
206 MpegTSFilter *filter;
207 MpegTSPESFilter *pes;
209 if (pid >= NB_PID_MAX || ts->pids[pid])
211 filter = av_mallocz(sizeof(MpegTSFilter));
214 ts->pids[pid] = filter;
215 filter->type = MPEGTS_PES;
217 filter->last_cc = -1;
218 pes = &filter->u.pes_filter;
219 pes->pes_cb = pes_cb;
220 pes->opaque = opaque;
224 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
229 if (filter->type == MPEGTS_SECTION)
230 av_freep(&filter->u.section_filter.section_buf);
231 else if (filter->type == MPEGTS_PES)
232 av_freep(&filter->u.pes_filter.opaque);
235 ts->pids[pid] = NULL;
238 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
239 int stat[packet_size];
244 memset(stat, 0, packet_size*sizeof(int));
246 for(x=i=0; i<size; i++){
249 if(stat[x] > best_score){
256 if(x == packet_size) x= 0;
262 /* autodetect fec presence. Must have at least 1024 bytes */
263 static int get_packet_size(const uint8_t *buf, int size)
265 int score, fec_score, dvhs_score;
267 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
270 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
271 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
272 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
273 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
275 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
276 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
277 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
281 typedef struct SectionHeader {
286 uint8_t last_sec_num;
289 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
302 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
308 if ((p + 1) >= p_end)
310 c = (p[0] << 8) | p[1];
316 /* read and allocate a DVB string preceeded by its length */
317 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
324 len = get8(&p, p_end);
327 if ((p + len) > p_end)
329 str = av_malloc(len + 1);
339 static int parse_section_header(SectionHeader *h,
340 const uint8_t **pp, const uint8_t *p_end)
344 val = get8(pp, p_end);
349 val = get16(pp, p_end);
353 val = get8(pp, p_end);
356 h->version = (val >> 1) & 0x1f;
357 val = get8(pp, p_end);
361 val = get8(pp, p_end);
364 h->last_sec_num = val;
368 static MpegTSService *new_service(MpegTSContext *ts, int sid,
369 char *provider_name, char *name)
371 MpegTSService *service;
374 av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
375 "sid=0x%04x provider='%s' name='%s'\n",
376 sid, provider_name, name);
379 service = av_mallocz(sizeof(MpegTSService));
383 service->provider_name = provider_name;
384 service->name = name;
385 dynarray_add(&ts->services, &ts->nb_services, service);
389 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
391 MpegTSContext *ts = opaque;
392 SectionHeader h1, *h = &h1;
395 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
396 int program_info_length, pcr_pid, pid, stream_type;
397 int desc_list_len, desc_len, desc_tag;
398 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
399 char language[4] = {0}; /* initialize to kill warnings */
402 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
403 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
405 p_end = section + section_len - 4;
407 if (parse_section_header(h, &p, p_end) < 0)
410 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
411 h->id, h->sec_num, h->last_sec_num);
413 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
416 pcr_pid = get16(&p, p_end) & 0x1fff;
419 ts->pcr_pid = pcr_pid;
421 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
423 program_info_length = get16(&p, p_end) & 0xfff;
424 if (program_info_length < 0)
426 p += program_info_length;
432 stream_type = get8(&p, p_end);
435 pid = get16(&p, p_end) & 0x1fff;
438 desc_list_len = get16(&p, p_end) & 0xfff;
439 if (desc_list_len < 0)
441 desc_list_end = p + desc_list_len;
442 if (desc_list_end > p_end)
445 desc_tag = get8(&p, desc_list_end);
448 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
449 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
450 /*assume DVB AC-3 Audio*/
451 stream_type = STREAM_TYPE_AUDIO_AC3;
452 } else if(desc_tag == 0x7B) {
454 stream_type = STREAM_TYPE_AUDIO_DTS;
457 desc_len = get8(&p, desc_list_end);
458 desc_end = p + desc_len;
459 if (desc_end > desc_list_end)
462 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
466 case DVB_SUBT_DESCID:
467 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
468 stream_type = STREAM_TYPE_SUBTITLE_DVB;
470 language[0] = get8(&p, desc_end);
471 language[1] = get8(&p, desc_end);
472 language[2] = get8(&p, desc_end);
475 comp_page = get16(&p, desc_end);
476 anc_page = get16(&p, desc_end);
479 case 0x0a: /* ISO 639 language descriptor */
480 language[0] = get8(&p, desc_end);
481 language[1] = get8(&p, desc_end);
482 language[2] = get8(&p, desc_end);
493 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
497 /* now create ffmpeg stream */
498 switch(stream_type) {
499 case STREAM_TYPE_AUDIO_MPEG1:
500 case STREAM_TYPE_AUDIO_MPEG2:
501 case STREAM_TYPE_VIDEO_MPEG1:
502 case STREAM_TYPE_VIDEO_MPEG2:
503 case STREAM_TYPE_VIDEO_MPEG4:
504 case STREAM_TYPE_VIDEO_H264:
505 case STREAM_TYPE_VIDEO_VC1:
506 case STREAM_TYPE_AUDIO_AAC:
507 case STREAM_TYPE_AUDIO_AC3:
508 case STREAM_TYPE_AUDIO_DTS:
509 case STREAM_TYPE_SUBTITLE_DVB:
510 pes = add_pes_stream(ts, pid, stream_type);
512 st = new_pes_av_stream(pes, 0);
515 /* we ignore the other streams */
520 if (language[0] != 0) {
521 st->language[0] = language[0];
522 st->language[1] = language[1];
523 st->language[2] = language[2];
524 st->language[3] = language[3];
527 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
528 st->codec->sub_id = (anc_page << 16) | comp_page;
532 /* all parameters are there */
533 ts->set_service_cb(ts->set_service_opaque, 0);
534 mpegts_close_filter(ts, ts->pmt_filter);
535 ts->pmt_filter = NULL;
538 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
540 MpegTSContext *ts = opaque;
541 SectionHeader h1, *h = &h1;
542 const uint8_t *p, *p_end;
546 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
547 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
549 p_end = section + section_len - 4;
551 if (parse_section_header(h, &p, p_end) < 0)
553 if (h->tid != PAT_TID)
557 sid = get16(&p, p_end);
560 pmt_pid = get16(&p, p_end) & 0x1fff;
564 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
569 if (ts->req_sid == sid) {
570 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
577 ts->set_service_cb(ts->set_service_opaque, -1);
580 mpegts_close_filter(ts, ts->pat_filter);
581 ts->pat_filter = NULL;
584 /* add all services found in the PAT */
585 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
587 MpegTSContext *ts = opaque;
588 SectionHeader h1, *h = &h1;
589 const uint8_t *p, *p_end;
591 char *provider_name, *name;
595 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
596 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
598 p_end = section + section_len - 4;
600 if (parse_section_header(h, &p, p_end) < 0)
602 if (h->tid != PAT_TID)
606 sid = get16(&p, p_end);
609 pmt_pid = get16(&p, p_end) & 0x1fff;
613 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
618 /* add the service with a dummy name */
619 snprintf(buf, sizeof(buf), "Service %x\n", sid);
620 name = av_strdup(buf);
621 provider_name = av_strdup("");
622 if (name && provider_name) {
623 new_service(ts, sid, provider_name, name);
626 av_freep(&provider_name);
633 mpegts_close_filter(ts, ts->pat_filter);
634 ts->pat_filter = NULL;
637 static void mpegts_set_service(MpegTSContext *ts, int sid,
638 SetServiceCallback *set_service_cb, void *opaque)
640 ts->set_service_cb = set_service_cb;
641 ts->set_service_opaque = opaque;
643 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
647 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
649 MpegTSContext *ts = opaque;
650 SectionHeader h1, *h = &h1;
651 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
652 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
653 char *name, *provider_name;
656 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
657 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
660 p_end = section + section_len - 4;
662 if (parse_section_header(h, &p, p_end) < 0)
664 if (h->tid != SDT_TID)
666 onid = get16(&p, p_end);
669 val = get8(&p, p_end);
673 sid = get16(&p, p_end);
676 val = get8(&p, p_end);
679 desc_list_len = get16(&p, p_end) & 0xfff;
680 if (desc_list_len < 0)
682 desc_list_end = p + desc_list_len;
683 if (desc_list_end > p_end)
686 desc_tag = get8(&p, desc_list_end);
689 desc_len = get8(&p, desc_list_end);
690 desc_end = p + desc_len;
691 if (desc_end > desc_list_end)
694 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
699 service_type = get8(&p, p_end);
700 if (service_type < 0)
702 provider_name = getstr8(&p, p_end);
705 name = getstr8(&p, p_end);
708 new_service(ts, sid, provider_name, name);
720 mpegts_close_filter(ts, ts->sdt_filter);
721 ts->sdt_filter = NULL;
724 /* scan services in a transport stream by looking at the SDT */
725 static void mpegts_scan_sdt(MpegTSContext *ts)
727 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
731 /* scan services in a transport stream by looking at the PAT (better
733 static void mpegts_scan_pat(MpegTSContext *ts)
735 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
739 /* TS stream handling */
743 MPEGTS_PESHEADER_FILL,
748 /* enough for PES header + length */
749 #define PES_START_SIZE 9
750 #define MAX_PES_HEADER_SIZE (9 + 255)
756 AVFormatContext *stream;
758 enum MpegTSState state;
759 /* used to get the format */
764 uint8_t header[MAX_PES_HEADER_SIZE];
767 static int64_t get_pts(const uint8_t *p)
772 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
773 val = (p[1] << 8) | p[2];
774 pts |= (int64_t)(val >> 1) << 15;
775 val = (p[3] << 8) | p[4];
776 pts |= (int64_t)(val >> 1);
780 /* return non zero if a packet could be constructed */
781 static void mpegts_push_data(void *opaque,
782 const uint8_t *buf, int buf_size, int is_start)
784 PESContext *pes = opaque;
785 MpegTSContext *ts = pes->ts;
790 pes->state = MPEGTS_HEADER;
794 while (buf_size > 0) {
797 len = PES_START_SIZE - pes->data_index;
800 memcpy(pes->header + pes->data_index, p, len);
801 pes->data_index += len;
804 if (pes->data_index == PES_START_SIZE) {
805 /* we got all the PES or section header. We can now
808 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
810 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
811 pes->header[2] == 0x01) {
812 /* it must be an mpeg2 PES stream */
813 code = pes->header[3] | 0x100;
814 if (!((code >= 0x1c0 && code <= 0x1df) ||
815 (code >= 0x1e0 && code <= 0x1ef) ||
816 (code == 0x1bd) || (code == 0x1fd)))
819 /* allocate stream */
820 new_pes_av_stream(pes, code);
822 pes->state = MPEGTS_PESHEADER_FILL;
823 pes->total_size = (pes->header[4] << 8) | pes->header[5];
824 /* NOTE: a zero total size means the PES size is
827 pes->total_size += 6;
828 pes->pes_header_size = pes->header[8] + 9;
830 /* otherwise, it should be a table */
833 pes->state = MPEGTS_SKIP;
838 /**********************************************/
839 /* PES packing parsing */
840 case MPEGTS_PESHEADER_FILL:
841 len = pes->pes_header_size - pes->data_index;
844 memcpy(pes->header + pes->data_index, p, len);
845 pes->data_index += len;
848 if (pes->data_index == pes->pes_header_size) {
852 flags = pes->header[7];
854 pes->pts = AV_NOPTS_VALUE;
855 pes->dts = AV_NOPTS_VALUE;
856 if ((flags & 0xc0) == 0x80) {
857 pes->pts = get_pts(r);
859 } else if ((flags & 0xc0) == 0xc0) {
860 pes->pts = get_pts(r);
862 pes->dts = get_pts(r);
865 /* we got the full header. We parse it and get the payload */
866 pes->state = MPEGTS_PAYLOAD;
870 if (pes->total_size) {
871 len = pes->total_size - pes->data_index;
878 AVPacket *pkt = ts->pkt;
879 if (pes->st && av_new_packet(pkt, len) == 0) {
880 memcpy(pkt->data, p, len);
881 pkt->stream_index = pes->st->index;
884 /* reset pts values */
885 pes->pts = AV_NOPTS_VALUE;
886 pes->dts = AV_NOPTS_VALUE;
900 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
903 int codec_type, codec_id;
905 switch(pes->stream_type){
906 case STREAM_TYPE_AUDIO_MPEG1:
907 case STREAM_TYPE_AUDIO_MPEG2:
908 codec_type = CODEC_TYPE_AUDIO;
909 codec_id = CODEC_ID_MP3;
911 case STREAM_TYPE_VIDEO_MPEG1:
912 case STREAM_TYPE_VIDEO_MPEG2:
913 codec_type = CODEC_TYPE_VIDEO;
914 codec_id = CODEC_ID_MPEG2VIDEO;
916 case STREAM_TYPE_VIDEO_MPEG4:
917 codec_type = CODEC_TYPE_VIDEO;
918 codec_id = CODEC_ID_MPEG4;
920 case STREAM_TYPE_VIDEO_H264:
921 codec_type = CODEC_TYPE_VIDEO;
922 codec_id = CODEC_ID_H264;
924 case STREAM_TYPE_VIDEO_VC1:
925 codec_type = CODEC_TYPE_VIDEO;
926 codec_id = CODEC_ID_VC1;
928 case STREAM_TYPE_AUDIO_AAC:
929 codec_type = CODEC_TYPE_AUDIO;
930 codec_id = CODEC_ID_AAC;
932 case STREAM_TYPE_AUDIO_AC3:
933 codec_type = CODEC_TYPE_AUDIO;
934 codec_id = CODEC_ID_AC3;
936 case STREAM_TYPE_AUDIO_DTS:
937 codec_type = CODEC_TYPE_AUDIO;
938 codec_id = CODEC_ID_DTS;
940 case STREAM_TYPE_SUBTITLE_DVB:
941 codec_type = CODEC_TYPE_SUBTITLE;
942 codec_id = CODEC_ID_DVB_SUBTITLE;
945 if (code >= 0x1c0 && code <= 0x1df) {
946 codec_type = CODEC_TYPE_AUDIO;
947 codec_id = CODEC_ID_MP2;
948 } else if (code == 0x1bd) {
949 codec_type = CODEC_TYPE_AUDIO;
950 codec_id = CODEC_ID_AC3;
952 codec_type = CODEC_TYPE_VIDEO;
953 codec_id = CODEC_ID_MPEG1VIDEO;
957 st = av_new_stream(pes->stream, pes->pid);
959 av_set_pts_info(st, 33, 1, 90000);
961 st->codec->codec_type = codec_type;
962 st->codec->codec_id = codec_id;
963 st->need_parsing = AVSTREAM_PARSE_FULL;
970 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
975 /* if no pid found, then add a pid context */
976 pes = av_mallocz(sizeof(PESContext));
980 pes->stream = ts->stream;
982 pes->stream_type = stream_type;
983 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
991 /* handle one TS packet */
992 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
994 AVFormatContext *s = ts->stream;
996 int len, pid, cc, cc_ok, afc, is_start;
997 const uint8_t *p, *p_end;
999 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1000 is_start = packet[1] & 0x40;
1001 tss = ts->pids[pid];
1002 if (ts->auto_guess && tss == NULL && is_start) {
1003 add_pes_stream(ts, pid, 0);
1004 tss = ts->pids[pid];
1009 /* continuity check (currently not used) */
1010 cc = (packet[3] & 0xf);
1011 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1014 /* skip adaptation field */
1015 afc = (packet[3] >> 4) & 3;
1017 if (afc == 0) /* reserved value */
1019 if (afc == 2) /* adaptation field only */
1022 /* skip adapation field */
1025 /* if past the end of packet, ignore */
1026 p_end = packet + TS_PACKET_SIZE;
1030 if (tss->type == MPEGTS_SECTION) {
1032 /* pointer field present */
1034 if (p + len > p_end)
1037 /* write remaining section bytes */
1038 write_section_data(s, tss,
1040 /* check whether filter has been closed */
1046 write_section_data(s, tss,
1051 write_section_data(s, tss,
1056 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
1057 p, p_end - p, is_start);
1061 /* XXX: try to find a better synchro over several packets (use
1062 get_packet_size() ?) */
1063 static int mpegts_resync(ByteIOContext *pb)
1067 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1072 url_fseek(pb, -1, SEEK_CUR);
1080 /* return -1 if error or EOF. Return 0 if OK. */
1081 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1086 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1087 if (len != TS_PACKET_SIZE)
1089 /* check paquet sync byte */
1090 if (buf[0] != 0x47) {
1091 /* find a new packet start */
1092 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1093 if (mpegts_resync(pb) < 0)
1094 return AVERROR_INVALIDDATA;
1098 skip = raw_packet_size - TS_PACKET_SIZE;
1100 url_fskip(pb, skip);
1107 static int handle_packets(MpegTSContext *ts, int nb_packets)
1109 AVFormatContext *s = ts->stream;
1110 ByteIOContext *pb = &s->pb;
1111 uint8_t packet[TS_PACKET_SIZE];
1112 int packet_num, ret;
1120 if (nb_packets != 0 && packet_num >= nb_packets)
1122 ret = read_packet(pb, packet, ts->raw_packet_size);
1125 handle_packet(ts, packet);
1130 static int mpegts_probe(AVProbeData *p)
1133 const int size= p->buf_size;
1134 int score, fec_score, dvhs_score;
1135 #define CHECK_COUNT 10
1137 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1140 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1141 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1142 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1143 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1145 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1146 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1147 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1148 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1151 /* only use the extension for safer guess */
1152 if (match_ext(p->filename, "ts"))
1153 return AVPROBE_SCORE_MAX;
1159 static void set_service_cb(void *opaque, int ret)
1161 MpegTSContext *ts = opaque;
1162 ts->set_service_ret = ret;
1166 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1167 (-1) if not available */
1168 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1169 const uint8_t *packet)
1171 int afc, len, flags;
1175 afc = (packet[3] >> 4) & 3;
1185 if (!(flags & 0x10))
1189 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1190 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1191 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1195 static int mpegts_read_header(AVFormatContext *s,
1196 AVFormatParameters *ap)
1198 MpegTSContext *ts = s->priv_data;
1199 ByteIOContext *pb = &s->pb;
1203 MpegTSService *service;
1206 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1207 if(ap->mpeg2ts_raw){
1208 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1213 /* read the first 1024 bytes to get packet size */
1214 pos = url_ftell(pb);
1215 len = get_buffer(pb, buf, sizeof(buf));
1216 if (len != sizeof(buf))
1218 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1219 if (ts->raw_packet_size <= 0)
1224 if (s->iformat == &mpegts_demuxer) {
1227 if (!ts->auto_guess) {
1228 ts->set_service_ret = -1;
1230 /* first do a scaning to get all the services */
1231 url_fseek(pb, pos, SEEK_SET);
1232 mpegts_scan_sdt(ts);
1234 handle_packets(ts, s->probesize);
1236 if (ts->nb_services <= 0) {
1237 /* no SDT found, we try to look at the PAT */
1239 /* First remove the SDT filters from each PID */
1241 for (i=0; i < NB_PID_MAX; i++) {
1243 mpegts_close_filter(ts, ts->pids[i]);
1245 url_fseek(pb, pos, SEEK_SET);
1246 mpegts_scan_pat(ts);
1248 handle_packets(ts, s->probesize);
1251 if (ts->nb_services <= 0) {
1252 /* raw transport stream */
1254 s->ctx_flags |= AVFMTCTX_NOHEADER;
1258 /* tune to first service found */
1259 for(i=0; i<ts->nb_services && ts->set_service_ret; i++){
1260 service = ts->services[i];
1263 av_log(ts->stream, AV_LOG_DEBUG, "tuning to '%s'\n", service->name);
1266 /* now find the info for the first service if we found any,
1267 otherwise try to filter all PATs */
1269 url_fseek(pb, pos, SEEK_SET);
1270 mpegts_set_service(ts, sid, set_service_cb, ts);
1272 handle_packets(ts, s->probesize);
1274 /* if could not find service, enable auto_guess */
1276 if (ts->set_service_ret != 0)
1280 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1283 s->ctx_flags |= AVFMTCTX_NOHEADER;
1286 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1287 int64_t pcrs[2], pcr_h;
1288 int packet_count[2];
1289 uint8_t packet[TS_PACKET_SIZE];
1291 /* only read packets */
1294 st = av_new_stream(s, 0);
1297 av_set_pts_info(st, 60, 1, 27000000);
1298 st->codec->codec_type = CODEC_TYPE_DATA;
1299 st->codec->codec_id = CODEC_ID_MPEG2TS;
1301 /* we iterate until we find two PCRs to estimate the bitrate */
1306 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1309 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1310 if ((pcr_pid == -1 || pcr_pid == pid) &&
1311 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1313 packet_count[nb_pcrs] = nb_packets;
1314 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1321 ts->pcr_pid = pcr_pid;
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;
1401 for(i=0;i<NB_PID_MAX;i++)
1402 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1404 for(i = 0; i < ts->nb_services; i++){
1405 av_free(ts->services[i]->provider_name);
1406 av_free(ts->services[i]->name);
1407 av_free(ts->services[i]);
1409 av_freep(&ts->services);
1414 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1415 int64_t *ppos, int64_t pos_limit)
1417 MpegTSContext *ts = s->priv_data;
1418 int64_t pos, timestamp;
1419 uint8_t buf[TS_PACKET_SIZE];
1421 const int find_next= 1;
1422 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1425 url_fseek(&s->pb, pos, SEEK_SET);
1426 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1427 return AV_NOPTS_VALUE;
1428 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1429 if (pid == ts->pcr_pid &&
1430 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1433 pos += ts->raw_packet_size;
1437 pos -= ts->raw_packet_size;
1439 return AV_NOPTS_VALUE;
1440 url_fseek(&s->pb, pos, SEEK_SET);
1441 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1442 return AV_NOPTS_VALUE;
1443 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1444 if (pid == ts->pcr_pid &&
1445 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1455 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1456 MpegTSContext *ts = s->priv_data;
1457 uint8_t buf[TS_PACKET_SIZE];
1460 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1463 pos= url_ftell(&s->pb);
1466 url_fseek(&s->pb, pos, SEEK_SET);
1467 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1469 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1470 if(buf[1] & 0x40) break;
1471 pos += ts->raw_packet_size;
1473 url_fseek(&s->pb, pos, SEEK_SET);
1478 /**************************************************************/
1479 /* parsing functions - called from other demuxers such as RTP */
1481 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1485 ts = av_mallocz(sizeof(MpegTSContext));
1488 /* no stream case, currently used by RTP */
1489 ts->raw_packet_size = TS_PACKET_SIZE;
1495 /* return the consumed length if a packet was output, or -1 if no
1497 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1498 const uint8_t *buf, int len)
1508 if (len < TS_PACKET_SIZE)
1510 if (buf[0] != 0x47) {
1514 handle_packet(ts, buf);
1515 buf += TS_PACKET_SIZE;
1516 len -= TS_PACKET_SIZE;
1522 void mpegts_parse_close(MpegTSContext *ts)
1526 for(i=0;i<NB_PID_MAX;i++)
1527 av_free(ts->pids[i]);
1531 AVInputFormat mpegts_demuxer = {
1533 "MPEG2 transport stream format",
1534 sizeof(MpegTSContext),
1541 .flags = AVFMT_SHOW_IDS,
1544 AVInputFormat mpegtsraw_demuxer = {
1546 "MPEG2 raw transport stream format",
1547 sizeof(MpegTSContext),
1550 mpegts_raw_read_packet,
1554 .flags = AVFMT_SHOW_IDS,