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 static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
35 enum MpegTSFilterType {
40 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
42 typedef struct MpegTSPESFilter {
47 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
49 typedef void SetServiceCallback(void *opaque, int ret);
51 typedef struct MpegTSSectionFilter {
56 int end_of_section_reached:1;
57 SectionCallback *section_cb;
59 } MpegTSSectionFilter;
61 typedef struct MpegTSFilter {
63 int last_cc; /* last cc code (-1 if first packet) */
64 enum MpegTSFilterType type;
66 MpegTSPESFilter pes_filter;
67 MpegTSSectionFilter section_filter;
71 typedef struct MpegTSService {
78 struct MpegTSContext {
80 AVFormatContext *stream;
81 int raw_packet_size; /* raw packet size, including FEC if present */
82 int auto_guess; /* if true, all pids are analized to find streams */
85 int mpeg2ts_raw; /* force raw MPEG2 transport stream output, if possible */
86 int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
88 /* used to estimate the exact PCR */
93 /* data needed to handle file based ts */
94 int stop_parse; /* stop parsing loop */
95 AVPacket *pkt; /* packet containing av data */
97 /******************************************/
98 /* private mpegts data */
100 MpegTSFilter *sdt_filter;
102 MpegTSService **services;
104 /* set service context (XXX: allocated it ?) */
105 SetServiceCallback *set_service_cb;
106 void *set_service_opaque;
107 MpegTSFilter *pat_filter;
108 MpegTSFilter *pmt_filter;
111 MpegTSFilter *pids[NB_PID_MAX];
114 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
115 const uint8_t *buf, int buf_size, int is_start)
117 MpegTSSectionFilter *tss = &tss1->u.section_filter;
122 memcpy(tss->section_buf, buf, buf_size);
123 tss->section_index = buf_size;
124 tss->section_h_size = -1;
125 tss->end_of_section_reached = 0;
127 if (tss->end_of_section_reached)
129 len = 4096 - tss->section_index;
132 memcpy(tss->section_buf + tss->section_index, buf, len);
133 tss->section_index += len;
136 /* compute section length if possible */
137 if (tss->section_h_size == -1 && tss->section_index >= 3) {
138 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
141 tss->section_h_size = len;
144 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
145 if (tss->check_crc) {
146 crc = mpegts_crc32(tss->section_buf, tss->section_h_size);
150 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
152 tss->end_of_section_reached = 1;
156 MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
157 SectionCallback *section_cb, void *opaque,
161 MpegTSFilter *filter;
162 MpegTSSectionFilter *sec;
165 printf("Filter: pid=0x%x\n", pid);
167 if (pid >= NB_PID_MAX || ts->pids[pid])
169 filter = av_mallocz(sizeof(MpegTSFilter));
172 ts->pids[pid] = filter;
173 filter->type = MPEGTS_SECTION;
175 filter->last_cc = -1;
176 sec = &filter->u.section_filter;
177 sec->section_cb = section_cb;
178 sec->opaque = opaque;
179 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
180 sec->check_crc = check_crc;
181 if (!sec->section_buf) {
188 MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
192 MpegTSFilter *filter;
193 MpegTSPESFilter *pes;
195 if (pid >= NB_PID_MAX || ts->pids[pid])
197 filter = av_mallocz(sizeof(MpegTSFilter));
200 ts->pids[pid] = filter;
201 filter->type = MPEGTS_PES;
203 filter->last_cc = -1;
204 pes = &filter->u.pes_filter;
205 pes->pes_cb = pes_cb;
206 pes->opaque = opaque;
210 void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
215 if (filter->type == MPEGTS_SECTION)
216 av_freep(&filter->u.section_filter.section_buf);
217 else if (filter->type == MPEGTS_PES)
218 av_freep(&filter->u.pes_filter.opaque);
221 ts->pids[pid] = NULL;
224 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
225 int stat[packet_size];
230 memset(stat, 0, packet_size*sizeof(int));
232 for(x=i=0; i<size; i++){
235 if(stat[x] > best_score){
242 if(x == packet_size) x= 0;
248 /* autodetect fec presence. Must have at least 1024 bytes */
249 static int get_packet_size(const uint8_t *buf, int size)
251 int score, fec_score;
253 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
256 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
257 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
258 // av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
260 if (score > fec_score) return TS_PACKET_SIZE;
261 else if(score < fec_score) return TS_FEC_PACKET_SIZE;
265 typedef struct SectionHeader {
270 uint8_t last_sec_num;
273 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
286 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
292 if ((p + 1) >= p_end)
294 c = (p[0] << 8) | p[1];
300 /* read and allocate a DVB string preceeded by its length */
301 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
308 len = get8(&p, p_end);
311 if ((p + len) > p_end)
313 str = av_malloc(len + 1);
323 static int parse_section_header(SectionHeader *h,
324 const uint8_t **pp, const uint8_t *p_end)
328 val = get8(pp, p_end);
333 val = get16(pp, p_end);
337 val = get8(pp, p_end);
340 h->version = (val >> 1) & 0x1f;
341 val = get8(pp, p_end);
345 val = get8(pp, p_end);
348 h->last_sec_num = val;
352 static MpegTSService *new_service(MpegTSContext *ts, int sid,
353 char *provider_name, char *name)
355 MpegTSService *service;
358 printf("new_service: sid=0x%04x provider='%s' name='%s'\n",
359 sid, provider_name, name);
362 service = av_mallocz(sizeof(MpegTSService));
366 service->provider_name = provider_name;
367 service->name = name;
368 dynarray_add(&ts->services, &ts->nb_services, service);
372 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
374 MpegTSContext *ts = opaque;
375 SectionHeader h1, *h = &h1;
376 const uint8_t *p, *p_end;
377 int program_info_length, pcr_pid, pid, stream_type, desc_length;
381 av_hex_dump(stdout, (uint8_t *)section, section_len);
383 p_end = section + section_len - 4;
385 if (parse_section_header(h, &p, p_end) < 0)
388 printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
390 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
393 pcr_pid = get16(&p, p_end) & 0x1fff;
396 ts->pcr_pid = pcr_pid;
398 printf("pcr_pid=0x%x\n", pcr_pid);
400 program_info_length = get16(&p, p_end) & 0xfff;
401 if (program_info_length < 0)
403 p += program_info_length;
407 stream_type = get8(&p, p_end);
410 pid = get16(&p, p_end) & 0x1fff;
413 desc_length = get16(&p, p_end) & 0xfff;
421 printf("stream_type=%d pid=0x%x\n", stream_type, pid);
424 /* now create ffmpeg stream */
425 switch(stream_type) {
426 case STREAM_TYPE_AUDIO_MPEG1:
427 case STREAM_TYPE_AUDIO_MPEG2:
428 case STREAM_TYPE_VIDEO_MPEG1:
429 case STREAM_TYPE_VIDEO_MPEG2:
430 case STREAM_TYPE_VIDEO_MPEG4:
431 case STREAM_TYPE_VIDEO_H264:
432 case STREAM_TYPE_AUDIO_AAC:
433 case STREAM_TYPE_AUDIO_AC3:
434 case STREAM_TYPE_AUDIO_DTS:
435 add_pes_stream(ts, pid, stream_type);
438 /* we ignore the other streams */
442 /* all parameters are there */
443 ts->set_service_cb(ts->set_service_opaque, 0);
444 mpegts_close_filter(ts, ts->pmt_filter);
445 ts->pmt_filter = NULL;
448 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
450 MpegTSContext *ts = opaque;
451 SectionHeader h1, *h = &h1;
452 const uint8_t *p, *p_end;
457 av_hex_dump(stdout, (uint8_t *)section, section_len);
459 p_end = section + section_len - 4;
461 if (parse_section_header(h, &p, p_end) < 0)
463 if (h->tid != PAT_TID)
467 sid = get16(&p, p_end);
470 pmt_pid = get16(&p, p_end) & 0x1fff;
474 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
479 if (ts->req_sid == sid) {
480 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
487 ts->set_service_cb(ts->set_service_opaque, -1);
490 mpegts_close_filter(ts, ts->pat_filter);
491 ts->pat_filter = NULL;
494 /* add all services found in the PAT */
495 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
497 MpegTSContext *ts = opaque;
498 SectionHeader h1, *h = &h1;
499 const uint8_t *p, *p_end;
501 char *provider_name, *name;
506 av_hex_dump(stdout, (uint8_t *)section, section_len);
508 p_end = section + section_len - 4;
510 if (parse_section_header(h, &p, p_end) < 0)
512 if (h->tid != PAT_TID)
516 sid = get16(&p, p_end);
519 pmt_pid = get16(&p, p_end) & 0x1fff;
523 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
528 /* add the service with a dummy name */
529 snprintf(buf, sizeof(buf), "Service %x\n", sid);
530 name = av_strdup(buf);
531 provider_name = av_strdup("");
532 if (name && provider_name) {
533 new_service(ts, sid, provider_name, name);
536 av_freep(&provider_name);
543 mpegts_close_filter(ts, ts->pat_filter);
544 ts->pat_filter = NULL;
547 void mpegts_set_service(MpegTSContext *ts, int sid,
548 SetServiceCallback *set_service_cb, void *opaque)
550 ts->set_service_cb = set_service_cb;
551 ts->set_service_opaque = opaque;
553 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
557 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
559 MpegTSContext *ts = opaque;
560 SectionHeader h1, *h = &h1;
561 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
562 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
563 char *name, *provider_name;
567 av_hex_dump(stdout, (uint8_t *)section, section_len);
570 p_end = section + section_len - 4;
572 if (parse_section_header(h, &p, p_end) < 0)
574 if (h->tid != SDT_TID)
576 onid = get16(&p, p_end);
579 val = get8(&p, p_end);
583 sid = get16(&p, p_end);
586 val = get8(&p, p_end);
589 desc_list_len = get16(&p, p_end) & 0xfff;
590 if (desc_list_len < 0)
592 desc_list_end = p + desc_list_len;
593 if (desc_list_end > p_end)
596 desc_tag = get8(&p, desc_list_end);
599 desc_len = get8(&p, desc_list_end);
600 desc_end = p + desc_len;
601 if (desc_end > desc_list_end)
604 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
608 service_type = get8(&p, p_end);
609 if (service_type < 0)
611 provider_name = getstr8(&p, p_end);
614 name = getstr8(&p, p_end);
617 new_service(ts, sid, provider_name, name);
629 mpegts_close_filter(ts, ts->sdt_filter);
630 ts->sdt_filter = NULL;
633 /* scan services in a transport stream by looking at the SDT */
634 void mpegts_scan_sdt(MpegTSContext *ts)
636 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
640 /* scan services in a transport stream by looking at the PAT (better
642 void mpegts_scan_pat(MpegTSContext *ts)
644 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
648 /* TS stream handling */
652 MPEGTS_PESHEADER_FILL,
657 /* enough for PES header + length */
658 #define PES_START_SIZE 9
659 #define MAX_PES_HEADER_SIZE (9 + 255)
661 typedef struct PESContext {
665 AVFormatContext *stream;
667 enum MpegTSState state;
668 /* used to get the format */
673 uint8_t header[MAX_PES_HEADER_SIZE];
676 static int64_t get_pts(const uint8_t *p)
681 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
682 val = (p[1] << 8) | p[2];
683 pts |= (int64_t)(val >> 1) << 15;
684 val = (p[3] << 8) | p[4];
685 pts |= (int64_t)(val >> 1);
689 /* return non zero if a packet could be constructed */
690 static void mpegts_push_data(void *opaque,
691 const uint8_t *buf, int buf_size, int is_start)
693 PESContext *pes = opaque;
694 MpegTSContext *ts = pes->ts;
697 int len, code, codec_type, codec_id;
700 pes->state = MPEGTS_HEADER;
704 while (buf_size > 0) {
707 len = PES_START_SIZE - pes->data_index;
710 memcpy(pes->header + pes->data_index, p, len);
711 pes->data_index += len;
714 if (pes->data_index == PES_START_SIZE) {
715 /* we got all the PES or section header. We can now
718 av_hex_dump(pes->header, pes->data_index);
720 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
721 pes->header[2] == 0x01) {
722 /* it must be an mpeg2 PES stream */
723 code = pes->header[3] | 0x100;
724 if (!((code >= 0x1c0 && code <= 0x1df) ||
725 (code >= 0x1e0 && code <= 0x1ef) ||
729 /* allocate stream */
730 switch(pes->stream_type){
731 case STREAM_TYPE_AUDIO_MPEG1:
732 case STREAM_TYPE_AUDIO_MPEG2:
733 codec_type = CODEC_TYPE_AUDIO;
734 codec_id = CODEC_ID_MP3;
736 case STREAM_TYPE_VIDEO_MPEG1:
737 case STREAM_TYPE_VIDEO_MPEG2:
738 codec_type = CODEC_TYPE_VIDEO;
739 codec_id = CODEC_ID_MPEG2VIDEO;
741 case STREAM_TYPE_VIDEO_MPEG4:
742 codec_type = CODEC_TYPE_VIDEO;
743 codec_id = CODEC_ID_MPEG4;
745 case STREAM_TYPE_VIDEO_H264:
746 codec_type = CODEC_TYPE_VIDEO;
747 codec_id = CODEC_ID_H264;
749 case STREAM_TYPE_AUDIO_AAC:
750 codec_type = CODEC_TYPE_AUDIO;
751 codec_id = CODEC_ID_AAC;
753 case STREAM_TYPE_AUDIO_AC3:
754 codec_type = CODEC_TYPE_AUDIO;
755 codec_id = CODEC_ID_AC3;
757 case STREAM_TYPE_AUDIO_DTS:
758 codec_type = CODEC_TYPE_AUDIO;
759 codec_id = CODEC_ID_DTS;
762 if (code >= 0x1c0 && code <= 0x1df) {
763 codec_type = CODEC_TYPE_AUDIO;
764 codec_id = CODEC_ID_MP2;
765 } else if (code == 0x1bd) {
766 codec_type = CODEC_TYPE_AUDIO;
767 codec_id = CODEC_ID_AC3;
769 codec_type = CODEC_TYPE_VIDEO;
770 codec_id = CODEC_ID_MPEG1VIDEO;
774 st = av_new_stream(pes->stream, pes->pid);
776 av_set_pts_info(st, 60, 1, 90000);
778 st->codec.codec_type = codec_type;
779 st->codec.codec_id = codec_id;
780 st->need_parsing = 1;
784 pes->state = MPEGTS_PESHEADER_FILL;
785 pes->total_size = (pes->header[4] << 8) | pes->header[5];
786 /* NOTE: a zero total size means the PES size is
789 pes->total_size += 6;
790 pes->pes_header_size = pes->header[8] + 9;
792 /* otherwise, it should be a table */
795 pes->state = MPEGTS_SKIP;
800 /**********************************************/
801 /* PES packing parsing */
802 case MPEGTS_PESHEADER_FILL:
803 len = pes->pes_header_size - pes->data_index;
806 memcpy(pes->header + pes->data_index, p, len);
807 pes->data_index += len;
810 if (pes->data_index == pes->pes_header_size) {
814 flags = pes->header[7];
816 pes->pts = AV_NOPTS_VALUE;
817 pes->dts = AV_NOPTS_VALUE;
818 if ((flags & 0xc0) == 0x80) {
819 pes->pts = get_pts(r);
821 } else if ((flags & 0xc0) == 0xc0) {
822 pes->pts = get_pts(r);
824 pes->dts = get_pts(r);
827 /* we got the full header. We parse it and get the payload */
828 pes->state = MPEGTS_PAYLOAD;
832 if (pes->total_size) {
833 len = pes->total_size - pes->data_index;
840 AVPacket *pkt = ts->pkt;
841 if (pes->st && av_new_packet(pkt, len) == 0) {
842 memcpy(pkt->data, p, len);
843 pkt->stream_index = pes->st->index;
846 /* reset pts values */
847 pes->pts = AV_NOPTS_VALUE;
848 pes->dts = AV_NOPTS_VALUE;
862 static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
867 /* if no pid found, then add a pid context */
868 pes = av_mallocz(sizeof(PESContext));
872 pes->stream = ts->stream;
874 pes->stream_type = stream_type;
875 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
883 /* handle one TS packet */
884 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
886 AVFormatContext *s = ts->stream;
888 int len, pid, cc, cc_ok, afc, is_start;
889 const uint8_t *p, *p_end;
891 pid = ((packet[1] & 0x1f) << 8) | packet[2];
892 is_start = packet[1] & 0x40;
894 if (ts->auto_guess && tss == NULL && is_start) {
895 add_pes_stream(ts, pid, 0);
901 /* continuity check (currently not used) */
902 cc = (packet[3] & 0xf);
903 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
906 /* skip adaptation field */
907 afc = (packet[3] >> 4) & 3;
909 if (afc == 0) /* reserved value */
911 if (afc == 2) /* adaptation field only */
914 /* skip adapation field */
917 /* if past the end of packet, ignore */
918 p_end = packet + TS_PACKET_SIZE;
922 if (tss->type == MPEGTS_SECTION) {
924 /* pointer field present */
929 /* write remaning section bytes */
930 write_section_data(s, tss,
935 write_section_data(s, tss,
940 write_section_data(s, tss,
945 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
946 p, p_end - p, is_start);
950 /* XXX: try to find a better synchro over several packets (use
951 get_packet_size() ?) */
952 static int mpegts_resync(ByteIOContext *pb)
956 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
961 url_fseek(pb, -1, SEEK_CUR);
969 /* return -1 if error or EOF. Return 0 if OK. */
970 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
975 len = get_buffer(pb, buf, TS_PACKET_SIZE);
976 if (len != TS_PACKET_SIZE)
978 /* check paquet sync byte */
979 if (buf[0] != 0x47) {
980 /* find a new packet start */
981 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
982 if (mpegts_resync(pb) < 0)
983 return AVERROR_INVALIDDATA;
987 skip = raw_packet_size - TS_PACKET_SIZE;
996 static int handle_packets(MpegTSContext *ts, int nb_packets)
998 AVFormatContext *s = ts->stream;
999 ByteIOContext *pb = &s->pb;
1000 uint8_t packet[TS_PACKET_SIZE];
1001 int packet_num, ret;
1009 if (nb_packets != 0 && packet_num >= nb_packets)
1011 ret = read_packet(pb, packet, ts->raw_packet_size);
1014 handle_packet(ts, packet);
1019 static int mpegts_probe(AVProbeData *p)
1022 const int size= p->buf_size;
1023 int score, fec_score;
1024 #define CHECK_COUNT 10
1026 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1029 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1030 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1031 // av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
1033 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1034 if (score > fec_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1035 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1038 /* only use the extension for safer guess */
1039 if (match_ext(p->filename, "ts"))
1040 return AVPROBE_SCORE_MAX;
1046 void set_service_cb(void *opaque, int ret)
1048 MpegTSContext *ts = opaque;
1049 ts->set_service_ret = ret;
1053 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1054 (-1) if not available */
1055 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1056 const uint8_t *packet)
1058 int afc, len, flags;
1062 afc = (packet[3] >> 4) & 3;
1072 if (!(flags & 0x10))
1076 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1077 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1078 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1082 static int mpegts_read_header(AVFormatContext *s,
1083 AVFormatParameters *ap)
1085 MpegTSContext *ts = s->priv_data;
1086 ByteIOContext *pb = &s->pb;
1090 MpegTSService *service;
1093 ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1094 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1097 /* read the first 1024 bytes to get packet size */
1098 pos = url_ftell(pb);
1099 len = get_buffer(pb, buf, sizeof(buf));
1100 if (len != sizeof(buf))
1102 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1103 if (ts->raw_packet_size <= 0)
1108 if (!ts->mpeg2ts_raw) {
1111 if (!ts->auto_guess) {
1112 ts->set_service_ret = -1;
1114 /* first do a scaning to get all the services */
1115 url_fseek(pb, pos, SEEK_SET);
1116 mpegts_scan_sdt(ts);
1118 handle_packets(ts, MAX_SCAN_PACKETS);
1120 if (ts->nb_services <= 0) {
1121 /* no SDT found, we try to look at the PAT */
1123 /* First remove the SDT filters from each PID */
1125 for (i=0; i < NB_PID_MAX; i++) {
1127 mpegts_close_filter(ts, ts->pids[i]);
1129 url_fseek(pb, pos, SEEK_SET);
1130 mpegts_scan_pat(ts);
1132 handle_packets(ts, MAX_SCAN_PACKETS);
1135 if (ts->nb_services <= 0) {
1136 /* raw transport stream */
1138 s->ctx_flags |= AVFMTCTX_NOHEADER;
1142 /* tune to first service found */
1143 for(i=0; i<ts->nb_services && ts->set_service_ret; i++){
1144 service = ts->services[i];
1147 printf("tuning to '%s'\n", service->name);
1150 /* now find the info for the first service if we found any,
1151 otherwise try to filter all PATs */
1153 url_fseek(pb, pos, SEEK_SET);
1154 mpegts_set_service(ts, sid, set_service_cb, ts);
1156 handle_packets(ts, MAX_SCAN_PACKETS);
1158 /* if could not find service, exit */
1160 if (ts->set_service_ret != 0)
1164 printf("tuning done\n");
1167 s->ctx_flags |= AVFMTCTX_NOHEADER;
1170 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1171 int64_t pcrs[2], pcr_h;
1172 int packet_count[2];
1173 uint8_t packet[TS_PACKET_SIZE];
1175 /* only read packets */
1178 st = av_new_stream(s, 0);
1181 av_set_pts_info(st, 60, 1, 27000000);
1182 st->codec.codec_type = CODEC_TYPE_DATA;
1183 st->codec.codec_id = CODEC_ID_MPEG2TS;
1185 /* we iterate until we find two PCRs to estimate the bitrate */
1190 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1193 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1194 if ((pcr_pid == -1 || pcr_pid == pid) &&
1195 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1197 packet_count[nb_pcrs] = nb_packets;
1198 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1205 ts->pcr_pid = pcr_pid;
1207 /* NOTE1: the bitrate is computed without the FEC */
1208 /* NOTE2: it is only the bitrate of the start of the stream */
1209 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1210 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1211 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1212 st->codec.bit_rate = s->bit_rate;
1213 st->start_time = ts->cur_pcr * 1000000.0 / 27.0e6;
1215 printf("start=%0.3f pcr=%0.3f incr=%d\n",
1216 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1220 url_fseek(pb, pos, SEEK_SET);
1226 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1228 static int mpegts_raw_read_packet(AVFormatContext *s,
1231 MpegTSContext *ts = s->priv_data;
1233 int64_t pcr_h, next_pcr_h, pos;
1234 int pcr_l, next_pcr_l;
1235 uint8_t pcr_buf[12];
1237 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1239 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1241 av_free_packet(pkt);
1244 if (ts->mpeg2ts_compute_pcr) {
1245 /* compute exact PCR for each packet */
1246 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1247 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1248 pos = url_ftell(&s->pb);
1249 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1250 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1251 get_buffer(&s->pb, pcr_buf, 12);
1252 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1253 /* XXX: not precise enough */
1254 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1259 url_fseek(&s->pb, pos, SEEK_SET);
1260 /* no next PCR found: we use previous increment */
1261 ts->cur_pcr = pcr_h * 300 + pcr_l;
1263 pkt->pts = ts->cur_pcr;
1264 pkt->duration = ts->pcr_incr;
1265 ts->cur_pcr += ts->pcr_incr;
1267 pkt->stream_index = 0;
1271 static int mpegts_read_packet(AVFormatContext *s,
1274 MpegTSContext *ts = s->priv_data;
1276 if (!ts->mpeg2ts_raw) {
1278 return handle_packets(ts, 0);
1280 return mpegts_raw_read_packet(s, pkt);
1284 static int mpegts_read_close(AVFormatContext *s)
1286 MpegTSContext *ts = s->priv_data;
1288 for(i=0;i<NB_PID_MAX;i++)
1289 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1293 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1294 int64_t *ppos, int64_t pos_limit)
1296 MpegTSContext *ts = s->priv_data;
1297 int64_t pos, timestamp;
1298 uint8_t buf[TS_PACKET_SIZE];
1300 const int find_next= 1;
1301 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1304 url_fseek(&s->pb, pos, SEEK_SET);
1305 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1306 return AV_NOPTS_VALUE;
1307 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1308 if (pid == ts->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 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1323 if (pid == ts->pcr_pid &&
1324 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1334 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts){
1335 MpegTSContext *ts = s->priv_data;
1336 uint8_t buf[TS_PACKET_SIZE];
1339 if(av_seek_frame_binary(s, stream_index, target_ts) < 0)
1342 pos= url_ftell(&s->pb);
1345 url_fseek(&s->pb, pos, SEEK_SET);
1346 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1348 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1349 if(buf[1] & 0x40) break;
1350 pos += ts->raw_packet_size;
1352 url_fseek(&s->pb, pos, SEEK_SET);
1357 /**************************************************************/
1358 /* parsing functions - called from other demuxers such as RTP */
1360 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1364 ts = av_mallocz(sizeof(MpegTSContext));
1367 /* no stream case, currently used by RTP */
1368 ts->raw_packet_size = TS_PACKET_SIZE;
1374 /* return the consumed length if a packet was output, or -1 if no
1376 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1377 const uint8_t *buf, int len)
1387 if (len < TS_PACKET_SIZE)
1389 if (buf[0] != 0x47) {
1393 handle_packet(ts, buf);
1394 buf += TS_PACKET_SIZE;
1395 len -= TS_PACKET_SIZE;
1401 void mpegts_parse_close(MpegTSContext *ts)
1405 for(i=0;i<NB_PID_MAX;i++)
1406 av_free(ts->pids[i]);
1410 AVInputFormat mpegts_demux = {
1412 "MPEG2 transport stream format",
1413 sizeof(MpegTSContext),
1420 .flags = AVFMT_SHOW_IDS,
1423 int mpegts_init(void)
1425 av_register_input_format(&mpegts_demux);
1426 #ifdef CONFIG_ENCODERS
1427 av_register_output_format(&mpegts_mux);