2 * MPEG2 transport stream (aka DVB) demux
3 * Copyright (c) 2002-2003 Fabrice Bellard.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 /* 1.0 second at 24Mbit/s */
27 #define MAX_SCAN_PACKETS 32000
29 /* maximum size in which we look for synchronisation if
30 synchronisation is lost */
31 #define MAX_RESYNC_SIZE 4096
33 typedef struct PESContext PESContext;
35 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
36 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
38 enum MpegTSFilterType {
43 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
45 typedef struct MpegTSPESFilter {
50 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
52 typedef void SetServiceCallback(void *opaque, int ret);
54 typedef struct MpegTSSectionFilter {
59 int end_of_section_reached:1;
60 SectionCallback *section_cb;
62 } MpegTSSectionFilter;
64 typedef struct MpegTSFilter {
66 int last_cc; /* last cc code (-1 if first packet) */
67 enum MpegTSFilterType type;
69 MpegTSPESFilter pes_filter;
70 MpegTSSectionFilter section_filter;
74 typedef struct MpegTSService {
81 struct MpegTSContext {
83 AVFormatContext *stream;
84 int raw_packet_size; /* raw packet size, including FEC if present */
85 int auto_guess; /* if true, all pids are analized to find streams */
88 int mpeg2ts_raw; /* force raw MPEG2 transport stream output, if possible */
89 int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
91 /* used to estimate the exact PCR */
96 /* data needed to handle file based ts */
97 int stop_parse; /* stop parsing loop */
98 AVPacket *pkt; /* packet containing av data */
100 /******************************************/
101 /* private mpegts data */
103 MpegTSFilter *sdt_filter;
105 MpegTSService **services;
107 /* set service context (XXX: allocated it ?) */
108 SetServiceCallback *set_service_cb;
109 void *set_service_opaque;
110 MpegTSFilter *pat_filter;
111 MpegTSFilter *pmt_filter;
114 MpegTSFilter *pids[NB_PID_MAX];
117 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
118 const uint8_t *buf, int buf_size, int is_start)
120 MpegTSSectionFilter *tss = &tss1->u.section_filter;
124 memcpy(tss->section_buf, buf, buf_size);
125 tss->section_index = buf_size;
126 tss->section_h_size = -1;
127 tss->end_of_section_reached = 0;
129 if (tss->end_of_section_reached)
131 len = 4096 - tss->section_index;
134 memcpy(tss->section_buf + tss->section_index, buf, len);
135 tss->section_index += len;
138 /* compute section length if possible */
139 if (tss->section_h_size == -1 && tss->section_index >= 3) {
140 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
143 tss->section_h_size = len;
146 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
147 tss->end_of_section_reached = 1;
148 if (!tss->check_crc ||
149 mpegts_crc32(tss->section_buf, tss->section_h_size) == 0)
150 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
154 MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
155 SectionCallback *section_cb, void *opaque,
159 MpegTSFilter *filter;
160 MpegTSSectionFilter *sec;
163 printf("Filter: pid=0x%x\n", pid);
165 if (pid >= NB_PID_MAX || ts->pids[pid])
167 filter = av_mallocz(sizeof(MpegTSFilter));
170 ts->pids[pid] = filter;
171 filter->type = MPEGTS_SECTION;
173 filter->last_cc = -1;
174 sec = &filter->u.section_filter;
175 sec->section_cb = section_cb;
176 sec->opaque = opaque;
177 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
178 sec->check_crc = check_crc;
179 if (!sec->section_buf) {
186 MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
190 MpegTSFilter *filter;
191 MpegTSPESFilter *pes;
193 if (pid >= NB_PID_MAX || ts->pids[pid])
195 filter = av_mallocz(sizeof(MpegTSFilter));
198 ts->pids[pid] = filter;
199 filter->type = MPEGTS_PES;
201 filter->last_cc = -1;
202 pes = &filter->u.pes_filter;
203 pes->pes_cb = pes_cb;
204 pes->opaque = opaque;
208 void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
213 if (filter->type == MPEGTS_SECTION)
214 av_freep(&filter->u.section_filter.section_buf);
215 else if (filter->type == MPEGTS_PES)
216 av_freep(&filter->u.pes_filter.opaque);
219 ts->pids[pid] = NULL;
222 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
223 int stat[packet_size];
228 memset(stat, 0, packet_size*sizeof(int));
230 for(x=i=0; i<size; i++){
233 if(stat[x] > best_score){
240 if(x == packet_size) x= 0;
246 /* autodetect fec presence. Must have at least 1024 bytes */
247 static int get_packet_size(const uint8_t *buf, int size)
249 int score, fec_score;
251 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
254 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
255 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
256 // av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
258 if (score > fec_score) return TS_PACKET_SIZE;
259 else if(score < fec_score) return TS_FEC_PACKET_SIZE;
263 typedef struct SectionHeader {
268 uint8_t last_sec_num;
271 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
284 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
290 if ((p + 1) >= p_end)
292 c = (p[0] << 8) | p[1];
298 /* read and allocate a DVB string preceeded by its length */
299 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
306 len = get8(&p, p_end);
309 if ((p + len) > p_end)
311 str = av_malloc(len + 1);
321 static int parse_section_header(SectionHeader *h,
322 const uint8_t **pp, const uint8_t *p_end)
326 val = get8(pp, p_end);
331 val = get16(pp, p_end);
335 val = get8(pp, p_end);
338 h->version = (val >> 1) & 0x1f;
339 val = get8(pp, p_end);
343 val = get8(pp, p_end);
346 h->last_sec_num = val;
350 static MpegTSService *new_service(MpegTSContext *ts, int sid,
351 char *provider_name, char *name)
353 MpegTSService *service;
356 printf("new_service: sid=0x%04x provider='%s' name='%s'\n",
357 sid, provider_name, name);
360 service = av_mallocz(sizeof(MpegTSService));
364 service->provider_name = provider_name;
365 service->name = name;
366 dynarray_add(&ts->services, &ts->nb_services, service);
370 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
372 MpegTSContext *ts = opaque;
373 SectionHeader h1, *h = &h1;
376 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
377 int program_info_length, pcr_pid, pid, stream_type;
378 int desc_list_len, desc_len, desc_tag;
379 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
384 av_hex_dump(stdout, (uint8_t *)section, section_len);
386 p_end = section + section_len - 4;
388 if (parse_section_header(h, &p, p_end) < 0)
391 printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
393 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
396 pcr_pid = get16(&p, p_end) & 0x1fff;
399 ts->pcr_pid = pcr_pid;
401 printf("pcr_pid=0x%x\n", pcr_pid);
403 program_info_length = get16(&p, p_end) & 0xfff;
404 if (program_info_length < 0)
406 p += program_info_length;
412 stream_type = get8(&p, p_end);
415 pid = get16(&p, p_end) & 0x1fff;
418 desc_list_len = get16(&p, p_end) & 0xfff;
419 if (desc_list_len < 0)
421 desc_list_end = p + desc_list_len;
422 if (desc_list_end > p_end)
425 desc_tag = get8(&p, desc_list_end);
428 desc_len = get8(&p, desc_list_end);
429 desc_end = p + desc_len;
430 if (desc_end > desc_list_end)
433 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
436 case DVB_SUBT_DESCID:
437 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
438 stream_type = STREAM_TYPE_SUBTITLE_DVB;
440 language[0] = get8(&p, desc_end);
441 language[1] = get8(&p, desc_end);
442 language[2] = get8(&p, desc_end);
445 comp_page = get16(&p, desc_end);
446 anc_page = get16(&p, desc_end);
449 case 0x0a: /* ISO 639 language descriptor */
450 language[0] = get8(&p, desc_end);
451 language[1] = get8(&p, desc_end);
452 language[2] = get8(&p, desc_end);
463 printf("stream_type=%d pid=0x%x\n", stream_type, pid);
466 /* now create ffmpeg stream */
467 switch(stream_type) {
468 case STREAM_TYPE_AUDIO_MPEG1:
469 case STREAM_TYPE_AUDIO_MPEG2:
470 case STREAM_TYPE_VIDEO_MPEG1:
471 case STREAM_TYPE_VIDEO_MPEG2:
472 case STREAM_TYPE_VIDEO_MPEG4:
473 case STREAM_TYPE_VIDEO_H264:
474 case STREAM_TYPE_AUDIO_AAC:
475 case STREAM_TYPE_AUDIO_AC3:
476 case STREAM_TYPE_AUDIO_DTS:
477 case STREAM_TYPE_SUBTITLE_DVB:
478 pes = add_pes_stream(ts, pid, stream_type);
480 st = new_pes_av_stream(pes, 0);
483 /* we ignore the other streams */
488 if (language[0] != 0) {
489 st->language[0] = language[0];
490 st->language[1] = language[1];
491 st->language[2] = language[2];
492 st->language[3] = language[3];
495 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
496 st->codec->sub_id = (anc_page << 16) | comp_page;
500 /* all parameters are there */
501 ts->set_service_cb(ts->set_service_opaque, 0);
502 mpegts_close_filter(ts, ts->pmt_filter);
503 ts->pmt_filter = NULL;
506 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
508 MpegTSContext *ts = opaque;
509 SectionHeader h1, *h = &h1;
510 const uint8_t *p, *p_end;
515 av_hex_dump(stdout, (uint8_t *)section, section_len);
517 p_end = section + section_len - 4;
519 if (parse_section_header(h, &p, p_end) < 0)
521 if (h->tid != PAT_TID)
525 sid = get16(&p, p_end);
528 pmt_pid = get16(&p, p_end) & 0x1fff;
532 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
537 if (ts->req_sid == sid) {
538 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
545 ts->set_service_cb(ts->set_service_opaque, -1);
548 mpegts_close_filter(ts, ts->pat_filter);
549 ts->pat_filter = NULL;
552 /* add all services found in the PAT */
553 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
555 MpegTSContext *ts = opaque;
556 SectionHeader h1, *h = &h1;
557 const uint8_t *p, *p_end;
559 char *provider_name, *name;
564 av_hex_dump(stdout, (uint8_t *)section, section_len);
566 p_end = section + section_len - 4;
568 if (parse_section_header(h, &p, p_end) < 0)
570 if (h->tid != PAT_TID)
574 sid = get16(&p, p_end);
577 pmt_pid = get16(&p, p_end) & 0x1fff;
581 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
586 /* add the service with a dummy name */
587 snprintf(buf, sizeof(buf), "Service %x\n", sid);
588 name = av_strdup(buf);
589 provider_name = av_strdup("");
590 if (name && provider_name) {
591 new_service(ts, sid, provider_name, name);
594 av_freep(&provider_name);
601 mpegts_close_filter(ts, ts->pat_filter);
602 ts->pat_filter = NULL;
605 void mpegts_set_service(MpegTSContext *ts, int sid,
606 SetServiceCallback *set_service_cb, void *opaque)
608 ts->set_service_cb = set_service_cb;
609 ts->set_service_opaque = opaque;
611 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
615 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
617 MpegTSContext *ts = opaque;
618 SectionHeader h1, *h = &h1;
619 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
620 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
621 char *name, *provider_name;
625 av_hex_dump(stdout, (uint8_t *)section, section_len);
628 p_end = section + section_len - 4;
630 if (parse_section_header(h, &p, p_end) < 0)
632 if (h->tid != SDT_TID)
634 onid = get16(&p, p_end);
637 val = get8(&p, p_end);
641 sid = get16(&p, p_end);
644 val = get8(&p, p_end);
647 desc_list_len = get16(&p, p_end) & 0xfff;
648 if (desc_list_len < 0)
650 desc_list_end = p + desc_list_len;
651 if (desc_list_end > p_end)
654 desc_tag = get8(&p, desc_list_end);
657 desc_len = get8(&p, desc_list_end);
658 desc_end = p + desc_len;
659 if (desc_end > desc_list_end)
662 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
666 service_type = get8(&p, p_end);
667 if (service_type < 0)
669 provider_name = getstr8(&p, p_end);
672 name = getstr8(&p, p_end);
675 new_service(ts, sid, provider_name, name);
687 mpegts_close_filter(ts, ts->sdt_filter);
688 ts->sdt_filter = NULL;
691 /* scan services in a transport stream by looking at the SDT */
692 void mpegts_scan_sdt(MpegTSContext *ts)
694 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
698 /* scan services in a transport stream by looking at the PAT (better
700 void mpegts_scan_pat(MpegTSContext *ts)
702 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
706 /* TS stream handling */
710 MPEGTS_PESHEADER_FILL,
715 /* enough for PES header + length */
716 #define PES_START_SIZE 9
717 #define MAX_PES_HEADER_SIZE (9 + 255)
723 AVFormatContext *stream;
725 enum MpegTSState state;
726 /* used to get the format */
731 uint8_t header[MAX_PES_HEADER_SIZE];
734 static int64_t get_pts(const uint8_t *p)
739 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
740 val = (p[1] << 8) | p[2];
741 pts |= (int64_t)(val >> 1) << 15;
742 val = (p[3] << 8) | p[4];
743 pts |= (int64_t)(val >> 1);
747 /* return non zero if a packet could be constructed */
748 static void mpegts_push_data(void *opaque,
749 const uint8_t *buf, int buf_size, int is_start)
751 PESContext *pes = opaque;
752 MpegTSContext *ts = pes->ts;
757 pes->state = MPEGTS_HEADER;
761 while (buf_size > 0) {
764 len = PES_START_SIZE - pes->data_index;
767 memcpy(pes->header + pes->data_index, p, len);
768 pes->data_index += len;
771 if (pes->data_index == PES_START_SIZE) {
772 /* we got all the PES or section header. We can now
775 av_hex_dump(pes->header, pes->data_index);
777 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
778 pes->header[2] == 0x01) {
779 /* it must be an mpeg2 PES stream */
780 code = pes->header[3] | 0x100;
781 if (!((code >= 0x1c0 && code <= 0x1df) ||
782 (code >= 0x1e0 && code <= 0x1ef) ||
786 /* allocate stream */
787 new_pes_av_stream(pes, code);
789 pes->state = MPEGTS_PESHEADER_FILL;
790 pes->total_size = (pes->header[4] << 8) | pes->header[5];
791 /* NOTE: a zero total size means the PES size is
794 pes->total_size += 6;
795 pes->pes_header_size = pes->header[8] + 9;
797 /* otherwise, it should be a table */
800 pes->state = MPEGTS_SKIP;
805 /**********************************************/
806 /* PES packing parsing */
807 case MPEGTS_PESHEADER_FILL:
808 len = pes->pes_header_size - pes->data_index;
811 memcpy(pes->header + pes->data_index, p, len);
812 pes->data_index += len;
815 if (pes->data_index == pes->pes_header_size) {
819 flags = pes->header[7];
821 pes->pts = AV_NOPTS_VALUE;
822 pes->dts = AV_NOPTS_VALUE;
823 if ((flags & 0xc0) == 0x80) {
824 pes->pts = get_pts(r);
826 } else if ((flags & 0xc0) == 0xc0) {
827 pes->pts = get_pts(r);
829 pes->dts = get_pts(r);
832 /* we got the full header. We parse it and get the payload */
833 pes->state = MPEGTS_PAYLOAD;
837 if (pes->total_size) {
838 len = pes->total_size - pes->data_index;
845 AVPacket *pkt = ts->pkt;
846 if (pes->st && av_new_packet(pkt, len) == 0) {
847 memcpy(pkt->data, p, len);
848 pkt->stream_index = pes->st->index;
851 /* reset pts values */
852 pes->pts = AV_NOPTS_VALUE;
853 pes->dts = AV_NOPTS_VALUE;
867 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
870 int codec_type, codec_id;
872 switch(pes->stream_type){
873 case STREAM_TYPE_AUDIO_MPEG1:
874 case STREAM_TYPE_AUDIO_MPEG2:
875 codec_type = CODEC_TYPE_AUDIO;
876 codec_id = CODEC_ID_MP3;
878 case STREAM_TYPE_VIDEO_MPEG1:
879 case STREAM_TYPE_VIDEO_MPEG2:
880 codec_type = CODEC_TYPE_VIDEO;
881 codec_id = CODEC_ID_MPEG2VIDEO;
883 case STREAM_TYPE_VIDEO_MPEG4:
884 codec_type = CODEC_TYPE_VIDEO;
885 codec_id = CODEC_ID_MPEG4;
887 case STREAM_TYPE_VIDEO_H264:
888 codec_type = CODEC_TYPE_VIDEO;
889 codec_id = CODEC_ID_H264;
891 case STREAM_TYPE_AUDIO_AAC:
892 codec_type = CODEC_TYPE_AUDIO;
893 codec_id = CODEC_ID_AAC;
895 case STREAM_TYPE_AUDIO_AC3:
896 codec_type = CODEC_TYPE_AUDIO;
897 codec_id = CODEC_ID_AC3;
899 case STREAM_TYPE_AUDIO_DTS:
900 codec_type = CODEC_TYPE_AUDIO;
901 codec_id = CODEC_ID_DTS;
903 case STREAM_TYPE_SUBTITLE_DVB:
904 codec_type = CODEC_TYPE_SUBTITLE;
905 codec_id = CODEC_ID_DVB_SUBTITLE;
908 if (code >= 0x1c0 && code <= 0x1df) {
909 codec_type = CODEC_TYPE_AUDIO;
910 codec_id = CODEC_ID_MP2;
911 } else if (code == 0x1bd) {
912 codec_type = CODEC_TYPE_AUDIO;
913 codec_id = CODEC_ID_AC3;
915 codec_type = CODEC_TYPE_VIDEO;
916 codec_id = CODEC_ID_MPEG1VIDEO;
920 st = av_new_stream(pes->stream, pes->pid);
922 av_set_pts_info(st, 33, 1, 90000);
924 st->codec->codec_type = codec_type;
925 st->codec->codec_id = codec_id;
926 st->need_parsing = 1;
933 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
938 /* if no pid found, then add a pid context */
939 pes = av_mallocz(sizeof(PESContext));
943 pes->stream = ts->stream;
945 pes->stream_type = stream_type;
946 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
954 /* handle one TS packet */
955 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
957 AVFormatContext *s = ts->stream;
959 int len, pid, cc, cc_ok, afc, is_start;
960 const uint8_t *p, *p_end;
962 pid = ((packet[1] & 0x1f) << 8) | packet[2];
963 is_start = packet[1] & 0x40;
965 if (ts->auto_guess && tss == NULL && is_start) {
966 add_pes_stream(ts, pid, 0);
972 /* continuity check (currently not used) */
973 cc = (packet[3] & 0xf);
974 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
977 /* skip adaptation field */
978 afc = (packet[3] >> 4) & 3;
980 if (afc == 0) /* reserved value */
982 if (afc == 2) /* adaptation field only */
985 /* skip adapation field */
988 /* if past the end of packet, ignore */
989 p_end = packet + TS_PACKET_SIZE;
993 if (tss->type == MPEGTS_SECTION) {
995 /* pointer field present */
1000 /* write remaining section bytes */
1001 write_section_data(s, tss,
1003 /* check whether filter has been closed */
1009 write_section_data(s, tss,
1014 write_section_data(s, tss,
1019 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
1020 p, p_end - p, is_start);
1024 /* XXX: try to find a better synchro over several packets (use
1025 get_packet_size() ?) */
1026 static int mpegts_resync(ByteIOContext *pb)
1030 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1035 url_fseek(pb, -1, SEEK_CUR);
1043 /* return -1 if error or EOF. Return 0 if OK. */
1044 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1049 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1050 if (len != TS_PACKET_SIZE)
1052 /* check paquet sync byte */
1053 if (buf[0] != 0x47) {
1054 /* find a new packet start */
1055 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1056 if (mpegts_resync(pb) < 0)
1057 return AVERROR_INVALIDDATA;
1061 skip = raw_packet_size - TS_PACKET_SIZE;
1063 url_fskip(pb, skip);
1070 static int handle_packets(MpegTSContext *ts, int nb_packets)
1072 AVFormatContext *s = ts->stream;
1073 ByteIOContext *pb = &s->pb;
1074 uint8_t packet[TS_PACKET_SIZE];
1075 int packet_num, ret;
1083 if (nb_packets != 0 && packet_num >= nb_packets)
1085 ret = read_packet(pb, packet, ts->raw_packet_size);
1088 handle_packet(ts, packet);
1093 static int mpegts_probe(AVProbeData *p)
1096 const int size= p->buf_size;
1097 int score, fec_score;
1098 #define CHECK_COUNT 10
1100 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1103 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1104 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1105 // av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
1107 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1108 if (score > fec_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1109 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1112 /* only use the extension for safer guess */
1113 if (match_ext(p->filename, "ts"))
1114 return AVPROBE_SCORE_MAX;
1120 void set_service_cb(void *opaque, int ret)
1122 MpegTSContext *ts = opaque;
1123 ts->set_service_ret = ret;
1127 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1128 (-1) if not available */
1129 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1130 const uint8_t *packet)
1132 int afc, len, flags;
1136 afc = (packet[3] >> 4) & 3;
1146 if (!(flags & 0x10))
1150 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1151 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1152 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1156 static int mpegts_read_header(AVFormatContext *s,
1157 AVFormatParameters *ap)
1159 MpegTSContext *ts = s->priv_data;
1160 ByteIOContext *pb = &s->pb;
1164 MpegTSService *service;
1167 ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1168 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1171 /* read the first 1024 bytes to get packet size */
1172 pos = url_ftell(pb);
1173 len = get_buffer(pb, buf, sizeof(buf));
1174 if (len != sizeof(buf))
1176 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1177 if (ts->raw_packet_size <= 0)
1182 if (!ts->mpeg2ts_raw) {
1185 if (!ts->auto_guess) {
1186 ts->set_service_ret = -1;
1188 /* first do a scaning to get all the services */
1189 url_fseek(pb, pos, SEEK_SET);
1190 mpegts_scan_sdt(ts);
1192 handle_packets(ts, MAX_SCAN_PACKETS);
1194 if (ts->nb_services <= 0) {
1195 /* no SDT found, we try to look at the PAT */
1197 /* First remove the SDT filters from each PID */
1199 for (i=0; i < NB_PID_MAX; i++) {
1201 mpegts_close_filter(ts, ts->pids[i]);
1203 url_fseek(pb, pos, SEEK_SET);
1204 mpegts_scan_pat(ts);
1206 handle_packets(ts, MAX_SCAN_PACKETS);
1209 if (ts->nb_services <= 0) {
1210 /* raw transport stream */
1212 s->ctx_flags |= AVFMTCTX_NOHEADER;
1216 /* tune to first service found */
1217 for(i=0; i<ts->nb_services && ts->set_service_ret; i++){
1218 service = ts->services[i];
1221 printf("tuning to '%s'\n", service->name);
1224 /* now find the info for the first service if we found any,
1225 otherwise try to filter all PATs */
1227 url_fseek(pb, pos, SEEK_SET);
1228 mpegts_set_service(ts, sid, set_service_cb, ts);
1230 handle_packets(ts, MAX_SCAN_PACKETS);
1232 /* if could not find service, exit */
1234 if (ts->set_service_ret != 0)
1238 printf("tuning done\n");
1241 s->ctx_flags |= AVFMTCTX_NOHEADER;
1244 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1245 int64_t pcrs[2], pcr_h;
1246 int packet_count[2];
1247 uint8_t packet[TS_PACKET_SIZE];
1249 /* only read packets */
1252 st = av_new_stream(s, 0);
1255 av_set_pts_info(st, 60, 1, 27000000);
1256 st->codec->codec_type = CODEC_TYPE_DATA;
1257 st->codec->codec_id = CODEC_ID_MPEG2TS;
1259 /* we iterate until we find two PCRs to estimate the bitrate */
1264 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1267 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1268 if ((pcr_pid == -1 || pcr_pid == pid) &&
1269 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1271 packet_count[nb_pcrs] = nb_packets;
1272 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1279 ts->pcr_pid = pcr_pid;
1281 /* NOTE1: the bitrate is computed without the FEC */
1282 /* NOTE2: it is only the bitrate of the start of the stream */
1283 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1284 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1285 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1286 st->codec->bit_rate = s->bit_rate;
1287 st->start_time = ts->cur_pcr;
1289 printf("start=%0.3f pcr=%0.3f incr=%d\n",
1290 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1294 url_fseek(pb, pos, SEEK_SET);
1300 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1302 static int mpegts_raw_read_packet(AVFormatContext *s,
1305 MpegTSContext *ts = s->priv_data;
1307 int64_t pcr_h, next_pcr_h, pos;
1308 int pcr_l, next_pcr_l;
1309 uint8_t pcr_buf[12];
1311 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1313 pkt->pos= url_ftell(&s->pb);
1314 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1316 av_free_packet(pkt);
1319 if (ts->mpeg2ts_compute_pcr) {
1320 /* compute exact PCR for each packet */
1321 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1322 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1323 pos = url_ftell(&s->pb);
1324 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1325 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1326 get_buffer(&s->pb, pcr_buf, 12);
1327 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1328 /* XXX: not precise enough */
1329 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1334 url_fseek(&s->pb, pos, SEEK_SET);
1335 /* no next PCR found: we use previous increment */
1336 ts->cur_pcr = pcr_h * 300 + pcr_l;
1338 pkt->pts = ts->cur_pcr;
1339 pkt->duration = ts->pcr_incr;
1340 ts->cur_pcr += ts->pcr_incr;
1342 pkt->stream_index = 0;
1346 static int mpegts_read_packet(AVFormatContext *s,
1349 MpegTSContext *ts = s->priv_data;
1351 if (!ts->mpeg2ts_raw) {
1353 return handle_packets(ts, 0);
1355 return mpegts_raw_read_packet(s, pkt);
1359 static int mpegts_read_close(AVFormatContext *s)
1361 MpegTSContext *ts = s->priv_data;
1363 for(i=0;i<NB_PID_MAX;i++)
1364 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1368 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1369 int64_t *ppos, int64_t pos_limit)
1371 MpegTSContext *ts = s->priv_data;
1372 int64_t pos, timestamp;
1373 uint8_t buf[TS_PACKET_SIZE];
1375 const int find_next= 1;
1376 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1379 url_fseek(&s->pb, pos, SEEK_SET);
1380 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1381 return AV_NOPTS_VALUE;
1382 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1383 if (pid == ts->pcr_pid &&
1384 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1387 pos += ts->raw_packet_size;
1391 pos -= ts->raw_packet_size;
1393 return AV_NOPTS_VALUE;
1394 url_fseek(&s->pb, pos, SEEK_SET);
1395 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1396 return AV_NOPTS_VALUE;
1397 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1398 if (pid == ts->pcr_pid &&
1399 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1409 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1410 MpegTSContext *ts = s->priv_data;
1411 uint8_t buf[TS_PACKET_SIZE];
1414 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1417 pos= url_ftell(&s->pb);
1420 url_fseek(&s->pb, pos, SEEK_SET);
1421 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1423 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1424 if(buf[1] & 0x40) break;
1425 pos += ts->raw_packet_size;
1427 url_fseek(&s->pb, pos, SEEK_SET);
1432 /**************************************************************/
1433 /* parsing functions - called from other demuxers such as RTP */
1435 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1439 ts = av_mallocz(sizeof(MpegTSContext));
1442 /* no stream case, currently used by RTP */
1443 ts->raw_packet_size = TS_PACKET_SIZE;
1449 /* return the consumed length if a packet was output, or -1 if no
1451 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1452 const uint8_t *buf, int len)
1462 if (len < TS_PACKET_SIZE)
1464 if (buf[0] != 0x47) {
1468 handle_packet(ts, buf);
1469 buf += TS_PACKET_SIZE;
1470 len -= TS_PACKET_SIZE;
1476 void mpegts_parse_close(MpegTSContext *ts)
1480 for(i=0;i<NB_PID_MAX;i++)
1481 av_free(ts->pids[i]);
1485 AVInputFormat mpegts_demux = {
1487 "MPEG2 transport stream format",
1488 sizeof(MpegTSContext),
1495 .flags = AVFMT_SHOW_IDS,
1498 int mpegts_init(void)
1500 av_register_input_format(&mpegts_demux);
1501 #ifdef CONFIG_MUXERS
1502 av_register_output_format(&mpegts_mux);