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 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(stdout, (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(stdout, (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(stdout, (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;
840 /* reset pts values */
841 pes->pts = AV_NOPTS_VALUE;
842 pes->dts = AV_NOPTS_VALUE;
856 static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
861 /* if no pid found, then add a pid context */
862 pes = av_mallocz(sizeof(PESContext));
866 pes->stream = ts->stream;
868 pes->stream_type = stream_type;
869 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
877 /* handle one TS packet */
878 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
880 AVFormatContext *s = ts->stream;
882 int len, pid, cc, cc_ok, afc, is_start;
883 const uint8_t *p, *p_end;
885 pid = ((packet[1] & 0x1f) << 8) | packet[2];
886 is_start = packet[1] & 0x40;
888 if (ts->auto_guess && tss == NULL && is_start) {
889 add_pes_stream(ts, pid, 0);
895 /* continuity check (currently not used) */
896 cc = (packet[3] & 0xf);
897 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
900 /* skip adaptation field */
901 afc = (packet[3] >> 4) & 3;
903 if (afc == 0) /* reserved value */
905 if (afc == 2) /* adaptation field only */
908 /* skip adapation field */
911 /* if past the end of packet, ignore */
912 p_end = packet + TS_PACKET_SIZE;
916 if (tss->type == MPEGTS_SECTION) {
918 /* pointer field present */
923 /* write remaning section bytes */
924 write_section_data(s, tss,
929 write_section_data(s, tss,
934 write_section_data(s, tss,
939 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
940 p, p_end - p, is_start);
944 /* XXX: try to find a better synchro over several packets (use
945 get_packet_size() ?) */
946 static int mpegts_resync(ByteIOContext *pb)
950 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
955 url_fseek(pb, -1, SEEK_CUR);
963 /* return -1 if error or EOF. Return 0 if OK. */
964 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
969 len = get_buffer(pb, buf, TS_PACKET_SIZE);
970 if (len != TS_PACKET_SIZE)
972 /* check paquet sync byte */
973 if (buf[0] != 0x47) {
974 /* find a new packet start */
975 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
976 if (mpegts_resync(pb) < 0)
977 return AVERROR_INVALIDDATA;
981 skip = raw_packet_size - TS_PACKET_SIZE;
990 static int handle_packets(MpegTSContext *ts, int nb_packets)
992 AVFormatContext *s = ts->stream;
993 ByteIOContext *pb = &s->pb;
994 uint8_t packet[TS_PACKET_SIZE];
1003 if (nb_packets != 0 && packet_num >= nb_packets)
1005 ret = read_packet(pb, packet, ts->raw_packet_size);
1008 handle_packet(ts, packet);
1013 static int mpegts_probe(AVProbeData *p)
1016 const int size= p->buf_size;
1017 int score, fec_score;
1018 #define CHECK_COUNT 10
1020 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1023 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1024 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1025 // av_log(NULL, AV_LOG_DEBUG, "score: %d, fec_score: %d \n", score, fec_score);
1027 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1028 if (score > fec_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1029 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1032 /* only use the extension for safer guess */
1033 if (match_ext(p->filename, "ts"))
1034 return AVPROBE_SCORE_MAX;
1040 void set_service_cb(void *opaque, int ret)
1042 MpegTSContext *ts = opaque;
1043 ts->set_service_ret = ret;
1047 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1048 (-1) if not available */
1049 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1050 const uint8_t *packet)
1052 int afc, len, flags;
1056 afc = (packet[3] >> 4) & 3;
1066 if (!(flags & 0x10))
1070 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1071 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1072 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1076 static int mpegts_read_header(AVFormatContext *s,
1077 AVFormatParameters *ap)
1079 MpegTSContext *ts = s->priv_data;
1080 ByteIOContext *pb = &s->pb;
1084 MpegTSService *service;
1087 ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1088 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1091 /* read the first 1024 bytes to get packet size */
1092 pos = url_ftell(pb);
1093 len = get_buffer(pb, buf, sizeof(buf));
1094 if (len != sizeof(buf))
1096 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1097 if (ts->raw_packet_size <= 0)
1102 if (!ts->mpeg2ts_raw) {
1105 if (!ts->auto_guess) {
1106 ts->set_service_ret = -1;
1108 /* first do a scaning to get all the services */
1109 url_fseek(pb, pos, SEEK_SET);
1110 mpegts_scan_sdt(ts);
1112 handle_packets(ts, MAX_SCAN_PACKETS);
1114 if (ts->nb_services <= 0) {
1115 /* no SDT found, we try to look at the PAT */
1117 /* First remove the SDT filters from each PID */
1119 for (i=0; i < NB_PID_MAX; i++) {
1121 mpegts_close_filter(ts, ts->pids[i]);
1123 url_fseek(pb, pos, SEEK_SET);
1124 mpegts_scan_pat(ts);
1126 handle_packets(ts, MAX_SCAN_PACKETS);
1129 if (ts->nb_services <= 0) {
1130 /* raw transport stream */
1132 s->ctx_flags |= AVFMTCTX_NOHEADER;
1136 /* tune to first service found */
1137 service = ts->services[0];
1140 printf("tuning to '%s'\n", service->name);
1143 /* now find the info for the first service if we found any,
1144 otherwise try to filter all PATs */
1146 url_fseek(pb, pos, SEEK_SET);
1147 mpegts_set_service(ts, sid, set_service_cb, ts);
1149 handle_packets(ts, MAX_SCAN_PACKETS);
1151 /* if could not find service, exit */
1152 if (ts->set_service_ret != 0)
1156 printf("tuning done\n");
1159 s->ctx_flags |= AVFMTCTX_NOHEADER;
1162 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1163 int64_t pcrs[2], pcr_h;
1164 int packet_count[2];
1165 uint8_t packet[TS_PACKET_SIZE];
1167 /* only read packets */
1170 s->pts_den = 27000000;
1173 st = av_new_stream(s, 0);
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 = ((packet[1] & 0x1f) << 8) | packet[2];
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;
1199 ts->pcr_pid = pcr_pid;
1201 /* NOTE1: the bitrate is computed without the FEC */
1202 /* NOTE2: it is only the bitrate of the start of the stream */
1203 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1204 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1205 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1206 st->codec.bit_rate = s->bit_rate;
1207 st->start_time = ts->cur_pcr * 1000000.0 / 27.0e6;
1209 printf("start=%0.3f pcr=%0.3f incr=%d\n",
1210 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1214 url_fseek(pb, pos, SEEK_SET);
1220 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1222 static int mpegts_raw_read_packet(AVFormatContext *s,
1225 MpegTSContext *ts = s->priv_data;
1227 int64_t pcr_h, next_pcr_h, pos;
1228 int pcr_l, next_pcr_l;
1229 uint8_t pcr_buf[12];
1231 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
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;
1270 if (!ts->mpeg2ts_raw) {
1272 return handle_packets(ts, 0);
1274 return mpegts_raw_read_packet(s, pkt);
1278 static int mpegts_read_close(AVFormatContext *s)
1280 MpegTSContext *ts = s->priv_data;
1282 for(i=0;i<NB_PID_MAX;i++)
1283 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1287 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1288 int64_t *ppos, int find_next)
1290 MpegTSContext *ts = s->priv_data;
1291 int64_t pos, timestamp;
1292 uint8_t buf[TS_PACKET_SIZE];
1298 url_fseek(&s->pb, pos, SEEK_SET);
1299 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1300 return AV_NOPTS_VALUE;
1301 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1302 if (pid == ts->pcr_pid &&
1303 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1306 pos += ts->raw_packet_size;
1310 pos -= ts->raw_packet_size;
1312 return AV_NOPTS_VALUE;
1313 url_fseek(&s->pb, pos, SEEK_SET);
1314 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1315 return AV_NOPTS_VALUE;
1316 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1317 if (pid == ts->pcr_pid &&
1318 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1327 typedef int64_t ReadTimestampFunc(AVFormatContext *s, int stream_index,
1328 int64_t *ppos, int find_next);
1330 static int64_t do_block_align(int64_t val, int block_align)
1332 return (val / block_align) * block_align;
1335 /* XXX: use it in other formats */
1336 static int timestamp_read_seek(AVFormatContext *s,
1337 int stream_index, int64_t timestamp,
1338 ReadTimestampFunc *read_timestamp,
1341 int64_t pos_min, pos_max, pos;
1342 int64_t dts_min, dts_max, dts;
1345 printf("read_seek: %d %0.3f\n", stream_index, timestamp / 90000.0);
1349 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1350 if (dts_min == AV_NOPTS_VALUE) {
1351 /* we can reach this case only if no PTS are present in
1355 pos_max = do_block_align(url_filesize(url_fileno(&s->pb)), block_align) -
1357 dts_max = read_timestamp(s, stream_index, &pos_max, 0);
1359 while (pos_min <= pos_max) {
1361 printf("pos_min=0x%llx pos_max=0x%llx dts_min=%0.3f dts_max=%0.3f\n",
1363 dts_min / 90000.0, dts_max / 90000.0);
1365 if (timestamp <= dts_min) {
1368 } else if (timestamp >= dts_max) {
1372 /* interpolate position (better than dichotomy) */
1373 pos = (int64_t)((double)(pos_max - pos_min) *
1374 (double)(timestamp - dts_min) /
1375 (double)(dts_max - dts_min)) + pos_min;
1376 pos = do_block_align(pos, block_align);
1379 printf("pos=0x%llx\n", pos);
1381 /* read the next timestamp */
1382 dts = read_timestamp(s, stream_index, &pos, 1);
1383 /* check if we are lucky */
1384 if (dts == AV_NOPTS_VALUE) {
1385 /* should never happen */
1388 } else if (timestamp == dts) {
1390 } else if (timestamp < dts) {
1392 dts_max = read_timestamp(s, stream_index, &pos_max, 0);
1393 if (dts_max == AV_NOPTS_VALUE) {
1394 /* should never happen */
1396 } else if (timestamp >= dts_max) {
1401 pos_min = pos + block_align;
1402 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1403 if (dts_min == AV_NOPTS_VALUE) {
1404 /* should never happen */
1406 } else if (timestamp <= dts_min) {
1415 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1416 pos_min += block_align;
1417 dts_max = read_timestamp(s, stream_index, &pos_min, 1);
1418 printf("pos=0x%llx %0.3f<=%0.3f<=%0.3f\n",
1419 pos, dts_min / 90000.0, timestamp / 90000.0, dts_max / 90000.0);
1422 url_fseek(&s->pb, pos, SEEK_SET);
1426 static int mpegts_read_seek(AVFormatContext *s,
1427 int stream_index, int64_t timestamp)
1429 MpegTSContext *ts = s->priv_data;
1431 timestamp = (timestamp * 90000) / AV_TIME_BASE;
1433 return timestamp_read_seek(s, stream_index, timestamp,
1434 mpegts_get_pcr, ts->raw_packet_size);
1437 /**************************************************************/
1438 /* parsing functions - called from other demuxers such as RTP */
1440 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1444 ts = av_mallocz(sizeof(MpegTSContext));
1447 /* no stream case, currently used by RTP */
1448 ts->raw_packet_size = TS_PACKET_SIZE;
1454 /* return the consumed length if a packet was output, or -1 if no
1456 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1457 const uint8_t *buf, int len)
1467 if (len < TS_PACKET_SIZE)
1469 if (buf[0] != 0x47) {
1473 handle_packet(ts, buf);
1474 buf += TS_PACKET_SIZE;
1475 len -= TS_PACKET_SIZE;
1481 void mpegts_parse_close(MpegTSContext *ts)
1485 for(i=0;i<NB_PID_MAX;i++)
1486 av_free(ts->pids[i]);
1490 AVInputFormat mpegts_demux = {
1492 "MPEG2 transport stream format",
1493 sizeof(MpegTSContext),
1499 .flags = AVFMT_SHOW_IDS,
1502 int mpegts_init(void)
1504 av_register_input_format(&mpegts_demux);
1505 #ifdef CONFIG_ENCODERS
1506 av_register_output_format(&mpegts_mux);