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((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 add_pes_stream(ts, pid, stream_type);
437 /* we ignore the other streams */
441 /* all parameters are there */
442 ts->set_service_cb(ts->set_service_opaque, 0);
443 mpegts_close_filter(ts, ts->pmt_filter);
444 ts->pmt_filter = NULL;
447 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
449 MpegTSContext *ts = opaque;
450 SectionHeader h1, *h = &h1;
451 const uint8_t *p, *p_end;
456 av_hex_dump((uint8_t *)section, section_len);
458 p_end = section + section_len - 4;
460 if (parse_section_header(h, &p, p_end) < 0)
462 if (h->tid != PAT_TID)
466 sid = get16(&p, p_end);
469 pmt_pid = get16(&p, p_end) & 0x1fff;
473 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
478 if (ts->req_sid == sid) {
479 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
486 ts->set_service_cb(ts->set_service_opaque, -1);
489 mpegts_close_filter(ts, ts->pat_filter);
490 ts->pat_filter = NULL;
493 /* add all services found in the PAT */
494 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
496 MpegTSContext *ts = opaque;
497 SectionHeader h1, *h = &h1;
498 const uint8_t *p, *p_end;
500 char *provider_name, *name;
505 av_hex_dump((uint8_t *)section, section_len);
507 p_end = section + section_len - 4;
509 if (parse_section_header(h, &p, p_end) < 0)
511 if (h->tid != PAT_TID)
515 sid = get16(&p, p_end);
518 pmt_pid = get16(&p, p_end) & 0x1fff;
522 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
527 /* add the service with a dummy name */
528 snprintf(buf, sizeof(buf), "Service %x\n", sid);
529 name = av_strdup(buf);
530 provider_name = av_strdup("");
531 if (name && provider_name) {
532 new_service(ts, sid, provider_name, name);
535 av_freep(&provider_name);
542 mpegts_close_filter(ts, ts->pat_filter);
543 ts->pat_filter = NULL;
546 void mpegts_set_service(MpegTSContext *ts, int sid,
547 SetServiceCallback *set_service_cb, void *opaque)
549 ts->set_service_cb = set_service_cb;
550 ts->set_service_opaque = opaque;
552 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
556 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
558 MpegTSContext *ts = opaque;
559 SectionHeader h1, *h = &h1;
560 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
561 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
562 char *name, *provider_name;
566 av_hex_dump((uint8_t *)section, section_len);
569 p_end = section + section_len - 4;
571 if (parse_section_header(h, &p, p_end) < 0)
573 if (h->tid != SDT_TID)
575 onid = get16(&p, p_end);
578 val = get8(&p, p_end);
582 sid = get16(&p, p_end);
585 val = get8(&p, p_end);
588 desc_list_len = get16(&p, p_end) & 0xfff;
589 if (desc_list_len < 0)
591 desc_list_end = p + desc_list_len;
592 if (desc_list_end > p_end)
595 desc_tag = get8(&p, desc_list_end);
598 desc_len = get8(&p, desc_list_end);
599 desc_end = p + desc_len;
600 if (desc_end > desc_list_end)
603 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
607 service_type = get8(&p, p_end);
608 if (service_type < 0)
610 provider_name = getstr8(&p, p_end);
613 name = getstr8(&p, p_end);
616 new_service(ts, sid, provider_name, name);
628 mpegts_close_filter(ts, ts->sdt_filter);
629 ts->sdt_filter = NULL;
632 /* scan services in a transport stream by looking at the SDT */
633 void mpegts_scan_sdt(MpegTSContext *ts)
635 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
639 /* scan services in a transport stream by looking at the PAT (better
641 void mpegts_scan_pat(MpegTSContext *ts)
643 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
647 /* TS stream handling */
651 MPEGTS_PESHEADER_FILL,
656 /* enough for PES header + length */
657 #define PES_START_SIZE 9
658 #define MAX_PES_HEADER_SIZE (9 + 255)
660 typedef struct PESContext {
664 AVFormatContext *stream;
666 enum MpegTSState state;
667 /* used to get the format */
672 uint8_t header[MAX_PES_HEADER_SIZE];
675 static int64_t get_pts(const uint8_t *p)
680 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
681 val = (p[1] << 8) | p[2];
682 pts |= (int64_t)(val >> 1) << 15;
683 val = (p[3] << 8) | p[4];
684 pts |= (int64_t)(val >> 1);
688 /* return non zero if a packet could be constructed */
689 static void mpegts_push_data(void *opaque,
690 const uint8_t *buf, int buf_size, int is_start)
692 PESContext *pes = opaque;
693 MpegTSContext *ts = pes->ts;
696 int len, code, codec_type, codec_id;
699 pes->state = MPEGTS_HEADER;
703 while (buf_size > 0) {
706 len = PES_START_SIZE - pes->data_index;
709 memcpy(pes->header + pes->data_index, p, len);
710 pes->data_index += len;
713 if (pes->data_index == PES_START_SIZE) {
714 /* we got all the PES or section header. We can now
717 av_hex_dump(pes->header, pes->data_index);
719 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
720 pes->header[2] == 0x01) {
721 /* it must be an mpeg2 PES stream */
722 code = pes->header[3] | 0x100;
723 if (!((code >= 0x1c0 && code <= 0x1df) ||
724 (code >= 0x1e0 && code <= 0x1ef) ||
728 /* allocate stream */
729 switch(pes->stream_type){
730 case STREAM_TYPE_AUDIO_MPEG1:
731 case STREAM_TYPE_AUDIO_MPEG2:
732 codec_type = CODEC_TYPE_AUDIO;
733 codec_id = CODEC_ID_MP3;
735 case STREAM_TYPE_VIDEO_MPEG1:
736 case STREAM_TYPE_VIDEO_MPEG2:
737 codec_type = CODEC_TYPE_VIDEO;
738 codec_id = CODEC_ID_MPEG2VIDEO;
740 case STREAM_TYPE_VIDEO_MPEG4:
741 codec_type = CODEC_TYPE_VIDEO;
742 codec_id = CODEC_ID_MPEG4;
744 case STREAM_TYPE_VIDEO_H264:
745 codec_type = CODEC_TYPE_VIDEO;
746 codec_id = CODEC_ID_H264;
748 case STREAM_TYPE_AUDIO_AAC:
749 codec_type = CODEC_TYPE_AUDIO;
750 codec_id = CODEC_ID_AAC;
752 case STREAM_TYPE_AUDIO_AC3:
753 codec_type = CODEC_TYPE_AUDIO;
754 codec_id = CODEC_ID_AC3;
757 if (code >= 0x1c0 && code <= 0x1df) {
758 codec_type = CODEC_TYPE_AUDIO;
759 codec_id = CODEC_ID_MP2;
760 } else if (code == 0x1bd) {
761 codec_type = CODEC_TYPE_AUDIO;
762 codec_id = CODEC_ID_AC3;
764 codec_type = CODEC_TYPE_VIDEO;
765 codec_id = CODEC_ID_MPEG1VIDEO;
769 st = av_new_stream(pes->stream, pes->pid);
772 st->codec.codec_type = codec_type;
773 st->codec.codec_id = codec_id;
774 st->need_parsing = 1;
778 pes->state = MPEGTS_PESHEADER_FILL;
779 pes->total_size = (pes->header[4] << 8) | pes->header[5];
780 /* NOTE: a zero total size means the PES size is
783 pes->total_size += 6;
784 pes->pes_header_size = pes->header[8] + 9;
786 /* otherwise, it should be a table */
789 pes->state = MPEGTS_SKIP;
794 /**********************************************/
795 /* PES packing parsing */
796 case MPEGTS_PESHEADER_FILL:
797 len = pes->pes_header_size - pes->data_index;
800 memcpy(pes->header + pes->data_index, p, len);
801 pes->data_index += len;
804 if (pes->data_index == pes->pes_header_size) {
808 flags = pes->header[7];
810 pes->pts = AV_NOPTS_VALUE;
811 pes->dts = AV_NOPTS_VALUE;
812 if ((flags & 0xc0) == 0x80) {
813 pes->pts = get_pts(r);
815 } else if ((flags & 0xc0) == 0xc0) {
816 pes->pts = get_pts(r);
818 pes->dts = get_pts(r);
821 /* we got the full header. We parse it and get the payload */
822 pes->state = MPEGTS_PAYLOAD;
826 if (pes->total_size) {
827 len = pes->total_size - pes->data_index;
834 AVPacket *pkt = ts->pkt;
835 if (pes->st && av_new_packet(pkt, len) == 0) {
836 memcpy(pkt->data, p, len);
837 pkt->stream_index = pes->st->index;
839 /* reset pts values */
840 pes->pts = AV_NOPTS_VALUE;
841 pes->dts = AV_NOPTS_VALUE;
855 static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
860 /* if no pid found, then add a pid context */
861 pes = av_mallocz(sizeof(PESContext));
865 pes->stream = ts->stream;
867 pes->stream_type = stream_type;
868 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
876 /* handle one TS packet */
877 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
879 AVFormatContext *s = ts->stream;
881 int len, pid, cc, cc_ok, afc, is_start;
882 const uint8_t *p, *p_end;
884 pid = ((packet[1] & 0x1f) << 8) | packet[2];
885 is_start = packet[1] & 0x40;
887 if (ts->auto_guess && tss == NULL && is_start) {
888 add_pes_stream(ts, pid, 0);
894 /* continuity check (currently not used) */
895 cc = (packet[3] & 0xf);
896 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
899 /* skip adaptation field */
900 afc = (packet[3] >> 4) & 3;
902 if (afc == 0) /* reserved value */
904 if (afc == 2) /* adaptation field only */
907 /* skip adapation field */
910 /* if past the end of packet, ignore */
911 p_end = packet + TS_PACKET_SIZE;
915 if (tss->type == MPEGTS_SECTION) {
917 /* pointer field present */
922 /* write remaning section bytes */
923 write_section_data(s, tss,
928 write_section_data(s, tss,
933 write_section_data(s, tss,
938 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
939 p, p_end - p, is_start);
943 /* XXX: try to find a better synchro over several packets (use
944 get_packet_size() ?) */
945 static int mpegts_resync(ByteIOContext *pb)
949 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
954 url_fseek(pb, -1, SEEK_CUR);
962 /* return -1 if error or EOF. Return 0 if OK. */
963 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
968 len = get_buffer(pb, buf, TS_PACKET_SIZE);
969 if (len != TS_PACKET_SIZE)
971 /* check paquet sync byte */
972 if (buf[0] != 0x47) {
973 /* find a new packet start */
974 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
975 if (mpegts_resync(pb) < 0)
976 return AVERROR_INVALIDDATA;
980 skip = raw_packet_size - TS_PACKET_SIZE;
989 static int handle_packets(MpegTSContext *ts, int nb_packets)
991 AVFormatContext *s = ts->stream;
992 ByteIOContext *pb = &s->pb;
993 uint8_t packet[TS_PACKET_SIZE];
1002 if (nb_packets != 0 && packet_num >= nb_packets)
1004 ret = read_packet(pb, packet, ts->raw_packet_size);
1007 handle_packet(ts, packet);
1012 static int mpegts_probe(AVProbeData *p)
1015 const int size= p->buf_size;
1016 int score, fec_score;
1017 #define CHECK_COUNT 10
1019 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1022 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1023 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1024 // av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
1026 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1027 if (score > fec_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1028 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1031 /* only use the extension for safer guess */
1032 if (match_ext(p->filename, "ts"))
1033 return AVPROBE_SCORE_MAX;
1039 void set_service_cb(void *opaque, int ret)
1041 MpegTSContext *ts = opaque;
1042 ts->set_service_ret = ret;
1046 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1047 (-1) if not available */
1048 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1049 const uint8_t *packet)
1051 int afc, len, flags;
1055 afc = (packet[3] >> 4) & 3;
1065 if (!(flags & 0x10))
1069 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1070 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1071 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1075 static int mpegts_read_header(AVFormatContext *s,
1076 AVFormatParameters *ap)
1078 MpegTSContext *ts = s->priv_data;
1079 ByteIOContext *pb = &s->pb;
1083 MpegTSService *service;
1086 ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1087 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1090 /* read the first 1024 bytes to get packet size */
1091 pos = url_ftell(pb);
1092 len = get_buffer(pb, buf, sizeof(buf));
1093 if (len != sizeof(buf))
1095 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1096 if (ts->raw_packet_size <= 0)
1101 if (!ts->mpeg2ts_raw) {
1104 if (!ts->auto_guess) {
1105 ts->set_service_ret = -1;
1107 /* first do a scaning to get all the services */
1108 url_fseek(pb, pos, SEEK_SET);
1109 mpegts_scan_sdt(ts);
1111 handle_packets(ts, MAX_SCAN_PACKETS);
1113 if (ts->nb_services <= 0) {
1114 /* no SDT found, we try to look at the PAT */
1116 /* First remove the SDT filters from each PID */
1118 for (i=0; i < NB_PID_MAX; i++) {
1120 mpegts_close_filter(ts, ts->pids[i]);
1122 url_fseek(pb, pos, SEEK_SET);
1123 mpegts_scan_pat(ts);
1125 handle_packets(ts, MAX_SCAN_PACKETS);
1128 if (ts->nb_services <= 0)
1131 /* tune to first service found */
1132 service = ts->services[0];
1135 printf("tuning to '%s'\n", service->name);
1138 /* now find the info for the first service if we found any,
1139 otherwise try to filter all PATs */
1141 url_fseek(pb, pos, SEEK_SET);
1142 mpegts_set_service(ts, sid, set_service_cb, ts);
1144 handle_packets(ts, MAX_SCAN_PACKETS);
1146 /* if could not find service, exit */
1147 if (ts->set_service_ret != 0)
1151 printf("tuning done\n");
1154 s->ctx_flags |= AVFMTCTX_NOHEADER;
1157 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1158 int64_t pcrs[2], pcr_h;
1159 int packet_count[2];
1160 uint8_t packet[TS_PACKET_SIZE];
1162 /* only read packets */
1165 s->pts_den = 27000000;
1167 st = av_new_stream(s, 0);
1170 st->codec.codec_type = CODEC_TYPE_DATA;
1171 st->codec.codec_id = CODEC_ID_MPEG2TS;
1173 /* we iterate until we find two PCRs to estimate the bitrate */
1178 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1181 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1182 if ((pcr_pid == -1 || pcr_pid == pid) &&
1183 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1185 packet_count[nb_pcrs] = nb_packets;
1186 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1193 ts->pcr_pid = pcr_pid;
1195 /* NOTE1: the bitrate is computed without the FEC */
1196 /* NOTE2: it is only the bitrate of the start of the stream */
1197 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1198 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1199 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1200 st->codec.bit_rate = s->bit_rate;
1201 st->start_time = ts->cur_pcr * 1000000.0 / 27.0e6;
1203 printf("start=%0.3f pcr=%0.3f incr=%d\n",
1204 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1208 url_fseek(pb, pos, SEEK_SET);
1214 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1216 static int mpegts_raw_read_packet(AVFormatContext *s,
1219 MpegTSContext *ts = s->priv_data;
1221 int64_t pcr_h, next_pcr_h, pos;
1222 int pcr_l, next_pcr_l;
1223 uint8_t pcr_buf[12];
1225 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1227 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1229 av_free_packet(pkt);
1232 if (ts->mpeg2ts_compute_pcr) {
1233 /* compute exact PCR for each packet */
1234 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1235 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1236 pos = url_ftell(&s->pb);
1237 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1238 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1239 get_buffer(&s->pb, pcr_buf, 12);
1240 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1241 /* XXX: not precise enough */
1242 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1247 url_fseek(&s->pb, pos, SEEK_SET);
1248 /* no next PCR found: we use previous increment */
1249 ts->cur_pcr = pcr_h * 300 + pcr_l;
1251 pkt->pts = ts->cur_pcr;
1252 pkt->duration = ts->pcr_incr;
1253 ts->cur_pcr += ts->pcr_incr;
1255 pkt->stream_index = 0;
1259 static int mpegts_read_packet(AVFormatContext *s,
1262 MpegTSContext *ts = s->priv_data;
1264 if (!ts->mpeg2ts_raw) {
1266 return handle_packets(ts, 0);
1268 return mpegts_raw_read_packet(s, pkt);
1272 static int mpegts_read_close(AVFormatContext *s)
1274 MpegTSContext *ts = s->priv_data;
1276 for(i=0;i<NB_PID_MAX;i++)
1277 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1281 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1282 int64_t *ppos, int find_next)
1284 MpegTSContext *ts = s->priv_data;
1285 int64_t pos, timestamp;
1286 uint8_t buf[TS_PACKET_SIZE];
1292 url_fseek(&s->pb, pos, SEEK_SET);
1293 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1294 return AV_NOPTS_VALUE;
1295 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1296 if (pid == ts->pcr_pid &&
1297 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1300 pos += ts->raw_packet_size;
1304 pos -= ts->raw_packet_size;
1306 return AV_NOPTS_VALUE;
1307 url_fseek(&s->pb, pos, SEEK_SET);
1308 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1309 return AV_NOPTS_VALUE;
1310 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1311 if (pid == ts->pcr_pid &&
1312 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1321 typedef int64_t ReadTimestampFunc(AVFormatContext *s, int stream_index,
1322 int64_t *ppos, int find_next);
1324 static int64_t do_block_align(int64_t val, int block_align)
1326 return (val / block_align) * block_align;
1329 /* XXX: use it in other formats */
1330 static int timestamp_read_seek(AVFormatContext *s,
1331 int stream_index, int64_t timestamp,
1332 ReadTimestampFunc *read_timestamp,
1335 int64_t pos_min, pos_max, pos;
1336 int64_t dts_min, dts_max, dts;
1339 printf("read_seek: %d %0.3f\n", stream_index, timestamp / 90000.0);
1343 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1344 if (dts_min == AV_NOPTS_VALUE) {
1345 /* we can reach this case only if no PTS are present in
1349 pos_max = do_block_align(url_filesize(url_fileno(&s->pb)), block_align) -
1351 dts_max = read_timestamp(s, stream_index, &pos_max, 0);
1353 while (pos_min <= pos_max) {
1355 printf("pos_min=0x%llx pos_max=0x%llx dts_min=%0.3f dts_max=%0.3f\n",
1357 dts_min / 90000.0, dts_max / 90000.0);
1359 if (timestamp <= dts_min) {
1362 } else if (timestamp >= dts_max) {
1366 /* interpolate position (better than dichotomy) */
1367 pos = (int64_t)((double)(pos_max - pos_min) *
1368 (double)(timestamp - dts_min) /
1369 (double)(dts_max - dts_min)) + pos_min;
1370 pos = do_block_align(pos, block_align);
1373 printf("pos=0x%llx\n", pos);
1375 /* read the next timestamp */
1376 dts = read_timestamp(s, stream_index, &pos, 1);
1377 /* check if we are lucky */
1378 if (dts == AV_NOPTS_VALUE) {
1379 /* should never happen */
1382 } else if (timestamp == dts) {
1384 } else if (timestamp < dts) {
1386 dts_max = read_timestamp(s, stream_index, &pos_max, 0);
1387 if (dts_max == AV_NOPTS_VALUE) {
1388 /* should never happen */
1390 } else if (timestamp >= dts_max) {
1395 pos_min = pos + block_align;
1396 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1397 if (dts_min == AV_NOPTS_VALUE) {
1398 /* should never happen */
1400 } else if (timestamp <= dts_min) {
1409 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1410 pos_min += block_align;
1411 dts_max = read_timestamp(s, stream_index, &pos_min, 1);
1412 printf("pos=0x%llx %0.3f<=%0.3f<=%0.3f\n",
1413 pos, dts_min / 90000.0, timestamp / 90000.0, dts_max / 90000.0);
1416 url_fseek(&s->pb, pos, SEEK_SET);
1420 static int mpegts_read_seek(AVFormatContext *s,
1421 int stream_index, int64_t timestamp)
1423 MpegTSContext *ts = s->priv_data;
1425 timestamp = (timestamp * 90000) / AV_TIME_BASE;
1427 return timestamp_read_seek(s, stream_index, timestamp,
1428 mpegts_get_pcr, ts->raw_packet_size);
1431 /**************************************************************/
1432 /* parsing functions - called from other demuxers such as RTP */
1434 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1438 ts = av_mallocz(sizeof(MpegTSContext));
1441 /* no stream case, currently used by RTP */
1442 ts->raw_packet_size = TS_PACKET_SIZE;
1448 /* return the consumed length if a packet was output, or -1 if no
1450 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1451 const uint8_t *buf, int len)
1461 if (len < TS_PACKET_SIZE)
1463 if (buf[0] != 0x47) {
1467 handle_packet(ts, buf);
1468 buf += TS_PACKET_SIZE;
1469 len -= TS_PACKET_SIZE;
1475 void mpegts_parse_close(MpegTSContext *ts)
1479 for(i=0;i<NB_PID_MAX;i++)
1480 av_free(ts->pids[i]);
1484 AVInputFormat mpegts_demux = {
1486 "MPEG2 transport stream format",
1487 sizeof(MpegTSContext),
1493 .flags = AVFMT_SHOW_IDS,
1496 int mpegts_init(void)
1498 av_register_input_format(&mpegts_demux);
1499 #ifdef CONFIG_ENCODERS
1500 av_register_output_format(&mpegts_mux);