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 struct MpegTSFilter MpegTSFilter;
48 typedef void PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start);
50 typedef struct MpegTSPESFilter {
55 typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
57 typedef void SetServiceCallback(void *opaque, int ret);
59 typedef struct MpegTSSectionFilter {
64 int end_of_section_reached:1;
65 SectionCallback *section_cb;
67 } MpegTSSectionFilter;
71 int last_cc; /* last cc code (-1 if first packet) */
72 enum MpegTSFilterType type;
74 MpegTSPESFilter pes_filter;
75 MpegTSSectionFilter section_filter;
79 typedef struct MpegTSService {
81 int sid; /**< MPEG Program Number of stream */
82 char *provider_name; /**< DVB Network name, "" if not DVB stream */
83 char *name; /**< DVB Service name, "MPEG Program [sid]" if not DVB stream*/
86 struct MpegTSContext {
88 AVFormatContext *stream;
89 /** raw packet size, including FEC if present */
91 /** if true, all pids are analyzed to find streams */
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 */
100 /* data needed to handle file based ts */
101 /** stop parsing loop */
103 /** packet containing Audio/Video data */
106 /******************************************/
107 /* private mpegts data */
109 /** number of PMTs in the last PAT seen */
111 /** list of PMTs in the last PAT seen */
112 MpegTSService **services;
115 /** filters for various streams specified by PMT + for the PAT and PMT */
116 MpegTSFilter *pids[NB_PID_MAX];
119 /* TS stream handling */
123 MPEGTS_PESHEADER_FILL,
128 /* enough for PES header + length */
129 #define PES_START_SIZE 9
130 #define MAX_PES_HEADER_SIZE (9 + 255)
134 int pcr_pid; /**< if -1 then all packets containing PCR are considered */
137 AVFormatContext *stream;
139 enum MpegTSState state;
140 /* used to get the format */
145 uint8_t header[MAX_PES_HEADER_SIZE];
149 * Assembles PES packets out of TS packets, and then calls the "section_cb"
150 * function when they are complete.
152 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
153 const uint8_t *buf, int buf_size, int is_start)
155 MpegTSSectionFilter *tss = &tss1->u.section_filter;
159 memcpy(tss->section_buf, buf, buf_size);
160 tss->section_index = buf_size;
161 tss->section_h_size = -1;
162 tss->end_of_section_reached = 0;
164 if (tss->end_of_section_reached)
166 len = 4096 - tss->section_index;
169 memcpy(tss->section_buf + tss->section_index, buf, len);
170 tss->section_index += len;
173 /* compute section length if possible */
174 if (tss->section_h_size == -1 && tss->section_index >= 3) {
175 len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
178 tss->section_h_size = len;
181 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
182 tss->end_of_section_reached = 1;
183 if (!tss->check_crc ||
184 av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
185 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
189 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
190 SectionCallback *section_cb, void *opaque,
194 MpegTSFilter *filter;
195 MpegTSSectionFilter *sec;
198 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
200 if (pid >= NB_PID_MAX || ts->pids[pid])
202 filter = av_mallocz(sizeof(MpegTSFilter));
205 ts->pids[pid] = filter;
206 filter->type = MPEGTS_SECTION;
208 filter->last_cc = -1;
209 sec = &filter->u.section_filter;
210 sec->section_cb = section_cb;
211 sec->opaque = opaque;
212 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
213 sec->check_crc = check_crc;
214 if (!sec->section_buf) {
221 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
225 MpegTSFilter *filter;
226 MpegTSPESFilter *pes;
228 if (pid >= NB_PID_MAX || ts->pids[pid])
230 filter = av_mallocz(sizeof(MpegTSFilter));
233 ts->pids[pid] = filter;
234 filter->type = MPEGTS_PES;
236 filter->last_cc = -1;
237 pes = &filter->u.pes_filter;
238 pes->pes_cb = pes_cb;
239 pes->opaque = opaque;
243 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
248 if (filter->type == MPEGTS_SECTION)
249 av_freep(&filter->u.section_filter.section_buf);
250 else if (filter->type == MPEGTS_PES)
251 av_freep(&filter->u.pes_filter.opaque);
254 ts->pids[pid] = NULL;
257 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
258 int stat[packet_size];
263 memset(stat, 0, packet_size*sizeof(int));
265 for(x=i=0; i<size; i++){
268 if(stat[x] > best_score){
275 if(x == packet_size) x= 0;
281 /* autodetect fec presence. Must have at least 1024 bytes */
282 static int get_packet_size(const uint8_t *buf, int size)
284 int score, fec_score, dvhs_score;
286 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
289 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
290 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
291 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
292 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
294 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
295 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
296 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
300 typedef struct SectionHeader {
305 uint8_t last_sec_num;
308 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
321 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
327 if ((p + 1) >= p_end)
335 /* read and allocate a DVB string preceeded by its length */
336 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
343 len = get8(&p, p_end);
346 if ((p + len) > p_end)
348 str = av_malloc(len + 1);
358 static int parse_section_header(SectionHeader *h,
359 const uint8_t **pp, const uint8_t *p_end)
363 val = get8(pp, p_end);
368 val = get16(pp, p_end);
372 val = get8(pp, p_end);
375 h->version = (val >> 1) & 0x1f;
376 val = get8(pp, p_end);
380 val = get8(pp, p_end);
383 h->last_sec_num = val;
387 static MpegTSService *new_service(MpegTSContext *ts, int sid,
388 char *provider_name, char *name)
390 MpegTSService *service=NULL;
394 av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
395 "sid=0x%04x provider='%s' name='%s'\n",
396 sid, provider_name, name);
399 for(i=0; i<ts->nb_services; i++)
400 if(ts->services[i]->sid == sid)
401 service= ts->services[i];
404 service = av_mallocz(sizeof(MpegTSService));
407 dynarray_add(&ts->services, &ts->nb_services, service);
410 assert((!provider_name) == (!name));
412 av_free(service->provider_name);
413 av_free(service-> name);
414 service->provider_name = provider_name;
415 service-> name = name;
420 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
422 MpegTSContext *ts = filter->u.section_filter.opaque;
423 SectionHeader h1, *h = &h1;
426 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
427 int program_info_length, pcr_pid, pid, stream_type;
428 int desc_list_len, desc_len, desc_tag;
429 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
430 char language[4] = {0}; /* initialize to kill warnings */
433 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
434 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
436 p_end = section + section_len - 4;
438 if (parse_section_header(h, &p, p_end) < 0)
441 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
442 h->id, h->sec_num, h->last_sec_num);
444 if (h->tid != PMT_TID)
447 pcr_pid = get16(&p, p_end) & 0x1fff;
451 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
453 program_info_length = get16(&p, p_end) & 0xfff;
454 if (program_info_length < 0)
456 p += program_info_length;
462 stream_type = get8(&p, p_end);
465 pid = get16(&p, p_end) & 0x1fff;
468 desc_list_len = get16(&p, p_end) & 0xfff;
469 if (desc_list_len < 0)
471 desc_list_end = p + desc_list_len;
472 if (desc_list_end > p_end)
475 desc_tag = get8(&p, desc_list_end);
478 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
479 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
480 /*assume DVB AC-3 Audio*/
481 stream_type = STREAM_TYPE_AUDIO_AC3;
482 } else if(desc_tag == 0x7B) {
484 stream_type = STREAM_TYPE_AUDIO_DTS;
487 desc_len = get8(&p, desc_list_end);
488 desc_end = p + desc_len;
489 if (desc_end > desc_list_end)
492 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
496 case DVB_SUBT_DESCID:
497 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
498 stream_type = STREAM_TYPE_SUBTITLE_DVB;
500 language[0] = get8(&p, desc_end);
501 language[1] = get8(&p, desc_end);
502 language[2] = get8(&p, desc_end);
505 comp_page = get16(&p, desc_end);
506 anc_page = get16(&p, desc_end);
509 case 0x0a: /* ISO 639 language descriptor */
510 language[0] = get8(&p, desc_end);
511 language[1] = get8(&p, desc_end);
512 language[2] = get8(&p, desc_end);
523 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
527 /* now create ffmpeg stream */
528 switch(stream_type) {
529 case STREAM_TYPE_AUDIO_MPEG1:
530 case STREAM_TYPE_AUDIO_MPEG2:
531 case STREAM_TYPE_VIDEO_MPEG1:
532 case STREAM_TYPE_VIDEO_MPEG2:
533 case STREAM_TYPE_VIDEO_MPEG4:
534 case STREAM_TYPE_VIDEO_H264:
535 case STREAM_TYPE_VIDEO_VC1:
536 case STREAM_TYPE_AUDIO_AAC:
537 case STREAM_TYPE_AUDIO_AC3:
538 case STREAM_TYPE_AUDIO_DTS:
539 case STREAM_TYPE_SUBTITLE_DVB:
541 assert(ts->pids[pid]->type == MPEGTS_PES);
542 pes= ts->pids[pid]->u.pes_filter.opaque;
545 pes = add_pes_stream(ts, pid, pcr_pid, stream_type);
547 st = new_pes_av_stream(pes, 0);
551 /* we ignore the other streams */
556 if (language[0] != 0) {
557 memcpy(st->language, language, 4);
560 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
561 st->codec->sub_id = (anc_page << 16) | comp_page;
565 /* all parameters are there */
567 mpegts_close_filter(ts, filter);
570 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
572 MpegTSContext *ts = filter->u.section_filter.opaque;
573 SectionHeader h1, *h = &h1;
574 const uint8_t *p, *p_end;
578 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
579 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
581 p_end = section + section_len - 4;
583 if (parse_section_header(h, &p, p_end) < 0)
585 if (h->tid != PAT_TID)
589 sid = get16(&p, p_end);
592 pmt_pid = get16(&p, p_end) & 0x1fff;
596 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
601 new_service(ts, sid, NULL, NULL);
603 mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1);
609 mpegts_close_filter(ts, filter);
612 static void mpegts_set_service(MpegTSContext *ts)
614 mpegts_open_section_filter(ts, PAT_PID,
618 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
620 MpegTSContext *ts = filter->u.section_filter.opaque;
621 SectionHeader h1, *h = &h1;
622 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
623 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
624 char *name, *provider_name;
627 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
628 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
631 p_end = section + section_len - 4;
633 if (parse_section_header(h, &p, p_end) < 0)
635 if (h->tid != SDT_TID)
637 onid = get16(&p, p_end);
640 val = get8(&p, p_end);
644 sid = get16(&p, p_end);
647 val = get8(&p, p_end);
650 desc_list_len = get16(&p, p_end) & 0xfff;
651 if (desc_list_len < 0)
653 desc_list_end = p + desc_list_len;
654 if (desc_list_end > p_end)
657 desc_tag = get8(&p, desc_list_end);
660 desc_len = get8(&p, desc_list_end);
661 desc_end = p + desc_len;
662 if (desc_end > desc_list_end)
665 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
670 service_type = get8(&p, p_end);
671 if (service_type < 0)
673 provider_name = getstr8(&p, p_end);
676 name = getstr8(&p, p_end);
679 new_service(ts, sid, provider_name, name);
690 /* scan services in a transport stream by looking at the SDT */
691 static void mpegts_scan_sdt(MpegTSContext *ts)
693 mpegts_open_section_filter(ts, SDT_PID,
697 static int64_t get_pts(const uint8_t *p)
699 int64_t pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
700 pts |= (AV_RB16(p + 1) >> 1) << 15;
701 pts |= AV_RB16(p + 3) >> 1;
705 /* return non zero if a packet could be constructed */
706 static void mpegts_push_data(MpegTSFilter *filter,
707 const uint8_t *buf, int buf_size, int is_start)
709 PESContext *pes = filter->u.pes_filter.opaque;
710 MpegTSContext *ts = pes->ts;
718 pes->state = MPEGTS_HEADER;
722 while (buf_size > 0) {
725 len = PES_START_SIZE - pes->data_index;
728 memcpy(pes->header + pes->data_index, p, len);
729 pes->data_index += len;
732 if (pes->data_index == PES_START_SIZE) {
733 /* we got all the PES or section header. We can now
736 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
738 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
739 pes->header[2] == 0x01) {
740 /* it must be an mpeg2 PES stream */
741 code = pes->header[3] | 0x100;
742 if (!((code >= 0x1c0 && code <= 0x1df) ||
743 (code >= 0x1e0 && code <= 0x1ef) ||
744 (code == 0x1bd) || (code == 0x1fd)))
747 /* allocate stream */
748 new_pes_av_stream(pes, code);
750 pes->state = MPEGTS_PESHEADER_FILL;
751 pes->total_size = AV_RB16(pes->header + 4);
752 /* NOTE: a zero total size means the PES size is
755 pes->total_size += 6;
756 pes->pes_header_size = pes->header[8] + 9;
758 /* otherwise, it should be a table */
761 pes->state = MPEGTS_SKIP;
766 /**********************************************/
767 /* PES packing parsing */
768 case MPEGTS_PESHEADER_FILL:
769 len = pes->pes_header_size - pes->data_index;
772 memcpy(pes->header + pes->data_index, p, len);
773 pes->data_index += len;
776 if (pes->data_index == pes->pes_header_size) {
780 flags = pes->header[7];
782 pes->pts = AV_NOPTS_VALUE;
783 pes->dts = AV_NOPTS_VALUE;
784 if ((flags & 0xc0) == 0x80) {
785 pes->pts = get_pts(r);
787 } else if ((flags & 0xc0) == 0xc0) {
788 pes->pts = get_pts(r);
790 pes->dts = get_pts(r);
793 /* we got the full header. We parse it and get the payload */
794 pes->state = MPEGTS_PAYLOAD;
798 if (pes->total_size) {
799 len = pes->total_size - pes->data_index;
806 AVPacket *pkt = ts->pkt;
807 if (pes->st && av_new_packet(pkt, len) == 0) {
808 memcpy(pkt->data, p, len);
809 pkt->stream_index = pes->st->index;
812 /* reset pts values */
813 pes->pts = AV_NOPTS_VALUE;
814 pes->dts = AV_NOPTS_VALUE;
828 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
831 int codec_type, codec_id;
833 switch(pes->stream_type){
834 case STREAM_TYPE_AUDIO_MPEG1:
835 case STREAM_TYPE_AUDIO_MPEG2:
836 codec_type = CODEC_TYPE_AUDIO;
837 codec_id = CODEC_ID_MP3;
839 case STREAM_TYPE_VIDEO_MPEG1:
840 case STREAM_TYPE_VIDEO_MPEG2:
841 codec_type = CODEC_TYPE_VIDEO;
842 codec_id = CODEC_ID_MPEG2VIDEO;
844 case STREAM_TYPE_VIDEO_MPEG4:
845 codec_type = CODEC_TYPE_VIDEO;
846 codec_id = CODEC_ID_MPEG4;
848 case STREAM_TYPE_VIDEO_H264:
849 codec_type = CODEC_TYPE_VIDEO;
850 codec_id = CODEC_ID_H264;
852 case STREAM_TYPE_VIDEO_VC1:
853 codec_type = CODEC_TYPE_VIDEO;
854 codec_id = CODEC_ID_VC1;
856 case STREAM_TYPE_AUDIO_AAC:
857 codec_type = CODEC_TYPE_AUDIO;
858 codec_id = CODEC_ID_AAC;
860 case STREAM_TYPE_AUDIO_AC3:
861 codec_type = CODEC_TYPE_AUDIO;
862 codec_id = CODEC_ID_AC3;
864 case STREAM_TYPE_AUDIO_DTS:
865 codec_type = CODEC_TYPE_AUDIO;
866 codec_id = CODEC_ID_DTS;
868 case STREAM_TYPE_SUBTITLE_DVB:
869 codec_type = CODEC_TYPE_SUBTITLE;
870 codec_id = CODEC_ID_DVB_SUBTITLE;
873 if (code >= 0x1c0 && code <= 0x1df) {
874 codec_type = CODEC_TYPE_AUDIO;
875 codec_id = CODEC_ID_MP2;
876 } else if (code == 0x1bd) {
877 codec_type = CODEC_TYPE_AUDIO;
878 codec_id = CODEC_ID_AC3;
880 codec_type = CODEC_TYPE_VIDEO;
881 codec_id = CODEC_ID_MPEG1VIDEO;
885 st = av_new_stream(pes->stream, pes->pid);
887 av_set_pts_info(st, 33, 1, 90000);
889 st->codec->codec_type = codec_type;
890 st->codec->codec_id = codec_id;
891 st->need_parsing = AVSTREAM_PARSE_FULL;
898 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid, int stream_type)
903 /* if no pid found, then add a pid context */
904 pes = av_mallocz(sizeof(PESContext));
908 pes->stream = ts->stream;
910 pes->pcr_pid = pcr_pid;
911 pes->stream_type = stream_type;
912 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
920 /* handle one TS packet */
921 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
923 AVFormatContext *s = ts->stream;
925 int len, pid, cc, cc_ok, afc, is_start;
926 const uint8_t *p, *p_end;
928 pid = AV_RB16(packet + 1) & 0x1fff;
929 is_start = packet[1] & 0x40;
931 if (ts->auto_guess && tss == NULL && is_start) {
932 add_pes_stream(ts, pid, -1, 0);
938 /* continuity check (currently not used) */
939 cc = (packet[3] & 0xf);
940 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
943 /* skip adaptation field */
944 afc = (packet[3] >> 4) & 3;
946 if (afc == 0) /* reserved value */
948 if (afc == 2) /* adaptation field only */
951 /* skip adapation field */
954 /* if past the end of packet, ignore */
955 p_end = packet + TS_PACKET_SIZE;
959 if (tss->type == MPEGTS_SECTION) {
961 /* pointer field present */
966 /* write remaining section bytes */
967 write_section_data(s, tss,
969 /* check whether filter has been closed */
975 write_section_data(s, tss,
980 write_section_data(s, tss,
985 tss->u.pes_filter.pes_cb(tss,
986 p, p_end - p, is_start);
990 /* XXX: try to find a better synchro over several packets (use
991 get_packet_size() ?) */
992 static int mpegts_resync(ByteIOContext *pb)
996 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1001 url_fseek(pb, -1, SEEK_CUR);
1009 /* return -1 if error or EOF. Return 0 if OK. */
1010 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1015 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1016 if (len != TS_PACKET_SIZE)
1018 /* check paquet sync byte */
1019 if (buf[0] != 0x47) {
1020 /* find a new packet start */
1021 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1022 if (mpegts_resync(pb) < 0)
1023 return AVERROR_INVALIDDATA;
1027 skip = raw_packet_size - TS_PACKET_SIZE;
1029 url_fskip(pb, skip);
1036 static int handle_packets(MpegTSContext *ts, int nb_packets)
1038 AVFormatContext *s = ts->stream;
1039 ByteIOContext *pb = &s->pb;
1040 uint8_t packet[TS_PACKET_SIZE];
1041 int packet_num, ret;
1046 if (ts->stop_parse>0)
1049 if (nb_packets != 0 && packet_num >= nb_packets)
1051 ret = read_packet(pb, packet, ts->raw_packet_size);
1054 handle_packet(ts, packet);
1059 static int mpegts_probe(AVProbeData *p)
1062 const int size= p->buf_size;
1063 int score, fec_score, dvhs_score;
1064 #define CHECK_COUNT 10
1066 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1069 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1070 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1071 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1072 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1074 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1075 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1076 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1077 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1080 /* only use the extension for safer guess */
1081 if (match_ext(p->filename, "ts"))
1082 return AVPROBE_SCORE_MAX;
1088 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1089 (-1) if not available */
1090 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1091 const uint8_t *packet)
1093 int afc, len, flags;
1097 afc = (packet[3] >> 4) & 3;
1107 if (!(flags & 0x10))
1112 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1113 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1117 static int mpegts_read_header(AVFormatContext *s,
1118 AVFormatParameters *ap)
1120 MpegTSContext *ts = s->priv_data;
1121 ByteIOContext *pb = &s->pb;
1127 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1128 if(ap->mpeg2ts_raw){
1129 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1134 /* read the first 1024 bytes to get packet size */
1135 pos = url_ftell(pb);
1136 len = get_buffer(pb, buf, sizeof(buf));
1137 if (len != sizeof(buf))
1139 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1140 if (ts->raw_packet_size <= 0)
1145 if (s->iformat == &mpegts_demuxer) {
1148 /* first do a scaning to get all the services */
1149 url_fseek(pb, pos, SEEK_SET);
1150 mpegts_scan_sdt(ts);
1152 mpegts_set_service(ts);
1154 handle_packets(ts, s->probesize);
1155 /* if could not find service, enable auto_guess */
1160 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1162 s->ctx_flags |= AVFMTCTX_NOHEADER;
1165 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1166 int64_t pcrs[2], pcr_h;
1167 int packet_count[2];
1168 uint8_t packet[TS_PACKET_SIZE];
1170 /* only read packets */
1172 st = av_new_stream(s, 0);
1175 av_set_pts_info(st, 60, 1, 27000000);
1176 st->codec->codec_type = CODEC_TYPE_DATA;
1177 st->codec->codec_id = CODEC_ID_MPEG2TS;
1179 /* we iterate until we find two PCRs to estimate the bitrate */
1184 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1187 pid = AV_RB16(packet + 1) & 0x1fff;
1188 if ((pcr_pid == -1 || pcr_pid == pid) &&
1189 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1191 packet_count[nb_pcrs] = nb_packets;
1192 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1200 /* NOTE1: the bitrate is computed without the FEC */
1201 /* NOTE2: it is only the bitrate of the start of the stream */
1202 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1203 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1204 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1205 st->codec->bit_rate = s->bit_rate;
1206 st->start_time = ts->cur_pcr;
1208 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1209 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1213 url_fseek(pb, pos, SEEK_SET);
1219 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1221 static int mpegts_raw_read_packet(AVFormatContext *s,
1224 MpegTSContext *ts = s->priv_data;
1226 int64_t pcr_h, next_pcr_h, pos;
1227 int pcr_l, next_pcr_l;
1228 uint8_t pcr_buf[12];
1230 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1231 return AVERROR(ENOMEM);
1232 pkt->pos= url_ftell(&s->pb);
1233 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1235 av_free_packet(pkt);
1238 if (ts->mpeg2ts_compute_pcr) {
1239 /* compute exact PCR for each packet */
1240 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1241 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1242 pos = url_ftell(&s->pb);
1243 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1244 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1245 get_buffer(&s->pb, pcr_buf, 12);
1246 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1247 /* XXX: not precise enough */
1248 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1253 url_fseek(&s->pb, pos, SEEK_SET);
1254 /* no next PCR found: we use previous increment */
1255 ts->cur_pcr = pcr_h * 300 + pcr_l;
1257 pkt->pts = ts->cur_pcr;
1258 pkt->duration = ts->pcr_incr;
1259 ts->cur_pcr += ts->pcr_incr;
1261 pkt->stream_index = 0;
1265 static int mpegts_read_packet(AVFormatContext *s,
1268 MpegTSContext *ts = s->priv_data;
1271 return handle_packets(ts, 0);
1274 static int mpegts_read_close(AVFormatContext *s)
1276 MpegTSContext *ts = s->priv_data;
1278 for(i=0;i<NB_PID_MAX;i++)
1279 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1281 for(i = 0; i < ts->nb_services; i++){
1282 av_free(ts->services[i]->provider_name);
1283 av_free(ts->services[i]->name);
1284 av_free(ts->services[i]);
1286 av_freep(&ts->services);
1291 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1292 int64_t *ppos, int64_t pos_limit)
1294 MpegTSContext *ts = s->priv_data;
1295 int64_t pos, timestamp;
1296 uint8_t buf[TS_PACKET_SIZE];
1297 int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
1298 const int find_next= 1;
1299 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1302 url_fseek(&s->pb, pos, SEEK_SET);
1303 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1304 return AV_NOPTS_VALUE;
1305 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1306 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1309 pos += ts->raw_packet_size;
1313 pos -= ts->raw_packet_size;
1315 return AV_NOPTS_VALUE;
1316 url_fseek(&s->pb, pos, SEEK_SET);
1317 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1318 return AV_NOPTS_VALUE;
1319 if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
1320 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1330 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1331 MpegTSContext *ts = s->priv_data;
1332 uint8_t buf[TS_PACKET_SIZE];
1335 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1338 pos= url_ftell(&s->pb);
1341 url_fseek(&s->pb, pos, SEEK_SET);
1342 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1344 // pid = AV_RB16(buf + 1) & 0x1fff;
1345 if(buf[1] & 0x40) break;
1346 pos += ts->raw_packet_size;
1348 url_fseek(&s->pb, pos, SEEK_SET);
1353 /**************************************************************/
1354 /* parsing functions - called from other demuxers such as RTP */
1356 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1360 ts = av_mallocz(sizeof(MpegTSContext));
1363 /* no stream case, currently used by RTP */
1364 ts->raw_packet_size = TS_PACKET_SIZE;
1370 /* return the consumed length if a packet was output, or -1 if no
1372 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1373 const uint8_t *buf, int len)
1381 if (ts->stop_parse>0)
1383 if (len < TS_PACKET_SIZE)
1385 if (buf[0] != 0x47) {
1389 handle_packet(ts, buf);
1390 buf += TS_PACKET_SIZE;
1391 len -= TS_PACKET_SIZE;
1397 void mpegts_parse_close(MpegTSContext *ts)
1401 for(i=0;i<NB_PID_MAX;i++)
1402 av_free(ts->pids[i]);
1406 AVInputFormat mpegts_demuxer = {
1408 "MPEG2 transport stream format",
1409 sizeof(MpegTSContext),
1416 .flags = AVFMT_SHOW_IDS,
1419 AVInputFormat mpegtsraw_demuxer = {
1421 "MPEG2 raw transport stream format",
1422 sizeof(MpegTSContext),
1425 mpegts_raw_read_packet,
1429 .flags = AVFMT_SHOW_IDS,