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 pcr_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 */
92 /** compute exact PCR for each transport stream packet */
93 int mpeg2ts_compute_pcr;
95 int64_t cur_pcr; /**< used to estimate the exact PCR */
96 int pcr_incr; /**< used to estimate the exact PCR */
98 /* data needed to handle file based ts */
99 /** stop parsing loop */
101 /** packet containing Audio/Video data */
104 /******************************************/
105 /* private mpegts data */
107 /** number of PMTs in the last PAT seen */
109 /** list of PMTs in the last PAT seen */
110 MpegTSService **services;
113 /** filters for various streams specified by PMT + for the PAT and PMT */
114 MpegTSFilter *pids[NB_PID_MAX];
117 /* TS stream handling */
121 MPEGTS_PESHEADER_FILL,
126 /* enough for PES header + length */
127 #define PES_START_SIZE 9
128 #define MAX_PES_HEADER_SIZE (9 + 255)
132 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
135 AVFormatContext *stream;
137 enum MpegTSState state;
138 /* used to get the format */
143 uint8_t header[MAX_PES_HEADER_SIZE];
147 * Assembles PES packets out of TS packets, and then calls the "section_cb"
148 * function when they are complete.
150 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
151 const uint8_t *buf, int buf_size, int is_start)
153 MpegTSSectionFilter *tss = &tss1->u.section_filter;
157 memcpy(tss->section_buf, buf, buf_size);
158 tss->section_index = buf_size;
159 tss->section_h_size = -1;
160 tss->end_of_section_reached = 0;
162 if (tss->end_of_section_reached)
164 len = 4096 - tss->section_index;
167 memcpy(tss->section_buf + tss->section_index, buf, len);
168 tss->section_index += len;
171 /* compute section length if possible */
172 if (tss->section_h_size == -1 && tss->section_index >= 3) {
173 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
176 tss->section_h_size = len;
179 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
180 tss->end_of_section_reached = 1;
181 if (!tss->check_crc ||
182 av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
183 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
187 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
188 SectionCallback *section_cb, void *opaque,
192 MpegTSFilter *filter;
193 MpegTSSectionFilter *sec;
196 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
198 if (pid >= NB_PID_MAX || ts->pids[pid])
200 filter = av_mallocz(sizeof(MpegTSFilter));
203 ts->pids[pid] = filter;
204 filter->type = MPEGTS_SECTION;
206 filter->last_cc = -1;
207 sec = &filter->u.section_filter;
208 sec->section_cb = section_cb;
209 sec->opaque = opaque;
210 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
211 sec->check_crc = check_crc;
212 if (!sec->section_buf) {
219 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
223 MpegTSFilter *filter;
224 MpegTSPESFilter *pes;
226 if (pid >= NB_PID_MAX || ts->pids[pid])
228 filter = av_mallocz(sizeof(MpegTSFilter));
231 ts->pids[pid] = filter;
232 filter->type = MPEGTS_PES;
234 filter->last_cc = -1;
235 pes = &filter->u.pes_filter;
236 pes->pes_cb = pes_cb;
237 pes->opaque = opaque;
241 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
246 if (filter->type == MPEGTS_SECTION)
247 av_freep(&filter->u.section_filter.section_buf);
248 else if (filter->type == MPEGTS_PES)
249 av_freep(&filter->u.pes_filter.opaque);
252 ts->pids[pid] = NULL;
255 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
256 int stat[packet_size];
261 memset(stat, 0, packet_size*sizeof(int));
263 for(x=i=0; i<size; i++){
266 if(stat[x] > best_score){
273 if(x == packet_size) x= 0;
279 /* autodetect fec presence. Must have at least 1024 bytes */
280 static int get_packet_size(const uint8_t *buf, int size)
282 int score, fec_score, dvhs_score;
284 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
287 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
288 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
289 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
290 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
292 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
293 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
294 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
298 typedef struct SectionHeader {
303 uint8_t last_sec_num;
306 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
319 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
325 if ((p + 1) >= p_end)
327 c = (p[0] << 8) | p[1];
333 /* read and allocate a DVB string preceeded by its length */
334 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
341 len = get8(&p, p_end);
344 if ((p + len) > p_end)
346 str = av_malloc(len + 1);
356 static int parse_section_header(SectionHeader *h,
357 const uint8_t **pp, const uint8_t *p_end)
361 val = get8(pp, p_end);
366 val = get16(pp, p_end);
370 val = get8(pp, p_end);
373 h->version = (val >> 1) & 0x1f;
374 val = get8(pp, p_end);
378 val = get8(pp, p_end);
381 h->last_sec_num = val;
385 static MpegTSService *new_service(MpegTSContext *ts, int sid,
386 char *provider_name, char *name)
388 MpegTSService *service=NULL;
392 av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
393 "sid=0x%04x provider='%s' name='%s'\n",
394 sid, provider_name, name);
397 for(i=0; i<ts->nb_services; i++)
398 if(ts->services[i]->sid == sid)
399 service= ts->services[i];
402 service = av_mallocz(sizeof(MpegTSService));
405 dynarray_add(&ts->services, &ts->nb_services, service);
408 assert((!provider_name) == (!name));
410 av_free(service->provider_name);
411 av_free(service-> name);
412 service->provider_name = provider_name;
413 service-> name = name;
418 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
420 MpegTSContext *ts = filter->u.section_filter.opaque;
421 SectionHeader h1, *h = &h1;
424 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
425 int program_info_length, pcr_pid, pid, stream_type;
426 int desc_list_len, desc_len, desc_tag;
427 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
428 char language[4] = {0}; /* initialize to kill warnings */
431 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
432 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
434 p_end = section + section_len - 4;
436 if (parse_section_header(h, &p, p_end) < 0)
439 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
440 h->id, h->sec_num, h->last_sec_num);
442 if (h->tid != PMT_TID)
445 pcr_pid = get16(&p, p_end) & 0x1fff;
449 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
451 program_info_length = get16(&p, p_end) & 0xfff;
452 if (program_info_length < 0)
454 p += program_info_length;
460 stream_type = get8(&p, p_end);
463 pid = get16(&p, p_end) & 0x1fff;
466 desc_list_len = get16(&p, p_end) & 0xfff;
467 if (desc_list_len < 0)
469 desc_list_end = p + desc_list_len;
470 if (desc_list_end > p_end)
473 desc_tag = get8(&p, desc_list_end);
476 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
477 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
478 /*assume DVB AC-3 Audio*/
479 stream_type = STREAM_TYPE_AUDIO_AC3;
480 } else if(desc_tag == 0x7B) {
482 stream_type = STREAM_TYPE_AUDIO_DTS;
485 desc_len = get8(&p, desc_list_end);
486 desc_end = p + desc_len;
487 if (desc_end > desc_list_end)
490 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
494 case DVB_SUBT_DESCID:
495 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
496 stream_type = STREAM_TYPE_SUBTITLE_DVB;
498 language[0] = get8(&p, desc_end);
499 language[1] = get8(&p, desc_end);
500 language[2] = get8(&p, desc_end);
503 comp_page = get16(&p, desc_end);
504 anc_page = get16(&p, desc_end);
507 case 0x0a: /* ISO 639 language descriptor */
508 language[0] = get8(&p, desc_end);
509 language[1] = get8(&p, desc_end);
510 language[2] = get8(&p, desc_end);
521 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
525 /* now create ffmpeg stream */
526 switch(stream_type) {
527 case STREAM_TYPE_AUDIO_MPEG1:
528 case STREAM_TYPE_AUDIO_MPEG2:
529 case STREAM_TYPE_VIDEO_MPEG1:
530 case STREAM_TYPE_VIDEO_MPEG2:
531 case STREAM_TYPE_VIDEO_MPEG4:
532 case STREAM_TYPE_VIDEO_H264:
533 case STREAM_TYPE_VIDEO_VC1:
534 case STREAM_TYPE_AUDIO_AAC:
535 case STREAM_TYPE_AUDIO_AC3:
536 case STREAM_TYPE_AUDIO_DTS:
537 case STREAM_TYPE_SUBTITLE_DVB:
539 assert(ts->pids[pid].type == MPEGTS_PES);
540 pes= ts->pids[pid]->u.pes_filter.opaque;
543 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
545 st = new_pes_av_stream(pes, 0);
549 /* we ignore the other streams */
554 if (language[0] != 0) {
555 memcpy(st->language, language, 4);
558 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
559 st->codec->sub_id = (anc_page << 16) | comp_page;
563 /* all parameters are there */
565 mpegts_close_filter(ts, filter);
568 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
570 MpegTSContext *ts = filter->u.section_filter.opaque;
571 SectionHeader h1, *h = &h1;
572 const uint8_t *p, *p_end;
576 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
577 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
579 p_end = section + section_len - 4;
581 if (parse_section_header(h, &p, p_end) < 0)
583 if (h->tid != PAT_TID)
587 sid = get16(&p, p_end);
590 pmt_pid = get16(&p, p_end) & 0x1fff;
594 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
599 new_service(ts, sid, NULL, NULL);
601 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
607 mpegts_close_filter(ts, filter);
610 static void mpegts_set_service(MpegTSContext *ts)
612 mpegts_open_section_filter(ts, PAT_PID,
616 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
618 MpegTSContext *ts = filter->u.section_filter.opaque;
619 SectionHeader h1, *h = &h1;
620 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
621 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
622 char *name, *provider_name;
625 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
626 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
629 p_end = section + section_len - 4;
631 if (parse_section_header(h, &p, p_end) < 0)
633 if (h->tid != SDT_TID)
635 onid = get16(&p, p_end);
638 val = get8(&p, p_end);
642 sid = get16(&p, p_end);
645 val = get8(&p, p_end);
648 desc_list_len = get16(&p, p_end) & 0xfff;
649 if (desc_list_len < 0)
651 desc_list_end = p + desc_list_len;
652 if (desc_list_end > p_end)
655 desc_tag = get8(&p, desc_list_end);
658 desc_len = get8(&p, desc_list_end);
659 desc_end = p + desc_len;
660 if (desc_end > desc_list_end)
663 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
668 service_type = get8(&p, p_end);
669 if (service_type < 0)
671 provider_name = getstr8(&p, p_end);
674 name = getstr8(&p, p_end);
677 new_service(ts, sid, provider_name, name);
688 /* scan services in a transport stream by looking at the SDT */
689 static void mpegts_scan_sdt(MpegTSContext *ts)
691 mpegts_open_section_filter(ts, SDT_PID,
695 static int64_t get_pts(const uint8_t *p)
700 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
701 val = (p[1] << 8) | p[2];
702 pts |= (int64_t)(val >> 1) << 15;
703 val = (p[3] << 8) | p[4];
704 pts |= (int64_t)(val >> 1);
708 /* return non zero if a packet could be constructed */
709 static void mpegts_push_data(MpegTSFilter *filter,
710 const uint8_t *buf, int buf_size, int is_start)
712 PESContext *pes = filter->u.pes_filter.opaque;
713 MpegTSContext *ts = pes->ts;
721 pes->state = MPEGTS_HEADER;
725 while (buf_size > 0) {
728 len = PES_START_SIZE - pes->data_index;
731 memcpy(pes->header + pes->data_index, p, len);
732 pes->data_index += len;
735 if (pes->data_index == PES_START_SIZE) {
736 /* we got all the PES or section header. We can now
739 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
741 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
742 pes->header[2] == 0x01) {
743 /* it must be an mpeg2 PES stream */
744 code = pes->header[3] | 0x100;
745 if (!((code >= 0x1c0 && code <= 0x1df) ||
746 (code >= 0x1e0 && code <= 0x1ef) ||
747 (code == 0x1bd) || (code == 0x1fd)))
750 /* allocate stream */
751 new_pes_av_stream(pes, code);
753 pes->state = MPEGTS_PESHEADER_FILL;
754 pes->total_size = (pes->header[4] << 8) | pes->header[5];
755 /* NOTE: a zero total size means the PES size is
758 pes->total_size += 6;
759 pes->pes_header_size = pes->header[8] + 9;
761 /* otherwise, it should be a table */
764 pes->state = MPEGTS_SKIP;
769 /**********************************************/
770 /* PES packing parsing */
771 case MPEGTS_PESHEADER_FILL:
772 len = pes->pes_header_size - pes->data_index;
775 memcpy(pes->header + pes->data_index, p, len);
776 pes->data_index += len;
779 if (pes->data_index == pes->pes_header_size) {
783 flags = pes->header[7];
785 pes->pts = AV_NOPTS_VALUE;
786 pes->dts = AV_NOPTS_VALUE;
787 if ((flags & 0xc0) == 0x80) {
788 pes->pts = get_pts(r);
790 } else if ((flags & 0xc0) == 0xc0) {
791 pes->pts = get_pts(r);
793 pes->dts = get_pts(r);
796 /* we got the full header. We parse it and get the payload */
797 pes->state = MPEGTS_PAYLOAD;
801 if (pes->total_size) {
802 len = pes->total_size - pes->data_index;
809 AVPacket *pkt = ts->pkt;
810 if (pes->st && av_new_packet(pkt, len) == 0) {
811 memcpy(pkt->data, p, len);
812 pkt->stream_index = pes->st->index;
815 /* reset pts values */
816 pes->pts = AV_NOPTS_VALUE;
817 pes->dts = AV_NOPTS_VALUE;
831 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
834 int codec_type, codec_id;
836 switch(pes->stream_type){
837 case STREAM_TYPE_AUDIO_MPEG1:
838 case STREAM_TYPE_AUDIO_MPEG2:
839 codec_type = CODEC_TYPE_AUDIO;
840 codec_id = CODEC_ID_MP3;
842 case STREAM_TYPE_VIDEO_MPEG1:
843 case STREAM_TYPE_VIDEO_MPEG2:
844 codec_type = CODEC_TYPE_VIDEO;
845 codec_id = CODEC_ID_MPEG2VIDEO;
847 case STREAM_TYPE_VIDEO_MPEG4:
848 codec_type = CODEC_TYPE_VIDEO;
849 codec_id = CODEC_ID_MPEG4;
851 case STREAM_TYPE_VIDEO_H264:
852 codec_type = CODEC_TYPE_VIDEO;
853 codec_id = CODEC_ID_H264;
855 case STREAM_TYPE_VIDEO_VC1:
856 codec_type = CODEC_TYPE_VIDEO;
857 codec_id = CODEC_ID_VC1;
859 case STREAM_TYPE_AUDIO_AAC:
860 codec_type = CODEC_TYPE_AUDIO;
861 codec_id = CODEC_ID_AAC;
863 case STREAM_TYPE_AUDIO_AC3:
864 codec_type = CODEC_TYPE_AUDIO;
865 codec_id = CODEC_ID_AC3;
867 case STREAM_TYPE_AUDIO_DTS:
868 codec_type = CODEC_TYPE_AUDIO;
869 codec_id = CODEC_ID_DTS;
871 case STREAM_TYPE_SUBTITLE_DVB:
872 codec_type = CODEC_TYPE_SUBTITLE;
873 codec_id = CODEC_ID_DVB_SUBTITLE;
876 if (code >= 0x1c0 && code <= 0x1df) {
877 codec_type = CODEC_TYPE_AUDIO;
878 codec_id = CODEC_ID_MP2;
879 } else if (code == 0x1bd) {
880 codec_type = CODEC_TYPE_AUDIO;
881 codec_id = CODEC_ID_AC3;
883 codec_type = CODEC_TYPE_VIDEO;
884 codec_id = CODEC_ID_MPEG1VIDEO;
888 st = av_new_stream(pes->stream, pes->pid);
890 av_set_pts_info(st, 33, 1, 90000);
892 st->codec->codec_type = codec_type;
893 st->codec->codec_id = codec_id;
894 st->need_parsing = AVSTREAM_PARSE_FULL;
901 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
906 /* if no pid found, then add a pid context */
907 pes = av_mallocz(sizeof(PESContext));
911 pes->stream = ts->stream;
913 pes->pcr_pid = pcr_pid;
914 pes->stream_type = stream_type;
915 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
923 /* handle one TS packet */
924 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
926 AVFormatContext *s = ts->stream;
928 int len, pid, cc, cc_ok, afc, is_start;
929 const uint8_t *p, *p_end;
931 pid = ((packet[1] & 0x1f) << 8) | packet[2];
932 is_start = packet[1] & 0x40;
934 if (ts->auto_guess && tss == NULL && is_start) {
935 add_pes_stream(ts, pid, -1, 0);
941 /* continuity check (currently not used) */
942 cc = (packet[3] & 0xf);
943 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
946 /* skip adaptation field */
947 afc = (packet[3] >> 4) & 3;
949 if (afc == 0) /* reserved value */
951 if (afc == 2) /* adaptation field only */
954 /* skip adapation field */
957 /* if past the end of packet, ignore */
958 p_end = packet + TS_PACKET_SIZE;
962 if (tss->type == MPEGTS_SECTION) {
964 /* pointer field present */
969 /* write remaining section bytes */
970 write_section_data(s, tss,
972 /* check whether filter has been closed */
978 write_section_data(s, tss,
983 write_section_data(s, tss,
988 tss->u.pes_filter.pes_cb(tss,
989 p, p_end - p, is_start);
993 /* XXX: try to find a better synchro over several packets (use
994 get_packet_size() ?) */
995 static int mpegts_resync(ByteIOContext *pb)
999 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1004 url_fseek(pb, -1, SEEK_CUR);
1012 /* return -1 if error or EOF. Return 0 if OK. */
1013 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1018 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1019 if (len != TS_PACKET_SIZE)
1021 /* check paquet sync byte */
1022 if (buf[0] != 0x47) {
1023 /* find a new packet start */
1024 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1025 if (mpegts_resync(pb) < 0)
1026 return AVERROR_INVALIDDATA;
1030 skip = raw_packet_size - TS_PACKET_SIZE;
1032 url_fskip(pb, skip);
1039 static int handle_packets(MpegTSContext *ts, int nb_packets)
1041 AVFormatContext *s = ts->stream;
1042 ByteIOContext *pb = &s->pb;
1043 uint8_t packet[TS_PACKET_SIZE];
1044 int packet_num, ret;
1049 if (ts->stop_parse>0)
1052 if (nb_packets != 0 && packet_num >= nb_packets)
1054 ret = read_packet(pb, packet, ts->raw_packet_size);
1057 handle_packet(ts, packet);
1062 static int mpegts_probe(AVProbeData *p)
1065 const int size= p->buf_size;
1066 int score, fec_score, dvhs_score;
1067 #define CHECK_COUNT 10
1069 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1072 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1073 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1074 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1075 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1077 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1078 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1079 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1080 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1083 /* only use the extension for safer guess */
1084 if (match_ext(p->filename, "ts"))
1085 return AVPROBE_SCORE_MAX;
1091 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1092 (-1) if not available */
1093 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1094 const uint8_t *packet)
1096 int afc, len, flags;
1100 afc = (packet[3] >> 4) & 3;
1110 if (!(flags & 0x10))
1114 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1115 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1116 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1120 static int mpegts_read_header(AVFormatContext *s,
1121 AVFormatParameters *ap)
1123 MpegTSContext *ts = s->priv_data;
1124 ByteIOContext *pb = &s->pb;
1130 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1131 if(ap->mpeg2ts_raw){
1132 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1137 /* read the first 1024 bytes to get packet size */
1138 pos = url_ftell(pb);
1139 len = get_buffer(pb, buf, sizeof(buf));
1140 if (len != sizeof(buf))
1142 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1143 if (ts->raw_packet_size <= 0)
1148 if (s->iformat == &mpegts_demuxer) {
1151 /* first do a scaning to get all the services */
1152 url_fseek(pb, pos, SEEK_SET);
1153 mpegts_scan_sdt(ts);
1155 mpegts_set_service(ts);
1157 handle_packets(ts, s->probesize);
1158 /* if could not find service, enable auto_guess */
1163 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1165 s->ctx_flags |= AVFMTCTX_NOHEADER;
1168 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1169 int64_t pcrs[2], pcr_h;
1170 int packet_count[2];
1171 uint8_t packet[TS_PACKET_SIZE];
1173 /* only read packets */
1175 st = av_new_stream(s, 0);
1178 av_set_pts_info(st, 60, 1, 27000000);
1179 st->codec->codec_type = CODEC_TYPE_DATA;
1180 st->codec->codec_id = CODEC_ID_MPEG2TS;
1182 /* we iterate until we find two PCRs to estimate the bitrate */
1187 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1190 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1191 if ((pcr_pid == -1 || pcr_pid == pid) &&
1192 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1194 packet_count[nb_pcrs] = nb_packets;
1195 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1203 /* NOTE1: the bitrate is computed without the FEC */
1204 /* NOTE2: it is only the bitrate of the start of the stream */
1205 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1206 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1207 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1208 st->codec->bit_rate = s->bit_rate;
1209 st->start_time = ts->cur_pcr;
1211 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1212 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1216 url_fseek(pb, pos, SEEK_SET);
1222 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1224 static int mpegts_raw_read_packet(AVFormatContext *s,
1227 MpegTSContext *ts = s->priv_data;
1229 int64_t pcr_h, next_pcr_h, pos;
1230 int pcr_l, next_pcr_l;
1231 uint8_t pcr_buf[12];
1233 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1234 return AVERROR(ENOMEM);
1235 pkt->pos= url_ftell(&s->pb);
1236 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1238 av_free_packet(pkt);
1241 if (ts->mpeg2ts_compute_pcr) {
1242 /* compute exact PCR for each packet */
1243 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1244 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1245 pos = url_ftell(&s->pb);
1246 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1247 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1248 get_buffer(&s->pb, pcr_buf, 12);
1249 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1250 /* XXX: not precise enough */
1251 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1256 url_fseek(&s->pb, pos, SEEK_SET);
1257 /* no next PCR found: we use previous increment */
1258 ts->cur_pcr = pcr_h * 300 + pcr_l;
1260 pkt->pts = ts->cur_pcr;
1261 pkt->duration = ts->pcr_incr;
1262 ts->cur_pcr += ts->pcr_incr;
1264 pkt->stream_index = 0;
1268 static int mpegts_read_packet(AVFormatContext *s,
1271 MpegTSContext *ts = s->priv_data;
1274 return handle_packets(ts, 0);
1277 static int mpegts_read_close(AVFormatContext *s)
1279 MpegTSContext *ts = s->priv_data;
1281 for(i=0;i<NB_PID_MAX;i++)
1282 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1284 for(i = 0; i < ts->nb_services; i++){
1285 av_free(ts->services[i]->provider_name);
1286 av_free(ts->services[i]->name);
1287 av_free(ts->services[i]);
1289 av_freep(&ts->services);
1294 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1295 int64_t *ppos, int64_t pos_limit)
1297 MpegTSContext *ts = s->priv_data;
1298 int64_t pos, timestamp;
1299 uint8_t buf[TS_PACKET_SIZE];
1300 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1301 const int find_next= 1;
1302 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1305 url_fseek(&s->pb, pos, SEEK_SET);
1306 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1307 return AV_NOPTS_VALUE;
1308 if ((pcr_pid < 0 || (((buf[1] & 0x1f) << 8) | buf[2]) == pcr_pid) &&
1309 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1312 pos += ts->raw_packet_size;
1316 pos -= ts->raw_packet_size;
1318 return AV_NOPTS_VALUE;
1319 url_fseek(&s->pb, pos, SEEK_SET);
1320 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1321 return AV_NOPTS_VALUE;
1322 if ((pcr_pid < 0 || (((buf[1] & 0x1f) << 8) | buf[2]) == pcr_pid) &&
1323 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1333 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1334 MpegTSContext *ts = s->priv_data;
1335 uint8_t buf[TS_PACKET_SIZE];
1338 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1341 pos= url_ftell(&s->pb);
1344 url_fseek(&s->pb, pos, SEEK_SET);
1345 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1347 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1348 if(buf[1] & 0x40) break;
1349 pos += ts->raw_packet_size;
1351 url_fseek(&s->pb, pos, SEEK_SET);
1356 /**************************************************************/
1357 /* parsing functions - called from other demuxers such as RTP */
1359 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1363 ts = av_mallocz(sizeof(MpegTSContext));
1366 /* no stream case, currently used by RTP */
1367 ts->raw_packet_size = TS_PACKET_SIZE;
1373 /* return the consumed length if a packet was output, or -1 if no
1375 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1376 const uint8_t *buf, int len)
1384 if (ts->stop_parse>0)
1386 if (len < TS_PACKET_SIZE)
1388 if (buf[0] != 0x47) {
1392 handle_packet(ts, buf);
1393 buf += TS_PACKET_SIZE;
1394 len -= TS_PACKET_SIZE;
1400 void mpegts_parse_close(MpegTSContext *ts)
1404 for(i=0;i<NB_PID_MAX;i++)
1405 av_free(ts->pids[i]);
1409 AVInputFormat mpegts_demuxer = {
1411 "MPEG2 transport stream format",
1412 sizeof(MpegTSContext),
1419 .flags = AVFMT_SHOW_IDS,
1422 AVInputFormat mpegtsraw_demuxer = {
1424 "MPEG2 raw transport stream format",
1425 sizeof(MpegTSContext),
1428 mpegts_raw_read_packet,
1432 .flags = AVFMT_SHOW_IDS,